Skip to content

Add MultiGroupDistributedDataParallel - #746

Merged
AkshitaB merged 12 commits into
akshitab/moe-v2-corefrom
akshitab/multigroup-ddp-core
Jul 7, 2026
Merged

AkshitaB merged 12 commits into
akshitab/moe-v2-corefrom
akshitab/multigroup-ddp-core

Conversation

@AkshitaB

@AkshitaB AkshitaB commented Jul 6, 2026

Copy link
Copy Markdown
Contributor

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.

AkshitaB and others added 2 commits July 6, 2026 09:57
A data-parallel module wrapper under olmo_core.nn.parallel that all-reduces gradients across
one or more process groups. Unlike torch DDP, 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). Gradients accumulate into flat per-group bucket views, bucketed all-reduces
overlap the backward pass (finalized via finalize_grad_reduce()), and grads can optionally be
accumulated/reduced in fp32. Includes gloo/nccl grad-parity and no_sync accumulation tests.

Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
flash-attn-4's cute path pulls quack-kernels, which imports cutlass.cute.core.ThrMma; that was
removed in nvidia-cutlass-dsl 4.6.0, so a fresh install raises AttributeError at import and breaks
every CPU test job at collection. Pin below 4.6.0 until quack-kernels supports it.

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

@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: 33493f4221

ℹ️ 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 +537 to +538
# Keep missing grads explicitly zero in the bucket view.
self._param_to_bucket_view[param].zero_()

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 accumulated no_sync grads for skipped params

When using no_sync() for gradient accumulation, a sparse/expert parameter can receive a gradient in an earlier unsynced micro-batch but be unused in the final synced micro-batch. In that case its hook returned early during no_sync() and never marks it ready, so finalize_grad_reduce() reaches this branch and zeroes the bucket view, silently discarding the already accumulated local gradient before the all-reduce. This breaks the exact MoE/imbalanced-routing scenario the wrapper is meant to support; only truly absent grads for the whole accumulation window should be zeroed.

Useful? React with 👍 / 👎.

AkshitaB and others added 2 commits July 6, 2026 10:04
…Parallel

The existing tests only exercise the default single process group. Add coverage for the two
features that distinguish this wrapper from torch DDP:
- test_multi_group_grad_parity (world_size=4, two subgroups): fc1 reduces over the full group
  and fc2 over the rank's subgroup via param_process_group_fn, matching per-group all-reduce
  references.
- test_fp32_grad_accumulation: accumulate_grads_in_fp32 + reduce_grads_in_fp32 accumulate into
  _main_grad_fp32 (with .grad left None) and match the all-reduce-averaged reference.

Both run on gloo (CPU) + nccl.

Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
The '# mypy: allow-untyped-defs' pragma was a one-off in the codebase and a no-op under the repo's
mypy config (check_untyped_defs is on, but disallow_untyped_defs is not). Remove it and add type
annotations to the public __init__ signature to match the codebase norm. mypy stays clean.

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

@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: 48945b276d

ℹ️ 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 +217 to +221
for p in module.parameters():
if not p.requires_grad:
continue
self._fp32_acc_hooks.append(
p.register_post_accumulate_grad_hook(self._fp32_post_grad_acc_hook)

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 Skip ignored params when installing fp32 hooks

When accumulate_grads_in_fp32=True and the wrapped module uses _ddp_params_and_buffers_to_ignore for a trainable parameter, this loop still registers _fp32_post_grad_acc_hook on that ignored parameter even though the bucket/view maps were built only from _module_parameters. If that ignored parameter participates in backward, the hook indexes self._param_to_bucket_view[param] and raises instead of leaving the parameter to be trained outside this reducer; install these hooks over the same non-ignored parameter set or skip ignored names here.

Useful? React with 👍 / 👎.

…ex review)

- finalize_grad_reduce no longer zeroes the bucket view of params that weren't marked ready this
  step. Under no_sync() gradient accumulation, a param can receive a grad in an earlier unsynced
  micro-batch but be unused in the final synced one, so it's never marked ready; zeroing discarded
  its accumulated grad — exactly the imbalanced-MoE-routing + accumulation case this wrapper
  targets. The bucket view already holds the correct value (zero if never touched, else the
  accumulated grad), so just mark it ready. Adds a repro test (fails before, passes after).
