Skip to content

← Broadcasting step 3 of 6

Medium Primitives

Add row sums without changing the destination shape

Jump to the task

An ordinary addition can produce a broadcasted result with a larger shape. An in-place addition must keep the destination's existing shape.

import torch

a = torch.zeros(3, 4)
b = torch.ones(3, 1)
print((a + b).shape)  # torch.Size([3, 4])
a.add_(b)            # Works: b broadcasts to a's shape.

Reversing the in-place operation does not work. b.add_(a) would need a (3, 4) result, but b has shape (3, 1). PyTorch raises a RuntimeError instead of resizing b.

Broadcasting treats compatible singleton dimensions of the source as repeated values without materializing repeated data. The destination of add_() must already have the result's shape. Shape compatibility is only one requirement: dtype and autograd rules also apply to in-place operations.

Accumulating one total per row

Suppose totals has shape (rows, 1) and batch has shape (rows, cols). You want to add each row's sum to its existing total. Adding the whole batch is not the same calculation, and cannot fit when cols is greater than one. Reduce each row first:

totals = torch.tensor([[10.0], [20.0]])
batch = torch.tensor([[1.0, 2.0], [3.0, 4.0]])
row_sums = batch.sum(dim=1, keepdim=True)
print(row_sums.tolist())  # [[3.0], [7.0]]
totals.add_(row_sums)
print(totals.tolist())    # [[13.0], [27.0]]

keepdim=True retains the reduced axis, producing (rows, 1) rather than (rows,). That matches totals directly and avoids accidentally aligning the row count with its last axis.

Your task

def accumulate(totals: torch.Tensor, batch: torch.Tensor) -> torch.Tensor

Add each row's sum from batch into the corresponding entry of totals, in place. Return the same totals tensor. The inputs are float32 tensors without gradient tracking, shaped (rows, 1) and (rows, cols) respectively. Preserve the initial totals and their storage.