torch.Tensor.Tensor.zeros_like
Returns a tensor with all zeros of the same shape as this tensor.
Creates a new tensor filled with zeros that matches the shape, dtype, and device of the current tensor. Useful for initializing buffers, masks, or computations that start from zero.
Related functions:
torch.zeros(shape)- Create zeros with explicit shapeones_like()- All ones insteadfull_like(value)- Fill with arbitrary valueempty_like()- Uninitialized tensor
Use Cases:
- Initialize accumulator tensors (sums, gradients)
- Create mask tensors for selection/masking operations
- Initialize output buffers with known size
- Element-wise operations requiring zero baseline
- Building computational graphs with zero initialization
- Dtype matching: Output has same dtype as input (int32 input → int32 zeros).
- Device matching: Output is on same device (CPU or WebGPU).
- Gradient handling: No gradients for filled zeros (makes sense).
- Memory: Allocates new memory (not a view).
Returns
Tensor<S, D, Dev>– New tensor with shape, dtype, device matching input, all values = 0Examples
// Create zeros matching input shape
const x = torch.randn(3, 4, 5);
const zeros = x.zeros_like(); // [3, 4, 5] of zeros
// Zero accumulator for sum
let accumulator = x.zeros_like();
for (const batch of batches) {
accumulator = accumulator.add(batch);
}
// Initialize gradient accumulator
let grad_sum = model.output.zeros_like();
for (const sample of samples) {
const grad = compute_gradient(sample);
grad_sum = grad_sum.add(grad);
}
// Mask initialization
const mask = features.zeros_like();
// ... populate mask based on some condition
const masked_features = features.mul(mask);See Also
- PyTorch torch.zeros_like()
- ones_like - Create all ones instead
- full_like - Fill with arbitrary value
- zeros - Create zeros with explicit shape
- empty_like - Uninitialized tensor (faster, no fill)