Skip to content

Molmo2: compile the vision tower and connector, and add response residual dropout - #825

Merged
jason718 merged 2 commits into
allenai:visionfrom
jason718:jasonr/stage1-compile-and-response-dropout
Aug 14, 2026
Merged

jason718 merged 2 commits into
allenai:visionfrom
jason718:jasonr/stage1-compile-and-response-dropout

Conversation

@jason718

Copy link
Copy Markdown
Contributor

Stacked on #824 (AC + knapsack packer). Review that one first; this branch contains its commit.

Closes the last two released-config settings that needed real code. Auditing the remaining
list first showed three of the five were not gaps at all:

Item Finding
multi_component_grad_norm: true Dead field in mm_olmo — declared at trainer_config.py:720, never read anywhere in the repo.
float32_attention: true No-op on the path the released config uses. With attention_type: sdpa it casts only q,k to fp32; under amp_bf16 autocast SDPA casts them back (output is bf16). Running the same code outside autocast raises Expected query, key, and value to have the same dtype — it only works because autocast nullifies it. It would matter on the direct path, which the released config doesn't use.
enable_variable_sized_token_pooling: true Collator memory optimization over mm_olmo's own TOKEN_POOLING_KEYS buffers, which our pipeline doesn't use. No modelling effect.

That left compile scope (throughput) and response dropout (modelling).

Compile: compile_vit: blocks, compile_connector: dynamic

VisionTransformer.apply_compile compiles each ViT block, mirroring the per-block strategy
Transformer.apply_compile already uses. VisionConnector.apply_compile compiles pooling and
projector with dynamic=True — the pooled-group count follows the per-batch crop count, so a
static compile would recompile on every new shape.

Both sit behind new compile_vision / compile_connector flags on the train module (default
True) and only fire when compile_model is set, so this is inert unless compilation is
already on.

Response residual dropout

mm_olmo's Dropout(mask_p=...) gives response tokens a different keep probability from
everything else, applied at both residual adds:

keep_prob = drop_mask * (1 - mask_p) + (1 - drop_mask) * (1 - p)

Our ResidualStream had a single uniform nn.Dropout, which is why this has been carried as
a KNOWN DELTA comment in the stage-1 script since the beginning.

ResidualStream gains masked_dropout implementing exactly that formula, plus an optional
drop_mask threaded Transformer.forward → TransformerBlock → both residual streams.
MultimodalLM.forward derives the mask from loss_masks (loss_masks > 0 is "is a response
token") and only builds it while training and when a block will consume it. drop_mask is an
explicit block kwarg rather than riding **kwargs, so it isn't forwarded into the sequence
mixer.

Blast radius is contained: masked_dropout defaults to 0 everywhere and is validated to
require the default block type (what Molmo2 uses). At 0 the path is byte-identical to before,
so every other model in the repo is untouched. The stage-1 script sets 0.1.

It is deliberately not defaulted on the molmo2_4B/molmo2_8B factories: those describe
the released weights for inference and must keep matching the HF-derived config, so the
training regularizer lives with the other training settings.

Verification

Masked-dropout semantics, measured over 4000 tokens:

unmasked (prompt/image) tokens zeroed : 0.0000   <- never dropped
masked (response) tokens zeroed       : 0.0910   <- rate 0.1
surviving value                       : 1.1111   = 1/0.9, inverted dropout
E[response]                           : 1.0100   <- unbiased
eval mode                             : no dropout
masked_dropout=0                      : byte-identical to the plain path
  • End to end through MultimodalLM: train-mode forward is stochastic with the rate set and
    deterministic without it; eval is deterministic either way.
  • 6 new tests in src/test/nn/residual_stream_test.py.
  • 510 passed / 1195 skipped across src/test/nn and src/test/data/multimodal. The one
    failure, convert_test.py::test_logprobs_match_after_roundtrip[gemma3], is a gated-HF-repo
    auth error that fails identically on vision.
  • Real-weight Molmo2-4B parity: 5 passed on GPU (logits, LM forward, embedding, training
    logits).
  • isort/black/ruff clean on changed files; mypy at the 21-error vision baseline. (The
    two isort errors reported for connector.py and multimodal_train_module.py are
    pre-existing — same count on the baseline.)

Not measured

The throughput gain from compiling the ViT and connector. That needs a GPU run, best done
together with the activation-checkpointing change in #824.

Jason Ren added 2 commits August 14, 2026 00:33
…the 2D-knapsack packer

The two remaining released-config settings that were reachable without new code.
Both are already-implemented capabilities this script simply never turned on.

Activation checkpointing + microbatch 4

The released config has `activation_checkpointing: true` with
`llm.activation_checkpoint: whole_layer` and `device_train_microbatch_size: 4`.
`ac_config` already exists on MultimodalTransformerTrainModuleConfig and wires to
`Transformer.apply_activation_checkpointing`; it was just left None, which is why
microbatch >1 OOM'd previously. Setting mode=full (checkpoint every block, i.e.
mm_olmo's whole_layer) and microbatch 4 together. Vision and connector AC were
already on by default, matching the released config's vit
`activation_checkpointing: true` and `connector_activation_checkpointing: true`.

Divisibility note: 128 % (4 x dp_world_size) must be 0, so microbatch 4 supports
world sizes up to 32 — the released 4B ran 16 GPUs and the 8B ran 32. At 64 GPUs
use microbatch 2.

2D-knapsack packing

The released config has `packing: {mode: dynamic_solver, buffer_size: 48,
text_weight: 1.0, image_weight: 1.0}`. `iter_dynamic_packs` (a verbatim port) has
been in the repo since #806 but stage 1 never passed `pack_max_crops`, so it fell
through to token-only next-fit. Now wired, with image_weight 1.0 — note the
MixtureDataLoader default is 30.0, so wiring it up without overriding that would
still have diverged.

`PACK_MAX_CROPS = 3 * (1 + 8)`: the crop budget is the knapsack's second dimension.
Measured with build_image_token_ids, an 8-crop example costs at most 9 crops
(1 global + 8 high-res) and ~1348 image tokens, so at seq 2560 the token budget
binds first and the crop cap mainly bounds worst-case ViT/collator memory. Below a
single example's 9 crops it would force that example into its own mostly-padding
pack.

Measured effect, and where it comes from

On a synthetic stream shaped like the real mixture (image examples ~1400 tok /
9 crops, text-only ~600 tok), 81 packs each:

  image-only stream : knapsack 1.00 ex/pack 54.7% fill | next-fit identical
  with text-only    : knapsack 1.70 ex/pack 69.3% fill | next-fit 1.00, 44.3%

So the gain is almost entirely cross-modal packing. `iter_packs` deliberately
refuses to mix text-only and image-bearing examples in one pack ("head-truncating a
cross-modal pack can orphan <im_patch> tokens from their pooled rows"); the
knapsack has no such guard, and mm_olmo likewise packs across modalities whenever
nlp > 0 (`shortcut_max_len_images: args.nlp == 0`).

That guard is worth being explicit about, since this removes it for stage 1. The
invariant it protects — one <im_patch> token per pooled row — held in 0/81 packs
for both packers on both streams, because the knapsack respects the token budget by
construction so nothing gets truncated. The equal-length synthetic also understates
the knapsack on image-only data; real caption lengths vary, which it can exploit
and sequential next-fit cannot.

Verified: 249 passed / 17 skipped across src/test/nn/vision,
src/test/data/multimodal and embedding_test; isort/black/ruff/mypy clean.

NOT yet validated on GPU: whether microbatch 4 with AC actually fits at seq 2560.
That is the point of the change and it matches what mm_olmo ran on comparable
hardware, but it should get a short GPU run before a full launch.
…dual dropout

Closes the last two released-config settings that needed real code. Auditing the
remaining list first showed three of the five were not gaps at all:

* `multi_component_grad_norm: true` is a dead field in mm_olmo — declared at
  trainer_config.py:720 and never read anywhere in the repo.
* `float32_attention: true` is a no-op on the path the released config uses. With
  `attention_type: sdpa` it casts only q and k to fp32; under `amp_bf16` autocast
  SDPA casts them straight back (verified: the output is bf16, and running the same
  code outside autocast raises "Expected query, key, and value to have the same
  dtype", which is why it only works at all). It would matter on the `direct`
  attention path, which the released config does not use.
* `enable_variable_sized_token_pooling: true` is a collator memory optimization over
  mm_olmo's own `TOKEN_POOLING_KEYS` buffers, which our pipeline does not use. No
  modelling effect.

That left compile scope (throughput) and response dropout (modelling).

Compile: `compile_vit: blocks`, `compile_connector: dynamic`

`VisionTransformer.apply_compile` compiles each ViT block, mirroring the per-block
strategy `Transformer.apply_compile` already uses. `VisionConnector.apply_compile`
compiles pooling and projector with `dynamic=True`, because the pooled-group count
follows the per-batch crop count and a static compile would recompile on every new
shape. Both are gated behind new `compile_vision` / `compile_connector` flags on the
train module (default True) and only fire when `compile_model` is set, so this is
inert unless compilation is already on.

Response residual dropout

mm_olmo's `Dropout(mask_p=...)` gives response tokens a different keep probability
from everything else: `keep = mask*(1-mask_p) + (1-mask)*(1-p)`, applied at both
residual adds. Our `ResidualStream` had a single uniform `nn.Dropout`, which is why
this has been carried as a KNOWN DELTA in the script since the beginning.

`ResidualStream` gains `masked_dropout` implementing exactly that formula, plus an
optional `drop_mask` argument threaded `Transformer.forward` -> `TransformerBlock`
-> both residual streams. `MultimodalLM.forward` derives the mask from `loss_masks`
(`loss_masks > 0` is precisely "is a response token") and only builds it while
training and when a block actually asks for it. `drop_mask` is an explicit block
kwarg rather than riding `**kwargs`, so it is not forwarded into the sequence mixer.

`masked_dropout` defaults to 0 everywhere and is validated to require the `default`
block type (which is what Molmo2 uses); at 0 the code path is byte-identical to
before, so every other model in the repo is untouched. The stage-1 script sets 0.1.
It is deliberately *not* defaulted on the `molmo2_4B`/`molmo2_8B` factories: those
describe the released weights for inference and must keep matching the HF-derived
config, so the training regularizer lives with the other training settings.

Verified:
- masked dropout semantics: unmasked tokens never dropped (0.0000), masked tokens
  dropped at 0.0910 for a rate of 0.1, survivors scaled by 1/0.9 = 1.1111 so the
  expectation stays 1.0, no dropout in eval, and `masked_dropout=0` byte-identical
  to the plain path. 6 new tests in src/test/nn/residual_stream_test.py.
- end to end through MultimodalLM: train-mode forward is stochastic with the rate
  set and deterministic without it; eval is deterministic either way.
- 510 passed / 1195 skipped across src/test/nn and src/test/data/multimodal. The one
  failure, convert_test.py::test_logprobs_match_after_roundtrip[gemma3], is a gated
  HF repo auth error that fails identically on `vision`.
- real-weight Molmo2-4B parity (logits, LM forward, embedding, training logits):
  5 passed on GPU.
- isort/black/ruff clean on the changed files; mypy at the 21-error `vision`
  baseline (the two isort errors reported for connector.py and
  multimodal_train_module.py are pre-existing).

Not measured: the throughput gain from compiling the ViT and connector. It needs a
GPU run alongside the activation-checkpointing change.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 6d78228864

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

return spec.factory(rope_theta=spec.rope_theta(init_from))
return spec.factory(
rope_theta=spec.rope_theta(init_from),
response_residual_dropout=RESPONSE_RESIDUAL_DROPOUT,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Pass loss_masks when enabling response dropout

Passing response_residual_dropout=0.1 here turns on MultimodalLM.forward's training-time requirement for loss_masks, but this Stage 1 config leaves response_logits_only at its default False, so MultimodalTransformerTrainModule.train_batch takes the full-logits branch and calls self.model(input_ids, labels=None, **model_kwargs) without loss_masks. The first training microbatch will raise the new ValueError before any step can run; pass mb_loss_masks through in that branch (or enable the response-logits-only path) before enabling this dropout.

Useful? React with 👍 / 👎.

Comment on lines +408 to +410
ac_config=TransformerActivationCheckpointingConfig(
mode=TransformerActivationCheckpointingMode.full
),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Preserve RNG when checkpointing masked dropout

With this full-LM activation checkpointing enabled together with RESPONSE_RESIDUAL_DROPOUT=0.1, every checkpointed block now contains _masked_dropout, which samples with torch.rand_like; Transformer.apply_activation_checkpointing() currently wraps blocks with preserve_rng_state=False, so backward recomputation samples a different dropout mask from the forward pass. Once the missing loss_masks issue is fixed, Stage 1 will train with gradients from inconsistent activations whenever masked dropout is active; preserve RNG state for this configuration or avoid checkpointing stochastic blocks.

Useful? React with 👍 / 👎.

@jason718
jason718 merged commit 70c867e into allenai:vision Aug 14, 2026
1 check passed
@jason718
jason718 deleted the jasonr/stage1-compile-and-response-dropout branch August 14, 2026 03:04
jason718 added a commit that referenced this pull request Aug 14, 2026
…erge) (#826)

#825 added Molmo2's `response_residual_dropout`. On GPU it turned out to
be broken in two
independent ways, the second of which silently prevented stage 1 from
training at all. Both are
fixed here, each with a regression test that fails on the old code.

## Measured on 2 nodes of holmes (B300), 150 steps, from-scratch 4B

| step | 15 | 45 | 75 | 105 | 150 |
|---|---|---|---|---|---|
| **before** (bug 2) | 3.57 | 3.51 | 3.52 | 8.24 | ~7.7 |
| dropout disabled (control) | 2.71 | 2.33 | 2.27 | 2.14 | **2.10** |
| known-good reference run | 3.26 | 2.32 | 2.11 | 2.03 | **1.96** |

The broken version never descends — CE holds at 3.3-4.1 for 75 steps,
then blows up to ~9 with
grad norms spiking to 537 / 174 / 156 against a clip of 1.0. Disabling
the dropout entirely
recovers the reference curve, which is what localised the bug.

Beaker: baseline `01KZZ9J77QVJ21MGGW2C934K73` (diverged),
unfreeze-embeddings ablation
`01KZZANAVXRDQNC28P7KGNF4B0` (still diverged, ruling out the embedding
hypothesis), no-dropout
control `01KZZANAAV8BC7WM3QDECE2MWM` (healthy).

## Bug 1 — `loss_masks` was not forwarded on the dense-logits path

`train_batch` only passed `loss_masks` to the model on the
`response_logits_only=True` branch. The
released Molmo2 recipe has `response_logits_only: false`, so the dense
branch is the one that runs,
and it died on the first batch:

```
ValueError: loss_masks is required when the LM uses masked_dropout
```

Fixed by passing `loss_masks` on both branches (`MultimodalLM.forward`
pops it and ignores it when
masked dropout is off).

## Bug 2 — dropout sampled per **token** instead of per **element**

mm_olmo (`olmo/nn/llm.py:916-946`) broadcasts the per-token keep
probability to the full input
shape and draws one Bernoulli per element:

```python
dropout_shape = list(input.shape)                  # (B, T, D)
keep_prob = keep_prob.broadcast_to(dropout_shape)
multiplier = input.new_empty(dropout_shape).bernoulli_(keep_prob)
```

#825 called `torch.rand_like(keep_prob)` while `keep_prob` was still
shaped `(B, T, 1)` — one
Bernoulli **per token**, which zeroes a token's entire `d_model`
residual contribution at once.
Across 36 blocks x 2 residual adds that is 72 chances to delete a
response token's contribution
outright: destructive rather than regularising, and a good match for
training that limps and then
diverges.

## Why the existing tests missed it

Every assertion in #825 holds identically under both samplings — \"~9%
of masked *elements* are
zero\", \"survivors are scaled by 1/0.9\", \"the expectation is
preserved\". The element-level
statistics are the same; only the correlation structure differs.

- `test_masked_dropout_samples_per_element_not_per_token` targets that
directly: at rate 0.5 with
D=8, per-element sampling makes all-or-nothing tokens vanishingly rare
(2 * 0.5\*\*8 per token),
  so it asserts almost every masked token is *partially* dropped.
- The new `multimodal_train_module_test.py` exercises `train_batch` —
the real caller — across both
logit paths. Bug 1 was invisible to tests that called
`MultimodalLM.forward` directly with
  `loss_masks` already in hand.

## Verification

13 tests pass across `residual_stream_test.py` and
`train_module/multimodal_train_module_test.py`;
both new tests confirmed to fail on the pre-fix code. `isort` / `black`
/ `ruff` clean; `mypy` at
the pre-existing baseline. A 2-node run with dropout re-enabled on the
fixed code is in flight
(`01KZZHA0HJN9AXFE67Y9JAVT15`) to confirm the curve now tracks the
reference.

---------

Co-authored-by: Jason Ren <[email protected]>
jason718 added a commit that referenced this pull request Aug 14, 2026
…t is active (#828)

Stacked on #826 (its two commits appear here; review the top commit
only).

`TransformerModel.apply_activation_checkpointing` hardcoded
`preserve_rng_state = False`, directly
below a `TODO: only preserve RNG state if dropout is active`.
Checkpointing discards activations
and rebuilds them by re-running the forward during backward; with the
RNG state unpreserved, that
recompute draws **fresh** dropout masks, so the gradients are taken with
respect to a different
sample than the loss was.

Harmless until now — no olmo-core model used dropout, so the flag cost
nothing. #825 added Molmo2's
`response_residual_dropout=0.1`, and the released stage-1 recipe sets
`activation_checkpointing: true`, so the exact configuration we are
reproducing hit this on every
step.

## How it surfaced

Measured on 2 nodes of holmes, 150 steps, from-scratch 4B, while
sweeping throughput settings.
Turning activation checkpointing off is supposed to be mathematically
neutral. It moved the loss:

| arm | AC | microbatch | CE @150 | examples/s/device |
|---|---|---|---|---|
| baseline | on | 4 | 2.495 | 6.077 |
| A2 | **off** | 4 | **2.195** | 6.767 |
| A4c | on | 8 | 2.487 | 7.126 |
| C1 | **off** | 8 | **2.194** | 7.750 |

The split follows AC exactly, not microbatch: both AC-off arms land at
2.194/2.195, both AC-on arms
at 2.487/2.495. A neutral knob shifting the loss 0.3 nats is mismatched
gradients, not noise — the
baseline's own step-to-step oscillation is ±0.05. Beaker:
`01KZZHSVW4EMG4R6MYQ2Y66PC3` (A2),
`01KZZHSX95NCGV94CGSWH4HTF9` (A4c), `01KZZJNCNH2V46X9H0MX94DGQM` (C1).

## The fix

mm_olmo gates the same flag on the same condition in
`llm_activation_checkpoint_function`:

```python
preserve_rng_state = (
    (cfg.attention_dropout != 0.0) or
    (cfg.response_residual_dropout != 0.0) or
    (cfg.residual_dropout != 0.0)
)
```

`_dropout_is_active()` walks submodules for `ResidualStream` (whose
`masked_dropout` carries
`response_residual_dropout`) and plain `nn.Dropout`, so the per-block
save/restore is only paid when
there is a mask worth replaying.

## Tests

`test_checkpointed_grads_match_uncheckpointed_grads_under_dropout`
asserts the property that
actually matters — checkpointing must not change the gradient — and a
parametrized test pins the
flag itself so the cost stays off when dropout is disabled. Both fail on
the pre-fix code.

Ran `model_test.py` + `train_module/` with and without the change: 9
failed / 60 passed / 5 skipped
either way, empty set difference in both directions, so the pre-existing
MoE tensor-parallel
failures are untouched. isort/black/ruff clean.

## Note for the stage-1 recipe

With this fix, AC-on and AC-off are genuinely equivalent, and the new
test enforces it. That makes
`ac_config=null` a free +11.4% throughput win on B300 (62 -> 161 GiB
reserved, against 288 GiB
available) — worth considering separately for the stage-1 script, but
not changed here.

Co-authored-by: Jason Ren <[email protected]>
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.

1 participant