Shape-matched initialization
Initialize a tensor-shaped buffer without manually copying dimensions.
PyTorch · Function
Creates a zero-filled tensor with the same size as an input tensor. By default, it also follows the input's dtype, layout, device, and preserved memory format.
torch.zeros_like accepts a reference tensor and creates a zero-filled tensor with the same size. Unless overridden, it also follows the reference tensor's data type, layout, device, and preserved memory format; requires_grad controls whether autograd records operations on the result.
torch.zeros_like(input, *, dtype=None, layout=None, device=None, requires_grad=False, memory_format=torch.preserve_format) → Tensor| Name | Type | Description |
|---|---|---|
input | Tensor | Tensor whose size determines the output tensor's size. |
dtype | torch.dtype, optional | Desired data type; None uses input.dtype. |
layout | torch.layout, optional | Desired layout; None uses input.layout. |
device | torch.device, optional | Desired device; None uses input.device. |
requires_grad | bool, optional | Whether autograd records operations on the returned tensor; defaults to False. |
memory_format | torch.memory_format, optional | Desired memory format; defaults to torch.preserve_format. |
Tensor
import torch
x = torch.empty((2, 3), dtype=torch.float64, device="cpu")
z = torch.zeros_like(x)
print(z)
print(z.dtype, z.device, z.shape)Creates a zero-filled tensor that matches x in shape, data type, layout, and device.
Initialize a tensor-shaped buffer without manually copying dimensions.
Create zeros alongside an existing CPU, CUDA, or other-device tensor.
Build a zero baseline while retaining or overriding numeric type and layout.
It returns a tensor filled with zeros whose size matches the input tensor. By default, its dtype, layout, and device come from the input, while optional keyword arguments can override those choices.
Follow-up: How would you create the same shape on another device? Pass the target device with device=, for example torch.zeros_like(x, device="cuda").
The input tensor determines the output size. None defaults dtype, layout, and device to the corresponding input attributes, while memory_format defaults to torch.preserve_format.
Follow-up: What controls gradient tracking on the result? requires_grad does; its documented default is False.
Its signature has one input tensor followed by keyword-only dtype, layout, device, requires_grad, and memory_format arguments. It returns a Tensor.
Follow-up: What is the documented limitation involving out? zeros_like does not accept out; use torch.zeros(input.size(), out=output) instead.
torch.zerostorch.ones_liketorch.empty_liketorch.full_like