Initialize storage
Preallocating a numeric buffer with a known shape before filling it during a computation.
PyTorch · Function
Creates a tensor filled with zeros, using dimensions supplied as separate arguments or as a collection. Optional keywords select its dtype, layout, device, output buffer, and autograd behavior.
torch.zeros accepts dimensions either as separate integer arguments or as a collection, then allocates a tensor filled with zero. Optional keyword arguments control its output buffer, data type, layout, device, and whether autograd records operations on it.
torch.zeros(*size, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) → Tensor| Name | Type | Description |
|---|---|---|
size | int ... | Dimensions defining the output shape; pass integer dimensions individually or as a list or tuple. |
out | Tensor, optional | Optional destination tensor for the result. |
dtype | torch.dtype, optional | Optional data type of the returned tensor; defaults to the global default dtype when omitted. |
layout | torch.layout, optional | Optional layout of the returned tensor; defaults to torch.strided. |
device | torch.device, optional | Optional device for the returned tensor; omitted values follow the current default device. |
requires_grad | bool, optional | Whether autograd records operations on the returned tensor; defaults to False. |
Tensor
import torch
x = torch.zeros(2, 3, dtype=torch.float32)
print(x)
Creates a 2-by-3 CPU tensor whose six elements are zero and whose dtype is explicitly float32.
Preallocating a numeric buffer with a known shape before filling it during a computation.
Creating a zero-valued matrix or vector for model inputs, masks, counters, or accumulators.
Selecting dtype and device explicitly when preparing tensors for a model or accelerator.
It creates and returns a tensor filled with scalar zero. The requested shape comes from size, which may be supplied as separate dimensions or as a list or tuple.
Follow-up: How would you preserve an existing tensor's shape and properties instead? Use torch.zeros_like(input), which is the corresponding shape-and-properties-oriented factory.
dtype controls the returned tensor's data type, while layout controls its tensor layout. If dtype is None, PyTorch uses its global default dtype; the default layout is torch.strided.
Follow-up: What determines the device when device is omitted? PyTorch uses the current device for the default tensor type; CPU tensor types use CPU, while CUDA types use the current CUDA device.
requires_grad defaults to False. When enabled, autograd records operations on the returned tensor; out can provide an output tensor instead of allocating a new result.
Follow-up: When is zeros_like preferable? When an existing input tensor defines the desired size, dtype, layout, and device.
torch.zeros_liketorch.onestorch.emptytorch.full