Critical-batch-size sequence-model experiments

This starter contains a small causal Transformer, an adapter for the official RWKV-7 implementation, a Gated DeltaNet model, and a reproducible PCFG corpus generator. LSTM was left out as requested.

Prepare the PCFG corpus

From the project root:

python -m cbs_benchmark.prepare_data --out-dir data/pcfg_balanced

This writes train.txt, valid.txt, test.txt, vocab.json, grammar.json, and split statistics. The default grammar generates typed balanced-bracket structures with terminal leaves. Its recursive rules emit OPEN_i S CLOSE_i S; the recursion probability is below 0.5. Set the seed and generation limits explicitly when recording an experiment.

Use PCFGBlockDataset(path, vocab_path, block_size=128) to create fixed-token next-token examples. A 128-token block divides 2,000,000 tokens exactly: 15,625 blocks make one optimizer update. Use gradient accumulation over smaller microbatches to fit the update into GPU memory. The same materialized corpus can be reused for every model, batch size, and optimizer.

Models

All models return logits shaped [batch, sequence, vocab_size] and expose the same next-token objective. The starter configurations target fewer than 3M trainable parameters for the small default PCFG vocabulary:

Model Suggested configuration
Transformer 6 layers, d_model=192, 6 heads, FFN multiplier 4
RWKV-7 5 layers, d_model=192, official head size 64
GDN 3 layers, d_model=256, head size 64, 3 QK heads

Use starter_configs(vocab_size) for these shapes and check each instantiated model with assert_parameter_budget(model). The count includes only tensors with requires_grad=True; frozen parameters, buffers, and recurrent state are excluded. Embeddings and the language-model output head are included. Larger vocabularies can push a starter shape over budget, so check the actual count.

RWKV-7

RWKV7LanguageModel loads RWKV-LM/RWKV-v7/train_temp/src/model.py from the official checkout and compiles its official CUDA extensions when instantiated. The checked-out code is Apache-2.0 licensed. The upstream fast kernel requires a CUDA GPU with BF16 support, head size 64, and sequence lengths divisible by 16. The wrapper stores model parameters in BF16 and keeps normalization outputs in BF16 for the kernels; the AdamW sweep uses FP32 master weights and optimizer state. It also calls the upstream generate_init_weight() initialization by default. RWKV-7 therefore cannot run on CPU through this adapter. The upstream README recommends pytorch-lightning==1.9.5; this experiment ran with pytorch-lightning==2.6.6 and ninja==1.13.2. On CUDA 13 and current PyTorch, apply the small compatibility patch at cbs_benchmark/patches/rwkv7_torch_cuda13_compat.patch to the official checkout before building the extensions. It replaces the unsupported vector float atomic with two scalar atomics and makes the upstream non-JIT helper names unique. The first model construction compiles the CUDA extensions.

Gated DeltaNet

GDNLanguageModel uses fla.layers.GatedDeltaNet in chunk mode. The Python import name is fla; install the CUDA package with:

uv pip install 'flash-linear-attention[cuda]==0.6.0'

The NVIDIA Gated Delta Networks repository points users to FLA for faster kernels and variable-length support. FLA is MIT-licensed. Chunkwise training works best with block sizes compatible with its kernel; use a multiple of 64 for the initial runs.

Minimal model setup

from cbs_benchmark.models import (
    GDNLanguageModel,
    RWKV7LanguageModel,
    TransformerLanguageModel,
    assert_parameter_budget,
    starter_configs,
)

import json

with open("data/pcfg_balanced/vocab.json", encoding="utf-8") as handle:
    vocab_size = len(json.load(handle))
configs = starter_configs(vocab_size, max_seq_len=128)
transformer = TransformerLanguageModel(configs["transformer"])

rwkv = RWKV7LanguageModel(configs["rwkv7"])

gdn = GDNLanguageModel(configs["gdn"], head_dim=64, num_heads=3)

print(assert_parameter_budget(transformer))
print(assert_parameter_budget(rwkv))
print(assert_parameter_budget(gdn))

