torch.index_copy
In-place version of scatter_reduce: applies reduction at indices in-place.
Modifies input tensor in-place using a custom reduction operation at index positions. Same semantics as scatter_reduce() but without creating a new tensor. Useful for:
- Memory efficiency: in-place reduction for aggregation
- Iterative updates: repeatedly reducing with different operations
- Graph networks: in-place message aggregation
- Custom pooling: in-place mean/max pooling without copies
- Flexible histograms: in-place histogram computation with reductions
- In-place modification: Input tensor is modified directly
- Returns input: Same tensor object returned for chaining
- Reduction types: sum, mean, amax, amin, prod
- include_self: Controls whether original values participate in reduction
- Overwrites input: Original values are modified
- Side effects: All references to input see the changes
- Reduction semantics: Different reductions have different numerical properties
Parameters
inputTensor- The input tensor (modified in-place)
dimnumber- The dimension along which to index
indexTensor- The indices tensor specifying where to reduce
sourceTensor
Returns
The modified input tensor (same object)
Examples
// In-place mean pooling
const output = torch.zeros(3, 64);
const values = torch.randn(10, 64);
const indices = torch.tensor([0, 1, 0, 2, 1, 0, 1, 2, 0, 1]);
torch.scatter_reduce_(output, 0, indices, values, 'mean'); // In-place
// Iterative max aggregation
const accumulated = torch.full([5, 10], -Infinity);
for (let batch = 0; batch < num_batches; batch++) {
const batch_data = get_batch(batch); // [100, 10]
const batch_indices = get_indices(batch); // [100]
torch.scatter_reduce_(accumulated, 0, batch_indices, batch_data, 'amax');
}
// Product accumulation
const product_result = torch.ones(5);
const factors = torch.randn(20);
const factor_indices = torch.randint(0, 5, [20]);
torch.scatter_reduce_(product_result, 0, factor_indices, factors, 'prod');See Also
- PyTorch torch.Tensor.scatter_reduce_()
- scatter_reduce - Non-in-place version
- scatter_add_ - In-place sum-only scatter
- index_reduce - Simpler 1D version