Dataset Viewer
Auto-converted to Parquet Duplicate
Search is not available for this dataset
image
imagewidth (px)
960
1.5k

Full-batch gradient descent on the NanoGPT speedrun model

Everything from a set of experiments training the NanoGPT speedrun world-record model (record #360, "ANVIL2") with exact full-batch gradients, compared against ordinary small-batch training on exactly the same data. The code is at github.com/shawnghu/nanogpt-fullbatch.

The result in one table

All runs use the same model and fixed objective. "Training-sample loss" is the loss on a fixed 10M-token sample spread across the 800M training set; "validation loss" is the standard speedrun validation set (10.5M FineWeb tokens).

Run Tokens per step Steps Training-sample loss (end) Validation loss (end)
Small batch on the 800M set (small_batch_control/) 393K 2,372 3.186 3.248
Full batch on the 800M set (full_batch/) 800M (all of it) 350 3.094 3.521 (best 3.498)
Fresh data, no token repeated (batch_ladder/batch_50M/fresh_data/) 50M 350 3.228 3.230

Full batch fits the training set better than small batch but generalizes much worse: at equal training-sample loss its validation loss is about 0.2 nats higher, and its validation loss stops improving after about step 260 while the training loss keeps falling.

Setup

  • Model: the record #360 architecture (11 layers, width 768, about 262M dense parameters of which 155M are the value-embedding table), with its FP8/FlashAttention-3 kernels and its optimizer (ANVIL, a Muon-family optimizer, for the attention and MLP matrices; Adam for everything else). Changes from the record, all to make the objective fixed and the gradient exact: one stage for the whole run (sequence length 3072 with attention segments capped at 2560, attention windows (5, 11) in 128-token blocks, plain next-token loss, full softmax), tied embeddings, no hashed n-gram table, and every optimizer updating every step.
  • Data: the fixed training set is in dataset/: the first 16,272 packed microbatches (799.8M tokens) of kjj0/fineweb10B-gpt2. Fixed-set runs train only on these tokens; fresh-data runs read the token stream from the start without repeating.
  • Full batch: every step accumulates the exact gradient of the mean loss over all 799.8M tokens (fp32 accumulators over 16,272 microbatches), then takes one optimizer step. 350 steps, learning-rate multiplier 1.2, linear decay over the last 80% of steps to 0.3 of the peak. It ran on 4 H200s on preemptible compute (106 preemptions), resuming from step-boundary or mid-step checkpoints.

Layout

dataset/
  train_tokens.npy                 uint16 [16272, 49153]; microbatch k: inputs = row[:49152], targets = row[1:]
  attention_segment_ends.npy       int32 [16272, 384]; cumulative attention-segment ends per microbatch, padded with 49152
  dataset_info.json                packing rule, source, checksum
full_batch/                        the full-batch run
  config.json, metrics.jsonl       per-step training loss over all 800M tokens; every 5 steps val and training-sample loss
  dynamics/scalars.jsonl           per-step dynamics statistics (see below)
  dynamics/arrays/step_XXXXXX.npz  per-step arrays (per-tensor norms, per-microbatch statistics, singular values, ...)
  gradients/step_XXXXXX.safetensors   G_t: gradient of the mean training loss over all 800M tokens at the weights before step t (bf16)
  updates/step_XXXXXX.safetensors     u_t = theta_{t+1} - theta_t (bf16)
  token_losses/step_XXXXXX.npy     fp16 [16272, 49152]: loss of every training token at the weights before step t (every 10 steps); row k = microbatch k of dataset/
  checkpoints/step_XXXXXX/model.safetensors        weights after step t (every 50 steps)
  checkpoints/step_XXXXXX/resume_state/            optimizer state, model buffers (fp8 caches, rotary tables) and rng, per rank: enough to resume exactly
  posthoc_curvature/               curvature analysis at each checkpoint (per-block and preconditioned sharpness, per-block line probes); see its README
small_batch_control/               393K tokens per step on the same 800M set (metrics only)
batch_ladder/batch_<B>/            intermediate batch sizes: fixed_800M_set/ and, where run, fresh_data/ at the same batch, lr and schedule
large_batch_sweep_fresh_data/      fresh-data sweep over batch size, steps and lr used to estimate the full-batch step budget
fresh_data_convergence_reference/  fresh data at 393K tokens per step, schedules of 1x, 3x and 10x the steps needed to reach 3.28
                                   (forward_path_check.json: training- vs evaluation-forward-pass losses; see caveats)
                                   old_record_18/: the Jan 2025 record #18 code (bf16, no FP8) at 1x/3x/10x: val 3.278 / 3.103 / 2.986
record_ablation/logs/              ablation of the original record toward the full-batch-compatible configuration
verification/                      gradient-accumulation and determinism checks of the trainer

Gradients, updates and weights are keyed by the record's parameter-bank names (qk_bank, vo_bank, mlp_bank, lm_head, the MUDD skip-connection weights, scalars, ...). Gradients and updates leave out value_embeds (155M parameters) to save space; the checkpoints include it. With tied embeddings, lm_head's gradient includes the embedding's.

Dynamics statistics (full_batch/dynamics/scalars.jsonl)

Measured at the weights before each step, on fixed probe sets of 1.6M training tokens where a probe set is needed:

  • every step: norm/* (global norms), cos/grad_prevgrad (cosine between consecutive full gradients), cos/update_prevupdate, ratio/update_over_weight, gns/* (per-microbatch gradient variance, the gradient noise scale B_simple = mean microbatch tokens × between-microbatch variance / ‖G‖², and the fraction of microbatch gradients anti-aligned with the previous full gradient);
  • every 5 steps: line/* (a 7-point line probe of the loss along the actual update, with a_star the loss-minimizing fraction of the step and stability_ratio = uᵀHu / (−2 gᵀu), which is 1 when the step lands at its starting loss), and spec/sv/* (singular-value summaries of weights, gradients and updates of the matrix banks);
  • every 10 steps: curv/* (curvature along the update and the gradient from finite-difference Hessian-vector products);
  • every 100 steps: sharp/* (Lanczos extreme Hessian eigenvalues and the Adam-preconditioned top eigenvalue; values at step 0 are not meaningful).

Hessian-vector products are finite differences of gradients, because the FP8 and FlashAttention kernels have no second derivatives; on a toy model with exact Hessians this gave 2–5% error on the top eigenvalue.

Loading a checkpoint and computing Hessian-vector products

Everything below uses the code in github.com/shawnghu/nanogpt-fullbatch. The model needs the record's kernels: H100/H200-class GPUs, a CUDA 13 runtime, and torch==2.10 from the cu128 index (see the repo README).

Weights only. checkpoints/step_XXXXXX/model.safetensors holds the weights after step XXXXXX (that is, the weights the step-XXXXXX gradient was taken at), keyed by the names in track_1_short/model/gpt.py. Load them into the trainer's model with FullBatchTrainer(cfg).raw_model.load_state_dict(..., strict=False), or into your own reimplementation. The matrix banks are stored in bf16, which is exactly what the forward pass used. ANVIL's extra precision bits are in the optimizer state, not here.

Exact training state. resume_state/ holds everything needed to continue the run exactly. It is sharded the way the run was, over 4 GPUs:

  • optimizer_rank{r}.safetensors: optimizer tensors keyed "<param label>/<state name>". For the ANVIL matrix banks (qk_bank, vo_bank, mlp_bank) this is velocity (shape [2, chunk, rows, cols]: the fast and slow momentum rails), lane_energy (the equalizer's EMA) and mantissa (the low 16 bits of the fp32 master weights). Rank r owns matrices [r*chunk, (r+1)*chunk) of the bank reshaped to [n_matrices, rows, cols] (the reshape attribute in the code). Adam parameters have exp_avg and exp_avg_sq; sharded ones (lm_head, value_embeds) are split the same way along their first dimension.
  • meta_rank{r}.json: the non-tensor state (Adam step counts, step_count, split_embed, mlp_quantize_calls).
  • buffers_rank{r}.safetensors: model buffers (FP8 weight caches and delayed scales, rotary tables). They are identical across ranks except two activation-scale buffers (_mlp_post_scales, _mlp_dpre_scales), which track each rank's own activations.
  • rng_rank{r}.safetensors: RNG state.

load_hf_checkpoint(trainer, checkpoint_dir) in posthoc_curvature.py restores all of this into a FullBatchTrainer built from full_batch/config.json, when run with torchrun --nproc_per_node=4. As a check, it recomputes the full-dataset training loss at the checkpoint and compares it with full_batch/metrics.jsonl.

Hessian-vector products. The FP8 and FlashAttention kernels have no second derivatives, so instr/dynamics.py computes HVPs as central finite differences of gradients (HVP(oracle, probe, mode="fd")). The step size is set so that the largest relative change in any single tensor is 1e-3; on a toy model with exact Hessians this gave 2–5% error on the top eigenvalue. FBOracle in instr/fb_hooks.py wraps the trainer, freezes the FP8 scaling state while probing (otherwise every forward pass changes it), and provides loss, loss_and_grad, get_params and set_params on fixed probe subsets of the training set. lanczos, MaskedHVP (one parameter block), ScaledHVP (diagonal preconditioning) and line_probe build on it. posthoc_curvature.py is a worked example that uses all of them.

Weights between checkpoints can be approximated by adding the per-step updates/ to the nearest earlier checkpoint. This is only approximate: the updates are stored in bf16, and the value-embedding table's updates were not saved per step.

Caveats

  • One run per configuration. Seed-to-seed noise in validation loss for this model is about 0.003.
  • Full batch on a fixed set means every token is seen on every step, so these runs don't separate "no gradient noise" from "many passes over the same data".
  • The learning rate was tuned on fresh data, not on the fixed set.
  • In the 10x fresh-data reference run, the model's FP8 training forward pass and its bf16 evaluation forward pass drifted apart after about 5,000 steps (3.15 against 4.62 on the same unseen tokens at the end), so its validation curve is not meaningful. The 1x and 3x runs (validation 3.282 and 3.170) and the full-batch run (3.562 against 3.549 on unseen tokens) don't have this problem.
  • Per-token losses at steps 0–40 were recorded with a bug that appended rows from instrumentation passes; those rows were removed in this export, so every token_losses file has exactly one row per training microbatch.
Downloads last month
238