Skip to content

Sync main into vision: #885, #888, #910-#912, #920 - #943

Merged
jason718 merged 9 commits into
visionfrom
jasonr/sync-main-into-vision
Oct 30, 2026
Merged

jason718 merged 9 commits into
visionfrom
jasonr/sync-main-into-vision

Conversation

@jason718

Copy link
Copy Markdown
Contributor

Merges main at ccf4ef4 into vision (6 PRs: #885, #888, #910, #911, #912, #920). Land by fast-forward push, not "Squash and merge": squashing would drop main as a parent and the next sync would re-conflict.

How the conflicts were resolved

#910-#912 put Molmo2 code on main that was cut from vision at f639a28 and then changed in review, while vision kept developing the same files (#889, #902, #903, #918, #933). Merging against the true merge-base reports 39 conflicting files, most of them the same code on both sides. Files that #910-#912 newly added were therefore merged against f639a28, so only real overlaps between review fixes and later vision work conflict; files that existed before were merged against the true merge-base. Every file in which a line from either side did not survive was reviewed by hand.

Kept from vision:

File Why
nn/transformer/model.py the activation-checkpoint RNG fix (_dropout_is_active), held out of main for #906; Molmo2 stage 1 (full AC + response dropout) needs it. Without dropout it is inert.
data/multimodal/pixmo_cap.py, sft_common.py #902's epoch-aware sampling and truncation design, which every vision dataset uses and which supersedes #912's review variant; keeps the PixMo-Cap stream identical to the hero runs. main's remote-image-URL check was ported.
train_module/transformer/multimodal_train_module.py (+ test) #911's review changes are simplifications, behaviour changes (loss divisor, CE metric, DDP-accumulation guard) and a SkipStep feature; none fixes a vision bug, and vision's loss-group code relies on the clamp(min=1) divisor.
data/multimodal/__init__.py, nn/vision/__init__.py main's versions are subsets; a plain merge would drop 33 dataset exports.

Taken from main: the attention files, transformer/config.py, lm_head.py (+ #888 fp32_output), image_vit.py, sdpa.py, molmo2_loader.py, speed_monitor.py (examples/step only for packed multimodal batches), sequence_builder.py, sft_formatter.py (renames and typing only).

Combined: nn/vision/multimodal.py keeps vision's document mode and MultimodalOLMoDDPModel and takes main's backend-based flex detection with its sliding-window and mixed-backend guards (flex stays off in document mode); ddp_train_module.py keeps vision's _optimizer_state_dict_for_load hook ahead of #885's load_pass; collator.py gains main's <im_patch> truncation guard; multimodal_test.py is the union of both sides' tests.

main removed MultimodalLMConfig.output_vocab_size (only ever None on vision) and multimodal_lm_state_dict_to_hf (no callers). What that and #885 left behind on the vision side is fixed:

  • in the merge: a stale output_vocab_size check in MultimodalOLMoDDPModel.forward is removed (it would raise on every forward), and the multimodal_lm_state_dict_to_hf export is dropped.
  • 2f194da: internal/vision_alignment.py imported _normalize_legacy_latent_moe_config, which Fix OLMoDDP Torch 2.13 training and preserve HF inference numerics #885 replaced with nn.transformer.config.normalize_legacy_config_dict (same logic); the OLMo 3.5 alignment recipe failed to import without it.
  • ab38631: a stale output_vocab_size assertion in molmo2_native_config_test.py.

Verification

Check Result
Text side the 11 shared non-multimodal files that differ from main differ by exactly vision's own changes since the merge-base (the reviewed #886 hooks), except transformer/model.py = the AC-RNG fix above
Lint (ruff F-codes) 1 finding, pre-existing on vision (annotation-only F821 in sft_common.py); vision has 2
Imports every olmo_core module imports; same single failure as vision (select_beaker_hosts: google.cloud.compute_v1 not installed)
Test collection 4,778 tests (vision 4,324 + main's new ones), same single collection error as vision and main
CPU tests (nn, data/multimodal, train, internal, distributed/checkpoint, optim) no failure beyond vision's, except olmo3_rope_import_test.py YaRN cases (7), which fail identically on clean main in this environment
Molmo2 Stage-1 / Stage-2 loaders (built as the scripts build them, rank 0, 4 batches) every tensor byte-identical to vision
OLMo 3.5 alignment bridge (internal.vision_alignment, rank 0, 3 batches) every tensor byte-identical; resolved config differs only by new main fields at defaults, each equal to the old behaviour: routed_experts.match_eager_rounding=False, row_specialization=static, routed_experts_router.lb_loss_count_source=executed, lm_head.fp32_output=False, process_group_timeout_seconds=900 (the previous default timeout was also 15 minutes)
Molmo2-0.6B forward + backward on CPU (seeded weights, image + text, response-masked dropout) loss, logits and all 725 parameter gradients bit-identical to vision
GPU tests on H100 (OLMo 3.5 multimodal OLMoDDP model, document mode, multimodal DDP train module, ViT, Molmo2 parity / logits parity / training-logits parity / generation, no-EP block), each tree run twice 56 passed, 1 failed, 10 skipped on both vision and this branch; the failure (test_document_mode_isolates_packed_examples_through_kda) is pre-existing on vision and fixed in #916

Follow-up: #916 is updated on top of this branch (merge, no rebase); Run 5's resolved config and first batches are unchanged there.

🤖 Generated with Claude Code

jason718 and others added 9 commits October 20, 2026 23:45
…ing (#910)

## Summary

PR 1 of 4 for moving the Molmo2 stage-1 reproduction from the long-lived
`vision` branch onto `main` in reviewable pieces (follows `[1/n]` #692).
This one is the **model side only**: no data pipeline, no train module,
no scripts. Everything is opt-in; existing `Transformer` / `OLMo`
configs behave exactly as before.

## What is in this PR, how each piece is used, and why it has to be here

### 1. HF Molmo2 loader (`nn/vision/molmo2_loader.py`)
- **What:** converts a released HuggingFace Molmo2 checkpoint (4B / 8B)
into a `MultimodalLM` state dict (fused QKV and gated-MLP splitting, the
base/extra embedding split, the patch-embedding flatten order), and
derives a `MultimodalLMConfig` from an HF config
(`molmo2_config_from_hf_config`).
- **How it is used:** (a) **correctness oracle**: every parity and
generation test loads the released weights through it and compares
against the HF reference model, which is the only way to *prove* our
architecture is Molmo2 and not merely Molmo2-shaped; (b)
`MultimodalLMConfig.molmo2_4B()/molmo2_8B()`, the factories stage 1
trains from, are asserted equal to the HF-derived config
(`molmo2_native_config_test`), so a launch needs no HF access; (c)
`Molmo2-Stage1.py --init_from=molmo2` (continue from the released
checkpoint) goes through the converter.
- **Why here:** the model is only trustworthy once it matches HF
numerically; landing the model without the thing that verifies it would
leave #911-#913 building on unverified code.

### 2. FlexAttention backend (`nn/attention/backend.py`, plus the dense
`or_mask` / `and_mask` path)
- **What:** an attention backend that expresses Molmo2's mask (causal,
image tokens attending bidirectionally to each other, and isolation
between the branches/examples packed into one sequence) as a fused
kernel built from per-token vectors, instead of materialising a `(B, 1,
S, S)` boolean mask.
- **How it is used:** stage 1 packs several annotations per image into
one sequence, so every training step needs this mask. `Molmo2-Stage1.py`
sets `USE_FLEX_ATTN = True` (about +8% MFU over the dense `torch`
backend, per the script). The dense masks stay as the CPU / inference
path and as the oracle: `flex_backend_test` checks flex against dense
for causal / or / and / both, MHA and GQA, and
`test_packed_examples_are_isolated` checks packed examples don't leak
into each other (dense and flex).
- **Why here:** the mask semantics are part of the model definition (HF
Molmo2 attends bidirectionally over image tokens; getting this wrong
silently changes logits, see the bidirectional-vs-causal parity numbers
below), and `MultimodalLM.forward` is where the mask gets built.

### 3. Split-vocab embedding (`nn/embedding.py`,
`TransformerConfig.n_extra_vocab`)
- **What:** an embedding table split into a base block and a small
"extra" block (Molmo2's 128 image-special tokens) held as two
parameters, with an LM head that spans only the base vocab and can be
tied to the base block.
- **How it is used:** HF Molmo2 stores `wte.embedding` and
`wte.new_embedding` separately, so the loader maps them one-to-one onto
`embeddings.weight` / `embeddings.extra_weight`. Stage 1 sets
`freeze_base_embeddings=True`: it keeps the pretrained vocabulary fixed
while learning the new image tokens. With one fused table that is a
partial-row freeze, which `requires_grad` cannot express; with the split
it is `embeddings.weight.requires_grad_(False)`. It also gives the head
the base width structurally (extra tokens are inputs, never targets),
which replaced an earlier logit-masking mechanism that I deleted as dead
code in this PR.
- **Why here:** it changes the model's parameter layout, and the loader
(above) and every checkpoint conversion depend on that layout, so it
cannot come later without re-doing the loader.

### Smaller opt-in pieces the model needs
`response_logits_only` (compute logits only at response positions, used
by the train module to save memory), `masked_dropout` (Molmo2's
`response_residual_dropout`: 10% residual dropout on response tokens
only), `RoPE position_ids` (packed branches share an overlapping
position range), and ViT / connector activation checkpointing and
compile hooks.

## Why this PR is fundamental

Everything else in the series imports from it, so it must land first:

| PR | What it takes from this one |
|---|---|
| #911 train module | wraps `MultimodalLM`; calls
`response_logits_only`, `masked_dropout`, the flex backend, the ViT /
connector AC and compile hooks |
| #912 data core | special-token ids (`molmo2_tokens`) and the sequence
layout (`position_ids`, sub-segments, image-token spans) that
`MultimodalLM.forward` consumes |
| #913 stage-1 recipe | `MultimodalLMConfig.molmo2_4B/8B`,
`n_extra_vocab` + `freeze_base_embeddings`, the loader for
`--init_from=molmo2` |

It also defines the numerical contract (parity with released Molmo2)
that the later PRs are checked against, and it is the only PR whose
correctness can be validated without data or a trainer. It is safe to
merge first: all defaults are unchanged and text-side behaviour is
bit-identical to `main` (see below).

## Series: all PRs

Linear stack. Each PR is cut fresh from `main` (not cherry-picked from
`vision`), so every diff shows only its own change; the base is
retargeted to `main` as parents land.

| # | PR | Contents | Touches |
|---|---|---|---|
| 1/4 | #910 Model **← this PR** | Molmo2 HF loader, image processor,
flex attention, split-vocab embedding, `MultimodalLM` extensions | `nn/`
|
| 2/4 | #911 Train infrastructure | `MultimodalTransformerTrainModule`,
`PerGroupScheduler`, weighted CE, unsharded-export callback | `train/`,
`optim/`, `nn/functional`, `distributed/` |
| 3/4 | #912 Data core | sequence builder / branch packing, collator,
mixture loader, SFT formatter, PixMo-Cap | `data/multimodal` (core) |
| 4/4 | #913 Stage-1 recipe | stage-1 datasets, mixtures,
`Molmo2-Stage1.py` | `data/multimodal` (datasets), `scripts/` |

**Not yet opened (planned follow-ups):**
- *AC-RNG follow-up*: make activation-checkpoint RNG replay cover
`ResidualStream.masked_dropout`. It has to sit on top of #906, which
rewrites the same lines, so it waits for #906.
- *Stage 2* (`Molmo2-Stage2.py`, the `image_only_v9` mixture,
multi-image datasets, `compare_sft_example.py`): stays on `vision` until
this series lands, then follows as its own PR(s).
- *Alignment / OLMoDDP multimodal layers* (#886, #889, #902, #903,
currently targeting `vision`): rebased on top once `vision` is synced to
`main`.

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

No intended text-side change. What was checked:

- **Diff audit of every pre-existing file the series modifies**
(`nn/transformer/{model,block,config}`, `nn/attention`, `nn/lm_head`,
`nn/residual_stream`, `nn/rope`, `nn/ddp/block`,
`train/callbacks/speed_monitor`, `optim`, `distributed`). All remaining
edits add optional arguments that default to the old behaviour
(`masked_dropout=0`, `n_extra_vocab=0`, `response_logits_only=False`,
`position_ids=None`, `or_mask/and_mask=None`, ...). The audit also found
two edits that *did* alter text behaviour; both were removed from the
series: a reroute of FSDP2 gradient clipping in `TransformerTrainModule`
(text FSDP2 models would have left the torchtitan path), and new
"examples per second" metrics in `SpeedMonitorCallback` on text runs
(now emitted only for batches carrying `example_ids`).
- **Bit-for-bit comparison, `main` vs the series tip**, same seeds, CPU:
`state_dict` keys and values, eval logits, loss, and every parameter
gradient are identical (SHA-256 over the bytes) for `olmo2_1M` in eval,
train, and train with `dropout=0.1`, and for a qwen3-style `llama_like`
model with `qk_norm`.
- **Existing (non-multimodal) test suites, run on `main` and on the tip
of this series** (`src/test/{nn,train,optim,data,distributed}`, CPU):
`main` 1175 passed / 8 failed; series tip 1204 passed / 8 failed. The 8
failures are identical on both and are environment issues (S3/network:
`mixes_test` x3, S3 checkpoint tests x4; and
`test_logprobs_match_after_roundtrip[gemma3]`). Nothing that passed on
`main` fails on the series.
- `mypy src/` (CI config, `<1.4`), ruff, black, isort all clean.
- **Not covered:** text GPU/distributed paths (FSDP2, TP, CP, flash
kernels) can't run on a CPU box. The GPU smoke below exercises FSDP2 on
the multimodal path only, so text-side GPU CI remains the gap.

## Left out on purpose

- Activation-checkpoint RNG replay for `masked_dropout` (`ac_rng_test`,
`_dropout_is_active`). It touches the same lines as #906, which fixes
the general case. I'll send a small follow-up on top of #906 so
`ResidualStream.masked_dropout` also counts. Until then `masked_dropout`
is inert by default but not AC-safe.
- Two tests that need the data package
(`test_packed_examples_are_isolated`,
`molmo2_training_logits_parity_test`) move to PR 3.

## Testing

**CPU:** `src/test/nn/vision`, `flex_backend_test`, `embedding_test`,
`lm_head_test`, `residual_stream_test`: pass (the one failure,
`parity_test::test_clip_parity`, is this dev box's `transformers`
version; it passes on the Beaker image). `mypy src/` (CI config), ruff,
black, isort clean.

**GPU logit parity vs HF Molmo2 (Beaker, 1 GPU, bf16, 146 passed / 5
skipped / 0 failed):** max |diff| vs the HF reference. Two runs on
different hardware:
[A100](https://beaker.org/ex/01M47FK4ES7M0QY3BA2HDSS9TG) (on
`987a5dbeb`, before the last trims) and
[B300](https://beaker.org/ex/01M48RE6ZHWSD6CKGK216EVPA4) (on
`3dd8281e4`, the current tip of #913). bf16 kernels differ across
hardware, so the diffs move a little; the two A100-era runs agree to
every printed digit with each other, i.e. the trims did not change
numerics.

| check | 4B (A100 / B300) | 8B (A100 / B300) |
|---|---|---|
| token embedding | 0.0 / 0.0 | 0.0 / 0.0 |
| LM-only last-token logits | 0.203 / 0.188 | 0.250 / 0.250 |
| full pipeline (ViT + connector + splice + LM) logits | 0.156 / 0.156 |
0.188 / 0.375 |
| vision tower layers 18 and 24 | 1.5e-3 / 2.3e-3 | 4.9e-4 / 8.5e-4 |

Argmax matches HF in every case; the weighted training loss and
all-response logits match for both models; bidirectional image attention
matches HF (0.25 vs 1.3 if left causal, i.e. the mask matters and is
correct). Also passing on GPU: generation parity, FlexAttention vs dense
masks, packed-example isolation, the multimodal train module.
**Skipped: Molmo2-O-7B** (all 5 variants): per-layer YaRN attention
scaling is not implemented in `MultimodalLM` (known, deferred), so O-7B
is *not* verified by this series.

**GPU training smoke (8x GPU, FSDP2)** on the tip of #913:
[`mm-trim2-gpu-smoke`](https://beaker.org/ex/01M48RF37WG2Y6HWK05T7XKY5C)
(B300): 30 steps of `Molmo2-Stage1.py`, CE 3.23 -> 2.57, grad norm 24.2
-> 7.7, checkpoint and unsharded export written. Earlier runs of
previous commits (A100-class nodes) went 3.24 -> 2.61.
… CE (#911)

## Summary

PR 2 of 4 for moving the Molmo2 stage-1 reproduction from the long-lived
`vision` branch onto `main` in reviewable pieces. #910 (the model) is
merged; this PR is the **training-loop machinery** for it. No data
pipeline and no scripts here (those are #912 and #913).

- `MultimodalTransformerTrainModule`: trains `MultimodalLM` with a
per-token weighted loss, optimizer param groups for LM / vision tower /
connector, and DDP / FSDP / HSDP over the composite model. It subclasses
`TransformerTrainModule` and reuses its state-dict, microbatch-context,
grad-clip and forward helpers; `train_batch` is its own because the
batch format and loss differ.
- `weighted_cross_entropy_loss` (`nn.functional`): CE with a per-token
float weight, as in mm_olmo.
- `PerGroupScheduler`: a different LR schedule per optimizer param group
(e.g. connector vs LM warmup).
- `SpeedMonitorCallback`: examples/second (only for batches carrying
`example_ids`) and optional `extra_flops_per_batch` from the train
module.

Everything is opt-in; existing train modules behave exactly as before.
Two small guards in already-merged code come with it: `MultimodalLM`
rejects sliding-window FlexAttention layers (the shared flex mask has no
window), and `TransformerConfig` rejects `n_extra_vocab` on every
non-default transformer type.

### Loss normalisation and metrics
Each rank divides its weighted CE sum by the **global** weight divisor
(global weight sum over DP world size), so gradients and the logged CE /
Z-loss equal `sum_r ce_r / global_weight` even when ranks have different
numbers of response tokens. Only an all-zero batch falls back to a
divisor of 1, so fractional weights normalise exactly. With a
`SkipStepOptimizer` the reduced loss and grad norm are handed to the
optimizer, as in the base module.

## Series: all PRs

Linear stack, each PR cut fresh from `main`; the base is retargeted to
`main` as parents land.

| # | PR | Contents | Status |
|---|---|---|---|
| 1/4 | #910 Model | Molmo2 HF loader, flex attention, split-vocab
embedding, `MultimodalLM` | merged |
| 2/4 | #911 Train module **← this PR** |
`MultimodalTransformerTrainModule`, `PerGroupScheduler`, weighted CE,
`SpeedMonitorCallback` additions | review |
| 3/4 | #912 Data core | image preprocessor, sequence builder / branch
packing, collator, mixture loader, SFT formatter, PixMo-Cap | draft |
| 4/4 | #913 Stage-1 recipe | stage-1 datasets, mixtures,
`Molmo2-Stage1.py`, unsharded-export callback | draft |

**Follow-ups, not yet opened:** activation-checkpoint RNG replay for
`ResidualStream.masked_dropout` (sits on top of #906); stage 2
(`Molmo2-Stage2.py`, `image_only_v9`, multi-image datasets), which stays
on `vision` until this series lands; the alignment / OLMoDDP layers,
rebased once `vision` is synced to `main`.

## Why this is a separate PR

- Different review concern from #910: optimizer param groups, FSDP/DDP
wrapping of a composite model, loss reduction. That is `train/`
territory, not model numerics.
- Unit-testable on CPU without any data, and reusable by any multimodal
model.
- It depends on #910 only for the `MultimodalLM` type, and #912 does not
depend on it, so the two can be reviewed in parallel.

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

No intended text-side change.
- **Diff audit:** the only lines this PR *removes* from existing files
are an `__all__` entry and the `n_extra_vocab` check (now stricter;
nothing on `main` sets it). Everything else is additive: new functions,
a new scheduler, and `SpeedMonitorCallback` logic that only triggers for
batches with `example_ids` or a train module defining
`extra_flops_per_batch`, which text modules don't.
- `SpeedMonitorCallback` for text runs: no new metrics, same FLOPs.
- `mypy src/` (CI config), ruff, black, isort are clean.
- Not covered: text GPU / distributed paths (FSDP2, TP, CP) can't run on
a CPU box; CI's GPU jobs are the check there.

## Review notes

Earlier review findings are fixed in this PR: skip-step bookkeeping,
exact fractional-weight normalisation, globally weighted metrics, plus
rejections for sliding-window flex, non-default `n_extra_vocab`, and DDP
with gradient accumulation (torch 2.10's composable `replicate` has no
`no_sync`, so every microbatch would all-reduce; stage 1 uses FSDP).
Deliberately not here: the unsharded-export callback and the
non-finite-loss collective. The callback moved to #913, its only user,
and the `Trainer` already raises on a non-finite CE loss when metrics
are reduced.
`MultimodalLM.forward(images=None)` is only safe single-rank or when
every rank passes `None`; `MultimodalCollator` always emits an `images`
tensor (a dummy crop for text-only batches), so ranks stay aligned.

## Testing

CPU: the train-module tests (response residual dropout with dense and
response-only logits, fractional-weight invariance of gradient and
metric, skip-step bookkeeping), weighted-CE tests, embedding /
multimodal tests for the new rejections. 175 passed, 0 related failures
on this PR; 322 passed at the top of the stack (#913). One distributed
checkpoint test (`test_load_checkpoint_with_missing_keys`) fails in this
sandbox identically on unmodified `main`.

GPU: the train module runs end to end in the stage-1 smoke (30 steps, 8
GPUs, FSDP2) on #913: CE 3.23 -> 2.57, linked from #913. It has no GPU
test of its own yet.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Sonnet 5.5 <[email protected]>
This PR adds Core interfaces for routing replay, custom RL objectives,
and streaming weight publication, plus opt-in checkpoint performance
improvements.

**The central design principle of this PR is to preserve existing
training behavior.** Existing scripts work unchanged; new RL behavior
requires explicit opt-in through configuration or the new APIs.

Below are the configuration and API controls introduced or newly exposed
by this PR that the Open Instruct/MILES integration uses or can use.
Defaults are **Core defaults**; MILES explicitly selects alternatives in
several places. APIs without a feature flag show how they are enabled
instead.

## Model and routing

| Control | Purpose |
|---|---|
|
[LMHeadConfig.fp32_output](https://github.com/allenai/OLMo-core/blob/7e97bc43ff25d080ae4fd0eab1050a79caf80e55/src/olmo_core/nn/lm_head.py#L94)<br/>`default:
False` | Keep output logits in FP32 while retaining low-precision
projection and backward. This reduces rounding of the logits used to
compute RL log-probabilities. |
|
[RoutedExpertsConfig.match_eager_rounding](https://github.com/allenai/OLMo-core/blob/7e97bc43ff25d080ae4fd0eab1050a79caf80e55/src/olmo_core/nn/moe/v2/routed_experts.py#L411)<br/>`default:
False` | Match eager training’s intermediate SiLU rounding to reduce
scoring/training differences. Matching this rounding step does not
guarantee bitwise parity for every dtype. |
|
[RoutedExpertsConfig.row_specialization](https://github.com/allenai/OLMo-core/blob/7e97bc43ff25d080ae4fd0eab1050a79caf80e55/src/olmo_core/nn/moe/v2/routed_experts.py#L410)<br/>`default:
"static"` | Select `"dynamic"` to reuse expert activation kernels across
token capacities. This reduces recompilation when RL batch shapes vary.
|
|
[MoERouterConfigV2.lb_loss_count_source](https://github.com/allenai/OLMo-core/blob/7e97bc43ff25d080ae4fd0eab1050a79caf80e55/src/olmo_core/nn/moe/v2/router.py#L59)<br/>`default:
"executed"` | Select `"router_selected"` to balance the current policy’s
expert choices while replaying rollout routes. This keeps the balancing
signal tied to the policy being trained. |
| [Router replay:
replay_routes](https://github.com/allenai/OLMo-core/blob/7e97bc43ff25d080ae4fd0eab1050a79caf80e55/src/olmo_core/nn/moe/v2/replay.py#L12)<br/>`Enabled
by: explicit API call` | Reuse rollout expert choices during scoring and
training, reducing routing mismatch. MILES selects this with
`miles.use_rollout_routing_replay=true`. |
| [Custom objective:
train_batch_with_loss](https://github.com/allenai/OLMo-core/blob/7e97bc43ff25d080ae4fd0eab1050a79caf80e55/src/olmo_core/train/train_module/transformer/objective.py#L11-L18)<br/>`Enabled
by: explicit API call` | Train with a supplied RL loss instead of the
standard language-model loss. Supports per-microbatch replay contexts;
rejects unsupported `bias_gamma` balancing. |
|
[reset_auxiliary_metrics](https://github.com/allenai/OLMo-core/blob/7e97bc43ff25d080ae4fd0eab1050a79caf80e55/src/olmo_core/train/train_module/transformer/objective.py#L17)<br/>`default:
False` | Clear model auxiliary counters before custom training and on
exit, including errors. Leave False when the caller collects and resets
them, as MILES does. |

## Checkpoint controls

Core already supports expert-parallel checkpointing. These controls tune
the existing save/load path without changing the checkpoint format. All
performance and profiling changes are opt-in; defaults preserve the
existing writer and planning policies. Open Instruct exposes these as
`core.checkpoint_<name>`.

| Control | Purpose |
|---|---|
|
[process_count](https://github.com/allenai/OLMo-core/blob/7e97bc43ff25d080ae4fd0eab1050a79caf80e55/src/olmo_core/train/train_module/transformer/ddp_train_module.py#L1157)<br/>`default:
None` | Request multiple writer processes instead of the existing thread
pool. This exposes the existing process-based writer through direct
save. |
|
[compact_storage](https://github.com/allenai/OLMo-core/blob/7e97bc43ff25d080ae4fd0eab1050a79caf80e55/src/olmo_core/train/train_module/transformer/ddp_train_module.py#L1159)<br/>`default:
False` | Skip copying CPU tensors that already own exactly the storage
being saved. This reduces checkpoint memory and copying overhead. |
|
[dedup_save_to_lowest_rank](https://github.com/allenai/OLMo-core/blob/7e97bc43ff25d080ae4fd0eab1050a79caf80e55/src/olmo_core/train/train_module/transformer/ddp_train_module.py#L1160)<br/>`default:
True` | Set `False` to spread replicated-tensor writes across ranks.
This avoids concentrating checkpoint work on the lowest rank. |
|
[constant_memory_planning](https://github.com/allenai/OLMo-core/blob/7e97bc43ff25d080ae4fd0eab1050a79caf80e55/src/olmo_core/train/train_module/transformer/ddp_train_module.py#L1161)<br/>`default:
False` | Build supported contiguous shard metadata without large
temporary allocations. This reduces memory pressure during checkpoint
save and restore. |
|
[profile](https://github.com/allenai/OLMo-core/blob/7e97bc43ff25d080ae4fd0eab1050a79caf80e55/src/olmo_core/train/train_module/transformer/ddp_train_module.py#L1162)<br/>`default:
False` | Collect checkpoint phase timings and counters to diagnose slow
saves or restores. Profiling, including its CUDA synchronization, is
disabled by default. |

The save-failure recovery fix restores live optimizer storage if saving
raises an exception, such as a disk-full error. This lets a caller that
handles the failure retry saving or continue training without leaving
optimizer storage empty. The exception still propagates; recovery is not
automatic. Successful checkpointing and training numerics are unchanged.

## Weight publication

These APIs run only when called; ordinary training does not invoke them.

| Control | Purpose |
|---|---|
| [Streaming export:
iter_olmo3_moe_hf_state](https://github.com/allenai/OLMo-core/blob/7e97bc43ff25d080ae4fd0eab1050a79caf80e55/src/olmo_core/nn/moe/v2/olmo3.py#L446-L448)<br/>`Enabled
by: explicit API call` | Gather and convert weights incrementally for
rollout-engine refreshes, avoiding a full gathered model copy. MILES
selects this through `core.stream_moe_export`. |
|
[fused_experts](https://github.com/allenai/OLMo-core/blob/7e97bc43ff25d080ae4fd0eab1050a79caf80e55/src/olmo_core/nn/moe/v2/olmo3.py#L447)<br/>`default:
False` | Publish stacked expert tensors for serving engines that accept
them, reducing per-expert transfers. MILES selects this with
`core.expert_publication="fused"`; it is not an HF checkpoint layout. |
| [cpu —
gather_olmo3_moe_hf_state](https://github.com/allenai/OLMo-core/blob/7e97bc43ff25d080ae4fd0eab1050a79caf80e55/src/olmo_core/nn/moe/v2/olmo3.py#L394)<br/>`default:
False` | Stage gathered export weights on CPU to reduce GPU residency.
MILES uses this in the full-gather fallback when streaming is disabled.
|

## HF-to-Core model construction

The new
[build_olmo3_moe_config_from_hf_config](https://github.com/allenai/OLMo-core/blob/7e97bc43ff25d080ae4fd0eab1050a79caf80e55/src/olmo_core/nn/moe/v2/olmo3.py#L55-L66)
creates the native MoE configuration used to initialize RL from an HF
checkpoint. These arguments select existing Core capabilities for that
new model; they do not change other models. The existing `get_hf_config`
remains the model-to-HF config builder.

| Control | Purpose |
|---|---|
|
[dtype](https://github.com/allenai/OLMo-core/blob/7e97bc43ff25d080ae4fd0eab1050a79caf80e55/src/olmo_core/nn/moe/v2/olmo3.py#L58)<br/>`default:
bfloat16` | Choose parameter precision for the imported model. MILES
uses BF16 to fit training alongside rollout workers. |
|
[attention_backend](https://github.com/allenai/OLMo-core/blob/7e97bc43ff25d080ae4fd0eab1050a79caf80e55/src/olmo_core/nn/moe/v2/olmo3.py#L59)<br/>`default:
flash_4` | Choose attention kernels for the target hardware. MILES
forwards `core.attention_backend`, including Torch for compatibility
checks. |
|
[attention_type](https://github.com/allenai/OLMo-core/blob/7e97bc43ff25d080ae4fd0eab1050a79caf80e55/src/olmo_core/nn/moe/v2/olmo3.py#L60)<br/>`default:
default` | Choose ordinary or fused-v2 attention projections. This
allows an imported model to use the corresponding Core implementation. |
|
[ep_path](https://github.com/allenai/OLMo-core/blob/7e97bc43ff25d080ae4fd0eab1050a79caf80e55/src/olmo_core/nn/moe/v2/olmo3.py#L61)<br/>`default:
sync_1d` | Choose how expert-parallel workers exchange tokens. This
allows the imported model’s communication path to match the deployment.
|
|
[ep_capacity_factor](https://github.com/allenai/OLMo-core/blob/7e97bc43ff25d080ae4fd0eab1050a79caf80e55/src/olmo_core/nn/moe/v2/olmo3.py#L62)<br/>`default:
1.25` | Size expert-parallel dispatch capacity. This controls the memory
reserved to accommodate uneven expert loads. |
|
[router_aux_loss_weight](https://github.com/allenai/OLMo-core/blob/7e97bc43ff25d080ae4fd0eab1050a79caf80e55/src/olmo_core/nn/moe/v2/olmo3.py#L63)<br/>`default:
None` | Set the expert load-balancing loss coefficient; `None` disables
it. MILES supplies this to discourage uneven expert usage. |
|
[router_z_loss_weight](https://github.com/allenai/OLMo-core/blob/7e97bc43ff25d080ae4fd0eab1050a79caf80e55/src/olmo_core/nn/moe/v2/olmo3.py#L64)<br/>`default:
None` | Set the router logit regularization coefficient; `None` disables
it. MILES supplies this to stabilize router logits during training. |
|
[init_seed](https://github.com/allenai/OLMo-core/blob/7e97bc43ff25d080ae4fd0eab1050a79caf80e55/src/olmo_core/nn/moe/v2/olmo3.py#L65)<br/>`default:
2026` | Set the new model’s initialization seed. This makes
initialization reproducible before checkpoint weights are loaded. |

## Commit review guide

Each link opens the diff for one functional commit, including its fixes
and tests.

| Commit | Scope |
|---|---|
| [FP32 output
head](7f847b1)
| Opt-in projection, mixed-precision gradients, autocast and numerical
tests. |
| [SwiGLU scoring
options](f85d2e3)
| Intermediate rounding and dynamic row specialization, with
default-path and numerical tests. |
| [Router
replay](25fb36c)
| Scoped route replay and current-policy balancing counts, with dispatch
and gradient tests. |
| [Custom
objectives](cf288ab)
| Caller-supplied losses, microbatch contexts and train/eval mode
handling, with integration tests. |
| [Checkpoint
controls](077b855)
| Writer and planner options, profiling isolation and save-failure
recovery, with checkpoint tests. |
| [HF construction and
publication](a4f2f96)
| OLMo3 MoE configuration, shared HF conversion, streaming exports and
distributed round-trip tests. |
| [Review feedback
corrections](7e97bc4)
| Device-aware checkpoint profiling and opt-in auxiliary-metric cleanup,
with CPU round-trip, failure-cleanup and gradient-parity tests. |
| [RoPE import review
fix](0117c4f)
| Addresses [Akshita's RoPE
finding](#888 (comment)):
preserves flat, legacy, and per-layer settings; maps linear, Llama-3,
and compatible YaRN scaling; rejects unsupported settings. Adds 121 test
cases, including HF/Core frequency, logits, and gradient parity.
Existing exporter restrictions are unchanged. |

## Validation

Validation combines the GPU integration panel for the [pinned Open
Instruct/MILES/olmo-sglang
stack](https://github.com/allenai/open-instruct/blob/52e6bbe719419a108f2817ee3430f993c28b8899/runtime/miles/runtime.lock.json)
with focused tests for the rebased branch. Default compatibility, GPU
numerics, checkpoint recovery and weight publication pass.

- **[RoPE import review
fix](0117c4fc4606db57244c801947c4632260266c70):**
291 tests passed and 130 skipped across the importer, factory, HF
conversion/export/modeling, and RoPE suites, including the two-process
CPU distributed regression. The new test file contributes 121 passing
cases. Ruff, Black/isort on changed files, and full mypy (614 source
files) passed. Numerical comparisons used Transformers 5.14.1.

- **Rebase checks:** 230 CPU tests passed; two S3 checkpoint cases were
blocked by an expired local AWS SSO session. Ruff, Black/isort and full
mypy (599 source files) passed. GPU tests were not rerun locally.
- **Review-feedback corrections:** 50 focused tests pass, including a
real CPU checkpoint round trip, profiling isolation, opt-in metric
cleanup on success and failure, preserved returned metrics, and exact
gradient parity. Ruff, Black/isort and full mypy (598 files) pass.
- **Default behavior:** 22 tensors match upstream `main` exactly on CPU
and again on CUDA, covering ordinary logits, losses, gradients,
optimizer updates and router outputs. The comparison uses the default
options and blocks imports from MILES, SGLang and Open Instruct.
Regression tests also cover positional-call compatibility and disabled
checkpoint profiling.
- **Core contracts:** 312 tests passed on two B300s. Coverage includes
FP32-head backward comparisons with ordinary linear, randomized SwiGLU
rounding and row modes, replay and custom-objective mode handling,
checkpoint save-failure recovery, EP checkpoint resharding, and
full/streaming HF conversion. Six cases requiring more GPUs were skipped
in this two-GPU job.
- **Integration:** A two-B300 job completed four nonzero optimizer
updates, then a fresh job restored the native checkpoint and completed
updates 5–6. The runs exercised FP32 logits, dynamic SwiGLU rows, route
replay, router-selected balancing counts, packing, asynchronous fused
weight refresh, response recording and HF export. Both trainer and
serving restored compiler-cache hits on resume. These are mechanics
checks, not learning-quality measurements.
- **Pinned-runtime contracts:** 537 tests passed, including real Core
optimizer updates and native resume across the supported test model
variants. Ten MoE-only cases were skipped for dense models.
- **CI:** [The validation panel’s full CI run
passed](https://github.com/allenai/OLMo-core/actions/runs/36897236658),
including all nine GPU jobs, CPU tests, Ruff, Black/isort, full mypy,
docs and build. [CI is
rerunning](https://github.com/allenai/OLMo-core/pull/888/checks) for the
rebased branch.

Runs:

1. [Default compatibility and GPU
contracts](https://beaker.org/ex/01M3W77R74AEY6R9T39A2Z7QFH).
2. [Four-update
training/save/export](https://beaker.org/ex/01M3W78GHXKHNT0F38TPJZNY2E).
3. [Fresh-process checkpoint
resume](https://beaker.org/ex/01M3W7VNSS1GW9Z6737HX9FGDD).
4. [Pinned-runtime
contracts](https://beaker.org/ex/01M3W8MKAZKVWYRCDWTKVQPJW9).

A **1,000-update run** of the same underlying RL implementation also
completed across checkpoint resumes, using EP4 training and 20 rollout
engines ([completion
run](https://beaker.org/ex/01M3T6SJFMAK80RSPEKBGRAA6B)). It used an
earlier revision before subsequent compatibility fixes and cleanup. This
is longer-run evidence for the implementation, not a 1,000-update test
of the exact PR head.

---------

Co-authored-by: Akshita Bhagia <[email protected]>
)

OLMoE3 training on B300 with Torch 2.13 failed before its first
optimizer step: packed BF16 parameters could violate compiled kernels’
alignment assumptions, and a separately compiled loss could replace
Dynamo’s stream registry before shared-expert backward. Cold-cache LC
data packing also exceeded the default distributed startup timeout.

This preserves 16-byte starts in flat model parameter buffers while
keeping logical parameter shapes and packed collective offsets
unchanged. Shared-expert stream contexts run outside the compiled graph
on both the no-EP and rowwise-NVSHMEM paths; child math stays compiled,
with the existing arithmetic, stream dependencies, and overlap.
Experiment configs now expose the process-group timeout (default
unchanged at 15 minutes), allowing the companion LC workload to use two
hours for cold-cache packing.

HF exports also now serialize `moe_use_core_numerics=true`. The exported
HF model reproduces the source no-EP expert arithmetic: packed
dense/shared projections, packed SwiGLU with a single rounding, and TE
index-map combination in routing-slot order. BF16 combination rounds
multiplication separately on pre-SM90 GPUs and uses fused updates on
SM90+, matching the respective TE kernels. CUDA inference without Triton
uses the existing Torch activation fallback. Prior HF configs retain
their original FP32-combination implementation. This fixes a real
model-forward difference rather than substituting a special verifier,
and leaves the strict conversion tolerance unchanged.

Companion to [scaling-ladders
#74](allenai/scaling-ladders#74).

## Validation

- Two-rank CPU regression checks BF16 pointer alignment, mixed
sharded/replicated FP32 master synchronization, and exact values
before/after updates. It failed before the buffer fix.
- [B300 stream regressions at
`52c4d42`](https://beaker.org/ex/01M3E62JVQVTTARVP0ZQJY35R4): **3
passed**. They compare forward outputs and input/weight gradients after
a separate compiled loss, including the split shared-expert path with
and without activation recomputation.
- Configuration tests verify timeout overrides survive serialization and
reach distributed initialization in both training and checkpoint
evaluation: **2 passed**.
- Production-command 275M Cx8 canary:
[PT](https://beaker.org/ex/01M3D82C49ZWWP2Z08G8PQ1JTH),
[MT](https://beaker.org/ex/01M3D97F10FCATAME3FPP64REP), and
[LC](https://beaker.org/ex/01M3DB87FD4AYSD4C41NY0MEDG) each completed
five steps with finite gradients, zero skipped updates, and checkpoint
audits passing.
- All seventeen 275M/450M/810M no-EP PT/MT/LC topologies completed 50
steps each on B300 (fifteen using core `97a4bc3`, the two LC retries
using core `2122d42`). Immutable training image:
`01M28XX5N4KM6PD0G81KC41BDW`; Torch `2.13.0+cu130`, Triton `3.7.1`, FLA
`0.5.2`, FA4 `4.0.0b16`. Detailed topology/source pins and job IDs are
recorded in the companion ladder PR.

- Focused CPU HF/config tests, lint, type, and formatting checks pass.
[Current-head
CI](https://github.com/allenai/OLMo-core/actions/runs/36231650355) at
`b5db31d` passed: **22 checks passed, 1 skipped**.

## Distributed qualification

All seven 1.4B EP4/EP8 production topologies completed 50 steps with
finite gradients and zero skipped updates, completing all 24 approved
B300 systems configurations in the companion ladder. Every replica exit
is verified. The one-GPU stream regression does not qualify distributed
expert communication. All three production PT/MT/LC conversions and
tokenizer export audits now pass; downstream PT/MT/LC native vLLM smoke
evaluations also passed (10,000 examples each, zero errors, exit 0).
Exact HF/core conversion does not establish exact HF/vLLM numerical
parity.


[Current A100
qualification](https://beaker.org/ex/01M3EDD3RZC0MMPV31SDBGS6ZN),
[H100](https://beaker.org/ex/01M3EDD4RFMC2WM8SC8612TZ54), and
[B300](https://beaker.org/ex/01M3EDD5PCY9B7PZDF553WR2KA) at `f09d694`:
**16 tests passed on each GPU**, covering actual core/TE BF16 and FP32
experts, the real dense/shared GEMM dimensions, CUDA without Triton,
FP64 rounding oracles, and full-graph forward/gradients. Each GPU also
produced **maximum logit difference `0.0` on three real PT-checkpoint
input seeds**, using contiguous HF weights as in the exporter. All jobs
exited successfully; `rtol=atol=1e-4` is unchanged.

---------

Co-authored-by: Akshita Bhagia <[email protected]>
…lator, mixture loader (#912)

## Summary

PR 3 of 4 for moving the Molmo2 stage-1 reproduction from the long-lived
`vision` branch onto `main` in reviewable pieces. #910 (model) and #911
(train module) are merged; this PR is the **data contract**: how a
multi-annotation example becomes tokens, positions, sub-segment ids and
float loss weights, and how examples are packed and mixed. No dataset
recipes yet (those are #913).

- `sequence_builder` (`build_packed_sequence`,
`build_branched_sequence`): multi-annotation / branch-packing sequence
assembly with float loss weights and sub-segment ids.
- `packing.pack_examples`, `MultimodalCollator`, `MultimodalDataLoader`.
- `MixtureDataLoader` + `mixture_weights`, `prefetch`: weighted,
resumable multi-dataset mixing.
- `SftFormatter` (+ `grounding`, `multiple_choice_templates`),
`message_sequence`, `message_weight`, `qwen3_layout`, `sft_common`,
`dataset_compat`, `paths`.
- `nn/vision/molmo2_image_processor.py` (`preprocess_image_molmo2`): the
Molmo2 image preprocessor (crops, pooling indices). Moved here from the
model PR because only the data pipeline uses it.
- `PixMoCapDataset`: kept here because the core tests exercise it end to
end and most #913 datasets build on its helpers.

`data/multimodal/__init__.py` exports only what is in this PR; #913
extends it. Nothing in existing code changes except one added line in
`CHANGELOG.md` and two additive exports in `nn/vision/__init__.py`.

## Series: all PRs

| # | PR | Contents | Status |
|---|---|---|---|
| 1/4 | #910 Model | Molmo2 HF loader, flex attention, split-vocab
embedding, `MultimodalLM` | merged |
| 2/4 | #911 Train module | `MultimodalTransformerTrainModule`,
`PerGroupScheduler`, weighted CE | merged |
| 3/4 | #912 Data core **← this PR** | image preprocessor, sequence
builder / branch packing, collator, mixture loader, SFT formatter,
PixMo-Cap | review |
| 4/4 | #913 Stage-1 recipe | stage-1 datasets, mixtures,
`Molmo2-Stage1.py`, unsharded-export callback | stacked on this PR |

**Follow-ups, not yet opened:** activation-checkpoint RNG replay for
`ResidualStream.masked_dropout` (sits on top of #906); stage 2
(`Molmo2-Stage2.py`, `image_only_v9`, multi-image datasets, `PixMoCap`
`sft_demo` mode), which stays on `vision` until this series lands; the
alignment / OLMoDDP layers, rebased once `vision` is synced to `main`.

## Why this is a separate PR

- This is the data contract: sequence layout, loss weighting and
packing. It is correctness-critical and reviewed by data owners, not
train-loop or model-numerics reviewers.
- No GPU or trainer dependency, only the special-token constants from
#910, so it is reviewable and testable on its own.
- Deliberately dataset-agnostic: with this API fixed, every dataset in
#913 is a mechanical adapter, so #913 need not re-litigate the core
design.
- It keeps ~4k lines of core logic from being buried under ~11k lines of
dataset adapters.

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

No. Everything is new files under `data/multimodal/` plus
`nn/vision/molmo2_image_processor.py` and its export; the text data
pipeline (`olmo_core.data` outside `multimodal/`) is untouched. `mypy
src/` (CI config), ruff, black and isort are clean.

## Review notes

Codex's findings on `PixMoCapDataset` are fixed here:
- **Epoch-aware sampling:** the dataset now uses `EpochSeededExamples`
(the loaders already call `set_epoch`), so a row with several
transcripts no longer picks the same one every epoch. Test added.
- **`sft_demo` mode removed:** it bypassed the truncation path and is
stage-2-only (wired from `image_only_v9`, which is not in this series).
It returns with stage 2.
- **Truncation (Akshita):** `pixmo_cap._truncate` and
`sft_common.truncate_example` were two near-copies. They are now one
weighting-aware `truncate_example`, which rescales surviving branches
only for `root_subsegments*` weighting (it used to rescale with
weighting `none` too), and the collator now refuses to cut `<im_patch>`
tokens instead of only asserting it in a comment. Tests added.
- **Remote URLs:** nothing in this series uses them, so `image` is
documented as a local path and `http(s)://` values now raise a clear
`ValueError` instead of a confusing `FileNotFoundError`.

## Testing

CPU: `src/test/data` and `src/test/nn/vision/multimodal_test.py`
(data-core tests, packed-example isolation for the dense and flex
backends, epoch rotation, URL rejection). Results are in the checks
below. The data path is exercised end to end, on GPU, by the stage-1
smoke linked from #913.
Adds `olmo_core.nn.maxtext`, which converts model weights between OLMo
Core checkpoints and
[MaxText](https://github.com/AI-Hypercomputer/maxtext) checkpoints in
both directions. It follows the structure of the Hugging Face converter
in `olmo_core.nn.hf`.

Weights only for now; optimizer state isn't converted.

## Design
- **`config.py`**: `get_maxtext_config(model_config)` plays the role of
`get_hf_config`.
- It picks the MaxText `decoder_block` from the OLMo Core block config.
- It checks that the decoder can build the model, and raises a clear
error if it can't.
- It gives the MaxText `model_name`, the overrides that size the model,
and the decoder's scan layout.
- It reads the config dict without building the model, so conversion
runs on CPU without GPU kernel packages.
- **`convert.py`**: the weight mappings, written as
`StateMappingTemplate`s and run by the existing `StateConverter`.
- They're grouped by OLMo Core component: embeddings and LM head, norms,
attention, Kimi Delta Attention, feed-forward, and shared and routed
experts.
- They're built per layer, because layers in a hybrid model share OLMo
Core names (`blocks.{i}.attention.*`) but not MaxText names. The HF
hybrid path splits by layer for the same reason.
- Supporting another architecture means adding a decoder entry, a scan
layout, and mapping builders.
- **`checkpoint.py`**: reads and writes OLMo Core DCP checkpoints,
including OLMoDDP's flat `module.*.main` entries, and MaxText Orbax
checkpoints. It also converts between MaxText's scanned and unscanned
layouts for each decoder.
- **`convert_checkpoint.py`**: `convert_checkpoint_to_maxtext()` and
`convert_checkpoint_from_maxtext()`.
- Conversion goes one layer at a time, so memory stays near one copy of
the model.
  - By default it checks that converting each layer back is bit-exact.
- **`parity.py`**: logit summaries and comparison metrics, plus
`maxtext_logit_summary()`, which runs a converted checkpoint in MaxText
and checks that it loaded the checkpoint's weights.
- **`src/examples/maxtext/`**: the CLIs
`convert_checkpoint_{to,from}_maxtext.py`, the parity scripts
`reference_logits.py` and `maxtext_logits.py`, and a README.

## Supported MaxText decoders
| `decoder_block` | OLMo Core models |
|---|---|
| `olmo3` | Dense `reordered_norm` blocks: RoPE attention with global QK
norm, SwiGLU, and an optional `[w, w, w, -1]` sliding window |
| `olmoe3` | Peri-norm hybrid: Kimi Delta Attention plus gated
NoPE/SSMax full attention, a dense first layer, then latent routed
experts with a shared expert |

## Testing
- **`convert_test.py`** (CPU, no JAX):
  - round trips in both directions and through the scan layouts
- semantic checks of every re-layout against each framework's
computation: up/gate order, router layout, query/gate interleave,
attention head layouts, SwiGLU
  - key and shape errors, and layouts the decoders can't build
  - full-scale shapes for a 12B-parameter hybrid config
- **`maxtext_test.py`** (runs when MaxText is installed; CPU JAX is
enough):
- Converted trees exactly match the parameter shapes from MaxText's own
`jax.eval_shape` init, for both decoders, scanned and unscanned.
- A random dense model gives the same logits in OLMo Core and MaxText on
CPU, scanned and unscanned, with max relative error about 1e-6. The test
uses a sequence longer than the sliding window; changing the window by
one makes it fail.
- **Equivalence with the earlier version of this PR**: before I replaced
the earlier hybrid-only mapping code, the new mappings gave
bit-identical output to it on every fixture.
- That earlier code had been checked on a real 12B hybrid checkpoint: a
bit-identical round trip of all 415 parameters, and MaxText logits
matching OLMo Core on GPU to fp32 noise (KL 1e-10).
- The MaxText config the new overrides resolve to is identical to the
one used then.

All 53 tests pass. isort, black, ruff and mypy are clean on the new
files.

## Not done yet
- Optimizer-state conversion.
- Tied embeddings, scaled (YaRN) RoPE for `olmo3`, and pre-norm blocks.
- Packed-document and bf16/TPU parity checks.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_011gHFAjGWHZotPXfJeNM9vM

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Akshita Bhagia <[email protected]>
Brings vision up to main at ccf4ef4. The Molmo2 files main gained from #910-#912 were
cut from vision at f639a28, so they were merged against that cut point: vision keeps
its later multimodal work (#889, #902, #903, #918, #933), main's review fixes come in
where vision had not replaced them. Per-file decisions are listed in the PR.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 30, 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-30T21:00:21.905098Z ab38631 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 ab38631 into vision Oct 30, 2026
1 check passed
@jason718
jason718 deleted the jasonr/sync-main-into-vision branch October 30, 2026 20:59
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.

4 participants