torch.zeros_like
function zeros_like<S extends Shape, D extends DType = DType, Dev extends DeviceType = DeviceType>(input: Tensor<S, D, Dev>, options: TensorOptions = {}): Tensor<S, D, Dev>Create a zero-filled tensor with the same shape as another tensor.
Returns a new tensor with identical shape to the input but filled with zeros. Useful for creating accumulators, buffers, or gradients with matching shapes without manually specifying dimensions.
By default, matches input's dtype, device, and gradient requirements. Override any of these with the options parameter.
- Shape matching: Automatically infers shape from input
- Dtype preservation: By default inherits input's dtype
- Device consistency: Stays on same device as input
- Efficient: Common operation optimized on all backends
Parameters
inputTensor<S, D, Dev>- Tensor to match shape from
optionsTensorOptionsoptional- Optional overrides: -
dtype: Data type (default: same as input) -requires_grad: Gradient tracking (default: same as input) -device: Compute device (default: same as input)
Returns
Tensor<S, D, Dev>– A zero-filled tensor with shape = input.shapeExamples
// Match input shape
const x = torch.randn(3, 4, 5);
const zeros = torch.zeros_like(x); // [3, 4, 5] of zeros, float32
// Accumulator for reductions
const batch = torch.randn(32, 784);
let sum = torch.zeros_like(batch[0]); // Accumulate samples
// Initialize gradients
const grad = torch.zeros_like(tensor); // Manually initialized gradient
// Change dtype
const int_zeros = torch.zeros_like(x, { dtype: 'int32' }); // [3, 4, 5] of int zerosSee Also
- PyTorch torch.zeros_like()
- zeros - Create zero tensor with explicit shape
- ones_like - One-filled tensor with same shape
- full_like - Constant-filled tensor with same shape
- empty_like - Uninitialized tensor with same shape