Gradient Accumulation Over K Micro-Batches
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement `accumulate_and_step(params, grad_fn, micro_batches, accum_steps, lr)`. Run one pass of SGD over `micro_batches` (a list of `(X, y)` pairs), grouping every `accum_steps` consecutive micro-batches into one update. Return `(final_params, history)`.
- For each group, call `grad_fn(w, X, y)` at the group's starting params and step `w -= lr * Σ(len(X)·g) / Σ len(X)`, the sample-weighted mean of the micro-batch gradients.
- A trailing partial group still steps.
- Empty micro-batches count toward K but skip `grad_fn`. A group with zero samples takes no step.
- `history` is a float64 array of shape `(num_steps, *params.shape)` holding the params after each step, with shape `(0, *params.shape)` if no step was taken.
- Raise `ValueError` when `accum_steps < 1`. Do not mutate `params`.
Example:
```python
grad_fn = lambda w, X, y: w - np.mean(y)
batches = [([[2], [4]], [2, 4]), ([[6]], [6]), ([[0], [2]], [0, 2])]
accumulate_and_step(np.array([1.0]), grad_fn, batches, 2, 0.5)
# group 1: (2*(-2) + 1*(-5)) / 3 = -3 -> w = 2.5
# group 2 (partial): 2.5 - 1 = 1.5 -> w = 1.75
# returns (array([1.75]), array([[2.5], [1.75]]))
```
```hint Group boundaries
Decide where the boundary check lives so that the last group fires even when it holds fewer than `accum_steps` micro-batches, and so that a group with no samples never divides by zero.
```
```hint What to carry between micro-batches
Two running quantities are enough to form the weighted mean at the boundary. Think about what each one adds per micro-batch and when both are reset.
```
### Constraints & Assumptions
- `grad_fn` returns the mean gradient over its micro-batch, with the same shape as `params`.
- Micro-batch sizes may differ, including size 0.
- `len(X)` is the number of samples in a micro-batch.
### What a Strong Answer Covers
- A sample-weighted mean of the per-batch mean gradients, with the params held fixed for every `grad_fn` call inside a group.
- Correct group boundaries: every `accum_steps` micro-batches plus a trailing partial group, empty micro-batches counted toward K, and no step or history row for a zero-sample group.
- A float64 history of shape `(num_steps, *params.shape)`, including the case with no steps.
- Input validation and no mutation of `params`.
- Why one accumulated step equals one large-batch step for a mean-reduced loss.
### Follow-up Questions
- Why weight by sample count instead of dividing the summed gradients by K?
- How does this interact with mixed precision and loss scaling?
- How would you avoid redundant communication under DDP?
Overview: Implement SGD with gradient accumulation, grouping every K micro-batches into one parameter update that uses a sample-weighted mean gradient. Tests handling of uneven and empty micro-batches, partial final groups, and why accumulation matches a single large-batch step.