Skip to content

Vision alignment for OLMoDDP on OLMo 3.5 as a multimodal-only layer on the #886 hooks (replaces the #869 copy) - #889

Merged
jason718 merged 9 commits into
visionfrom
jasonr/native-vision-alignment-on-886
Oct 5, 2026
Merged

jason718 merged 9 commits into
visionfrom
jasonr/native-vision-alignment-on-886

Conversation

@jason718

@jason718 jason718 commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

Summary

The OLMoDDP vision-alignment core, as a multimodal-only layer on the OLMoDDP hooks (#886) and the multimodal data infrastructure, both now on vision. The recipe has its own main() / train() / run() in internal/vision_alignment.py (Vision-Align.py calls it), so the shared internal/experiment.py is not modified. 39 files, +10,457/−90, of which 22 test files (+5,085). Restructured 2026-10-02 from the earlier 100-file version: generic infrastructure moved to its own PR, perception/joint adapters and the evaluation suites deferred to a stacked draft, dead code removed (collator/loader text_only, the HF vision shard downloader and its train-module hook), and tests cut to the key contracts (77 test functions removed; 63% fewer test lines).

What it contains:

  • MultimodalOLMoDDPModel (nn/vision/multimodal.py): the OLMoDDP wrapper that calls the LM through the Add the OLMoDDP hooks a multimodal wrapper needs, inert by default #886 hooks, computes the weighted response-only loss + z-loss, casts pixels to the vision tower's dtype, and runs document mode for KDA language models (packed examples isolated by doc_lens, no masks/positions).
  • MultimodalOLMoDDPTrainModule + MultimodalOLMoDDPOptimizer: frozen-parameter save/restore and load-key adapters through the train-module hooks; per-group clipping, component grad norms, partial fp32-master sync.
  • Callbacks (train/callbacks/multimodal.py): W&B auto-resume, Beaker config on resumed runs, metric overwrite, evaluator dedupe, checkpoint retention, model initialization.
  • The recipe (internal/vision_alignment*.py) with recipe.text_config inheritance of the text team's mid-training settings and the MULTIMODAL_OVERRIDES table (diff-tested), the alignment mixture (alignment.py), native text replay, LM evaluator + image pairing, the bridge-phase sources, the train script and the guide.

Not carried from #869: the router token mask, frozen experts under expert parallelism, rowwise-EP eval dispatch, every shared-file change (documented in docstrings/CHANGELOG).

OLMo 3.5 support (formerly PR #897, consolidated here)

Makes the vision alignment recipe (#889) run on the OLMo 3.5 "small hero" checkpoint (/weka/olmo-3p5-checkpoints/protected/olmo35-small-hero-20260907/emo/8T) by inheriting the text team's mid-training settings instead of hard-coding the s002-era runtime. Multimodal-only files; shared code is byte-identical to #886/#889.

  • recipe.text_config: path to a text mid-training config.json (the resolved config of scaling-ladders ladders/olmoe3/workloads/midtraining.py). The LM model config, optimizer (eps 1e-8, sigma_factor 6, compile, weight decay 0.1, betas, max_grad_norm), train-module settings (z-loss 1e-5, compile_model, DDP fp32 reduce/accumulate, ep_config=None, reset_optimizer_states_on_load), checkpointer bookkeeping, data-loader workers and the launch defaults (image, post_setup, env, shared memory, one node) come from it; a single MULTIMODAL_OVERRIDES table lists everything the alignment phases change (per-phase LRs/schedulers/warmups, per-group clipping, 128 x seq global batch, 4 x seq microbatch (joint 2 x seq), 500/50 checkpoint cadence, 50M foreach chunk, freeze lists, image-token rows, response-only logits, evaluator and init callbacks). A unit test builds bridge → perception → joint from a trimmed fixture of the pin's config and asserts the differing keys equal the table.
  • Without text_config the LM config is read from the checkpoint's config.json through the legacy latent-MoE normalizer with EMO cleared (what text mid-training does). The s002 forcing (flex backend, rowwise EP, capacity factor 8, recompute, EP degree 8) is gone on both paths.
  • Document mode for recurrent LMs: when any block is Kimi Delta Attention (no attention-mask support), packed examples are isolated through doc_lens/max_doc_lens derived from example_ids (no masks, no position_ids; sibling-branch packing rejected). Verified on a B300 with the 8T weights: packed-vs-standalone per-token CE diff 0.00000, negative control leaks 0.062, eager and compiled.
  • KDA stays on the fla kernels in document mode (use_experimental_kernels=False in the override table): kernel_fun.kda.ops.is_supported bool-evaluates cu_seqlens and crashes with document boundaries; text mid-training never passes them. Pending an upstream kernel_fun fix.
  • Launch defaults: workspace ai2/oe-olmo3p5-mt (budget ai2/oe-other), jasonr_* secrets, no AWS secrets, follow=False, min_runtime=8h, ai2/holmes.

Bridge smoke on the 8T checkpoint (1 node x 8 B300, Beaker 01M3TRTWNZ8SZ3EW77P72Z6MD4)

150 steps with recipe.text_config = the text team's resolved mid-training config and the bridge phase overrides: train CE 2.803 → 2.281, 0 skipped steps, grad norm 3.39 → 0.105, no torch.compile recompiles after step 20, ~5 s/step, 97 GiB active / 103.5 GiB reserved per GPU, checkpoints at steps 100 and 150.

evaluation (64 examples/source) startup step 150
pixmo_caption validation CE 2.7736 2.1665
caption matched-correct / matched-wrong CE (gap) 2.8348 / 2.8209 (−0.014) 2.2383 / 2.5036 (0.265)
caption first-8-token gap (wrong − correct) −0.070 1.265
caption blank-image CE 2.8048 2.3946
pixmo_transcript validation CE 2.8554 2.4357
transcript matched gap / first-8 gap 0.001 / −0.039 0.233 / 0.635

Resume test: relaunching the same run with max_duration 170 loaded the step-150 checkpoint and optimizer state, resumed the W&B run, trained steps 151-170 (0 skipped steps) and saved step 170; final caption validation CE 2.1477, image gap 0.284.

Three follow-up commits came out of the smoke: the document-mode guard now rejects only examples that really carry sibling branches (the packer always emits subsegment_ids, a constant id per branch-free example), the recipe uses MultimodalBeakerCallback (#889) so a resumed W&B run accepts the new Beaker experiment URL, and the pixel-dtype cast lives in #889.

Text-neutrality

Shared code is byte-identical to vision (which includes #886), so the #886 gates carry over; in addition the full stack (#886 + this PR + #885) was gated against the text pin b5db31dbd on a B300 with the production kernels: eager golden forward on the real 8T weights bitwise identical to the pin (96 router metrics equal, grads within the pin's own spread), the pin's GPU tests identical (283 passed, 40 xfailed), the pin's CPU tests identical (668 passed, same 2 S3-credential failures), the resolved text mid-training config identical, and a seeded 100-step text A/B of vision+hooks+#885 against two pin runs within the pins' own spread (details in #886).

Connector activation checkpointing is off

VisionConnector.apply_activation_checkpointing wraps the pooling and projector modules in checkpoint_wrapper; afterwards reset_parameters no longer recognizes the projector (isinstance on the wrapper fails), so a connector initialized after wrapping — the OLMoDDP train module's order — stays uninitialized. The 20-step bridge check showed it directly: connector output RMS 0 and a step-1 grad norm of 5e3 with checkpointing on, versus CE 2.803 / grad norm 3.4 with it off (identical to the earlier smoke). The recipe therefore sets connector_activation_checkpointing=False; the connector's activations are a negligible share of memory (97 of 268 GiB used). Rustin's #869 had worked around this by rewriting the connector's checkpointing in shared vision code, which this stack does not carry.

Removed in the restructure (2026-10-02)

Dead code: collator/loader text_only option; load_molmo2_hf_vision_state_dict (HF shard downloader) and MultimodalOLMoDDPTrainModule.load_molmo2_vision_state_dict (the recipe initializes vision from SigLIP). Tests: 77 functions (exhaustive parametrizations cut to one representative case, validation-only/error-message tests, launch/pipeline plumbing, duplicate variants, logging-only diagnostics); the full list is in the PR discussion on request. The bridge dry-run config is identical to the pre-restructure head except the removed text_only field.

Tests

OLMo 3.5 support:

  • recipe suites (vision_alignment_olmo35_test.py new, vision_alignment_{,bridge_,joint_}test.py updated): 135 passed
  • multimodal_document_mode_test.py: 8 CPU tests + 1 GPU KDA isolation test
  • broader CPU suite (internal, nn/vision, train_module/transformer, train/callbacks): 556 passed, 13 skipped
  • ruff / black / isort clean; mypy: no new errors (62 pre-existing repo-wide on the base too)

Multimodal layer (after the restructure): the kept suites pass on this branch — 278 passed, 30 skipped (CPU); the perception/joint and evaluation-suite tests moved to #903 (470 passed, 8 skipped there); the infrastructure tests moved to #902 (513 passed, 32 skipped, 1 pre-existing parity_test::test_clip_parity failure that also fails on vision)

  • ruff / black / isort clean; mypy adds no errors in the changed files
  • Multi-GPU tests (multimodal_ddp_train_module_test.py) updated for the EP limitation; not run locally (no multi-GPU box)

🤖 Generated with Claude Code

@jason718
jason718 force-pushed the jasonr/native-olmo-ddp-runtime-on-vision branch from 80d401a to cc7696c Compare September 30, 2026 04:19
@jason718 jason718 self-assigned this Sep 30, 2026
@jason718
jason718 force-pushed the jasonr/native-vision-alignment-on-886 branch from dca7517 to e5d5711 Compare October 1, 2026 02:39
@jason718 jason718 changed the title Integrate native three-stage vision alignment (#869 rebased onto #886) Vision alignment for OLMoDDP as a multimodal-only layer on the #886 hooks (replaces the #869 copy) Oct 1, 2026
@jason718
jason718 force-pushed the jasonr/native-olmo-ddp-runtime-on-vision branch from cc7696c to 299e442 Compare October 1, 2026 17:45
@jason718
jason718 force-pushed the jasonr/native-vision-alignment-on-886 branch from 1b2e506 to 9c511db Compare October 1, 2026 17:45
@jason718 jason718 changed the title Vision alignment for OLMoDDP as a multimodal-only layer on the #886 hooks (replaces the #869 copy) Vision alignment for OLMoDDP on OLMo 3.5 as a multimodal-only layer on the #886 hooks (replaces the #869 copy) Oct 2, 2026

@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: 5878dcf3f8

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

invalid_special_ids = set(tokenizer.all_special_ids) - {tokenizer.eos_token_id}
for part in module.model_parts:
part.eval()
with torch.compiler.set_stance("force_eager"), module._multimodal_eval_batch_context():

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 Call the train module's evaluation context

When vision_decoded.run() reaches this decoding path, module is a MultimodalOLMoDDPTrainModule, which exposes _eval_batch_context() but has no _multimodal_eval_batch_context() method. The first real decoded batch therefore raises AttributeError before image encoding, so decoded-panel evaluation cannot run; use the existing evaluation context (as vision_academic does) or provide the intended alias.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Not in this PR any more: multimodal_decoding.py moved to #903. Fixed there in c695ac4 (the decoded path now calls _eval_batch_context()).

@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: ef8a2050b5

ℹ️ 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 +126 to +131
extend = _PHASE_SOURCE_EXTENSIONS.get(phase)
if extend is None:
raise ValueError(
f"Visual sources for the {phase!r} phase are provided by the alignment phases layer "
"(olmo_core.internal.vision_alignment_phases); import it to register them."
)

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 Register the perception and joint source builders

Selecting either --recipe.phase=perception or joint always reaches this branch, but _PHASE_SOURCE_EXTENSIONS is never populated in this checkout: a repo-wide search finds neither olmo_core.internal.vision_alignment_phases nor any call to register_phase_sources(). Consequently build_config() raises this ValueError before either later phase can construct its training or validation datasets, so the advertised three-stage recipe cannot advance beyond bridge.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

By design: this PR is bridge only. The perception and joint source builders register through register_phase_sources() in #903. The guide that advertised all three phases moved to #903 as well (35c4b76).

Comment thread src/scripts/train/Vision-Align.py Outdated
Comment on lines +9 to +10
if __name__ == "__main__":
main(config_builder=build_config)

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 Add the all-stage launcher described by the recipe

For the documented default commands that omit --recipe.phase, this entrypoint invokes the generic single-config runner and VisionAlignmentRecipeConfig.phase defaults to bridge, so it can only launch the bridge phase. A repo-wide search finds no vision_alignment_pipeline implementation or other dispatcher that could create the perception/joint jobs and their handoffs; therefore the advertised default three-stage launch silently stops after bridge.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 35c4b76: Vision-Align.py here documents a single phase (default bridge); the all-stage launcher and its guide are in #903.

Comment thread docs/source/guides/vision_alignment.md Outdated

### Checkpoint benchmarks

`src/scripts/eval/Vision-Align.py` provides three independent runners. Each uses one

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 Provide the documented checkpoint-evaluation runner

Every benchmark command in this new guide invokes src/scripts/eval/Vision-Align.py, but a repo-wide search of src/ finds no scripts/eval directory or alternate Vision-Align evaluation entrypoint. Users following the documented fast-text, decoded, or academic evaluation commands will therefore fail before loading a checkpoint; add the runner or remove these unusable commands.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 35c4b76: the guide (including the evaluation runner commands) moved to #903, where src/scripts/eval/Vision-Align.py exists.

@jason718
jason718 force-pushed the jasonr/native-olmo-ddp-runtime-on-vision branch from 2cc6777 to eae829e Compare October 2, 2026 17:55
@jason718
jason718 force-pushed the jasonr/native-vision-alignment-on-886 branch from ef8a205 to d2f9cde Compare October 2, 2026 17:55

@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: 25fc07fe7b

ℹ️ 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 +1330 to +1331
with torch.enable_grad():
output = self.model_forward_no_pipeline(

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 Run multimodal evals in the evaluation context

When compile_model=True (the recipe's normal configuration), this multimodal path bypasses _eval_batch_context() and enters only torch.enable_grad(). It therefore misses the torch.compiler.set_stance("force_eager") guard that was added for evaluation; startup and periodic image evaluation can instead compile/recompile the variable-shape validation forward (or hit the known compiled-eval behavior) rather than using the safe eager path. Wrap this forward in _eval_batch_context() as the text-only path does.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 35c4b76: the multimodal eval forward now runs inside _eval_batch_context() (grad enabled, force_eager).

@jason718
jason718 force-pushed the jasonr/native-olmo-ddp-runtime-on-vision branch from eae829e to df9e404 Compare October 2, 2026 22:12
@jason718
jason718 force-pushed the jasonr/native-vision-alignment-on-886 branch from 25fc07f to 3879dcb Compare October 2, 2026 22:12

@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: 3879dcbe5a

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

AlignmentPhase.bridge: _PhaseDefaults(
microbatch_instances=4,
steps=500,
freeze_params=("vision.*", "lm.embedding_norm.*", "lm.blocks.*", "lm.lm_head.*"),

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 Keep expert parameters checkpointable in frozen phases

When bridge (and likewise perception) is run with expert parallelism enabled—the legacy fallback config sets ep_config to degree 8—this pattern freezes every routed-expert parameter. The multimodal checkpoint writer then explicitly raises NotImplementedError for frozen *.routed_experts.* tensors under EP, so the first ephemeral checkpoint at step 50 aborts the phase and no handoff checkpoint can be produced. Either do not freeze EP expert weights or make their checkpointing supported before enabling this phase configuration.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Known limitation, documented in the CHANGELOG entry: this layer does not checkpoint frozen routed experts under EP. The OLMo 3.5 path inherits the text team's runtime, which has no EP (ep_config=None), so bridge and perception checkpoint normally. Only the legacy no-text_config fallback (s002, EP8) hits it; changing that fallback's defaults is left for a follow-up.

Comment thread docs/source/guides/vision_alignment.md Outdated
Comment on lines +296 to +297
src/test/internal/vision_alignment_perception_test.py \
src/test/internal/vision_alignment_joint_test.py \

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 Point the focused-test command at existing tests

The documented focused-test command names vision_alignment_perception_test.py and vision_alignment_joint_test.py, but neither file exists in this commit (only bridge, generic, and OLMo 3.5 alignment tests were added). Running the provided command therefore exits with pytest's file-not-found error before executing the valid test paths; replace these entries with existing tests or add the missing test files.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 35c4b76: the guide moved to #903, where those test files exist.

@jason718
jason718 force-pushed the jasonr/native-olmo-ddp-runtime-on-vision branch from df9e404 to 5b6775e Compare October 3, 2026 03:28
@jason718
jason718 force-pushed the jasonr/native-vision-alignment-on-886 branch from 3879dcb to c03e24b Compare October 3, 2026 03:28

@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: c03e24ba7b

ℹ️ 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 +320 to +321
for name in ("d_model", "n_layers", "vocab_size", "tie_word_embeddings"):
if getattr(lm, name) != getattr(pretrained, name):

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 Validate the full inherited LM topology

When recipe.text_config has the same four checked scalar fields but changes a shape-compatible functional setting such as attention head count, RoPE configuration, or router behavior, this check succeeds and _build_model() uses that altered config while the initialization callback loads the pretraining weights. Many of these changes do not alter tensor shapes, so the checkpoint load can succeed while training a semantically different LM from the claimed pretraining checkpoint; compare the complete learned-model topology/configuration (excluding only deliberately allowed execution settings) before accepting the text config.

Useful? React with 👍 / 👎.

@jason718 jason718 Oct 5, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Agreed this is worth hardening. Here recipe.text_config is the text team's resolved mid-training config for the same model. Diffed against the 14T checkpoint's model config, the only differences are execution or intended settings: EMO routing cleared (as text mid-training does), the KDA kernel flag renamed (use_cute_kernel → use_experimental_kernels) and init_seed; no topology field differs. A full-topology check needs an allow-list of exactly those settings, so I'll do it as a follow-up rather than in this PR.

jason718 added a commit that referenced this pull request Oct 3, 2026
#889 carries only the bridge-validated single-phase recipe, so its Vision-Align.py calls the
standard experiment main. This PR adds the pipeline controller, but the script was not
switched back, so a launch without --recipe.phase trained only the default bridge phase
instead of bridge -> perception -> joint as the guide documents. Restore RustinS's entry
point (vision_alignment_pipeline.main), which also handles an explicit --recipe.phase.
@jason718
jason718 force-pushed the jasonr/native-olmo-ddp-runtime-on-vision branch from 5b6775e to cedefb4 Compare October 5, 2026 18:26
@jason718
jason718 force-pushed the jasonr/native-vision-alignment-on-886 branch from c03e24b to 687795a Compare October 5, 2026 18:26
jason718 added a commit that referenced this pull request Oct 5, 2026
#889 carries only the bridge-validated single-phase recipe, so its Vision-Align.py calls the
standard experiment main. This PR adds the pipeline controller, but the script was not
switched back, so a launch without --recipe.phase trained only the default bridge phase
instead of bridge -> perception -> joint as the guide documents. Restore RustinS's entry
point (vision_alignment_pipeline.main), which also handles an explicit --recipe.phase.
@jason718
jason718 force-pushed the jasonr/native-olmo-ddp-runtime-on-vision branch from cedefb4 to 8d8fa9b Compare October 5, 2026 19:44
@jason718
jason718 force-pushed the jasonr/native-vision-alignment-on-886 branch from 687795a to a824cc4 Compare October 5, 2026 19:44
Base automatically changed from jasonr/native-olmo-ddp-runtime-on-vision to vision October 5, 2026 19:44
…ster sync

The alignment phases clip connector, vision and LM gradients per scheduler group (their
gradients are on different scales), report per-component gradient norms, cap the foreach
chunk size for memory, and synchronize fp32 masters for only the parameters a component
load touched. All of it lives in this subclass; OLMoDDPOptimizer is unchanged.
A MultimodalLM around an OLMoDDPModel that opts into OLMoDDPTrainModule through the #886
hooks: embeddings go in through `input_embeddings`, router auxiliary losses get their own
divisor, apply_dp wraps the whole model, and the weighted response-only loss (plus the LM's
z-loss) is computed from the response logits. Text-only batches defer to the LM's plain loss.
For recurrent LMs (Kimi Delta Attention) packed examples are isolated through document
boundaries derived from example_ids instead of attention masks; pixels are cast to the vision
tower's dtype. The router token mask of #868 is not carried (documented).
MultimodalMixtureConfig (sources, loss-mass targets, calibrated mean loss weights,
image-disjoint selections), PretrainingReplayDataset (the parent checkpoint's own text data
with its sidecar masks, plus the metadata filter for zero-allocation paths), and the
weighted multimodal LM evaluator with blank/matched/wrong-image controls.
The train module uses the #886 hooks for per-batch auxiliary-loss divisors, native-text
checkpoint key aliasing, frozen-parameter save/restore, fresh-component deferral on
masters-only loads and Q/K-gain expansion; frozen expert weights under expert parallelism are
not supported (the recipe runs EP1). Callbacks: component initialization (SigLIP tower,
image-token rows), W&B auto-resume, Beaker config on resumed runs, metric overwrite,
evaluator dedupe, permanent-checkpoint retention, and the multimodal evaluator config.
…herited

Bridge, perception and joint phases through the standard experiment runner. With
recipe.text_config the LM config, optimizer, train-module, trainer, data-loader and launch
settings come from the text team's resolved mid-training config and a single
MULTIMODAL_OVERRIDES table lists what the phases change (a unit test asserts the differing
keys equal the table); without it the checkpoint's config is read through the legacy
normalizer with EMO cleared. Document mode keeps KDA on the fla kernels (kernel_fun rejects
cu_seqlens). Perception/joint visual sources are registered by the phases layer, so the
bridge path imports none of their data adapters.
…d load SigLIP through vision's converter

The recipe no longer reads Molmo2-4B's config from the Hugging Face Hub (the molmo2_model_id /
molmo2_revision fields are gone) and the initialization callback uses
transformers.SiglipVisionModel + siglip_state_dict_to_vision_encoder, as Molmo2-Stage1.py does,
instead of a second SigLIP loader.
…recipe

VisionConnector.apply_activation_checkpointing wraps the pooling and projector modules in
checkpoint_wrapper, after which reset_parameters no longer recognizes the projector, so a
connector initialized after wrapping (the OLMoDDP train module's order) stays uninitialized:
the bridge check showed connector output RMS 0 and a step-1 grad norm of 5e3. The connector's
activations are a negligible share of memory, so checkpointing them buys nothing here.
@jason718
jason718 force-pushed the jasonr/native-vision-alignment-on-886 branch from a824cc4 to 53cac6f Compare October 5, 2026 19:45
jason718 added a commit that referenced this pull request Oct 5, 2026
# Conflicts:
#	CHANGELOG.md

@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: 35c4b76b2f

ℹ️ 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 +420 to +422
model = MultimodalLMConfig.molmo2_vision_stack(
lm, image_patch_token_id=token_ids.im_patch_id
)

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 Select a mask-capable attention backend for multimodal batches

For an attention-only OLMoDDP checkpoint whose inherited blocks use FlashAttention (the standard OLMo configs default to flash_2), this preserves that backend even though every collated multimodal batch supplies token_type_ids and the wrapper passes a non-null or_mask. Attention.sdpa() rejects that mask on Flash backends, so the first bridge forward raises NotImplementedError rather than training. Convert such inherited attention blocks to torch/flex, or reject unsupported checkpoint topologies during config construction.

Useful? React with 👍 / 👎.

@jason718
jason718 merged commit 2462972 into vision Oct 5, 2026
1 check passed
@jason718
jason718 deleted the jasonr/native-vision-alignment-on-886 branch October 5, 2026 21:22
jason718 added a commit that referenced this pull request Oct 21, 2026
…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.
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