Repository navigation
Add opt-in Core interfaces for RL training and weight publication - #888
Conversation
fb59c61 to
ac500c5
Compare
52db1a4 to
4f00ddc
Compare
There was a problem hiding this comment.
💡 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".
|
@codex review |
|
Codex Review: Didn't find any major issues. Can't wait for the next one! Reviewed commit: ℹ️ About Codex in GitHubCodex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
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". |
1763fe2 to
7e97bc4
Compare
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.
7e97bc4 to
7313088
Compare
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 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".
|
Found one correctness issue in PR head [P1] Preserve HF RoPE parameters when building the model — olmo3.py:212–217. The builder reads only top-level 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.0Weights 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, Please resolve RoPE parameters for each layer type, preserve their theta, and reject unsupported scaling explicitly. Regression coverage should include both the flat 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. |
|
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. |
## 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]>
## 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]>
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
default: Falsedefault: Falsedefault: "static""dynamic"to reuse expert activation kernels across token capacities. This reduces recompilation when RL batch shapes vary.default: "executed""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.Enabled by: explicit API callmiles.use_rollout_routing_replay=true.Enabled by: explicit API callbias_gammabalancing.default: FalseCheckpoint 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>.default: Nonedefault: Falsedefault: TrueFalseto spread replicated-tensor writes across ranks. This avoids concentrating checkpoint work on the lowest rank.default: Falsedefault: FalseThe 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.
Enabled by: explicit API callcore.stream_moe_export.default: Falsecore.expert_publication="fused"; it is not an HF checkpoint layout.default: FalseHF-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_configremains the model-to-HF config builder.default: bfloat16default: flash_4core.attention_backend, including Torch for compatibility checks.default: defaultdefault: sync_1ddefault: 1.25default: NoneNonedisables it. MILES supplies this to discourage uneven expert usage.default: NoneNonedisables it. MILES supplies this to stabilize router logits during training.default: 2026Commit review guide
Each link opens the diff for one functional commit, including its fixes and tests.
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
mainexactly 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:
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.