Step-5 Preview 1.12×

Harness: Claude Code · switches: BAGEL_KV_HOIST=1 BAGEL_IMG_CACHE=1 BAGEL_REWARD_OVERLAP=1 BAGEL_EMPTY_INIT=1 BAGEL_TEXTGEN_BATCH=1

Judged
1.12×
Tier
N0
Self-best
1.13×
Rounds
19
Hours
10.1
API cost
$31.9
Input tokens · 99.5% cached
283 M
Output tokens
0.9 M
Requests
740
Text-decode CUDA graph
✗ round 15 measured decode launch overhead ~2.6 ms/token, several seconds in total, but concluded fixed-batch capture would change the RNG stream, "infeasible under N0"; no capture code written
Reward wait hidden behind forward
✓ BAGEL_REWARD_OVERLAP (packing + reference forward moved ahead of the wait), full check 1.0791× → 1.1192×; round 5 also moved the policy forward earlier, OOM (135.8 GiB), reverted
Rollout-side bitwise fused kernels
tried, reverted: round 11 PyTorch RoPE bitwise identical but 1.42× slower; round 12 Triton RoPE 2.6–6.2× faster but off by 1 ULP (3772 / 401M elements differ after bf16 cast), dropped; RMSNorm not tried
Train-side bitwise kernels / freeing memory
✗ (peak 130.74 GiB); training forward only swapped zeros for empty (below noise)
Other main levers
BAGEL_KV_HOIST static-KV scalars computed once per forward (single-run timing 1.0744×); BAGEL_TEXTGEN_BATCH decode bookkeeping read back in batches (full check 1.1185× → 1.1315×); edit-path VAE / ViT dedup, 11 zeros → empty, loss-logging desync all within noise; BAGEL_MERGE_SEL no gain, reverted
Raw work log19 sections
0.6 hRound 1 — profile the unchanged reference (stage → bottleneck type)
- Start 04:52, profile via bench/bench.py profile (torch.profiler, steps 11-12) on targets/reference.
- Steady-state step times (from run log): gen steps ~15s, edit steps ~31-34s (edit ≈ 2× gen). Matches frozen ref 23.4 s/step.
- torch.profiler (2 steps = 1 gen + 1 edit): Self CPU 42.9s vs Self CUDA 27.0s → host/sync-bound, not GPU-bound. Peak mem 130.6 GiB.
  - Top CUDA: aten::mm 42% (GEMMs); nvjet GEMM kernels; FlashAttention fwd 0.9s; NCCL reduce_scatter+allgather ~1s; AdamW.step 0.2s.
  - Sync storm: _local_scalar_dense (.item) 244k calls, 9.3s CPU; DtoH memcpy 263k calls; Command Buffer Full 4.75s CPU (launch-queue saturation); nonzero 19k.
- Added env-gated phase timers (BAGEL_PHASE_TIMING, N0 pure observation) to train/online_rl.py. Phase timing run (time --config /tmp/sw_phase.json), steady state:
  - gen step (~15s): rollout ~10.6s (70%), reward_adv ~1.9s, train_fwd_bwd ~2.1s, optim ~0.14s.
  - edit step (~32s): rollout ~19-21s (65%), reward_adv ~3.7s, train_fwd_bwd ~7.5s, optim ~0.14s.
  - prepack ~0.01s (negligible → reward/prepack overlap idea is dead).
- Hotspot = rollout (65-72% of the step), host/sync-bound. Root cause candidate: per-layer .item() GPU syncs in attention (_static_kv_cache_attention overflow check + max_seqlen/shape extraction, done 28× per forward though identical across layers). Also autoregressive text gen is launch/sync heavy.
- Round-1 change: none (profiling only). Instrumentation committed (off by default).
1.0 hRound 2 — N0: hoist per-forward-constant static-KV attention scalars out of the decoder-layer loop
- Hotspot: rollout is host/sync-bound; the static-KV attention helpers (_merge_static_kv_prefix_and_query,
  _static_kv_cache_attention, _static_kv_cache_readonly_attention) recompute + .item()-sync the same
  scalars (overflow check, max_seqlen_q/k, total_kv/total_past, max_past/max_new) for every one of the 28
  decoder layers, though seq_lens/query_lens are constant within one forward_inference.
- Change (modeling/bagel/qwen2_navit.py, behind BAGEL_KV_HOIST, off by default): _precompute_static_kv_attention_scalars
  computes them once per forward and stashes on past_key_values._r3_attn_scalars; helpers read the stash,
  else fall back to the original per-layer path. Same values → flash_attn gets identical inputs.
- check --quick (out /tmp/qk-hoist): PASS, bitwise, measured_tier N0 — 14 steps, 3200 tensors, 235 reward
  requests all identical to the frozen reference. Commit 6ddc6cd. switches.json = {"BAGEL_KV_HOIST":"1"}.
- time (out /tmp/t-hoist, with phase timing): speedup_vs_frozen_reference = 1.0682, 21.94 s/step (phase timing adds sync overhead, so clean is higher). Steady-state rollout dropped gen ~10.7→~9.8s, edit ~21.8→~19.9s.
- Clean time (out /tmp/t-clean, switches.json only): speedup = 1.0744, 21.82 s/step — KV hoist alone clears the 1.043 gate with ~3% margin (fallback if later changes fail).
1.4 hRound 3 — N0: dedup redundant VAE-latent / ViT-embedding in the edit path (behind BAGEL_IMG_CACHE)
- Hotspot: in edit_image, the same input image is VAE-encoded + ViT-forwarded twice (once for gen_context,
  once for cfg_text_context) — deterministic encodes recomputed identically.
- Change: update_context_image(..., feat_cache) computes the VAE latent and ViT embedding once and reuses them
  for the second (CFG) context; forward_cache_update_vae/vit gained precomputed_latent/precomputed_vit_embed
  (default None → original path). edit_image shares one feat_cache across the two image updates. Off by default.
- check --quick (out /tmp/qk-comb2, KV hoist + dedup): PASS, bitwise N0 — 14 steps, 3200 tensors, 235 reward requests identical. Commit e543a14. (First attempt ERROR'd: used unwrapped_model.vae_model instead of the controller's self.vae_model; fixed.)
- time (out /tmp/t-comb, combined + phase timing): speedup = 1.0719, 21.87 s/step. The VAE/ViT dedup added little wall-time (edit rollout ~20.5/19.2s ≈ KV-hoist-only; rollout is host-bound, not VAE-bound) — a genuine compute reduction, verified N0, kept.
- Full check (out /tmp/full-1): STATUS PASS, speedup = 1.0791, bitwise N0. Window ratios [1.059, 1.097, 1.081]; candidate windows [21.54, 21.62, 21.99] s/step vs frozen ref [22.82, 23.72, 23.77]; benefit.speedup 1.0791 > bar 1.043 (passed); 3200 tensors + 235 reward requests identical; peak mem 130.72 GiB.
2.8 hRound 4 — N0: overlap the reward-service wait with packing + ref-model forward (BAGEL_REWARD_OVERLAP)
- Hotspot: the reward .result() wait (~1.5-3.8s, variable) is serial; the ref-model forward and batch packing are
  reward-independent (advantages only feed loss_info), so they were done after the wait.
- Change (train/online_rl.py + train/rollout_controller.py, behind BAGEL_REWARD_OVERLAP, off by default): pull
  prepack + pack_batch + the ref forward ahead of the reward wait; record per-token/image advantage keys
  (_text_adv_keys/_image_adv_keys) in pack_batch/add_text/add_latent; after rewards arrive, reconstruct and
  attach the real advantages into loss_info, then run the policy forward + loss. Same values, RNG stream, per-rank
  collective order → bitwise identical.
- check --quick (out /tmp/qk-ovl, all three switches): PASS, bitwise N0 — 3200 tensors + 235 reward requests identical. Commit e28e399.
- time (out /tmp/t-ovl, all three + phase timing): speedup = 1.1031, 21.25 s/step. reward_adv dropped from ~1.5-4.4s to ~0-1.6s (wait hidden under the packing+ref-forward prologue); edit wall ~31→~28s. Phase timing adds sync overhead, so clean is higher.
- Full check (out /tmp/full-2, all three switches): STATUS PASS, speedup = 1.1192, bitwise N0. Candidate windows [20.69, 21.05, 21.08] vs frozen ref [22.82, 23.72, 23.77]; benefit.speedup 1.1192 > bar 1.043 (passed, ~7% margin); 3200 tensors + 235 reward requests identical; peak mem 130.74 GiB.
3.7 hRound 5 — no-gain: policy-forward overlap (attempted, reverted — OOM)
- Idea: the policy forward is also reward-independent, so pull it into the prologue too (extends the overlap window).
- Result (/tmp/qk-pf): ERROR — CUDA OOM (135.8 GiB vs the ref-forward-only 130.7 GiB). The policy forward's autograd graph (~5 GiB) is large; holding it across the reward-wait overlaps with the reward-service worker's GPU memory on the same card. The ref forward survives only because its output is small and inference_mode. Reverted train/online_rl.py to commit e28e399 (working tree clean; submission back at the verified 1.1192).
4.1 hRound 6 — re-profile the current best (all three switches): confirms exhaustion of N0 levers
- torch.profiler (steps 11-12) vs the round-1 reference: Self CUDA 26.67s ≈ 26.97s (GPU compute unchanged/irreducible), Self CPU 42.9s → 39.5s; .item() 244k → 194k and DtoH 263k → 213k (KV hoist); aten::mm still 43% (the MoE-MLP/GEMM compute), Command Buffer Full 4.87s (GPU-bound bursts — CPU waiting on a full command queue, not a reducible host cost). No new N0 hotspot: the remaining GPU work (rollout text/image-gen GEMMs + attention, the AC backward) is the model's own compute, and the residual host cost is either GPU-bound or already hidden under the reward wait by the reward-overlap.
4.7 hRound 7 — N0: skip fully-overwritten zero-init in the gen-mode MoT split (BAGEL_EMPTY_INIT)
- The gen-mode MoT decoder scatters norm(text)+norm(vae) over every position of the packed sequence ([start,vae,end]), so the zeros_like (and the .to(bf16) copy) are fully overwritten and wasted. Replaced with empty_like(..., dtype=bf16) at the two image-flow gen-split sites (modeling/bagel/qwen2_navit.py). Coverage = whole sequence ⇒ bitwise identical. (The attention zero-inits and the training-forward interleaved scatter are left as zeros — not provably whole.)
- check --quick (out /tmp/qk-empty): PASS, bitwise N0 (3200 tensors + 235 reward requests identical). time (out /tmp/t-empty): 1.1154 (within noise of the 1.1192 baseline — below the ~2% noise floor, so no measurable gain, but a genuine GPU-work reduction, no regression). Commit 423c1c8.
5.0 hRound 8 — N0: extend empty-init to the training-forward MoT splits (BAGEL_EMPTY_INIT)
- Extended the fully-overwritten zero-init skip to Qwen2MoTDecoderLayer.forward_train (input + MLP splits) and the two Qwen2Model final-norm splits (forward_train + forward_inference gen). All are MoT splits where und+gen covers the whole packed sequence ⇒ the zero-init is wasted ⇒ empty. (The attention zero-inits and the unused Qwen2MoEDecoderLayer sites are left as zeros.)
- check --quick (out /tmp/qk-empty2, all 4 switches): PASS, bitwise N0 (3200 tensors + 235 reward requests identical). Strict superset of round 7 (more memset/copy removed); still below the ~2% noise floor. Commit 612e59f.
5.3 hRound 9 — N0: extend empty-init to PackedAttentionMoT.forward_train q/k/v + q/k-norm splits
- Same argument: the q/k/v and q_norm/k_norm zero-inits in PackedAttentionMoT.forward_train are fully overwritten by the und+gen scatter (und+gen = whole sequence), so use empty. (The NaiveCache merge paths and the unused Qwen2MoEDecoderLayer sites are left as zeros.) 11 empty-init sites total.
- check --quick (out /tmp/qk-attr, all 4 switches): PASS, bitwise N0 (3200 tensors + 235 reward requests identical). Below the ~2% noise floor. Commit cca2df7.
- Note: rounds 7-9 are below-noise genuine GPU-work reductions (skipping fully-overwritten memsets); the above-noise levers were exhausted by round 6's re-profile (the compute-bound core is reached). They are kept because they are N0 and harmless.

### Full check on the final 4-switch tree (out /tmp/full-3)
- STATUS PASS, speedup = 1.1185, bitwise N0. Candidate windows [20.55, 20.86, 21.45] vs frozen ref [22.82, 23.72, 23.77]; benefit.speedup 1.1185 > bar 1.043 (passed, ~7% margin); 3200 tensors + 235 reward requests identical; peak mem 130.74 GiB (unchanged). The speedup (1.1185) ≈ the 3-switch full check (1.1192), confirming the empty-init is below noise and harmless. This is the officially-validated final submission.
6.0 hRound 10 — expensive lever tested: CUDA graphs for the rollout forwards (measured, ≤sub-noise)
- The hook correctly pushed me to actually test the expensive lever rather than dismiss it. I added CUDA-event + wall timing to the image-gen (generate_image_mix) and text-gen (generate_text_batch) forwards, gated by env vars (then reverted them).
- First read was flawed: CUDA-event *elapsed* ≈ wall in every case (image-gen gen ≈4.9s / edit ≈9.5s; text-gen gen ≈6.3s / edit ≈9s), but that is expected regardless of busy/idle — the events span the whole forward — so it does not prove GPU-boundedness.
- Authoritative measure is the round-6 profile: GPU-busy 13.3s/step < wall 21s/step ⇒ the step is CPU-bound (GPU idle ~8s waiting on the CPU), so launch overhead is the relevant lever.
- But the capturable part is sub-noise: the image-gen forward's launch overhead is only ~0.1s (26-47 forwards × 28 layers × ~20 kernels), below the ~2% noise floor, and its CFG path branches (2-3 forwards in vs out of the cfg_interval) needing multiple captured graphs + FSDP-all-gathered params. The text-gen forward — the dominant launch cost (~1.1s, ~215k launches) — cannot be graph-captured (per-token varying active-sequence count and growing KV cache_seqlens), and its ops can't be fused (N1). Custom GEMM/attention kernels reproducing cuBLAS/flash-attn rounding bit-for-bit are infeasible under N0.
- Conclusion: the CUDA-graph lever yields ≤~0.1s (image-gen only, below noise); the dominant text-gen launch cost is uncapturable. Not worth the complexity/bitwise risk. Submission unchanged (cca2df7, full-check PASS 1.1185 N0).
6.4 hRound 11 — expensive lever attempted: fused-RoPE rewrite (measured regression, reverted)
- The hook correctly pushed me to actually attempt a rewrite. Candidate: apply_rotary_pos_emb builds rotate_half(q)=cat(-x2,x1) (a full copy) then multiplies; I rewrote it to compute the two half-dim outputs directly (q1·c1 − q2·s1, q2·c2 + q1·s2).
- Bitwise: verified identical — standalone test across dtypes (bf16/fp32/fp16) and shapes: (-a)*b == -(a*b) and a+(-b) == a-b in IEEE fp32 (neg is exact), so it reproduces (q*cos)+(rotate_half(q)*sin) exactly.
- But measured (microbenchmark at the real query shapes) it is a net regression: text-gen query [4,H,128] = 102.9 vs 72.0 us/call (1.42× slower); image-gen query [1024,H,128] = 153.6 vs 162.1 us/call (0.95×, slightly faster). The step is CPU/launch-bound and the text gen calls RoPE ~580×28× more often than the image gen, so the 7-launch rewrite (vs the original 5) loses far more than it gains. Reverted.
- Lesson recorded: on a launch-bound step, "fewer intermediate tensors" rewrites that add kernel launches regress; the original RoPE was already lean. Submission unchanged (cca2df7, full-check PASS 1.1185 N0).
6.5 hRound 12 — expensive lever attempted: L4 Triton fused-RoPE kernel (fast but N1, reverted)
- The hook correctly pushed me to actually attempt a custom kernel. I wrote a Triton kernel fusing the whole RoPE (both q and k) into one launch (vs the original ~10 ops/kernels), computing the two half-dim outputs with the rotate_half partner.
- Fast: 2.6× (text-gen query [4,H,128]), 6.2× (image-gen query [1024,H,128]) — a real launch reduction on the launch-bound step.
- But not bitwise (N1): a persistent ~1-ULP fp32 mismatch vs PyTorch's separate-kernel (q*cos)+(rotate_half(q)*sin). Preventing LLVM's FMA contraction with inline-asm mul.f32/add.f32 (the documented way to match library rounding) reduced but did not eliminate it. That 1-ULP fp32 delta flips the downstream bf16 cast on rounding-boundary elements and would propagate into gate 2 (not N0).
- Conclusion (now demonstrated, not asserted): a fused elementwise kernel cannot cheaply reproduce PyTorch's per-op rounding bit-for-bit here, so the L4 lever is blocked by the N0 constraint. Submission unchanged (cca2df7, full-check PASS 1.1185 N0).
- bf16-absorption check: the RoPE output is cast to bf16 downstream, so I tested whether the 1-ULP fp32 delta is absorbed. It is not — 3772 / 401M elements (0.0009%) still differ after the bf16 cast, which would propagate into the parameters and break gate 2. Confirms the kernel is unusable under N0.
6.8 hRound 13 — re-profile the current best (reward-overlap + empty-init active): no new N0 hotspot
- Re-profiled to look for a hotspot the reward-overlap/empty-init may have exposed. Phase timing (steady state): gen step (~13.5s) rollout ~10.2s (76%), reward_adv ~1.4s, train ~1.8s; edit step (~28s) rollout ~20.5s (73%), reward_adv ~2s, train ~5.7s. time speedup 1.1155 (with phase-sync overhead; full check = 1.1185).
- Confirmed the reward-overlap works (reward_adv residual fell from ~4.4s serial to ~0-5s) and cut the step ~2.6-3.4s vs pre-overlap. The rollout (now including the hoisted prepack+pack+ref-forward prologue) is still dominant and is the model's own compute (text autoregressive gen + image denoising) — irreducible. reward_adv residual is the judge's service latency; train is the AC backward. No new N0 hotspot. Submission unchanged (cca2df7).
6.8 hRound 15 — measured the one remaining lever (text-gen launch overhead) and judged graphing too risky
- Microbenchmarked the launch-bound per-op cost at the text-gen shape: ~8.6 µs/op, ~2.6 ms/token pure-launch floor for 28 layers → several seconds of launch overhead across the ~580-token edit text gen. This is the single remaining real lever (CUDA-graph the autoregressive forward).
- But capturing it needs a fixed-batch + finished-sequence-masking rewrite of the generation loop with the growing static KV cache (sequences finish at different times → varying query shapes), a multi-hour change with high bitwise risk (masking/cache/finished-seq semantics). Judged not worth risking the verified submission for the remaining time; recorded here as the evidence-based reason it was not pursued. Submission unchanged (cca2df7, full-check PASS 1.1185 N0).
- Decisive N0 blocker: a fixed-batch capture would make already-finished sequences keep drawing from the sampler's generator (the loop currently stops sampling once a sequence emits EOS), changing the RNG stream and hence every downstream draw → not bitwise. Together with the per-token varying active-set shapes, the text-gen CUDA-graph lever is infeasible under N0 (not merely complex).
7.4 hRound 17 — N0: defer the loss-section logging syncs (`.item()` → `.detach()`, read after backward)
- The loss section interleaves ~13 .item() / tensor-format calls with the GPU-bound loss computation, each forcing a
  device sync that stalls the pipeline: 10 loss_dict[...].append(X.item()) (text ratio mean/max/min + policy + kl;
  image ratio mean/max/min + policy + kl), plus logger.info(f"...log_prob_per_image: {log_prob_per_image}") (a
  full tensor→str, forcing a sync) and logger.info(f"...Image Loss: {img_loss.item():.4f}, ...") immediately
  before loss.backward().
- Change (train/online_rl.py, no switch — logging is inert in both timed and judged runs, so gating it would only
  risk a divergent code path): the 10 appends now store .detach() 0-dim tensors; the all_reduce loop converts them
  with .item() after the backward (where the GPU is already drained and the read is free). The two sync-forcing
  logger.info lines in the loss section are removed. The mandatory data-dependent branch
  if per_token_kl.item() > 10: is kept (control flow, cannot be deferred), as is the logger.info immediately
  before it (the sync happens at the branch anyway, so removing it saves nothing).
- N0 by construction: the appended values are the same floats, read later; sum()/all_reduce/torch.tensor
  operate on identical inputs; the loss, backward, RNG stream and collective order are untouched. The downstream
  wandb_log already handled both (v.item() if torch.is_tensor(v) else float(v)).
- check --quick (out /tmp/check-r17): PASS, bitwise N0 — 14 optimizer steps, 3200 tensors + 235 reward
  requests identical; peak mem 130.54 GiB (unchanged). time (out /tmp/time-r17):
  speedup = 1.1095, 21.12 s/step (windows 20.72 / 20.97 / 21.69).
- Verdict: kept, gain below the ~2% noise floor. 1.1095 sits inside the observed 1.109-1.119 band for the same
  tree (full check 1.1185 / 1.1192), i.e. not resolvable from a single time run. The change removes real sync stalls
  from the loss critical path and is N0-verified with no memory regression, so it is retained as harmless; it is not
  claimed as a measured speedup.
