MCPcopy Create free account
hub / github.com/tinygrad/tinygrad / rand

Method rand

tinygrad/tensor.py:567–591  ·  view source on GitHub ↗

Creates a tensor with the given shape, filled with random values from a uniform distribution over the interval `[0, 1)`. You can pass in `dtype` and `device` keyword arguments to control the data type and device of the tensor. ```python exec="true" source="above" session="tensor" resu

(*shape, device:str|None=None, dtype:DTypeLike|None=None, contiguous:bool=True)

Source from the content-addressed store, hash-verified

565
566 @staticmethod
567 def rand(*shape, device:str|None=None, dtype:DTypeLike|None=None, contiguous:bool=True) -> Tensor:
568 """
569 Creates a tensor with the given shape, filled with random values from a uniform distribution over the interval `[0, 1)`.
570
571 You can pass in `dtype` and `device` keyword arguments to control the data type and device of the tensor.
572
573 ```python exec="true" source="above" session="tensor" result="python"
574 Tensor.manual_seed(42)
575 t = Tensor.rand(2, 3)
576 print(t.numpy())
577 ```
578 """
579 dt = to_dtype(dtype or dtypes.default_float)
580 if not dtypes.is_float(dt): raise ValueError(f"rand only supports float dtypes, got {dt}")
581 if not all_int(shape:=argfix(*shape)) or not all(s >= 0 for s in shape): raise ValueError(f"invalid input {shape=}")
582 if device is not None and not isinstance(device, str): raise ValueError(f"rand only supports single device, got {device=}")
583 device = cast(str, canonicalize_device(device))
584
585 # if shape has 0, return zero tensor
586 if (numel := prod(shape)) == 0: return Tensor.zeros(shape, device=device, dtype=dt)
587 num = ceildiv(numel * dt.itemsize, 4)
588 key, counter = Tensor._next_counter(device, num)
589 bits = Tensor.random_bits(key, counter, num)
590 out = Tensor._bits_to_rand(bits, shape, dt)
591 return out.contiguous() if contiguous else out
592
593 # ***** creation helper functions *****
594

Callers 15

rand_likeMethod · 0.80
uniformMethod · 0.80
randpermMethod · 0.80
multinomialMethod · 0.80
hook_cuda.pyFile · 0.80
torch_gemm.pyFile · 0.80
fuzz_matmul.pyFile · 0.80
_randFunction · 0.80
real_pmatmul.pyFile · 0.80
rand_inputFunction · 0.80
tvm_gemm.pyFile · 0.80

Calls 13

to_dtypeFunction · 0.90
all_intFunction · 0.90
argfixFunction · 0.90
canonicalize_deviceFunction · 0.90
prodFunction · 0.90
ceildivFunction · 0.90
castFunction · 0.85
is_floatMethod · 0.80
zerosMethod · 0.80
_next_counterMethod · 0.80
random_bitsMethod · 0.80
_bits_to_randMethod · 0.80

Tested by 15

test_matmulFunction · 0.64
test_reduce_sumFunction · 0.64
test_reduce_maxFunction · 0.64
test_expFunction · 0.64
test_softmaxFunction · 0.64
test_conv2dFunction · 0.64
test_large_matmulFunction · 0.64
test_elementwise_chainFunction · 0.64
test_broadcastFunction · 0.64
test_plus_bigFunction · 0.64
randFunction · 0.64
test_large_astMethod · 0.64