Gemini 4 Hydrogen 2.10×

Harness: Antigravity · switches: PYTORCH_ALLOC_CONF=expandable_segments:True

Judged
2.10×
Tier
N0
Self-best
2.16×
Rounds
7
Hours
10.0
API cost
$59.0
Input tokens · 91.6% cached
216 M
Output tokens
2.3 M
Requests
1,360
Text-decode CUDA graph
✓ round 3 captures a torch.cuda.CUDAGraph per num_active (embed + 28 layers + norm + lm_head, sampling left outside the graph to keep the RNG order), graphs and private pool released at the end of each decode; together with removing per-token .item() / .split(1) and the packing overlap, full check 1.1575× → 1.4495×; round 6 shares the capture stream and pool with the denoise graphs, round 7 adds double-buffered async EOS
Reward wait hidden behind forward
✓ round 3 moves prepack + pack_iterator into the reward wait, advantages filled in afterwards (same round as the decode graph, no separate number); round 5 also moves the training forward (Phase A) into the wait, backward runs once advantages are in (with the denoise graph, partial recompute etc. in the same round, 1.5421× → 1.7105×)
Rollout-side bitwise fused kernels
✓ custom SM90 CUDA extension r3_fast_ops: round 6 SiLU·mul, q/k RoPE, generation-branch RoPE + V cast + scatter (RoPE and SiLU forward built with --fmad=false to match non-FMA rounding), with the shared graph pool and vectorized packing in the same round 1.7105× → 1.9518×; round 7 RMSNorm, residual add + RMSNorm, q/k norm + RoPE (with scatter on the generation branch), with GPU BlockMask, layer-0 CFG cache etc. in the same round → 2.1619×
Train-side bitwise kernels / freeing memory
✓ round 4 reference model reshards after forward (reshard_after_forward=True), ref_loss_dict deleted early, expandable segments on (the only entry in the final switches), peak 130.67 → 102.05 GiB (with shared BlockMask / ViT and the split MoT training route in the same round, 1.4495× → 1.5421×); round 5 drops recompute only on layers 26–27 (ac_num_layers=26; 23 OOMed at 133.44 GiB); round 6 train-side RoPE + scatter + transpose/pad fwd/bwd kernel, SiLU·mul fwd/bwd; final peak 107.31 GiB
Other main levers
round 2 denoise desync: StaticKVCache also tracks lengths on the CPU, KV prefix merged once across the 28 layers, embeddings / RoPE / timesteps hoisted out of the denoise loop, edit_image updates the context once and copies it into the CFG text branch, full check 1.1575×; round 4 BlockMask and ViT output shared between reference and policy, ViT dedup of repeated images, MoT training branches computed directly on their own subsets (no new_zeros scatter round-trips); round 5 denoise CUDA graph (kept in the submission); round 7 BlockMask built directly on the GPU (no create_block_mask), layer-0 QKV projection cached across the three CFG branches
Raw work log7 sections
0.2 hRound 1 — Tiered Profiling & Bottleneck Baseline (Reference `761b0b0`)
- Command: bench/bench.py profile --tree /submission/r3 --config /submission/switches.json --out /tmp/prof-ref --from 11 --iters 2
- Profile result: wall_s = 1234.7s, startup_to_first_step_s = 379.6s, peak_alloc = 130.64 GiB, peak_res = 132.94 GiB.
- Profiled step durations: Step 11 (odd/refine): 38.261s; Step 12 (even/generate): 20.577s (total 58.84s; Self CUDA time total = 26.916s = 45.7% overall GPU utilization).

### Breakdown of 2-Step Cycle (Step 11 Edit + Step 12 Gen)
| Phase | Profiled Span | GPU Busy % | Primary Root Causes |
|---|---|---|---|
| Thinking (generate_text_batch) | Step 11: ~12.5s<br>Step 12: ~8.5s | 16.2–16.6% | 56 .item() CUDA syncs/token in _static_kv_cache_attention (28 layers x 2); per-token .split(1)/.item() + redundant full-vocab F.softmax(152064) in generate_text_batch; tiny M<=4 ungraphed eager dispatch (~18.5k launches/0.5s). |
| Image Rollout (edit_image / gen_image) | Step 11: ~13.0s<br>Step 12: ~6.7s | 49–73% | ~6 .item() syncs + fresh merged_k/merged_v allocation & aten::nonzero + index_put_ scatters in _merge_static_kv_prefix_and_query (28 layers x 21x3 + 16x2 calls); edit_image runs update_context_image(vae+vit) TWICE on identical input_imgs; _forward_flow recomputes text/pos embeds and runs timestep.unique() every denoising step; decode_image does 4 sync D2H copies. |
| Post-Rollout Reward Wait + Prepack | Step 11: 1.25s idle + 0.55s<br>Step 12: 1.53s idle + 0.26s | 0% (1.25–1.53s) | GPUs sit idle in per_round_reward.result() waiting for GenEval HTTP server before starting CPU/VAE prepack & pack_batch, plus redundant torch.cuda.empty_cache() / resard serialization. |
| Train Forward + Backward | Step 11: ~9.55s<br>Step 12: ~2.45s | ~75–99% (w/ stalls) | Three huge aten::empty CUDA Caching Allocator stalls (440ms, 491ms, 1387ms = 2.32s in Step 11 alone near 130.64 GiB peak, caused in part by ref_model keeping reshard_after_forward=False + ref_loss_dict["logits"] alive); 8,177 + 2,623 Command Buffer Full (4.13s CPU); create_block_mask & frozen vit_model run twice (ref_model + fsdp_model); 12+ new_zeros + index / index_put_ scatters per MoT layer (28x3); FSDP rank work imbalance (8.45s vs 9.90s). |

---
1.7 hRound 2 — Class A1: Rollout Sync & Redundancy Elimination (`PASS`, `1.1575x`)
- Commit: opt branch (Round 2: eliminate rollout KV/embed redundancy and StaticKVCache syncs)
- Changes:
  - modeling/bagel/qwen2_navit.py: Track seq_lens_cpu in StaticKVCache, fast clone_active() copying only [:max_active] via empty_like, StaticReadonlyKVPlan + build_readonly_kv_plan() pre-merging KV prefix once across all 28 layers for diffusion CFG/cond branches, and _build_static_cache_ctx() built once per Qwen2Model.forward_inference to eliminate 56+ per-layer .item() syncs.
  - modeling/bagel/bagel.py: Added _prepare_flow_loop_assets() in generate_image* to hoist embed_tokens, latent_pos_embed, RoPE (cos, sin), CFG active flags, timesteps_batch, and StaticReadonlyKVPlans out of the denoising step loop; passed query_lens_cpu & active_indices_cpu in generate_text_batch.
  - train/rollout_controller.py: edit_image() updates context (vae=True, vit=True) once on gen_context then clones active KV prefix into cfg_text_context; generate_image_with_think() avoids redundant deepcopy of cfg_text_context/cfg_img_context; batched uint8 decode_image D2H conversion.
- Verification (bench/bench.py check, /tmp/check-r2):
  - Tier N0 (record): PASS (bitwise: true, 14 steps, 3200 tensors, 235 reward requests).
  - Timing: Windows [22.2854, 23.2515, 22.6862] s/step; mean 22.7410 s/step vs frozen ref 26.3191 s/step -> 1.1575x speedup (Step 14 gen 13.938s, Step 15 edit 31.391s), peak alloc 130.64 GiB.

---
2.2 hRound 3 — Class A2: CUDAGraph Decode & Reward/Prepack Overlap (`PASS`, `1.4495x`)
- Commit: opt branch (Round 3: CUDAGraph text decode and reward-prepack overlap)
- Changes:
  - modeling/bagel/bagel.py (generate_text_batch):
    - Eliminated per-token .item(), .nonzero(), and .split(1) syncs via preallocated GPU buffers (gen_ids_buf, gen_probs_buf) and a single (active_curr_tokens == end_token_id).tolist() EOS check per decode step; throttled tqdm updates (mininterval=1.0).
    - Added lazy per-num_active torch.cuda.CUDAGraph capture with shared private pool (torch.cuda.graph_pool_handle()) covering embed_tokens + rotary_emb + all 28 layers (via unwrapped _checkpoint_wrapped_module) + norm + lm_head; graph buffers & private pool are cleared in finally: so ZERO persistent pool memory remains after decode, while sampling remains outside the graph to preserve exact RNG progression.
  - train/rollout_controller.py:
    - Removed duplicate torch.cuda.empty_cache() after fsdp2_rollout_context.
    - Scoped per-pack_batch CPU VAE/ViT image & latent position-ID memoization (_vae_img_cache, _vit_img_cache, _latent_pos_cache) preserving B=8 vae_model.encode batch semantics.
    - Added deferred advantage population (text_advantages=None, image_advantages=None + populate_advantages()) so packing no longer depends on rewards.
  - train/online_rl.py:
    - Overlapped rollout_controller.prepack() + pack_iterator() immediately after rollout context exit while asynchronous GenEval HTTP reward futures run in background threads, then calls populate_advantages() once advantages are computed.
- Verification (bench/bench.py check, /tmp/check-r3):
  - Tier N0 (record): PASS (bitwise: true, 14 steps, 3200 tensors, 235 reward requests).
  - Timing: Windows [17.2060, 18.3005, 19.0306] s/step; mean 18.1790 s/step vs frozen ref 26.3191 s/step -> 1.4495x speedup (Step 10 gen 10.427s, Step 11 edit 23.980s, Step 12 gen 11.613s, Step 13 edit 24.987s), peak alloc 130.67 GiB (134.02 GiB reserved).

---
3.3 hRound 4 — Class B: Ref Resharding, Shared BlockMask/ViT & MoT Train Route (`PASS`, `1.5421x`)
- Commit: opt branch (Round 4: reshard ref_model, share BlockMask/ViT, eliminate MoT train scatters)
- Environment (/submission/switches.json): {"environment": {"PYTORCH_ALLOC_CONF": "expandable_segments:True"}}
- Changes:
  - data/data_utils.py (create_sparse_mask): Construct full_and_noise_seq_id, noise_seq_id, and document_id directly as torch.int32 on target device.
  - train/online_rl.py:
    - Configured ref_model with explicit sharding_strategy="FULL_SHARD" and reshard_after_forward=True (bypassing FSDP2Config.get_reshard_after_forward()'s SHARD_GRAD_OP -> False override) and del ref_loss_dict before fsdp_model forward.
    - Precomputed precomputed_block_mask once per batch under torch.no_grad() and passed to both ref_model and fsdp_model.
    - Extracted vit_hidden_states from ref_model (return_vit_hidden_states=True, .clone()d outside torch.inference_mode()) and passed precomputed_vit_hidden_states into fsdp_model (preserving trainable connector autograd).
    - Reused cached params_to_optimize list in clip_grad_norm_fsdp2.
  - modeling/bagel/bagel.py:
    - Added precomputed_block_mask, precomputed_vit_hidden_states, return_vit_hidden_states, and _forward_vit_with_dedup() (deduplicating identical vit_token_seqlens image batches under no_grad/inference_mode).
    - Added per-call image preprocessing cache in prepare_vit_images and prepare_vae_images.
  - modeling/bagel/qwen2_navit.py:
    - Optimized Qwen2MoTDecoderLayer.forward_train and PackedAttentionMoT.forward_train (return_split=True) to operate directly on und and gen token subsets across LayerNorm, Q/K/V/O projections, Q/K norms, residuals, and MLPs instead of intermediate full-sequence new_zeros scatter/gather round-trips.
    - Optimized pad_sequence(tensor, pad_size=0) to return tensor.contiguous() directly (maintaining bitwise stride equivalence with torch.cat in compiled flex_attention backward).
- Verification (bench/bench.py check, /tmp/check-r4b):
  - Tier N0 (record): PASS (bitwise: true, 14 steps, 3200 tensors, 235 reward requests).
  - Timing: Windows [15.7237, 17.6252, 17.9943] s/step; mean 17.1144 s/step vs frozen ref 26.3191 s/step -> 1.5421x speedup (Step 10 gen 10.207s, Step 11 edit 21.241s, Step 12 gen 12.157s, Step 13 edit 23.091s, Step 14 gen 11.678s, Step 15 edit 24.311s).
  - Memory: Peak allocated 102.05 GiB (down -28.62 GiB vs Round 3 130.67 GiB), peak reserved 121.69 GiB (down -12.33 GiB).

---
4.9 hRound 5 — CUDAGraph Diffusion Flow, Readonly Split-Route, Pipelined `ref_model` & Partial AC (`PASS`, `1.7105x`)
- Commit: opt branch (Round 5: CUDAGraph diffusion flow, readonly split-route, pipelined ref_model, partial AC)
- Changes:
  - modeling/bagel/modeling_utils.py: Build TimestepEmbedder.timestep_embedding torch.arange directly on t.device to avoid CPU-GPU sync inside CUDA Graph capture.
  - modeling/bagel/qwen2_navit.py: Extended StaticReadonlyKVPlan/build_readonly_kv_plan() with precomputed new_text_idx_flat, new_vae_idx_flat, q_buf, and covers_all; implemented split-routing (und, gen) / (text, vae) across all 28 layers of PackedAttentionMoT, Qwen2MoTDecoderLayer, Qwen2Model, and Qwen2ForCausalLM (with return_vae_only for flow/VAE prefill, new_empty when covers_all, shared gen_q_buf, and direct index_copy_ into plan.k_buf/v_buf).
  - modeling/bagel/bagel.py: Updated forward_cache_update_vae (return_vae_only=True), precomputed split RoPE & gen_q_buf in _prepare_flow_loop_assets(), and added lazy per-(cfg_active, x_t.dtype) torch.cuda.CUDAGraph runner (_make_flow_step_runner, shared private graph_pool_handle(), freed in finally:) over _forward_flow.
  - train/fsdp2_utils.py & train/rollout_controller.py: Added ac_num_layers partial activation checkpointing (skipping frozen modules and LLM layers >= ac_num_layers); cached _r3_fsdp_modules & _r3_ckpt_modules on model in fsdp2_rollout_context(); removed redundant torch.cuda.empty_cache() stalls across rollout entry/exit and RolloutBuffer.all_gather().
  - train/online_rl.py: Defaulted ac_num_layers=26 (skipping AC on layers 26–27; note 23 OOM'd at 133.44 GiB); pipelined single-pack training (Phase A: _run_forward_phase overlapping with GenEval HTTP rewards -> batched [cot_mean, fmt_mean] all_reduce -> populate_advantages() -> Phase B: _finish_backward_phase); eliminated Phase A .item() syncs and batched loss_dict / [mem_allocated, mem_cache] reductions.
- Verification (bench/bench.py check, /tmp/check-r5):
  - Tier N0 (record): PASS (bitwise: true, 14 steps, 3200 tensors, 235 reward requests).
  - Timing: Windows [14.2043, 16.0275, 16.0454] s/step; mean 15.4257 s/step vs frozen ref 26.3191 s/step -> 1.7105x speedup (Step 10 gen 9.508s, Step 11 edit 18.901s, Step 12 gen 11.730s, Step 13 edit 20.325s, Step 14 gen 10.179s, Step 15 edit 21.551s / rank 2 21.912s).
  - Memory: Peak allocated 110.17 GiB, peak reserved 131.66 GiB (131.66 GiB R1 / 131.60 GiB R2, ~8.1 GiB below 139.8 GiB device limit).

---
7.3 hRound 6 — SM90 Custom CUDA Kernels (`r3_fast_ops`), Allocator Cache Tuning & Pipeline Overhead Cleanup (`PASS`, `1.9518x`)
- Commit: opt branch (Round 6: custom SM90 r3_fast_ops CUDA kernels, shared CUDA graph pool, vectorized packing)
- Python Extension (/opt/candidate-env/src/r3_fast_ops):
  - Built two SM90 (compute_90) CUDA extension modules separating --fmad=false (_nofma, preserving exact non-FMA PyTorch bf16 rounding for RoPE & SiLU forward) from FMA-enabled (_fma, for SiLU backward):
    - fused_silu_mul_bf16 (used in Qwen2MLP when hidden_act=="silu" & bf16 on CUDA): single-pass uint2 vectorized silu(gate)*up fwd & bwd.
    - rope_qk_bf16 (used in PackedAttentionMoT.forward_inference mode=="und"): fused (Q, K) RoPE in fp32-to-bf16 without extra cat/slice kernels.
    - rope_qkv_scatter_gen (used in PackedAttentionMoT.forward_inference mode=="gen"): fused text+vae Q/K RoPE + V cast & direct scatter into q_buf/k_buf/v_buf (plan.new_text_idx_flat / plan.new_vae_idx_flat).
    - fused_rope_scatter_permute_train (used in PackedAttentionMoT.forward_train when covers_all & BlockMask): single-pass und+gen RoPE fwd + scatter + (L, H, D) -> (H, L_pad, D) permute/pad (saving all intermediate new_empty/index_put_/transposes) and matching rope_scatter_permute_train_bwd backward kernel.
- Changes in /submission/r3:
  - modeling/bagel/qwen2_navit.py: Integrated r3_fast_ops into Qwen2MLP and PackedAttentionMoT (forward_train, forward_inference und & gen); sized StaticKVCache at max_len + 1.
  - modeling/bagel/bagel.py: Shared persistent CUDA graph capture stream & pool runtime (_get_cudagraph_runtime with pre-warmed cuBLAS handles on persistent stream and 1-byte anchor graph + _capture_cudagraph_fast) across decode and flow graphs so private pools never pin extra cuBLAS workspaces; reset graphs in finally:; kept per-num_active decode graphs (M = num_active) so Hopper cuBLAS GEMM kernel selection matches upstream bit-for-bit; hoisted logits_f32 = pred_logits.float().
  - train/rollout_controller.py: Vectorized _pack_repeated_float_runs, _cat_dedup_to_device, populate_advantages, ce_loss_weights (torch.ones), and _vae_latent_plan.
  - data/data_utils.py & train/online_rl.py: Vectorized create_sparse_mask and lightweight cleanup.
- Verification (bench/bench.py check, /tmp/check-r6):
  - Tier N0 (record): PASS (bitwise: true, 14 steps, 3200 tensors, 235 reward requests).
  - Timing: Windows [12.6082, 14.0883, 13.8288] s/step; mean 13.5085 s/step vs frozen ref 26.3191 s/step -> 1.9518x speedup (Step 10 gen 8.051s, Step 11 edit 17.165s, Step 12 gen 9.436s, Step 13 edit 18.740s, Step 14 gen 9.234s, Step 15 edit 18.424s).
  - Memory: Peak allocated 107.35 GiB, peak reserved 128.89 GiB (~10.9 GiB headroom).

---
9.2 hRound 7 — Fused `RMSNorm`/`add+RMSNorm`/`QK-Norm+RoPE` Kernels, GPU `BlockMask`, Layer-0 CFG Cache & Async EOS (`PASS`, `2.1619x`)
- Commit: opt branch 5df7a86 (Round 7: fused RMSNorm/add-RMSNorm/QK-norm-RoPE, Layer-0 CFG cache, GPU BlockMask, async EOS & persistent graph warmups)
- Python Extension (/opt/candidate-env/src/r3_fast_ops):
  - Added exact SM90 kernels matching PyTorch eager fp32-accumulate + bf16-cast bit-for-bit:
    - rmsnorm_exact (D in (128, 3584)) and add_rmsnorm_exact (fusing residual add + next RMSNorm and returning (updated_residual, norm_out)).
    - qk_norm_rope_bf16 (fusing Q/K RMSNorm + RoPE in PackedAttentionMoT.forward_inference mode=="und").
    - qk_norm_rope_qkv_scatter_gen (fusing text+vae Q/K fp32-cast + RMSNorm + RoPE + scatter + V scatter in PackedAttentionMoT.forward_inference mode=="gen").
    - build_bagel_block_mask_tensors (direct GPU construction of H=1 flex_attention BlockMask metadata without create_block_mask cold compile).
- Changes in /submission/r3:
  - data/data_utils.py, modeling/bagel/bagel.py, train/online_rl.py: Replaced create_sparse_mask + create_block_mask with create_bagel_block_mask.
  - modeling/qwen2/modeling_qwen2.py & modeling/bagel/qwen2_navit.py: Dispatched rmsnorm_exact, add_rmsnorm_exact across intra-layer / inter-layer MoT residuals (und, gen, and decode graph), qk_norm_rope_bf16, qk_norm_rope_qkv_scatter_gen, and Layer-0 CFG QKV projection cache (layer0_qkv_cache) across cond / cfg_text / cfg_img flow branches.
  - modeling/bagel/bagel.py & train/rollout_controller.py: Propagated vit_token_seqlens_cpu, text_token_lens_cpu, packed_seqlens_cpu to eliminate host .tolist() / .item() syncs; kept _FLOW_GLOBAL_WARMUP_SIGS & _DECODE_GLOBAL_WARMUP_SEEN across calls to capture CUDA graphs on step 0 of subsequent rollouts; added double-buffered async EOS pinned-CPU D2H overlap (_EOS_PINNED_BUF_CACHE, device="cpu").
- Verification (bench/bench.py check, /tmp/check-r7):
  - Tier N0 (record): PASS (bitwise: true, 14 steps, 3200 tensors, 235 reward requests).
  - Timing: Windows [11.2309, 12.8131, 12.5756] s/step; mean 12.2065 s/step vs frozen ref 26.3191 s/step -> 2.1619x speedup (Step 10 gen 7.172s, Step 11 edit 15.290s, Step 12 gen 8.556s, Step 13 edit 17.066s, Step 14 gen 8.548s, Step 15 edit 16.603s).
  - Memory: Peak allocated 107.31 GiB, peak reserved 128.99 GiB, startup_to_first_step_s dropped to 267.7s (vs 379.6s baseline).
↑ R3