Repository navigation
Add MultiGroupDistributedDataParallel - #746
Conversation
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]>
There was a problem hiding this comment.
💡 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".
| # Keep missing grads explicitly zero in the bucket view. | ||
| self._param_to_bucket_view[param].zero_() |
There was a problem hiding this comment.
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 👍 / 👎.
…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]>
There was a problem hiding this comment.
💡 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".
| 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) |
There was a problem hiding this comment.
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]>
There was a problem hiding this comment.
💡 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".
| 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." |
There was a problem hiding this comment.
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, |
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
It looks like a critical correctness issue. The fix is necessary.
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]>
There was a problem hiding this comment.
💡 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".
| 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") |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
💡 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": |
There was a problem hiding this comment.
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 👍 / 👎.
- 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]>
There was a problem hiding this comment.
💡 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: |
There was a problem hiding this comment.
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 👍 / 👎.
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]>
There was a problem hiding this comment.
💡 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".
| if self._accumulate_grads_in_fp32: | ||
| param._main_grad_fp32 = buffer # type: ignore[attr-defined] |
There was a problem hiding this comment.
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 👍 / 👎.
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]>
Adds
MultiGroupDistributedDataParallelunderolmo_core.nn.parallel(targeting the MoEintegration 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 differentprocess groups via a
param_process_group_fn(name, param) -> process_groupmapping — needed whensubsets of the model are replicated over different device meshes (e.g. expert weights under expert
parallelism reduce only over ranks holding the same experts).
.gradis a view into its bucket slice, enabling one all-reduce per bucket.finalize_grad_reduce()waits for completion afterloss.backward().getattr(module, ...)) for syncing fp8/mxfp8 gradient stores — no-opsfor 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 gradsmatch a manual all-reduce reference) and
test_no_sync_accumulation(no_sync()defers the reduceand accumulates across micro-batches). Pass on gloo (CPU);
make checksclean.Also pins
nvidia-cutlass-dsl<4.6.0(separate commit): flash-attn-4'scutepath pullsquack-kernels, which importscutlass.cute.core.ThrMma— removed in cutlass-dsl 4.6.0 — breakingimport olmo_core.nnat CI collection. This is a general CI fix; drop it wherever it lands second.