torch.Tensor.Tensor.new_zeros
Tensor.new_zeros(size: number[], options?: TensorOptions): Tensor<DynamicShape, D, Dev>Creates a new tensor filled with zeros, inheriting dtype and device from this tensor.
Allocates a tensor with given shape and fills all elements with 0. Inherits dtype and device from this tensor (can override with options). Useful for accumulators, initialization of masks where all elements are deselected, or additive identity.
Common use cases:
- Initialize accumulators and gradients
- Zero out tensors before filling
- Initialize masks where nothing is selected initially
- Additive baseline (x + zeros = x)
- Padding or placeholder tensors
- Additive identity: x + zeros = x (useful for conditional applications).
- Dtype/device inherit: Copies dtype/device from this tensor by default.
- Fast initialization: Zeros are often optimized in hardware.
- GPU support: Allocates GPU memory if this tensor is on WebGPU.
Parameters
sizenumber[]- Shape of the new tensor
optionsTensorOptionsoptional- Optional overrides for dtype/device (defaults to this tensor's dtype/device)
Returns
Tensor<DynamicShape, D, Dev>– New tensor with all elements = 0Examples
// Initialize gradient accumulator
const x = torch.randn(100, 100, { dtype: 'float32' });
const gradient_sum = x.new_zeros([100, 100]); // Accumulate gradients
for (const grad of gradients) {
gradient_sum.add_(grad);
}
// Initialize deselection mask (nothing selected initially)
const features = torch.randn(batch_size, feature_dim);
const mask = features.new_zeros([batch_size, feature_dim]);
for (let i = 0; i < feature_dim; i++) {
if (should_keep(i)) mask[:, i] = 1; // Select some features
}
const selected = features.mul(mask);
// Padding/placeholder tensor
const embeddings = torch.randn(vocab_size, embedding_dim);
const pad_embedding = embeddings.new_zeros([embedding_dim]); // Padding token = zeros
// Zero out specific entries before filling
const buffer = x.new_zeros([batch_size, max_seq_len]);
for (let i = 0; i < actual_len; i++) {
buffer[:, i] = data[i]; // Fill selectively
}See Also
- PyTorch tensor.new_zeros()
- new_ones - Fill with 1 instead
- new_full - Fill with arbitrary value
- new_empty - Uninitialized (faster if not relying on zero values)
- zeros - Module-level function to create zeros tensors