|
4 | 4 |
|
5 | 5 | import os |
6 | 6 | import time |
7 | | -from dataclasses import dataclass |
| 7 | +from dataclasses import dataclass, replace |
8 | 8 | from typing import Callable, Mapping |
9 | 9 |
|
10 | 10 | import mlx.core as mx |
11 | 11 | import mlx.nn as nn |
12 | 12 | import mlx.optimizers as optim |
13 | | -from mlx.utils import tree_flatten |
| 13 | +from mlx.utils import tree_flatten, tree_map |
14 | 14 |
|
15 | | -from cppmega_mlx.data.batch import LMTokenBatch |
| 15 | +from cppmega_mlx.data.batch import LMTokenBatch, ensure_lm_batch |
16 | 16 | from cppmega_mlx.training.loss import next_token_cross_entropy |
17 | 17 | from cppmega_mlx.training.optimizers import make_adamw |
18 | 18 |
|
19 | 19 |
|
20 | 20 | LossFn = Callable[[nn.Module, LMTokenBatch | Mapping[str, mx.array] | mx.array], tuple[mx.array, mx.array]] |
21 | 21 |
|
22 | 22 | _STRICT_DTYPE_CONTRACT_ENV = "STRICT_DTYPE_CONTRACT" |
| 23 | +# PR-2 (FUSED-PIPELINE-ROADMAP §4/§5): gradient accumulation in the loop. |
| 24 | +# Default OFF (grad_accum_steps=1) so behavior is byte-identical to the prior |
| 25 | +# single-eval step unless explicitly opted in. ``GRAD_ACCUM_STEPS`` env var |
| 26 | +# provides a process-wide default for callers that do not pass the kwarg. |
| 27 | +_GRAD_ACCUM_STEPS_ENV = "GRAD_ACCUM_STEPS" |
23 | 28 |
|
24 | 29 |
|
25 | 30 | @dataclass(frozen=True) |
@@ -68,32 +73,162 @@ def assert_grad_dtype_matches_param_dtype(grads, params) -> None: |
68 | 73 | ) |
69 | 74 |
|
70 | 75 |
|
| 76 | +def _resolve_grad_accum_steps(grad_accum_steps: int | None) -> int: |
| 77 | + """Resolve the microbatch count from kwarg then env, default 1 (OFF).""" |
| 78 | + |
| 79 | + if grad_accum_steps is None: |
| 80 | + env_value = os.environ.get(_GRAD_ACCUM_STEPS_ENV) |
| 81 | + grad_accum_steps = int(env_value) if env_value not in (None, "") else 1 |
| 82 | + if not isinstance(grad_accum_steps, int) or grad_accum_steps < 1: |
| 83 | + raise ValueError( |
| 84 | + f"grad_accum_steps must be a positive integer, got {grad_accum_steps!r}" |
| 85 | + ) |
| 86 | + return grad_accum_steps |
| 87 | + |
| 88 | + |
| 89 | +def _microbatch_slices(batch_size: int, num_micro: int) -> list[tuple[int, int]]: |
| 90 | + """Split ``batch_size`` rows into ``num_micro`` contiguous, near-equal spans. |
| 91 | +
|
| 92 | + Raises if the batch is too small to provide one row per microbatch — a |
| 93 | + silent no-op split would mask a misconfigured ``grad_accum_steps`` (RULE #1). |
| 94 | + """ |
| 95 | + |
| 96 | + if num_micro > batch_size: |
| 97 | + raise ValueError( |
| 98 | + f"grad_accum_steps={num_micro} exceeds batch size {batch_size}; " |
| 99 | + "each microbatch needs at least one row" |
| 100 | + ) |
| 101 | + base, extra = divmod(batch_size, num_micro) |
| 102 | + spans: list[tuple[int, int]] = [] |
| 103 | + start = 0 |
| 104 | + for i in range(num_micro): |
| 105 | + length = base + (1 if i < extra else 0) |
| 106 | + spans.append((start, start + length)) |
| 107 | + start += length |
| 108 | + return spans |
| 109 | + |
| 110 | + |
| 111 | +def _slice_lm_batch(batch: LMTokenBatch, start: int, stop: int) -> LMTokenBatch: |
| 112 | + """Return a row-slice ``[start:stop)`` of every per-example array field.""" |
| 113 | + |
| 114 | + updates: dict[str, mx.array] = {} |
| 115 | + for name, value in vars(batch).items(): |
| 116 | + if isinstance(value, mx.array) and value.shape and value.shape[0] == batch.tokens.shape[0]: |
| 117 | + updates[name] = value[start:stop] |
| 118 | + return replace(batch, **updates) |
| 119 | + |
| 120 | + |
| 121 | +def _accumulate_grads_token_weighted( |
| 122 | + accumulator: dict | None, |
| 123 | + grads: dict, |
| 124 | + weight: mx.array, |
| 125 | +) -> dict: |
| 126 | + """Add ``weight * grads`` into ``accumulator`` (token-weighted running sum). |
| 127 | +
|
| 128 | + Token weighting makes the accumulated gradient numerically equal to the |
| 129 | + full-batch gradient: the per-microbatch loss is a token-mean, so the |
| 130 | + full-batch grad is ``sum_i (n_i / N) * grad_i`` by linearity. |
| 131 | + """ |
| 132 | + |
| 133 | + weighted = tree_map( |
| 134 | + lambda g: (g * weight).astype(g.dtype) if isinstance(g, mx.array) else g, |
| 135 | + grads, |
| 136 | + ) |
| 137 | + if accumulator is None: |
| 138 | + return weighted |
| 139 | + return tree_map( |
| 140 | + lambda acc, g: acc + g if isinstance(acc, mx.array) else acc, |
| 141 | + accumulator, |
| 142 | + weighted, |
| 143 | + ) |
| 144 | + |
| 145 | + |
71 | 146 | def one_step_train( |
72 | 147 | model: nn.Module, |
73 | 148 | optimizer: optim.Optimizer, |
74 | 149 | batch: LMTokenBatch | Mapping[str, mx.array] | mx.array, |
75 | 150 | *, |
76 | 151 | loss_fn: LossFn = next_token_cross_entropy, |
| 152 | + grad_accum_steps: int | None = None, |
| 153 | + clear_cache: bool = False, |
77 | 154 | ) -> TrainStepResult: |
78 | | - """Run one eager MLX AdamW-compatible training step.""" |
| 155 | + """Run one eager MLX AdamW-compatible training step. |
| 156 | +
|
| 157 | + ``grad_accum_steps`` (default 1, also settable via the ``GRAD_ACCUM_STEPS`` |
| 158 | + env var) splits the batch into N microbatches and accumulates token-weighted |
| 159 | + grads with an ``mx.eval(grads)`` free-barrier between microbatches, dropping |
| 160 | + each microbatch's forward/backward graph before the next is built. This |
| 161 | + collapses peak activation memory from full-batch to ~one microbatch while |
| 162 | + remaining numerically equivalent to the full-batch step (FUSED-PIPELINE |
| 163 | + ROADMAP §4/§5, PR-2). With N=1 the path is byte-identical to the prior step. |
| 164 | + """ |
79 | 165 |
|
80 | 166 | model.train() |
81 | | - loss_and_grad = nn.value_and_grad(model, loss_fn) |
| 167 | + num_micro = _resolve_grad_accum_steps(grad_accum_steps) |
82 | 168 |
|
83 | 169 | start = time.perf_counter() |
84 | | - (loss, ntokens), grads = loss_and_grad(model, batch) |
| 170 | + if num_micro == 1: |
| 171 | + loss_and_grad = nn.value_and_grad(model, loss_fn) |
| 172 | + (loss, ntokens), grads = loss_and_grad(model, batch) |
| 173 | + if _strict_dtype_contract_enabled(): |
| 174 | + assert_grad_dtype_matches_param_dtype(grads, model.parameters()) |
| 175 | + optimizer.update(model, grads) |
| 176 | + mx.eval(model.parameters(), optimizer.state, loss, ntokens) |
| 177 | + elapsed = time.perf_counter() - start |
| 178 | + tokens = int(ntokens.item()) |
| 179 | + if clear_cache: |
| 180 | + mx.clear_cache() |
| 181 | + return TrainStepResult( |
| 182 | + loss=float(loss.item()), |
| 183 | + ntokens=tokens, |
| 184 | + seconds=elapsed, |
| 185 | + tokens_per_second=tokens / elapsed if elapsed > 0 else float("inf"), |
| 186 | + ) |
| 187 | + |
| 188 | + lm_batch = ensure_lm_batch(batch) |
| 189 | + batch_size = int(lm_batch.tokens.shape[0]) |
| 190 | + spans = _microbatch_slices(batch_size, num_micro) |
| 191 | + |
| 192 | + loss_and_grad = nn.value_and_grad(model, loss_fn) |
| 193 | + |
| 194 | + # Pass 1: total live-token count across the whole batch, used to |
| 195 | + # token-weight each microbatch grad so the accumulated grad equals the |
| 196 | + # full-batch grad. ``target_mask`` is pure data (no forward graph), so this |
| 197 | + # costs nothing in activation memory. |
| 198 | + total_ntokens = lm_batch.target_mask.sum().astype(mx.float32) |
| 199 | + mx.eval(total_ntokens) |
| 200 | + total_tokens_int = int(total_ntokens.item()) |
| 201 | + if total_tokens_int <= 0: |
| 202 | + raise ValueError("grad accumulation requires at least one live target token") |
| 203 | + |
| 204 | + accumulator: dict | None = None |
| 205 | + weighted_loss = mx.array(0.0, dtype=mx.float32) |
| 206 | + for span_start, span_stop in spans: |
| 207 | + micro = _slice_lm_batch(lm_batch, span_start, span_stop) |
| 208 | + (micro_loss, micro_ntok), micro_grads = loss_and_grad(model, micro) |
| 209 | + weight = (micro_ntok.astype(mx.float32) / total_ntokens) |
| 210 | + accumulator = _accumulate_grads_token_weighted(accumulator, micro_grads, weight) |
| 211 | + weighted_loss = weighted_loss + micro_loss.astype(mx.float32) * weight |
| 212 | + # Free-barrier: force the accumulator + running loss, then drop the |
| 213 | + # microbatch's forward/backward graph before building the next one. |
| 214 | + mx.eval(accumulator, weighted_loss) |
| 215 | + del micro_grads, micro, micro_loss, micro_ntok |
| 216 | + |
| 217 | + if accumulator is None: |
| 218 | + raise RuntimeError("grad accumulation produced no gradients") |
85 | 219 | if _strict_dtype_contract_enabled(): |
86 | | - assert_grad_dtype_matches_param_dtype(grads, model.parameters()) |
87 | | - optimizer.update(model, grads) |
88 | | - mx.eval(model.parameters(), optimizer.state, loss, ntokens) |
| 220 | + assert_grad_dtype_matches_param_dtype(accumulator, model.parameters()) |
| 221 | + optimizer.update(model, accumulator) |
| 222 | + mx.eval(model.parameters(), optimizer.state, weighted_loss) |
89 | 223 | elapsed = time.perf_counter() - start |
90 | 224 |
|
91 | | - tokens = int(ntokens.item()) |
| 225 | + if clear_cache: |
| 226 | + mx.clear_cache() |
92 | 227 | return TrainStepResult( |
93 | | - loss=float(loss.item()), |
94 | | - ntokens=tokens, |
| 228 | + loss=float(weighted_loss.item()), |
| 229 | + ntokens=total_tokens_int, |
95 | 230 | seconds=elapsed, |
96 | | - tokens_per_second=tokens / elapsed if elapsed > 0 else float("inf"), |
| 231 | + tokens_per_second=total_tokens_int / elapsed if elapsed > 0 else float("inf"), |
97 | 232 | ) |
98 | 233 |
|
99 | 234 |
|
|
0 commit comments