Fixed-budget comparison protocol

  1. Train the reference Transformer with AdamW at the selected small token batch for a fixed number of optimizer steps. This defines the baseline token budget: T = small_batch_tokens * baseline_steps.
  2. Record the reference validation loss after exactly T training tokens. Keep the held-out validation split fixed for every run.
  3. Run every comparison model/optimizer with exactly 2,000,000 training tokens per optimizer update. Accumulate gradients over microbatches; normalize summed loss by the full update's token count before backpropagating.
  4. Fix the comparison step budget to T / 2,000,000 steps (choose T so this is an integer). Compare validation loss at that fixed endpoint. Do not stop individual runs early when they cross the reference loss.

Use the same materialized training data and initialization seed policy across comparisons. Tune each optimizer at the fixed 2M-token batch with the same search budget. The main result is loss after the matched token budget; also log the fixed optimizer-step count and elapsed time for the speedrun view.

Small-batch Transformer reference run

The reference uses 4,096 tokens/update and a fixed-seed PCFG token stream with no block reused during the 50M-token run. The stream is stored as uint8 IDs and loaded onto the GPU by the trainer. Generate it and train the baseline with:

python -m cbs_benchmark.prepare_data \
  --out-dir data/pcfg_balanced_resident \
  --train-tokens 49999872 \
  --block-size 128 \
  --valid-sequences 10000 \
  --test-sequences 10000 \
  --seed 1234
python -m cbs_benchmark.train_transformer \
  --data-dir data/pcfg_balanced_resident \
  --run-dir runs/transformer_adamw_small_batch_50m_resident \
  --tokens 49999872 \
  --batch-tokens 4096 \
  --block-size 128

The training stream has 49,999,873 IDs: 49,999,872 next-token targets plus one input token. At 128 tokens/block and 32 blocks/update, the run consumes all 390,624 training blocks exactly once across 12,207 updates.

The no-repeat run completed with 2,701,824 trainable parameters. Full validation loss was 1.583530 after 49,999,872 tokens, taking about 294 seconds on an RTX 3060. Configuration, periodic fixed-slice losses, full validation result, and final checkpoint are saved under the run directory. The earlier runs/transformer_adamw_small_batch_50m run used a smaller fixed corpus repeated about 21 times; it is retained for reference, but the resident no-repeat run is the context-128 baseline.

2M-token Transformer learning-rate sweep

The sweep uses 2,000,000 tokens/update for 25 updates (50M tokens total), a constant AdamW learning rate, and 16,384-token microbatches accumulated to the logical batch. Each run resets the same initialization seed and uses the same shuffled order of all 390,625 training blocks. Generate the corpus and launch the default LR grid with:

python -m cbs_benchmark.prepare_data \
  --out-dir data/pcfg_balanced_50m \
  --train-tokens 50000000 \
  --block-size 128 \
  --valid-sequences 10000 \
  --test-sequences 10000 \
  --seed 1234
python -m cbs_benchmark.sweep_transformer_lr \
  --data-dir data/pcfg_balanced_50m \
  --run-dir runs/transformer_adamw_2m_lr_sweep \
  --tokens 50000000 \
  --batch-tokens 2000000 \
  --microbatch-tokens 16384 \
  --block-size 128 \
  --seed 1234

This run was stopped manually during LR 3e-4. The completed full-validation losses are 2.950932 (1e-5), 2.709717 (3e-5), and 2.252520 (1e-4). The 3e-4 run reached 11 updates / 22M tokens before stopping; it has a partial metrics log but no final checkpoint. Higher learning rates were not started. See runs/transformer_adamw_2m_lr_sweep/sweep_status.csv for the complete status record and per-run directories for metrics and checkpoints.

Context-512 re-run

The context-512 comparison uses a fixed-seed stream with 50,331,648 targets. The small-batch baseline trains for 12,288 updates at 4,096 tokens/update. The large-batch sweep uses 2^21 = 2,097,152 tokens/update for 24 updates, also 50,331,648 targets total. A 32,768-token microbatch accumulates to the logical batch. Each model has 2,775,552 trainable parameters. All runs use the same initialization seed and traverse the 98,304 data blocks once, in the same shuffled order.

Run Full validation loss Wall time
Small-batch baseline, 4,096 tokens/update 1.544358 295 s
2^21 batch, AdamW LR 1e-5 2.965026 205 s
2^21 batch, AdamW LR 3e-5 2.733884 205 s
2^21 batch, AdamW LR 1e-4 2.279817 205 s
2^21 batch, AdamW LR 3e-4 2.076741 205 s
2^21 batch, AdamW LR 1e-3 2.055168 204 s
2^21 batch, AdamW LR 3e-3 2.059620 205 s
2^21 batch, AdamW LR 1e-2 2.058765 205 s

1e-3 was best in this sweep. It remained 0.511 nats/token above the small-batch baseline after the same token budget, while using about 31% less wall time on the RTX 3060. The plot's curves use the same fixed 256-block validation slice; endpoint markers show the full 456-block validation split.

Context-512 Transformer learning-rate sweep

Recreate the context-512 runs and plot with:

python -m cbs_benchmark.prepare_data \
  --out-dir data/pcfg_balanced_context512 \
  --train-tokens 50331648 \
  --block-size 512 \
  --valid-sequences 10000 \
  --test-sequences 10000 \
  --seed 1234
python -m cbs_benchmark.train_transformer \
  --data-dir data/pcfg_balanced_context512 \
  --run-dir runs/transformer_adamw_small_batch_context512_50331648 \
  --tokens 50331648 --batch-tokens 4096 --block-size 512 \
  --eval-every-tokens 2097152 --eval-blocks 256 --eval-batch-blocks 8 \
  --learning-rate 0.0003 --min-learning-rate 0.00003 \
  --warmup-tokens 1000000 --seed 1234
python -m cbs_benchmark.sweep_transformer_lr \
  --data-dir data/pcfg_balanced_context512 \
  --run-dir runs/transformer_adamw_2pow21_context512_lr_sweep \
  --tokens 50331648 --batch-tokens 2097152 --microbatch-tokens 32768 \
  --block-size 512 --eval-blocks 256 --eval-batch-blocks 8 \
  --learning-rates 1e-5,3e-5,1e-4,3e-4,1e-3,3e-3,1e-2 --seed 1234
python -m cbs_benchmark.plot_lr_sweep

The full per-step metrics, full-validation results, and checkpoints are under the two run directories. context512_comparison.csv contains the final-loss and wall-time comparison. The 50M-token corpus is synthetic PCFG data generated from the grammar and seed recorded in data/pcfg_balanced_context512.

Muon sweep and reducible-loss plot

The Muon run uses PyTorch's built-in torch.optim.Muon on hidden 2D weight matrices and AdamW on embeddings, the output head, biases, and normalization parameters. It uses nesterov=True, adjust_lr_fn="match_rms_adamw", momentum 0.95, five Newton-Schulz iterations, and weight decay 0.1. This is a hybrid optimizer setup following the PyTorch Muon API guidance; match_rms_adamw applies the per-shape update scaling described for large-model training by Liu et al. (2025). The run used PyTorch 2.14.1+cu130.

Run Best LR Full validation loss Wall time
AdamW, 2^21 batch 1e-3 2.055168 204.4 s
Muon + AdamW, 2^21 batch 2e-2 2.026795 205.5 s

Muon's full LR sweep (all runs used 24 updates and 50,331,648 tokens):

Muon LR Full validation loss
1e-5 3.105996
3e-5 3.066636
1e-4 2.943627
3e-4 2.678300
1e-3 2.166079
3e-3 2.044387
1e-2 2.036619
2e-2 2.026795

Both sweeps use the same 2.775552M-parameter Transformer, seed, data order, 24 updates, and 50,331,648 training tokens. Muon improves the best AdamW full-validation loss by 0.028372 nats/token (1.38%) at essentially the same wall time. The Nesterov-enabled 2e-2 run improved on the earlier 1e-2 Muon run by 0.009824 nats/token. The 4,096-token AdamW reference reaches 1.544358 after the same token count; neither large-batch optimizer matches it in this experiment.

The grammar's source entropy rate was computed by exact dynamic programming over the bounded PCFG, including its depth and length limits and rejection resampling: 1.523474 nats/token (2.197908 bits/token). This is the information-theoretic lower bound for the source when the full history is available. Since the model sees at most 512 tokens, the optimal finite-context Bayes loss can be higher. Thus the plotted excess (validation cross-entropy minus source entropy) is an upper-bound proxy for model-reducible loss at context 512, not the exact finite-context reducible loss. The log-log power-law exponent is a descriptive fit to fixed-slice validation points from 2,097,152 through 50,331,648 tokens; it should not be extrapolated beyond this range.

Series Full validation excess above source entropy Fitted exponent α
AdamW small batch, 4,096 tokens 0.020885 0.746
AdamW large batch, best LR 1e-3 0.531694 0.229
Muon + AdamW large batch, best LR 2e-2 0.503322 0.222

The combined figure includes the entropy line, validation-loss curves, and the log-log reducible-loss proxy. A standalone AdamW-only version was captured while the Muon sweep was running.

Context-512 AdamW and Muon reducible-loss scaling

AdamW-only reducible-loss scaling

Recreate the Muon sweep and figure with:

python -m cbs_benchmark.sweep_transformer_muon \
  --data-dir data/pcfg_balanced_context512 \
  --run-dir runs/transformer_muon_2pow21_context512_lr_sweep \
  --tokens 50331648 --batch-tokens 2097152 --microbatch-tokens 32768 \
  --block-size 512 --eval-blocks 256 --eval-batch-blocks 8 \
  --learning-rates 1e-5,3e-5,1e-4,3e-4,1e-3,3e-3,1e-2,2e-2 \
  --adjust-lr-fn match_rms_adamw --weight-decay 0.1 --momentum 0.95 \
  --grad-clip 1.0 --seed 1234
python -m cbs_benchmark.entropy_bound \
  --data-dir data/pcfg_balanced_context512 \
  --out runs/transformer_muon_2pow21_context512_lr_sweep/entropy_bound.json
python -m cbs_benchmark.plot_reducible_loss \
  --baseline-dir runs/transformer_adamw_small_batch_context512_50331648 \
  --adamw-sweep-dir runs/transformer_adamw_2pow21_context512_lr_sweep \
  --muon-sweep-dir runs/transformer_muon_2pow21_context512_lr_sweep \
  --entropy-json runs/transformer_muon_2pow21_context512_lr_sweep/entropy_bound.json \
  --output runs/transformer_muon_2pow21_context512_lr_sweep/reducible_loss_context512

The per-learning-rate summaries, full validation metrics, training curves, and final checkpoints are stored in the Muon run directory. The reducible_loss_analysis.json file records the endpoint losses, log-log exponents, and fit range; reducible_loss_curves.csv contains plotted points.

GDN large-batch learning-rate sweep

The GDN sweep uses FLA GatedDeltaNet 0.6.0 in chunk mode, with 3 layers, d_model=256, head dimension 64, and 3 QK heads. It has 2,784,402 trainable parameters. AdamW uses betas (0.9, 0.95), weight decay 0.1, and gradient clipping at 1.0. The sweep uses the same seed, shuffled PCFG block order, context length 512, 2^21 tokens/update, and 50,331,648-token budget as the Transformer and Muon runs.

GDN AdamW LR Full validation loss Wall time
1e-5 2.926757 306.0 s*
3e-5 2.561280 163.1 s
1e-4 2.021339 163.1 s
3e-4 1.725444 163.5 s
1e-3 1.680953 163.4 s
3e-3 1.664507 162.9 s
1e-2 1.768347 163.0 s
2e-2 1.883196 163.0 s

3e-3 is best in this sweep. Its full validation loss is 0.120149 nats/token above the 4,096-token Transformer reference, but substantially below the large-batch Transformer AdamW and Muon results. This is a cross-architecture comparison; GDN and Transformer have similar trainable parameter counts but different architectures. The first candidate's wall time (*) includes the initial FLA Triton kernel compilation; later candidates reuse the compiled kernels. The best run itself took 162.9 seconds after that one-time compile.

For the entropy-based view, the GDN reducible-loss proxy is 0.141034 nats/token with fitted log-log exponent α=0.6562 over 2.10M–50.33M training tokens. As above, subtracting the full-history source entropy gives an upper-bound proxy because the finite-context Bayes loss may be higher.

Context-512 Transformer, Muon, and GDN reducible-loss comparison

Recreate the GDN sweep and combined graph with:

uv pip install 'flash-linear-attention[cuda]==0.6.0'
python -m cbs_benchmark.sweep_gdn_lr \
  --data-dir data/pcfg_balanced_context512 \
  --run-dir runs/gdn_adamw_2pow21_context512_lr_sweep \
  --tokens 50331648 --batch-tokens 2097152 --microbatch-tokens 32768 \
  --block-size 512 --eval-blocks 256 --eval-batch-blocks 8 \
  --learning-rates 1e-5,3e-5,1e-4,3e-4,1e-3,3e-3,1e-2,2e-2 \
  --weight-decay 0.1 --grad-clip 1.0 --seed 1234
python -m cbs_benchmark.plot_reducible_loss \
  --baseline-dir runs/transformer_adamw_small_batch_context512_50331648 \
  --adamw-sweep-dir runs/transformer_adamw_2pow21_context512_lr_sweep \
  --muon-sweep-dir runs/transformer_muon_2pow21_context512_lr_sweep \
  --gdn-sweep-dir runs/gdn_adamw_2pow21_context512_lr_sweep \
  --entropy-json runs/transformer_muon_2pow21_context512_lr_sweep/entropy_bound.json \
  --output runs/gdn_adamw_2pow21_context512_lr_sweep/reducible_loss_context512

Per-rate metrics and checkpoints are under runs/gdn_adamw_2pow21_context512_lr_sweep. The sweep summary records full validation loss, while the graph and reducible_loss_analysis.json include the entropy floor and fitted exponents.

RWKV-7 AdamW large-batch learning-rate sweep

This sweep uses the official BlinkDL RWKV-7 train_temp implementation and CUDA kernels, with 5 layers, d_model=192, and head size 64 (2,545,728 trainable parameters). The official generate_init_weight() initialization is used. Kernel parameters and activations are BF16; AdamW updates FP32 master weights with fused AdamW, betas (0.9, 0.95), weight decay 0.1, and gradient clipping at 1.0. The schedule is constant LR. Each candidate sees the same seeded permutation of 98,304 context-512 blocks and gets 24 updates of 2^21 tokens (50,331,648 tokens total). Per-update gradients accumulate over 32,768-token microbatches. Full validation uses all 456 validation blocks.

The local upstream compatibility patch is needed for CUDA 13 and this PyTorch version; it is distributed separately from the Apache-2.0 upstream checkout. Candidate wall times exclude the one-time CUDA extension build. The LR table, full-validation results, curves, checkpoints, and console log are stored in runs/rwkv7_adamw_2pow21_context512_lr_sweep/.

RWKV-7 AdamW LR Full validation loss Wall time
1e-5 1.819216 131.2 s
3e-5 1.809211 130.8 s
1e-4 1.794956 130.9 s
3e-4 1.760554 130.4 s
1e-3 1.693805 130.9 s
3e-3 1.687089 130.8 s
1e-2 2.072643 130.8 s
2e-2 1.821135 130.8 s

The best candidate, LR 3e-3, is 0.022582 nats/token above GDN AdamW (1.664507) and 0.142730 above the 4,096-token Transformer reference (1.544358). It is 0.368079 below large-batch Transformer AdamW and 0.339706 below Transformer Muon; these comparisons cross architectures. The entropy-subtracted reducible-loss proxy is 0.163615 nats/token, with fitted log-log exponent α=0.5910 over 2.10M–50.33M tokens. As for the other models, this proxy subtracts the full-history source entropy; the finite-context Bayes loss can be higher. Candidate times exclude the one-time CUDA extension build and span 130.4–131.2 seconds.

Prepare the local upstream checkout and Python build helpers with:

git clone https://github.com/BlinkDL/RWKV-LM.git
git -C RWKV-LM apply cbs_benchmark/patches/rwkv7_torch_cuda13_compat.patch
uv pip install ninja==1.13.2 pytorch-lightning==2.6.6

Best context-512 validation-loss curves overlaid on one graph

The X markers show full validation over all 456 blocks; the connected curves show the fixed 256-block validation slice at each checkpoint. The entropy-subtracted log-log comparison is also available.

Recreate the sweep and combined graph with:

python -m cbs_benchmark.sweep_rwkv7_lr \
  --data-dir data/pcfg_balanced_context512 \
  --run-dir runs/rwkv7_adamw_2pow21_context512_lr_sweep \
  --tokens 50331648 --batch-tokens 2097152 --microbatch-tokens 32768 \
  --block-size 512 --eval-blocks 256 --eval-batch-blocks 8 \
  --learning-rates 1e-5,3e-5,1e-4,3e-4,1e-3,3e-3,1e-2,2e-2 \
  --weight-decay 0.1 --grad-clip 1.0 --seed 1234
python -m cbs_benchmark.plot_reducible_loss \
  --baseline-dir runs/transformer_adamw_small_batch_context512_50331648 \
  --adamw-sweep-dir runs/transformer_adamw_2pow21_context512_lr_sweep \
  --muon-sweep-dir runs/transformer_muon_2pow21_context512_lr_sweep \
  --gdn-sweep-dir runs/gdn_adamw_2pow21_context512_lr_sweep \
  --rwkv-sweep-dir runs/rwkv7_adamw_2pow21_context512_lr_sweep \
  --entropy-json runs/transformer_muon_2pow21_context512_lr_sweep/entropy_bound.json \
  --output runs/rwkv7_adamw_2pow21_context512_lr_sweep/reducible_loss_context512
python -m cbs_benchmark.plot_loss_comparison \
  --output runs/rwkv7_adamw_2pow21_context512_lr_sweep/best_loss_overlay_context512

Upstream models and software

For the Transformer, cite Vaswani et al. (2017). For RWKV-7, cite the RWKV-7 paper and, when referring to the official implementation and kernels, cite BlinkDL/RWKV-LM using its CITATION.cff (software DOI 10.5281/zenodo.5196577). For Gated DeltaNet, cite Yang et al. (2025); this project uses the FLA GatedDeltaNet implementation, whose authors request the Yang and Zhang (2024) software citation. For AdamW, cite Loshchilov and Hutter (2019). Full BibTeX entries are in references.bib.

Component Author-year citation Primary citation/source
Transformer Vaswani et al. (2017) NeurIPS paper
RWKV-7 architecture Peng et al. (2025) RWKV-7 paper
RWKV-LM code and kernels Peng (2021), software v1.0.0 BlinkDL/RWKV-LM, official citation metadata and DOI
Gated Delta Networks Yang et al. (2025) GDN paper
FLA GatedDeltaNet implementation Yang & Zhang (2024), FLA 0.6.0 FLA repository and installation guide
AdamW Loshchilov & Hutter (2019) ICLR paper
Muon optimizer Jordan et al. (2024) Original Muon description
Muon large-model scaling Liu et al. (2025) Muon is Scalable for LLM Training
PyTorch Muon implementation PyTorch 2.14.1 Official torch.optim.Muon documentation

The reported context-512 experiment runs cover Transformer, Muon, GDN, and RWKV-7. The PCFG stream is generated by this project and is not an externally sourced dataset.

Downloads last month
-
Inference Providers NEW
This model isn't deployed by any Inference Provider. 🙋 Ask for provider support

Papers for Ilikemechuri/large_batch_scaling