Categorical integer data
Create synthetic labels or token IDs within a known vocabulary range.
PyTorch · Function
Creates a tensor of uniformly distributed random integers in the half-open interval [low, high). The requested size determines its shape, and low defaults to zero.
The function constructs a tensor whose shape comes from size and whose entries are uniformly sampled integers in the half-open interval [low, high). If low is omitted, sampling starts at zero; optional arguments control randomness, storage, placement, output reuse, and gradient tracking.
torch.randint(low=0, high, size, *, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) → Tensor| Name | Type | Description |
|---|---|---|
low | int, optional | Lowest integer to sample; defaults to 0. |
high | int | Exclusive upper bound; one above the greatest sample. |
size | tuple | Tuple defining the output shape. |
generator | torch.Generator, optional | Generator used for sampling. |
out | Tensor, optional | Destination output tensor. |
dtype | torch.dtype, optional | Returned tensor data type. |
layout | torch.layout, optional | Returned tensor layout; defaults to torch.strided. |
device | torch.device, optional | Device on which to create the tensor. |
requires_grad | bool, optional | Whether autograd records operations on the result; defaults to False. |
A Tensor filled with uniformly sampled random integers in the half-open interval [low, high), with the shape specified by size.
import torch
samples = torch.randint(0, 10, (2, 3), dtype=torch.int32)
print(samples)
print(samples.shape, samples.dtype)Creates a 2-by-3 tensor containing integer samples from 0 through 9.
Create synthetic labels or token IDs within a known vocabulary range.
Build randomized indices, masks, or test fixtures with controlled bounds.
Generate tensors directly on a selected accelerator or with an explicit integer dtype.
torch.randint returns a tensor filled with uniformly sampled integers. Values are at least low and strictly less than high, while size determines the tensor shape.
Follow-up: How would you generate values from 1 through 6? Use torch.randint(1, 7, size), because the high endpoint is exclusive.
If low is omitted, it defaults to zero, so torch.randint(10, (2, 2)) samples from 0 through 9. The required high argument is the exclusive upper bound in this form.
Follow-up: What changes if you need values 10 through 19? Call torch.randint(10, 20, size), rather than passing only 20.
The function accepts optional generator, out, dtype, layout, device, and requires_grad keyword arguments. A generator controls sampling, dtype selects the returned type, device selects placement, and out supplies the destination tensor.
Follow-up: Why might dtype matter for storage? The documented default is int64, so explicitly selecting a suitable integer dtype can reduce representation size when its range is sufficient.
torch.randint_liketorch.randtorch.randntorch.randperm