triton.language.range

triton.language.range#

class triton.language.range(arg1, arg2=None, step=None, num_stages=None, loop_unroll_factor=None, disallow_acc_multi_buffer=False, flatten=False, warp_specialize=False, disable_licm=False)#

Iterator that counts upward forever.

说明

This is a special iterator used to implement similar semantics to Python's range in the context of triton.jit functions. In addition, it allows user to pass extra attributes to the compiler.

参数:
  • arg1 -- the start value.

  • arg2 -- the end value.

  • step -- the step value.

  • num_stages --

    pipeline the loop into this many stages (so there are num_stages iterations of the loop in flight at once).

    Note this is subtly different than passing num_stages as a kernel argument. The kernel argument only pipelines loads that feed into dot operations, while this attribute tries to pipeline most (though not all) loads in this loop.

  • loop_unroll_factor -- Tells the Triton IR level loop unroller how many times to unroll a for loop that this range is used with. Less than 2 for this value implies no unrolling.

  • disallow_acc_multi_buffer -- If true, prevent the accumulator of the dot operation in the loop to be multi-buffered, if applicable.

  • flatten -- automatically flatten the loop nest starting at this loop to create a single flattened loop. The compiler will try to pipeline the flattened loop which can avoid stage stalling.

  • warp_specialize -- has no effect on Ascend.

  • disable_licm -- Tells the compiler it shouldn't hoist loop invariant code outside the loop. This is often useful to avoid creating long liveranges within a loop.

示例

import torch
import torch_npu
from torch.testing import assert_close

import triton
import triton.language as tl


@triton.jit
def range_kernel(x_ptr, out_ptr, N: tl.constexpr):
    acc = 0.0
    # Iterate from 0 to N (exclusive), accumulating each element
    for i in tl.range(0, N):
        acc += tl.load(x_ptr + i)
    tl.store(out_ptr, acc)


def test_range():
    N = 128
    x = torch.randn(N, device="npu", dtype=torch.float32)
    out = torch.empty(1, device="npu", dtype=torch.float32)

    range_kernel[(1, )](x, out, N=N)
    torch.npu.synchronize()

    assert_close(out, x.sum().reshape(1), rtol=1e-3, atol=1e-3)


if __name__ == "__main__":
    test_range()
    print("test_range PASSED!")

数据类型支持

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

✓

✓

✓

✓

✓

✓

✓

✓

×

×

×

×

×

×

×

特殊说明

  • disallow_acc_multi_buffer, flatten, disable_licm: related functionality is incomplete on Ascend.

__init__(arg1, arg2=None, step=None, num_stages=None, loop_unroll_factor=None, disallow_acc_multi_buffer=False, flatten=False, warp_specialize=False, disable_licm=False)#

Methods

__init__(name)

Initialize self.

Attributes

type