Skip to content

Preserve RNG state across activation-checkpoint recompute when dropout is active - #828

Merged
jason718 merged 1 commit into
allenai:visionfrom
jason718:jasonr/ac-preserve-rng
Aug 14, 2026
Merged

jason718 merged 1 commit into
allenai:visionfrom
jason718:jasonr/ac-preserve-rng

Conversation

@jason718

Copy link
Copy Markdown
Contributor

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:

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.

@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: 09010d84c6

ℹ️ 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".

if isinstance(module, ResidualStream):
if module.p > 0.0 or module.masked_dropout > 0.0:
return True
elif isinstance(module, nn.Dropout) and module.p > 0.0:

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Preserve RNG for attention dropout

When only the attention config has dropout (AttentionConfig.dropout > 0) and residual/plain dropout are zero, this predicate never returns true because attention dropout is stored as AttentionBackend.dropout_p and passed directly to SDPA/flash rather than represented as an nn.Dropout module. In that configuration apply_activation_checkpointing() still wraps blocks with preserve_rng_state=False, so checkpoint recompute redraws attention masks and the gradients differ from the uncheckpointed run—the same class of issue this commit fixes for residual dropout. Please include attention backends with dropout_p > 0 in this check.

Useful? React with 👍 / 👎.

…t is active

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

This was harmless until now — no olmo-core model used dropout, so the flag cost nothing. #825
added Molmo2's `response_residual_dropout=0.1`, which made it live, and the released stage-1
recipe has `activation_checkpointing: true`, so the configuration we are trying to reproduce hit
it on every step.

Measured on 2 nodes of holmes, 150 steps, from-scratch 4B. Disabling activation checkpointing is
supposed to be mathematically neutral, yet it moved the loss:

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

The split is exactly along AC, not microbatch: both AC-off arms land at 2.194/2.195 and both
AC-on arms at 2.487/2.495. A neutral knob moving the loss by 0.3 nats is the signature of
mismatched gradients, not of run-to-run noise (the baseline's own step-to-step oscillation is
+/-0.05).

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

    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 the 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 actually a mask to replay.

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

Verified: 5 new tests pass. Ran `model_test.py` + `train_module/` with and without the change:
9 failed / 60 passed / 5 skipped either way, with an empty set difference in both directions, so
the pre-existing MoE tensor-parallel failures are untouched. isort/black/ruff clean.
@jason718
jason718 merged commit 4c8f133 into allenai:vision Aug 14, 2026
1 check passed
@jason718
jason718 deleted the jasonr/ac-preserve-rng branch August 14, 2026 16:01

@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: 535a8402c2

ℹ️ 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".

Comment on lines +852 to +856
if isinstance(module, ResidualStream):
if module.p > 0.0 or module.masked_dropout > 0.0:
return True
elif isinstance(module, nn.Dropout) and module.p > 0.0:
return True

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Preserve RNG for MoE router jitter

When a MoE router has jitter_eps enabled and activation checkpointing uses selected_ops (or wraps the router through selected_modules), the checkpointed region calls MoERouter.jitter(), which samples with torch.rand_like, but this predicate still returns false unless unrelated dropout is also configured. The recomputation can therefore route tokens using fresh noise and produce gradients for a different expert assignment; include active router jitter—or, more generally, all stochastic checkpointed modules—in the RNG-preservation decision.

Useful? React with 👍 / 👎.

jason718 added a commit that referenced this pull request Sep 26, 2026
Second merge of main into this sync branch, taking main from 0589a03 to
718d08f.

Conflicts:
- nn/attention/__init__.py: take main's removal of FusedAttention (#873).
  Vision's only changes to it were NotImplementedError guards for
  or_mask/and_mask/position_ids; FusedAttentionV2 subclasses Attention and
  already threads position_ids. Keep vision's Dict import.
- nn/transformer/model.py: activation checkpointing preserves RNG state when
  dropout is active (vision, #828) or EMO routing needs segment IDs (main,
  #872), which also resolves main's "preserve RNG state if dropout is active"
  TODO.
jason718 added a commit that referenced this pull request Nov 10, 2026
…1.py (#913)

## Summary

PR 4 of 7 for moving the Molmo2 stage-1 reproduction from the long-lived
`vision` branch onto `main`. #910 (model), #911 (train module) and #912
(data core) are merged; this PR adds the **stage-1 recipe** that makes
them runnable end to end: the datasets, the mixtures, and
`Molmo2-Stage1.py`.

About 6.7k source lines and 4.8k test lines. It also restores one fix
needed for the recipe to train correctly: activation-checkpoint RNG
replay (see "Why the RNG fix is here"). Almost all of it is new files;
the only existing files touched are listed under "Read closely" below.

## Review map

Reading every file closely is not necessary. Here is where attention
pays off.

### Read closely (about 1.9k lines)
| File | Lines | What to check |
|---|---|---|
| `scripts/train/Molmo2-Stage1.py` | 1537 | The recipe itself: the `v1`
/ `v2` / `v3` mixture rates, step counts, optimizer groups and learning
rates, the `--init_from` paths, and the launch settings. This is where a
wrong constant changes the training run silently. |
| `train/callbacks/unsharded_export.py` | 128 | Writes
`model.safetensors` and a config copy into each permanent checkpoint
from a background op on rank 0; skips ephemeral checkpoints. Moved here
from #911 because the stage-1 script is its only user. |
| `distributed/checkpoint/__init__.py` | +30 |
`load_unsharded_model_state()`: the only change to a shared distributed
module. Additive. |
| `nn/transformer/model.py` (+`ac_rng_test.py`) | +24 / -4 | Activation
checkpointing now preserves the RNG state when dropout is active
(`masked_dropout`, `ResidualStream` dropout, `nn.Dropout`), so the
recomputed forward replays the original dropout masks. Required by this
recipe; see below. |
| `data/multimodal/__init__.py`, `sequence_builder.py` | +92 / +4 |
Exports, and a type annotation on `build_branched_sequence` that already
accepted multi-turn branches. No behaviour change. |

### Skim for the shared pattern (about 4.9k lines of dataset code)
These are adapters. Each one defines a config dataclass and a map-style
dataset, formats its rows into the stage-1 prompt family, builds the
sequence with the #912 builders, and truncates with `truncate_example`.
Seven of them (`academic_dataset`, `gui_syn`, `ocr_caption_tars`,
`olmocr`, `pixmo_points_v2`, `synthetic_ocr`, `text_rich_caption`) use
the `EpochSeededExamples` mixin from #912 for epoch-aware sampling; the
others do not sample per epoch. If one is right, the rest are
variations.

| Group | Files |
|---|---|
| Pointing and counting | `pixmo_points.py` (433), `pixmo_points_v2.py`
(579), `gui_syn.py` (243), `detect_counting_question.py` (82) |
| OCR | `olmocr.py` (328), `ocr_caption_tars.py` (366),
`synthetic_ocr.py` (384), `text_rich_caption.py` (200),
`mixtures/ocr.py` (245) |
| Academic QA | `academic/registry.py` (611), `academic_dataset.py`
(179), `academic/formatters.py` (102), `mixtures/stage1_academic.py`
(149) |
| Other sources | `pixmo_clocks.py` (145), `pixmo_cap_qa.py` (104),
`pixmo_ama.py` (96), `tulu.py` (173), `finevision.py` (249),
`mmfinereason.py` (218) |

### Tests (about 4.8k lines)
They mirror the modules above (one test file per dataset group), plus
`molmo2_training_logits_parity_test.py` (GPU, needs the HF checkpoint)
and the callback and distributed-checkpoint tests. A test that needs
Weka data skips when the data is absent.

### Invariants the design relies on (worth a spot check)
These are stated in the script's docstring and should hold across every
file:
- Every default source is a **train split only**; the training set of a
benchmark the stage-2 checkpoints are evaluated on is never a stage-1
source.
- OCR and academic sources use a **style tag as the whole user turn**,
with no question text.
- Data lives on Weka, so datasets read paths from `paths.py` (#912) and
nothing here needs S3 or GCS secrets.
- Mixture rates per recipe are as in the script's docstring: `v1`
caption 0.6 / pointing and counting 0.3 / text 0.1; `v2` caption 0.5 /
pointing 0.25 / OCR 0.25; `v3` caption 0.33 / pointing 0.16 / OCR 0.34 /
academic 0.14 / clocks 0.03.

## Series

| # | PR | Status |
|---|---|---|
| 1/7 | #910 Model: HF Molmo2 loader, flex attention, split-vocab
embedding | merged |
| 2/7 | #911 Train module, `PerGroupScheduler`, weighted CE | merged |
| 3/7 | #912 Data core | merged |
| 4/7 | #913 Stage-1 recipe **(this PR)** | review |
| 5/7 | #934 Data infrastructure, stage-2 recipe, Qwen3-0.6B / 1.7B
sizes | draft, stacked on this PR |
| 6/7 | #936 OLMo 3.5 alignment training: OLMoDDP hooks and train
module, optimizer, callbacks, alignment pipeline | draft |
| 7/7 | #937 In-repo evaluation suites and remaining tools | draft |
| 8 | #938 Stable mixed mid-training (from #916) | draft |
| 9 | #939 Still-changing mixed mid-training (from #916) | draft |

PRs 5 to 7 bring the rest of `vision` onto `main`, so that `main` can do
everything `vision` can. Separate: activation-checkpoint RNG replay for
`ResidualStream.masked_dropout` is already in this PR; #906 (open) will
need a rebase on it.

## Why this is a separate PR

- It is the bulk of the series, but the review is mostly
pattern-checking, and it is the only part that depends on external data
locations and recipe choices.
- It can be iterated (new datasets, recipe tweaks) without touching any
core API from #910 to #912.
- It is what makes stage 1 runnable, so it is where the end-to-end
evidence belongs.

## Does this change anything on `main` / the text side?

No intended text-side change. The shared files it touches are the
additive checkpoint helper, the callbacks `__init__` export, a type
annotation, and the activation-checkpointing change in
`nn/transformer/model.py`. That last one changes behaviour only for
models that use dropout together with activation checkpointing (their
recompute now replays the dropout masks, which it previously did not);
with `dropout=0`, the default, text models are unaffected. For the
series as a whole, text-side outputs (weights, logits, loss and
gradients) were compared bit for bit against `main` on CPU and match,
and the existing test suites show no regressions. Text GPU and
distributed paths (FSDP2, TP, CP) cannot run on the CPU box I used, so
CI's GPU jobs are the check there.

## Why the RNG fix is here

Stage 1 trains with full activation checkpointing and 10% response-token
residual dropout. Without replaying the RNG, the recompute draws
different dropout masks than the original forward, so gradients are
taken against a different sample than the loss. This was held out of
#910 because #906 (open) rewrites the same lines; the end-to-end parity
run below showed it cannot be left out of the recipe: without it the run
trains much worse than `vision` (final loss 1.83 vs 1.19). The change
here is `vision`'s own fix (#828) unchanged, with its test. #906 fixes
the general case differently and will need a rebase on top of this.

## Not included (stays on `vision`)

Stage 2 (`Molmo2-Stage2.py`, `image_only_v9`, multi-image datasets,
`compare_sft_example.py`), the stage-1 data infrastructure upgrades, and
the OLMo 3.5 alignment work; see the plan above.

## Testing

**CPU:** `src/test/data`, the callback and distributed-checkpoint tests:
462 passed, 0 failed (before the last test-only fix below). ruff, black,
isort and `mypy src/` (the CI config) are clean. `Molmo2-Stage1.py
dry_run` resolves for the default, `--recipe=v2` and `--recipe=v3` (32k
and 50k steps). One test (`test_st_qa_train_validation_split`) read a
Weka path with no skip, which failed on the CI runner; it now skips when
the data is absent.

**GPU smoke (Beaker, 8x GPU, FSDP2):** an earlier 30-step run of the
stack: CE loss 3.23 → 2.57, checkpoint and unsharded export written.

**End-to-end parity on Beaker** (`ai2/molmofication`, Holmes, allocated,
`--recipe=v3`, 1 node x 8 GPUs, 2000 steps, same seed and arguments; W&B
disabled because `BeakerCallback.pre_train` calls `wandb.Run.get_url()`,
which the image's `wandb` lacks, existing code unrelated to this
series). V is the control: `vision` at the commit this series was cut
from.

| Run | Code | Result |
|---|---|---|
| [V](https://beaker.org/ex/01M5N24PSKG4EYXQNXQ7KK45XC) | `vision` @
`f639a28` (control) | CE 3.16 -> 1.20 |
| [P](https://beaker.org/ex/01M5N222MQ1JSY1TBDWY3YZBEY) | this PR
**without** the RNG fix | trains worse than V, gap grows: +0.05 (steps
1-50), +0.41 (201-500), +0.60 (1501-2000); final-100-step CE 1.83 vs
1.20 |
| [P2](https://beaker.org/ex/01M5NWNH21XHNA9WFKPJRARQHS) | this PR
**with** the RNG fix | tracks V |

Windowed mean CE, with the fix (P2) against the control (V):

| steps | P2 | V | P2 - V |
|---|---|---|---|
| 1-50 | 2.619 | 2.619 | +0.000 |
| 51-200 | 2.114 | 2.096 | +0.018 |
| 201-500 | 1.638 | 1.640 | -0.002 |
| 501-1000 | 1.326 | 1.315 | +0.011 |
| 1001-1500 | 1.248 | 1.238 | +0.011 |
| 1501-2000 | 1.199 | 1.201 | -0.002 |

Last 100 steps: P2 1.192, V 1.197. The offset has no trend (-0.002 per
1000 steps; without the fix, +0.195 per 1000 steps). Two identical-code
runs (P and R1) differ by about 0.015 per logged point, so window means
agree within about that. Per-point differences between P2 and V are
larger (stdev 0.057) because the data draws differ on purpose: the
review fixes made PixMo-Cap sampling epoch-aware.

Caveats: one run per arm. The gradient norm is spiky; P2 had two
transient spikes (step 300: 30, step 455: 37.6) that V did not, with
normal loss at those steps and clipping at 1.0 (the unfixed run spiked
as high as 165). I cannot tell noise from a small residual difference
from single runs.

**Checkpoint and resume:** run
[R1](https://beaker.org/ex/01M5N222PV51TWTJ7YR9KXWWNP) (1000 steps)
wrote a checkpoint;
[R2](https://beaker.org/ex/01M5NS0S9NSNFQGJBQVDGF2ENE) resumed it from
step 1000 to 2000 (first logged step 1005). Over steps 1001-2000 its
loss differs from the uninterrupted run P by +0.003 on average (stdev
0.013), inside the same-code noise. The unsharded `model.safetensors`
export was written. This pair ran on the code before the RNG fix; resume
does not depend on it, but I have not rerun it on the final code.

**Second parity check: Qwen3-0.6B on 2 nodes (16 GPUs), against a
finished `vision` run.** This covers paths the 4B runs above did not:
`response_logits_only=true`, no activation checkpointing, and 16-GPU
FSDP. Reference: `molmo2-stage1-0p6b-v3-50k-20261023` (`vision` HEAD),
whose per-step training loss is readable from its W&B files. Test:
[`mm-e2e-0p6b-main-2k`](https://beaker.org/ex/01M5QC1TVNGX0R8CXF8VZ725C5),
this branch plus `vision`'s #933 (the 0.6B size) cherry-picked, with the
reference's launch arguments, image and environment, stopped at step
2000 by `hard_stop` while keeping its 50k-step LR schedule. Windowed
mean CE:

| steps | run | reference | diff |
|---|---|---|---|
| 1-50 | 4.580 | 4.595 | -0.015 |
| 51-200 | 2.722 | 2.729 | -0.007 |
| 201-500 | 2.383 | 2.380 | +0.002 |
| 501-1000 | 1.738 | 1.737 | +0.002 |
| 1001-2000 | 1.519 | 1.520 | -0.002 |

Last 100 steps: 1.443 vs 1.458; trend of the difference -0.006 per 1000
steps; loss finite throughout. Per-point differences between the two
runs have stdev 0.093, which matches what two independent runs of the
same curve should give (the reference's own per-step noise is about
0.064, so about 0.09 for a difference). Caveat: the reference ran
`vision` HEAD, which includes data-code changes made after this series'
cut point (#902, #903, #918), so this is a sanity check of overall
health, not an apples-to-apples control; the rigorous rerun comes once
those changes land on `main`.

**Offline check, no GPU:** one training step of a tiny multimodal model
on `vision`@cut and on this branch (dropout off) produces bit-identical
loss, gradients and updated weights, so the model and train-module path
is unchanged apart from the RNG fix.

**GPU logit parity vs HF Molmo2 (4B and 8B pass; O-7B skipped):** see
#910.

**Not covered:** long-horizon loss parity against the released
Molmo2-4B-Pretrain recipe (these are 2000-step checks); GPU text-side
paths beyond CI; a resume rerun on the final code.
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