torch.Tensor.Tensor.ones_like
Returns a tensor with all ones of the same shape as this tensor.
Creates a new tensor filled with ones that matches the shape, dtype, and device of the current tensor. Useful for initializing multiplicative identities, masks, or baseline computations.
Related functions:
torch.ones(shape)- Create ones with explicit shapezeros_like()- All zeros insteadfull_like(value)- Fill with arbitrary valueempty_like()- Uninitialized tensor
Use Cases:
- Multiplicative identity (multiply by ones = no-op)
- Initialize uniform masks (all selected)
- Broadcasting factors and multipliers
- Element-wise operations with unity baseline
- Conditional selection (mask = ones if keep)
- Dtype matching: Output has same dtype as input (int32 input → int32 ones).
- Device matching: Output is on same device (CPU or WebGPU).
- Gradient handling: No gradients for filled ones (makes sense).
- Memory: Allocates new memory (not a view).
Returns
Tensor<S, D, Dev>– New tensor with shape, dtype, device matching input, all values = 1Examples
// Create ones matching input shape
const x = torch.randn(3, 4);
const ones = x.ones_like(); // [3, 4] of ones
// Multiplicative identity
const result = x.mul(ones); // Same as x
// Initialize selection mask (keep all)
const mask = features.ones_like(); // Start with keeping everything
// Remove features based on criteria
for (const i of 0 to d) {
if (should_remove(i)) mask[i] = 0;
}
const selected = features.mul(mask);
// Uniform attention weights
const attention = scores.ones_like().div(scores.numel()); // Uniform distribution
// Initialize factor tensor for broadcasting
const batch_size = 32;
const scaling = torch.tensor([2.0]).ones_like(); // [1] of 1.0
const scaled = features.mul(scaling);See Also
- PyTorch torch.ones_like()
- zeros_like - Create all zeros instead
- full_like - Fill with arbitrary value
- ones - Create ones with explicit shape
- empty_like - Uninitialized tensor (faster, no fill)