Qwen4-Max 1.57×

Harness: Qwen Code · switches: YOCO_PIPELINE_CAST=1 YOCO_FUSED_NORM=1 YOCO_FUSED_GRAD_SCALE=1 YOCO_GRAD_SCALE_MT=1 YOCO_DDP_BUCKET_VIEW=1 YOCO_DDP_BUCKET_MB=100 YOCO_FUSED_ADAM=1 YOCO_FUSED_GATE_SCALE=1 YOCO_FUSED_CE=1 YOCO_CAST_DOWN_MT=1 YOCO_SKIP_GRAD_ZERO=1 YOCO_MP_IDENTITY=1 YOCO_FUSED_NORM_DW=1 YOCO_GATE_SCALE_STRIDE=1 YOCO_BCAST_BF16=1 YOCO_BCAST_BF16_VIEW=1 YOCO_BCAST_FLAT_MT=1 YOCO_GRAD_SCALE_LOCAL=1 YOCO_GRAD_NORM_LOCAL=1 YOCO_GRAD_FLAT=1

Judged
1.57×
Tier
N1
Self-best
1.58×
Rounds
32
Hours
10.0
API cost
$17.1
Input tokens · 95.0% cached
96 M
Output tokens
0.7 M
Requests
755
Cross-GPU exchange via CUDA IPC + copy engine (no SMs)
✗ still NCCL; CUDA IPC / copy engine never tried in the log. Round 3: the trace showed OSS's two fp32 shard broadcasts serialized on one communicator (18.4 + 18.6 ms); gave each broadcast its own communicator and dropped torch.cuda.synchronize so they run concurrently (~19 ms together), timed 1.0777×, quick check N0 (9616/9616 bitwise); round 26 casts first and broadcasts bf16 shards (YOCO_BCAST_BF16, half the wire volume), full check 1.4476× → 1.4575×; round 27 aliases the bf16 model params into the broadcast buffers (YOCO_BCAST_BF16_VIEW), paired 1.4665× → 1.5185×, full check 1.5004×. Grad all-reduce stays DDP + NCCL; NCCL Simple / LL128 / NVLS / BUFFSIZE gave nothing
Forward / backward CUDA graph
✗ no CUDA graph in the log. Round 1 already measured many launch-bound gaps (33.7 ms GPU idle per step in the instrumented profile, ~1300 small 50–400 µs gaps); it went for regional torch.compile instead: round 2 whole-layer compile errored twice (DDPOptimizer can't handle the higher-order op; Inductor failed inlining the custom Triton kernels), compiling RMSNorm alone 0.9935×; round 13 retried with the custom Functions marked allow_in_graph, still hit AOTAutograd's "input mutated during backward" assertion; dropped
Newer cuBLAS
✗ no library swap: the judge's record shows candidate library versions identical to the reference (torch 2.3.1+cu121). Round 1 noted GEMMs already at ~640 TFLOP/s (~65% of peak), "little room"; rounds 23 and 26 again judged the sm90 GEMMs cuBLAS-optimal and looked no further
Retention / attention kernel swap
partial: only retention's gate scaling. Round 14 YOCO_FUSED_GATE_SCALE fuses the exp gate scaling of q / v in cross_chunk (~8 elementwise kernels) into one Triton kernel, timed 1.3375× → 1.3406× (within noise), full check 1.3445×; strided reads added in round 15 were noise and reverted, a re-test in round 24 paid off (YOCO_GATE_SCALE_STRIDE, paired 1.4331× → 1.4429×, full check 1.4476×). Recurrence kernel, bmms and attention (flash-attn 2.6.3) not swapped; round 25 put the ceiling of a flash-style retention or an sm90 bmm at only 0.1–0.3 ms
Other main levers
round 4 Triton RMSNorm fwd + bwd, timed 1.0777× → 1.144× (N1); round 6 local-shard fp32→bf16 cast pipelined with the broadcast, full check 1.1605×; round 7 norm taken directly on bf16 grads (bitwise equal to the fp32 norm) and scaled fp32 master grads written in one pass, 1.2159×, round 8 as one multi-tensor Triton kernel, 1.2694×; round 9 DDP gradient_as_bucket_view + 100 MB buckets, 1.3113×; round 11 multi-tensor Triton AdamW, 1.3375×; round 17 fused cross-entropy 1.3522×; round 18 multi-tensor fp32→bf16 cast 1.3966×; rounds 19–22 skip fp32 master-grad zeroing, drop mp=1 identity autograd nodes, RMSNorm dw side output, to 1.436×; round 29 fp32 master grads written only for this rank's shard (YOCO_GRAD_SCALE_LOCAL) 1.5699×; rounds 30–31 local-shard norm + all_reduce, flat fp32 master-grad buffer, to 1.5837× (all full checks except round 4)
Raw work log33 sections
0.0 hRound 1 — profile reference + foreach-copy probe (20:30–20:39)
Profile (/tmp/r1/profile, instrumented 0.295 s/upd; real reference 0.2344 s/upd):
Per-update kernel time ~236 ms. Categories: nccl 67.6 ms (Broadcast_RING_LL 37.6 ms = OSS fp32 param
sync refresh_trainable; AllReduce_Sum_bf16 30 ms = DDP grads, overlapped in backward), gemm 61 ms,
memcpy/cast 42.8 ms, elementwise 29.5 ms, optimizer multi_tensor 18 ms (FusedAdam 14 + L2norm 4),
flash-attn 6 ms, reduce 3.7 ms, triton 2.6 ms, jiterator swiglu 2.2 ms, loss 1.8 ms. GPU busy 71% (29% idle).
GEMM already ~640 TFLOP/s (bf16 tensor cores, ~65% of Hopper peak) — little room there.

Key structural facts (fairseq + fairscale OSS, bf16 => per-param fp32 masters, flatten=False):
- update = DDP bf16 grad allreduce (backward) -> per-param bf16->fp32 grad copy -> OSS clip (shard norm +
  allreduce) -> FusedAdam on local fp32 shard -> OSS broadcast fp32 shards (13.6 GB, exposed) ->
  per-param fp32->bf16 copy. Adapter reads fp32 masters AND grads of ALL params on EVERY rank (chunked
  view), so allreduce-all-grads + broadcast-all-fp32-masters is REQUIRED; reduce-scatter / bf16 broadcast
  would change recorded values => INCORRECT. Communication pattern is fixed; only protocol/overlap tunable.
- Sync points: _check_grad_norms (allreduce), if not torch.isfinite(grad_norm).all() (D2H), OSS
  torch.cuda.synchronize() before broadcast, logging allreduce.

Change tried: YOCO_FOREACH_SYNC=1 — batch the ~520 per-param bf16<->fp32 copies with torch._foreach_copy_
(verified bitwise-equal cross-dtype => N0). Code in yoco/_opt.py, imported from models/yoco.py.
- time /tmp/r1/time_foreach: speedup 0.9986 (NO GAIN), 0.2344 s/upd. Copies were already hidden
  behind nccl/gemm; launch-overhead reduction does not help. Switch left OFF.
- Lesson: target EXPOSED time (broadcast, syncs, GPU idle), not overlapped copy launches.

Fast-path inventory: apex FusedAdam (active), flash_attn 2.6.3 (active), Triton rotary + chunk recurrence
(active), jiterator swiglu (active), inner_chunk @torch.compile (active). RMSNorm is naive eager (6 kernels
each, ~66 calls/fwd) — fusion candidate. OSS broadcast uses RING_LL protocol (suspicious for 6.8 GB).

NCCL probe: NCCL_PROTO=Simple (/tmp/r1/time_nccl_simple): speedup 0.9977 (NO GAIN). Broadcast not
protocol-limited; nccl mostly overlapped. Switch OFF.

Trace gap analysis (/tmp/r1/profile trace): GPU idle 168 ms/5 = 33.7 ms/upd (instrumented). ~13 big ~2 ms
gaps inside backward (BmmBackward0, aten::to/copy_ => host syncs); the rest is ~1300 small 50–400 µs gaps
between eager elementwise kernels => launch-bound. Conclusion: target the model's eager elementwise /
reduction chains (RMSNorm, residual adds, retention masks) via fusion / regional torch.compile, not the
overlapped copies or nccl protocol.
0.2 hRound 2 — regional torch.compile of DecoderLayer.forward (start ~20:43)
Hypothesis: fusing the eager elementwise/norm chains between the custom autograd Functions (rotary, swiglu,
chunk recurrence, flash_attn) cuts kernel count and the launch-bound idle. N1 (Inductor reorders reductions).
Switch YOCO_COMPILE_LAYER=1.

Results (all NO GAIN / ERROR):
- YOCO_COMPILE_LAYER=1 (/tmp/r2/time_compile): ERROR — DDPOptimizer "higher order op" (nested compiled
  inner_chunk). With torch._dynamo.config.optimize_ddp=False (/tmp/r2/time_compile2): ERROR — Inductor
  tries to inline the custom Triton _fwd_recurrence kernel: NameError: Optional, tt.reduce. Whole-layer
  compile fights the custom Triton kernels. Abandoned.
- YOCO_COMPILE_NORM=1 (/tmp/r2/time_norm): 0.9935 (NO GAIN, slightly slower). Norm fusion does not
  help => norms are NOT on the critical path (overlapped). Dynamo guard overhead per call.

Trace timeline evidence (decisive): the optimizer-phase tail is fully EXPOSED on the NCCL stream (stream 18,
zero overlap with compute stream 7): Adam finishes -> broadcast0 18.4 ms -> broadcast1 18.6 ms run
SERIALIZED (mutual overlap 0; NCCL orders collectives on one communicator) -> fp32->bf16 cast ~10 ms.
Total ~47 ms/update exposed. THIS is the critical-path overhead to attack (not the overlapped copies/norms).
0.4 hRound 3 — overlap the two OSS rank-broadcasts (start ~20:53)
Idea: OSS._broadcast_params issues 2 broadcasts (one per rank's fp32 shard) on the SAME communicator =>
serialized 37 ms. Use a distinct process group per broadcast so they overlap full-duplex NVLink (~19 ms),
and drop the redundant torch.cuda.synchronize (ProcessGroupNCCL already orders NCCL after the compute
stream via events). Exact data movement => N0 (fp32 masters identical on all ranks, adapter satisfied).
Switch YOCO_OVERLAP_BCAST=1.

Result: time /tmp/r3/time_bcast: speedup 1.0777 (0.2172 s/upd), beyond_reference_noise=true.
check --quick /tmp/r3/quick: PASS, N0, bitwise 9616/9616, precision_changed=false. Committed 047a06e.
First real gain. The serialized-broadcast insight was the key; copies/norms/nccl-protocol were red herrings
(overlapped). Next: profile the candidate to find the new exposed tail (param cast after broadcast, grad cast).
0.7 hRound 4 — fused Triton RMSNorm (start ~21:04)
Profile of broadcast-overlap candidate (/tmp/r4/profile): broadcasts now fully overlap (mutual overlap
18.6 ms; pair takes ~19 ms not 37). Remaining exposed tail: fp32->bf16 param cast (bandwidth-bound) and the
model's serial eager RMSNorm chains. compile-norm had failed to fuse (Dynamo fallback); hand-written Triton
fused RMSNorm (register-resident, fwd+bwd) is justified (L4). Norms ~13 ms serial on critical path.
- Kernel yoco/_rmsnorm_kernel.py; patch YOCO_FUSED_NORM=1. Correctness probe: fwd relL2 ~1e-5,
  dx relL2 ~2.8e-3 (~1 bf16 ulp), dw relL2 ~6e-5 — far below the trajectory seed perturbation (2^-6=1.5%).
- time /tmp/r4/time_norm (broadcast overlap + fused norm): speedup 1.144 (0.2046 s/upd), beyond noise.
  Fused norm added ~6.6% over broadcast overlap alone. Committed 2e32c92. N1 => needs gate 3.
- Full check launched to validate gate 3 (see below).
1.3 hRound 5 — profile fused-norm candidate + foreach re-probe (21:18–21:24)
Profile of broadcast-overlap+fused-norm candidate (/tmp/r5/profile, instrumented 0.2754 s/upd, GPU busy 66%):
nccl 365 ms (Broadcast 188 ms now overlapped per-communicator; AllReduce_bf16 176 ms overlapped in backward),
gemm 315 ms, memcpy/cast 172 ms, elementwise 124 ms, optimizer multi_tensor 90 ms (Adam 70.6 + L2norm 19.9).
Exposed optimizer tail: phase:clip-grads 52 ms/5 = 10.4 ms/upd (bf16->fp32 grad cast + L2norm);
phase:optimizer 246 ms/4 (FusedAdam 14 ms/upd sharded bandwidth-bound + broadcast + param cast).
phase:multiply-grads ~0.01 ms => the clip scale is a NO-OP most updates (grad_norm<2 => clip_coef=1), so
folding scale into FusedAdam.step(scale=) has little to gain AND wrong direction semantics => abandoned.
GPU idle 34% => launch-bound gaps; aten::is_nonzero 12/upd are D2H syncs.
- YOCO_FOREACH_SYNC=1 stacked on the base (/tmp/r5/time_foreach): 1.1319 (WORSE than 1.144 base).
  Copies are bandwidth-bound, not launch-bound; batching launches adds overhead. Switch left OFF.
1.3 hRound 6 — pipeline fp32->bf16 weight cast with the broadcast (21:25–21:45)
Idea: the local rank's fp32 shard is updated by its own FusedAdam BEFORE the broadcast; only the remote
shard arrives via broadcast. So cast the LOCAL shard's bf16 model weights on the compute stream WHILE the
broadcasts run on the NCCL stream, then cast the REMOTE shard after they complete. Same copies as upstream,
reordered => N0. Switch YOCO_PIPELINE_CAST=1 (subsumes YOCO_OVERLAP_BCAST). Code in _opt.py.
- First attempt /tmp/r6/time_pipe: ERROR — 'FairseqAdam' object has no attribute 'buckets'. The OSS
  instance is self.fp32_optimizer.optimizer (FairseqAdam wraps FairseqOSS), not self.fp32_optimizer.
  Fixed _ensure_cast_info/step/_sync to use getattr(self.fp32_optimizer,"optimizer",None) + guard.
- Fixed /tmp/r6/time_pipe2 (pipeline + fused norm): speedup 1.1576 (0.2022 s/upd), beyond noise.
  Up from 1.144x => pipeline-cast adds ~1.2% (overlaps the local param cast with the broadcast).
- check --quick pipeline ONLY (fused norm off, /tmp/r6/quick_pipe_only): **PASS, N0, bitwise 9616/9616,
  precision_changed=false** => pipeline-cast is bitwise-safe in isolation. Committed 3b78a23.
- check --quick combination (/tmp/r6/quick): PASS, N1 (the fused-norm component; 1270/9616 bitwise).
- Full check on the combination (/tmp/r6/check): PASS, speedup 1.1605, tier N1, gate-3 verdict
  "equivalent" (max endpoint bias 0.72σ at loss_u100_200; all 6 within 3σ). Pipeline-cast adds no trajectory
  perturbation (N0); biases are from the fused norm only.
1.6 hRound 7 — fuse grad cast + scale, norm bf16 grads directly (21:54–22:07)
Profile of pipeline-cast candidate (/tmp/r7/profile, instrumented 0.2662 s/upd, GPU busy 66%): exposed
optimizer prep = phase:clip-grads 53.9 ms/5 = 10.8 ms/upd (bf16->fp32 grad cast + apex L2norm 3.8 ms) PLUS
the grad scale mul BinaryFunctor<float> 60 ms/5 = 12 ms/upd (240 calls, in _unscale_grads, scales ALL
fp32 grads — required by adapter). Three full DRAM passes over grads: cast 18 GB + norm 12 GB + scale 24 GB.
Key probes (flock, correctness only): apex multi_tensor_l2norm on bf16 grads == norm of fp32 casts BITWISE
(reldiff 0.0, verified for 10- and 260-tensor lists); **bf16_grad * factor.reshape(1) -> fp32** rounds exactly
like cast-then-mul (bitwise, incl. in-place torch.mul(..., out=fp32)). 0-dim factor stays bf16 (weak scalar
promotion) — must reshape to [1] for strong fp32 promotion.
Change YOCO_FUSED_GRAD_SCALE=1: patch FP16Optimizer.clip_grad_norm to norm the bf16 grads directly (apex,
bitwise-equal), compute the clip/sample factor, then write fp32 master grads in ONE fused cast+scale pass;
set _multiply_factor=1 so _unscale_grads is a no-op. Removes the separate cast + scale passes (~30 GB/upd). N0.
- time /tmp/r7/time_fgs (pipeline + fused norm + fused grad scale): speedup 1.2147 (0.1927 s/upd),
  beyond noise. Up from 1.1576x => fused-grad-scale adds ~5%. Committed 3b9b115.
- check --quick fused-grad-scale + pipeline (fused norm OFF, /tmp/r7/quick_fgs_n0): **PASS, N0, bitwise
  9616/9616, precision_changed=false** => bitwise-safe in isolation.
- Full check on the full combination (/tmp/r7/check): PASS, speedup 1.2159, tier N1, gate-3 verdict
  "equivalent" (max endpoint bias 1.26σ at loss_u100_200; all 6 within 3σ). Fused-grad-scale is N0 (bitwise);
  the bias vs round 6 (0.72σ) is run-to-run production-trajectory noise, not error accumulation.
2.1 hRound 8 — NCCL protocol probe (no gain) + multi-tensor cast+scale kernel (22:17–22:34)
Profile of 1.2159x best (/tmp/r8/profile, instrumented 0.2632 s/upd, GPU busy 63%): trace stream-overlap
analysis shows the fused cast+scale (BinaryFunctor<float>, 240 per-param launches) is 100% EXPOSED
(zero NCCL overlap), 13.3 ms/upd for ~18 GB => only ~1.2 TB/s (torch mixed-dtype mul is slow). Broadcasts
overlap on streams 18 & 22 (18.6 ms each, RING_LL); Adam also 100% exposed (14 ms, sharded bandwidth-bound).
- NCCL protocol probe (N0): NCCL_PROTO=LL128 /tmp/r8/time_ll128 1.1948 (WORSE); NCCL_PROTO=Simple
  /tmp/r8/time_simple 1.2159 (neutral). Broadcast NOT protocol-limited (confirms round 1). Default LL kept.
- Kernel microbench (/tmp/r8/kbench.py, single-op): per-param torch mul 15.2 ms vs per-param Triton 11.1 ms
  vs multi-tensor Triton 6.5 ms (2.8 TB/s), all bitwise. Triton 2.3 CAN dereference a loaded int64 pointer
  via .to(tl.pointer_type(...)) (multi-tensor apply pattern).
- Change YOCO_GRAD_SCALE_MT=1 (within fused grad scale): one multi-tensor Triton launch for all grads
  (block->tensor lookup table; structure cached by shape, pointer table rebuilt per call). N0 bitwise.
  time /tmp/r8/time_mt (all 4 switches): speedup 1.2652 (0.185 s/upd), beyond noise. Up from 1.2147x
  => multi-tensor adds ~4.2%. Committed 3b07f2c.
- check --quick MT + pipeline + fused grad scale (fused norm OFF, /tmp/r8/quick_mt_n0): **PASS, N0, bitwise
  9616/9616. Full check on all 4 (/tmp/r8/check): PASS, speedup 1.2694, tier N1**, gate-3 equivalent,
  max bias 0.165σ (MT is N0; the bias swing vs round 7's 1.26σ is run-to-run production-trajectory noise).
2.6 hRound 9 — DDP gradient bucketing (allreduce overlap) (22:44–23:03)
Profile of 1.2694x best (/tmp/r9/profile, instrumented 0.2521 s/upd): trace stream-overlap shows the DDP
grad AllReduce_bf16 is now 24% EXPOSED (65.6 ms/5 = 13.1 ms/upd) — as backward compute shrank, the
allreduce tail sticks out past it. Param cast (direct_copy) is 97% hidden (NOT a bottleneck). MT cast+scale
5.7 ms/upd 100% exposed. Broadcast ~21 ms/upd exposed.
For 2 DP ranks each reduced grad element is g0+g1 (commutative) => grad values bitwise independent of bucket
size/layout => bucket tuning is N0. Patch the constructed DDP module (args.bucket_cap_mb left at 25 so the
recorded parsed config matches): YOCO_DDP_BUCKET_VIEW (gradient_as_bucket_view) + YOCO_DDP_BUCKET_MB.
Sweep (time, all with the 4 prior switches): b10 1.2735, b50 1.2728, view(25) 1.2889, view10 1.2911,
view50 1.2961, view100 1.3091 (best, 0.1788 s/upd), view200 1.3047. gradient_as_bucket_view (no grad->bucket
copy) + 100MB buckets (fewer/larger allreduces) wins.
- check --quick view100 (fused norm OFF, /tmp/r9/quick_ddp_n0): PASS, N0, bitwise 9616/9616.
  Committed 8a4a65a. Full check on all 6 (/tmp/r9/check): PASS, speedup 1.3113, tier N1, gate-3
  equivalent, max bias 0.268σ.
2.8 hRound 10 — MT kernel tuning + Adam kernel probe (both no gain) (23:12–23:20)
Profile of 1.3113x best (/tmp/r10/profile, instrumented 0.2468 s/upd): exposed tail = broadcast 20.9 ms/upd
(near NVLink limit), Adam 14.1 ms (100% exposed, ~3 TB/s), MT cast+scale 5.68 ms, allreduce 7.2 ms (bucketing
cut it from 13.1), L2Norm 2.72 ms, param cast 0.93 ms (97% hidden). Compute kernel total 137 ms/upd.
- MT kernel BLOCK/warps sweep (/tmp/r10/mttune.py, single-op): current BLOCK=4096/warps=8 (6.39 ms) already
  optimal; 4096/16 = 6.36 ms (negligible), others worse. NO meaningful gain — keep current.
- Adam kernel probe (/tmp/r10/adambench.py): apex FusedAdam KERNEL ~3 TB/s (14 ms trace) vs naive Triton
  fused AdamW ~1.9 TB/s => apex already faster (multi-tensor, optimized). Custom Adam rewrite is a dead end
  (and would be risky N1). NOT pursued.
- NCCL internal tuning (N0): NCCL_NVLS_ENABLE=1 /tmp/r10/time_nvls 1.3011 (worse); NCCL_BUFFSIZE=16MB
  /tmp/r10/time_buff 1.3106 (neutral). Broadcast at practical NVLink limit; no gain. Defaults kept.
- Conclusion: safe levers exhausted. Remaining exposed (broadcast ~21 ms near NVLink limit, Adam 14 ms at
  apex roofline) are not improvable without forbidden precision/semantics changes or risky rewrites with no
  demonstrated kernel-level headroom.
3.3 hRound 11 — tuned multi-tensor Triton AdamW (expensive lever) (23:25–23:48)
Per directive to take expensive levers, re-attacked FusedAdam — round 10's "apex at ~3 TB/s roofline, dead
end" was WRONG (confounded microbench: opt.step() Python overhead + untuned flat kernel + a TB/s calc bug).
Profile of 1.3113x best (/tmp/r11/profile): Adam kernel multi_tensor_apply_kernel<AdamFunctor<float>>
70.6 ms/5 = 14.1 ms/upd. bf16 recipe steps fp32 shards via fairseq FusedAdamV2 (subclass of apex
FusedAdam); fp32 path calls apex multi_tensor_adam on [g,p,m,v].
- Proper kernel microbench (/tmp/r11/adam_bench.py, single-op, calling apex applier DIRECTLY to exclude
  Python overhead): apex 1.49 TB/s (25.96 ms on 1.384B elems) vs tuned multi-tensor Triton 4.21 TB/s
  (9.20 ms, BLOCK=1024/warps=8) => 2.82x kernel speedup. Sweep: 1024/8 best; larger BLOCK spills registers.
- Formula probe (/tmp/r11/formula_probe.py): apex uses denom=sqrt(v)/sqrt(1-b2^step)+eps, ss=lr/(1-b1^step),
  decoupled decay p*=1-lr*wd. Matching it gives relL2 p=2.96e-8 (fp32 rounding only). Integration test
  (/tmp/r11/integ_test.py): patched FusedAdamV2 vs apex, 8 steps, decay/no_decay groups => max relL2
  param 1.1e-7, state keys + group step preserved.
- Change YOCO_FUSED_ADAM=1: patch FusedAdamV2.step to one multi-tensor Triton launch/group (kernel
  yoco/_adam_kernel.py, reuses cast_scale block->tensor pattern; structure cached by shape, ptrs rebuilt
  per call). Feasibility pre-check falls back to apex for non-fp32/sparse grads or bias_correction off. N1.
- time /tmp/r11/time: 1.3262 (0.1765 s/upd), beyond noise. Full check /tmp/r11/check: **PASS,
  speedup 1.3375 (0.175 s/upd), tier N1**, gate-3 equivalent, max bias 0.703σ (loss_u050_100), peak 60.33 GiB.
  Committed 07ffa67. Up from 1.3113x => fused Adam adds ~2%.
- KEY LESSON: kernel-level 2.8x did NOT translate to 5% end-to-end — only ~2%. The 14.1 ms Adam kernel is
  MOSTLY OVERLAPPED in training (only ~3.6 ms exposed), so round 10's "100% exposed" was also wrong. The
  rewrite captures the exposed fraction. Re-profile + measure end-to-end; never trust category totals or a
  single microbench for the end-to-end ceiling.
3.5 hRound 12 — exposure re-analysis + cast_scale re-tune (no gain) (23:50–00:05)
Profile of 1.3375x best (/tmp/r12/profile, instrumented 0.2422 s/upd). Wrote a sweep-line exposure
analyzer (/tmp/r12/exposure.py) that decomposes GPU wall time into per-category EXPOSED (solely-running)
vs overlapped vs idle. Result (ms/upd exposed): gemm 43.5, copy_elem 21.2, other 11.7, broadcast 11.0,
allreduce 10.7, cast_scale 5.7, flash 3.7, l2norm 2.7, loss 1.8, swiglu 1.7, triton_rec 1.4, rmsnorm 1.4;
idle 62.8, overlapped 38.5. Adam now has ZERO exposed time (fully overlapped after the rewrite — the
_adam_mt kernel never runs alone). Optimizer tail is near-optimal: L2norm ~4.4 TB/s (near peak), broadcast
at NVLink limit, allreduce bucket-tuned. The remaining exposed overhead is model eager elementwise
(direct_copy unrolled 15.9 ms/upd = bf16<->fp32 casts; FillFunctor 4.4; AUnaryFunctor 4.6; residual add 2.5)
plus launch-bound idle. These need model rewrites / compile (round 2 whole-layer compile failed).
- cast_scale re-tune microbench (/tmp/r12/cs_bench.py, realistic 2.19B-elem full-grad shapes, 13.1 GB):
  current BLOCK=4096/warps=8 = 3.571 ms (3.68 TB/s, 77% peak); best alt 4096/16 = 3.563 ms (negligible).
  Confirms round 10: cast_scale already optimal. NO gain, no code change.
- Lesson: microbench absolute BW can mislead (apex Adam showed 1.49 TB/s on 100 separate tensors but ~3 TB/s
  in training's contiguous shard) — the 2.8x kernel ratio became only ~2% end-to-end. ALWAYS verify end-to-end.
3.6 hRound 13 — whole-layer compile with opaque custom kernels (ERROR, no gain) (00:00–00:02)
Expensive lever: retry regional torch.compile of DecoderLayer.forward, but mark the custom Triton autograd
Functions (ApplyRotaryEmb/SwiGLU/ChunkGateRecurrent/_FusedRMSNorm .apply + inner_chunk) allow_in_graph so
Inductor fuses only the eager ops BETWEEN them (round 2 failed because Inductor inlined the Triton kernels).
Patch YOCO_COMPILE_LAYER_OPAQUE (optimize_ddp=False, fullgraph=False, dynamic=False).
- time /tmp/r13/time: ERROR. torch 2.3 AOTAutograd still traces the custom Function backward into the
  Triton kernel wrap: Exception: Incorrect number of arguments passed to kernel (identify_mutated_tensors)
  and fatal `AssertionError: Found an input to the backward that was mutated during the backward pass. This
  is not supported` => BackendCompilerFailed => ChildFailedError. allow_in_graph does NOT stop AOTAutograd
  from tracing the backward in torch 2.3. Whole-layer compile is a confirmed dead end (rounds 2 + 13).
  Switch left OFF; patch kept gated (harmless). No code change committed.
3.9 hRound 14 — fused Triton gate-exp scaling for retention cross_chunk (00:05–00:20)
Expensive custom-kernel lever: cross_chunk scales q/v before its two bmms with ~8 eager elementwise kernels
(neg/add/exp/cast/mul for each). Fused both scalings into one multi-row Triton kernel (_gate_scale_kernel.py,
_GateScale autograd Function): v*=bf16(exp(g_last-g)), q*=bf16(exp(g)). Patch YOCO_FUSED_GATE_SCALE
replaces gr.cross_chunk (bmms + chunk recurrence unchanged).
- Standalone probe (/tmp/r14/cross_fuse.py): forward bitwise (qs 3.5e-10, vs 1.4e-8); grad_q/grad_v bitwise;
  grad_g initially 1e-2 — TWO bugs found & fixed: (1) exp-backward must use the UNROUNDED fp32 exp (cast
  backward is straight-through), (2) a race: tl.store(DG[last]) clobbered the atomic_add g_last accumulation
  => use atomic_add for the local dg too. After fixes grad_g relL2 2.6e-3 (bf16-rounding level, like fused norm).
- time /tmp/r14/time: 1.3406 (0.1746 s/upd) — marginal (+0.23% over 1.3375, within noise band 0.0128);
  the q/v .contiguous() copies offset most of the launch savings. Full check /tmp/r14/check: **PASS,
  speedup 1.3445 (0.1741 s/upd), tier N1**, gate-3 equivalent, max bias 1.189σ (loss_u100_200; margin to 3σ
  ample), peak 60.33 GiB. Committed 9f45e21. Small but verified gain; enabled.
- Lesson: a correct fused kernel still needs the backward rounding chain matched (fp32 exp derivative, bf16
  grad_scale) and atomic-safe accumulation; and end-to-end gain can be tiny when .contiguous() copies added.
4.0 hRound 15 — gate-scale stride support (no gain, reverted) (00:22–00:27)
Refinement of round 14: q/v entering cross_chunk are NON-contiguous (strides 3072,128,786432,3072,1 after the
head/len transpose), so the fused kernel's .contiguous() copied them. Added native 4D-stride reads (no copies;
math unchanged => identical numerics). Standalone (/tmp/r15/stride_test.py, non-contiguous q/v): fwd bitwise,
grad_q/grad_v bitwise, grad_g 1.9e-3.
- time /tmp/r15/time: 1.3452 (0.174 s/upd) vs committed 1.3445 (0.1741) => +0.05%, NOISE. The copies
  were already hidden by the GPU; the gate-scale ceiling is ~0.5% (scaling is tiny vs the bmms). Reverted to
  the simpler committed kernel (git checkout HEAD). No commit.
- Lesson: removing .contiguous() copies only helps if they are EXPOSED; here they overlapped. Confirm a
  refinement moves end-to-end time before keeping added complexity.
4.1 hRound 16 — DDP bucket re-sweep at new compute level (no gain) (00:28–00:31)
N0 lever: re-check the bucket optimum now that compute shrank (Adam faster + gate-scale fused). time with
the 8-switch best but YOCO_DDP_BUCKET_MB varied: b150 = 1.3414 (0.1745), b75 = 1.3375 (0.175) vs b100 =
1.3445 (0.1741). 100 MB still best; the optimum did not shift. NO gain, no change. Confirms round 9.
4.5 hRound 17 — fused Triton cross-entropy for the criterion (+1.0%, N1) (00:45–01:00)
Expensive custom-kernel lever. Re-profiled the best (/tmp/r17/profile, instrumented 0.2324 s/upd); the
kernel->op External-id correlation left most exposed eager copies as backward "<unknown>" (autograd-engine
launched), but the LOSS kernels showed log_softmax fwd+bwd and nll SEPARATELY. Read fairseq CrossEntropyCriterion:
get_normalized_probs = log_softmax(logits.float()) (fp32) then F.nll_loss — materializing BOTH an 820MB
fp32 logits cast AND an 820MB fp32 log_probs, re-read in backward. CE sits on the fwd-end/bwd-start critical path.
Wrote _ce_kernel.py (_FusedCE autograd Function): one program/row reads bf16 logits, fp32 ONLINE logsumexp
(max+sumexp loop over V=100277 in BLOCK_V=1024 chunks), loss_row = lse - logits[target] (0 for ignore_index),
loss = rowloss.sum(); backward grad_logits = (exp(logits-lse) - onehot)*grad_loss cast bf16, no fp32 intermediate.
Patch YOCO_FUSED_CE replaces CrossEntropyCriterion.compute_loss (reduce=True only; reduce=False falls back).
- Standalone (/tmp/r17/ce_bench.py, flock): loss rel 1.2e-7, grad relL2 2.3e-6 max 3e-5; fwd+bwd
  2.04 ms vs 7.62 ms ref (3.7x), fwd 0.66 vs 3.34 ms. Matches the log_softmax+nll backward algebra exactly
  (grad = softmax - onehot), only fp32 reduction order differs => N1.
- time --paired /tmp/r17/time_ce: 1.3585 (0.1723 s/upd) vs committed 1.3445 => +1.04%, beyond band.
  Full check /tmp/r17/check_ce: PASS, speedup 1.3522 (0.1731 s/upd), tier N1, precision_changed false,
  gate-3 equivalent, max bias 0.182σ (loss_u100_200; BETTER margin than prior 1.189σ), peak 59.0 GiB
  (was 60.33 — the avoided fp32 intermediates). Committed f996a1b; enabled (9 switches).
- Lesson: the criterion's fp32 log_softmax materialization was a hidden ~5ms critical-path cost split across
  copy/softmax/nll trace categories; fusing it (read bf16, fp32 registers) is the biggest single lever since the
  early rounds. A custom kernel can also IMPROVE gate-3 margin (fp32 online lse) and cut peak memory.
5.0 hRound 18 — fused fp32->bf16 OSS param-refresh cast (+2.0%, N0); norm-dw fusion no-gain (01:02–01:29)
Re-profiled best (/tmp/r18/profile, 0.2317 instrumented). FIXED the kernel->op correlation: the GPU-timestamp
containment failed (GPU timeline offset from CPU); the correct chain is kernel.correlation -> cuda_runtime
(cudaLaunchKernel) -> its CPU launch ts -> innermost enclosing cpu_op + ancestor autograd node on the same tid
(/tmp/r18/correlate3.py,correlate4.py). This resolved the backward "<unknown>": direct_copy 19ms (all
aten::copy_), AUnaryFunctor 2.4ms = DDP reducer::mul_out, and **8.38ms of per-param copy_ inside
Optimizer.step#FairseqOSS.step** (108 calls/upd, one ~308M-elem embedding copy 1.04ms).
- First tried fusing the fused-RMSNorm backward WEIGHT grad (dw was eager: x.float()*rstd->bf16->*dout->sum(0),
  ~6ms under _FusedRMSNormBackward). Added _rmsnorm_dw atomic column-reduction behind YOCO_FUSED_NORM_DW.
  Microbench (/tmp/r18/dw_bench.py): dx/dw N1 (dw relL2 8.7e-5) BUT fused-dw SLOWER (0.336 vs 0.316ms) — torch's
  optimized sum(0) beats the atomic kernel. NO gain => reverted (git checkout). Lesson: a fused reduction must
  beat torch's tree-reduce, not just remove launches.
- Then targeted the OSS cast: pipeline_cast casts local shard during broadcast (hidden) but remote shard AFTER
  wait() (exposed) via ~108 torch copy_ at ~2TB/s. Added _cast_down_mt multi-tensor fp32->bf16 kernel
  (_cast_scale_kernel.py, RNE => bitwise) + YOCO_CAST_DOWN_MT in pipeline_cast (cached block structure, ptrs
  rebuilt per call). Microbench (/tmp/r18/castdown_bench.py): bitwise identical, 1.52x (7.80 vs 11.81ms /
  1.78B elems). time --paired /tmp/r18/time_cast: 1.3858 (0.1689) vs 1.3585 => +2.0%. Full check
  /tmp/r18/check_cast: PASS 1.3966 (0.1676), tier N1 (CE), gate-3 equivalent max bias 0.569σ, peak 59.0 GiB,
  exact_failures 0. Committed f11c293; enabled (10 switches).
- Lesson: the correlation fix exposed the optimizer-phase cast as a big EXPOSED hotspot hidden across per-param
  copy_ launches; a bitwise multi-tensor cast (N0) gave +2%. Re-profile + correct trace linkage finds levers the
  raw kernel-category totals miss.
5.4 hRound 19 — skip redundant fp32 master-grad zero fills (+1.4%, N0) (01:30–01:50)
Re-profiled best (/tmp/r19/profile, 0.2261 instrumented, GPU busy 63%). The round-18 cast_down removed ~14ms
of direct_copy (OSS cast now one Triton kernel). Correlated remaining eager by phase (/tmp/r19/correlate5.py):
AccumulateGrad AUnaryFunctor 4.4ms (DDP reducer::mul_out), _FusedRMSNormBackward ~5.3ms (eager dw, torch-fast),
FillFunctor<float> 4.17ms/upd (307 calls) = the per-param fp32 master-grad zero_() in FP16Optimizer.zero_grad.
- Verified redundancy: fused_grad_scale's clip_grad_norm cast_scale writes EVERY trainable fp32 grad (creating a
  zero bf16 grad where missing) BEFORE Adam reads it in step(); zero_grad then zeroes those fp32 grads but they
  are never read before the next cast_scale overwrites them. The ~307 fp32 zero_() fills are pure waste. Patch
  YOCO_SKIP_GRAD_ZERO drops the fp32 zero loop (keeps bf16 p.grad=None + _needs_sync=False), guarded on
  fused_grad_scale + not flat + scaler None. N0 (grads read by Adam bitwise unchanged).
- time --paired /tmp/r19/time_zero: 1.405 (0.1666) vs 1.3858 => +1.4%, beyond band. Full check
  /tmp/r19/check_zero: PASS, tier N1, gate-3 equivalent max bias 0.167σ (dropped from 0.569σ — confirms
  bitwise-identical grads), peak 59.0 GiB, exact_failures 0. Check speedup 1.3933 vs prior 1.3966 is frozen-ref
  timing noise (paired time is the clean +1.4% signal). Committed ca5720e; enabled (11 switches).
- Lesson: a fused overwrite kernel can make a downstream zero/init pass redundant — trace the dataflow (write
  before read) to delete whole passes, not just speed them. Gate-3 bias DROPPING toward 0 is evidence of N0.
5.7 hRound 20 — bypass model-parallel identity autograd Functions at mp=1 (+0.6%, N0) (01:52–02:10)
From the round-19 correlation, _CopyToModelParallelRegionBackward elementwise ~0.98ms (79 calls). Read mpu
mappings.py: at mp=1 _reduce returns the input (identity), but _CopyTo/_ReduceFromModelParallelRegion are still
autograd Functions whose forward aliases input->output, so the engine copies the grad on fan-out (fc1+gate both
consume x). Patch YOCO_MP_IDENTITY replaces the megatron layers.py mapping globals (copy_to/reduce_from_model_
parallel_region, used by ColumnParallelLinear/RowParallelLinear in FFN+retention) with plain identity at mp=1
(call-time get_model_parallel_group world_size check, cached) — removes the nodes entirely. Bitwise N0.
- time --paired /tmp/r20/time_mp: 1.4135 (0.1656) vs 1.405 => +0.6% (paired 1.4227 vs 1.41). Small,
  near band, but a clean simplification. Full check /tmp/r20/check_mp: PASS 1.4135 (0.1656), tier N1,
  gate-3 equivalent max bias 1.214σ (within 3σ; seed-sample variation), peak 59.0 GiB, exact_failures 0. The check
  sample 1.4135 > prior 1.3966 confirms the gain. Committed 11d8323; enabled (12 switches).
- Lesson: identity autograd Functions still cost grad-aliasing copies on fan-out; bypassing them at mp=1 is a
  free N0 win. Check speedup samples vary (1.3933/1.3966/1.4135) — use paired time + multiple checks to confirm.
5.8 hRound 21 — NCCL_PROTO=Simple re-test at new exposure (no gain) (02:12–02:17)
N0 probe: the OSS broadcast still uses RING_LL (38.6ms total, ~11ms exposed). Round 8 found NCCL_PROTO=Simple
neutral, but exposure shifted after cast/zero/mp fusions, so re-tested. time --paired /tmp/r21/time_simple:
frozen 1.4212 (0.1647) but paired 1.422 vs prior 1.4227 => FLAT. The frozen-ref +0.55% is reference drift;
the paired comparison shows no gain. Confirms round 8: broadcast not protocol-limited (NVLink bandwidth/latency
bound). NO change (NCCL_PROTO not added to switches). Lesson: re-test env levers after exposure shifts, but trust
the PAIRED signal over frozen-ref drift.
6.1 hRound 22 — fuse RMSNorm weight-grad yb into the dx kernel (+1.6%, N0 vs eager) (02:18–02:33)
Retry of the round-18 norm-dw fusion (atomic reduction was SLOWER than torch sum). Better approach: the dx
kernel already computes x*rstd in fp32 registers, so emit yb = bf16(x*rstd) as a SIDE OUTPUT (WRITE_YB flag),
then dw = (doutc*yb).sum(0) via torch's fast mul+reduce. Removes the eager x.float() (fp32 materialization) +
rstd-mul + bf16-cast (3 kernels) while keeping torch's optimized sum. yb bitwise-matches the eager path => dw
UNCHANGED (N0 relative to eager; the norm overall stays N1 from dx). Patch YOCO_FUSED_NORM_DW (reused switch).
- Microbench (/tmp/r18/dw_bench.py): fused 0.277 vs eager 0.321 ms/norm (-14%); dw relL2 vs autograd 8.7e-5
  (same N1 baseline as eager; fused==eager bitwise). time --paired /tmp/r22/time_dw: 1.436 (0.163) vs
  1.4135 => +1.6% (-2.6ms, matches microbench). Full check /tmp/r22/check_dw: **PASS 1.436 (0.163),
  tier N1, gate-3 equivalent max bias 0.705σ, peak 59.0 GiB, exact_failures 0. Committed 2f1d080**; enabled
  (13 switches).
- Lesson: don't fuse a reduction with atomics (contention beats torch's tree-reduce); instead reuse a value the
  kernel ALREADY computes (x*rstd) as a side output and keep torch's fast reduction. A failed fusion (round 18)
  can succeed with a different decomposition.
6.2 hRound 23 — sweep-line exposure analysis + fused L2norm probe (no gain) (02:34–02:45)
Re-profiled best (/tmp/r23/profile, 0.2137 instrumented). Wrote a sweep-line exposure analyzer
(/tmp/r23/exposure.py): compute-stream kernel time minus overlap with the merged NCCL-stream intervals, per
category. EXPOSED ms/upd: gemm 42.8 (total 71.4), adam 11.4 (fully exposed, ~3.7 TB/s ≈ roofline), cast_scale 5.7
(roofline), elementwise 4.5, l2norm 2.74 (fully exposed, ~2.2 TB/s), cast_down 2.67 (remote half), copy 2.4,
swiglu 1.4, rotary 1.3, rmsnorm 1.2, gate_scale 1.0. Confirms adam/cast_scale are bandwidth-bound near peak; the
big GEMMs (sm90_xmma, 58ms) dominate and cuBLAS is near-optimal; retention cutlass_80 bmms only ~2.7ms total.
- Tried a Triton multi-tensor L2norm (per-block partial sums -> sum().sqrt(), no atomic contention) to beat apex
  multi_tensor_l2norm (chunk 65536). Microbench (/tmp/r23/l2_bench.py): norm rel diff 0.0 (bitwise for the
  probe) BUT speed 3.583 vs apex 3.748 ms — only ~4% faster. apex's kernel is already efficient; end-to-end gain
  ~0.1% (negligible), not worth the N1 reduction-order risk. Reverted (git checkout). NO change.
- Lesson: the exposure analyzer confirms most remaining compute is at the DRAM roofline (adam, cast_scale) or
  cuBLAS-optimal (gemm). apex L2norm is NOT a slow target despite ~2.2 TB/s in-trace (microbench shows it fast).
  Cheap levers are exhausted; remaining gains need expensive GEMM/bmm rewrites with modest ceilings.
6.6 hRound 24 — gate-scale native strided reads, re-test at new exposure (+0.7%, N1) (02:46–03:05)
- Hypothesis: round 15 found the gate-scale q/v .contiguous() copies overlapped (stride support +0.05% noise,
  reverted). Since then compute shrank ~15% (rounds 17–22), so the copies may now be EXPOSED. Round-23 exposure
  showed copy ~2.4 ms/upd exposed (gate_scale contiguous ~1.1 ms of it). Re-test the stride lever.
- Change (yoco/_gate_scale_kernel.py, switch YOCO_GATE_SCALE_STRIDE, off default): added _gate_scale_fwd_s
  / _gate_scale_bwd_s that decompose row -> (b,h,n,c) and read q/v at b*sq0+h*sq1+n*sq2+c*sq3 + cols (last-dim
  stride 1) instead of row*D. Outputs qs/vs/dq/dv allocated contiguous; forward skips q.contiguous()/v.contiguous()
  (g still contiguous, small). Backward dqs/dvs still .contiguous() (grads of contiguous outputs). Contiguous
  path retained when switch off or last-dim stride != 1.
- Numerics (flock microbench /tmp/r24/gate_bench.py, non-contig q/v strides (6291456,32768,786432,128,1)):
  qs/vs/dq/dv bitwise identical to contiguous path; dg relL2 2.9e-7 (atomic add ordering only — same N1 tier
  as the existing fused gate-scale). Kernel-only fwd+bwd 1.732 -> 1.627 ms (~6%, the strided copy was slow).
- Time: paired 1.4429 (prior best paired 1.4331, +0.69%); s/upd 0.163 -> 0.1619, paired reference stable
  ~0.2336 both runs => genuine candidate gain, not drift. Copies ARE now exposed (confirms the hypothesis).
- Full check /tmp/r24/check_stride: PASS, speedup 1.4476, 0.1617 s/upd, tier N1 (precision_changed false),
  gate-3 max bias 0.501σ (loss_u100_200; all 6 endpoints within), peak 59.0 GiB alloc / 60.01 reserved.
- Commit 9443034. Switch enabled in switches.json (14 active). NEW BEST 1.4476.
- Lesson: a lever that was overlapped at one compute level can become exposed after later gains shrink the
  surrounding compute — RE-TEST cheap levers periodically, don't permanently discard them on a single no-gain.
6.9 hRound 25 — re-profile best + hotspot triage (no change; levers blocked/modest) (03:06–03:35)
- Re-profiled 14-switch best (/tmp/r25/profile, exposure.py + breakdown.py + copysrc.py). Exposed ms/upd:
  gemm 42.6 (cuBLAS sm90 optimal; retention cutlass_80 subset ~2.7), adam 11.4 (3.7 TB/s ≈ 77% peak, 4-stream
  RMW roofline), cast_scale 5.7 (roofline), elementwise 4.43, l2norm 2.87 (apex fast), cast_down 2.67
  (remote half, roofline), copy 1.74 (down from 2.4 — round-24 stride win confirmed), swiglu 1.53,
  rmsnorm 1.34, gate_scale 1.17, rotary 1.15, inductor 0.82, reduce 0.64, ce 0.50.
- elementwise breakdown: AUnaryFunctor<bf16> 2.61 ms exposed (n=268) = DDP grad ×1/world_size applied
  under AccumulateGrad; CUDAFunctor_add<bf16> 1.40 ms (n=260) = grad accumulation into bucket views;
  BinaryFunctor<bf16> 0.21 ms (n=54) = residual adds.
- copy breakdown: ViewBackward0 1.14 ms (n≈50, 2/layer) + mixer forward aten::copy_ 0.74 ms (n=65) — both are
  the retention/attention **(B,H,L,D)->(B,L,H*D) transpose-reshapes** (o.transpose(1,2).reshape(...)), which
  are architectural layout changes (out_proj needs contiguous last dim) => unavoidable without arch change.
- DDP scale-fold analysis: ×1/world_size = ×0.5 is EXACT in bf16 (power of 2) and commutes with round-to-nearest
  addition, so folding it past the allreduce into cast_scale (with clip decided on norm_sum/2 and an exact ×0.5
  in the kernel before the factor mul) would be ~N0. BUT removing the division requires patching the torch 2.3
  C++ Reducer (mul_out / finalize_bucket_dense) — not reachable from Python. BLOCKED. The grad-accumulation adds
  are inherent to gradient_as_bucket_view (p.grad=bucket slice != None => AccumulateGrad adds, can't steal);
  disabling bucket_view loses the round-9 +3.5% overlap gain => net negative.
- rmsnorm dw=(doutc*yb).sum(0) (1.18 ms mul + 0.64 ms reduce): fusing mul+reduce needs replicating torch's
  tree-reduce order for bitwise; a custom column-reduction reorders the fp32 accumulation => N1, ~0.2 ms ceiling.
  Not worth the N1 risk vs the existing N0 dw. adam BLOCK/warps already tuned (rounds 10–11); 77% is realistic
  for the 4-stream read-modify-write pattern.
- Outcome: NO change (no tractable N0 lever above noise this round). Cheap levers confirmed exhausted; the next
  substantive lever is an expensive custom kernel (fused retention inner_chunk flash-style, or sm90 Triton bmm),
  both with modest (~0.1–0.3 ms) ceilings because retention is memory-bound on small (256×256×128) matrices.
7.2 hRound 26 — broadcast bf16 OSS shards instead of fp32 (+0.7%, N0; expensive lever) (03:20–03:42)
- Insight: OSS broadcasts each rank's fp32 master shard, then the remote rank casts fp32->bf16 into the model.
  Casting to bf16 BEFORE the broadcast halves the NVLink volume AND removes the remote fp32->bf16 cast. The
  fp32->bf16 rounding R is identical wherever it runs (owner casts its own shard), bf16 transfer is exact and
  bf16->bf16 copy is exact => model weights bitwise unchanged (N0). GEMM triage first confirmed sm90 GEMMs
  compute-optimal and retention cutlass_80 bmms already at DRAM roofline (~3.7 TB/s) — no GEMM lever left.
- Change (_opt.py pipeline_cast + _cast_scale_kernel.py, switch YOCO_BCAST_BF16, off default, world_size==2):
  allocate a bf16 flat buffer mirroring each rank's fp32 bucket.buffer; local flat cast fp32->bf16buf (compute
  stream, broadcast waits on it); broadcast bf16buf per rank/communicator; local bf16buf->ld and remote
  bf16buf->rd via a new _copy_bf16_mt multi-tensor kernel (offsets from fp32 view data_ptr deltas).
- Time: paired 1.4665 (prior 1.4429; part is reference drift +1.07%); frozen-ref 1.4539. Candidate s/upd
  0.1619 -> 0.1610 (paired) / 0.1606 (check) ≈ -0.6..0.7% (~0.9-1.1 ms). Gain limited because the local
  fp32->bf16 cast is newly EXPOSED (was overlapped with the fp32 broadcast), offsetting much of the wire saving.
- Full check /tmp/r26/check_bcast: PASS, speedup 1.4575, 0.1606 s/upd, tier N1 (cumulative from prior fused
  kernels; precision_changed false), gate-3 max bias 1.03σ (loss_u050_100, within 3σ; seed-sample variation).
  Peak 59.0 -> 65.4 GiB — the persistent bf16 broadcast buffers duplicate shard storage (+6.4 GiB).
- Commit b569bff. Switch enabled (15 active). NEW BEST 1.4575. Memory regression noted (not a scored gate).
- Next: alias the bf16 model params (ld/rd) as VIEWS into the bf16 broadcast buffers so the buffer IS the model
  storage — removes the local/remote bf16 copies (remote ~1.3 ms exposed) AND reclaims the +6.4 GiB. Requires
  preserving initial weights + checking DDP param-storage caching => round 27.
7.5 hRound 27 — alias bf16 model params into the broadcast buffers (+3.0%, N0) (03:43–03:59)
- Follow-up to round 26: instead of copying bf16buf->model after the cast/broadcast, point each bf16 model
  param's .data at its slice of the bf16 broadcast buffer (local shard params -> local buffer, remote ->
  remote buffer; offsets from the fp32 view data_ptr deltas, .view(p.shape)). The local fp32->bf16 flat cast
  and the incoming bf16 broadcast then update the model IN PLACE => both _copy_bf16_mt copies dropped.
  Switch YOCO_BCAST_BF16_VIEW (off default; requires YOCO_BCAST_BF16). Aliasing done once in _ensure_cast_info;
  the first step's cast/broadcast fills the buffers before the next forward reads them (no garbage read).
- Numerics: bitwise identical weights (same bf16 values, copy removed) => N0; gate-2 exact_failures [].
- Time: paired 1.5185 (prior 1.4665, +3.5%); frozen-ref 1.5189. Candidate s/upd 0.161 -> 0.1541 (paired)
  / 0.156 (check). Gain MUCH larger than the ~1.3 ms remote-copy removal alone => the forward GEMMs also benefit
  from reading weights out of flat contiguous bf16 storage (was ~260 separate allocations) — locality/TLB win.
- Full check /tmp/r27/check_view: PASS, speedup 1.5004, 0.156 s/upd, tier N1 (cumulative), gate-3 max bias
  1.188σ (within 3σ), exact_failures []. Peak still 65.4 GiB — the original param storage is still referenced
  elsewhere (autograd saved tensors / DDP), so aliasing did NOT reclaim it; the win is copies + locality.
- Commit 5b675fa. Switch enabled (16 active). NEW BEST 1.5004 (crossed 1.5×).
- Lesson: weight STORAGE LAYOUT (flat contiguous vs many small allocations) materially affects forward GEMM
  speed on Hopper, beyond the obvious copy removal. Opens a direction: audit other storage locality (grads, fp32
  master, optimizer state). Re-profile next round to see the new gemm/copy exposure.
7.9 hRound 28 — fast MT kernel for the bf16 broadcast flat cast (+1.7% check, N0) (04:00–04:23)
- Re-profiled 16-switch best (/tmp/r28/profile). Exposure shifted after the bf16 broadcast: nccl busy 66->54.7 ms
  (wire halved), cast_down MT category gone, copy jumped 1.74->6.56 ms exposed. Breakdown: the local
  fp32->bf16 shard cast bf16buf.copy_(lb.buffer) runs as torch unrolled_elementwise direct_copy at ~0.94 TB/s
  (~4.7 ms, optimizer phase) — torch's mixed-dtype .copy_ is ~5x slower than the cast_down MT kernel (~3.7 TB/s).
- Change (_opt.py, switch YOCO_BCAST_FLAT_MT, off default): cache a single-tensor pointer table + block
  structure per bucket and run cast_down for the local flat cast instead of .copy_. Same fp32->bf16 RNE =>
  bitwise identical (N0). Rest of copy exposure is architectural (ViewBackward0 1.13 ms, mixer 0.64 ms transposes).
- Time: paired 1.5247 (prior 1.5185, +0.4%); frozen-ref 1.5239. Candidate 0.1541 -> 0.1536 (paired) / 0.1534
  (check). Exposed gain < kernel-time saving because the local cast overlaps the remote-shard broadcast.
- Full check /tmp/r28/check_flat: PASS, speedup 1.5259, 0.1534 s/upd, tier N1, gate-3 max bias 1.425σ
  (within 3σ), exact_failures [], peak 65.4 GiB. Commit 46fb72a. Switch enabled (17 active). NEW BEST 1.5259.
- Lesson: torch mixed-dtype .copy_ (fp32->bf16) is slow (unrolled_elementwise ~0.94 TB/s); always route bulk
  casts through the vectorized MT Triton kernel. Re-profile after each structural change — the bf16 broadcast
  moved the bottleneck from nccl/cast_down into the copy category.
8.4 hRound 29 — cast+scale only the local OSS shard's fp32 grads (+2.9%, N0) (04:24–04:53)
- Re-profiled 17-switch best (/tmp/r29/profile): flat-cast MT moved 4.7 ms from copy into cast_down (2.63 ms);
  copy 6.56->2.12 ms; nccl busy 66->36 ms. cast_scale still 5.7 ms exposed (full-model fp32 grad write).
- OSS-aware insight: the fused grad cast+scale wrote fp32 master grads for EVERY trainable param, but the OSS
  inner Adam is constructed from partition_parameters()[rank] (fairscale oss.py:407) and reads ONLY the local
  shard. The remote fp32 grads were written and never read (the reference redundantly casts all grads for its
  fp32 L2 norm; our patch norms bf16 directly, so it doesn't need them).
- Change (_opt.py clip_grad_norm, switch YOCO_GRAD_SCALE_LOCAL, off default): cache the local-bucket fp32
  param id set; restrict the cast_scale bf16/fp32 tensor lists to local-shard params (skip remote allocation +
  write). The L2 norm still runs over the FULL bf16 grad list (params unchanged). Falls back to full if the id
  set is empty. Halves cast_scale DRAM traffic (read 6->3 GB, write 12->6 GB) + drops remote fp32 grad allocs.
- Numerics: local fp32 grads bitwise unchanged; remote grads unused => N0; gate-2 exact_failures [].
- Time: paired 1.5664 (prior 1.5247, +2.7%); frozen-ref 1.5688. Candidate 0.1536 -> 0.1492 (paired) /
  0.1491 (check) ≈ -2.9% (~4.4 ms; more than the cast_scale halving alone — fewer allocs + less TLB pressure).
- Full check /tmp/r29/check_local: PASS, speedup 1.5699, 0.1491 s/upd, tier N1, gate-3 max bias 1.257σ
  (within 3σ), exact_failures [], peak 65.4 GiB. Commit 5cf4fa0. Switch enabled (18 active). NEW BEST 1.5699.
- Lesson: audit OSS/sharded-optimizer semantics for REDUNDANT full-model work (grad casts, norms, copies) that
  only the local shard actually consumes. Next: the bf16 L2 norm also reads the full model on every rank — check
  whether aggregate_norm_fn already allreduces local contributions (could halve l2norm ~2.9 ms), but verify the
  aggregation semantics carefully first (DDP grads are already averaged => risk of double counting).
8.8 hRound 30 — grad L2 norm over local OSS shard + allreduce (+1.2% paired, N1) (04:54–05:18)
- Trainer passes aggregate_norm_fn=None (trainer.py:1208) and DDP grads are already averaged, so every rank
  redundantly ran apex multi_tensor_l2norm over the FULL bf16 grad list (l2norm ~2.9 ms exposed). The global
  norm² is just the sum of the two ranks' local-shard norm².
- Change (_opt.py clip_grad_norm, switch YOCO_GRAD_NORM_LOCAL, off default): norm only the local shard's
  bf16 grads (apex multi_tensor_total_norm), .pow(2), dist.all_reduce(nsq) (scalar, world group), .sqrt()
  => same global norm with half the DRAM read. Refactored local_ids computation to be shared with
  YOCO_GRAD_SCALE_LOCAL. Reduction order differs (local chunking + allreduce vs one full chunked reduce) => N1.
- Time: paired 1.5853 (prior 1.5664, +1.2%, above the 0.64% noise band); frozen-ref 1.5784 (+0.6%).
  Candidate 0.1492 -> 0.1483 (paired) / 0.149 (check). The allreduce adds a small sync but nets positive.
- Full check /tmp/r30/check_norm: PASS, speedup 1.5709, 0.149 s/upd, tier N1, gate-3 max bias 0.255σ
  (very low — norm reorder bias negligible), exact_failures [], peak 65.4 GiB. Check timing sample flat (+0.06%,
  noise); the paired signal carries the gain (method: trust paired over a single noisy check sample).
- Commit a96c5c0. Switch enabled (19 active). NEW BEST 1.5709 check / 1.5853 paired.
- OSS-aware redundant-work audit continues to pay: bf16 broadcast (+0.7), param view alias (+3.0), flat cast MT
  (+1.7), local grad cast+scale (+2.9), local grad norm (+1.2 paired). Next candidate: flatten the local fp32
  grad storage for Adam read locality (adam ~11.4 ms at 3.7 TB/s).
9.2 hRound 31 — flat fp32 master-grad buffer for Adam locality (+0.8%, N0) (05:19–05:40)
- Same locality class as the round-27 weight win: the local fp32 master grads (p32.grad) were ~130 separate
  empty_like allocations; Adam's MT kernel read them fragmented. Allocate ONE flat fp32 buffer mirroring the
  local OSS bucket layout and point each local p32.grad at its slice (offset = (p32.data_ptr - bucket.base)//4,
  .view(p32.shape)). cast_scale writes the same values into the views; Adam reads contiguous storage.
- Change (_opt.py clip_grad_norm, switch YOCO_GRAD_FLAT, off default; needs local_ids). Cached buffer+views.
  Bitwise identical grads => N0; gate-2 exact_failures [].
- Time: frozen-ref 1.5858 (prior 1.5784, +0.47%); paired 1.5793 (dip is reference drift). Candidate
  0.1483 -> 0.1476 (paired) / 0.1478 (check) ≈ -0.5..0.8% (~0.7-1.2 ms).
- Full check /tmp/r31/check_gflat: PASS, speedup 1.5837, 0.1478 s/upd, tier N1, gate-3 max bias 0.2245σ,
  exact_failures [], peak 65.4 GiB. Commit ae531a7. Switch enabled (20 active). NEW BEST 1.5837.
- Storage-locality audit (weights + grads) now done; next: Adam m/v optimizer states (apex per-param) are the
  remaining fragmented Adam streams (2 of 4) — flattening them is the next locality candidate (~1% ceiling).
9.5 hRound 32 — flat Adam m/v optimizer state for locality (NO GAIN, reverted) (05:49–05:58)
- Profile current best (/tmp/r32/profile, 20 switches): _adam_mt 57.2 ms/5 = 11.44 ms/upd, fully exposed
  (0 NCCL overlap; optimizer phase precedes broadcast). 2nd-largest exposed category after gemm (50.3 ms).
  Adam already ~3.7 TB/s (4 read + 3 write fp32 streams over ~1.5B local params). m/v were the only fragmented
  streams left (per-param zeros_like, ~130 allocs each); g/p already flat (rounds 27/31).
- Change (_opt.py fused_adam step, switch YOCO_ADAM_STATE_FLAT, off default): one flat fp32 m buffer + one
  flat v buffer per param_group (param order), state['exp_avg'/'exp_avg_sq'] = .narrow(0,off,n).view(shape)
  slices. Zero-init + update arithmetic unchanged => N0 (bitwise vs current fused Adam). Cached on self._adam_flat.
- Time /tmp/r32/time_flat (21-switch temp config, paired): frozen-ref 1.5826, paired 1.5849,
  0.1479 s/upd vs prior best 0.1478 / paired 1.5858. Δ +0.07% s/upd — inside the 1.28% noise band => NO GAIN.
- Diagnosis: the per-param m/v allocations were already allocator-contiguous (allocated in a tight loop at first
  step), so flattening changed little real layout; Adam is BW/latency-bound at BLOCK=1024, not TLB-bound on m/v.
  The round-27/31 flat wins came mostly from copy/remote-write REMOVAL, not pure locality — pure m/v locality alone
  is negligible. Reverted the inline edit (git checkout yoco/_opt.py); no commit; switches stay at 20.
- Lesson: storage-locality lever is exhausted (weights/grads/m/v all tried). Remaining exposed time is gemm
  (cuBLAS-optimal), NCCL broadcast/allreduce (NVLink limit), and the elementwise/cast/norm tail. Next hotspots to
  attack with fused/custom kernels: the bf16 elementwise add chain (residual+norm, ~5.7 ms exposed) and the
  cast_scale/cast_down pair (2.8+2.6 ms) — candidate for a fused residual-add+RMSNorm or a single-pass cast.
9.2 hCurrent summary (updated after round 31)
- Current switches: /submission/switches.json = {"YOCO_PIPELINE_CAST":"1","YOCO_FUSED_NORM":"1","YOCO_FUSED_GRAD_SCALE":"1","YOCO_GRAD_SCALE_MT":"1","YOCO_DDP_BUCKET_VIEW":"1","YOCO_DDP_BUCKET_MB":"100","YOCO_FUSED_ADAM":"1","YOCO_FUSED_GATE_SCALE":"1","YOCO_FUSED_CE":"1","YOCO_CAST_DOWN_MT":"1","YOCO_SKIP_GRAD_ZERO":"1","YOCO_MP_IDENTITY":"1","YOCO_FUSED_NORM_DW":"1","YOCO_GATE_SCALE_STRIDE":"1","YOCO_BCAST_BF16":"1","YOCO_BCAST_BF16_VIEW":"1","YOCO_BCAST_FLAT_MT":"1","YOCO_GRAD_SCALE_LOCAL":"1","YOCO_GRAD_NORM_LOCAL":"1","YOCO_GRAD_FLAT":"1"}.
- Best verified: 20 switches, full check PASS (/tmp/r31/check_gflat), speedup 1.5837 (0.1478 s/upd), tier N1,
  gate-3 equivalent max bias 0.2245σ, exact_failures [], peak 65.4 GiB. Paired best 1.5853. Check samples
  (frozen-ref noise): /tmp/r31/check_gflat 1.5837, /tmp/r30/check_norm 1.5709, /tmp/r29/check_local 1.5699,
  /tmp/r28/check_flat 1.5259, /tmp/r27/check_view 1.5004, /tmp/r26/check_bcast 1.4575, /tmp/r24/check_stride 1.4476,
  /tmp/r22/check_dw 1.436, /tmp/r20/check_mp 1.4135, /tmp/r19/check_zero 1.3933, /tmp/r18/check_cast 1.3966,
  /tmp/r17/check_ce 1.3522, /tmp/r14/check 1.3445. Paired-time progression: 1.3585 -> 1.3858 -> 1.405 -> 1.4135
  -> 1.4331 -> 1.4429 -> 1.4665 -> 1.5185 -> 1.5247 -> 1.5664 -> 1.5853 -> 1.5793.
- Gains by change: broadcast overlap +7.8% (N0); fused RMSNorm +6.6% (N1); pipeline-cast +1.2% (N0);
  fused grad cast+scale +5% (N0); multi-tensor cast+scale kernel +4.2% (N0); DDP bucket_view+100MB +3.5% (N0);
  multi-tensor fused AdamW +2% (N1); fused gate-exp scaling +0.5% (N1); fused cross-entropy +1.0% (N1);
  multi-tensor fp32->bf16 OSS refresh cast +2.0% (N0); skip redundant fp32 grad zero +1.4% (N0);
  mp=1 identity autograd bypass +0.6% (N0); RMSNorm dw yb side-output fusion +1.6% (N0 vs eager);
  gate-scale native strided reads (drop q/v copies) +0.7% (N1, re-test of round-15 lever at new exposure);
  bf16 OSS shard broadcast (halve NVLink volume) +0.7% (N0, expensive lever; +6.4 GiB peak);
  alias bf16 model params into broadcast buffers (drop copies + flat weight locality) +3.0% (N0);
  fast MT kernel for the bf16 broadcast flat cast (replace slow torch .copy_) +1.7% check (N0);
  cast+scale only local OSS shard fp32 grads (drop redundant remote writes) +2.9% (N0);
  grad L2 norm over local shard + allreduce norm² (drop redundant full-model norm) +1.2% paired (N1);
  flat fp32 master-grad buffer for Adam locality (mirror flat weight gain) +0.8% (N0).
- Commits: 047a06e (overlap N0), 2e32c92 (fused norm N1), 3b78a23 (pipeline-cast N0), 3b9b115 (fused grad
  cast+scale N0), 3b07f2c (multi-tensor cast+scale N0), 8a4a65a (DDP bucketing N0), 07ffa67 (fused AdamW N1),
  9f45e21 (fused gate-scale N1), f996a1b (fused CE N1), f11c293 (fp32->bf16 cast N0), ca5720e (skip grad zero N0),
  11d8323 (mp identity N0), 2f1d080 (norm dw yb N0), 9443034 (gate-scale strided N1), b569bff (bf16 broadcast N0),
  5b675fa (bf16 param view alias N0), 46fb72a (bf16 flat cast MT N0), 5cf4fa0 (local-shard grad scale N0),
  a96c5c0 (local-shard grad norm N1), ae531a7 (flat fp32 master-grad N0).
- Code: yoco/_opt.py + _rmsnorm_kernel.py + _cast_scale_kernel.py (cast_scale + cast_down) +
  _adam_kernel.py + _gate_scale_kernel.py + _ce_kernel.py (patches at import via models/yoco.py), each
  behind an env switch, off default. Active: pipeline_cast(+overlap+cast_down_MT) + fused_grad_scale(+MT
  +local shard +local norm +flat grad) + skip_grad_zero + mp_identity + fused_norm(+dw_yb) + ddp_bucket(view+100MB)
  + fused_adam + fused_gate_scale
  (+strided reads) + fused_ce + bcast_bf16(+param view alias +flat cast MT). Dormant gated-off probes:
  foreach_sync, compile_layer, compile_norm, compile_layer_opaque.
- Directions that did NOT work: foreach copies (bandwidth-bound), NCCL Simple/LL128/NVLS/BUFFSIZE (broadcast
  not protocol-limited), compile-norm (Dynamo fallback), whole-layer compile ×2 (Triton inline error + DDP
  higher-order op; torch 2.3 AOTAutograd backward-mutation assert even with allow_in_graph), scale-fusion into
  FusedAdam (adapter needs ALL grads scaled), MT/cast_scale BLOCK/warps retune (already optimal), fused RMSNorm
  dw ATOMIC reduction (slower than torch sum(0), round 18 — but the yb side-output decomposition WON, round 22),
  NCCL_PROTO=Simple re-test (neutral again, round 21). QKV/proj merging FORBIDDEN (param names/shapes exact).
- Remaining levers: DDP reducer::mul_out / AccumulateGrad AUnaryFunctor ~4.4ms (grad scale during backward,
  partly overlapped; fold 1/world_size into cast_scale factor is N1+risky); ViewBackward0/reshape copies ~1ms;
  residual-add+norm fusion (~0.5ms); retention cross_chunk bmms use cutlass_80 (sm80) kernels on Hopper — a custom
  sm90 Triton bmm is an expensive lever (~2.5ms total, modest ceiling); broadcast ~11ms exposed (NVLink limit).
  GEMMs ~640 TFLOP/s. CE + OSS cast + fp32 grad zero + mp identity + norm dw + gate-scale copies DONE.
  Cheap levers largely exhausted; re-test previously-overlapped levers after each compute shrink (round 24 win).
- Key method: trace sweep-line exposure finds EXPOSED time (re-profile each round); single-op microbench sizes
  fusions BUT end-to-end gain is bounded by the EXPOSED fraction AND added copies, not the kernel speedup;
  probe numerics with flock scripts; match the backward rounding chain + atomic-safe accumulation for custom
  autograd kernels. Triton 2.3 int64->pointer cast enables multi-tensor apply. 2-rank allreduce commutative =>
  bucketing N0. apex Adam really ~1.5 TB/s on separate tensors (~3 TB/s on contiguous shard).
  **Trace correlation (round 18): kernel.correlation -> cuda_runtime cudaLaunchKernel -> its CPU ts -> innermost
  enclosing cpu_op + ancestor autograd node on the same tid. GPU-timestamp containment FAILS (GPU timeline offset
  from CPU); kernel.External id matches cpu_op only for FORWARD ops, backward needs the launch-ts chain.** This
  resolves the backward "<unknown>" and exposes optimizer-phase per-param copies as fusion targets.
↑ YOCO