torch.Tensor.Tensor.new_ones
Tensor.new_ones(size: number[], options?: TensorOptions): Tensor<DynamicShape, D, Dev>Creates a new tensor filled with ones, inheriting dtype and device from this tensor.
Allocates a tensor with given shape and fills all elements with 1. Inherits dtype and device from this tensor (can override with options). Useful for multiplicative identity, masks where all elements are selected, or baselines.
Common use cases:
- Multiplicative identity: multiply by ones for no-op
- Initialize uniform masks (all elements selected)
- Element-wise baseline (e.g., attention weights before masking)
- Broadcasting factors and multipliers
- Conditional selection (mask = ones where keeping elements)
- Multiplicative identity: x * ones = x (useful for conditional applications).
- Dtype/device inherit: Copies dtype/device from this tensor by default.
- Broadcasting ready: Can be broadcasted with this tensor's shape.
- 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 = 1Examples
// Create multiplicative identity
const x = torch.randn(100, 100, { dtype: 'float32' });
const identity = x.new_ones([100, 100]); // All ones, float32
const unchanged = x.mul(identity); // Same as x
// Initialize selection mask (keep all initially)
const features = torch.randn(batch_size, feature_dim);
const mask = features.new_ones([batch_size, feature_dim]);
for (let i = 0; i < feature_dim; i++) {
if (should_remove(i)) mask[:, i] = 0; // Remove some features
}
const selected = features.mul(mask);
// Uniform attention weights
const scores = torch.randn(seq_len, seq_len);
const uniform = scores.new_ones([seq_len, seq_len]).div(seq_len);
// Initialize scaling factors
const data = torch.randn(batch_size, feature_dim);
const scales = data.new_ones([batch_size, 1]).mul(2.0); // Scale by 2
const scaled = data.mul(scales);See Also
- PyTorch tensor.new_ones()
- new_zeros - Fill with 0 instead
- new_full - Fill with arbitrary value
- new_empty - Uninitialized (faster if not using values)
- ones - Module-level function to create ones tensors