Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
38 commits
Select commit Hold shift + click to select a range
fa17762
Added flextron code, training/eval example scripts, functional and un…
sheliang-nv Apr 21, 2026
cb56a0f
Removed flextron examples
sheliang-nv Apr 21, 2026
4c18286
Added Flextron overrides to load_teacher_model_config
sheliang-nv Apr 21, 2026
c38d1f1
Added all reduce Flextron router grads for PP
sheliang-nv Apr 21, 2026
3b8f6ff
Merge remote-tracking branch 'main/main' into shel/flex_merge
sheliang-nv Apr 22, 2026
892ca2f
Sync with upstream main: adopt Hybrid* naming and new pretrain() entry
sheliang-nv Apr 22, 2026
8b9ffae
Applied linter fixes
sheliang-nv Apr 22, 2026
044965d
Merge branch 'main' into shel/flex_merge
sheliang-nv Apr 22, 2026
aab70ea
Fixed multi argument wrong formatting for flextron functional test
sheliang-nv Apr 23, 2026
c03c840
Added explicit arg model type for flextron func test
sheliang-nv Apr 23, 2026
93608a8
Bugfix for when main_param is None
sheliang-nv Apr 24, 2026
3c864d3
Added golden values for functional test
sheliang-nv Apr 27, 2026
b53eba1
Removed commented out block
sheliang-nv Apr 27, 2026
e8c12da
Removed comments and dead code, redundant all reduces from loss_func.…
sheliang-nv Apr 27, 2026
e05503d
Removed hardcoded teacher config fields
sheliang-nv Apr 27, 2026
fe19e6a
Removed comments, redundant reporting_loss, and defaulted teacher fle…
sheliang-nv Apr 28, 2026
115f5b5
Elastification autoformatted
sheliang-nv Apr 28, 2026
7f2b92f
Assertion message bugfix for flextron_elasticity_hooks.py
sheliang-nv Apr 28, 2026
0ae4d4d
Update functional test to use HybridModel
sheliang-nv Apr 28, 2026
39b93a3
Raise error bugfix in pretrain_mamba_flex.py
sheliang-nv Apr 28, 2026
6b742b6
Bugfix for config.override_selected_budget
sheliang-nv Apr 28, 2026
77bd779
Uncomment budget fallback when not not set in args
sheliang-nv Apr 28, 2026
0f0ac6f
Removed dead out_proj_mask_list, moved training script to elastificat…
sheliang-nv Apr 28, 2026
f871331
Fixed typos and renamed router param attr for PP sync
sheliang-nv Apr 29, 2026
32c7d09
Changed entry path for flextron functional test
sheliang-nv Apr 29, 2026
160336b
Removed unused imports and dead config field
sheliang-nv Apr 30, 2026
e975d5e
Merge branch 'main' into shel/flex_merge
sheliang-nv Apr 30, 2026
33b5c9e
Removed attention head masking
sheliang-nv Apr 30, 2026
96c8e5c
Removed head masking args from tests
sheliang-nv Apr 30, 2026
1570c80
Fix expert_bias mutation, PP-sync test attr, pretrain() signature
sheliang-nv Apr 30, 2026
b8bdfd6
Removed dead code and comments, added init file for router
sheliang-nv Apr 30, 2026
9311c95
Fix MoE expert MSE drop, mlp_per UnboundLocalError, budget=1.0 fallba…
sheliang-nv Apr 30, 2026
0894912
Added args check for int-per-lists, added loss_func unit test
sheliang-nv Apr 30, 2026
41e8976
Fix budget=1.0 KeyError paths, retire original_model kill-switch, sor…
sheliang-nv Apr 30, 2026
c2f58f9
Fix CUDA RNG leak in DP gumbel softmax, update stale loss_func docstring
sheliang-nv Apr 30, 2026
f68b0e6
Removed unused imports and added double check for MLP hook
sheliang-nv Apr 30, 2026
3292cf7
Add unit tests for FlextronTopKRouter and FlextronGroupedMLP elastici…
sheliang-nv Apr 30, 2026
7e4c52e
Autoformat
sheliang-nv Apr 30, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 42 additions & 1 deletion megatron/core/distributed/finalize_model_grads.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.

from functools import partial
from typing import Callable, List, Optional, Union
from typing import Callable, Dict, List, Optional, Union

import torch
from torch._utils import _flatten_dense_tensors, _unflatten_dense_tensors
Expand Down Expand Up @@ -275,6 +275,44 @@ def _allreduce_position_embedding_grads(
)


def _allreduce_router_grads(model: List[torch.nn.Module], config: TransformerConfig):
"""
All-reduce router grads.

Reduce grads across all the pp stages to ensure that parameters of the router stay in sync.
"""

if parallel_state.get_pipeline_model_parallel_world_size() > 1:
grads_dict: Dict[str, List[torch.Tensor]] = {}
for model_chunk in model:
for name, param in get_attr_wrapped_model(model_chunk, 'named_parameters')():
if param.requires_grad and getattr(param, 'flextron_router_pp_sync', False):
grad = param.main_grad
if name in grads_dict:
# Add all the virtual PP rank's gradients to
# the first local virtual PP rank.
grads_dict[name][0].add_(grad)
# Append to the end for later update after cross-rank reduce.
grads_dict[name].append(grad)
else:
grads_dict[name] = [grad]

if grads_dict:
# All-reduce the gradient on the first VPP rank.
grads = [param_grad[0] for _, param_grad in grads_dict.items()]
coalesced = _flatten_dense_tensors(grads)
torch.distributed.all_reduce(
coalesced, group=parallel_state.get_pipeline_model_parallel_group()
)
for buf, synced in zip(grads, _unflatten_dense_tensors(coalesced, grads)):
buf.copy_(synced)

# Update the gradients on other VPP ranks.
for grads in grads_dict.values():
for grad in grads[1:]:
grad.copy_(grads[0])

Comment on lines +278 to +314

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.

This new function modifies a core distributed file but has no unit test coverage. A test verifying the all-reduce behavior (especially the VPP gradient aggregation logic in lines 291-313) would help prevent regressions, since bugs here would silently produce incorrect router gradients across pipeline stages.


def reset_model_temporary_tensors(config: TransformerConfig, model: List[torch.nn.Module]):
"""
Reset the temporary tensors of the model.
Expand Down Expand Up @@ -457,6 +495,9 @@ def finalize_model_grads(
if config.timers is not None:
config.timers('conditional-embedder-grads-all-reduce').stop()

if getattr(config, 'flextron', False):
_allreduce_router_grads(model, config)

# All-reduce layer-norm grads (for sequence parallelism) and non-tensor parallel modules.
if config.timers is not None:
config.timers('non-tensor-parallel-grads-all-reduce', log_level=1).start(
Expand Down
1 change: 1 addition & 0 deletions megatron/elastification/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# Copyright (c) 2026, NVIDIA CORPORATION. All rights reserved.
Loading
Loading