Skip to content

Add the fused MoE distributed optimizer - #744

Merged
AkshitaB merged 11 commits into
akshitab/moe-v2-corefrom
akshitab/moe-v2-optimizer
Jul 7, 2026
Merged

AkshitaB merged 11 commits into
akshitab/moe-v2-corefrom
akshitab/moe-v2-optimizer

Conversation

@AkshitaB

@AkshitaB AkshitaB commented Jul 3, 2026

Copy link
Copy Markdown
Contributor

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.

@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: 01f420fd06

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

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

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread src/olmo_core/optim/moe_optimizer.py Outdated
Comment on lines +435 to +437
from ..train.train_module.transformer.moe_train_module import (
MoEV2TransformerTrainModule,
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Remove runtime import of missing MoE train module

Calling MoEFusedV2OptimizerConfig.build() currently fails before it can construct the optimizer because this runtime import targets olmo_core.train.train_module.transformer.moe_train_module, which is not present in this repository (repo-wide search only finds this reference). Since the imported class is only used for cast(), any current attempt to use the newly exported optimizer hits ModuleNotFoundError even when a compatible train module object is passed.

Useful? React with 👍 / 👎.

Comment thread src/olmo_core/optim/moe_optimizer.py Outdated
Comment on lines +143 to +144
eps: float,
) -> torch.Tensor:

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Scale Muon updates using the matrix dimensions

For grouped expert weights with ndim > 2, the Newton-Schulz path treats each matrix as the last two dimensions (grad.size(-2), grad.size(-1)), but the LR adjustment here uses the first two dimensions. With routed/shared expert shapes like (experts, hidden, d_model), original scaling is computed from experts / hidden instead of hidden / d_model, so Muon groups get the wrong update magnitude for the main tensors this optimizer targets.

Useful? React with 👍 / 👎.

Comment on lines +453 to +455
dp_groups = self.build_groups(
model_parts, strict=strict, param_filter=lambda p: id(p) not in ep_param_ids
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Allow overrides that match only one optimizer partition

build() expands the same group_overrides against the DP-filtered parameters first with strict=True; a valid override that targets only EP parameters (for example routed experts) has zero matches in this filtered DP set and raises before the later ep_groups pass can match it. The same applies to dense-only overrides in the EP pass, so per-parameter overrides are unusable unless every pattern happens to match both partitions.

Useful? React with 👍 / 👎.

@AkshitaB
AkshitaB force-pushed the akshitab/moe-v2-optimizer branch from f37e457 to 3018ffc Compare July 3, 2026 01:00

@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: 3018ffc1f1

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

MoEV2TransformerTrainModule,
)

assert train_module is not None, "MoEFusedV2OptimizerConfig.build requires a train_module"

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Preserve the existing optimizer build contract

In the training constructors I checked, optimizers are still built as optim.build(model, strict=...) (TransformerTrainModule) or per-stage with the same signature (TransformerPipelineTrainModule), so no normal training path passes this new train_module argument. Once the already-commented missing import is fixed, selecting this optimizer through the existing config path will still abort on this assertion instead of constructing the optimizer; either thread the train module through those call sites or keep this build() compatible with the OptimConfig.build(model, strict=...) interface.

Useful? React with 👍 / 👎.



@dataclass
class MoEFusedV2OptimizerConfig(Config):

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Register the MoE optimizer config

The standard train-module config decodes optim as an OptimConfig, and the other optimizer configs in this package are registered with @OptimConfig.register(...); this new config only inherits Config and is never registered. As a result, a normal YAML/JSON config using the registry-style optim.type cannot select the new optimizer even though it is exported from olmo_core.optim, so users would have to construct it manually rather than through the supported training config path.

Useful? React with 👍 / 👎.

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

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

# FP8 cache refresh, and checkpoint serialization directly. Revisit the choice
# if trainer/callback integration starts needing more of the torch optimizer
# interface.
class MoEFusedV2Optimizer:

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Preserve the SkipStepOptimizer contract

The existing transformer train modules only populate latest_loss/latest_grad_norm for optimizers that satisfy isinstance(..., SkipStepOptimizer). This optimizer reimplements the skip-step buffers and get_step_factor(), but it explicitly does not subclass that contract, so in those training paths _losses stays empty and get_step_factor() always returns 1.0; the advertised loss-spike skipping never triggers unless a separate MoE train path manually wires these fields. Either inherit/register the skip-step contract or explicitly update the metrics before step().

