Skip to content

Opt-in speedups for shared components: dense_full 1.99x on 8 GPUs - #26

Merged
Selen-Suyue merged 7 commits into
Interactive-Active-AI:mainfrom
henry-y:speedups/shared-components
Nov 6, 2026
Merged

Selen-Suyue merged 7 commits into
Interactive-Active-AI:mainfrom
henry-y:speedups/shared-components

Conversation

@henry-y

@henry-y henry-y commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

Optimized with ResearchBoost-Agent (RBA).

What this changes

This adds --speedups, an opt-in flag that runs the components every architecture shares through fused kernels, and removes one host synchronization from the training loop. On dense_full with the real trainer on our device:

dense_full, ms/update 8 GPUs speedup 4 GPUs speedup peak memory, 8 GPUs
default (main) 1375 1.00× 2698 1.00× 75.0 GB
--speedups exact 851 1.62× 1636 1.65× 63.1 GB
--speedups all 690 1.99× 1342 2.01× 60.9 GB

Reference and optimized runs alternate; the three 8-GPU reference runs measured 1373.4, 1375.8 and 1374.9 ms. Each number is a median after warmup, over 30 updates on 8 GPUs and 14 on 4 GPUs, at micro batch 16.

  • exact is bit-identical to the default path on the deterministic path: parameters, optimizer state and the data cursor match.
  • all adds cudnn and merge. They compute the same function with other rounding, so the run is not comparable bit for bit. Over 300 updates its loss stays within what two default-path runs differ by.

Without the flag, nothing changes except the host synchronization below, which keeps the same value. nexttransformer/models/ and nanochat/ are untouched: the patches apply at run time, so published proofs and fingerprints stay valid.

Why this is a draft: it adds code under nexttransformer/runtime/ and edits nexttransformer/train.py, both contract paths, and CONTRIBUTING asks for an issue first. We have not opened one yet and are happy to move the discussion there. We would like your view on whether this belongs in the repository, and on whether exact could be allowed in formal runs. Until then we suggest treating it as a research-mode option.

Starting point

The work began by asking which optimizations of Faster-NanoChat transfer here. Its retained changes hook FP8 and Inductor-generated code, while NextTransformer is BF16 and eager, so its patches do not apply; its row-packing idea does, and that was the largest single gain. The rest came from profiling dense_full, where GEMM took only 28% of GPU time, elementwise work and RMSNorm 45%, and attention 18%. Most of that overhead sits in the shell shared by all methods.

What each part does

Name Replaces How Bit-identical
norm F.rms_norm Several rows per program. QK-norm rows are only 128 wide, and ATen gives each a block of its own yes
attention norm(apply_rotary_emb(z))*1.2, v+gate*e, the input gradient of the projections RoPE, QK-norm and scale in one kernel; the value gate fused; the path gradients added in one kernel, which also removes the full-size fill and add of the gate's slice backward yes
mlp F.relu(h).square() One pass in each direction yes
residual a*x+b*x0 One kernel yes
readout 15*tanh(x/15) and cross entropy One pass over the BF16 logits in ATen's reduction order, storing row statistics only; backward recomputes yes
embedding dense nn.Embedding gradients One sort per batch shared by all tables, then ATen's grouped summation yes
data row packing A background thread packs into pinned memory; checkpoints record the consumed position yes
weights weight.to(bf16) Once per update instead of once per micro batch. Each use keeps its own autograd node, so looped methods still accumulate in FP32 yes
addnorm x+attn(...) with the next norm, the residual mix with the first norm One kernel each; backward adds the residual gradients and accumulates the gradient of x0 in place yes
cudnn SDPA backend order Prefers cuDNN SDPA where FlashAttention-3 is unavailable; off with --deterministic-attention no
merge several rounding points Projection gradients add inside the GEMMs, residual scalar gradients sum inside the kernel, RoPE rounds once, weight gradients leave the GEMM in FP32, the MLP residual is written over its input no

Measured effect

First round, 8 GPUs, cumulative ms/update, 14 updates per step:

base data attention norm mlp residual readout embedding cudnn
1354 1333 1090 1082 1034 987 938 914 782

Second round, 1 GPU running 4 micro batches with cudnn on, starting from the first round plus the one-pass cross entropy:

Change ms/update
weights, addnorm 753 → 740
Hardware rounding instruction, faster gradient widening, projection gradient sum 740 → 718
In-place x0 gradient, gate gradient sum in the kernel, cross entropy tiling 718 → 702
merge, on one GPU, alternating 693 → 673

The change on the default path

The training loop copied a constant from the host once per micro batch, and that copy drained the GPU queue:

- torch.tensor(float(x.numel()), device=device, dtype=torch.float64)
+ x.new_full((), x.numel(), dtype=torch.float64)

The value is the same. It saves 4 ms per micro batch for every method, with or without --speedups.

How bit identity is kept

Fused kernels keep every rounding point of the eager sequence and reproduce ATen's reduction order in Triton: RMSNorm (128 threads, vectors of 4, shuffle-down tree, (w0+w2)+(w1+w3)), log_softmax at width 32768 (1024 threads, 8 rounds of 4 elements, two shuffle-down levels), the BF16 sum over 128 (32 lanes of 4 strided elements, then adjacent pairs), embedding gradients (stable sort, groups of 10 rows in FP32), and path gradients in the order autograd receives them.

Traps worth knowing when maintaining this: Triton folds .to(bf16).to(f32) away, so rounding goes through an inline cvt.rn.bf16.f32; ATen does not contract x*rstd*stat into an FMA, hence libdevice.mul_rn; libdevice tanh flushes subnormals, hence a guard for tiny inputs; and NSA's branch_gate also reads x, so NSA stays off the fused projection path.

install refuses to start on another torch version, or if any of the 13 patched functions no longer has the reviewed source hash, so an upstream change cannot silently diverge. Every fast path falls back to the original code outside CUDA BF16 with the expected layout.

Results per method

All 33 methods run with all. Single GPU, micro batch 16 (2 for gla and deltanet), which excludes the gains from data and the host synchronization, so dense_full is below its trainer number.

All methods
Method default, ms all, ms speedup
ouro 954 460 2.07×
fixed_recursive 986 489 2.02×
dense 1001 500 2.00×
ut_act 1007 508 1.98×
huginn 931 483 1.93×
deeploop 957 503 1.90×
dense_full 670 362 1.85×
mha_no_ve 639 352 1.82×
residual_standard 624 353 1.77×
attnres 915 617 1.48×
mla_nope 547 370 1.48×
moba_hybrid 957 660 1.45×
gdn_hybrid_swa 701 490 1.43×
moba 994 699 1.42×
seer 1165 891 1.31×
gdn_hybrid 767 596 1.29×
deltanet_hybrid 754 594 1.27×
qsa 1317 1041 1.27×
retnet 649 519 1.25×
hc 1711 1398 1.22×
qsa_hybrid 941 776 1.21×
kda_hybrid 833 693 1.20×
dsa 1555 1294 1.20×
mhc 1813 1516 1.20×
gdn 767 648 1.18×
kda 939 799 1.18×
nsa 1811 1542 1.17×
kda_no_ve 905 779 1.16×
elu_norm 1002 874 1.15×
elu_qknorm 1079 950 1.14×
elu_linear 1127 998 1.13×
gla 20752 20618 1.01×
deltanet 40275 41291 0.98×

The gain follows the share of the shared shell and softmax attention. gla and deltanet use the reference backend, a per-token Python loop these changes do not reach; repeated runs show about 1.00×, with roughly 10% noise between processes.

Verification

Bit comparisons use --deterministic-attention, because SDPA flash differs between two runs of the same code.

