Step-5 Preview 2.42×

Harness: Claude Code · switches: none

Judged
2.42×
Tier
N1
Self-best
2.42×
Rounds
26
Hours
10.1
API cost
$35.2
Input tokens · 99.5% cached
313 M
Output tokens
0.9 M
Requests
726
Sequence packing
✓ round 5 LLAVA_PACKED, 2150.3 → 1576.4 ms at the same GC=12 (1.289 → 1.758×)
Recompute / activations
✓ LLAVA_GC_SKIP raised from 8 layers to all 32 layers without recompute (rounds 1, 9), with expandable_segments (round 8); under ZeRO-2, GC=24 → 32 gives 1362.9 → 1281.9 ms
Optimizer
✓ rounds 24–25 LLAVA_DS_ADAM, two Triton kernels (moment update + tail), 1182.7 → 1144.6 ms; round 20 skips the multiply-by-1 unscale + fused grad norm, 1222.1 → 1193.8 ms
Communication & libraries
partial: round 6 ZeRO-2 (1451.7 → 1361.2 ms), bucket 1e9; no cuBLAS / FlashAttention swap (round 19 concluded "833 ms is irreducible GEMM"), overlap_comm left on
Other main levers
hand-written Triton: RoPE (rounds 2, 21), RMSNorm (rounds 3, 14, 23), SiLU·up (round 10), CLIP quick_gelu (round 22); CLIP on SDPA (1259.8 → 1250.3 ms); input-assembly syncs 48 → 3 + a single embedding lookup; LM head not restricted to supervised positions; fused QKV 11% slower in the model, reverted
Raw work log29 sections
—Round 0 — profile the unchanged reference
profile --tree /submission/llava --detail → /tmp/r1/profile (one profiled step, 10732 kernels).
GPU kernel time 2880 ms for a 2684 ms step; the union of kernel intervals is 2360 ms over a 2585 ms
span, so the GPU is busy ~91% of the step and NCCL (529 ms: 277 reduce-scatter + 252 all-gather,
both on their own streams) is almost entirely overlapped with compute.

Top GPU time: bf16 GEMMs 1338 ms (47%, running at ~690 TFLOP/s = 96% of the measured device peak),
elementwise ~1000 ms, NCCL 529 ms, flash-attn 78 ms, AdamW 55 ms.
Notable structure: 32 CheckpointFunctionBackward nodes and 64 forward passes per step → **every
decoder layer is recomputed** by gradient checkpointing; 1048 aten::mm; 165 aten::item (host
syncs); 112 aten::nonzero; aten::to 3213 / aten::copy_ 1854 calls.
RoPE (apply_rotary_pos_emb) ≈ 280 ms, LlamaRMSNorm ≈ 200 ms, the flash-attn unpad/pad
(index_first_axis + pad_input + _get_unpad_data) ≈ 108 ms.

Key discovery: LLaVA's llava/train/llama_flash_attn_monkey_patch.py is dead code in this recipe —
train_mem.py passes attn_implementation="flash_attention_2" and nothing calls
replace_llama_attn_with_flash_attn(). The attention is transformers' own LlamaFlashAttention2, and
RoPE is applied by the module-level transformers.models.llama.modeling_llama.apply_rotary_pos_emb.
Any change to the attention path has to patch that.
—Round 1 — gradient checkpointing: keep the first N layers' activations (`LLAVA_GC_SKIP`)
llava/model/language_model/llava_llama.py: intercept the _gradient_checkpointing_func assignment
that PreTrainedModel._set_gradient_checkpointing makes on the LlavaModel (via a property with a
setter) and wrap it so layers with idx < LLAVA_GC_SKIP run without the checkpoint wrapper.
Skipped layers are identified through layer.self_attn.layer_idx (the LlamaDecoderLayer itself
carries no index in transformers 4.37 — the first attempt keyed on layer.layer_idx and silently did
nothing, which the unchanged peak memory gave away).

Tier N0: checkpointing only decides whether a layer's forward is re-run inside its backward; the
arithmetic and the RNG stream are unchanged.

| config | ms/step | speedup | peak GiB |
|---|---|---|---|
| reference (sweep arm) | 2769–2779 | 1.000 | 73.5 |
| LLAVA_GC_SKIP=8 | 2620.0 | 1.058 | 120.1 |
| LLAVA_GC_SKIP=16 | — | ERROR (OOM) | — |

≈19 ms saved per layer that stops being recomputed; the binding constraint is activation memory
(~5.8 GiB per kept layer on the peak batch), not compute.
—Round 2 — fused rotary position embedding (`LLAVA_FUSED_ROPE`)
llava/train/fused_rope.py: one Triton kernel (forward + backward, ADJOINT flag) replacing
q*cos + rotate_half(q)*sin and its autograd graph, installed by patching
transformers.models.llama.modeling_llama.apply_rotary_pos_emb at import of the model module.
Verified bitwise identical (forward and backward) against upstream for shapes
16x32x1113x128, 2x32x877x128, 1x32x2048x128, 16x32x512x128, 3x8x65x64, 16x32x100x128 and for both
cat-structured and random cos/sin tables. Isolated: fwd+bwd 5.08 ms → 1.21 ms.
Tier N0.

| config | ms/step | speedup |
|---|---|---|
| LLAVA_FUSED_ROPE=1 | 2607.0 | 1.063 |
| + LLAVA_GC_SKIP=8 | 2459.3 | 1.127 |
—Round 3 — fused LlamaRMSNorm (`LLAVA_FUSED_NORM`)
llava/train/fused_norm.py: the squares are written by a Triton kernel but the reduction is still
PyTorch's own mean and the scale is still torch.rsqrt(v + eps), so **the forward is bitwise
identical**; the two dtype copies, the weight multiply and the whole backward collapse into single
kernels (forward ~2.9 GB → ~1.0 GB of traffic, backward ~3.5 GB → ~0.44 GB). Only the order of
sum(d_h * h) in the backward's scale gradient differs (3.7e-5 RMS relative on the gradient).
Tier N1 (gradients only; the forward is bitwise).
—Round 3b — RoPE output layout
The RoPE kernel now returns a view of a [b, seq, heads, dim] buffer (strides are the transposed
ones), so the transpose(1, 2) that LlamaFlashAttention2.forward does next is contiguous and the
unpad reshape(b*seq, heads, dim) is a free view instead of a 146 MB copy per tensor. Bitwise
identical (verified forward and backward).
—Round 4 — full check of RoPE + RMSNorm + `LLAVA_GC_SKIP=12`
check --tree /submission/llava --config /submission/switches.json → **PASS, speedup 1.2919,
tier N1** (/tmp/r1/check/check.json). Gate 0 passes with the reference's own partition; gate 2 has no
exact failures and no violations (4724 tensors checked, worst relative L2 14.7% against a 23% calibrated
gate, all of them LlamaRMSNorm.weight gradients / Adam states); gate 3 is far inside the band —
train_loss_last20_canonical −7.5e-5 (0.024σ, bound 0.0093) and probe_loss_last20 +1.05e-4 (0.037σ,
bound 0.0086).

| config | ms/step | speedup | peak GiB |
|---|---|---|---|
| reference | 2771.6 | 1.000 | 73.5 |
| RoPE + Norm | 2345.0 | 1.182 | 72.5 |
| + GC_SKIP=8 | 2213.0 | 1.252 | 103.6 |
| + GC_SKIP=12 | 2150.3 | 1.289 | 119.1 (reserved 137.1 of 140.4) |
| + GC_SKIP=16 | — | OOM | — |

### Dead ends measured this session
- LLAVA_TOKEN_LENGTHS (word count → token count as the sampler's length key). Simulated the real
  get_modality_length_grouped_indices + split_to_even_chunks on the timing fixture: word key 32.9%
  mean padding, token key 32.9%, true-length key 33.1% — no difference. The megabatches come from
  torch.randperm, so the key only re-orders inside a megabatch; the step's sample multiset is
  unchanged (verified), but the padding is not improved. Reverted.
- Re-partitioning the 32 samples of a step between the two GPUs. The step time is
  16 x max(L) for whichever GPU holds the longest sample, and that sample is in the step whatever the
  split, so no partition beats 16 x L_max. The only real fix is to stop padding at all (run the LLM
  on the packed token layout), which is a rewrite of LlamaModel/LlamaDecoderLayer/attention/loss.
—Round 5 — packed (unpadded) sequence layout (`LLAVA_PACKED`)
The reference pads every micro-batch to its longest sample: the trace shows
index_first_axis gathering a [13600, 4096] slice out of [17808, 4096], i.e. **23.6% of every
padded token is padding**, and all of it goes through the projection GEMMs, the layernorms, the MLP and
the residual.  Re-partitioning the 32 samples of a step between the two GPUs cannot fix it (the step
time is 16 x L_max whichever GPU holds the longest sample), and changing the sampler's length key
does not either (measured).  So the layout itself changes:

* prepare_inputs_labels_for_multimodal concatenates the per-sample embeddings / labels / positions
  instead of padding and stacking them, and returns a [1, total, hidden] tensor (the samples, their
  order and their contents are untouched — gate 0 still sees the reference's own partition).
* LlamaFlashAttention2._flash_attention_forward is patched to call flash_attn_varlen_func with the
  batch's cu_seqlens — the same call the reference makes after unpad-ing, so the attention is
  unchanged and the whole unpad/pad round trip disappears.
* the loss is the same mean cross entropy over the same supervised tokens, shifted per sample instead
  of across the padding.

Correctness checked on a real LlamaDecoderLayer: equal-length batches are bitwise identical to
the padded reference, unequal lengths differ by 2 bf16 ULP (only the cuBLAS tile selection for a
different M).  Two bugs found and fixed on the way: cumsum promotes to int64 (flash-attn rejects a
non-int32 cu_seqlens), and ModelOutput.loss = x does not add the loss key when it was None.

| config | ms/step | speedup | peak alloc GiB | reserved GiB (of 140.4) |
|---|---|---|---|---|
| reference | 2771.6 | 1.000 | 73.5 | 77.8 |
| RoPE+Norm, GC=12 | 2150.3 | 1.289 | 119.1 | 137.1 |
| + packed, GC=12 | 1576.4 | 1.758 | 86.9 | — |
| + packed, GC=20 | 1499.0 | 1.849 | 102.4 | 123.8 |
| + packed, GC=24 | 1445.9 | 1.917 | 110.5 | 136.1 |
| + packed, GC=28 | 1406.8 | 1.970 | 118.5 | 136.8 |

Packing also removes ~39 GiB of activation memory, which is what lets LLAVA_GC_SKIP go from 12 to
20+ (each kept layer now costs ~2 GiB instead of ~3.9).
—Round 6 — DeepSpeed ZeRO stage 2 (`scripts/zero3.json`)
scripts/zero3.json is what the judge runs the candidate with, and the task statement allows the
stage to change.  Stage 2 keeps a full bf16 copy of the parameters on each rank, so the 264 ms/step of
parameter all-gather traffic and the LinearFunctionForZeroStage3 autograd nodes disappear.  The
gradient reduce-scatter, the fp32 master weights and the Adam state are unchanged (the judge's
safe_get_full_* helpers handle stages 1/2 through _hp_mapping and stage 3 through ds_id).
time: 1451.7 → 1361.2 ms/step.
—Round 7 — checks
| switches | ms/step | speedup | status | tier | probe_loss in σ |
|---|---|---|---|---|---|
| RoPE+Norm, GC=12 | 2150.3 | 1.289 | PASS | N1 | 0.037 |
| + packed, GC=20 | 1499.0 | 1.849 | PASS | N1 | 0.300 |
| + packed, GC=24 | 1451.7 | 1.909 | PASS | N1 | 0.411 |
| + packed, GC=24, ZeRO-2 | 1362.9 | 2.034 | PASS | N1 | 0.690 |

All four are check runs in /tmp/r1/check, /tmp/r3/check, /tmp/r3/check24, /tmp/r3/check2.
Gate 2 is NOT_BITWISE for every packed/ZeRO-2 configuration (the GEMM shapes change); the per-tensor
violations are all resolved by the judge's fp64 arbitration, with zero exact failures.  The probe-loss
bias grows with each change but stays under a quarter of the 3σ budget.

Things that did not help, measured: stage3_max_live_parameters 1e9 → 3e8 (no memory saved, 2%
slower); the word→token length key for the sampler (no padding change).
—Round 8 — allocator fragmentation (`PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True`)
With the default allocator, 28 kept layers OOM'd while 61 GiB sat reserved-but-unallocated.
expandable_segments:True removes that fragmentation at no cost to the code path or the numerics.
(max_split_size_mb:256 was tried instead and cost 24% — much worse.)
—Round 9 — gradient checkpointing fully off at the packed layout (`LLAVA_GC_SKIP=32`)
Each kept layer now costs ~2 GiB instead of ~3.9 (the activations scale with the real token count), so
all 32 layers can keep theirs: 1322.6 → 1297.2 ms/step.
—Round 10 — fused gated activation (`LLAVA_FUSED_ACT`)
llava/train/fused_act.py: one Triton kernel for silu(gate_proj(x)) * up_proj(x) instead of SiLU +
a multiply, forward and backward. The forward is bitwise identical to upstream and the backward
matches to 7e-8 relative. Isolated 0.390 → 0.209 ms for a 13600 x 11008 bf16 pair.
—Round 11 — SDPA for the frozen CLIP vision tower (`LLAVA_CLIP_SDPA`)
transformers 4.37.2 has no SDPA variant for CLIP, so CLIPAttention.forward runs the eager path
(bmm -> softmax -> bmm), materialising a [256, 577, 577] bf16 score tensor per layer for each of
the 24 layers.  llava/train/clip_sdpa.py routes it through F.scaled_dot_product_attention, keeping
upstream's bf16 scaling of q before the call and passing scale=1.0, so only the bf16 rounding of the
scores in between is lost.  Isolated: 1.424 -> 0.945 ms per attention.  time: 1259.8 -> 1250.3 ms/step.
—Round 12 — hoisting the per-sample GPU syncs (`llava/model/llava_arch.py`)
Upstream strips the padding with a boolean mask per row and then does two more device->host syncs per
sample for the image-token count and positions: 48 syncs per micro-batch, each stopping the CPU from
queuing the per-sample embedding work ahead of the GPU.  One batch-wide reduction replaces them (3
syncs) and the image positions are derived on the host.  Values unchanged.  time: 1264.9 -> 1259.8.
—Round 13 — DeepSpeed `reduce_bucket_size`
The auto bucket for ZeRO-2 is 5e8 elements, which splits the 6.7B-parameter gradient into ~14
reduce-scatter rounds with a flat-buffer copy each.  Measured: 5e8 -> 1250.3 ms, 1e9 -> 1240.0 ms,
2e9 -> 1239.0 ms, 4e9 -> 1964.8 ms (one huge bucket loses the overlap and the memory).  1e9 was
chosen over 2e9: the same speed but 3.7 GiB less reserved (130.4 vs 135.9 of 140.4), which leaves room
for the gate-2/gate-3 fixtures.

### Tried and rejected this session
- ZeRO-3 again with the packed layout: 1349.6 ms vs ZeRO-2's 1264.9 — stage 2 stays.
- contiguous_gradients: false: 1278.9 ms (and with a big bucket 1237.8, a wash) — reverted to true.
- stage3_max_live_parameters 1e9 -> 3e8: no memory saved, 2% slower.
- foreach=True on the AdamW: no speed change (1250.9 vs 1250.3) but the numerics moved — reverted.
- max_split_size_mb:256: 1691 ms — 24% slower than expandable_segments:True.
6.7 hRound 14 — the remaining torch ops inside the fused RMSNorm (`LLAVA_FUSED_NORM`)
The profile showed the norm still spending 12.9 ms and two kernels per call on the variance: a Triton
kernel writing a 222 MB fp32 square buffer, then aten::mean reducing over it (444 MB of round trip,
plus 9.5 ms of host bubbles around it).  Replaced by one _var_kernel pass over x.  The tree reduction
differs from aten::mean's order by ~1e-7 relative on the variance, which flips 0.00025% of the bf16
outputs by one ULP (1.1e-5 RMS relative) — the forward stops being bitwise, but the perturbation is two
orders of magnitude below the packing's.  Isolated: fwd 0.786 -> 0.096 ms, fwd+bwd 3.327 -> 1.279 ms.
time: 1240.6 -> 1234.4 ms/step.

The weight gradient was likewise (dy * hb).reshape(-1, d).sum(0): a 222 MB materialised product then a
reduction along the non-contiguous axis.  A 2-D grid of column blocks with atomic accumulation reads dy
and hb once (the order is not fixed, so dw differs by ~1e-6 relative).  Isolated fwd+bwd 3.318 -> 1.243 ms.
time: 1234.4 -> 1232.0 ms/step.
—Round 15 — fused QKV projection: REJECTED
LlamaFlashAttention2.forward runs q/k/v as three [13600, 4096] x [4096, 4096] GEMMs; one
[13600, 4096] x [4096, 12288] GEMM measures 11% faster in isolation (1.911 vs 2.122 ms), and the
backward's dy @ W fuses the same way.  Implemented in llava/train/fused_qkv.py behind
LLAVA_FUSED_QKV (the parameters are not merged — their weights are concatenated for the call, inside
the autograd graph, so the cat's backward splits the gradient back into q_proj.weight etc.).

In the real model it is 11% slower: 1240.6 -> 1372.5 ms/step.  The profile explains it — the kernel
time is unchanged (1222 vs 1223 ms) while the step grows by 130 ms, i.e. it becomes host-bound: the
weight torch.cat (24.6 ms of CPU ops) plus SplitWithSizesBackward0 (22.1 ms) plus the extra autograd
nodes.  The step has only ~17 ms of host slack, so any change that adds host time loses even when the
kernels get cheaper.  Reverted (the switch is off; the file stays as a record of the measurement).
—Round 16 — patching DeepSpeed's optimiser from the tree: REJECTED (no gain)
The profile attributed ~15 ms to a no-op param.data.mul_(1 / combined_scale) in
DeepSpeedZeroOptimizer_Stage2.unscale_and_clip_grads (with bf16 loss_scale == 1 and a gradient norm
far below clip_grad_norm, the factor is exactly 1.0 on a 3.4 GB partition) and ~20 ms to
get_grad_norm_direct, which converts every parameter's gradient to double, norms it and calls
.item() — ~160 fp64 copies and 160 device->host syncs per step.

Both were patched from the tree (llava/train/ds_patch.py, installed from llava_llama.py like the
transformers patches): the unscale skips the loop when the factor is 1, the norm uses one
torch._foreach_norm per 128 tensors with a single host read (falling back to the original whenever the
norm comes within a tenth of clip_grad_norm, so the clipping decision is preserved).

Measured: unscale alone 1232.4 ms/step vs 1232.0 without — a wash (the 15 ms of mul_ is not that
loop), and adding the fused norm made it 1234.9 ms. Reverted; the file is gone.  DeepSpeed's
optimiser prologue is not improvable from the tree.
6.7 hRound 14–16 net
2.2341 -> 2.2496 (time), validated by check at 2.2481.  The two accepted changes are the
fused RMSNorm variance (+0.5%) and the fused weight-gradient reduction (+0.2%); the fused QKV
projection and the DeepSpeed patches were both measured and rejected.
—Round 17 — one embedding lookup per micro-batch instead of one per sample
prepare_inputs_labels_for_multimodal called embed_tokens once per sample — 16 small gathers plus 16
id concatenations per micro-batch, all on the host's critical path (the step has only ~17 ms of host
slack, so host work is as expensive as kernel time).  The image tokens are dropped from the flat id
sequence first, so each sample's chunks are contiguous slices of a single lookup; the split sizes and
each sample's text offset follow from the image positions, which are already on the host.  An embedding
lookup is a gather, so the values are bitwise the same.  time: 1232.0 -> 1230.1 ms/step.
—Round 18 — launch-config tuning of the Triton kernels
Every kernel was benchmarked against the measured 5 TB/s.  _var_kernel (3.9 TB/s), _scale_kernel
(3.9) and _gated_fwd (3.7) are already optimal at their defaults.  The RoPE kernel is 11% faster with
8 warps than the default 4, and _hb_kernel/_bwd_kernel are marginally faster with 16.
time: 1230.1 -> 1227.5 ms/step.

The dw column reduction is a further 28% faster with BLOCK_C=256, BLOCK_R=128 (0.090 -> 0.065 ms
for 222 MB), but that configuration drifts the logged loss by 0.9% by step 5 — the atomic
accumulation order changes enough to compound over a trajectory — so it was left at 128/64.  Measured
and rejected.

### Also measured and rejected this session
- A fused QKV projection (round 15): 11% faster in isolation, 11% *slower* in the model because the
  weight torch.cat and the split's backward add ~47 ms of host time to a step that has only ~17 ms of
  host slack.
- Patching DeepSpeed's optimiser from the tree (round 16): skipping the no-op mul_(1.0) on the
  gradient partition was a wash (1232.4 vs 1232.0 ms); a fused gradient norm made it worse (1234.9).
- A "contiguous row" RoPE kernel that walks whole seq rows of heads*dim contiguous elements
  instead of scattered 256-byte rows: bitwise identical and verified, but 0.287 ms vs 0.245 ms for the
  scattered one — the redundant cos/sin loads cost more than the locality gains.
—Round 19 — the remaining non-GEMM budget: measured, nothing left to take
Profiled the current best (1210 ms of kernel time for a 1227.5 ms step — the GPU is 98.6% busy, so
there is no host slack and nothing left to overlap).  Every remaining non-GEMM item was chased to its
cause:

| item | ms/step | finding |
|---|---|---|
| cuBLAS bf16 GEMMs | 833 | 646–674 TFLOP/s is cuBLAS's own limit for these shapes (the lm_head, with N=32000, reaches 740).  The FLOPs are the model's own; LLAVA_GC_SKIP=32 already removed every recomputed forward |
| AdamW multi_tensor_apply | 65 | 1141 kernels = one per tensor per op (163 tensors × 2 groups × ~4 ops).  87.8 GB of traffic → 17.6 ms at peak, so it runs at 1.35 TB/s.  foreach=True explicitly: no gain (round 16).  Inside PyTorch |
| direct_copy (17 × the 6.76 GB gradient partition) | 38 | traced to .to() + copy_ on the flat gradient, launched from the autograd thread.  contiguous_gradients: false: 1227.9 vs 1227.5 ms — a wash, but 3.7 GiB less peak memory |
| flash-attention fwd+bwd | 68 | irreducible |
| residual adds | 18 | 224 ops at 4.2 TB/s — already 84% of peak, so fusing them into the norm would save at most 3 ms |
| RoPE | 19.8 | 2.7 TB/s is the limit for this strided access pattern; a contiguous-row rewrite measured 0.287 vs 0.245 ms (slower) |
| gated activation | 17.9 | 3.7 TB/s |
| my five Triton kernels | 21 | 3.9 TB/s each |

Also re-tested in isolation this round:
- contiguous_gradients: false (with reduce_bucket_size 1e9): 1227.9 ms — no speed change.
- A fused gradient norm replacing DeepSpeed's per-parameter fp64 norm + .item(): 1228.0 ms — no
  change, so the fp64 norm is not a bottleneck.  Both reverted.

Conclusion: the step is 1229 ms of which 833 ms is irreducible GEMM.  The submission stays at
2.2545× (validated), and time re-confirms 1229.5 ms / 2.2543 on the restored tree.
—Round 20 — DeepSpeed's optimiser prologue, with the class name actually right
Root cause of two earlier null results: the ZeRO-1/2 optimiser class in
deepspeed.runtime.zero.stage_1_and_2 is DeepSpeedZeroOptimizer, not
DeepSpeedZeroOptimizer_Stage2.  Rounds 16 and 19 both imported the latter, the try/except in
install() swallowed the ImportError, and both "patches" were never installed — so their null
measurements said nothing about the ideas.

With the name fixed, and a print added to prove the patch fires (`loss_scale=1.0 clip_grad=0.0
norm=6.697 -> scale=1.0`, 75 calls per run):

1. unscale_and_clip_grads skipped when combined_scale == 1.  bf16 → loss_scale is exactly 1.0
   (DeepSpeed asserts this for any dtype but fp16) and clip_grad is 0.0 (the recipe has no gradient
   clipping), so the loop multiplies the 3.4-billion-element flat gradient partition by exactly 1.0 —
   15 ms of pure bandwidth.  time: 1222.1 → 1216.0 ms.
2. get_grad_norm_direct fused: it converted every parameter's gradient to double, took the L2
   norm and called .item() — an fp64 copy and a device→host sync per parameter, ~160 of each per step,
   plus 295 fp64 reduction kernels.  One torch._foreach_norm per 128 tensors with a single host read
   replaces it.  The norm is unused (clip_grad == 0), and the patch falls back to the original whenever
   clip_grad is non-zero and the norm comes within a tenth of it, so the clipping decision is preserved.
   time: 1216.0 → 1193.8 ms.
—Round 20b — CLIP SDPA without the `.contiguous()` copies
CLIPAttention._shape calls .contiguous() on q, k and v; SDPA only needs the last dimension
contiguous, which the transpose already guarantees.  Removes 72 copies of 18.9 MB per step.
time: 1229.5 → 1222.1 ms.
—Round 21 — contiguous-row RoPE kernel
The scattered RoPE kernel gave each program 16 rows of 128 elements, heads*dim (8 KB) apart, so every
256-byte read pulled a much larger DRAM burst and the swapped read missed cache — 1.08 TB/s effective.
A program that owns whole seq rows reads heads*dim contiguous elements and the swapped read lands
in the same lines: 0.242 → 0.113 ms isolated (5.9 TB/s).  Bitwise identical, verified forward and
backward for 7 shapes.  time: 1193.8 → 1186.2 ms/step.
—Round 22 — fused quick_gelu for the frozen CLIP tower (`LLAVA_FUSED_GELU`)
QuickGELUActivation.forward is input * torch.sigmoid(1.702 * input): three kernels over a
[16, 577, 4096] tensor for each of the 24 CLIP layers.  One Triton kernel reads x once, keeping every
rounding point upstream has (beta*x -> bf16, sigmoid -> bf16, x*sigmoid -> bf16) — **bitwise
identical**, verified.  Isolated 0.153 → 0.051 ms.  time: 1186.2 → 1181.8 ms/step.
—Round 23 — one-pass RMSNorm forward (`LLAVA_FUSED_NORM`, extended)
The norm's forward was _var_kernel + torch.rsqrt + _scale_kernel: the variance kernel read the
input, then the scale kernel read it again.  Folding the variance, the rsqrt and the weight
multiply into one kernel moves 2x the tensor instead of 3x.  tl.math.rsqrt is bitwise torch.rsqrt
on fp32 (verified), so the forward is bitwise identical to the two-kernel version — verified for 6
shapes.  Isolated 119.8 → 76.0 µs per norm (44 µs × 65 norm calls/step ≈ 2.9 ms).
time: 1181.4 → 1182.7 ms/step — no measurable gain (below the 0.35% run-to-run spread); kept
because it is bitwise-safe and strictly less work.
—Round 24 — fused AdamW master-weight tail (`LLAVA_DS_ADAM`) ← the round's win
_multi_tensor_adamw ends the step with four full passes over the fp32 master partition —
_foreach_sqrt (out-of-place, allocating a fresh 6.8 GB buffer), _foreach_div_, _foreach_add_,
_foreach_addcdiv_ — 10x the partition in bytes, where one pass suffices (denom is consumed by
nothing but the addcdiv).  DeepSpeed's ZeRO-2 hands the optimizer **one flat fp32 partition per param
group**, so one Triton kernel replaces all four: 21.96 → 6.06 ms per 6.76 GB partition, ×2 partitions
per rank.  time: 1182.7 → 1154.1 ms/step, speedup 2.4014 (was 2.3435); peak memory unchanged at
119.36 GiB (the transient denom buffer is gone, which frees ~13.5 GB of transient fp32).

Numerics — N0 (bitwise).  Three separate rounding traps had to be closed, each found by isolating
the op:
1. tl.sqrt is sqrt.approx.f32 (~2 ULP) → a 6.7e-5/step systematic loss drift.  tl.math.sqrt_rn
   is libdevice's IEEE round-to-nearest and is bitwise torch.sqrt.
2. PyTorch's tensor / scalar is a multiply by the fp32 reciprocal, not a division;
   div_rn is its tensor/tensor division.
3. LLVM contracts a*b + c into an FMA; PyTorch's addcdiv does not.  mul_rn/add_rn pin it.
Result: 3 of 131072 master weights differ over 20 AdamW steps, by 3.6e-12, and a whole 25-step run's
logged losses are indistinguishable from the unpatched tree's — two *identical* runs differ by more
(max 0.0013) than the patched and unpatched runs do (max 0.0018).

A crash found and fixed (important): patching at import time made the run die with
ERROR: Unexpected segmentation fault encountered in worker, 3/3 times.  Cause: DeepSpeed's ZeRO-2
constructor (initialize_optimizer_states) runs one AdamW.step() to create the optimizer state,
which compiles the Triton kernel while the CUDA context is still pristine; the Trainer's DataLoader
workers are forked after that, and a forked child of a process that has loaded a Triton module into its
CUDA context segfaults.  Every other Triton kernel in this tree is first launched from inside the
training loop (after the fork) and never hits it.  Fix: arm the patch on the first
DeepSpeedZeroOptimizer.step (the wrapper unhooks itself), so it is applied after the fork and before
anything is timed.  That pre-fork step leaves the master weights untouched (its gradient is zero), so
the numerics are unaffected.  check --quick PASSES.
—Round 25 — fused AdamW moment updates (`LLAVA_DS_ADAM`, extended)
The profile after R24 showed the Adam's three moment passes as the top remaining item:
_foreach_lerp_ 10.5 ms + _foreach_mul_ 7.5 ms + _foreach_addcmul_ 10.7 ms = 28.7 ms/step,
i.e. 9x the partition in bytes where 5x suffices (all three read exp_avg, exp_avg_sq and grad
and write only the two moments).  One Triton kernel does both updates in a single pass.
time: 1154.1 → 1144.6 ms/step, speedup 2.4214.

Numerics: N0 — bitwise.  mul_rn/add_rn/sub_rn pin every rounding to PyTorch's, because
LLVM contracts a*b + c into an FMA and neither lerp nor addcmul fuses (verified: fma_rn
differs in 268865/4.2M values).  Verified on 4.2M random fp32 values and over 20 real AdamW steps —
both moments bitwise identical.  Whole-run loss drift is indistinguishable from run-to-run noise:
identical unpatched runs differ by max 0.0013/mean 0.00057, the Adam-patched runs by
max 0.0020-0.0023/mean 0.00068-0.00074.  check --quick PASSES (/tmp/r31/quick2).
↑ LLaVA