- Install the fp32 post-accumulate hooks over self._module_parameters (the non-ignored set) instead
  of module.parameters(); an ignored trainable param otherwise got a hook that indexes a missing
  bucket-view entry during backward.

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

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

ℹ️ 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 +179 to +182
named_buffers = list(self.module.named_buffers())
if len(named_buffers) > 0:
raise NotImplementedError(
"DDP with param_process_group_fn does not support buffers yet."

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 Don't reject MoE routing buffers

When wrapping a MoE v2 model whose router sets bias_gamma, MoERouterV2 registers score_bias as a real buffer, and MoEFusedV2Transformer.apply_dp() always constructs this wrapper with a param_process_group_fn. This unconditional named_buffers() check therefore raises before training starts even though the buffer is non-gradient router state and not part of the gradient buckets, making auxiliary-loss-free MoE configs unusable with the new DDP wrapper.

Useful? React with 👍 / 👎.

def test_multi_group_grad_parity(backend):
run_distributed_test(
_run_multi_group_grad_parity,
world_size=4,

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 Require four GPUs for the 4-rank NCCL test

BACKENDS marks the NCCL case as requiring only multiple GPUs, but this test hard-codes four ranks and _device_for_backend() maps each rank to cuda:{rank}. On 2- or 3-GPU machines the NCCL variant starts ranks 2/3 on nonexistent devices, so the test fails before exercising the wrapper; either skip unless at least four GPUs are available or make the subgroup test scale to the available world size.

Useful? React with 👍 / 👎.

@TianhuaTao TianhuaTao left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

It looks like a critical correctness issue. The fix is necessary.

AkshitaB and others added 2 commits July 6, 2026 10:39
test_multi_group_grad_parity uses world_size=4 (two subgroups). The gloo variant runs as 4 CPU
processes, but the NCCL variant needs 4 GPUs and the CI GPU box has 2, so it hit 'invalid device
ordinal'. Guard the NCCL backend on torch.cuda.device_count() >= 4 (mirrors the existing pattern
in nn/transformer/model_test.py); gloo still runs everywhere.

Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
Instead of world_size=4 (two 2-rank subgroups, which needs 4 GPUs for the NCCL variant), route
fc1 to the full group and fc2 to the rank's own singleton group: fc1 grads are averaged across
ranks while fc2 grads stay per-rank (the EP case where an expert lives on one rank). This still
exercises per-group bucketing and per-group reduction, and runs on gloo and the 2-GPU NCCL CI.
Drops the 4-GPU skip guard.

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

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

ℹ️ 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 +523 to +526
def finalize_grad_reduce(self):
# Grad buffers should already be bound before backward starts. If they are detached here,
# we cannot safely rebind without risking silent corruption.
self._ensure_grad_views_bound(allow_none_rebind=False, where="finalize_grad_reduce")

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 Finalize bucket reductions before stepping

finalize_grad_reduce() is the only place that waits for _grad_reduce_hooks and launches buckets that did not become ready during backward, but the production path that gets this wrapper from MoEFusedV2Transformer.apply_dp() never calls it: repo-wide search finds calls only in src/test/nn/parallel/distributed_test.py, while TransformerTrainModule.optim_step() goes from backward to clipping/self.optim.step()/zero_grads(). In that path, optimizers can read local or stale bucket contents while async all-reduces are still in flight, so hook this method before grad clipping/optimizer step or make finalization automatic.

Useful? React with 👍 / 👎.

)

main_grad.add_(g)
param.grad = None

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Keep fp32 grads visible to the optimizer

With accumulate_grads_in_fp32=True (the default in MoEFusedV2Transformer.apply_dp()), this hook moves the reduced gradient into _main_grad_fp32 and clears param.grad, but the repo's train modules, gradient clipping, and optimizers read only p.grad (for example AdamW.step() skips parameters whose p.grad is None). In the default MoE DP path, clipping sees no gradients and the optimizer skips the wrapped parameters, so training silently fails to update them unless the fp32 buffer is copied back or the optimizer path is taught to consume it.

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: d797fb318e

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



def _device_for_backend() -> torch.device:
if dist.get_backend() == "nccl":

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 Use CUDA for the multi-backend NCCL case

For the backend=NCCL parametrization, BACKENDS passes the multi-backend string cuda:nccl,cpu:gloo (see src/olmo_core/testing/utils.py), not the literal nccl, so this equality check falls through to CPU. In that GPU-marked test run all model tensors and bucket all-reduces are CPU tensors, so the new tests exercise Gloo rather than the CUDA/NCCL path they are meant to cover; use the same substring/backend-support check used by init_distributed() before selecting the device.

Useful? React with 👍 / 👎.

AkshitaB and others added 2 commits July 6, 2026 12:13
- Drop the unconditional buffer rejection: the wrapper reduces parameter gradients only and leaves
  module buffers untouched (unsynced, like torch DDP broadcast_buffers=False), so a model with
  buffers — e.g. a MoE router's score_bias, or RoPE caches — no longer raises at construction. Adds
  a buffered-module grad-parity test (raised before the fix).
- Fix _device_for_backend: BACKENDS passes the multi-backend string 'cuda:nccl,cpu:gloo', so the
  '== "nccl"' check fell through to CPU and the NCCL-marked tests silently ran on gloo. Use
  backend_supports_cuda() (substring-aware) so they actually exercise CUDA.

Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
Per review: retain the removed NotImplementedError guard as a commented block plus a
TODO(revisit) so the buffer-handling question (whether any buffer needs cross-rank sync) is
tracked rather than lost.

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

@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: 3c565499cc

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

sync_logical_grads()

def zero_grad(self, set_to_none: bool = True):
if not set_to_none:

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 Zero ignored gradients in the fast zero_grad path

When a wrapped module uses _ddp_params_and_buffers_to_ignore for a trainable parameter and callers use ddp.zero_grad(set_to_none=False), this fast path returns after zeroing only the reducer buckets. Ignored parameters are deliberately absent from _module_parameters/_grad_buckets, so their .grad tensors keep the previous step's values instead of being zeroed as Module.zero_grad(False) would do; explicitly clear ignored params or delegate that part to the wrapped module before returning.

Useful? React with 👍 / 👎.

AkshitaB and others added 2 commits July 6, 2026 14:04
zero_grad(set_to_none=False) took a fast path that only zeroed the reducer buckets, leaving
ignored (_ddp_params_and_buffers_to_ignore) trainable params with stale grads — unlike
Module.zero_grad(False). Zero their existing grads too, matching nn.Module semantics.

Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
run_distributed_test defaults gloo to start_method=fork, but forking after CUDA has been
initialized in the parent pytest process (by earlier GPU-marked tests in the same session)
deadlocks — the suite hung right after output_discard, when these tests run. Spawn creates
fresh processes with no inherited CUDA context. Matches the rest of the suite (spawn everywhere).

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

@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: 86c660c808

ℹ️ 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 +271 to +272
if self._accumulate_grads_in_fp32:
param._main_grad_fp32 = buffer # type: ignore[attr-defined]

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 Clear fp32 bucket grads after optimizer zeroing

When accumulate_grads_in_fp32=True, the persistent gradient is stored in _main_grad_fp32 while .grad is cleared, but normal training code calls optim.zero_grad(set_to_none=True) rather than this wrapper's zero_grad(). Optimizer zeroing only clears p.grad, so the bucket view assigned here remains non-None; the next forward treats it as a valid binding and does not zero the bucket, causing the next backward to add_ new gradients onto the previous step's reduced gradients whenever fp32 accumulation is enabled.

Useful? React with 👍 / 👎.

@AkshitaB
AkshitaB merged commit a980834 into akshitab/moe-v2-core Jul 7, 2026
63 of 70 checks passed
@AkshitaB
AkshitaB deleted the akshitab/multigroup-ddp-core branch July 7, 2026 01:04
AkshitaB added a commit that referenced this pull request Jul 7, 2026
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants