Mini-Batch SGD with Gradient Variance Tracking

Quick Overview

Implement mini-batch stochastic gradient descent in NumPy with a seeded reshuffle every epoch, an option to drop the short final batch, and a per-epoch measure of how widely batch gradients spread around their mean. Tests careful handling of random state and input arrays, and reasoning about gradient noise and batch size.

Mini-Batch SGD with Gradient Variance Tracking

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: medium

Interview Round: Other

Implement `minibatch_sgd(grad_fn, loss_fn, w0, X, y, lr, batch_size, n_epochs, seed=0, drop_last=False)`. Train `w` with mini-batch SGD using a fresh shuffle each epoch. Return a dict with `"w"`, `"loss_history"`, `"grad_variance"` and `"n_steps"`. The function must follow these rules: - Create one `np.random.default_rng(seed)`. Each epoch, draw `rng.permutation(n)` and use consecutive slices `perm[i:i+batch_size]`. With `drop_last=True`, skip the final short batch (the permutation is still drawn). - After each batch, apply `w = w - lr * grad_fn(w, X[idx], y[idx])`. Never mutate `w0`. - `grad_variance[e]` is the mean over that epoch's batches of `||g_b - mean(g)||²`, where `mean(g)` is the average of that epoch's batch gradients. Divide by the number of batches. Use `nan` if the epoch had no batches. - `loss_history[e]` is `loss_fn(w, X, y)` on the full data at the end of each epoch. Both histories are float arrays of length `n_epochs`. - `n_steps` is the total number of updates, as an `int`. `batch_size < 1` raises `ValueError`. In this example `grad_fn` ignores the data and returns `w`, so every step halves `w` and the shuffle order does not change the result: ```python X = [[0], [1], [2], [3], [4]] y = [0, 0, 0, 0, 0] w0 = [4.0] grad_fn = lambda w, Xb, yb: w loss_fn = lambda w, X, y: 0.5 * float(w @ w) out = minibatch_sgd(grad_fn, loss_fn, w0, X, y, lr=0.5, batch_size=2, n_epochs=2, drop_last=False) # out["w"] -> array([0.0625]) # out["n_steps"] -> 6 # out["loss_history"] -> array([0.125, 0.001953125]) # out["grad_variance"] -> array([14/9, 14/9/64]) (about 1.5556 and 0.0243) ``` Each epoch has three batches of sizes 2, 2 and 1. The first epoch's gradients are 4, 2 and 1, which gives a variance of 14/9 and leaves `w = 0.5`. The second epoch repeats the pattern at one eighth the scale, so its variance is 64 times smaller. ```hint Where the mean comes from The spread is measured around the epoch's mean gradient, which you only know after the last batch of that epoch. Decide what you need to keep from each step to compute it. ``` ```hint Two easy ways to break reproducibility Think about what must happen to the generator in an epoch where every batch is dropped, and what an in-place update would do to `w0` or to a gradient array that `grad_fn` returned by reference. ``` ### Constraints & Assumptions - `X` is array-like with `n` rows along its first axis, and `y` has `n` entries aligned with `X`. - `w0` can have any shape. `grad_fn(w, Xb, yb)` returns an array shaped like `w`, and `loss_fn(w, X, y)` returns a scalar. Both are provided by the caller. - All randomness comes from the single `np.random.default_rng(seed)`, so two calls with the same arguments must return identical results. ### What a Strong Answer Covers - Advancing one seeded generator exactly once per epoch, including epochs where every batch is dropped - Leaving `w0` untouched and recording each gradient at the weights where it was evaluated - The per-epoch spread with the population divisor, the `nan` case, and correct output types - The short final batch under both `drop_last` settings and the `batch_size < 1` check - Time and memory cost, and what the tracked variance actually measures along a moving trajectory ### Follow-up Questions - How does gradient variance scale with batch size, and how would you verify it? - Why can the partial last batch be problematic, and when is `drop_last` preferable? - How would you adjust the learning rate when increasing batch size?

Overview: Implement mini-batch stochastic gradient descent in NumPy with a seeded reshuffle every epoch, an option to drop the short final batch, and a per-epoch measure of how widely batch gradients spread around their mean. Tests careful handling of random state and input arrays, and reasoning about gradient noise and batch size.

General logo
General
Nov 25, 2026
mediumMachine Learning EngineerOtherMachine Learning
0
0

Implement minibatch_sgd(grad_fn, loss_fn, w0, X, y, lr, batch_size, n_epochs, seed=0, drop_last=False). Train w with mini-batch SGD using a fresh shuffle each epoch. Return a dict with "w", "loss_history", "grad_variance" and "n_steps".

The function must follow these rules:

  • Create one np.random.default_rng(seed) . Each epoch, draw rng.permutation(n) and use consecutive slices perm[i:i+batch_size] . With drop_last=True , skip the final short batch (the permutation is still drawn).
  • After each batch, apply w = w - lr * grad_fn(w, X[idx], y[idx]) . Never mutate w0 .
  • grad_variance[e] is the mean over that epoch's batches of ||g_b - mean(g)||² , where mean(g) is the average of that epoch's batch gradients. Divide by the number of batches. Use nan if the epoch had no batches.
  • loss_history[e] is loss_fn(w, X, y) on the full data at the end of each epoch. Both histories are float arrays of length n_epochs .
  • n_steps is the total number of updates, as an int . batch_size < 1 raises ValueError .

In this example grad_fn ignores the data and returns w, so every step halves w and the shuffle order does not change the result:

X = [[0], [1], [2], [3], [4]]
y = [0, 0, 0, 0, 0]
w0 = [4.0]
grad_fn = lambda w, Xb, yb: w
loss_fn = lambda w, X, y: 0.5 * float(w @ w)

out = minibatch_sgd(grad_fn, loss_fn, w0, X, y,
                    lr=0.5, batch_size=2, n_epochs=2, drop_last=False)
# out["w"]             -> array([0.0625])
# out["n_steps"]       -> 6
# out["loss_history"]  -> array([0.125, 0.001953125])
# out["grad_variance"] -> array([14/9, 14/9/64])   (about 1.5556 and 0.0243)

Each epoch has three batches of sizes 2, 2 and 1. The first epoch's gradients are 4, 2 and 1, which gives a variance of 14/9 and leaves w = 0.5. The second epoch repeats the pattern at one eighth the scale, so its variance is 64 times smaller.

Constraints & Assumptions

  • X is array-like with n rows along its first axis, and y has n entries aligned with X .
  • w0 can have any shape. grad_fn(w, Xb, yb) returns an array shaped like w , and loss_fn(w, X, y) returns a scalar. Both are provided by the caller.
  • All randomness comes from the single np.random.default_rng(seed) , so two calls with the same arguments must return identical results.

What a Strong Answer Covers Guidance

  • Advancing one seeded generator exactly once per epoch, including epochs where every batch is dropped
  • Leaving w0 untouched and recording each gradient at the weights where it was evaluated
  • The per-epoch spread with the population divisor, the nan case, and correct output types
  • The short final batch under both drop_last settings and the batch_size < 1 check
  • Time and memory cost, and what the tracked variance actually measures along a moving trajectory

Follow-up Questions Guidance

  • How does gradient variance scale with batch size, and how would you verify it?
  • Why can the partial last batch be problematic, and when is drop_last preferable?
  • How would you adjust the learning rate when increasing batch size?