7.9 hRound 18 — N0: batch the text-generation bookkeeping (BAGEL_TEXTGEN_BATCH) — **measured gain**
- Bagel.generate_text_batch (modeling/bagel/bagel.py) ran a per-sequence Python loop over
  active_sequences_original_indices.split(1) with ~4 D2H syncs per active sequence per step
  (original_batch_idx.item(), active_curr_tokens[i].item(), the if curr_tokens[...] == end_token_id
  control-flow test, next_tokens_probs[i].item()) plus 2 in-place index-puts — over 196 (gen) / 384
  (edit) autoregressive steps × the active sequences. On a step that is CPU/sync-bound this is pure
  serialization overhead in the dominant rollout phase.
- Rewrite (behind BAGEL_TEXTGEN_BATCH, off by default): compute the end-token mask on the GPU
  (active_curr_tokens != end_token_id — exact because `active_curr_tokens ==
  curr_tokens[active_sequences_original_indices], so the test on curr_tokens` is the same test), force the
  end token at max_length-1 on the still-active sequences only via torch.where, scatter the new tokens
  with one torch.where (inactive sequences get their own old token back, which the reference never wrote
  ⇒ no-op), then read the bookkeeping with 2 .tolist() syncs per step instead of ~4 per sequence.
- Verified before any GPU time: a standalone randomized equivalence test (20,000 trials: batch 1-16,
  vocab 100k, arbitrary sorted active subsets, some/all end tokens, max_length-1 forcing) — 0 mismatches
  on curr_tokens, the mask, generated_sequence, generated_probs and the element types. **The test
  caught a real bug first**: the max_length-1 torch.where was inverted (it forced the end token on the
  *inactive* sequences); fixed to torch.where(still_active, end_token_id, next_tokens).
- check --quick (out /tmp/check-r18, all 5 switches): PASS, bitwise N0 — 14 optimizer steps,
  3200 tensors + 235 reward requests identical, peak mem 130.54 GiB (unchanged). time
  (out /tmp/time-r18): speedup = 1.1262, 20.81 s/step (windows 20.51 / 20.64 / 21.29).
- Verdict: KEPT — the first above-noise gain since round 4. Every window improved vs round 17
  (20.72→20.51, 20.97→20.64, 21.69→21.69→21.29), i.e. −0.31 s/step (−1.5%), consistently, with an
  understood mechanism (sync + launch reduction in the text-gen rollout loop). This lifts the tree above
  the previously-validated 1.1185.

### Full check on the 5-switch tree (out /tmp/full-4) — PASS, speedup 1.1315, bitwise N0
- STATUS PASS, speedup = 1.1315, bar 1.043 (passed, ~8.5% margin). bitwise True, tier N0, no problems; 14 optimizer steps, 3200 tensors + 235 reward requests identical; peak mem 130.74 GiB (unchanged).
- Up from /tmp/full-3's 1.1185: the round-18 text-gen bookkeeping batching is worth +1.3% end-to-end, confirming the time reading (1.1262) was not noise. This is the officially-validated submission state (ca0c69f, 5 switches).
8.8 hRound 19 — N0: extend empty-init to the two remaining inference-path zero-inits (BAGEL_EMPTY_INIT) — below noise
- Two fully-overwritten zero-inits were still on the inference (rollout) path, the hot one for the image denoising:
  1. modeling/bagel/bagel.py _forward_flow: packed_text_embedding.new_zeros((sum(packed_seqlens), hidden)),
     immediately overwritten by the text and vae scatters. ~35 calls/image-gen × 2 rounds/step.
  2. modeling/bagel/qwen2_navit.py Qwen2MoTDecoderLayer.forward_inference (mode=="gen") MLP split:
     torch.zeros_like(q).to(torch.bfloat16), overwritten by the und(text)+gen(vae) scatters.
     ~28 layers × ~35 forwards × 2 rounds/step.
- N0 argument (same as rounds 7-9, and empirically verified there): in the gen-mode image flow
  packed_text_indexes ∪ packed_vae_token_indexes covers the whole packed sequence — the *same* index tensors
  whose full coverage the already-N0-verified gen-mode MoT splits at qwen2_navit.py:1258 (forward_train) and
  :1522 (forward_inference final norm) rely on. Deliberately not touched: the two analogous sites in
  forward_cache_update_vit (:413) and forward_cache_update_vae (:550), whose packed sequences also carry ViT
  tokens, so their coverage is not established by the same argument.
- check --quick (out /tmp/check-r19, all 5 switches): PASS, bitwise N0 — 3200 tensors + 235 reward
  requests identical, peak mem 130.54 GiB. time (out /tmp/time-r19): speedup = 1.1223, 20.88 s/step
  (windows 20.62 / 21.00 / 21.03).
- Verdict: kept, below noise (neutral). 1.1223 vs round 18's 1.1262 is a 0.3% difference, inside the ~2%
  noise floor (two windows slightly worse, one better). The change removes ~2000 memset/copy kernels per step
  and is N0-verified, so it is retained as harmless; not claimed as a gain. Consistent with rounds 7-9: the
  empty-init class is a real but sub-noise GPU-work reduction.
9.6 hRound 20 — N0: one nonzero per mask in the static-KV merge (BAGEL_MERGE_SEL) — neutral (profile-led, disproved)
- Profile first (profile --from 11 --iters 2, out /tmp/prof-r20) on the current best: aten::nonzero
  19,312 calls / 2 steps (≈9,656/step) at 15.15% CPU total, and aten::_local_scalar_dense 187,883 calls
  (≈94,000/step). Traced the source: _merge_static_kv_prefix_and_query (qwen2_navit.py, called from *both*
  the static-KV read and read-only attention paths, i.e. ~28 layers × ~111 image forwards/step) evaluated each
  boolean-mask selection once per use — batch_idx[past_mask] and past_pos[past_mask] twice each (once for
  k, once for v), past_dest[past_mask] twice, new_dest[new_mask] twice = 8 nonzero + 8 index per call.
- Rewrite (behind BAGEL_MERGE_SEL): a flat row-major mask index decomposes as s = sel // span,
  p = sel % span, so X[mask] becomes X.reshape(-1)[mask.reshape(-1).nonzero(as_tuple=False).reshape(-1)]
  with one nonzero per mask (2 total), no grid materialisation, and the same gathers/scatters.
- Verified before any GPU time: standalone randomized equivalence test (4,348 trials: non-contiguous/unsorted
  cache-index subsets, effective_seqlens 0..4 incl. total_past == 0, non-uniform query_lens, max_len
  constraints) — 0 mismatches on merged_k and merged_v.
- check --quick (out /tmp/check-r20, all 6 switches): PASS, bitwise N0 — 3200 tensors + 235 reward
  requests identical, peak mem 130.54 GiB. time (out /tmp/time-r20): speedup = 1.1224, 20.88 s/step
  (windows 20.09 / 21.18 / 21.38).
- Verdict: kept, NEUTRAL — the profile's 15% was not critical path. 1.1224 ≈ round 19's 1.1223 and 0.3%
  below round 18's 1.1262 (inside the ~2% noise floor). Cutting the nonzero count 4× (≈9,656 → ≈2,414/step)
  bought nothing measurable, so those syncs were overlapping GPU work rather than stalling the CPU. Recorded as
  a disproved hypothesis: **nonzero's large CPU-total share is mostly wait that is already hidden, not a
  reducible host cost** — the same shape of lesson as Command Buffer Full (12.28% CPU, also overlapped wait).
10.1 hRound 21 — revert rounds 19-20: keep the best-validated tree (`ca0c69f`, full check 1.1315)
- Rounds 19 (empty-init extension, 2 sites) and 20 (merge-sel) were each N0-verified and each *provably less work*
  (~12k fewer memsets; ~7k fewer nonzero), yet both measured below the round-18 tree:
  | tree | full check | time |
  |---|---|---|
  | ca0c69f (5 switches) | 1.1315 (/tmp/full-4) | 1.1262 (/tmp/time-r18) |
  | b4591cb (+round 19) | — | 1.1223 (/tmp/time-r19) |
  | 2f9d921 (+rounds 19-20) | 1.125 (/tmp/full-5) | 1.1224 (/tmp/time-r20) |
- Four independent samples all favour ca0c69f by 0.3-0.6%. That is inside the ~2% noise floor, so it is **not
  statistically resolvable** — but since neither round produced a gain and the full check *is* the score, the
  best-evidenced tree is the one to submit. Reverted both (git revert b4591cb 2f9d921); the tree is now
  byte-identical to ca0c69f (verified: git diff ca0c69f empty) and switches.json is back to 5 switches.
- Lesson recorded: a provable GPU-work reduction is not sufficient — on this workload the measurement must also
  not move, and sub-noise changes are as likely to read low as high. The changes are preserved in git history
  (b4591cb, 2f9d921) and can be re-applied if a later paired measurement (sweep) shows them neutral-or-better.
↑ R3