Gemini 4 Hydrogen 2.61×

Harness: Antigravity · switches: TORCH_BLAS_PREFER_CUBLASLT=1

Judged
2.61×
Tier
N1
Self-best
2.58×
Rounds
6
Hours
10.0
API cost
$69.2
Input tokens · 94.4% cached
303 M
Output tokens
3.0 M
Requests
1,885
Cross-GPU exchange via CUDA IPC + copy engine (no SMs)
✓ round 6: weight exchange as 16 copy-engine chunks pipelined with Adam (14.59 ms vs 21.80 ms serial), with custom optimizer kernels 1.779× → 1.898×; then FastP2PDataParallel replaces DDP, each rank pushes only the peer shard's grads over the copy engine (half the NVLink traffic), with fused kernels reading local + peer grads 1.898× → 2.128×; exchange has been bf16 only since round 3
Forward / backward CUDA graph
✗ tried make_graphed_callables in round 6: ~17.9 ms saved in deterministic mode, only 100.71 → 100.14 ms in production mode; dropped
Newer cuBLAS
not stated: moved to a Torch 2.8 env (same commit 408be3a as FA3 etc., 2.396× → 2.54×), cuBLAS version not in the log; custom cached cuBLASLt calls 2.5666× → 2.5694×; final switches hold only TORCH_BLAS_PREFER_CUBLASLT=1, which the log never mentions
Retention / attention kernel swap
✓ round 5 custom Triton retention pipeline (FastInnerChunk32 and three more kernels, no 256×256 scores materialized), 1.614× → 1.748×; round 6 moved to hand-written CUDA (recurrence kernel 0.2866 → 0.0263 ms per layer), that batch 2.128× → 2.190×; attention moved to FA3, called directly from cb09ef5 on
Other main levers
round 3 optimizer path rewrite: fp32 master grads materialized only for this rank's shard, flat Triton AdamW also writing bf16, exchange switched to bf16, 1.22× (N0) → 1.36× (N1); round 5 Apex RMSNorm + Triton cross-entropy + Megatron wrappers bypassed, 1.41× → 1.61×; round 6 hand-written CUDA RoPE / SwiGLU / residual + RMSNorm; merged same-input projections + sparse embedding-grad exchange 2.313× → 2.396×; stats and grad norm via NVLink mailboxes instead of NCCL, 2.569× → 2.581×
Raw work log7 sections
0.1 hRound 1: Baseline Profiling & Bottleneck Inventory
Started: 2026-11-19T19:26:15Z | Ended: 2026-11-19T19:33Z

### Profile Measurements (/tmp/r1/profile)
- Command: /opt/yoco-env/bin/python bench/bench.py profile --tree /submission/yoco --config /submission/switches.json --out /tmp/r1/profile
- Instrumented 5-update window (iters 5..9): 1.488 s (0.2977 s/update, median 0.2779 s/update).
- GPU busy fraction: 70.7% (1.052 s busy over 1.488 s span -> 29.3% GPU idle).
- Kernel time total (rank 0, 5 iters): 1.178 s (235.6 ms/iter).

#### Kernel Time by Category (5 updates, rank 0)
| Category | Total (ms) | Per-iter (ms) | Notes |
|---|---:|---:|---|
| nccl | 336.2 | 67.24 | Broadcast_RING_LL 185.3 ms (10 calls), AllReduce_Sum_bf16_RING_LL 150.8 ms (595 calls) |
| gemm | 308.2 | 61.64 | sm90_xmma_gemm + cutlass_80 (mostly forward/backward linear layers) |
| memcpy/cast | 214.0 | 42.80 | direct_copy fp32<->bf16 (144.2 ms, 4940 calls!), Memcpy DtoD (25.3 ms, 1985 calls) |
| elementwise | 147.5 | 29.50 | mul_fp32 (76.3 ms total, 12.0 ms/iter in _unscale_grads), fill_ zero_grad (22.0 ms) |
| optimizer (multi_tensor) | 89.6 | 17.92 | FusedAdamV2 (70.5 ms across 4 steps), L2Norm (19.1 ms, 825 calls) |
| flash-attention | 29.5 | 5.90 | Cross-decoder attention fwd (8.2 ms) + bwd (21.3 ms) |
| reduce | 18.6 | 3.72 | RMSNorm + retention reductions |
| triton (rotary/recurrence/inductor) | 13.2 | 2.64 | Rotary (6.8 ms), Inductor inner_chunk, ChunkGateRecurrent |
| jiterator (swiglu) | 10.8 | 2.16 | SwiGLU fwd (4.0 ms) + bwd (6.9 ms) |
| loss (log_softmax/nll) | 8.8 | 1.76 | Full [2048, 100288] fp32 log_softmax + nll_loss |

#### Detailed Iteration Timeline (Iter 6->7, 277.8 ms profiled)
1. Zero-grad & step prep (+0..+6 ms): FP16Optimizer.zero_grad issues 240 individual fill_ calls (4.16 ms GPU).
2. Forward (+6..+67 ms CPU, ~44.6 ms GPU): self_decoder is CPU-launch-bound (43.1 ms CPU vs 20.3 ms GPU) due to uncompiled cross_chunk, eager subln RMSNorm, cumsum, and 5 separate projections per layer.
3. Backward + DDP AllReduce (+67..+182 ms): 100.8 ms GPU Stream 7 compute; 29.5 ms Stream 18 AllReduce_bf16 (119 calls, overlaps almost completely except last 2.8 ms + bandwidth contention); 4.08 ms Memcpy DtoD copying DDP buckets back to .grad.
4. Post-Backward Optimizer & OSS Broadcast (+182..+277 ms = 95 ms!):
   - clip-grads: _sync_fp16_grads_to_fp32 copies ALL 240 bf16->fp32 grads (10.20 ms, half are unused by this rank!); calc_grad_norm launches 165 L2Norm calls (3.81 ms); _check_grad_norms + is_finite syncs CPU (9.1 ms).
   - multiply-grads / _unscale_grads: FairseqOptimizer.multiply_grads loops over ALL 240 fp32 grads (12.02 ms, half dead code, non-batched!).
   - FusedAdamV2.step: updates rank's 120 local fp32 params (14.10 ms GPU, 1.47 ms CPU).
   - OSS._broadcast_params(): cudaDeviceSynchronize() (22.46 ms CPU block), then 2 SERIAL unidirectional FP32 ncclBroadcast calls (37.01 ms GPU Stream 18 = 18.37 ms + 18.64 ms for 13.78 GB total while GPU Stream 7 is idle!).
   - _sync_fp32_params_to_fp16(): 240 separate copy_ calls (13.78 GB -> 6.89 GB, 10.04 ms GPU), blocking CPU 43.96 ms in aten::is_nonzero inside _reduce_and_log_stats.

### Prebuilt Fast Paths Verified in /opt/yoco-env
- amp_C: multi_tensor_adam, multi_tensor_adam_capturable, multi_tensor_adam_capturable_master, multi_tensor_l2norm, multi_tensor_scale
- fused_layer_norm_cuda: rms_forward_affine, rms_backward_affine, rms_forward, rms_backward (Apex sm_90 CUDA RMSNorm)
- flash_attn.ops.triton.cross_entropy: Triton fused CrossEntropy (avoids fp32 logit materialization)
- flash_attn_2_cuda, fused_dense_cuda, fused_rotary_positional_embedding, xentropy_cuda

### Action Plan (Ordered by Measured Cost)
1. Round 2 (Switches): Investigate/test NCCL switches (NCCL_PROTO, NCCL_ALGO, NCCL_MIN_NCHANNELS, NCCL_NVLS_ENABLE, NCCL_BUFFSIZE, PYTORCH_CUDA_ALLOC_CONF) via /submission/switches.json.
2. Round 3 (OSS Broadcast + Zero-1 Gradient/Param Sync — ~60-75 ms potential!):
   - Replace serial 2-call FP32 Broadcast (37 ms) + cudaDeviceSynchronize (22 ms) + 240-call multiply_grads (12 ms) + 240-call copy_to_fp32 (10.2 ms) + 240-call zero_grad (4.2 ms) + 165-call L2Norm (3.8 ms) + 240-call copy_to_bf16 (10.0 ms)!
   - First test N0-exact bidirectional/batched + local-shard-only optimizations (multi_tensor_l2norm, multi_tensor_scale, local-shard-only grad copy/zero/mul, simultaneous full-duplex NVLink P2P send/recv or all_gather), then evaluate N1 BF16 weight broadcast / fused BF16-grad-to-FP32-master optimizer!
3. Round 4 (DDP Gradient Comm + ReduceScatter / gradient_as_bucket_view=True + Bucket Size):
   - Enable gradient_as_bucket_view=True (eliminates 4.08 ms Memcpy DtoD), tune bucket_cap_mb, and evaluate ReduceScatter DDP comm hook for ZeRO-1 (1/2 traffic vs AllReduce!).
4. Round 5 (SelfDecoder / GateRetention / RMSNorm / Linear Fusions + Removing MPU & Host Syncs):
   - Replace 54 PyTorch RMSNorms with Apex fused_layer_norm_cuda or fused Triton Residual+RMSNorm.
   - Remove model_parallel_size==1 MPU wrappers & VocabParallelEmbedding masks/copies; remove per-step .item() syncs in logging/grad norm checks where safe.
   - Fuse Q/K/V/G/Gt projections (Self), Up/Gate projections (FFN), K/V projections (Cross), compile/fuse cross_chunk + cumsum + chunk_gate_retention, optimize rotary and cross_entropy.


---
0.2 hRound 2: Environment & NCCL Parameter Sweep
Started: 2026-11-19T19:33Z | Ended: 2026-11-19T19:39Z

### Standalone 2-GPU NCCL & P2P Microbenchmarks (torchrun --nproc-per-node=2, BF16 / FP32)
1. Default NCCL vs NCCL_PROTO=Simple vs NCCL_MIN_NCHANNELS=32 NCCL_BUFFSIZE=16777216:
   - 138 × all_reduce (25MB bf16): 14.63 ms (default) vs 31.77 ms (Simple) vs 30.35 ms (32ch/16M).
   - 138 × reduce_scatter (25MB bf16): 9.82 ms (default) vs 21.85 ms (Simple) vs 20.48 ms (32ch/16M).
   - 1 × reduce_scatter (6.89GB bf16): 11.43 ms (default) vs 23.30 ms (Simple).
   - 1 × all_reduce (6.89GB bf16): 19.58 ms (default) vs 43.00 ms (Simple).
   - Finding: Default NVLink LL/LL128 protocols strongly outperform forced Simple / large-buffer overrides (~2.1x faster on small/medium buckets).
2. Serial Broadcast vs Full-Duplex batch_isend_irecv / all_gather_into_tensor:
   - Serial 2× broadcast (FP32, 6.89 GB/rank = 13.78 GB total): 77.99 ms (standalone), 37.0 ms (in profile; LL).
   - Full-duplex batch_isend_irecv (FP32, 6.89 GB/rank): 41.76 ms (1.87x faster).
   - Serial 2× broadcast (BF16, 3.44 GB/rank): 39.38 ms.
   - Full-duplex batch_isend_irecv (BF16, 3.44 GB/rank): 21.20 ms (and direct CUDA peer memcpy: 17.63 ms, ~2.2x faster!).

### bench.py time Run on /submission/switches.json (TORCH_NCCL_AVOID_RECORD_STREAMS=1, PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True)
- Output: /tmp/r2/time/time.json (status ok)
- s_per_update: 0.2345 s (frozen ref: 0.23407 s)
- speedup_vs_frozen_reference: 0.9982x (beyond_reference_noise: false, window spread 0.0016)
- peak_memory_allocated_gib: 61.75 GiB
- Decision: Reverted /submission/switches.json to {}; neither switch improved runtime on this workload. Proceeding to code-level optimizations in /submission/yoco.

---
0.5 hRound 3: Optimizer, ZeRO-1 Communication & Host-Sync Overhaul
Started: 2026-11-19T19:40Z | Stage 3A Ended: 2026-11-19T19:56:58Z

### Stage 3A: Strict N0 Optimizer / Comm / Host-Sync Rewrite (yoco/models/_fast_optim.py)
Committed on branch opt at 53dd9a9:
1. Skipped redundant 240 × fp32.grad.zero_() (4.16 ms) in _FP16OptimizerMixin.zero_grad; cleared fp16_params .grad = None.
2. Computed clip_grad_norm L2 norm directly from BF16 p16.grad via amp_C.multi_tensor_l2norm (microbenchmarked bitwise identical 0.0 diff vs FP32, cutting grad read traffic in half before clip).
3. Fused p16.grad * _multiply_factor -> p32.grad (FP32) into 1 chunked Triton kernel (_indexed_bf16_to_fp32_scale_kernel) inside FP16Optimizer.step() immediately before fp32_optimizer.step(), eliminating separate 240-call grad copy + non-batched FairseqOptimizer.multiply_grads.
4. Allocated contiguous flat FP32 buffers inside OSS.refresh_trainable for p32.grad, exp_avg, and exp_avg_sq matching OSS.buckets, and cached parameter tensor lists inside FusedAdamV2.step (with ptr-signature validation; verified 120 tensor views avoid amp_C.multi_tensor_adam's 1-tensor indexing bug).
5. Eliminated blocking torch.cuda.synchronize() (22.5 ms) and replaced serial 2× dist.broadcast (37.0 ms) in OSS._broadcast_params with full-duplex dist.batch_isend_irecv for world_size == 2.
6. Replaced 240 separate p32 -> p16 copy_ calls (10.04 ms) with 1 Triton kernel (_chunked_fp32_to_bf16_kernel).
7. Eliminated per-step CPU<->GPU host syncs in Trainer: single-tensor float64 _fast_stat_sync_sum, torch.where instead of (sample_size or 1.0), async pinned-memory ring buffer for _check_grad_norms, and direct CrossEntropyCriterion fast path in _reduce_and_log_stats avoiding if sample_size != ntokens: (44.0 ms aten::is_nonzero stall).

### Stage 3A Measurements
- bench/bench.py time (/tmp/r3a/time/time.json):
  - s_per_update: 0.1921 s (window_s [1.918, 1.923], window_range: 0.0028, slow_update_fraction_rank0: 0.0)
  - Frozen ref: 0.23407 s -> speedup_vs_frozen_reference: 1.2185x (beyond_reference_noise: true)
  - peak_memory_allocated_gib: 61.75 GiB (unchanged)
  - other_optimizer_steps: [24] (IterTimer latched on FusedAdamV2.step, compiles_in_window: 0, RNG fingerprints exact)
- bench/bench.py check --quick (/tmp/r3a/quick/check.json):
  - status: PASS
  - measured_tier: N0, bitwise: true, bitwise_identical: 9616 / 9616, exact_failures: [], errors: 0, violations: 0

### Stage 3B: Owned-Shard Grad/Norm, Fused Flat Triton AdamW+BF16, & BF16 Exchange
Ended: 2026-11-19T20:16Z | Committed on branch opt:
1. Owned-shard vectorized BF16 L2-norm + scalar all_reduce (_indexed_sum_sq_bf16_kernel): computes sum(g^2) only on the rank's owned ~120 BF16 grads (chunk=65536, tl.multiple_of 16B alignment -> 0.85 ms vs 3.52 ms multi_tensor_l2norm), sharing the single H2D dev_src_ptrs copy with grad sync via _zero_grad_seq.
2. Owned-shard-only grad sync & scale (_indexed_bf16_to_fp32_scale_kernel): peer p32.grad stays fixed zero from refresh_trainable; sync+scale processes only ~1.72B owned elements (chunk=4096, BLOCK_SIZE=1024, tl.multiple_of -> 4.23 ms vs ~13.5 ms Stage 3A).
3. Direct p16.data aliasing into contiguous per-rank BF16 buckets (fast_shard_ / _bind_fp16_to_oss): aliases all 240 p16.data views directly into bf16_buckets[dev][0..1] (verified all tensors >=256B aligned and DDP(gradient_as_bucket_view=True) compatible).
4. Flat single-launch Triton AdamW + inline BF16 write (_flat_adamw_bf16_kernel): updates owned flat (p32, grad, exp_avg, exp_avg_sq) and writes bf16_my_flat in a single pass (11.90 ms vs 18.54 ms Apex + fp32->bf16 cast; 3.66e-10 rel diff vs Apex).
5. BF16 full-duplex exchange (OSS._broadcast_params): exchanges contiguous BF16 shards (3.42 GB / 3.47 GB) directly via batch_isend_irecv and skips _sync_fp32_params_to_fp16() completely (0.0 ms).

### Stage 3B Measurements (Cleaned)
- bench/bench.py time (/tmp/r3b_time/time.json):
  - s_per_update: 0.1717 s (window_s: [1.716, 1.718], window_range: 0.0011, slow_update_fraction_rank0: 0.0, tokens_per_s: 23850.1)
  - Frozen ref: 0.23407 s -> speedup_vs_frozen_reference: 1.3632x (beyond_reference_noise: true)
  - peak_memory_allocated_gib: 61.76 GiB (compiles_in_window: 0, other_optimizer_steps: [24])
- bench/bench.py check --quick:
  - status: PASS, measured_tier: N1 (exact_failures: [], errors: 0, bitwise_identical: 2087 / 9616, all model forward/loss within gates; 1604 diagnostic unresolved mostly unowned grad/delta peer views).
- bench/bench.py check --n1:
  - status: PASS, verdict: equivalent (mean_in_sigma: +0.025, +0.012, +0.008, +0.033, -0.629, -0.633, all cleanly within ±3.0 sigma).

---
1.2 hRound 4: DDP `gradient_as_bucket_view=True` & Bucket Sizing
Ended: 2026-11-19T20:35Z | File: yoco/models/_fast_ddp.py, yoco/models/__init__.py

### Changes & Findings
- Patched DistributedFairseqModel (fairseq.models.distributed_fairseq_model and fairseq.models) in yoco/models/_fast_ddp.py to set:
  - gradient_as_bucket_view=True (eliminates 240 per-param DtoD copies from DDP buckets -> .grad, keeping all 240 BF16 .grad tensors contiguous and >=256B aligned).
  - bucket_cap_mb=100 (without mutating args.bucket_cap_mb/cfg so the frozen cfg sha256 stays unchanged; reduces post-step-0 DDP buckets from 119 -> 47).
- Swept cap=25/50/100/150/200 and custom ReduceScatter comm hooks in standalone 2-GPU DDP forward+backward benchmarks: gradient_as_bucket_view=True, cap=100 (125.98 ms) beat both cap=25 (133.01 ms) and Python register_comm_hook (127.23 ms) while preserving 50/50 OSS shard balance (3.42 GB / 3.47 GB).

### Measurements (Cleaned /tmp/r4_*)
- bench/bench.py time (/tmp/r4_time/time.json):
  - s_per_update: 0.1661 s (window_s: [1.661, 1.660], window_range: 0.0007, slow_update_fraction_rank0: 0.0, tokens_per_s: 24660.9)
  - Frozen ref: 0.23407 s -> speedup_vs_frozen_reference: 1.4092x (beyond_reference_noise: true)
  - peak_memory_allocated_gib: 61.76 GiB (peak_memory_reserved_gib: 62.23 GiB)
- bench/bench.py check --quick (/tmp/r4_quick/check.json):
  - status: PASS, measured_tier: N1 (exact_failures: [], errors: 0, bitwise_identical: 2087 / 9616).

---
2.3 hRound 5: Model Compute, MPU, RMSNorm, CrossEntropy & Fused GateRetention Triton Pipeline
Ended: 2026-11-19T21:42Z | Files: yoco/models/_fast_model.py, yoco/models/_fast_gate.py, yoco/models/__init__.py, yoco/models/decoder/kernel/rotary.py

### Step 5A (yoco/models/_fast_model.py, rotary.py) -> 0.1450 s/update (1.6143x)
1. Bypassed VocabParallelEmbedding index masking/cloning and ColumnParallelLinear / RowParallelLinear identity autograd regions when model_parallel_size == 1 (zero math change, removes 184 autograd wrappers/iter).
2. Made LanguageModel.set_num_updates a no-op (no submodule overrides set_num_updates).
3. Cached contiguous BF16 (cos, sin) buffers on (x.dtype, x.device) inside SelfDecoder.build_rel_pos, CrossDecoder.build_rel_pos, and Transformer.build_rel_pos.
4. Patched RMSNorm.forward to call Apex SM90 FusedRMSNormAffineFunction (54 calls/iter) and FusedRMSNormFunction (13 calls/iter), replacing 67 multi-kernel float32 cast/pow/mean/rsqrt chains.
5. Patched CrossEntropyCriterion.compute_loss to use flash_attn.ops.triton.cross_entropy.cross_entropy_loss(..., inplace_backward=False).sum(), eliminating full [2048, 100288] float32 log_softmax materialization.
6. Tuned rotary.py interleaved BLOCK_M heuristic (8 for nheads >= 16, 32 for nheads <= 8 at rotary_dim == 128, seqlen >= 64).

### Step 5B (yoco/models/_fast_gate.py) -> 0.1339 s/update (1.7481x)
Replaced GateRetention.forward (when incremental_state is None and seqlen % 256 == 0) with a deterministic tiled Triton pipeline:
1. FastPrepQKV: fused Q/K interleaved rotary + K * (D**-0.5) + V transpose directly into contiguous [B, H, S, D].
2. FastGatePrep: fused logsigmoid(gt) / 16 + exact chunk tl.cumsum + (q_decay, k_decay, cross_decay) in 1 kernel (eliminates PyTorch cumsum nondeterminism warnings).
3. FastInnerChunk32: [BM=32, BN=32, nw=4] Flash-style causal decayed attention without materializing [BHN, 256, 256] scores or invoking @torch.compile Dynamo overhead (compiles_in_window: 0).
4. FastAddSubLNSwiGLU: fused (cross + inner) + no-affine RMSNorm(128) + [B, H, S, D] -> [B, S, H*D] transpose + SwiGLU(g, y) in a single fwd/bwd kernel pass (0 Memcpy DtoD).
2.3 hRound 5 Measurements (`/tmp/r5b_time`, `/tmp/r5_skip` -> Cleaned)
- bench/bench.py time:
  - s_per_update: 0.1339 s (window_s: [1.344, 1.334], median_update_s: 0.13385, slow_update_fraction_rank0: 0.0, tokens_per_s: 30595.7)
  - Frozen ref: 0.23407 s -> speedup_vs_frozen_reference: 1.7481x (beyond_reference_noise: true)
  - peak_memory_allocated_gib: 60.91 GiB (peak_memory_reserved_gib: 58.77 GiB)
- bench/bench.py check --skip-timing:
  - status: PASS, measured_tier: N1, exact_failures: [], errors: 0, precision_changed: false
  - trajectory.verdict: equivalent (mean_in_sigma: -0.014, -0.035, -0.117, -0.015, -0.394, -0.060, all cleanly within ±3.0 sigma).

---
3.4 hRound 6: DDP SUM Hook, Non-Blocking Stats, Memory-Bound Optimizer & Compute Fusion
Started: 2026-11-19T22:00Z

### Step 6A: DDP ReduceOp.SUM Hook + Zero-Sync Host Path -> 0.1316 s/update (1.7786x)
Committed (6b4da23 on opt):
1. DDP ReduceOp.SUM hook (yoco/models/_fast_ddp.py): Registered _bf16_sum_comm_hook when world_size > 1 (eliminating NCCL AVG pre/post /2 division across 240 grad buffers) paired with numer = 1.0 in Trainer.train_step (_fast_optim.py).
2. O(1) grad plan seq check (_get_grad_pairs_and_plan): Cached _fast_grad_ptrs_seq == seq so clip_grad_norm -> g2f skips re-scanning 120 grads per update.
3. Zero-sync stat aggregation (_fast_stat_sync_sum, _reduce_and_log_stats): Replaced blocking pageable torch.tensor(cpu_vals) with a 4-slot (CUDAEvent, pin_memory float64) ring (non_blocking=True), cached (100, 0) clip indicator tensors, and returned {} from _reduce_and_log_stats after logging to metrics (eliminating per-step agg.get_smoothed_values() DtoH syncs; metrics.get_smoothed_values("train_inner") remains intact on log_interval).
4. Investigation of CUDA Graphs (make_graphed_callables): Solved DDP autograd-hook capture via torch.func.functional_call with detached views aliasing bf16_buckets; measured ~17.9 ms gain under deterministic=True (Gate 2 only), but < 0.6 ms (100.71 -> 100.14 ms) under production non-deterministic eager mode (TorchProfile's 52 forward hooks had caused synthetic CPU starvation). Rejected CUDA graphs in favor of real HBM/NVLink/kernel optimizations.

#### Step 6A Measurements (/tmp/r6a_time, /tmp/r6a_quick -> Cleaned)
- bench/bench.py time:
  - s_per_update: 0.1316 s (window_s: [1.317, 1.314], median_update_s: 0.13155, window_range: 0.0019, tokens_per_s: 31130.2)
  - Frozen ref: 0.23407 s -> speedup_vs_frozen_reference: 1.7786x (beyond_reference_noise: true)
  - peak_memory_allocated_gib: 60.91 GiB, compiles_in_window: 0, other_optimizer_steps: [24]
- bench/bench.py check --quick:
  - status: PASS, measured_tier: N1, exact_failures: [], errors: 0, precision_changed: false, bitwise_identical: 1272 / 9616.

### Step 6B: Custom SM90 CUDA Optimizer Extension + Chunked NVLink IPC Pipeline -> 0.1233 s/update (1.8984x)
Built precompiled SM90 CUDA extension (yoco/models/_csrc/fast_optim_cuda.cu, yoco/models/_csrc/build_ext.py -> yoco/models/_fast_optim_cuda.cpython-310-x86_64-linux-gnu.so, compiled -O3 -arch=sm_90 without --use_fast_math) and wired into yoco/models/_fast_optim.py:
1. g2f_vec4_kernel (launch_g2f, scale_chunk=8192, 256 threads): Coalesced uint2 (__ldcg) -> float4 (16B stores) replacing Triton k_g2f (9.62 ms -> 2.486 ms, 4.05 TB/s, bitwise 0.0 vs FP32 multiply).
2. sumsq_vec8_kernel (launch_sumsq, norm_chunk=65536, 256 threads): Deterministic uint4 (__ldcg) + warp shuffle + shared-memory tree reduction replacing Triton k_sumsq (~0.76 ms, 4.43 TB/s, no atomics).
3. adamw_bf16_vec4_kernel + Chunked NVLink P2P IPC Pipeline (launch_adamw_bf16_pipe):
   - Setup CUDA IPC handles + peer access between the two Hopper for peer BF16 weight buckets inside OSS.refresh_trainable.
   - Inside OSS.step, splits the owned flat AdamW + inline BF16 write (float4 / uint2) into K=16 1024-aligned chunks, recording a CUDA event after each chunk and asynchronously DMA-copying that chunk over NVLink via cudaMemcpyAsync(..., p2p_stream) while chunk k+1 computes on comp_stream.
   - OSS._broadcast_params awaits p2p_stream and executes dist.barrier(group=self.group) (14.59 ms pipelined vs 21.80 ms serial AdamW + batch_isend_irecv; bitwise 0.0 vs SendRecv; eliminates Triton JIT warmup -0.5s on cold startup).

#### Step 6B Measurements (/tmp/r6b_time, /tmp/r6b_quick -> Cleaned)
- bench/bench.py time:
  - s_per_update: 0.1233 s (window_s: [1.233, 1.232], median_update_s: 0.1232, window_range: 0.0014, tokens_per_s: 33231.0, slow_update_fraction_rank0: 0.0)
  - Frozen ref: 0.23407 s -> speedup_vs_frozen_reference: 1.8984x (beyond_reference_noise: true)
  - peak_memory_allocated_gib: 60.91 GiB, startup_to_first_update_s: 66.0, compiles_in_window: 0, other_optimizer_steps: [24]
- bench/bench.py check --quick:
  - status: PASS, measured_tier: N1, exact_failures: [], errors: 0, precision_changed: false, bitwise_identical: 1268 / 9616.

### Step 6C-1: Zero-Contention NVLink Copy-Engine P2P DDP & Dual Optimizer Kernels -> 0.1100 s/update (2.1279x)
Committed on opt:
1. FastP2PDataParallel (yoco/models/_fast_ddp.py, yoco/models/_fast_optim.py):
   - Replaces PyTorch DistributedDataParallel on 2-GPU NVLink P2P configurations (normalized torch.device("cuda", current_device) to match bucket keys).
   - Fires asynchronous copy-engine cudaMemcpyAsync(..., p2p_stream) in register_post_accumulate_grad_hook on unowned parameters (120 tensors, 3.42-3.47 GB) directly into the peer's grad_recv_buf allocated via CUDA IPC, eliminating DDP DtoD bucket copies, NCCL SM contention (~7+ ms), and redundant bidirectional AllReduce traffic (50% less NVLink traffic).
   - all_reduce_grads() synchronizes via non-blocking _cuda_opt.stream_wait_stream_raw(comp_raw, p2p_raw) + dist.barrier, matched inside fast_oss_broadcast_params via non-blocking stream_wait_stream_raw + dist.barrier.
2. Dual CUDA Kernels & Ring Buffer (yoco/models/_csrc/fast_optim_cuda.cu):
   - sumsq_dual_vec8_kernel (with __launch_bounds__(256) + 2-way uint4 ILP) and g2f_dual_vec4_kernel read and sum local_grad + peer_grad on the fly inside the owned-shard norm and grad-to-fp32-scale kernels, avoiding extra intermediate BF16 gradient buffers and reducing peak memory (60.91 -> 57.68 GiB).
   - Added 4-slot pinned host buffer ring for dev_src_ptrs H2D copies so async CPU scheduling stays hazard-free.

#### Step 6C-1 Measurements (Cleaned /tmp/r6c1_*)
- bench/bench.py time:
  - s_per_update: 0.1100 s (window_s: [1.101, 1.1], median_update_s: 0.10985, window_range: 0.0007, slow_update_fraction_rank0: 0.0, tokens_per_s: 37227.6)
  - Frozen ref: 0.23407 s -> speedup_vs_frozen_reference: 2.1279x (beyond_reference_noise: true)
  - peak_memory_allocated_gib: 57.68 GiB, compiles_in_window: 0, other_optimizer_steps: [24]
- bench/bench.py check --quick:
  - status: PASS, measured_tier: N1, exact_failures: [], errors: 0, precision_changed: false, bitwise_identical: 1270 / 9616.

### Step 6C-2: Vectorized SM90 CUDA Model Kernels, ChunkGateRecurrent & 50/52 Residual-Add+RMSNorm Fusions -> 0.1069 s/update (2.1896x)
Built precompiled SM90 CUDA extension (yoco/models/_csrc/fast_model_cuda.cu -> yoco/models/_fast_model_cuda.cpython-310-x86_64-linux-gnu.so) and wired into yoco/models/_fast_model.py and yoco/models/_fast_gate.py:
1. prep_qkv_bhsd_{fwd,bwd}: replaces Triton FastPrepQKV (3.05x faster in microbenchmark).
2. gate_prep_256_{fwd,bwd}: 8-warp shuffle prefix scan + reverse cumsum replacing Triton FastGatePrep (2.79x faster).
3. scale_chunk_128_{fwd,bwd} (FastScaleChunk): replaces vc * k_dec[..., None] and its separate BF16 .sum(-1) reduction (2.58x faster, exact FP32 ds).
4. chunk_gate_recurrent_{fwd,bwd} (FastChunkGateRecurrent): single register-resident loop per [B, H, N, D, D] head with inline last-chunk zeroing and direct FP32 dg_part warp+subwarp reduction (0.2866 -> 0.0263 ms/layer = 10.92x vs Triton ChunkGateRecurrent, skipping unused DL allocation).
5. add_subln_swiglu_bshd_{fwd,bwd}: folds q_dec * cross + inner + SubLN RMSNorm + [B,H,S,D]->[B,S,H*D] transpose + SwiGLU + FP32 dq_dec reduction (2.17x faster, removes separate qc * q_dec mul + backward reduce).
6. rotary_interleaved_128 (FastRotaryInterleaved128) & swiglu_bf16_{fwd,bwd} (FastSwiGLU): replaces Triton rotary_kernel (3.52x faster) in CrossDecoder/CrossAttention and jiterator swiglu (removes NVRTC JIT startup overhead).
7. add_rmsnorm_3072_{fwd,bwd} (FastAddRMSNorm, nctas=256): fused Residual-Add + RMSNorm across all interior layers of SelfDecoder.forward and CrossDecoder.forward (50/52 residual adds fused cleanly while keeping single-tensor SelfDecoder/CrossDecoder/YOCO module contracts intact).

#### Step 6C-2 Measurements (/tmp/r6c2_* -> Cleaned)
- bench/bench.py time:
  - s_per_update: 0.1069 s (window_s: [1.069, 1.069], median_update_s: 0.1068, window_range: 0.0001, slow_update_fraction_rank0: 0.0, tokens_per_s: 38305.6)
  - Frozen ref: 0.23407 s -> speedup_vs_frozen_reference: 2.1896x (beyond_reference_noise: true)
  - peak_memory_allocated_gib: 57.68 GiB, compiles_in_window: 0, other_optimizer_steps: [24]
- bench/bench.py check --quick:
  - status: PASS, measured_tier: N1, exact_failures: [], errors: 0, precision_changed: false, bitwise_identical: 1270 / 9616.

### Steps 1de85d6 .. cb09ef5 (GPU IPC Flags, Packed Linears, Sparse Embed, Torch 2.8 + FA3 + RMSNorm3072) -> 0.0912 s/update (2.5666x)
- 1de85d6: GPU-side IPC peer flags, C++ prepare_grad_ptrs_async, direct cuLaunchKernel InnerChunk32, FastChunkKV (2.3129x).
- 43a59e8: Contiguous packed GateRetention (Q/K/V/G/Gt), FFN (fc1/gate), CrossKV (k/v), plus sparse P2P/local embedding gradient scatter (2.3958x).
- 408be3a: Candidate env (/opt/candidate-env Torch 2.8 + Triton 3.4 + FA3) + native FastRMSNorm3072 + adamw_bf16_vec4_p2p_kernel (2.54x).
- cb09ef5: 384-thread RMSNorm backward, direct FA3 calls in CrossAttention, tuned InnerChunk32 tiles, async 32-slot pinned log ring (0.0912 s/update, 2.5666x, PASS).

### Clean Batch A: Cached Heuristic cublasLt BF16 Matmul / BMM + FastLinear (2026-11-20) -> 0.0911 s/update (2.5694x)
- Committed at 99626ef on opt.
- Added lt_matmul_bf16 (yoco/models/_csrc/fast_model_cuda.cu, -lcublasLt in build_ext.py) with 32-entry thread-local cache + best-of-heuristic cublasLtMatmul selection when !det (and REDUCTION_SCHEME_NONE when deterministic).
- Wired _lt_matmul / _fast_lt_linear / _fast_bmm / FastLtBMM across yoco/models/_fast_model.py (ColumnParallelLinear, RowParallelLinear, nn.Linear, FastPackedFFN, FastPackedCrossKV) and yoco/models/_fast_gate.py (FastPackedGateRetentionFn, FastChunkKV, _fast_autograd_bmm).
- Verified Measurements:
  - bench.py time (/tmp/ba_clean_time/time.json, cleaned): 0.0911 s/update (window_s: [0.914, 0.908], median_update_s: 0.08925, 2.5694x, tokens_per_s: 44977.7, peak_memory_allocated_gib: 54.56 GiB, peak_memory_reserved_gib: 49.8 GiB).
  - bench.py check --quick (/tmp/ba_quick/check.json, cleaned): PASS, measured_tier: N1, errors: 0, exact_failures: [], bitwise_identical: 1269 / 9616.

### Batch B: Zero-NCCL NVLink P2P Mailboxes (stat, sumsq+clip, grad_norm) (2026-11-20) -> 0.0907 s/update (2.5807x)
- Added 3 NVLink P2P mailbox kernels (yoco/models/_csrc/fast_optim_cuda.cu): p2p_stat_sync_sum (up to 16 items + 2 CUDA scalar tensors, writing derived total_train_time * 0.5 and inv_denom on GPU), p2p_sumsq_reduce_clip (1024-thread tree reduction + P2P scalar exchange + f64 clip scale directly to scale_buf), and p2p_check_grad_norm_async (f64 norm exchange + finiteness/consistency check + async pinned DtoH).
- Expanded local_flag_ptr IPC buffer (256 -> 4096 bytes, 8-slot cacheline-aligned ping-pong mailboxes), added clip_ring_buf (32 x 2 f64) and _fast_stat_dev_ring (32 x 18 f64) plus fast_multiply_grads and cached _fast_has_sum_hook_cached in yoco/models/_fast_optim.py.
- Verified 2-GPU unit parity across normal/zero-sample/multi-iter/unclipped/clipped/NaN/Inf/mismatch cases with exact cross-rank agreement (test_batch_b.py).
- Verified Measurements:
  - bench.py time (/tmp/bb_time/time.json, cleaned): 0.0907 s/update (window_s: [0.907, 0.907], window_range: 0.0001, median_update_s: 0.08935, 2.5807x, tokens_per_s: 45153.1, peak_memory_allocated_gib: 54.56 GiB, startup_to_first_update_s: 62.8).
  - bench.py check --quick (/tmp/bb_quick/check.json, cleaned): PASS, measured_tier: N1, errors: 0, exact_failures: [], bitwise_identical: 1263 / 9616.
↑ YOCO