randperm(n: int, generator: _C_engine.Generator | None = None, dtype: DTypeLike = int64, device: DeviceLike = None, requires_grad: bool = False)Return a uniformly random permutation of the integers .
Produces a rank-1 tensor containing a uniformly random element of , the symmetric group of permutations on symbols. Every one of the orderings is equally likely:
Parameters
nintNumber of elements. Must be . Returns an empty tensor
when
n = 0.Explicit generator. Defaults to the global default.
dtypelucid.dtype= int64Integer data type of the output. Defaults to
lucid.int64.devicestr or lucid.device= NoneTarget device —
"cpu" or "metal".requires_gradbool= FalseEnable autograd tracking. Default:
False.Returns
Tensor1-D integer tensor of shape (n,) containing a permutation of
.
Notes
The implementation uses the lottery-ticket argsort trick: assign each integer a uniform random key and return the argsort of those keys:
This is equivalent to the Fisher–Yates shuffle in expectation and is more cache-friendly on SIMD hardware because the sort can be vectorised without branch-dependent swaps.
randperm is the standard building block for:
- Dataset shuffling —
dataset[lucid.randperm(len(dataset))] - k-fold cross-validation — split a shuffled index tensor
- Contrastive learning — negative-sample mining via permuted indices
Examples
>>> import lucid
>>> lucid.manual_seed(0)
>>> lucid.randperm(5).tolist()
[2, 4, 3, 1, 0]
Shuffle a dataset of 1024 examples in one line:
>>> idx = lucid.randperm(1024)
>>> shuffled = data[idx]
Edge cases:
>>> lucid.randperm(0).shape
(0,)
>>> lucid.randperm(1).tolist()
[0]