torch.func._random.randint_#
- torch.func._random.randint_(key, result, *, low=0, high=None)[source]#
Fill
resultin-place with uniform random integers in[low, high).lowdefaults to0andhighto the dtype’s largest value plus one. PassingNonefor either selects the corresponding limit of the dtype, sorandint_(key, result, low=None, high=None)draws from the dtype’s full range.Warning
The two in-place analogues in core PyTorch both take bounds positionally, while these are keyword-only. Versus
torch.randint()without=, which needs the size even thoughoutalready fixes it:torch.randint(10, (2, 3), out=result) # -> [0, 10) randint_(key, result, high=10) # size comes from result torch.randint(1, 5, (2, 3), out=result) # -> [1, 5) randint_(key, result, low=1, high=5)
Versus
torch.Tensor.random_(), which names the boundsfrom/toand treats a lone bound as the upper one:result.random_(10) # -> [0, 10) randint_(key, result, high=10) result.random_(1, 5) # -> [1, 5) randint_(key, result, low=1, high=5) result.random_() # -> [0, DTYPE_MAX] randint_(key, result) result.random_(DTYPE_MIN, None) # whole dtype range randint_(key, result, low=None, high=None)
The bound defaults agree: both fill
[0, DTYPE_MAX]when given no bounds, and both need an explicit lower bound to reach negative values. The spelling differs in thatNonehere means the dtype’s limit for either bound, solow=Nonereplacesrandom_’sDTYPE_MIN.The output is fully determined by the key, so calling with the same key always produces the same result.
Supports batched keys: if
keyhas shape(*batch, K), the leading dimensions ofresultmust be broadcastable with*batchand each key independently generates its slice of the output.- Parameters:
key (Tensor) – A PRNG key returned by
key(),split(), orfold_in().result (Tensor) – The output tensor to fill in-place. Must have an integer dtype other than
torch.bool.low (int, optional) – Lower bound (inclusive) of the range.
Nonemeans the dtype’s smallest value. Default:0.high (int, optional) – Upper bound (exclusive) of the range.
Nonemeans the dtype’s largest value plus one. For 32-bit dtypes,high - lowmust be a power of two or less than2 ** 28; see the note below. Default:None.
- Returns:
result, filled with random integers.- Return type:
Note
Values are reduced into
[low, high)with a modulo, which is exactly uniform only whenhigh - lowis a power of two. Other ranges of2 ** 28or more are rejected for 32-bit dtypes; use a 64-bit dtype if you need a range that large. Seerandint()for the bias in detail.Example:
>>> key = torch.func._random.key(42, device="cuda") >>> result = torch.empty(1000, dtype=torch.int64, device="cuda") >>> torch.func._random.randint_(key, result, high=10)