torch.index_fill
Fills positions specified by 1D indices with a scalar value.
Sets all elements at index positions along a dimension to the same scalar value. Simpler than index_copy when you want to fill with a constant. Useful for:
- Masking: setting masked positions to value
- Zeroing: clearing specific elements
- Initialization: setting positions to constant value
- Regularization: marking positions for special handling
- Mask application: applying mask with fill value
- Scalar fill: Fills with single value at all index positions
- Simple operation: Faster than index_copy for constant values
- 1D indices: Index must be 1D tensor
- Broadcasting: Value is scalar, broadcasts to all dimensions
- Index length: Indices can be any length (non-unique allowed)
- Value type: Must be compatible with tensor dtype
Parameters
inputTensor- The input tensor
dimnumber- The dimension along which to index
indexTensor- 1D tensor of indices to fill
valuenumber- Scalar value to fill at index positions
Returns
A new tensor with positions filled
Examples
// Zero out specific positions
const data = torch.randn(10, 5);
const indices = torch.tensor([0, 2, 4, 6, 8]); // Positions to zero
const zeroed = torch.index_fill(data, 0, indices, 0);
// Set masked positions
const logits = torch.randn(32, 100);
const masked_indices = torch.tensor([5, 10, 20, 50]); // Positions to mask
const masked_logits = torch.index_fill(logits, 1, masked_indices, -Infinity);
// Initialize specific rows
const matrix = torch.ones(5, 5);
const init_indices = torch.tensor([1, 3]);
const initialized = torch.index_fill(matrix, 0, init_indices, 0.5);See Also
- PyTorch torch.index_fill()
- index_copy - Copy values instead of fill
- index_add - Add instead of fill