torch.Tensor.Tensor.new_full
Tensor.new_full(size: number[], fill_value: number, options?: TensorOptions): Tensor<DynamicShape, D, Dev>Creates a new tensor filled with a specified value, inheriting dtype and device from this tensor.
Allocates a tensor with given shape and fills all elements with the same scalar value. Inherits dtype and device from this tensor (but can override with options). Useful for initializing bias terms, creating constant offsets, or setting default/placeholder values.
Common use cases:
- Initialize bias vectors with constant values
- Create constant offset tensors for broadcasting
- Fill placeholders (e.g., fill with -inf for masking)
- Initialize attention masks with specific pattern
- Create baseline/reference tensors for comparison
- Value promotion: fill_value is automatically converted to this tensor's dtype.
- Dtype/device inherit: Copies dtype/device from this tensor by default.
- Broadcasting ready: Compatible for broadcasting with operations.
- GPU support: Allocates GPU memory if this tensor is on WebGPU.
Type coercion: fill_value type doesn't matter; result matches this tensor's dtype.
Parameters
sizenumber[]- Shape of the new tensor
fill_valuenumber- Scalar value to fill all elements (automatically promoted to tensor dtype)
optionsTensorOptionsoptional- Optional overrides for dtype/device (defaults to this tensor's dtype/device)
Returns
Tensor<DynamicShape, D, Dev>– New tensor with all elements = fill_valueExamples
// Initialize bias vector
const x = torch.randn(1000); // Template on same device/dtype
const bias = x.new_full([100], 0.1); // 100-element bias vector
// Create mask pattern
const reference = torch.zeros(1); // On same device as data
const mask = reference.new_full([batch_size, seq_len], 1.0); // Start with all 1s
// Fill with large negative value for masking
const scores = torch.randn(batch, seq_len, seq_len);
const mask = scores.new_full([batch, seq_len, seq_len], -1e9); // Mask value
// Override dtype
const float_ref = torch.randn(1, { dtype: 'float32' });
const int_const = float_ref.new_full([50], 7, { dtype: 'int32' });
// Initialize with pattern for broadcasting
const data = torch.randn(32, 100);
const scaling = data.new_full([32, 1], 2.0); // Scale each batch element
const scaled = data.mul(scaling); // Broadcasting: [32, 100] * [32, 1]See Also
- PyTorch tensor.new_full()
- new_zeros - Fill with 0 instead
- new_ones - Fill with 1 instead
- new_empty - Uninitialized (faster, use if not relying on values)
- full - Module-level function to create filled tensors