Useful? React with 👍 / 👎.

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

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

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

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +2318 to +2323
if not self._shares_tensor_storage(ckpt_local, state_local):
# Free the local shard storage while keeping DTensor metadata.
empty_local = torch.empty(
0, dtype=state_local.dtype, device=state_local.device
)
self.states[state_key] = DTensor.from_local(

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Do not drop live optimizer state while checkpointing

When _ep_dp_state_to_checkpoint() produces a checkpoint tensor that does not share storage with the live EP state, this branch replaces the optimizer's live DTensor local shard with an empty tensor during state_dict(). Checkpointing is normally done while training continues, but nothing in state_dict() restores that storage afterwards (_ensure_local_state_storage() only runs during load), so the next optimizer step or parameter gather can see zero-length main/moment shards and either fail or update from invalid state.

Useful? React with 👍 / 👎.

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

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

# Concatenate, ensuring the "default" groups remain first in each partition (already ensured by build_groups()).
all_groups: List[Dict[str, Any]] = list(dp_groups) + list(ep_groups) # type: ignore

from olmo_core.nn.parallel.distributed import MultiGroupDistributedDataParallel

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Use an available DDP wrapper in build

This import runs unconditionally during build(), but this repo has no olmo_core.nn.parallel package; a repo-wide search for MultiGroupDistributedDataParallel only finds these references. Even when the caller passes ordinary model parts and never needs the wrapper branch, selecting this optimizer will hit ModuleNotFoundError before it can construct anything.

Useful? React with 👍 / 👎.

reset_chunk_buffers()

def zero_grad(self, set_to_none=True):
raise RuntimeError(

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Implement zero_grad for trainer cleanup

When this optimizer is used with the existing transformer training loops, optim_step() calls zero_grad(set_to_none=True) after every step (train_module.py and pipeline_train_module.py both do this). This method raises unconditionally, so the first otherwise-successful training iteration aborts instead of clearing gradients; either clear the model/FP8 grad buffers here or make sure those train modules never receive this optimizer.

Useful? React with 👍 / 👎.

AkshitaB and others added 11 commits July 6, 2026 18:08
Move maybe_annotate out of nn/moe/v2/_nvtx.py into olmo_core/_nvtx.py (next to the
no-op nvtx fallback) and rename it maybe_nvtx_annotate so it reads as nvtx-profiling
and can be the single entry point for nvtx ranges anywhere (e.g. optim/), not just
nn.moe.v2. Give it a no-color default: with no subsystem it now emits an uncolored
range (a drop-in for a bare nvtx.annotate(label)) instead of forcing gray. Repoint all
nn/moe/v2 call sites.

Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
Adds MoEFusedV2Optimizer + MoEFusedV2OptimizerConfig: the distributed optimizer for the
fused MoE model (MoEFusedV2Transformer). Keeps fp32 master params, reduce-scatters grads and
gathers updated params across the data-parallel and expert-parallel-data-parallel groups
(DTensor/expert-parallel-aware), and applies a fused per-group AdamW/Muon step with skip-step
loss-spike detection.

Routes nvtx through maybe_nvtx_annotate, adds class/step docstrings, drops dead
commented-out code, and wires the exports into optim/__init__. Its build() consumes the
train module, which lands separately.

Co-authored-by: Tianhua Tao <[email protected]>
Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
Covers the self-contained pieces: Muon Newton-Schulz orthogonalization (spread collapse
+ 2D requirement + n-d shape), the Muon lr adjustment, config param-group overrides
(build_groups), and fp8-weight-store detection. The full distributed step-parity test
needs the train module + multiple GPUs and lands with it.

Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
The rest of the codebase compiles a module-level function with a @torch.compile
decorator (see generate/utils.py); the separate NAME = torch.compile(NAME) alias is a
MoE-only idiom. The 2D kernel is always compiled and its uncompiled form is never called
directly, so decorate it directly and drop the alias (and the pointless _nd_compiled
alias, which just pointed at the uncompiled n-d kernel).

Not applied to comm.py / routed_experts.py: their aliases back a runtime compiled-vs-eager
toggle (an uncompiled _impl fallback selected by device + OLMO_MXFP8_COMPILE_SWIGLU_BWD),
so both the compiled and uncompiled callables are needed there — a decorator can't express
that.

Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
Drop the shape-only n-d test and the isinstance-only fp8-detection test, and the redundant
shape assert. Fold the n-d kernel into the orthogonalization test via parametrization so both
dispatch branches are checked for what matters — that Newton-Schulz drives the singular values
toward 1 — rather than just preserving shape.

Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
…izer

_str_paramt was an unused '### DEBUG PRINT ###' param-group dumper (and stale — it referenced
group keys the builder no longer uses), and the commented-out Opt TypeVar was leftover.

Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
The config fields mirror MoEFusedV2Optimizer.__init__ (name + default) so build() can forward
them via as_dict()->kwargs — consistent with the other optim configs, but the two default lists
can drift since the optimizer is ours. Flag it for a single-source-of-truth revisit.

Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
…t foreach

The nvtx-helper relocation changed the call sites from a relative 'from ._nvtx import' to an
absolute 'from olmo_core._nvtx import', which isort groups differently — re-sort the affected
v2 modules (this is what failed the Style CI job). Also drop the commented-out 'foreach' config
field (whose attribute docstring was left dangling, documenting nothing) and the matching
commented-out __init__ param.

Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
The MoEV2TransformerTrainModule import was a runtime import used only for a cast(); since that
module lands separately, calling build() would hit ModuleNotFoundError before constructing the
optimizer. Move it to the TYPE_CHECKING block and use a string forward-ref in the cast, so the
type is available to mypy without a runtime import. (Addresses Codex P1.)

Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
The Muon path's LR scaling was computed from the wrong matrix dims for n-d grouped-expert
weights (`_adjust_muon_lr` read `param_shape[:2]` while Newton-Schulz orthogonalizes the last two
dims), and no training script enables it (every recipe sets `use_muon=False`). Rather than ship a
broken, dormant code path, remove it entirely: the Newton-Schulz kernels, `_adjust_muon_lr`, the
`muon_*` config/constructor args + `MUON_DEFAULT_*` constants, the `use_muon` group handling and
per-param muon state, the muon branch in the step, and the muon-only unit tests. The optimizer now
does a fused AdamW-only step (skip-step spike detection unchanged).

Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
With MultiGroupDistributedDataParallel now on core (via #746), mypy can resolve
model_parts[0]._accumulate_grads_in_fp32 (bool), which exposed that build() reused
has_grad_accum_fp32_buffer as both a bool and a List[bool]. Use a distinct local for the
per-part list so the variable stays a bool.

Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
@AkshitaB
AkshitaB force-pushed the akshitab/moe-v2-optimizer branch from 075b433 to e10ad53 Compare July 7, 2026 02:17
@AkshitaB
AkshitaB merged commit 0e8a981 into akshitab/moe-v2-core Jul 7, 2026
24 checks passed
@AkshitaB
AkshitaB deleted the akshitab/moe-v2-optimizer branch July 7, 2026 03:51
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant