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
§ 02Key levers
- Text-decode CUDA graph
- ✓ round 3 captures a
torch.cuda.CUDAGraphpernum_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_iteratorinto 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=falseto 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_dictdeleted 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:
StaticKVCachealso tracks lengths on the CPU, KV prefix merged once across the 28 layers, embeddings / RoPE / timesteps hoisted out of the denoise loop,edit_imageupdates 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 (nonew_zerosscatter round-trips); round 5 denoise CUDA graph (kept in the submission); round 7 BlockMask built directly on the GPU (nocreate_block_mask), layer-0 QKV projection cached across the three CFG branches
§ ARaw trace
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-vocabF.softmax(152064)ingenerate_text_batch; tinyM<=4ungraphed 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 + freshmerged_k/merged_vallocation &aten::nonzero+index_put_scatters in_merge_static_kv_prefix_and_query(28 layers x 21x3 + 16x2calls);edit_imagerunsupdate_context_image(vae+vit)TWICE on identicalinput_imgs;_forward_flowrecomputes text/pos embeds and runstimestep.unique()every denoising step;decode_imagedoes 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 inper_round_reward.result()waiting for GenEval HTTP server before starting CPU/VAEprepack&pack_batch, plus redundanttorch.cuda.empty_cache()/resardserialization. | | Train Forward + Backward | Step 11: ~9.55s<br>Step 12: ~2.45s | ~75–99% (w/ stalls) | Three hugeaten::emptyCUDA Caching Allocator stalls (440ms,491ms,1387ms= 2.32s in Step 11 alone near 130.64 GiB peak, caused in part byref_modelkeepingreshard_after_forward=False+ref_loss_dict["logits"]alive); 8,177 + 2,623Command Buffer Full(4.13sCPU);create_block_mask& frozenvit_modelrun twice (ref_model+fsdp_model); 12+new_zeros+index/index_put_scatters per MoT layer (28x3); FSDP rank work imbalance (8.45svs9.90s). | ---
1.7 hRound 2 — Class A1: Rollout Sync & Redundancy Elimination (`PASS`, `1.1575x`)
- Commit:optbranch (Round 2: eliminate rollout KV/embed redundancy and StaticKVCache syncs) - Changes: -modeling/bagel/qwen2_navit.py: Trackseq_lens_cpuinStaticKVCache, fastclone_active()copying only[:max_active]viaempty_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 perQwen2Model.forward_inferenceto eliminate 56+ per-layer.item()syncs. -modeling/bagel/bagel.py: Added_prepare_flow_loop_assets()ingenerate_image*to hoistembed_tokens,latent_pos_embed, RoPE(cos, sin), CFG active flags,timesteps_batch, andStaticReadonlyKVPlans out of the denoising step loop; passedquery_lens_cpu&active_indices_cpuingenerate_text_batch. -train/rollout_controller.py:edit_image()updates context (vae=True, vit=True) once ongen_contextthen clones active KV prefix intocfg_text_context;generate_image_with_think()avoids redundantdeepcopyofcfg_text_context/cfg_img_context; batcheduint8decode_imageD2H 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; mean22.7410s/step vs frozen ref26.3191s/step ->1.1575xspeedup (Step 14 gen13.938s, Step 15 edit31.391s), peak alloc130.64 GiB. ---
2.2 hRound 3 — Class A2: CUDAGraph Decode & Reward/Prepack Overlap (`PASS`, `1.4495x`)
- Commit:optbranch (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_activetorch.cuda.CUDAGraphcapture with shared private pool (torch.cuda.graph_pool_handle()) coveringembed_tokens+rotary_emb+ all 28layers(via unwrapped_checkpoint_wrapped_module) +norm+lm_head; graph buffers & private pool are cleared infinally:so ZERO persistent pool memory remains after decode, while sampling remains outside the graph to preserve exact RNG progression. -train/rollout_controller.py: - Removed duplicatetorch.cuda.empty_cache()afterfsdp2_rollout_context. - Scoped per-pack_batchCPU VAE/ViT image & latent position-ID memoization (_vae_img_cache,_vit_img_cache,_latent_pos_cache) preservingB=8vae_model.encodebatch semantics. - Added deferred advantage population (text_advantages=None, image_advantages=None+populate_advantages()) so packing no longer depends on rewards. -train/online_rl.py: - Overlappedrollout_controller.prepack()+pack_iterator()immediately after rollout context exit while asynchronous GenEval HTTP reward futures run in background threads, then callspopulate_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; mean18.1790s/step vs frozen ref26.3191s/step ->1.4495xspeedup (Step 10 gen10.427s, Step 11 edit23.980s, Step 12 gen11.613s, Step 13 edit24.987s), peak alloc130.67 GiB(134.02 GiBreserved). ---
3.3 hRound 4 — Class B: Ref Resharding, Shared BlockMask/ViT & MoT Train Route (`PASS`, `1.5421x`)
- Commit:optbranch (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): Constructfull_and_noise_seq_id,noise_seq_id, anddocument_iddirectly astorch.int32on targetdevice. -train/online_rl.py: - Configuredref_modelwith explicitsharding_strategy="FULL_SHARD"andreshard_after_forward=True(bypassingFSDP2Config.get_reshard_after_forward()'sSHARD_GRAD_OP -> Falseoverride) anddel ref_loss_dictbeforefsdp_modelforward. - Precomputedprecomputed_block_maskonce per batch undertorch.no_grad()and passed to bothref_modelandfsdp_model. - Extractedvit_hidden_statesfromref_model(return_vit_hidden_states=True,.clone()d outsidetorch.inference_mode()) and passedprecomputed_vit_hidden_statesintofsdp_model(preserving trainableconnectorautograd). - Reused cachedparams_to_optimizelist inclip_grad_norm_fsdp2. -modeling/bagel/bagel.py: - Addedprecomputed_block_mask,precomputed_vit_hidden_states,return_vit_hidden_states, and_forward_vit_with_dedup()(deduplicating identicalvit_token_seqlensimage batches underno_grad/inference_mode). - Added per-call image preprocessing cache inprepare_vit_imagesandprepare_vae_images. -modeling/bagel/qwen2_navit.py: - OptimizedQwen2MoTDecoderLayer.forward_trainandPackedAttentionMoT.forward_train(return_split=True) to operate directly onundandgentoken subsets across LayerNorm, Q/K/V/O projections, Q/K norms, residuals, and MLPs instead of intermediate full-sequencenew_zerosscatter/gather round-trips. - Optimizedpad_sequence(tensor, pad_size=0)to returntensor.contiguous()directly (maintaining bitwise stride equivalence withtorch.catin compiledflex_attentionbackward). - 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; mean17.1144s/step vs frozen ref26.3191s/step ->1.5421xspeedup (Step 10 gen10.207s, Step 11 edit21.241s, Step 12 gen12.157s, Step 13 edit23.091s, Step 14 gen11.678s, Step 15 edit24.311s). - Memory: Peak allocated102.05 GiB(down-28.62 GiBvs Round 3130.67 GiB), peak reserved121.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:optbranch (Round 5: CUDAGraph diffusion flow, readonly split-route, pipelined ref_model, partial AC) - Changes: -modeling/bagel/modeling_utils.py: BuildTimestepEmbedder.timestep_embeddingtorch.arangedirectly ont.deviceto avoid CPU-GPU sync inside CUDA Graph capture. -modeling/bagel/qwen2_navit.py: ExtendedStaticReadonlyKVPlan/build_readonly_kv_plan()with precomputednew_text_idx_flat,new_vae_idx_flat,q_buf, andcovers_all; implemented split-routing(und, gen)/(text, vae)across all 28 layers ofPackedAttentionMoT,Qwen2MoTDecoderLayer,Qwen2Model, andQwen2ForCausalLM(withreturn_vae_onlyfor flow/VAE prefill,new_emptywhencovers_all, sharedgen_q_buf, and directindex_copy_intoplan.k_buf/v_buf). -modeling/bagel/bagel.py: Updatedforward_cache_update_vae(return_vae_only=True), precomputed split RoPE &gen_q_bufin_prepare_flow_loop_assets(), and added lazy per-(cfg_active, x_t.dtype)torch.cuda.CUDAGraphrunner (_make_flow_step_runner, shared privategraph_pool_handle(), freed infinally:) over_forward_flow. -train/fsdp2_utils.py&train/rollout_controller.py: Addedac_num_layerspartial activation checkpointing (skipping frozen modules and LLM layers>= ac_num_layers); cached_r3_fsdp_modules&_r3_ckpt_modulesonmodelinfsdp2_rollout_context(); removed redundanttorch.cuda.empty_cache()stalls across rollout entry/exit andRolloutBuffer.all_gather(). -train/online_rl.py: Defaultedac_num_layers=26(skipping AC on layers 26–27; note23OOM'd at133.44 GiB); pipelined single-pack training (Phase A:_run_forward_phaseoverlapping with GenEval HTTP rewards -> batched[cot_mean, fmt_mean]all_reduce->populate_advantages()->Phase B:_finish_backward_phase); eliminated Phase A.item()syncs and batchedloss_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; mean15.4257s/step vs frozen ref26.3191s/step ->1.7105xspeedup (Step 10 gen9.508s, Step 11 edit18.901s, Step 12 gen11.730s, Step 13 edit20.325s, Step 14 gen10.179s, Step 15 edit21.551s/ rank 221.912s). - Memory: Peak allocated110.17 GiB, peak reserved131.66 GiB(131.66 GiBR1 /131.60 GiBR2, ~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:optbranch (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 inQwen2MLPwhenhidden_act=="silu"&bf16on CUDA): single-passuint2vectorizedsilu(gate)*upfwd & bwd. -rope_qk_bf16(used inPackedAttentionMoT.forward_inferencemode=="und"): fused(Q, K)RoPE in fp32-to-bf16 without extra cat/slice kernels. -rope_qkv_scatter_gen(used inPackedAttentionMoT.forward_inferencemode=="gen"): fused text+vae Q/K RoPE + V cast & direct scatter intoq_buf/k_buf/v_buf(plan.new_text_idx_flat/plan.new_vae_idx_flat). -fused_rope_scatter_permute_train(used inPackedAttentionMoT.forward_trainwhencovers_all&BlockMask): single-pass und+gen RoPE fwd + scatter +(L, H, D) -> (H, L_pad, D)permute/pad (saving all intermediatenew_empty/index_put_/transposes) and matchingrope_scatter_permute_train_bwdbackward kernel. - Changes in/submission/r3: -modeling/bagel/qwen2_navit.py: Integratedr3_fast_opsintoQwen2MLPandPackedAttentionMoT(forward_train,forward_inferenceund&gen); sizedStaticKVCacheatmax_len + 1. -modeling/bagel/bagel.py: Shared persistent CUDA graph capture stream & pool runtime (_get_cudagraph_runtimewith 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 infinally:; kept per-num_activedecode graphs (M = num_active) so Hopper cuBLAS GEMM kernel selection matches upstream bit-for-bit; hoistedlogits_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: Vectorizedcreate_sparse_maskand 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; mean13.5085s/step vs frozen ref26.3191s/step ->1.9518xspeedup (Step 10 gen8.051s, Step 11 edit17.165s, Step 12 gen9.436s, Step 13 edit18.740s, Step 14 gen9.234s, Step 15 edit18.424s). - Memory: Peak allocated107.35 GiB, peak reserved128.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:optbranch5df7a86(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)) andadd_rmsnorm_exact(fusing residual add + next RMSNorm and returning(updated_residual, norm_out)). -qk_norm_rope_bf16(fusing Q/K RMSNorm + RoPE inPackedAttentionMoT.forward_inferencemode=="und"). -qk_norm_rope_qkv_scatter_gen(fusing text+vae Q/K fp32-cast + RMSNorm + RoPE + scatter + V scatter inPackedAttentionMoT.forward_inferencemode=="gen"). -build_bagel_block_mask_tensors(direct GPU construction ofH=1flex_attentionBlockMaskmetadata withoutcreate_block_maskcold compile). - Changes in/submission/r3: -data/data_utils.py,modeling/bagel/bagel.py,train/online_rl.py: Replacedcreate_sparse_mask+create_block_maskwithcreate_bagel_block_mask. -modeling/qwen2/modeling_qwen2.py&modeling/bagel/qwen2_navit.py: Dispatchedrmsnorm_exact,add_rmsnorm_exactacross 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_imgflow branches. -modeling/bagel/bagel.py&train/rollout_controller.py: Propagatedvit_token_seqlens_cpu,text_token_lens_cpu,packed_seqlens_cputo eliminate host.tolist()/.item()syncs; kept_FLOW_GLOBAL_WARMUP_SIGS&_DECODE_GLOBAL_WARMUP_SEENacross 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; mean12.2065s/step vs frozen ref26.3191s/step ->2.1619xspeedup (Step 10 gen7.172s, Step 11 edit15.290s, Step 12 gen8.556s, Step 13 edit17.066s, Step 14 gen8.548s, Step 15 edit16.603s). - Memory: Peak allocated107.31 GiB, peak reserved128.99 GiB,startup_to_first_step_sdropped to267.7s(vs379.6sbaseline).