Gemini 4 Neon 2.19×

Harness: Antigravity · switches: PYTORCH_ALLOC_CONF=expandable_segments:True OPT_DECODE_GRAPH=1 OPT_DIFFUSION_FAST=1 OPT_TRAIN_FAST=1 OPT_AC_BUDGET_GIB=52.0 OPT_FUSED_KERNELS=1 OPT_TRAIN_FUSED_NORM=1 OPT_OVERLAP_FSDP_REWARD=1 OPT_ROLLOUT_FAST=1 OPT_ROLLOUT_V2=1 OPT_TRAIN_V2=1 OPT_ROLLOUT_V3=1 OPT_TRAIN_V3=1

API stalls passed the 6 h pause allowance, so the lost time was run as a continuation of the same conversation on the saved submission (51 min); the judged result is the continuation's. The time axis leaves out the held time of both segments.

Judged
2.19×
Tier
N0
Self-best
2.16×
Rounds
8
Hours
10.0
API cost
$73.7
Input tokens · 95.5% cached
196 M
Output tokens
1.3 M
Requests
664
Text-decode CUDA graph
✓ OPT_DECODE_GRAPH, round 1 full check 1.25× (first attempt hit a 740 MiB backward OOM; passed after reusing one stream, g.reset() and expandable segments); top-p prep moved into the graph in round 4, one-step async pipeline in round 6, persistent graph pool + manual capture_begin/capture_end in round 7
Reward wait hidden behind forward
✓ round 3 moves packing and the reference-model forward before the wait, advantages filled in afterwards; round 5 OPT_OVERLAP_FSDP_REWARD also moves the policy forward and the advantage-independent loss terms (together with train-side fusion, full check 1.85× → 1.99×)
Rollout-side bitwise fused kernels
✓ round 2 Triton pure-copy scatter / split; round 4 custom CUDA extension r3_fused_ops: RMSNorm (with residual add), q/k norm + RoPE + scatter (21 kernels per denoise layer → 1), SwiGLU, also wired into training in the same round, full check 1.55× → 1.85×; round 8 gate/up concat + fused SwiGLU
Train-side bitwise kernels / freeing memory
✓ round 3 reference model keeps bf16 params only and reshards after forward, peak 130.76 → 112.18 GiB, freed memory spent on less recompute per layer under a budget (OPT_AC_BUDGET_GIB); round 5 train-side RMSNorm, q/k norm + RoPE + scatter fwd/bwd (OPT_TRAIN_FUSED_NORM), all 13 full-recompute layers in the refine step removed; round 8 custom single-pass AdamW (83.08 → 29.13 ms/step); final peak 121.77 GiB
Other main levers
round 2 denoise desync + pre-merged KV, CFG text context shared zero-copy (no repeated VAE + ViT + LLM prefill), full check 1.25× → 1.49×; frozen-ViT dedup of repeated images, block mask / ViT output shared between reference and policy (round 3); CFG branch batching, create_block_mask(H=None) (round 6 → 2.05×); refine image context B=1 broadcast, step-0 CFG merge (round 7 → 2.10×); policy model kept unsharded from rollout on (round 8 → 2.16×); denoise CUDA graph measured only 4.35 ms faster per forward, not used
Raw work log18 sections
-8.1 hRound 1: Baseline Profile & Text Generation Rollout (Host/Sync + CUDA Graphs)
- Start: 2026-11-19 19:40:50 UTC

### Baseline Profile Findings (/tmp/prof-ref-r1, steps 6–7, Gen + Refine)
- Total trace span: 62.61s (instrumented; uninstrumented steps 10–11 = 46.2s pair: Gen 14.5s, Refine 31.7s)
- GPU active time (union): 26.95s (43.0% of wall clock — heavily host/sync-bound)
- CUDA runtime overhead (2 steps):
  - cudaLaunchKernel: 1,466,461 calls (9.03s)
  - cudaStreamSynchronize: 269,373 calls (8.54s) — aten::_local_scalar_dense: 250,220 calls (9.27s CPU), aten::nonzero: 19,405 calls (1.47s CPU)
  - cudaFree + cudaMalloc: 419 + 428 calls (1.73s) from 4x torch.cuda.empty_cache() per step
  - cudaMemcpyAsync: 280,253 calls (1.21s)
- Stage breakdown (uninstrumented steady-state Gen+Refine pair, ~46.6s):
  1. Text rollout (generate_text_batch): ~15.5–17.5s (~35% of pair, incl. 2–4s rank straggling in Refine). Only 18–19% GPU utilization (35 tok/s; GEMMs + flash_fwd_splitkv only need ~2.7s GPU time across both steps!). Kind 2 (Launch/Sync): 84+ .item() syncs/token in _static_kv_cache_attention + 17 syncs/token in generate_text_batch + eager Python launches.
  2. Image diffusion rollout (edit_image + generate_image_with_think + _forward_flow): ~19–20s (~42% of pair). 61–67% GPU utilization (37k kernels/s). Kind 2/3 (Sync + Layout/Copy + Redundant Compute): _merge_static_kv_prefix_and_query does 7 .item() + 4 nonzero syncs + full KV cache copy per layer × 28 layers × 90 passes; edit_image runs duplicate VAE+ViT+28-layer LLM prefill for cfg_text_context; mode="gen" scatters/gathers 4096 VAE vs 8 text tokens 10× per layer.
  3. Training step (ref_model + fsdp_model + backward + AdamW): ~9.7s (~21% of pair: Gen 2.1s, Refine 7.6s). 95–100% GPU utilization. Kind 2/3 (Recompute + Redundant Compute + Layout): Full Activation Checkpointing on all 28 layers (ref_model kept in fp32 + unsharded bf16 wastes ~36 GiB VRAM); duplicate frozen vit_model forward (12 images) and duplicate create_block_mask in ref_model and fsdp_model; und/gen scatter-gather between layers.
  4. Reward wait + empty_cache + all_gather idle gaps: ~2.5s (two ~1.25s 0%-GPU gaps).
-8.1 hPlanned Round 1 Change
- Target hotspot #1: Text rollout (generate_text_batch + _static_kv_cache_attention)
- Switch: OPT_DECODE_GRAPH=1 (off by default)
- Remove per-layer syncs in _static_kv_cache_attention, eliminate 16/17 syncs/token in generate_text_batch, and capture CUDA graphs per active batch size for the 28-layer decode + lm_head forward pass.
-8.1 hRound 1 Results
- End: 2026-11-20 03:13 UTC (finished 2026-11-19 20:49:53 UTC)
- Changed: modeling/bagel/qwen2_navit.py (Qwen2ForCausalLM.decode_step_static_cache), modeling/bagel/bagel.py (Bagel._generate_text_batch_graph), gated behind OPT_DECODE_GRAPH=1 (+ PYTORCH_ALLOC_CONF=expandable_segments:True).
- Note on first attempt (/tmp/check-r1, deleted): Creating a new torch.cuda.Stream() per call and not calling g.reset() caused ~740 MiB OOM on step 1 backward (3.58 GiB reserved unallocated fragmentation). Reusing a single _decode_warmup_stream, calling g.reset() in finally:, and enabling PYTORCH_ALLOC_CONF=expandable_segments:True resolved it completely (peak 130.76 GiB vs ref 130.72 GiB).
- Full check (/tmp/check-r1b): PASS (N0 bitwise identical: 3200/3200 tensors, 235/235 reward requests)
  - Windows [10-11, 12-13, 14-15]: [18.4424, 18.9967, 18.4511] s/step (mean 18.6301 s/step vs ref 23.3224 s/step; Gen ~11.9s, Refine ~25.2s)
  - Window ratios: [1.2405, 1.2420, 1.2734] -> speedup = 1.2520
- Committed to /submission/r3 (opt) and activated in /submission/switches.json.

---
-0.2 hRound 2: Diffusion Flow Rollout, Zero-Copy CFG Prefix Views & ViT Reuse (`OPT_DIFFUSION_FAST=1`)
- Start: 2026-11-20 03:15 UTC
- End: 2026-11-20 03:56:32 UTC

### Target & Findings
- Post-Round-1 bottleneck #1: Diffusion rollout (~22.4s/pair, ~60% of wall clock).
- Root causes:
  1. bagel.py (torch.tensor([t] * x_t.shape[0])) triggered 4,096 .item() syncs per denoising step (~143,360/pair).
  2. _merge_static_kv_prefix_and_query did 7 .item() + 4 nonzero syncs + full static prefix copy per layer × 28 layers × ~81 diffusion passes/pair.
  3. Qwen2MoTDecoderLayer.forward_inference(mode='gen') did 10+ full-sequence zeros_like + gather/scatter ops per layer to separate 8 BOI/EOI text tokens from 4,096 VAE tokens (~1.26 TB/pair traffic).
  4. edit_image ran update_context_image(..., vae=True, vit=True) twice (duplicate VAE+ViT+28-layer LLM prefill for cfg_text_context), did 2× large deepcopys of StaticKVCache, and recomputed frozen ViT embeddings already computed in get_edit_think_and_operation.
- Micro-benchmark (bench_flow.py, 28 layers): eager Split-MoT + Prebuilt-KV + pure-copy Triton scatter/split improved 251.46 -> 138.95 ms/pass (1.81×, bitwise N0). Diffusion CUDA Graph only added 4.35 ms/pass (outweighed by ~280ms×3 capture cost/step) so was intentionally not used. time_embedder(t.unsqueeze(0)).expand(4096, -1) was rejected due to 7.63e-6 cuBLAS tile drift (kept t.expand(4096) which is bitwise N0).

### Changes (OPT_DIFFUSION_FAST=1)
- modeling/bagel/opt_kernels.py: pure bf16 load/store Triton kernels scatter_qkv_gen and split_attn_gen.
- modeling/bagel/qwen2_navit.py: StaticKVCache.readonly_view(), StaticFlowKVWorkspace (pre-allocates merged K/V and copies static prefix once before denoising loop), Qwen2ForCausalLM.forward_flow_branch_fast (keeps (h_text, h_vae) split across all 28 layers), and _prefill_meta fast path in _static_kv_cache_attention / Qwen2Model.forward_inference.
- modeling/bagel/bagel.py: _prepare_flow_fast_context, _forward_flow_fast (using t.expand(N) + hoisted h_text_init/packed_pos_embed/timesteps_cpu), wired into generate_image, generate_image_sde, generate_image_mix; optional cached_vit_embeds reuse in forward_cache_update_vit.
- train/rollout_controller.py: zero-copy readonly_view() for cfg_text_context in generate_image_with_think and edit_image (eliminates duplicate VAE+ViT+LLM prefill and deepcopys), compact max_cache_len for cfg_img_context, and identity-checked ViT embedding cache from get_edit_think_and_operation -> edit_image (cleared immediately after use and in context() finally:).
-0.2 hRound 2 Results
- Unit bitwise test (test_r2_bitwise.py): 14/14 PASS (both deterministic=False and deterministic=True).
- Full check (/tmp/check-r2/check.json): PASS (N0 bitwise identical: 3200/3200 tensors, 235/235 reward requests)
  - Windows [10-11, 12-13, 14-15]: [15.1728, 15.9887, 15.9314] s/step (mean 15.6976 s/step vs ref 23.3224 s/step; Gen ~9.8s, Refine ~21.4s)
  - Window ratios: [1.5078, 1.4756, 1.4748] -> speedup = 1.4861
  - Peak allocated memory: 130.76 GiB (reserved 133.72 GiB)
- Committed to /submission/r3 (opt) and activated in /submission/switches.json.

---
0.7 hRound 3: Training Step, Memory Headroom, Reward Overlap & Zero-Sync Packing (`OPT_TRAIN_FAST=1`)
- Start: 2026-11-20 04:10 UTC
- End: 2026-11-20 04:51:21 UTC

### Post-Round-2 Profile Findings (/tmp/prof-r2, steps 10–11, Gen + Refine)
- Trace span: 31.97s, GPU active: 24.48s (76.6%).
- Major remaining bottlenecks uncovered:
  1. cudaFree (1.120s, 431x) + cudaMalloc (1.018s, 432x) = 2.14s/pair from 3x torch.cuda.empty_cache() per step.
  2. 36,976 aten::_local_scalar_dense syncs (~532ms CPU) in rollout_controller.py pack_batch from torch.tensor([cuda_scalar] * N) on packed_timesteps, dts, packed_timesteps_for_loss.
  3. 1.12s + 0.32s zero-GPU reward HTTP wait gaps after rollout.
  4. Refine training step ([23-31s]): index_put_ (380ms) + gather (133ms) + pad_sequence CatArrayBatchedCopy (128ms) + direct_copy (168ms) + duplicate create_block_mask (114ms) + duplicate 27-layer frozen vit_model (12 identical images) + full AC on all 28 layers (ref_model kept fp32 + unsharded bf16 wasted 35.5 GiB).
- Probes (probe_r3.py, probe_r3_part2.py, probe_fsdp2_r3.py):
  - flex_attention = torch.compile(flex_attention, dynamic=True) had max_diff=9.77e-4 (non-N0 -> rejected).
  - pad_sequence skip when pad_size == 0 -> bitwise N0.
  - 27-layer SigLIP ViT B=1 repeated 4x/12x vs B=4/B=12 -> bitwise N0 (max_diff=0.0) in both det=False/True.
  - 4-GPU FSDP2 ref_model param-only bf16 + FULL_SHARD(reshard_after_forward=True) and fsdp_model FULL_SHARD + Split-MoT + dynamic AC (full/mlp_only/none) -> bitwise N0 (max_diff=0.0).
  - Single-layer Refine (L=38,912) benchmark: upstream full AC 178.85 ms/layer -> Split-MoT full AC 160.96 ms/layer -> Split-MoT mlp_only AC 148.78 ms/layer (+3.05 GiB) -> Split-MoT no_ac 124.92 ms/layer (+9.32 GiB).

### Changes (OPT_TRAIN_FAST=1)
- modeling/bagel/opt_kernels.py: pure-copy Triton autograd kernels ScatterQkvMotTrainFn, SplitAttnMotTrainFn, SplitHiddenMotFn, MergeHiddenMotFn.
- modeling/bagel/qwen2_navit.py: Qwen2MoTDecoderLayer.forward_train_split + dynamic per-step AC scheduler in Qwen2Model.forward_train (allocates mlp_only/none from layer 27 down using OPT_AC_BUDGET_GIB=48.0, so saved activations free before full AC recompute spikes); pad_sequence fast path for pad_size == 0.
- modeling/bagel/bagel.py: frozen ViT identical-image deduplication (_run_vit_model), plus shared precomputed_block_mask and precomputed_vit_output forwarding from ref_model to fsdp_model.
- train/fsdp2_utils.py: skip static CheckpointWrapper (replaced by dynamic AC) and remove torch.cuda.empty_cache() in fsdp2_rollout_context.
- train/rollout_controller.py: remove torch.cuda.empty_cache() in context(), fix 37k .item() syncs via _materialize_scalar_runs, memoize PIL/patchify transforms in pack_batch, and add defer_advantages/populate_advantages.
- train/online_rl.py: param-only bf16 ref_model + FULL_SHARD(reshard_after_forward=True) on ref_model/fsdp_model; overlap reward HTTP futures with prepack + pack_batch + ref_model (torch.no_grad() so shared BlockMask/ViT are normal tensors); share block_mask + frozen ViT output with fsdp_model; defer non-control-flow .item() logging syncs and fuse loss_dict/stats all_reduces.
0.7 hRound 3 Results
- 4-GPU FSDP2 E2E bitwise test (test_r3_e2e_fsdp2.py): PASS (all logits, mse, grad norm, post-AdamW params bitwise identical).
- Full check (/tmp/check-r3/check.json): PASS (N0 bitwise identical: 3200/3200 tensors, 235/235 reward requests)
  - Windows [10-11, 12-13, 14-15]: [14.8194, 15.2758, 15.1335] s/step (mean 15.0762 s/step vs ref 23.3224 s/step; Gen ~9.4s, Refine ~20.6s)
  - Window ratios: [1.5438, 1.5445, 1.5525] -> speedup = 1.5470
  - Peak allocated memory: 112.18 GiB (down 18.58 GiB from 130.76 GiB!)
- Committed to /submission/r3 (opt, commit b329096) and activated in /submission/switches.json.

---
1.5 hRound 4: Bitwise-Exact Custom CUDA Kernels & Graphed Top-P Prep (`OPT_FUSED_KERNELS=1`)
- Start: 2026-11-20 04:53 UTC
- End: 2026-11-20 05:37:07 UTC

### Target & Findings
- Post-Round-3 remaining kernel-launch and HBM-bandwidth hotspots across Decode, Diffusion Flow, and Training (ref_model & fsdp_model):
  1. Unfused PyTorch Qwen2RMSNorm (3584) + residual add: 8 kernels/norm reading/writing fp32 intermediates across 28 layers × (Decode + 81 Diffusion passes + Training).
  2. Unfused q_norm/k_norm (128) + apply_rotary_pos_emb + scatter: 21 kernels/layer + ~1.1 GB HBM/layer in Diffusion Flow, 14 kernels/layer in Training fwd+bwd, 26 kernels/layer in ref_model.
  3. Unfused F.silu(gate) * up (SwiGLU) forward and backward: extra HBM passes + saving sig_gate (1.37 GiB/no-AC Refine layer).
  4. Top-p sampling prep (topk(1000), logsumexp, cumsum, masked_fill, F.softmax) running eagerly outside the Decode CUDA Graph on every token.
- Exact PyTorch Reduce.cuh (setReduceConfig) analysis verified exact reduction order (N=3584: vec4 4-acc + shared-mem tree + ascending shfl_down(1,2,4,8,16) + float(1.0/3584.0); N=128: scalar vt0=4, stride=bw with bw=32/64/128 so rotate_half partners live in the same warp thread registers; SwiGLU bwd dg = __fmul_rn(__fmul_rn(dsg, sig), fmaf(gf, 1.0f - sig, 1.0f))).
- 28-layer E2E micro-benchmarks (test_r4_e2e.py):
  - Diffusion Flow: 138.56 -> 110.40 ms/pass (2.28× faster than upstream's 251.46 ms), 100% bitwise N0.
  - Decode CUDA Graph (64 tok): 621.4 -> 445.2 ms (103.0 -> 143.8 tok/s, +40% faster on top of R1), 100% bitwise N0.
  - Note: first check attempt with OPT_AC_BUDGET_GIB=64.0 hit a 740 MiB OOM on step 1 backward (123.6 GiB allocated + 10.1 GiB reserved unallocated); keeping OPT_AC_BUDGET_GIB=48.0 avoided the OOM completely (5 extra mlp_only layers only save ~30 ms/step).

### Changes (OPT_FUSED_KERNELS=1)
- modeling/bagel/csrc/fused_ops.cu & setup.py: pre-built CUDA C++ extension r3_fused_ops installed into /opt/candidate-env (nvcc 12.8 -O3 --fmad=false -gencode=arch=compute_90,code=sm_90, 0.0s cold compile):
  - rmsnorm_3584_bf16, add_rmsnorm_3584_bf16 (exact Reduce.cuh + smem row cache)
  - fused_qknorm_rope_scatter_gen (1 register-only kernel replacing 21 kernels/layer in Diffusion Flow)
  - fused_qknorm_rope_128_bf16 (exact BW=32/64/128 QK-Norm + RoPE for Decode)
  - fused_swiglu_bf16, fused_swiglu_bwd_bf16 (vectorized 128-bit uint4, exact FMA bwd)
  - fused_rope_scatter_mot_train_fwd, fused_rope_scatter_mot_train_bwd (replaces 14 RoPE+scatter/gather kernels in training)
  - fused_qknorm_rope_scatter_mot_ref (replaces 26 kernels/layer in ref_model)
- modeling/bagel/opt_kernels.py: get_fused_ops(), FusedSwiGLUBf16Fn, FusedRopeScatterMotTrainFn.
- modeling/bagel/qwen2_navit.py: wired fused kernels into forward_flow_branch_fast (residual-fused across 28 layers), decode_step_static_cache (residual-fused across 28 layers), and forward_train_split (ref_model & fsdp_model); lowered upgrade_no_ac from 6.27 -> 4.90 when OPT_FUSED_KERNELS=1.
- modeling/bagel/bagel.py: captured _decode_and_prep_topp (topk(1000) + logsumexp + filtered_probs + F.softmax) inside the Decode CUDA Graph.
1.5 hRound 4 Results
- Unit & 28-layer E2E bitwise tests (test_r4_kernels.py, test_r4_e2e.py): 100% PASS (0 bits diff across all shapes, both deterministic=False and deterministic=True).
- Full check (/tmp/check-r4/check.json): PASS (N0 bitwise identical: 3200/3200 tensors, 235/235 reward requests)
  - Windows [10-11, 12-13, 14-15]: [12.0956, 13.1320, 12.6362] s/step (mean 12.6213 s/step vs ref 23.3224 s/step; Gen ~7.45–8.47s, Refine ~16.74–17.80s)
  - Window ratios: [1.8914, 1.7966, 1.8594] -> speedup = 1.8492
  - Peak allocated memory: 110.77 GiB (timing) / 110.37 GiB (record) — down 1.41 GiB from R3 and 20.0 GiB below ref!
- Committed to /submission/r3 (opt, commit 0c011d0) and activated in /submission/switches.json.

---
2.4 hRound 5: Bitwise-Exact Training Fused RMSNorm/QKNorm+RoPE+Scatter & FSDP-Reward Overlap (`OPT_TRAIN_FUSED_NORM=1`, `OPT_OVERLAP_FSDP_REWARD=1`)
- Start: 2026-11-20 05:49 UTC
- End: 2026-11-20 06:32:14 UTC

### Post-Round-4 Profile Findings (/tmp/prof-r4, steps 10–11, Gen + Refine)
- Trace span: 24.738s, GPU active: 20.657s (83.5% of wall clock).
- Major remaining training & wait bottlenecks uncovered:
  1. Unfused PyTorch Qwen2RMSNorm (3584) + q_norm/k_norm (128) in fsdp_model training: ~737 ms of Refine training kernels (OTHER = 856 ms) + ~200 ms on Gen, AND saved 400 MB/RMSNorm + 1259 MB/QKNorm of fp32 intermediates forcing mlp_only AC to cost 2.79 GiB/layer (leaving 13 Refine layers in full AC).
  2. Hidden torch.cuda.empty_cache() in RolloutBuffer.all_gather() (train/online_rl.py:528) causing cudaFree (664ms) + cudaMalloc (574ms) allocator thrashing (FSDP::all_gather (layers.19) blocked 168ms in cudaMalloc).
  3. Reward HTTP & rank-straggle wait gaps: 1.280 s zero-GPU idle gap on Gen waiting for per_round_reward.result() and 1.040 s exposed AllReduce stall on Refine waiting for slower ranks' reward workers.
- Note on FSDP2 FULL_SHARD vs SHARD_GRAD_OP: trace showed fsdp_model forward/backward AllGather was already 95–99% overlapped (< 23 ms exposed), so keeping FULL_SHARD and spending the freed HBM on eliminating full AC layers + allocator headroom is strictly better.
- Unit & full-layer benchmarks (test_r5_kernels.py, bench_r5_layer.py, Refine L=38912):
  - FusedRMSNorm3584TrainFn: 7.98× faster (2.817 -> 0.353 ms), saved memory 400.1 -> 1.1 MB, 0 bits diff (det=False/True).
  - FusedQKNormRopeScatterMotTrainFn: 5.82× faster (8.256 -> 1.419 ms), saved memory 1258.8 -> 347.3 MB, 0 bits diff (det=False/True).
  - Full Qwen2MoTDecoderLayer: mlp_only saved memory dropped 2.79 -> 1.42 GiB/layer (all 28 Refine layers fit without full AC!) and backward peak_delta dropped 9.78 -> 7.37 GiB (-2.41 GiB); 100% bitwise N0 across all params and AC modes.

### Changes (OPT_TRAIN_FUSED_NORM=1, OPT_OVERLAP_FSDP_REWARD=1)
- modeling/bagel/csrc/fused_ops.cu: added 4 bitwise-exact CUDA kernels (rmsnorm_3584_fwd_rstd_bf16, rmsnorm_3584_bwd_bf16 matching PyTorch 1.0 / 3584.0 reciprocal multiply + exact prod = dout * y_norm_bf16, fused_qknorm_rope_scatter_mot_train_fwd, fused_qknorm_rope_scatter_mot_train_bwd), rebuilt into /opt/candidate-env (r3_fused_ops).
- modeling/bagel/opt_kernels.py: FusedRMSNorm3584TrainFn and FusedQKNormRopeScatterMotTrainFn (calling exact PyTorch .sum(...) on prod for guaranteed bitwise-exact dw).
- modeling/bagel/qwen2_navit.py: wired fused training norms + QK-Norm+RoPE+Scatter into Qwen2MoTDecoderLayer.forward_train_split and final norm/norm_moe_gen in Qwen2Model.forward_train; recalibrated dynamic AC costs (cost_mlp=1.45, upgrade_no_ac=4.45) with OPT_AC_BUDGET_GIB=52.0 (eliminates all 13 full AC layers on Refine + upgrades 2 Refine / 20 Gen layers to no_ac).
- train/online_rl.py: fused RolloutBuffer.all_gather() into a single all_gather_object without redundant dist.barrier() or torch.cuda.empty_cache(); moved fsdp_model forward and all advantage-independent loss ops (log_softmax, gather_text_policy_logps, per_token_kl, apply_cfg, get_x_t_distribution, log_prob, kl_img_loss) before per_round_reward.result() so GPU training overlaps asynchronously with GenEval HTTP latency.
2.4 hRound 5 Results
- Full check (/tmp/check-r5/check.json): PASS (N0 bitwise identical: 3200/3200 tensors, 235/235 reward requests)
  - Windows [10-11, 12-13, 14-15]: [10.9622, 12.0606, 12.1529] s/step (mean 11.7253 s/step vs ref 23.3224 s/step; Gen ~7.11–7.73s, Refine ~14.81–16.61s)
  - Window ratios: [2.0870, 1.9563, 1.9333] -> speedup = 1.9922
  - Peak allocated memory: 119.31 GiB (timing) / 118.89 GiB (record)
- Committed to /submission/r3 (opt, commit bd87b80) and activated in /submission/switches.json.

---
3.6 hRound 6: Pipelined Decode CUDA Graph, Batched CFG Flow, Fused Prefill & `create_block_mask(H=None)` (`OPT_ROLLOUT_FAST=1`)
- Start: 2026-11-20 06:34 UTC
- End: 2026-11-20 07:44:46 UTC

### Target & Findings
- Rollout (Decode + Diffusion Flow + Prefill) accounted for ~70% of remaining wall clock after Round 5.
- Probes (probe_r6.py, probe_r6_gpu.py, probe_r6_e2e.py, probe_r6_flow_prefill.py):
  1. Decode 1-token async pipeline (bagel.py): Upstream EOS dropout checks curr_tokens[orig_idx] == end_token_id (input token, known at step k-1), NOT next_tokens (output token of step k). Capturing torch.multinomial (register_generator_state), gather, and s_tok/s_pos/s_sl updates inside the CUDA graph lets step k+1 launch on GPU before reading step k's pinned D2H next_tokens (6.51 -> 5.97 ms/tok, 100% bitwise N0 on seq/probs/kv/rng across staggered EOS and forced max_length-1 EOS).
  2. Rollout horizontal KV_cat (k_proj + v_proj, 512+512->1024, bias=True): 2.0× faster pure GPU (13.6 -> 7.0 us/layer) at M=1..24, bitwise N0 on _KV_CAT_SAFE_M = {1, 2, 3, 4, 8, 16, 24, 2048, 2052, 4096, 4104, 8192, 12288} (det=False/True), but differs by 1–2 ULPs at M ∈ [100..200] (caught in first Round 6 check at Eval Round 0 prompt prefill -> fixed via strict _KV_CAT_SAFE_M whitelist).
  3. Batched CFG Diffusion Flow: Merging 2-branch Gen (B=8) and 3-branch Refine (B=12) into one StaticFlowKVWorkspace with zero-copy cond_view(), Layer-0 shared QKV (src_b_mod=4), forced_bw=64 text RMSNorm, down_proj 16+8 split at M=24, and Layer-27 dead text skip saved +10.14 ms/step on Gen and +14.09 ms/step on Refine (0 bits diff).
  4. Fused Prefill (Qwen2Model.forward_inference): Residual-fused mode="und" (126.05 -> 104.05 ms, 0 bits diff) and Split-MoT mode="gen" (150.28 -> 109.22 ms, 0 bits diff).
  5. create_block_mask(..., H=None): 3.0× faster (17.11 -> 5.61 ms at L=38912), 0 bits diff across flex_attention fwd+bwd.

### Changes (OPT_ROLLOUT_FAST=1)
- modeling/bagel/csrc/fused_ops.cu: added rmsnorm_3584_bw_bf16 / add_rmsnorm_3584_bw_bf16 (explicit forced_bw matching single-branch M=8's BW=64), fused_qknorm_rope_scatter_gen_ex (src_b_mod for Layer-0 shared QKV + zero-copy strided KV inputs), and strided dim-0 support in fused_qknorm_rope_128_bf16; rebuilt r3_fused_ops in /opt/candidate-env.
- train/fsdp2_utils.py: create temporary _rollout_wkv/_rollout_bkv & _rollout_wkv_gen/_rollout_bkv_gen (410 MB total) on fsdp2_rollout_context entry and delete before reshard() (0 training memory overhead).
- modeling/bagel/qwen2_navit.py: StaticFlowKVWorkspace.from_branches() & cond_view(); Batched CFG + Layer-0 shared QKV + Layer-27 dead text skip in forward_flow_branch_fast; _KV_CAT_SAFE_M-guarded KV_cat in Decode, Flow, and Prefill; residual-fused mode="und" and Split-MoT mode="gen" in Qwen2Model.forward_inference.
- modeling/bagel/bagel.py: create_block_mask(..., H=None); Batched CFG wiring in _prepare_flow_fast_context / _forward_flow_fast (B=4); 1-token async pipelined Decode CUDA Graph in _generate_text_batch_graph.
3.6 hRound 6 Results
- 28-layer E2E bitwise test (test_r6_e2e.py): 100% PASS (det=False/True).
- Full check (/tmp/check-r6/check.json): PASS (N0 bitwise identical: 3200/3200 tensors, 235/235 reward requests)
  - Windows [10-11, 12-13, 14-15]: [10.6422, 11.8629, 11.7516] s/step (mean 11.4189 s/step vs ref 23.3224 s/step; Gen ~6.62–7.67s, Refine ~14.06–16.08s)
  - Window ratios: [2.1498, 1.9889, 1.9993] -> speedup = 2.0460
  - Peak allocated memory: 119.28 GiB (timing) / 118.84 GiB (record)
- Committed to /submission/r3 (opt, commit b0c0656) and activated in /submission/switches.json.

---
6.8 hRound 7: Anchored Decode Graph Pool, B=1 VAE/ViT Dedup, Step-0 CFG, Unsharded Shared ViT & Zero-Sync Training (`OPT_ROLLOUT_V2=1`, `OPT_TRAIN_V2=1`)
- Start: 2026-11-20 08:20 UTC
- End: 2026-11-20 10:55 UTC

### Target & Findings
- Post-Round-6 profile (prof-r6, 21.438s pair) revealed:
  1. with torch.cuda.graph(...) unconditionally calls gc.collect() (~40 ms × 8) and torch.cuda.empty_cache(), flushing 50+ GiB of warm caching-allocator blocks 8×/pair and causing 964.5 ms cudaMalloc + 840.3 ms cudaFree thrashing in Refine forward/backward.
  2. torch.set_default_device("cuda") placed all 800 AdamW state["step"] tensors on CUDA, triggering 1,600 synchronous aten::item -> cudaStreamSynchronize stalls per optimizer step (~128 ms/pair).
  3. img_latent_lengths list comprehension on CUDA tensor triggered 8 synchronous aten::item + aten::is_nonzero stalls.
  4. fsdp2_rollout_context and ref_model unsharded/resharded all 27 frozen SiglipEncoderLayers every step (79 ms on Refine + wasted AllGathers on Gen).
  5. Refine ran redundant vae_transform/vit_transform 4× on identical input_imgs, forward_cache_update_vae (M=4104) and forward_cache_update_vit (M=2312) on 4 identical inputs, and Step-0 cfg_text on 4 identical initial latents.
  6. 3×–4× redundant Image.fromarray(img[i]) copies (72 ms Gen + 117 ms Refine GPU idle gaps) delayed reward_fn HTTP submission on Gen's reward-server-bound critical path.

### Changes (OPT_ROLLOUT_V2=1, OPT_TRAIN_V2=1, OPT_AC_BUDGET_GIB=42.0)
- modeling/bagel/qwen2_navit.py: StaticKVCache.broadcast_slot0() & _all_slots_identical; StaticFlowKVWorkspace.step0_view(); num_seqs >= 1 + forced_text_bw in Qwen2Model.forward_inference; shared_l0 remainder handling in forward_flow_branch_fast; expanded _KV_CAT_SAFE_M with (10, 18, 578, 1024, 1026, 5120, 9216) (all verified N0).
- modeling/bagel/bagel.py: deduped transforms(image) in prepare_vit_images/prepare_vae_images; dedup_b1=True in forward_cache_update_vae & forward_cache_update_vit (broadcasting from actual_start = int(past_key_values.seq_lens[0].item()) to match upstream StaticKVCache write offset!); Step i=0 cfg_text B=4->1 via zero-copy ws_cfg_step0 (B=5 Gen, B=9 Refine with cfg_text_last=True); Decode use_v2 using a persistent anchored 64 MiB graph_pool + direct g.capture_begin/g.capture_end (zero gc.collect(), zero empty_cache() except < 512 MiB OS-VRAM guard for cudaGraphInstantiate), 1-time warmup per (device, num_active), and immediate capture ((max_length - step) >= 3).
- train/rollout_controller.py: dedup_b1 orchestration & skip prepare_vit_images on _cached_vit_embeds hit; single pinned CPU D2H copy in decode_image; single Image.fromarray per sample; early reward_submit_fn right after decode_image; CPU loss_info['_img_latent_lengths'].
- train/fsdp2_utils.py: apply_fsdp2_with_activation_checkpointing(..., skip_vit=True) (ignored_params=set(model.vit_model.parameters())) + _vit_bf16_cast_pre_hook on SiglipEncoderLayer (matching FSDP2 cast_forward_inputs=True during training/ref and bypassed during fsdp2_rollout_context).
- train/online_rl.py: unsharded shared bf16 frozen vit_model across fsdp_model & ref_model; with torch.device("cpu"): optimizer.step(); CPU _img_latent_lengths; batched avg_vals.tolist(); fused 2-element mem stats all_reduce.

### Bugs Caught & Fixed
- Padded B=4 decode graph diverged from exact num_active after EOS dropout -> switched to exact-num_active graphs in persistent anchored pool.
- broadcast_slot0 initially used key_values_lens[0] (1026) instead of past_key_values.seq_lens[0] (0, matching upstream update_context_image which syncs seq_lens after both VAE and ViT) -> fixed to actual_start = int(past_key_values.seq_lens[0].item()).
- cudaGraphInstantiate in g.capture_end() hit CUDA OOM in deterministic record mode when expandable_segments:True reserved 135.9 GiB leaving < 16 MiB OS VRAM -> fixed with persistent anchored 64 MiB pool + < 512 MiB mem_get_info guard + OOM retry.
6.8 hRound 7 Results
- Full check (/tmp/check-r7e/check.json): PASS (N0 bitwise identical: 3200/3200 tensors, 235/235 reward requests)
  - Windows [10-11, 12-13, 14-15]: [10.6065, 11.3325, 11.4275] s/step (mean 11.1222 s/step vs ref 23.3224 s/step; earlier r7c/r7d timing runs measured 2.1225x / 2.1173x)
  - Window ratios: [2.1570, 2.0819, 2.0560] -> speedup = 2.0983
  - Peak allocated memory: 115.11 GiB (timing) / 114.71 GiB (record) — 4.17 GiB lower than Round 6!
- Committed to /submission/r3 (opt, commit 8a6046e) and activated in /submission/switches.json.

---
7.4 hRound 8: Rollout `GU_cat`, FSDP2 `keep_unsharded` + Dynamic Reshard, Zero-Duplicate Training Autograd & Single-Pass Bitwise-Exact CUDA AdamW (`OPT_ROLLOUT_V3=1`, `OPT_TRAIN_V3=1`)
- Start: 2026-11-20 10:57 UTC
- End: 2026-11-20 11:33 UTC

### Target & Findings
- Probes (probe_r8.py, test_r8_kernels.py, test_r8_e2e.py):
  1. Horizontal GU_cat (cat([W_gate, W_up]), 3584 -> 37888): 100% bitwise N0 across all M ∈ {1..12288} (det=False/True), and +33.5–38.3 us/layer faster at small M ∈ {1, 2, 3, 4, 8, 16, 24} (lifts SM utilization from 99/132 = 75% to full GPU saturation across 26,000+ Decode GEMMs/pair).
  2. FSDP2 keep_unsharded=True across Rollout -> Training Forward + Gen reshard_after_forward=False: FSDP2's unshard() is a no-op when self.is_unsharded is already True, and init_unsharded_param() sets requires_grad=self.sharded_param.requires_grad even under no_grad(). Keeping fsdp_model unsharded out of fsdp2_rollout_context eliminates all fsdp_model forward AllGathers on BOTH Gen and Refine for +0.0 GiB peak VRAM on Refine (since Layer k reshards immediately after Layer k forward, while "none" layers sit at the end), and disabling reshard_after_forward on Gen eliminates Gen backward AllGathers too.
  3. Zero-Duplicate Training Autograd (FusedSplitAttnOProjFn + FusedSwiGLUDownProjFn + FusedAddRMSNorm3584TrainFn):
     - FusedSplitAttnOProjFn reuses attn_out already saved by flex_attention instead of saving duplicate (ao_u, ao_g) for o_proj/o_proj_moe_gen (-0.26 GiB * scale per layer across all 28 layers = -6 GiB on Refine!).
     - FusedSwiGLUDownProjFn recomputes a = bf16(silu(g) * u) inside swiglu_bwd_with_a_bf16 (1 extra register mul + write), dropping a storage (-1.373 GiB * scale per "none" layer -> upgrade_no_ac shrinks from 4.45 -> 3.05 GiB * scale), upgrading ~8 more Refine layers from "mlp_only" to "none".
     - FusedAddRMSNorm3584TrainFn fuses both forward res + delta add + RMSNorm and backward dx + dh_out add inside rmsnorm_3584_bwd_add_bf16.
  4. Single-Pass Bitwise-Exact Multi-Tensor FP32 AdamW + Fused clip_coef (r3_fused_ops.fused_adamw_step_fp32): Replaces 7 separate PyTorch _foreach_* passes (284 GB HBM traffic + 14.2 GB exp_avg_sq_sqrt temp buffer = 83.08 ms/step) with a single pass (99.4 GB, 4.0 TB/s effective HBM3e = 24.71 ms/step + 4.42 ms get_total_norm = 29.13 ms/step, saving 107.9 ms/pair, 0 bit diffs across clipped/unclipped steps and heterogeneous state['step'] groups).

### Changes (OPT_ROLLOUT_V3=1, OPT_TRAIN_V3=1, OPT_AC_BUDGET_GIB=52.0)
- modeling/bagel/csrc/fused_ops.cu: added 4 bitwise-exact CUDA kernels (fused_swiglu_gu_bf16, fused_swiglu_bwd_with_a_bf16, add_rmsnorm_3584_fwd_rstd_bf16/rmsnorm_3584_bwd_add_bf16, fused_adamw_step_fp32); rebuilt r3_fused_ops in /opt/candidate-env.
- modeling/bagel/opt_kernels.py: added FusedAddRMSNorm3584TrainFn, FusedSplitAttnOProjFn, FusedSwiGLUDownProjFn.
- modeling/bagel/qwen2_navit.py: _GU_CAT_SAFE_M-guarded _rollout_wgu + fused_swiglu_gu_bf16 in Decode, Flow text MLP, and Prefill; wired V3 autograd functions and updated AC cost model (cost_mlp=1.18, upgrade_no_ac=3.05) in forward_train_split/forward_train.
- train/fsdp2_utils.py: fsdp2_rollout_context(..., keep_unsharded=False) + temporary _rollout_wgu creation/cleanup; fsdp2_reshard_all, fsdp2_set_reshard_after_forward, clip_grad_norm_fsdp2_no_mul, fast_adamw_step_context (with per-step_val grouping for Refine-only connector params).
- train/rollout_controller.py & train/online_rl.py: wired keep_unsharded=train_v3, dynamic Gen/Refine reshard_after_forward, post-backward fsdp2_reshard_all, and fused clip+AdamW step.
7.4 hRound 8 Results
- Single-GPU + 2-rank FSDP2 E2E bitwise tests (test_r8_kernels.py, test_r8_e2e.py): 0 bit diffs across all 3 ac_modes, Decode GU_cat, and 3 mixed Gen/Refine FSDP2 steps (det=False/True).
- Full check (/tmp/check-r8/check.json): PASS (N0 bitwise identical: 3200/3200 tensors, 235/235 reward requests)
  - Windows [10-11, 12-13, 14-15]: [10.4784, 10.8956, 11.0679] s/step (mean 10.8140 s/step vs ref 23.3224 s/step; Gen 6.40–7.11s, Refine 13.42–15.06s)
  - Window ratios: [2.1834, 2.1654, 2.1229] -> speedup = 2.1572
  - Peak allocated memory: 121.77 GiB (timing) / 121.76 GiB (record) — still 9.0 GiB below reference!
- Committed to /submission/r3 (opt, commit 10ae10d) and activated in /submission/switches.json.

---
7.4 hCurrent Summary (updated after Round 8)
- Active switch file (/submission/switches.json): {"environment": {"PYTORCH_ALLOC_CONF": "expandable_segments:True", "OPT_DECODE_GRAPH": "1", "OPT_DIFFUSION_FAST": "1", "OPT_TRAIN_FAST": "1", "OPT_AC_BUDGET_GIB": "52.0", "OPT_FUSED_KERNELS": "1", "OPT_TRAIN_FUSED_NORM": "1", "OPT_OVERLAP_FSDP_REWARD": "1", "OPT_ROLLOUT_FAST": "1", "OPT_ROLLOUT_V2": "1", "OPT_TRAIN_V2": "1", "OPT_ROLLOUT_V3": "1", "OPT_TRAIN_V3": "1"}}
- Latest full check: /tmp/check-r8/check.json — PASS (N0), speedup = 2.1572 (10.8140 vs 23.3224 s/step, peak mem 121.77 GiB)
- Breakdown of gains:
  - Round 1 (OPT_DECODE_GRAPH=1): 23.3224 -> 18.6301 s/step (1.2520x, saves ~4.69 s/step)
  - Round 2 (OPT_DIFFUSION_FAST=1): 18.6301 -> 15.6976 s/step (1.1868x incremental, 1.4861x cumulative, saves ~2.93 s/step)
  - Round 3 (OPT_TRAIN_FAST=1): 15.6976 -> 15.0762 s/step (1.0412x incremental, 1.5470x cumulative, saves ~0.62 s/step, frees 18.6 GiB HBM)
  - Round 4 (OPT_FUSED_KERNELS=1): 15.0762 -> 12.6213 s/step (1.1945x incremental, 1.8492x cumulative, saves ~2.45 s/step)
  - Round 5 (OPT_TRAIN_FUSED_NORM=1, OPT_OVERLAP_FSDP_REWARD=1): 12.6213 -> 11.7253 s/step (1.0764x incremental, 1.9922x cumulative, saves ~0.90 s/step)
  - Round 6 (OPT_ROLLOUT_FAST=1): 11.7253 -> 11.4189 s/step (1.0268x incremental, 2.0460x cumulative, saves ~0.31 s/step)
  - Round 7 (OPT_ROLLOUT_V2=1, OPT_TRAIN_V2=1): 11.4189 -> 11.1222 s/step (1.0267x incremental, 2.0983x cumulative, saves ~0.30 s/step, frees 4.17 GiB HBM)
  - Round 8 (OPT_ROLLOUT_V3=1, OPT_TRAIN_V3=1, AC=52.0): 11.1222 -> 10.8140 s/step (1.0285x incremental, 2.1572x cumulative, saves ~0.31 s/step)
- Negative / dead-end directions:
  - time_embedder(t.unsqueeze(0)).expand(4096, -1): cuBLAS tile drift 7.63e-6 vs M=4096 (non-N0, abandoned).
  - Diffusion flow CUDA Graph: only 4.35 ms/pass over eager Split+PreKV+Triton, outweighed by ~280ms×3 capture cost/step (abandoned).
  - flex_attention = torch.compile(flex_attention, dynamic=True): max_diff=9.77e-4 vs static compile (non-N0, abandoned).
  - QKV horizontal GEMM concat at M=1..8: non-N0 due to cuBLAS split-K tile mismatch (abandoned).
  - KV_cat horizontal concat at M ∈ [100..200]: 1–2 ULP cuBLAS mismatch (whitelisted to _KV_CAT_SAFE_M).
  - SHARD_GRAD_OP on fsdp_model: FULL_SHARD AllGather during forward/backward is already 95–99% overlapped (< 23 ms exposed), so HBM is far better spent eliminating AC layers.
↑ R3