Check Scope Result
Bit identity, 1 GPU exact, all 33 methods, 6 updates, reference run twice identical parameters
Bit identity, 4 GPUs, real trainer dense_full, 30 updates all events identical; of about 9.5M checkpoint entries only 2 timing fields and 2 source hashes differ
Bit identity, 4 GPUs, real trainer gdn, moba_hybrid, deeploop, mhc, ouro, mla_nope, residual_standard, attnres, 6 updates same
Resume 6+6 updates against 12, exact and all all shared events identical; model and optimizer state identical
GPU tests tests/test_speedups.py 41 passed, including tanh on every BF16 value and whole-layer gradients
Repository pytest -n 16, checks.golden, protocol.fingerprint, checks.public, checks.changes 605 passed, 103 skipped on CPU; all methods bitwise identical; proofs match; no public findings; contract paths flagged as expected

Numerics of all, dense_full, 4 GPUs, 300 updates, each configuration run twice:

Configuration mean loss, last 50 updates validation bpb
exact, first run 3.18369 0.99202
exact, second run 3.18375 0.99223
all, first run 3.18339 0.99131
all, second run 3.18432 0.99339

Mean absolute loss difference over updates 200 to 300: 0.0054 between the two exact runs, and 0.0053 and 0.0060 between exact and all.

Reproduce

nexttransformer/checks/speedups.py is the entry point for maintenance. Arguments it does not know go to the trainer.

git worktree add ../main origin/main
python -m nexttransformer.checks.speedups tests                         # GPU tests
python -m nexttransformer.checks.speedups timing --base ../main --gpus 8    # alternating timing
python -m nexttransformer.checks.speedups bits --base ../main --gpus 8      # bit identity, one method per family
python -m nexttransformer.checks.speedups resume --gpus 8               # interrupted equals continuous
python -m nexttransformer.checks.speedups numerics --gpus 8             # all against run-to-run noise

After changing a patched function, review its patch, update its hash in REVIEWED, and run tests and bits.

We ran all five commands at reduced update counts, resume on 2 GPUs and the others on 4. The numbers in this description come from equivalent runs at full length.

Limits

  • All numbers come from our device. Other GPUs are untested. Where FlashAttention-3 is in use, cudnn has no effect.
  • The final code was bit-compared on 1 and 4 GPUs. The 8-GPU bit comparison was run on the first-round code only; the 8-GPU numbers above are timing.
  • Runs are bounded, 300 updates at most, on a public data subset with a locally trained tokenizer, so absolute losses are not comparable with published runs. No full training run was made.
  • The numerics of all were compared on dense_full only.
  • The kernels are verified against torch 2.9.1, whose reduction order they pin.

Tried and not kept

  • Micro batch 32 speeds up the reference as much: 1.87× becomes 1.86×.
  • Concurrent dX and dW on two streams is slower: GEMMs already fill the device.
  • A non-in-place addmm for the residual: cuBLAS copies C first, which cancels the gain.
  • Approximate tanh and exp in the loss: no measurable change, so the exact version stays.
  • A shorter GIL switch interval for the packing thread: the data metric falls, the step time does not.
  • Larger DDP buckets: within noise on 2 GPUs, and one 8-GPU comparison of 690 → 687 ms is not enough to adopt it.

Checklist

  • The training contract is unchanged: data, tokenizer, token budget, batch, schedule, seed and evaluation points.
  • Result: not applicable.
  • New method: not applicable.
  • Shared code: agreed in an issue first; python -m nexttransformer.checks.golden --base origin/main reports no difference, or this pull request explains why one is expected. Golden reports no difference; the issue is still open, see above.
  • python -m pytest -q -n auto passes locally.

AI assistance

  • An AI agent prepared or substantially wrote this pull request. Agent and model: Claude Code, Claude Opus 5.5.

🤖 Generated with Claude Code

henry-y and others added 3 commits November 6, 2026 11:15
The training loop copied the token count from the host in every micro
batch. A copy from pageable memory synchronizes, so the GPU went idle
until the host had enqueued the next forward. Filling the value on the
device keeps it identical and saves 4 ms per micro batch for every method.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Fused kernels for the shell around the mixer, the loss and the data path,
applied at run time so shared model files, proofs and fingerprints stay
as they are. `exact` is bit-identical to the default path; `all` adds
cuDNN SDPA and `merge`, which change rounding only. install() refuses a
torch version or a patched function it was not reviewed against.

dense_full on the real trainer, 8 GPUs: 1375 ms/update by default, 851 ms
with `exact` (1.62x), 690 ms with `all` (1.99x).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
python -m nexttransformer.checks.speedups runs the GPU tests, alternating
timing, bit identity across the architecture families, resume and the
numerics of `all` on the real trainer, so a maintainer can check them
after changing a patched function.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@github-actions github-actions Bot added the contract Changes the training contract; agree in an issue first label Nov 6, 2026
@henry-y
henry-y marked this pull request as ready for review November 6, 2026 03:31
Selen-Suyue and others added 4 commits November 6, 2026 16:26
…ction

--speedups stays off by default. With --formal the trainer accepts only `exact`
or a selection of its parts, which reproduce the default path bit for bit, and
refuses `all`, `cudnn` and `merge`. A resumed segment must use the checkpoint's
selection in both directions, the audit rejects formal segments outside `exact`,
and the exported result records the selection as proof.speedups; records of runs
without speedups are unchanged. The protocol overview states the rule.

Co-authored-by: Cursor <cursoragent@cursor.com>
The fused readout leaves logits uncapped for the patched shared loss. A model
class that overrides _token_loss, as a plugin may, received those uncapped
logits and computed a different loss without an error. Such a class now keeps
the original readout; a GPU test checks that its loss is unchanged.

Co-authored-by: Cursor <cursoragent@cursor.com>
…wed sources

Two checkouts at different commits record different software/git_commit, which
`checks.speedups bits` reported as a difference. The fast tests now warn, without
failing, when a patched function no longer has its reviewed source.

Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
@Selen-Suyue Selen-Suyue added the core-approved Maintainers agreed to this contract change label Nov 6, 2026
@Selen-Suyue Selen-Suyue closed this Nov 6, 2026
@Selen-Suyue Selen-Suyue reopened this Nov 6, 2026
@Selen-Suyue
Selen-Suyue merged commit 5943c54 into Interactive-Active-AI:main Nov 6, 2026
10 of 11 checks passed
@Selen-Suyue

Copy link
Copy Markdown
Member

Merged in 5943c54. Thank you, @henry-y, and thanks to the ResearchBoost-Agent team: this speeds up every method that runs on the shared trainer.

Before merging we added four maintainer commits on top of yours; #27 has the full review and our measurements. In short:

  • --speedups stays off by default. Formal runs accept exact (or a selection of its parts), since it reproduces the default path bit for bit; all, cudnn and merge remain research only. The selection is part of a segment's identity, the audit checks it, and exported results record it as proof.speedups.
  • Resume now compares the selection in both directions.
  • A model class that overrides _token_loss keeps the original readout; it previously received the uncapped logits.
  • checks.speedups bits ignores software/git_commit, which differs between two checkouts.

On our node of eight 80 GB Ampere-generation GPUs, exact trains dense_full 1.38× faster with 12 GiB less peak memory, and nine methods stayed bitwise identical to main on 8 GPUs. cuDNN attention is slower than SDPA flash there, so all came out slightly behind exact.

We also added ResearchBoost-Agent to "Built on NextTransformer" in our README and documentation (#28). We would be glad to see NextTransformer among RBA's results too, for example a Faster-NextTransformer entry next to Faster-NanoChat on the project page. If you publish one, a line in its README saying it builds on NextTransformer keeps the listing in line with our community rule, and we will point the card to it.

The kernels pin torch 2.9.1 and 13 shared functions; when either changes, --speedups refuses to start until the patches are reviewed, and we may ping you then.

yitianlian pushed a commit to yitianlian/NextTransformer that referenced this pull request Nov 6, 2026
ResearchBoost-Agent by AI4AI for Anything contributed the opt-in --speedups (Interactive-Active-AI#26). Its card sits next to NextTransformer-V in the README, its Chinese translation and the community page; the invitation for further projects now spans the row below.

Co-authored-by: Cursor <cursoragent@cursor.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

contract Changes the training contract; agree in an issue first core-approved Maintainers agreed to this contract change

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants