Rate this Page

helion.language.rand#

helion.language.rand(shape, seed, device=None, offsets=None)[source]#

hl.rand provides a Philox-based pseudorandom number generator (PRNG) that operates independently of PyTorch’s global random seed. Instead, it requires an explicit seed argument. By default, offsets are derived from the full logical sizes of the tiles specified in the shape argument. An explicit offsets tensor may be supplied to bypass the implicit offset computation; the output will then have offsets.shape and shape is ignored (an empty list [] is fine).

Parameters:
  • shape (list[object]) – A list of sizes for the output tensor. Ignored when offsets is provided.

  • seed (int | Tensor) – A single element int64 tensor or int literal

  • device (device | None) – Device must match the current compile environment device

  • offsets (Tensor | None) – Optional explicit int64 offset tensor fed directly into the philox RNG. When provided, the output shape equals offsets.shape.

Returns:

A device tensor of float32 dtype filled with uniform random values in [0, 1)

Return type:

torch.Tensor

Examples

@helion.kernel
def process_kernel(x: torch.Tensor) -> torch.Tensor:
    output = torch.zeros_like(x)
    (m,) = x.shape
    for tile_m in hl.tile(m):
        output[tile_m] = hl.rand([tile_m], seed=42)
    return output

With explicit offsets (e.g. spaced out so sibling streams may use offsets +1 and +2):

@helion.kernel
def spaced_rand_kernel(x: torch.Tensor) -> torch.Tensor:
    output = torch.zeros_like(x)
    (m,) = x.shape
    for tile_m in hl.tile(m):
        base = hl.arange(tile_m).to(torch.int64) * 3
        output[tile_m] = hl.rand([], seed=42, offsets=base)
    return output