Skip to content

Mixed midtraining: faster vision encoder and connector - #924

Merged
jason718 merged 3 commits into
jasonr/olmo35-mixed-midtrainingfrom
rustins/vit-speed
Oct 18, 2026
Merged

jason718 merged 3 commits into
jasonr/olmo35-mixed-midtrainingfrom
rustins/vit-speed

Conversation

@RustinS

@RustinS RustinS commented Oct 16, 2026 •

Copy link
Copy Markdown

Into #916's branch, after #923 (1a2064c): three commits, reviewable separately. The encoder and
connector changes are always on and add no options.

Summary

  1. Crop balancing rejects vision dropout, from the Codex review of Mixed midtraining: opt-in crop balancing for the vision encoder #923: a crop encoded on
    another rank would draw that rank's dropout randomness, so balance_vit_crops now requires zero
    vision attention and residual dropout, as trim_microbatch_image_padding does.
  2. Vision encoder
    • ViTAttention projects q, k and v in one matmul over the concatenated wq, wk and wv
      weights (the parameters stay separate, so checkpoints are unchanged) and hands them to the
      attention as strided views, without the head-transposed copies. This applies to
      self-attention without grouped KV heads; anything else takes the existing path.
    • On SM100 GPUs that self-attention tries cuDNN's attention first
      (vision_scaled_dot_product_attention(..., cudnn_first_on_sm100=True)). Every other caller,
      and every other GPU, keeps flash and memory-efficient attention.
    • The blocks' LayerNorms run olmo_core.kernels.layer_norm: Triton forward and backward kernels
      that are never specialized on the row count, with float32 statistics and a deterministic
      weight and bias reduction. CPU inputs, rows wider than 8,192 and environments without Triton
      fall back to F.layer_norm. The modules are still nn.LayerNorms with the same state dict.
    • VIT_CROP_MICROBATCH defaults to 0: one encoder forward per micro-batch instead of 16-crop
      chunks.
  3. Connector
    • With compact images and host-side indices (the trainer's case), MultimodalLM.encode_images
      pools only the valid pooled rows, indexing the encoder's features of all the batch's crops
      directly instead of first placing them in the padded per-example layout. A batch without
      image rows pools one fully padded row, so the connector stays in every step.
    • The connector gathers its pooled patches with one index_select (backward: one index_add_)
      instead of advanced indexing, and computes the attention over each group's few patches as
      elementwise float32 ops (no grouped KV heads; otherwise the existing SDPA path).

Why

With crops balanced (#923) and batches built outside the trainer process (#925), the trainable vision encoder was the largest part of a 90/10 step, and three things made it
slow on B300s:

  • 16-crop chunks: about 19 encoder calls per micro-batch, 7.9K kernels forward and 34K
    backward; the GPU sat idle about 38% of the encoder's time waiting on kernel launches.
  • Head dimension 72: PyTorch's flash attention is slow there on SM100, 31% of the encoder's
    time. cuDNN does the same work in 37% of the time. FA4 cannot run head dimension 72, and padding
    the heads to 96 or 128 is slower than cuDNN.
  • Copies and LayerNorm: head-transpose copies were 14% of the encoder's time, and PyTorch's
    LayerNorm reduces the weight and bias gradients far below memory bandwidth at 180K rows.
    torch.compile fixes that only for static shapes, and the crop count changes every micro-batch.

On a text sequence the connector pooled about 40K padding rows (compact images keep each packed
sequence's pooled rows padded to the batch's longest), and the gather's backward sorted every
padded slot onto the first patch: about 470 ms per micro-batch, which every other rank waited for.

Results

Encoder alone, one B300, 240 crops with activation checkpointing:

ms per micro-batch
Before 1,147
After 650

LayerNorm at 179K x 1152 bf16, forward / backward:

us
PyTorch 448 / 3,034
torch.compile, dynamic shapes 830 / 1,523
flash-attn's Triton layer_norm_fn 341 / 1,124
olmo_core.kernels.layer_norm 207 / 698

In training, 90/10 split (--recipe.visual_data=stage1_v3 --recipe.text_loss_share=0.9, the
21,000-step schedule of the v3 90/10 run), crops balanced, batches built in a child process, 8 B300s,
same batches; seconds per step from CUDA events:

8 GPUs Encoder forward + backward Connector Rest of the step
Before 49.9 10.1 34.9
After 21.5 0.7 36.0

End to end, 16 GPUs

90/10 split on 2 nodes, same batches as the 2-node runs of #923; medians over steps 11-200, or
11-100 for the branches as committed:

16 GPUs s/step vs text-only
Text-only merged MT+LC 15.0 1.0x
90/10 on #916 75.1 5.0x
+ #923, crops balanced 62.3 4.2x
+ #925 and this PR, prototype (200 steps) 31.4 2.1x
+ #925 and this PR, as committed (100 steps) 31.2 2.1x

Mean CE by window:

Steps #916 + #923 + both PRs, as committed + both PRs, prototype
1-10 1.6697 1.6697 1.6696 1.6697
11-50 1.5880 1.5880 1.5876 1.5878
51-100 1.5019 1.5018 1.5016 1.5017
101-150 1.4693 1.4693 1.4692
151-200 1.4571 1.4571 1.4571

Numerics, against a float32 reference of the original path: encoder output error 7.50e-3 for both
the original and the new bf16 path, median gradient error 8.93e-3 and 8.88e-3; connector 5.9e-3
and 5.7e-3. A 100-step A/B on 8 GPUs, same batches: CE differs from the original by 0.00032 on
average (largest 0.0013), while two runs of the new code differ by 0.00027 (largest 0.0012).

Behavior changes to note:

  • vision_sdpa_backends excluded cuDNN for vision ("cuDNN math pitfalls"). This turns it on only
    for the ViT's unmasked self-attention on SM100, where it was measured as accurate as flash.
  • Without chunks, recomputation under activation checkpointing holds one block's activations for
    all of a micro-batch's crops: about 10 GB more peak memory at 400 crops. VIT_CROP_MICROBATCH
    still sets a chunk size.
  • The connector output RMS diagnostic now covers the valid rows only; it used to average in the
    padding rows' outputs.

Tests

  • kernels/layer_norm_test.py: forward and all three gradients against float32 PyTorch for
    float32 and bf16, 1 to 4,099 rows, widths 72 and 1,152; strided inputs; the CPU fallback.
  • image_vit_test.py: the fused self-attention matches separate projections and plain softmax
    attention, outputs and gradients (CPU); on GPU, at SigLIP's sizes, it is as close to float32 as
    the unfused path; the block norms keep nn.LayerNorm's type and state dict.
  • connector_test.py: the few-key attention matches SDPA, with and without masks and with fully
    masked groups; the connector matches the advanced-indexing and SDPA formulation, outputs and
    gradients, with partly padded groups and padded rows.
  • multimodal_test.py: the connector receives only the valid rows (one padded row for a text-only
    batch); _compact_pooled_rows offsets; the existing compact-versus-padded tests, bitwise on CPU.
  • All of src/test/nn/vision/ passes, including the CLIP, SigLIP, SigLIP2 and Molmo2 parity tests
    against Hugging Face. test_document_mode_isolates_packed_examples_through_kda fails the same way
    on [Do not merge yet] Mixed midtraining on OLMo 3.5: the OLMo-core side of scaling-ladders#83 #916's head, 1a2064c (its tolerance is the size of the tiny model's logits), and so does
    test_native_checkpoint_loads_into_multimodal_and_roundtrips (as noted in Mixed midtraining: opt-in crop balancing for the vision encoder #923).
  • multimodal_ddp_train_module_test.py: balance_vit_crops with vision attention or residual
    dropout fails at construction.

How to test

pytest src/test/kernels/layer_norm_test.py src/test/nn/vision/image_vit_test.py \
  src/test/nn/vision/connector_test.py src/test/nn/vision/multimodal_test.py
pytest src/test/train/train_module/transformer/multimodal_ddp_train_module_test.py -k dropout

The GPU tests need one GPU.

🤖 Generated with Claude Code

https://claude.ai/code/session_0159PTUsp2w3YTANVDZ4BUss

RustinS and others added 3 commits October 16, 2026 09:47
A crop the exchange sends to another rank is encoded there and draws that
rank's dropout randomness, and the changed per-rank batch shapes advance
every rank's random stream differently, so with vision dropout the
balanced features and gradients would no longer match unbalanced encoding
up to rounding. balance_vit_crops now requires zero vision attention and
residual dropout, as trim_microbatch_image_padding does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_0159PTUsp2w3YTANVDZ4BUss
…LayerNorm

The trainable vision encoder was the largest part of a mixed mid-training
step on B300s.

- ViTAttention projects q, k and v in one matmul (wq, wk and wv stay
  separate parameters, so checkpoints are unchanged) and hands them to the
  attention as strided views, without head-transposed copies.
- On SM100 GPUs that self-attention tries cuDNN's attention first
  (vision_scaled_dot_product_attention's cudnn_first_on_sm100; every other
  caller keeps flash and memory-efficient attention). PyTorch's flash
  attention is slow there for head dimension 72; cuDNN does the same work
  in about a third of the time, as accurate against a float32 reference.
- The blocks' LayerNorms run olmo_core.kernels.layer_norm: Triton kernels
  not specialized on the row count, so the crop count changing every
  micro-batch costs no recompiles. PyTorch's weight and bias gradient
  reduction ran far below memory bandwidth: at 180K rows of 1152, its
  backward takes 3.0 ms and these kernels' 0.7 ms (forward 0.45 and
  0.21 ms).
- VIT_CROP_MICROBATCH defaults to 0, one encoder forward per micro-batch:
  with 16-crop chunks the GPU sat idle about 38% of the encoder's time on
  kernel launches. Without chunks, recomputation under activation
  checkpointing holds one block's activations for all crops (about 10 GB at
  400 crops).

Encoder on one B300, 240 crops with activation checkpointing: 650 ms
instead of 1,147 ms per micro-batch.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_0159PTUsp2w3YTANVDZ4BUss
Compact images keep each packed sequence's pooled rows padded to the
batch's longest, so on a text sequence the connector pooled about 40K
padding rows, and its gather's backward sorted every padded slot onto the
first patch: about 470 ms per micro-batch, which every other rank waited
for.

- With compact images and host-side indices (the trainer's case),
  MultimodalLM.encode_images pools only the valid rows, indexing the
  encoder's features of all the batch's crops directly instead of placing
  them in the padded per-example layout first. A batch without image rows
  pools one padded row, which keeps the connector in the step.
- The connector gathers with one index_select (backward: one index_add_)
  and computes the attention over each group's few patches as elementwise
  float32 ops instead of generic attention kernels.

Outputs and gradients are unchanged up to rounding. The connector output
RMS diagnostic now covers the valid rows only (it averaged in the padding).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_0159PTUsp2w3YTANVDZ4BUss
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 16, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-16T09:54:16.691278Z 1bb0e8a PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@jason718
jason718 merged commit f37f5d1 into jasonr/olmo35-mixed-midtraining Oct 18, 2026
1 check passed
@jason718
jason718 deleted the rustins/vit-speed branch October 18, 2026 02:31
jason718 pushed a commit that referenced this pull request Oct 18, 2026
Batch building in a forked child process (batch_prefetch_process) and example loading in forked worker processes (prefetch_processes), both off by default, with identical batches, order and resume state; fewer large fresh allocations while packing and collating (reused knapsack table, defer_packed_image_copy, shared-memory compact images in the child); the recipe builds 8 batches ahead. With #924 on the 90/10 stage at 64 GPUs: 8.42 s/step median vs 20.92 on #916, CE equal to 4 decimals over 300 steps.
jason718 added a commit that referenced this pull request Oct 18, 2026
cuDNN 9.10.2 (olmo-eval's torch 2.10 / cu128 image) builds no execution plan on B300 for the
ViT's attention, with or without gradients, and PyTorch does not fall back, so every stage-1
eval of a checkpoint on #924's code failed. cuDNN 9.20.0 (the training image) runs all of it.
Older cuDNNs now take the flash / efficient backends as before #924.
RustinS added a commit that referenced this pull request Oct 19, 2026
…lity check

torch.backends.cudnn.version() raises when the loaded cuDNN is older than the
one PyTorch was built against. The training image is built against 9.20 and
loads 9.13, so cudnn_first_supported crashed every training job at the first
vision forward. Read the loaded library's version directly instead, and lower
the cuDNN-first threshold to 9.13: 9.10.2 builds no execution plan for the
ViT's attention on SM100, while 9.13 ran all of it in the #924 training runs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_0159PTUsp2w3YTANVDZ4BUss
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants