triton.language.sum

目录

triton.language.sum#

triton.language.sum(input, axis=None, keep_dims=False, dtype: constexpr = None)#

Returns the sum of all elements in the input tensor along the provided axis

参数:
  • input (Tensor) -- the input values

  • axis (int) -- the dimension along which the reduction should be done. If None, reduce all dimensions

  • keep_dims (bool) -- if true, keep the reduced dimensions with length 1

  • dtype (tl.dtype) -- the desired data type of the returned tensor. If specified, the input tensor is casted to dtype before the operation is performed. This is useful for preventing data overflows. If not specified, integer and bool dtypes are upcasted to tl.int32 and float dtypes are upcasted to at least tl.float32.

This function can also be called as a member function on tensor, as x.sum(...) instead of sum(x, ...).

示例

import torch
import torch_npu
import triton
import triton.language as tl


@triton.jit
def tt_sum_2d(in_ptr, out_ptr, M: tl.constexpr, N: tl.constexpr, dim: tl.constexpr):
    mblk_idx = tl.arange(0, M)
    nblk_idx = tl.arange(0, N)
    idx = mblk_idx[:, None] * N + nblk_idx[None, :]
    x = tl.load(in_ptr + idx)
    ret = tl.sum(x, dim)
    if dim == 0:
        tl.store(out_ptr + tl.arange(0, N), ret)
    else:
        tl.store(out_ptr + tl.arange(0, M), ret)


def test_sum():
    M, N, dim = 4, 8, 1
    x = torch.randn(M, N, dtype=torch.float32).npu()
    out = torch.empty(M, dtype=torch.float32).npu()
    tt_sum_2d[1, 1, 1](x, out, M, N, dim)
    ref = torch.sum(x, dim=dim)
    assert torch.allclose(out.cpu(), ref.cpu()), "sum result mismatch"
    print("sum result:", out)


if __name__ == "__main__":
    test_sum()

数据类型支持

uint8

int8

uint16

int16

uint32

int32

uint64

int64

fp16

fp32

fp64

bf16

fp8e(e4m3)

fp8e5(e5m2)

bool

Atlas A2 products/Atlas A3 products

√

√

×

√

×

√

×

√

√

√

×

√

×

×

√

Ascend 950PR&950DT products

×

√

×

√

×

√

√

√

√

√

×

√

√

√

√

特殊说明

  • keep_dims=True requires more test coverage; currently verified for 3D tensor with dim=2.