Repository navigation
Add the OLMoDDP fused MoE / expert-parallel training stack - #844
Conversation
The MoE stack is being landed incrementally as small PRs into this long-lived integration branch (kept in sync with main). Add akshitab/moe-v2-core to the Main workflow's pull_request and push branch filters so those PRs get the same lint / test / type-check / build / GPU CI as PRs into main. Temporary: to be removed before akshitab/moe-v2-core is merged into main. (pr_checks.yml's CHANGELOG gate is intentionally left main-only — the feature gets a single CHANGELOG entry when the integration branch lands on main.) Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
## What this adds `olmo_core.kernels.cuda_extension_utils` — a generic just-in-time loader (`load_cuda_extension`) for CUDA/C++ extensions built via `torch.utils.cpp_extension`, with: - **arch/ABI-tagged build directories**, so a cached build isn't reused across an incompatible torch/CUDA/arch toolchain; - **cross-process build-lock handling**, so concurrent ranks don't clobber each other's builds. ## Import-safety / testing Pure-Python and import-safe on CPU — the `cpp_extension` import is lazy, so importing the module needs neither a GPU nor a compiler. Includes `cuda_extension_utils_test.py`, a CPU unit test for the pure-Python helpers (env parsing, arch/ABI tag construction, lock handling). The actual extension build is exercised by GPU tests on hardware. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Tianhua Tao <[email protected]> Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
The MoE grouped-matmul wrapper calls torch.nn.functional.grouped_mm, which is not available in the previous GPU image's torch 2.9.1. Use the torch 2.10 image so the grouped_mm (and downstream FP8) GPU tests can run. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
This reverts commit af1f36f.
The MoE kernels require torch >= 2.10: the grouped-matmul wrapper uses torch.nn.functional.grouped_mm, and the FP8 path reads F.ScalingType / F.SwizzleType at import time. Both are torch 2.10 APIs, so the GPU test image must be torch 2.10. (Supersedes the brief revert to the 2.9 image.) Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
… job The MoE kernels use torch >= 2.10 APIs (torch.nn.functional.grouped_mm, F.ScalingType/F.SwizzleType) and their tests are version-gated, so they skip on the torch 2.9 image. Keep the main GPU suite on torch 2.9 (the project's baseline) and add a dedicated torch 2.10 job that runs src/test/kernels/ so the gated MoE kernel tests actually execute. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
## What this adds `olmo_core.kernels.grouped_mm` — a thin wrapper over `torch.nn.functional.grouped_mm` (ragged/grouped matmul indexed by an `offs` tensor) that adds two caller-provided buffers: - **`out=`** — write the forward result in place into a preallocated tensor and return it. - **`input_grad_out=`** — write `grad(mat_a)` into a preallocated buffer during backward. These let callers reuse preallocated forward/backward buffers and avoid extra allocations in hot loops. Ships `cuda/grouped_mm_out.cpp` for the in-place output path, loaded lazily via `load_cuda_extension`, and exports `grouped_mm` from `olmo_core.kernels`. ## Import-safety / testing Pure-Python wrapper; the CUDA extension builds lazily on first use, so the module is import-safe on CPU (no GPU or compiler needed to import). Correctness is covered by GPU tests on hardware. --------- Co-authored-by: Tianhua Tao <[email protected]> Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
## What this adds
Makes `nvtx` (NVIDIA Tools Extension) an **optional** dependency instead
of a hard requirement. nvtx is only used to emit profiler ranges
(`@nvtx.annotate(...)`), so code shouldn't fail to import when it isn't
installed. This is setup for future use.
- New `profiling` extra in `pyproject.toml` (`pip install
ai2-olmo-core[profiling]`), also rolled into the `all` extra.
- New `olmo_core._nvtx` module exposing a no-op `nvtx` stand-in whose
`annotate` works as both a decorator and a context manager. Modules that
annotate hot paths import defensively:
```python
try:
import nvtx
except ImportError:
from olmo_core._nvtx import nvtx
```
so the annotations become no-ops when nvtx isn't installed.
## Testing
`src/test/nvtx_test.py` exercises the no-op shim as both a decorator and
a context manager. Pure-Python, CPU-only.
Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
## What this adds MXFP8 (OCP microscaling FP8) quantization support: - `olmo_core.kernels.mxfp8_utils` — Triton-backed quantize/dequantize to block-scaled FP8 (e4m3 data + e8m0 scales). - `OlmoMXFP8Tensor` (`olmo_core.kernels.mxfp8_tensor`) — a `torch.Tensor` subclass holding the quantized data + scales, with high-precision fallback dispatch for generic ops. Exported from `olmo_core.kernels` and marked `@beta_feature`. ## Import-safety / testing Triton is import-guarded and the dtypes used (`float8_e4m3fn`, `float8_e8m0fnu`) are available on the supported torch range, so the module imports on CPU without a GPU. `mxfp8_tensor_subclass_test.py` covers the roundtrip / fallback dispatch, gradient-object use, forward/backward edges, and torch.compile (the quant/dequant cases run on CPU; the inductor case is CUDA-gated). --------- Co-authored-by: Tianhua Tao <[email protected]> Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
## What this adds
The FP8 grouped-matmul compute path, built on MXFP8:
- **`scaled_grouped_mm_q` / `scaled_grouped_mm_q_fp8_weight`**
(`olmo_core.kernels.scaled_grouped_mm`) — MXFP8-quantized grouped matmul
on `torch.nn.functional.scaled_grouped_mm`, with prequantized-weight
caching (`prequantize_scaled_grouped_mm_rhs`,
`ScaledGroupedMMPrequantized{LHS,RHS}`).
- **`FP8WeightStore` / `FP8WeightCacheSpec`**
(`olmo_core.nn.fp8_weight`) — prequantizes a weight to its MXFP8 RHS
form (and the dgrad transpose) and caches it.
All public entry points are marked `@beta_feature`.
## torch version
This path uses `torch.nn.functional.grouped_mm` (backward) and
`F.ScalingType`/`F.SwizzleType` — torch 2.10 APIs. The module imports
safely on older torch (the enum constants fall back via `try/except`),
and the tests are version-gated (`has_torch_grouped_mm`) so they skip on
torch < 2.10 rather than erroring; CI exercises them on a torch 2.10 GPU
image. The autograd-plumbing tests stub the CUDA forward and run on CPU.
---------
Co-authored-by: Tianhua Tao <[email protected]>
Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
## What this adds CUDA + Triton/torch MoE token permute, reorder, and unpermute-backward kernels used to route tokens to experts and gather their outputs: - `kernels/moe_chunk_reorder.py` — chunked permute/unpermute by row-id map, with caller-provided `out=`/backward-grad buffers for comm-buffer reuse. - `kernels/moe_permute_drop.py` — fused permute-with-drop. - `kernels/moe_unpermute_bwd.py` — unpermute backward kernel. - `kernels/cuda/*` — the C++/CUDA sources, built lazily via the JIT extension loader. The Python wrappers are CPU-import-safe; the CUDA path builds lazily on first use. ## Testing - `src/test/kernels/moe_chunk_reorder_test.py` — CPU reference-path tests for the torch chunk permute/unpermute (out-of-range row zeroing, `out=` buffer honoring). - `src/test/kernels/moe_unpermute_bwd_test.py` — GPU test (`@requires_gpu`) checking the unpermute-backward kernel matches an autograd reference with an `out=` buffer. `make checks` passes; CPU tests pass locally; the GPU test skips cleanly without a GPU. --------- Co-authored-by: Tianhua Tao <[email protected]> Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
## What this adds
Symmetric-memory and NCCL-RMA point-to-point communication kernels used
for expert-parallel all-to-all and RMA-based transport:
- `kernels/symm_mem_vdev2d.py` +
`kernels/cuda/symm_mem_vdev2d{.cpp,_kernel.cu}` — a 2D virtual-device
symmetric-memory kernel, built ahead-of-time via CMake against NVSHMEM
(`build_symm_mem_vdev2d_ext.py` + `kernels/cuda/CMakeLists.txt`), loaded
lazily.
- `kernels/olmo_symm_mem.py` — symmetric-memory helpers built through
the JIT extension loader.
- `kernels/nccl_rma_p2p.py` + `kernels/cuda/nccl_rma_p2p.cpp` — NCCL RMA
put/signal/wait primitives, built through the JIT extension loader.
All Python wrappers are CPU-import-safe; the CUDA/NVSHMEM extensions
build lazily on first use. `nvtx` is used only for optional profiler
annotations, behind the no-op fallback.
## Testing
- `src/test/kernels/nccl_rma_p2p_test.py` — a 2-GPU test
(`@requires_multi_gpu`) that allocates an RMA window, does a
bidirectional `put_signal` / `wait_signal` exchange between two ranks,
and checks the received payloads. Skips cleanly when fewer than 2 GPUs
are present.
The symmetric-memory (`symm_mem_vdev2d`) path additionally requires a
multi-GPU NVSHMEM build and is exercised by hardware tests.
`make checks` passes; the test skips cleanly without multiple GPUs.
---------
Co-authored-by: Tianhua Tao <[email protected]>
Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
Adds `nn/moe/v2/checkpointing.py`: thread-local depth tracking for activation checkpointing. It reports whether execution is currently inside a checkpointed **forward** or a **recompute** (via re-entrant `checkpoint_forward_context` / `checkpoint_recompute_context` context managers), and exposes `get_rowwise_checkpoint_state()` returning `(checkpointing_active, save_for_recompute)` — so a checkpointed MoE forward can save outputs on the initial pass but avoid repeating metric side effects when it is recomputed in backward. Pure-Python (`threading` + `contextlib` + `torch`), no MoE/model coupling. Includes CPU unit tests covering the depth tracking (nesting + reset) and the save-on-forward / skip-on-recompute behavior. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Tianhua Tao <[email protected]> Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
# Conflicts: # .github/workflows/main.yml # CHANGELOG.md
Adds `nn/moe/utils.py`: the autograd-aware, `torch.compile`-safe wrapper layer over the MoE token permute / unpermute / chunk-reorder CUDA kernels (with optional Triton and TransformerEngine backends). These move tokens between the router's assignment order and the experts' grouped (per-expert-contiguous) order, in both forward and backward. Contents: - **Permute / unpermute with custom autograd** — including fused capacity-drop and row-id-map variants (`moe_permute_1d_fused_drop_no_compile`, `moe_unpermute_1d_fused_drop_no_compile`, `moe_reorder_rows_permutation`). - **Chunk reordering** for the grouped-expert layout, with TE / CUDA backend selection (`moe_chunk_reorder_no_compile`, `build_chunk_te_routing_map`). - Small `@torch.compiler.disable` stream/event sync helpers and eager kernel passthroughs. It depends only on the permute/reorder kernels already in `olmo_core.kernels` plus `olmo_core.utils.get_or_init_stream`; Triton and TransformerEngine are optional, guarded imports, so the module imports on CPU. Also includes a CPU test for the chunk-reorder torch reference paths (`_chunk_unpermute_torch` zeroing out-of-range rows; `_dispatch_permute_by_row_id_map` honoring an `out=` buffer). The fused permute/unpermute correctness tests are GPU + TransformerEngine gated and will follow. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Tianhua Tao <[email protected]> Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
Adds `nn/moe/v2/router.py`: `MoERouterV2` and `MoERouterConfigV2`, the mixture-of-experts router. Given hidden states `(B, S, d_model)` it: - computes per-token expert scores via softmax or sigmoid gating, - selects the top-k experts (with optional input jitter, expert-weight normalization, and the auxiliary-loss-free bias-balancing strategy), - returns the expert weights, expert indices, the per-expert token counts, and the inputs needed for the load-balancing / z-loss auxiliary losses (the losses themselves are reduced separately in `compute_aux_loss`). It depends only on existing pieces (`olmo_core.ops.moe`, `nn.moe.loss`, `nn.moe.router`, `olmo_core.config`/`distributed.utils`); `nvtx` is an optional import with the `olmo_core._nvtx` no-op fallback. The optional fp32-cast recompute path (which uses `OutputDiscardCheckpoint`, provided by a separate change) is disabled for now — the router falls back to a plain fp32 cast. Includes CPU unit tests covering the routing contract, the scores-only path, and top-1 / sigmoid gating. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Tianhua Tao <[email protected]> Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
The router tensor-parallel test (`test_router_tp_replicates_weight_and_runs`) was parametrized over both gloo and NCCL backends. The gloo variant runs in the CPU `Test` job, where `run_distributed_test`'s fork start method deadlocks inside the large test session (the job hangs and times out at 15m). Restrict the test to `@requires_multi_gpu` / NCCL, which runs in the multi-GPU lane and already passes — it provides the real `apply_tp` coverage. The CPU lane no longer exercises this distributed path. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
Adds `nn/moe/v2/shared_experts.py`: `SharedExperts` and `SharedExpertsConfig`. Shared experts act like a feed-forward applied to every token, but support more than one expert. The up/gate projections of all experts are column-packed into one weight so the first projection is a single GEMM `(BS, D) @ (D, E*2H)`; the result is split per-expert into up/gate, run through a SwiGLU nonlinearity, and the per-expert down projection is a grouped (batched) GEMM `(E, BS, H) x (E, H, D) -> (E, BS, D)`. A split `forward1`/`forward2` variant is provided so the projection and the down-GEMM can overlap with expert-parallel communication. Depends only on `olmo_core.config`; `nvtx` is an optional import with the `olmo_core._nvtx` no-op fallback. Includes CPU unit tests covering num_params, the forward output shape, the single-expert case, and that the split forward matches the fused one. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Tianhua Tao <[email protected]> Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
Adds the routed-expert MLP and the rowwise-FP8 config + machinery it builds on. - `routed_experts.py` — `RoutedExperts` / `RoutedExpertsConfig`: grouped-GEMM up/gate + per-expert down projection with SwiGLU, plus optional rowwise-FP8 expert weights (prequantized RHS caching, fp8-only-param weight stores). - `fp8.py` — `MoERowwiseFP8Config` (validation + runtime-support checks) and the cache-refresh/invalidation helpers used to keep prequantized FP8 weights in sync. `MoERowwiseFP8Config` is marked `@beta_feature`. Tests cover config validation/normalization, `RoutedExperts` construction and fp8-only weight-store gradient handling, the FP8 weight store, and the cache-refresh logic (via lightweight fakes). FP8/compute-capability paths are gated with `@requires_gpu`. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Tianhua Tao <[email protected]> Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
Adds the fused Mixture-of-Experts transformer block and model and wires them into the transformer build dispatch. ## What's added - **`MoEFusedV2TransformerBlock`** and **`MoEFusedV2Transformer`** — the fused MoE block and model. - **`no_ep.py`** — the no-expert-parallel forward dispatch (`combined_forward_no_ep`). - **`tbo_state.py`** — the two-batch-overlap pending-context dataclass. - **`fp8.py`** — the rowwise-FP8 block machinery (shared-expert prequant cache + forward helpers) added alongside the existing config. - **Transformer integration** — `moe_fused_v2` entries on `TransformerType` / `TransformerBlockType`, `MoEFusedV2TransformerConfig` (builds the model), the block-build dispatch, and `InitMethod.init_moe_v2` with the per-block init dispatch. ## Notes - The fused block consumes a single `layer_norm` config and builds identical attention and feed-forward norms from it. - The expert-parallel dispatch families (sync / no-sync VDev / no-sync rowwise) are imported lazily inside their wrapper methods, so this change imports and runs with only the no-EP path present. Those families land in follow-up changes. ## Testing `src/test/nn/moe/v2/block_no_ep_test.py`: - `test_v2_no_ep_module_names_importable` (CPU) - `test_v2_no_ep_forward_backward_smoke`, `test_v2_no_ep_apply_compile_forward_smoke` (GPU) — forced-router no-EP block forward/backward and compile. - `test_v2_transformer_config_builds_and_initializes` (GPU) — end-to-end config build + weight init. Existing tests in `src/test/nn/moe/v2/` continue to pass; `make checks` is clean. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
Adds `nn/moe/v2/comm.py`: the autograd-aware all-to-all dispatch/combine transport used by no-sync expert parallelism. It provides the dispatch/combine `torch.autograd.Function`s for two transports: - the symmetric-memory **VDev** path (`_DispatchVDevAutograd` / `_CombineVDevAutograd`), and - the **row-wise** path including row-wise **FP8** (`_DispatchRowwise*` / `_RowwiseCombineWeighted*`), built on the symmetric-memory and MXFP8 / scaled-grouped-mm kernels. Everything operates on plain tensors, process groups, and symmetric-memory buffers — there is no dependency on the MoE block or model. Depends only on `olmo_core.kernels.*` (already present) and torch; the kernel extensions load lazily, so the module imports on CPU. The all-to-all ops require multiple GPUs + symmetric memory to exercise, so correctness tests run on GPU hardware and are added with the GPU test pass. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Tianhua Tao <[email protected]> Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
Adds the shared helpers used by the no-sync expert-parallel forward paths. ## What's added `nn/moe/v2/ep_no_sync_common.py`: - **`build_keep_reorder`** — builds the per-expert capacity-drop reorder: stably partitions routed rows into kept-then-dropped, returning the permutation, its inverse, and a keep-mask. - **`sync_tail_drop_allowed_splits_single_a2a`** — agrees a global tail-drop policy across expert-parallel ranks with a single all-gather of per-rank requested token counts. - **`restore_drop_unpermute_1d`** — inverts the capacity drop (scatters kept expert outputs back, zero-filling dropped rows) and unpermutes + combines for the 1D no-sync path. These operate on plain tensors / a passed-in block; the EP forward families that consume them land in follow-up changes. ## Notes - The optional `nvtx` import uses the `_nvtx` fallback so the module imports without the profiling extra. - The dead env-gated debug helpers were trimmed to a single labeled hook + an `OLMO_TBO_VERBOSE_DEBUG_PRINT` note. ## Testing `src/test/nn/moe/v2/ep_no_sync_common_test.py` (CPU): validates `build_keep_reorder` against an independent reference (partial-drop, no-drop, full-drop-some-experts) and that the reorder/inverse permutations invert each other. `make checks` clean. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
Adds the symmetric-memory buffer machinery shared by the no-sync expert-parallel forward paths. ## What's added `nn/moe/v2/ep_no_sync_buffers.py`: - Symmetric-memory tensor allocation + caching (with leading-dim reuse). - The lease pool that hands out and recycles those buffers across forward passes, so the no-sync all-to-all can read/write peer memory without reallocating each step. - The per-block shared pool and the stage / pending-context state the two-batch-overlap path threads between micro-batches (bf16 and rowwise-FP8 variants). It operates on plain tensors / a passed-in block and depends only on `olmo_core.kernels.olmo_symm_mem` (+ torch); the EP forward families that consume it land in follow-up changes. ## Notes - Removed the dead env-gated debug instrumentation (every call site was commented out); a single note on the `OLMO_TBO_VERBOSE_DEBUG_PRINT` trace switch remains at the allocation site. - Added a module docstring; lowercase `tuple[...]` type hints per convention. ## Testing `src/test/nn/moe/v2/ep_no_sync_buffers_test.py` (CPU): buffer-reuse coverage, prefix-view aliasing, env parsing (incl. error case), and the rank-capacity formula. `make checks` clean. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
Adds the 1D (VDev) no-sync expert-parallel forward. ## What's added `nn/moe/v2/ep_no_sync_1d.py` — `combined_forward_ep_no_sync_1d`: dispatches each token to its expert-owning rank over the symmetric-memory variable-length all-to-all (`_DispatchVDevAutograd`), runs the routed experts on the received tokens, and combines the results back (`_CombineVDevAutograd`), using the buffer-lease pool for the symmetric buffers. Also shared by the 1D two-batch-overlap path. Operates on a passed-in block; built on the comm transport, the no-sync common helpers, and the symmetric-memory buffer pool. ## Notes - nvtx ranges use the shared `_nvtx.annotate(label, subsystem)` helper. ## Testing This is a multi-rank symmetric-memory forward with no single-process surface (its only pure logic, rank-capacity, is already covered). It's validated end-to-end by the multi-GPU EP-vs-no-EP parity test that lands with the no-sync forward path. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
Adds the two-batch-overlap (TBO) variant of the 1D no-sync expert-parallel forward. ## What's added `nn/moe/v2/ep_no_sync_tbo_1d.py` — `combined_forward_ep_no_sync_tbo` and its stage pipeline (`ep_no_sync_stage_a` / `stage_c_launch` / `stage_d_launch` / `stage_e` / `stage_tail`, plus the `_NoSyncTboPendingContext` carried between stages). It splits a micro-batch into two halves and overlaps one half's symmetric-memory all-to-all with the other half's compute. Driven by the model's `forward_tbo` / `_tbo_last_step` (which lazy-import it). Depends only on the comm transport, the no-sync common helpers, and the symmetric-memory buffer pool (all on `moe-v2-core`). ## Notes - nvtx ranges use the shared `_nvtx.annotate(label, subsystem)` helper. ## Testing The applicable dev test (`v2_tbo_test.py`, no-sync variant — TBO output must match the non-TBO no-sync forward) compares against the non-TBO `combined_forward_ep_no_sync_1d`, so it lands once that forward (`ep_no_sync_1d`) is on the branch. The sync-TBO variant needs the sync EP family. Both are multi-GPU. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]> Co-authored-by: Tianhua Tao <[email protected]>
First piece of the rowwise no-sync expert-parallel path (the production no-sync path). ## What's added `nn/moe/v2/ep_no_sync_rowwise_helpers.py`: - `build_rowwise_route_maps` — per-route destination rank/row maps for the rowwise all-to-all (tail-dropped routes encoded as `-1`). - `accumulate_` / `add_` / `reset_ep_no_sync_rowwise_metrics` — per-block drop-rate and symm-buffer-utilization counters, read by the block's auxiliary-metrics path (which already lazy-imports them). Clean leaf — depends only on `get_rank` + torch (block ref is `TYPE_CHECKING`-only). ## Notes - Removed the dead env-gated route-map debug instrumentation; the trace switch (`OLMO_TBO_VERBOSE_DEBUG_PRINT`) is noted in the module docstring. - nvtx via the shared `_nvtx.annotate` helper; lowercase `tuple[...]` hints; module docstring. ## Testing `src/test/nn/moe/v2/ep_no_sync_rowwise_helpers_test.py` (CPU): metric accumulation (drop rate + symm-buffer util with reduce types) and the zero-capacity ignore case. `make checks` clean. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
) Adds the synchronous (count-synchronized) expert-parallel forward paths for the fused MoE block: - `ep_sync_1d.py` — single-batch forward. Exchanges per-expert token counts with a blocking all-to-all, then dispatches and combines tokens with an async all-to-all over the expert-parallel group, runs the routed experts, and overlaps the shared experts on a side stream. - `ep_sync_tbo.py` — the same pipeline with two-batch overlap: two micro-batches are interleaved so one batch's expert-parallel all-to-all overlaps the other's attention/router compute. Batch 0 is finished within the call; batch 1 is returned mid-flight in a `SyncedTboPendingContext` for the next block (or the model's final TBO step) to complete. `MoEFusedV2TransformerBlock.combined_forward_ep_tbo` dispatches the no-sync case before importing this module, so the sync TBO entry point here is sync-only. These forwards rely on the async all-to-all primitives (`all_to_all_async` / `all_to_all_wait`) in `olmo_core.ops.moe`, which are included here so the paths type-check and run. --------- Co-authored-by: Tianhua Tao <[email protected]> Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
Adds `MultiGroupDistributedDataParallel` under `olmo_core.nn.parallel` (targeting the MoE integration branch). Same code as #688, re-based onto this branch. A data-parallel module wrapper that all-reduces gradients across one or more process groups. Unlike `torch.nn.parallel.DistributedDataParallel`, **different parameters can be reduced over different process groups** via a `param_process_group_fn(name, param) -> process_group` mapping — needed when subsets of the model are replicated over different device meshes (e.g. expert weights under expert parallelism reduce only over ranks holding the same experts). - **Bucket views**: gradients accumulate into flat pre-allocated per-group buffers; each param's `.grad` is a view into its bucket slice, enabling one all-reduce per bucket. - **Overlap**: bucketed all-reduces launch during backward as each bucket fills; `finalize_grad_reduce()` waits for completion after `loss.backward()`. - **Optional fp32** gradient accumulation and/or reduction. - Opt-in, duck-typed hooks (`getattr(module, ...)`) for syncing fp8/mxfp8 gradient stores — no-ops for standard modules, so this stays a standalone primitive with no MoE dependency. This is the DDP wrapper the fused-MoE optimizer's `build()` and the MoE train module require. **Tests** (`src/test/nn/parallel/distributed_test.py`, gloo + nccl): `test_grad_parity` (DDP grads match a manual all-reduce reference) and `test_no_sync_accumulation` (`no_sync()` defers the reduce and accumulates across micro-batches). Pass on gloo (CPU); `make checks` clean. Also pins `nvidia-cutlass-dsl<4.6.0` (separate commit): flash-attn-4's `cute` path pulls `quack-kernels`, which imports `cutlass.cute.core.ThrMma` — removed in cutlass-dsl 4.6.0 — breaking `import olmo_core.nn` at CI collection. This is a general CI fix; drop it wherever it lands second. --------- Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
Adds the distributed fused optimizer for the fused MoE model (`MoEFusedV2Transformer`): - `MoEFusedV2Optimizer` — keeps fp32 master copies of the parameters, reduce-scatters gradients and gathers updated parameters across the data-parallel and expert-parallel-data-parallel process groups (DTensor- and expert-parallel-aware), and applies a fused per-parameter-group step supporting **AdamW** and **Muon** with **skip-step** loss-spike detection. Unlike the other optimizers (thin configs over `torch.optim.Optimizer` that rely on FSDP for gradient reduction and state sharding), this one owns its optimizer-state sharding and the reduce-scatter/all-gather itself, over separate process groups for regular vs expert params. - `MoEFusedV2OptimizerConfig` — builds the optimizer from AdamW settings, the `muon_*` settings, the skip-step spike-detection settings, and optional per-parameter-group overrides. The optimizer is import-clean (its only cross-package dependency is `nn.fp8_weight`); its `build()` consumes the train module, which lands separately. Also relocates the shared nvtx annotation helper from `nn/moe/v2/_nvtx.py` to `olmo_core/_nvtx.py` and renames it `maybe_nvtx_annotate`, so it's the single entry point for nvtx ranges anywhere (the optimizer routes through it). It now emits an uncolored range by default (a drop-in for a bare `nvtx.annotate(label)`); passing a subsystem still selects a consistent color. Tests (CPU): Muon Newton-Schulz orthogonalization, the Muon lr adjustment, config param-group overrides, and fp8-weight-store detection. The full optimizer-step parity test (reduce-scatter → master update → gather) needs the sharded distributed model state the train module sets up, plus multiple GPUs, so it lands with the train module. --------- Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]> Co-authored-by: Tianhua Tao <[email protected]>
…nner (#797) Adds a Beaker image build matrix and tooling to build the images and run the CI test suite across them on GPUs. ## Image matrix Two CUDA families, each with optional add-ons: - **CUDA 12.8 / torch 2.10** — builds for H100 (sm_90) and B200 (sm_100). - **CUDA 13.0 / torch 2.11** — additionally builds for B300 (sm_103, Blackwell Ultra), which requires the CUDA 13 toolkit. Optional layers, gated by build args so the default image is unchanged: - **FA4** (`flash_attn.cute`, the `flash_4` attention backend) — prebuilt wheel, CUDA-13 only. Pins `nvidia-cutlass-dsl` to a 4.5-era release (the FA4 betas float the pin, and cutlass-dsl 4.6.x dropped an API the wheel calls). - **RMA** — optional NVSHMEM install for the rowwise-EP symmetric-memory extension. B300 handling: FA3 is skipped for B300 (it builds no sm_103 kernels and its bundled CUTLASS won't compile against CUDA 13); flash-attn 2 and grouped_gemm take `sm_103` via per-tool arch lists. Image tags carry no GPU-generation suffix, staying consistent with existing image names. ## Tooling - `Makefile`: `beaker-image-{cu128, cu128-rma, cu130, cu130-fa4, cu130-rma, cu130-fa4-rma}` targets bundling the right build args per combination. - `src/scripts/beaker/build_all_images.sh`: builds every matrix image (checks Docker + Beaker auth + jq up front, continue-on-error, prints a summary). - `src/scripts/beaker/run_ci_tests_on_images.py`: launches the pytest CI suite on each image across GPU types (2 GPUs/launch), collects the JUnit results, and reports union coverage — confirming every test runs on at least one image (excluding >2-GPU tests). GPU type is selected by cluster; workspace and priority are CLI-configurable. Covered by `src/test/scripts/run_ci_tests_on_images_test.py`. --------- Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
# Conflicts: # pyproject.toml
## Summary
This PR adds LatentMoE support to the original MoE and MoE v2
implementations.
Instead of running routed experts on the model’s hidden representation,
LatentMoE wraps the routed expert path with two shared linear
projections:
1. Project routed token payloads into a smaller latent representation: d
→ ℓ
2. Perform expert dispatch, expert computation, and combine in latent
space
3. Project the combined routed output back into model space: ℓ → d
The router continues to compute gating decisions from the original
model-space representation. Only the routed payload and routed expert
computation use
the latent dimension.
Shared experts, transformer norms, and residual operations remain in
model space.
## Configuration
### Original MoE
For the original MoE implementation, add latent_moe to MoEConfig:
```
from olmo_core.nn.moe import LatentMoEConfig, MoEConfig
moe = MoEConfig(
...,
latent_moe=LatentMoEConfig(
latent_dim=1024,
),
)
```
The router remains model-width, while the routed experts are built
automatically with latent_dim.
### MoE v2
For MoE v2, configure the router with the model dimension and the routed
experts with the latent dimension:
```
from olmo_core.nn.moe import LatentMoEConfig
from olmo_core.nn.moe.v2.routed_experts import RoutedExpertsConfig
from olmo_core.nn.moe.v2.router import MoERouterConfigV2
d_model = 4096
latent_dim = 1024
block = OLMoDDPTransformerBlockConfig(
...,
latent_moe=LatentMoEConfig(
latent_dim=latent_dim,
),
routed_experts_router=MoERouterConfigV2(
d_model=d_model,
...,
),
routed_experts=RoutedExpertsConfig(
d_model=latent_dim,
...,
),
)
```
The following dimensional constraints are enforced:
- 0 < latent_dim < d_model
- routed_experts_router.d_model == d_model
- routed_experts.d_model == latent_dim
- Shared expert and shared router dimensions remain equal to d_model
Leave latent_moe=None to use the standard MoE architecture.
## Optional pre-up-projection normalization
Normalization before the ℓ → d projection is disabled by default.
Enable it with:
```
latent_moe=LatentMoEConfig(
latent_dim=1024,
up_proj_input_norm_enabled=True,
)
```
When enabled without an explicit configuration, a bias-free RMSNorm is
used.
A different normalization can be configured explicitly:
```
from olmo_core.nn.layer_norm import LayerNormConfig, LayerNormType
latent_moe=LatentMoEConfig(
latent_dim=1024,
up_proj_input_norm_enabled=True,
up_proj_input_norm=LayerNormConfig(
name=LayerNormType.rms,
eps=1e-6,
bias=False,
),
)
```
Projection biases are disabled by default and can be enabled with
bias=True.
## Supported execution paths
LatentMoE is integrated with:
- Original MoE and dropless MoE
- MoE v2 without expert parallelism
- Synchronous and asynchronous expert parallelism
- Rowwise, rowwise-wave, and DeepEP v2 backends
- Hybrid MoE combined-forward paths
- Tensor, expert, context, data, and pipeline parallel execution
Routing remains model-width in every path, while routed communication
and expert computation use latent_dim.
fla 0.5.2 requires triton >= 3.7.1 (a hard runtime guard on Hopper for gated delta-net backward) and pulls torchaudio 2.11, but the GPU CI/beaker image ships torch 2.10 / triton 3.6.0, and no released torch bundles triton >= 3.7.1 (torch 2.11 pins 3.6.0, torch 2.12 pins 3.7.0). Under 0.5.2 the GPU jobs fail two ways: test_gated_delta_net_fwd_bwd raises on the triton guard, and torchaudio 2.11's .so fails to load against torch 2.10 (undefined symbol torch_dtype_float4_e2m1fn_x2). Stay on 0.4.1 until the GPU image moves to a torch that bundles triton >= 3.7.1. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
# Conflicts: # .github/workflows/main.yml # Makefile # src/Dockerfile # src/olmo_core/nn/moe/router.py
The akshitab/moe-v2-core entries in main.yml's pull_request/push branch filters were a temporary measure to run the full Main suite on the incremental MoE PRs landing into the integration branch. Strip them so the workflow config is clean when the branch merges into main. Note: pushes/PRs to moe-v2-core no longer trigger the Main workflow after this. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: a19a19ec32
ℹ️ 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".
| hf_model = AutoModelForCausalLM.from_pretrained( | ||
| model_name_or_path, revision=revision, trust_remote_code=True | ||
| ) |
There was a problem hiding this comment.
Require opt-in before executing Hugging Face remote code
When model_name_or_path is a Hugging Face repository ID, setting trust_remote_code=True imports and executes Python supplied by that repository on every rank. Since this API accepts arbitrary repository IDs and defaults to the mutable main revision, loading an untrusted or later-compromised model now permits code execution on training nodes; preserve the previous safe default and expose an explicit opt-in, or enable remote code only for trusted local olmo3moe exports.
Useful? React with 👍 / 👎.
| elif isinstance(self.trainer.train_module, OLMoDDPTrainModule): | ||
| optimizers = [self.trainer.train_module.optim] | ||
| scheduler = self.trainer.train_module.scheduler |
There was a problem hiding this comment.
Rebuild the PP schedule after changing the OLMoDDP batch size
When OLMoDDPTrainModule uses pipeline parallelism and this callback advances to a later batch-size stage, the branch updates only the data loader and optimizer LR. OLMoDDPTrainModule.on_attach() computed the pipeline schedule's microbatch count once from the earlier global batch size, and normal run_pipeline() calls do not override it, so the new rank batch is split into the old number of microbatches and no longer respects rank_microbatch_size; a warmup increase can therefore produce unexpectedly large microbatches and OOM. Update/rebuild the PP schedule when the batch size changes, or reject this callback with OLMoDDP PP.
Useful? React with 👍 / 👎.
## Summary
Adds a CUDA 12.9 / torch 2.13 Beaker image and moves GPU CI onto it.
This lets `flash-linear-attention` be un-pinned back to 0.5.2 — 0.5.2
refuses its gated-delta-net backward on Hopper unless triton ≥ 3.7.1,
which comes with torch 2.13.
## Image
- New `beaker-image-cu129` / `-cu129-rma` / `-cu129-sm80` Makefile
targets: torch 2.13.0, CUDA 12.9.1, TransformerEngine 2.18. The CUDA-13
family and the default build are also on torch 2.13 now.
- The `sm80` variant builds for sm_80/90/100 on a CUDA devel base, so it
runs on A100, H100, and B200, and imports TransformerEngine (the devel
base provides the system libcudart TE loads at import).
- TE 2.18's NCCL expert-parallel extension is disabled at build
(`NVTE_WITH_NCCL_EP=0`) — olmo-core doesn't use TE's NCCL-EP API, and it
fails to compile against the bundled NCCL.
- `flash-linear-attention` un-pinned to 0.5.2; `dion` bumped to
`e64832041` for torch-2.13 compatibility.
- The rowwise MXFP8 quant kernel's per-warp staging
(`ROWWISE_MXFP8_Q_CHUNK_BLOCKS`) is reduced 128 → 32 so it fits sm_100's
48 KB static shared-memory cap — at 128 the kernel needs ~80 KB and
nvlink rejects it on B200 ("uses too much shared data"). sm_90 is
unaffected.
## CI
- GPU test matrix moved to the cu129 images: `sm80` is the universal
image for the general jobs and the attention job; `rma` serves the **MoE
kernels** job (needs NVSHMEM for the `symm_mem_vdev2d` EP kernels).
- Jobs target explicit `--cluster` lists rather than `--gpu-type`
(jupiter/ceres = H100, saturn = A100, titan = B200), so scheduling only
lands on clusters this budget can use. Every GPU job can run on B200;
the attention and MoE-kernels jobs run on H100 + B200; the general jobs
also on A100.
- `torch` is pinned `<2.14` and the CPU-CI setup action defaults to
torch 2.13, so CI tests a torch the images actually ship (previously
`.[all]`'s unbounded fla floor floated CPU CI up to 2.14).
- Dropped the separate torch-2.11 job (the universal image now covers
all GPU types).
## Test gating for the new arch reality
- TE fused attention and FP8-e4m3 tests gated to compute capability ≥ 9
— they self-skip on A100 (sm_80).
- TE MXFP8 comparison gated to cc ≥ 10 (Blackwell).
- dion HSDP is skipped in tests on torch ≥ 2.13 (broken upstream two
ways: a deterministic CPU-tensor→Triton error in the replica-only path,
and a flaky ALLREDUCE hang in the sharded path). Since the default image
is now torch 2.13, `Dion.build_parallelism_config` also raises a clear
`RuntimeError` when HSDP is configured on torch ≥ 2.13, instead of
erroring or hanging deep in the optimizer step.
- The flaky te-attn Ulysses CP tests (attention + transformer) are
xfailed (`strict=False`) so those jobs stay green whether the test
flakes or passes.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Tests on all GPU types:
| GPU | cluster | image | link |
|------|----------------|---------------------------------------------------|-----------------------------------------------|
| h100 | jupiter/ceres | akshitab/olmo-core-tch2130cu129-rma-2026-09-11
| https://beaker.org/ex/01M2938RQ8KG44NX6TZC9XXR1Z |
| b200 | titan | akshitab/olmo-core-tch2130cu129-rma-2026-09-11 |
https://beaker.org/ex/01M2938M48E9WZ764VPGA1S8KG |
| a100 | saturn | akshitab/olmo-core-tch2130cu129-sm80-2026-09-11 |
https://beaker.org/ex/01M2938PMSXY5ZS67M6NZ9GDDZ |
| b300 | holmes | akshitab/olmo-core-tch2130cu130-fa4-rma-2026-09-11 |
https://beaker.org/ex/01M2945AZD1DTVPHS5NGK2GTE0 |
---------
Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: e3a853587c
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| if isinstance(block, OLMoDDPTransformerBlock): | ||
| if moe_block is None: | ||
| moe_block = block |
There was a problem hiding this comment.
Classify shared-only OLMoDDP blocks as dense
When an OLMoDDP model uses dense overrides, as the added OLMoE3 scripts do, those layers are still OLMoDDPTransformerBlock instances with routed_experts=None. This branch therefore labels every block as MoE; if the first block is dense it is selected as moe_block and export raises “MoE block is missing routed experts,” while dense blocks appearing later are omitted from dense_layers_indices and conversion looks for nonexistent routed-expert weights. Classify these blocks by whether they actually have routed experts and convert their shared-only weights as dense weights.
Useful? React with 👍 / 👎.
| # Maybe reduce across the process group. | ||
| if is_distributed(): | ||
| dist.all_reduce(batch_size_per_expert, group=self.group) |
There was a problem hiding this comment.
Exclude pipeline ranks from router bias reduction
When bias_gamma is enabled with pipeline parallelism, self.group is never assigned, so passing it here as None reduces across the default world group. Different PP ranks own different layers, meaning corresponding collectives blend token counts from unrelated routers; if stages own different numbers of routed blocks, they also execute different numbers of world collectives and hang. Bind each router to the replica group for the same stage/layer, excluding the PP dimension.
AGENTS.md reference: AGENTS.md:L98-L101
Useful? React with 👍 / 👎.
| checkpoint_key = self._resolve_model_checkpoint_key(name, checkpoint_keys) | ||
| if checkpoint_key is None: | ||
| continue |
There was a problem hiding this comment.
Reject checkpoints with missing model parameters
During eval-only or weights-only loading, a checkpoint with renamed, missing, or otherwise unmatched parameter keys silently skips each unresolved parameter and errors only when no parameters matched at all. Because the model has already been initialized, the load succeeds with those parameters left at fresh initialization, producing plausible but invalid evaluation or fine-tuning results; this also affects optimizer-only checkpoints from runs where frozen parameters were not present in optimizer state. Require all expected parameters to resolve unless an explicit non-strict load mode is requested.
Useful? React with 👍 / 👎.
## Summary Adds the remaining training entry points behind the Olmo-core MoE tech report, *Supercharging Olmo-core for Efficient and Scalable MoE Training*, so that every reported configuration has a reference script in `src/examples/olmo_ddp/`. #844 already added the eight production scripts; this PR adds the rest. There are no library code changes. **Per-row variants of the headline throughput results** (each a copy of its base script with only the named constants changed). The headline rates use random expert routing, whereas the existing Tiny/Small scripts default to learned routing: - `OLMoE3-dev-t001-random.py`, `OLMoE3-dev-s001-random.py`, `OLMoE3-dev-s001-random-16mi.py` - `OLMoE3-dev-m001-64e-16mi.py` (Medium-64E) - `OLMoE3-dev-l001-pp8-24mi.py` **Ported from the pre-merge `moe-v2-core` API** (experiment settings unchanged; only the API surface changed): - Eight-layer DDP vs. FSDP/HSDP benchmark: `moe_8l_fsdp.py`, `dense_8l_ddp.py` - EP transport profiles: `moe_8l_ep8_{sync,rowwise,deepep_v2}_profile.py`, their `*_no_shared` variants, `moe_8l_ep1_no_shared_profile.py`, and `moe_6l_ep8_{rowwise,deepep_v2}_mxfp8_no_shared_profile.py` - Load-balancing-loss weight runs (Token Gerrymandering): `moe_8l_ddp_lbl_0p{02,20}.py`, `moe_10l_ddp_lbl_0p{05,50}.py`, `moe_10l_ddp_lbl_0p50_shared.py` **Also included** - `src/examples/olmo_ddp/README.md`: maps each reported result to its script, with launch requirements and porting notes. - `src/test/examples/olmo_ddp_tech_report_test.py`: CPU-only config-build checks. They build model, train-module, and trainer configs without instantiating models or touching GPUs, data, or the network, and they pin the reported parameter counts, batch sizes, parallel degrees, and routing. ## Notes - These are reference scripts released alongside the report. - The branch is up to date with current `main` (merged 2026-09-30, no conflicts); it still only adds the 23 files above. The CPU config-build test runs in CI against current `main`. - Two-batch overlap (the `tbo` schedule) is not supported on `main`, so the report's TBO result cannot be reproduced from these scripts.
|
This PR has been released in v3.0.0. |
## 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]>
Adds the OLMoDDP fused Mixture-of-Experts / expert-parallel training stack and its supporting kernels, distributed primitives, model/train-module integration, HuggingFace interop, and image tooling.
Model & training
nn/ddp(OLMoDDP*), with anExpertParallelConfigabstraction for the block/model.MoEV2TransformerTrainModuleand the fused MoE distributed optimizer.Kernels
OlmoMXFP8Tensor) andscaled_grouped_mmFP8 kernels with an FP8 weight cache.grouped_mmwrapper, MoE token permute/reorder and permute/unpermute helpers.cuda_extension_utils/LazyCudaExtension).Distributed / expert parallelism
MultiGroupDistributedDataParalleland reduce-scatter gradient reduction.HuggingFace interop
olmo3moemodel plus checkpoint converters and logit-parity tests (Qwen-MoE, GPT-OSS).Image / build tooling
flash_attn.cute) and symm-mem/RMA (NVSHMEM + RMA-capable NCCL) layers, plus B300 (sm_103) support.moe.v2.*_CLASS_paths.Testing
spawn; GPU/extension-only tests are gated so the CPU CI lane stays green.Notes for reviewers
flash-linear-attentionis pinned to0.4.1(main is on0.5.2). fla0.5.2requires Triton >= 3.7.1 (a hard Hopper guard) and pulls torchaudio 2.11, but the current GPU image ships torch 2.10 / Triton 3.6.0; no released torch below 2.13 bundles Triton >= 3.7.1. The pin keeps the GPU jobs green; revisit once the image moves to a torch that bundles Triton >= 3.7.1.akshitab/moe-v2-coreentries in the CI branch filters have already been removed.🤖 Generated with Claude Code