Skip to content
masterclassBuddyTech Buzz5 fresh blogs · 5:00 AM IST

PyTorch · Function

torch.rand

torch.rand creates a tensor of a requested shape with uniformly distributed random values in the half-open interval [0, 1). Optional arguments control the generator, output properties, device, gradient tracking, and memory allocation.

How it works

torch.rand creates a new tensor whose dimensions come from the positional size arguments. Each element is sampled independently from a uniform distribution over the half-open interval [0, 1), while keyword options control generation, storage, placement, and autograd behavior.

Syntax

torch.rand(*size, *, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, pin_memory=False) → Tensor

Parameters

NameTypeDescription
sizeint...One or more integers specifying the output dimensions.
generatortorch.Generator, optionalOptional pseudorandom number generator used for sampling.
outTensor, optionalOptional destination tensor for the operation.
dtypetorch.dtype, optionalOptional element dtype; defaults to the global default dtype when omitted.
layouttorch.layout, optionalOptional tensor layout; defaults to torch.strided.
devicetorch.device, optionalOptional placement; otherwise follows the current default tensor device.
requires_gradbool, optionalWhether autograd records operations on the returned tensor; default false.
pin_memorybool, optionalWhether to allocate pinned memory; supported only for CPU tensors and defaulting to false.

Returns

A Tensor filled with uniformly distributed random numbers in [0, 1).

Key points

  • Values are sampled uniformly from the half-open interval [0, 1), so zero may occur but one is excluded.
  • Pass dimensions positionally; their sequence becomes the result's shape.
  • The optional generator argument selects the pseudorandom stream used to produce samples.
  • dtype requests the returned tensor's element type and otherwise follows the global default.
  • layout lets callers request the tensor memory layout, whose default is torch.strided.
  • pin_memory requests pinned allocation for supported CPU tensors and defaults to false.

Common mistakes

  • pin_memory applies only to CPU tensors; using it does not make a CUDA allocation pinned.
  • requires_grad controls whether autograd records operations on the result, and it defaults to false.
  • Leaving dtype unset selects the current global default dtype rather than guaranteeing a particular floating-point type.
  • With no device specified, placement follows the current default tensor device and type.

Example: Reproducible uniform samples

import torch

generator = torch.Generator().manual_seed(7)
x = torch.rand(2, 3, generator=generator, dtype=torch.float64)
print(x.shape)  # torch.Size([2, 3])
print(bool(((x >= 0) & (x < 1)).all()))  # True

Creates a reproducible 2-by-3 tensor of float64 samples and verifies that every value lies in the documented interval.

When to use it

Synthetic tensor data

Generate random input tensors for tests, demonstrations, or synthetic data pipelines.

Uniform initialization

Create initialized tensors whose values are bounded between zero and one.

Reproducible sampling

Use a seeded Generator to make experiments and tests repeatable.

Device- and dtype-aware creation

Allocate random tensors directly on a selected device or with a selected dtype.

Interview questions

QWhat distribution and interval does torch.rand use?

torch.rand accepts one or more integer dimensions through size and returns a tensor filled with samples from a uniform distribution on [0, 1). The upper endpoint is excluded.

Follow-up: How would you obtain normally distributed values instead? Use torch.randn, which is the related random-sampling operation for a standard normal distribution.

QHow is the output shape determined?

The positional size arguments define the output shape, so torch.rand(2, 3) produces a two-dimensional tensor with shape 2 by 3. Keyword arguments can then specify dtype, layout, device, and other properties.

Follow-up: How can shape and properties be inherited from an existing tensor? Use torch.rand_like, which creates uniform samples with the input's size and can preserve relevant tensor attributes.

QWhich arguments help control reproducibility and gradient tracking?

generator supplies the pseudorandom number generator used for sampling, allowing callers to control the random stream. In practice, seeding a torch.Generator makes repeated calls reproducible under the same conditions.

Follow-up: What option controls gradient tracking on the result? Set requires_grad=True when autograd should record operations involving the returned tensor.

  • torch.rand_like
  • torch.randn
  • torch.randn_like
  • torch.randint
  • torch.randperm
  • torch.set_default_dtype
  • torch.set_default_device

Source: torch.rand — PyTorch main documentation. Checked 2026-10-16.