Skip to content

Add opt-in Core interfaces for RL training and weight publication - #888

Merged
no0p merged 10 commits into
mainfrom
robertb/miles-fp32-head
Oct 22, 2026
Merged

no0p merged 10 commits into
mainfrom
robertb/miles-fp32-head

Conversation

@no0p

@no0p no0p commented Sep 27, 2026 •

Copy link
Copy Markdown
Contributor

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
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
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
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
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
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
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
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
default: None
Request multiple writer processes instead of the existing thread pool. This exposes the existing process-based writer through direct save.
compact_storage
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
default: True
Set False to spread replicated-tensor writes across ranks. This avoids concentrating checkpoint work on the lowest rank.
constant_memory_planning
default: False
Build supported contiguous shard metadata without large temporary allocations. This reduces memory pressure during checkpoint save and restore.
profile
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
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
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
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 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
default: bfloat16
Choose parameter precision for the imported model. MILES uses BF16 to fit training alongside rollout workers.
attention_backend
default: flash_4
Choose attention kernels for the target hardware. MILES forwards core.attention_backend, including Torch for compatibility checks.
attention_type
default: default
Choose ordinary or fused-v2 attention projections. This allows an imported model to use the corresponding Core implementation.
ep_path
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
default: 1.25
Size expert-parallel dispatch capacity. This controls the memory reserved to accommodate uneven expert loads.
router_aux_loss_weight
default: None
Set the expert load-balancing loss coefficient; None disables it. MILES supplies this to discourage uneven expert usage.
router_z_loss_weight
default: None
Set the router logit regularization coefficient; None disables it. MILES supplies this to stabilize router logits during training.
init_seed
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 Opt-in projection, mixed-precision gradients, autocast and numerical tests.
SwiGLU scoring options Intermediate rounding and dynamic row specialization, with default-path and numerical tests.
Router replay Scoped route replay and current-policy balancing counts, with dispatch and gradient tests.
Custom objectives Caller-supplied losses, microbatch contexts and train/eval mode handling, with integration tests.
Checkpoint controls Writer and planner options, profiling isolation and save-failure recovery, with checkpoint tests.
HF construction and publication OLMo3 MoE configuration, shared HF conversion, streaming exports and distributed round-trip tests.
Review feedback corrections Device-aware checkpoint profiling and opt-in auxiliary-metric cleanup, with CPU round-trip, failure-cleanup and gradient-parity tests.
RoPE import review fix Addresses Akshita's RoPE finding: 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 with focused tests for the rebased branch. Default compatibility, GPU numerics, checkpoint recovery and weight publication pass.

  • RoPE import review fix: 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, including all nine GPU jobs, CPU tests, Ruff, Black/isort, full mypy, docs and build. CI is rerunning for the rebased branch.

Runs:

  1. Default compatibility and GPU contracts.
  2. Four-update training/save/export.
  3. Fresh-process checkpoint resume.
  4. Pinned-runtime contracts.

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). 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.

@no0p
no0p force-pushed the robertb/miles-fp32-head branch from fb59c61 to ac500c5 Compare September 30, 2026 05:22
@no0p no0p changed the title Add opt-in Core interfaces for MILES RL training and weight publication Add opt-in Core interfaces for RL training and weight publication Sep 30, 2026
@no0p
no0p force-pushed the robertb/miles-fp32-head branch 5 times, most recently from 52db1a4 to 4f00ddc Compare October 1, 2026 17:08
@no0p
no0p marked this pull request as ready for review October 1, 2026 18:10

@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: 4f00ddcb47

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

@no0p

no0p commented Oct 1, 2026

Copy link
Copy Markdown
Contributor Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Can't wait for the next one!

Reviewed commit: 1763fe2dc2

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

@no0p
no0p force-pushed the robertb/miles-fp32-head branch from 1763fe2 to 7e97bc4 Compare October 4, 2026 19:09
no0p added 7 commits October 21, 2026 15:49
Retain FP32 logits with low-precision GEMMs and ordinary mixed-precision first-order gradients. Keep fp32_output disabled by default; test CUDA/autocast gradients against nn.Linear and restore TF32 settings after tests.
Preserve the existing static fused kernel by default. Add explicit intermediate-rounding and dynamic-row options with boundary, numerical, randomized dtype and existing-call compatibility coverage.
Replay selected experts through a scoped API and optionally compute balancing counts from current-policy choices. Preserve dispatch counts by default and reject unsupported combinations; test dispatch, gradients, recomputation and call compatibility.
Add explicit loss-callback APIs for both train modules, including per-microbatch contexts for replay. Keep the model-mode cache synchronized and test accumulation, replay restoration, and evaluation after successful or failed objectives.
…failure

Expose compact storage, process writers, bounded planning, write distribution and profiling while preserving default save/load policies. Restore live optimizer storage on exceptional saves; cover round trips, EP resharding, default profiling isolation and existing calls.
Reuse the existing HF config builder and weight conversions for native model construction and full or streaming export. Share expert gathering and fused-QKV splitting; test hybrid layouts, exact weight round trips, distributed gathering and attention metadata compatibility. Document the new interfaces in the changelog.
@no0p
no0p force-pushed the robertb/miles-fp32-head branch from 7e97bc4 to 7313088 Compare October 21, 2026 22:52
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 21, 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-22T21:51:22.179971Z 97aea6a New commits
ℹ️ 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.

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

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

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

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/olmo_core/nn/moe/v2/olmo3.py Resolved
Comment thread src/olmo_core/nn/moe/v2/olmo3.py Resolved
@AkshitaB

Copy link
Copy Markdown
Contributor

Found one correctness issue in PR head 55c944c:

[P1] Preserve HF RoPE parameters when building the model — olmo3.py:212–217.

The builder reads only top-level rope_theta, while the HF model uses rope_parameters. I reproduced this with:

hf = Olmo3MoeConfig(
    use_head_qk_norm=True,
    layer_types=["full_attention"],
    num_hidden_layers=1,
    dense_layers_indices=[],
    rope_parameters={"rope_type": "default", "rope_theta": 500000.0},
)
core = build_olmo3_moe_config_from_hf_config(hf)
print(hf.rope_parameters["rope_theta"])  # 500000.0
print(core.block.sequence_mixer.rope.theta)  # 10000.0

Weights can load successfully, but attention behavior silently changes. Nested per-layer scaled-RoPE configurations also bypass the unsupported-scaling check at lines 81–83: for example, rope_parameters={"full_attention": {"rope_type": "linear", "factor": 2.0, "rope_theta": 500000.0}} is accepted and produces ordinary, unscaled RoPE with theta 10000.

Please resolve RoPE parameters for each layer type, preserve their theta, and reject unsupported scaling explicitly. Regression coverage should include both the flat rope_parameters form and nested per-layer settings.

Validation on this head: 91 focused tests passed, 22 skipped. One distributed test was blocked by local sandbox socket permissions; GPU behavior was not verified.

no0p commented Oct 22, 2026

Copy link
Copy Markdown
Contributor Author

Note

Drafted by Codex.

Addressed in 0117c4fc4. The importer now preserves flat and per-layer RoPE settings, maps supported scaling configurations to Core’s existing implementations, and explicitly rejects unsupported settings.

Added 121 passing regression tests covering config mapping, validation, and numerical comparisons. GPU RoPE-buffer comparisons also passed. This changes the importer only; the exporter and underlying RoPE implementations are unchanged.

@no0p
no0p merged commit 6ceda65 into main Oct 22, 2026
24 of 25 checks passed
@no0p
no0p deleted the robertb/miles-fp32-head branch October 22, 2026 22:12
no0p added a commit that referenced this pull request Nov 9, 2026
## What this changes

The three valid-prefix SwiGLU Triton kernels in
`olmo_core/kernels/swiglu.py` (static forward, dynamic-row forward, and
backward) compute memory offsets as `row_idx * stride + col_idx`. All
three did that multiplication in signed 32-bit integers. This change
widens the row and column indices to int64 **before** the multiply, in
all three kernels. It changes no rounding, filtering, or thresholds, and
adds regression tests that cross the 32-bit boundary.

## Background for readers outside the RL work

Inside each MoE expert, the layer computes a SwiGLU activation over a
buffer with one row per (token, expert) pair and `2 * hidden` columns.
OLMo-core has two implementations of that activation. Gradient-enabled
forwards use plain PyTorch (`up * F.silu(gate)`). Forwards with
gradients off use `swiglu_valid_prefix`, a fused Triton kernel added
with the fused MoE stack in #844, which does the same math in one memory
pass and can skip padded rows.

A 32-bit signed integer holds values up to 2,147,483,647. The kernel's
offset for row `r` is `r * 2048` when the expert hidden size is 1024, so
it overflows once `r` reaches 1,048,576. Past that row the offset wraps
negative and the kernel reads its inputs from, and writes its outputs
to, memory about 4 GB below the buffer. The result is wrong values for
those rows and silent writes into whatever tensor lives at the wrapped
address. The row count and the stride each fit comfortably in int32;
only their product does not, which is why nothing in the wrapper's
validation caught it.

**Why it surfaced now.** The rows a GPU handles per layer are roughly
its tokens times the experts per token. With 16 experts per token, a
65,536-token packed sequence is 1,048,576 rows, exactly the boundary.
MILES RL training recently raised its packing limit from 34,816 to
65,536 tokens to fit long-prompt datasets, and the MILES scoring pass
runs with gradients off, so it was the first workload to take this
kernel across the line. Pretraining never reaches the kernel because it
always runs with gradients on. The MILES scoring consistency check,
which compares the no-gradient scoring forward against the
gradient-enabled training forward on identical tokens, is what noticed
the disagreement.

## Evidence

Offline compilation confirms an i32 multiply followed by signed pointer
widening. A one-GPU reproducer confirms exact agreement below the
boundary and wrong values beginning exactly at it:

| Case | Pinned kernel | Patched kernel |
|---|---:|---:|
| 1,044,480 rows, hidden 1,024 | 0 mismatching rows | 0 |
| 1,052,672 rows, hidden 1,024 | 4,096 mismatching rows, starting at
1,048,576 | 0 |

Both static and dynamic variants have the same result. The reproducer
uses a controlled sentinel prefix inside its own allocation, so wrapped
reads remain mapped and cannot depend on unrelated allocations. All 46
tests in the targeted SwiGLU suite pass on one A100, including new
large-offset forward/backward regressions; CPU execution passes 6 with
40 GPU skips. Black, isort, Ruff, and diff checks pass.

**Performance.** The widening has no measurable cost. On one A100-80GB
at hidden 1024, bf16, median of 50 launches, the patched kernel is
within +2% / −3% of the pinned kernel at 131K, 524K, and 1,044K rows for
both variants, inside run-to-run noise; all variants move about 1.7
TB/s, so the kernel is memory-bound and the extra index arithmetic hides
behind the loads. Outputs are bit-identical to the pinned kernel and to
eager at every shape.

Runs:

1. Boundary reproduction, patched comparison, and targeted GPU suite:
[Beaker](https://beaker.org/ex/01M6VRJVFEXM5QAM40RD4C58S0). Results
dataset: `01M6VRJVFPXDG9F7525MMBRQ8W`; diagnostic source bundle:
`01M6VRJ8K2AV60DYNSRHF0FRC2`.
2. Pinned vs patched kernel timing, plus eager reference:
[Beaker](https://beaker.org/ex/01M6VVM7200Y9GY6M5T6G69JSZ).

## Scope and what remains

- The static kernels originate in #844; #888 added the dynamic-row
forward variant with the same arithmetic. Both current main and the
runtime's pinned Core revision contain the bug.
- This PR fixes the kernel for every caller. The companion #951 is a
separate design change that lets RL scoring run the eager activation
under no-grad so its consistency check no longer depends on two
implementations matching. Both are needed: this one because the kernel
corrupts memory for anyone who uses it at scale, that one because a
correctness check should not rest on kernel parity.
- The large-pack B300 model-level validation remains pending; this PR
establishes the kernel defect and fix without yet claiming it explains
every observed model-level discrepancy.
- The adjacent legacy MoE and MXFP8 kernels also contain offset
expressions needing separate large-buffer validation; they are not
changed in this narrowly scoped fix.

---------

Co-authored-by: Claude Fable 5.1 <[email protected]>
no0p added a commit that referenced this pull request Nov 10, 2026
## What this changes

Adds one option to the routed-expert MoE layer:
`RoutedExpertsConfig.fused_no_grad_activation` (default `True`, so
nothing changes unless a caller opts in). Setting it to `False` makes
the expert activation under `torch.no_grad()` use the same eager PyTorch
expression as training, `up * F.silu(gate)`, instead of the fused Triton
kernel that the layer currently selects whenever gradients are off.

## Background for readers outside the RL work

Inside each MoE expert, the layer computes a SwiGLU activation.
OLMo-core has two implementations of it:

- **Eager** (`up * F.silu(gate)`): plain PyTorch ops. This is what every
gradient-enabled forward uses, so it is the arithmetic that training
actually sees.
- **Fused valid-prefix kernel** (`swiglu_valid_prefix`): a Triton kernel
introduced with the fused MoE stack in #844. It does the same math in
one pass over memory and can skip padded rows. It has no autograd rule,
so the layer only picks it when gradients are disabled.

For pretraining this distinction never matters: training always runs
with gradients on, and the fused kernel is only taken on forward-only
paths.

RL post-training (MILES) is different. Each update needs the "before the
update" log-probabilities of the sampled tokens, which the loss uses as
the denominator of its importance ratio. The straightforward way to get
them is a dedicated forward pass with gradients off, run before the
training forward. MILES takes a shortcut when there is exactly one
optimizer step per batch: the weights have not changed yet, so it reuses
the training forward's own log-probabilities and skips the separate
pass. To make sure that shortcut is valid, it periodically runs both
passes on the same tokens and expert routes and requires them to agree.
Today those two forwards take different activation code. They agree only
because #888 added a `match_eager_rounding` flag that makes the fused
kernel round the way eager does. A kernel defect found this week (#950)
showed how fragile that is: the two paths disagreed, and the scoring
check was the only thing that noticed.

With this option, the scoring forward and the training forward run
identical ops, so their agreement holds by construction rather than by
careful kernel matching. The consistency check then only has to catch
non-determinism or memory corruption, which is what it is good at.

## Scope

- Existing callers keep the fused default. Explicit FP8 and wave-kernel
callers are unaffected.
- Eager computes all capacity rows rather than only the valid prefix,
and materializes one intermediate the size of the activation. In the RL
scoring pass, which runs once per process in the default configuration,
that is a few milliseconds. Workloads that score every update should
measure.
- This is a separate design change from the pointer-overflow repair in
#950. #950 fixes a bug in the fused kernel for everyone who uses it;
this PR lets RL scoring stop depending on that kernel at all. Both
remain necessary.

## Validation

Tests cover config serialization, fused/eager dispatch under both grad
modes, exact eager output, and unchanged gradients. CPU validation: 7
passed, 39 GPU cases skipped across the new and existing SwiGLU suites;
Black/isort/Ruff pass. GPU dispatch and large-pack model validation are
pending in the MILES integration smoke. No runtime performance estimate
is claimed.

---------

Co-authored-by: Claude Fable 5.1 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants