Test MLX gradient accumulation with uneven microbatches

Test MLX gradient accumulation with uneven microbatches

Test MLX gradient accumulation with uneven microbatches

You switch MLX training on a cloud Mac from full batches to microbatches. Memory usage drops, but the loss curve changes. Before adjusting the learning rate, check two common mistakes: treating the final, shorter microbatch as a full one when averaging, and stepping the optimizer before accumulation is complete. The five-sample experiment below isolates these errors within a single parameter update.

Define the effective batch first

The effective batch comprises all samples covered by one optimizer update. A microbatch is simply the unit used to compute gradients in smaller chunks. Suppose five samples are split into three microbatches of two, two, and one. If the target loss is the mean loss over all five samples, the mean gradient from each microbatch must be weighted by two fifths, two fifths, and one fifth, respectively.

Adding the three mean gradients and dividing by three gives the last sample too much weight. This mistake may not cause a runtime error, but it changes the training objective.

Keep parameters unchanged throughout the accumulation window, then update them exactly once at the end. The full-batch versus microbatch comparison checks this contract; it does not require bitwise-identical floating-point results.

The experiment uses a linear layer without bias, mean squared error, and SGD without momentum. This removes interference from stochastic layers, cross-sample statistics, and optimizer history.

Prepare an isolated environment

Run the commands in a native Apple Silicon terminal. First, use uname -m to confirm that the output is arm64. With a working Python 3 installation available, create a dedicated virtual environment rather than upgrading dependencies used by production training jobs.

python3 -m venv .venv-accum
source .venv-accum/bin/activate
python -m pip install mlx
python -m pip freeze > requirements-accum.txt

Save the following code as check_accum.py, then run python check_accum.py. Keep the dependency list alongside the script. When changing MLX versions later, rerun the check with the same inputs.

Compare one full-batch update with an accumulated update

The two models start with identical weights and use separate optimizers. The full-batch model updates directly. The microbatch model first weights gradients by sample count, accumulates the gradient tree, and then performs a single update. The code requires no external model weights or training data.

import mlx.core as mx
import mlx.nn as nn
import mlx.optimizers as optim
from mlx.utils import tree_map

x = mx.array([
    [1.0, 0.0],
    [0.0, 1.0],
    [1.0, 1.0],
    [2.0, 1.0],
    [1.0, 2.0],
])
y = mx.array([[1.0], [2.0], [3.0], [4.0], [5.0]])
initial = mx.array([[0.25, -0.5]])

def make_model():
    model = nn.Linear(2, 1, bias=False)
    model.update({"weight": initial})
    return model

def loss_fn(model, inputs, targets):
    return mx.mean(mx.square(model(inputs) - targets))

full = make_model()
micro = make_model()
full_opt = optim.SGD(learning_rate=0.01, momentum=0.0)
micro_opt = optim.SGD(learning_rate=0.01, momentum=0.0)

full_grad = nn.value_and_grad(full, loss_fn)
micro_grad = nn.value_and_grad(micro, loss_fn)

_, grads = full_grad(full, x, y)
full_opt.update(full, grads)
mx.eval(full.parameters(), full_opt.state)

accumulated = None
covered = 0

for start, end in [(0, 2), (2, 4), (4, 5)]:
    _, grads = micro_grad(micro, x[start:end], y[start:end])
    weight = (end - start) / len(x)
    weighted = tree_map(lambda g: g * weight, grads)
    if accumulated is None:
        accumulated = weighted
    else:
        accumulated = tree_map(
            lambda a, b: a + b, accumulated, weighted
        )
    mx.eval(accumulated)
    covered += end - start

assert covered == len(x)
micro_opt.update(micro, accumulated)
mx.eval(micro.parameters(), micro_opt.state)

error = mx.max(mx.abs(full.weight - micro.weight)).item()
assert error < 1e-5, f"Update mismatch: {error}"

If the script exits normally, this update has passed the check. It compares not just gradients but also the updated parameters, checking that the learning rate, update order, and accumulation weights are applied correctly. The tolerance here is specific to this small experiment; do not copy it unchanged into low-precision training of large models.

Add checks for partial batches and window resets

In a production loop, define exactly how many samples belong to each accumulation window. When the total dataset length is known, determine the actual denominator for the current window first. Alternatively, accumulate unnormalized gradients and divide by the window's actual total before updating. Do not mix the two approaches, or you will scale the gradients twice.

Keep at least the following checks:

In the example, accumulated starts as None. When adapting it to a loop with multiple windows, reinitialize both accumulated and covered at the start of every window. MLX returns a gradient tree; do not copy gradient-zeroing patterns from other frameworks that rely on per-parameter gradient buffers.

Establish the boundaries before moving to language models

Language-model losses are often averaged over valid tokens rather than samples. Even when two texts belong to the same microbatch, their valid token counts may differ after padding and masked positions are excluded. Check the denominator actually used by the loss function before choosing the weights. Handle fully masked microbatches explicitly to avoid division by zero.

If using gradient clipping, accumulate and normalize first, then compute the global norm across the entire gradient tree. Clipping each microbatch's gradients before adding them generally differs from clipping the total gradient. Also specify whether the learning-rate schedule advances with optimizer updates or with the number of samples processed.

Enable stochastic layers, mixed precision, or real optimizer state only after these checks. Models with cross-sample operations do not necessarily preserve equivalence when batches are split. Even with a fixed seed, splitting batches can change the order in which stochastic layers consume random numbers. First validate the loop's semantics with a deterministic test fixture, then assess statistical behavior on the real task. This lets you distinguish an accumulation bug from a model that does not meet the assumptions required for equivalence.

Frequently asked questions

Can I divide every microbatch loss by the accumulation count?

Only when microbatches have equal size and use the same loss denominator. Weight uneven batches by sample count, or by valid token count for a token-averaged objective.

Is accumulation equivalent to several optimizer steps?

No. Keep parameters fixed throughout an effective batch and update once after accumulation. Updating each microbatch changes both the gradient evaluation point and optimizer state.

Rent for a Day to Test Your Model

VPSMain offers dedicated physical Mac mini servers—not virtual machines—from $19.6/day. Rent by the day, week, month, or quarter, with same-day setup. Choose unified memory based on quantized model weights, KV cache, and system overhead.