Skip to content
Merged
Show file tree
Hide file tree
Changes from 72 commits
Commits
Show all changes
90 commits
Select commit Hold shift + click to select a range
d50a125
Start heterogeneous CP idea prototyping
parthmannan Jul 15, 2025
676f0bf
Add current_cp_assignment and some supporting code
parthmannan Jul 16, 2025
65a24cc
Add bricks for building heterogeneous CP schedules
parthmannan Jul 16, 2025
0c5fa39
Return sub-sample per CP rank count to schedules
parthmannan Jul 17, 2025
8546b0f
Move wrapper to utils and formatting
parthmannan Jul 18, 2025
b17a2a2
Add TransformerConfig and arguments
parthmannan Jul 18, 2025
98f592a
Fix implementation issues [WIP]
parthmannan Jul 19, 2025
552bd27
Add sharding logic and packed_seq_params attribute for TE support
parthmannan Jul 21, 2025
48913d0
Protect attention shape change logic with THD assumption
parthmannan Jul 21, 2025
056055c
Add sharding logic and TODO for sync across multiple microbatches
parthmannan Jul 22, 2025
f069e0d
Merge branch 'main' of https://gitlab-master.nvidia.com/ADLR/megatron…
parthmannan Aug 13, 2025
8d34369
Updates to working milestone 1 Hybrid CP scheduling
parthmannan Aug 14, 2025
771fc21
Add SFT dataset support
parthmannan Aug 21, 2025
3a7e50a
New updates to use DataIterator wrapper
parthmannan Aug 22, 2025
bd2321d
Test scripts
parthmannan Aug 22, 2025
6a1ab4f
Minor fixes
parthmannan Aug 22, 2025
e01583a
SFT Dataset + GPT with Hybrid CP working example
parthmannan Aug 22, 2025
286129c
Remove new SFT loss calculation in favor of regular loss calc
parthmannan Aug 23, 2025
2674be8
Milestone 2: Add global batch scheduling, data movement and training
parthmannan Aug 29, 2025
3b87385
Fix for 0 seq len in data
parthmannan Sep 15, 2025
bd04cfe
Fix fill_empty_gpus workload assignment
parthmannan Sep 16, 2025
160f514
llama3 8B benchmarking script
parthmannan Sep 16, 2025
b0eb325
Bug fix
parthmannan Sep 16, 2025
eccf31d
Merge branch 'main' of ssh://gitlab-master.nvidia.com:12051/ADLR/mega…
parthmannan Sep 16, 2025
7e9fe90
Revert "ADLR/megatron-lm!3963 - SFT chat template and pad token chang…
parthmannan Sep 16, 2025
b635d15
Turn on legacy tokenizer
parthmannan Sep 16, 2025
dc8139f
chore: Format files
Sep 16, 2025
69ef399
Remove scheduled id and other finished TODO items
parthmannan Sep 16, 2025
b37e3f7
Merge branch 'pmannan/hetero_cp_test_sft' of ssh://gitlab-master.nvid…
parthmannan Sep 16, 2025
3bafa2c
Formatting and cleanup
parthmannan Sep 16, 2025
78dec32
Add copyright
parthmannan Sep 17, 2025
6b1d9c4
Start testing
parthmannan Sep 17, 2025
71c2966
chore: Format files
Sep 17, 2025
bff834c
Fix arg name in test
parthmannan Sep 18, 2025
2860324
Merge branch 'pmannan/hetero_cp_test_sft' of ssh://gitlab-master.nvid…
parthmannan Sep 18, 2025
ff5600b
Fix arg name in test
parthmannan Sep 18, 2025
7ff37e5
Update RoPE logic to handle none packed_seq_params
parthmannan Sep 18, 2025
3c1f66a
Fix test import
parthmannan Sep 18, 2025
aa6c7f7
chore: Format files
Sep 18, 2025
9d761cc
fix some bugs and support TP
xiaoyao0115 Sep 23, 2025
7d6c2b1
fix pad issue, should pad for sequence parallel when TP>1 and conside…
xiaoyao0115 Sep 23, 2025
fbdfe18
little adjustment according to comments
xiaoyao0115 Sep 24, 2025
8e6aa49
little fix to loop parameter
xiaoyao0115 Sep 25, 2025
f050f54
disable cudagraph anb fsdp when using hybrid cp
xiaoyao0115 Sep 26, 2025
1e76e8e
Add cp comm type to dynamic CP attn
parthmannan Sep 29, 2025
ab8dc81
Merge branch 'main' of ssh://gitlab-master.nvidia.com:12051/ADLR/mega…
parthmannan Sep 29, 2025
3a39a3a
Cleanup
parthmannan Sep 29, 2025
cb72e4e
Removing benchmarking scripts for MR
parthmannan Oct 2, 2025
aeb9e36
Merge branch 'main' of ssh://gitlab-master.nvidia.com:12051/ADLR/mega…
parthmannan Oct 2, 2025
6aebf37
Restore SFT dataset/tokenizer to main
parthmannan Oct 2, 2025
f5c0e76
Update pre-train script
parthmannan Oct 2, 2025
9d96178
Lint change
parthmannan Oct 2, 2025
b7aff32
chore: Format files
Oct 2, 2025
994e65f
Add assert
parthmannan Oct 3, 2025
f60bfdd
Merge branch 'pmannan/hybrid_dp_cp_feature' of ssh://gitlab-master.nv…
parthmannan Oct 3, 2025
aa6cf10
Add support for Yarn Rope
parthmannan Oct 3, 2025
f3a6e17
Add support for MultimodalRope
parthmannan Oct 3, 2025
a0fb848
General and RoPE support cleanup
parthmannan Oct 3, 2025
b0b0fab
Data sampler cleanup
parthmannan Oct 3, 2025
335994c
chore: Format files
Oct 3, 2025
ba99cad
Cleanup hybrid_cp_schedule
parthmannan Oct 3, 2025
d3c0c03
lint fixes
parthmannan Oct 3, 2025
1712980
Fix MLA + Yarn calls
parthmannan Oct 3, 2025
62817e8
chore: Format files
Oct 3, 2025
e586fa4
ProcessGroupCollection.use_mpu_process_groups() doesn't initialize dp…
kunlunl Oct 9, 2025
4221bdc
Fix num_microbatches always being 0
kunlunl Oct 9, 2025
0856c61
Raise error when not using per-token loss
kunlunl Oct 9, 2025
d2db69e
Minor fix
parthmannan Oct 9, 2025
627753b
Address comments
parthmannan Oct 16, 2025
a3b5ebe
Lint
parthmannan Oct 16, 2025
1c22f5c
chore: Format files
Oct 16, 2025
9c75535
Merge branch 'dev' of https://github.com/NVIDIA/Megatron-LM into pman…
parthmannan Oct 30, 2025
97d8224
Merge branch 'dev' of github.com:NVIDIA/Megatron-LM into pmannan/hybr…
parthmannan Nov 7, 2025
617fb17
Fix import
parthmannan Nov 8, 2025
e95ae83
Move Dataloader wrapper to core/datasets
parthmannan Nov 17, 2025
0a0339a
Formatting
parthmannan Nov 17, 2025
4af66dd
Fix conflict
parthmannan Nov 17, 2025
35a86a3
Fixes and address comments
parthmannan Nov 25, 2025
bf7e2ac
Lint fix
parthmannan Nov 25, 2025
2497931
Merge branch 'dev' of github.com:NVIDIA/Megatron-LM into pmannan/hybr…
parthmannan Nov 25, 2025
aa3858d
Lint fix
parthmannan Nov 25, 2025
60234b3
Fix TP hanging issue
kunlunl Dec 1, 2025
e2a32cb
Merge branch 'dev' of github.com:NVIDIA/Megatron-LM into pmannan/hybr…
parthmannan Dec 1, 2025
0ba6f2c
Packed seq in DSA arg match
parthmannan Dec 1, 2025
d53c323
Lint
parthmannan Dec 1, 2025
66404ca
Mamba script fix
parthmannan Dec 3, 2025
70b9758
Merge branch 'dev' of github.com:NVIDIA/Megatron-LM into pmannan/hybr…
parthmannan Dec 4, 2025
9387269
API check fix
parthmannan Dec 4, 2025
2bde6c8
API check parallel_state
parthmannan Dec 4, 2025
604ddd2
Merge branch 'dev' of github.com:NVIDIA/Megatron-LM into pmannan/hybr…
parthmannan Dec 4, 2025
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
18 changes: 18 additions & 0 deletions megatron/core/datasets/gpt_dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,24 @@ class GPTDatasetConfig(BlendedMegatronDatasetConfig):
object_storage_cache_path: Optional[str] = None
"""Path for caching indices for s3 or msc dataloading."""

context_parallel_size: int = 1
"""Option to enable context parallelism"""

data_parallel_size: int = 1
"""Option to enable data parallelism"""

sequence_parallel_size: int = 0
"""Option to indicate the sequence parallelism size when using TP
Set to 0 if sequence parallel is not enabled regardless of TP size.
"""

hybrid_context_parallel: bool = False
"""Option to enable hybrid context parallelism. When setting this to True,
each sample should be divisible by the data parallel size * context parallel size * 2.
If sequence parallel is enabled, it should be divisible by the
data parallel size * context parallel size * sequence parallel size * 2.
"""

Comment thread
parthmannan marked this conversation as resolved.
Resolved
def __post_init__(self) -> None:
"""Do asserts and set fields post init"""
super().__post_init__()
Expand Down
20 changes: 20 additions & 0 deletions megatron/core/extensions/transformer_engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -976,6 +976,7 @@ def __init__(
self.kept_packed_seq_params = set(
field.name for field in dataclasses.fields(PackedSeqParams)
)

if get_te_version() < PkgVersion("1.3.0"):
# TE 1.3.0 introduces precomputing max_seqlen to remove unnecessary kernels and D2H
# copies (#555)
Expand Down Expand Up @@ -1018,6 +1019,25 @@ def forward(
packed_seq_params: PackedSeqParams = None,
):
"""Forward."""
if packed_seq_params is not None:
# If Dynamic CP group is provided, update TE DPA CP group
if packed_seq_params.cp_group is not None:
self.cp_group = packed_seq_params.cp_group
super().set_context_parallel_group(
self.cp_group,
torch.distributed.get_process_group_ranks(self.cp_group),
TEDotProductAttention.cp_stream,
self.cp_comm_type,
)
# If cp_group is None but local_cp_size is provided,
# Indicates to turn off CP dynamically
elif packed_seq_params.local_cp_size is not None:
assert (
packed_seq_params.local_cp_size == 1
), "local_cp_size must be == 1 if provided without cp_group"
super().set_context_parallel_group(None, None, None, self.cp_comm_type)
self.kept_packed_seq_params.discard("cp_group")
self.kept_packed_seq_params.discard("local_cp_size")
packed_seq_kwargs = (
{key: getattr(packed_seq_params, key) for key in self.kept_packed_seq_params}
if packed_seq_params is not None
Expand Down
16 changes: 16 additions & 0 deletions megatron/core/model_parallel_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,22 @@ class ModelParallelConfig:
type.
"""

max_seqlen_per_dp_cp_rank: Optional[int] = None
"""
Maximum sequence length per DPxCP rank. This is the maximum sequence length each rank
can handle without overflowing the memory. Typically, a good starting point is to set this
to maximum sequence length / context parallel size.
This is used to calculate the number and length of sub-samples assigned to
each rank when using hybrid_context_parallel.
"""

hybrid_context_parallel: bool = False
"""
If true, enables hybrid context parallel. This is used to balance the workload of
each CP rank when we use packed samples with variable sequence lengths.
Please set max_seqlen_per_dp_cp_rank when using hybrid_context_parallel.
"""

expert_model_parallel_size: int = 1
"""Distributes Moe Experts across sub data parallel dimension."""

Expand Down
62 changes: 52 additions & 10 deletions megatron/core/models/common/embeddings/rotary_pos_embedding.py
Original file line number Diff line number Diff line change
Expand Up @@ -148,13 +148,12 @@ def get_cos_sin(self, max_seq_len: int, offset: int = 0) -> (Tensor, Tensor):
return cos, sin

@lru_cache(maxsize=32)
def forward(self, max_seq_len: int, offset: int = 0, packed_seq: bool = False) -> Tensor:
"""Forward pass of RoPE embedding.
def get_emb(self, max_seq_len: int, offset: int = 0) -> Tensor:
"""Forward pass of RoPE embedding before CP sharding.

Args:
max_seq_len (int): Maximum size of sequence
offset (int, optional): RoPE offset. Defaults to 0.
packed_seq (bool, optional): Whether to use packed sequence. Defaults to False.

Returns:
Tensor: Embeddings after applying RoPE.
Expand All @@ -174,10 +173,38 @@ def forward(self, max_seq_len: int, offset: int = 0, packed_seq: bool = False) -
)
# emb [seq_length, .., dim]
emb = emb[:, None, None, :]
if self.cp_group is not None and self.cp_group.size() > 1 and not packed_seq:
# slice rotary_pos_emb along sequence dimension and select the parition of the current
# CP rank
emb = get_pos_emb_on_this_cp_rank(emb, 0, self.cp_group)
return emb

def forward(
self, max_seq_len: int, offset: int = 0, packed_seq_params: Optional[PackedSeqParams] = None
) -> Tensor:
"""Forward pass of RoPE embedding.

Args:
max_seq_len (int): Maximum size of sequence
offset (int, optional): RoPE offset. Defaults to 0.
packed_seq_params (PackedSeqParams, optional): Packed sequence params. Defaults to None.

Returns:
Tensor: Embeddings after applying RoPE.
"""
emb = self.get_emb(max_seq_len, offset)
packed_seq = packed_seq_params is not None and packed_seq_params.qkv_format == 'thd'
if packed_seq_params is not None and packed_seq_params.local_cp_size is not None:
if packed_seq_params.local_cp_size > 1:
# Set CP group to dynamic CP group for CP slicing
cp_group = packed_seq_params.cp_group
else:
Comment thread
parthmannan marked this conversation as resolved.
Resolved
# Set CP group to None to avoid CP slicing
cp_group = None
else:
cp_group = self.cp_group

if cp_group is not None and cp_group.size() > 1 and not packed_seq:
Comment thread
kunlunl marked this conversation as resolved.
Resolved
# slice rotary_pos_emb along sequence dimension
# and select the parition of the current CP rank
emb = get_pos_emb_on_this_cp_rank(emb, 0, cp_group)

return emb

def _load_from_state_dict(self, state_dict, prefix, *args, **kwargs):
Expand Down Expand Up @@ -279,13 +306,19 @@ def __init__(
else parallel_state.get_context_parallel_group(check_initialized=False)
)

def forward(self, position_ids: torch.Tensor, mrope_section: List[int]) -> Tensor:
def forward(
self,
position_ids: torch.Tensor,
mrope_section: List[int],
packed_seq_params: Optional[PackedSeqParams] = None,
) -> Tensor:
"""Forward pass of multimodal RoPE embedding.

Args:
position_ids (torch.Tensor): A postion_id tensor with shape [3, batchsize, seqlens]
mrope_section (list[int]): Multimodal rope section is for channel dimension of temporal,
height and width in rope calculation.
packed_seq_params (PackedSeqParams, optional): Packed sequence params. Defaults to None.

Returns:
Tensor: Embeddings after applying RoPE.
Expand Down Expand Up @@ -318,8 +351,17 @@ def forward(self, position_ids: torch.Tensor, mrope_section: List[int]) -> Tenso

# shape (seq_length, bs, 1, 2 * dim)
emb = emb[..., None, :].transpose(0, 1).contiguous()
if self.cp_group is not None and self.cp_group.size() > 1:
if packed_seq_params is not None and packed_seq_params.local_cp_size is not None:
if packed_seq_params.local_cp_size > 1:
# Set CP group to dynamic CP group for CP slicing
cp_group = packed_seq_params.cp_group
else:
# Set CP group to None to avoid CP slicing
cp_group = None
else:
cp_group = self.cp_group
if cp_group is not None and cp_group.size() > 1:
# slice rotary_pos_emb along sequence dimension and select the parition of the current
# CP rank
emb = get_pos_emb_on_this_cp_rank(emb, 0, self.cp_group)
emb = get_pos_emb_on_this_cp_rank(emb, 0, cp_group)
return emb
Original file line number Diff line number Diff line change
Expand Up @@ -99,13 +99,12 @@ def __init__(
)

@lru_cache(maxsize=32)
def forward(self, max_seq_len: int, offset: int = 0, packed_seq: bool = False) -> Tensor:
def get_emb(self, max_seq_len: int, offset: int = 0) -> Tensor:
"""Forward pass of Yarn Rotary Embedding.

Args:
max_seq_len (int): Maximum size of sequence
offset (int, optional): RoPE offset. Defaults to 0.
packed_seq (bool, optional): Whether to use packed sequence. Defaults to False.

Returns:
Tensor: Embeddings after applying Yarn RoPE.
Expand Down Expand Up @@ -151,19 +150,47 @@ def forward(self, max_seq_len: int, offset: int = 0, packed_seq: bool = False) -
emb = torch.cat((freqs, freqs), dim=-1)
# emb [seq_length, .., dim]
emb = emb[:, None, None, :]
if self.cp_group is not None and self.cp_group.size() > 1 and not packed_seq:
return emb, _mscale

def forward(
self, max_seq_len: int, offset: int = 0, packed_seq_params: Optional[PackedSeqParams] = None
) -> Tensor:
"""Forward pass of Yarn Rotary Embedding.

Args:
max_seq_len (int): Maximum size of sequence
offset (int, optional): RoPE offset. Defaults to 0.
packed_seq_params (PackedSeqParams, optional): Packed sequence params. Defaults to None.

Returns:
Tensor: Embeddings after applying Yarn RoPE.
"""
emb, _mscale = self.get_emb(max_seq_len, offset)
packed_seq = packed_seq_params is not None and packed_seq_params.qkv_format == 'thd'
if packed_seq_params is not None and packed_seq_params.local_cp_size is not None:
if packed_seq_params.local_cp_size > 1:
# Set CP group to dynamic CP group for CP slicing
cp_group = packed_seq_params.cp_group
else:
# Set CP group to None to avoid CP slicing
cp_group = None
else:
cp_group = self.cp_group
if cp_group is not None and cp_group.size() > 1 and not packed_seq:
# slice rotary_pos_emb along sequence dimension
# and select the parition of the current CP rank
emb = get_pos_emb_on_this_cp_rank(emb, 0, self.cp_group)
emb = get_pos_emb_on_this_cp_rank(emb, 0, cp_group)
return emb, _mscale

def _set_cos_sin_cache(self, seq_len, offset, dtype, packed_seq=False):
def _set_cos_sin_cache(self, seq_len, offset, dtype, packed_seq_params=None):
self.max_seq_len_cached = seq_len
self.offset_cached = offset
self.dtype_cached = dtype
self.packed_seq_cached = packed_seq
self.packed_seq_cached = (
packed_seq_params is not None and packed_seq_params.qkv_format == 'thd'
)

emb, _mscale = self.forward(seq_len, offset, packed_seq)
emb, _mscale = self.forward(seq_len, offset, packed_seq_params)
self.register_buffer(
"cos_cached", (emb.cos() * _mscale).to(dtype).contiguous(), persistent=False
)
Expand All @@ -172,16 +199,17 @@ def _set_cos_sin_cache(self, seq_len, offset, dtype, packed_seq=False):
)

def get_cached_cos_sin(
self, seq_len, offset=0, dtype=torch.get_default_dtype(), packed_seq=False
self, seq_len, offset=0, dtype=torch.get_default_dtype(), packed_seq_params=None
):
"""Get cached cos and sin values."""
packed_seq = packed_seq_params is not None and packed_seq_params.qkv_format == 'thd'
if (
seq_len > self.max_seq_len_cached
or offset != self.offset_cached
or dtype != self.dtype_cached
or packed_seq != self.packed_seq_cached
):
self._set_cos_sin_cache(seq_len, offset, dtype, packed_seq)
self._set_cos_sin_cache(seq_len, offset, dtype, packed_seq_params)
return (self.cos_cached[:seq_len, ...], self.sin_cached[:seq_len, ...])


Expand Down
12 changes: 7 additions & 5 deletions megatron/core/models/gpt/gpt_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -345,24 +345,26 @@ def _preprocess(
inference_context, self.decoder, decoder_input, self.config, packed_seq_params
)
rotary_pos_emb = self.rotary_pos_emb(
rotary_seq_len,
packed_seq=packed_seq_params is not None
and packed_seq_params.qkv_format == 'thd',
rotary_seq_len, packed_seq_params=packed_seq_params
)
elif self.position_embedding_type == 'yarn':
if self.training or not self.config.flash_decode:
rotary_seq_len = self.rotary_pos_emb.get_rotary_seq_len(
inference_context, self.decoder, decoder_input, self.config, packed_seq_params
)
rotary_pos_emb, _ = self.rotary_pos_emb(rotary_seq_len)
rotary_pos_emb, _ = self.rotary_pos_emb(
rotary_seq_len, packed_seq_params=packed_seq_params
)
else:
raise NotImplementedError(
"Flash decoding uses precomputed cos and sin for RoPE, not implemented in "
"YarnRotaryEmbedding yet."
)
elif self.position_embedding_type == 'mrope' and not self.config.multi_latent_attention:
if self.training or not self.config.flash_decode:
rotary_pos_emb = self.rotary_pos_emb(position_ids, self.mrope_section)
rotary_pos_emb = self.rotary_pos_emb(
position_ids, self.mrope_section, packed_seq_params=packed_seq_params
)
else:
# Flash decoding uses precomputed cos and sin for RoPE
raise NotImplementedError(
Expand Down
3 changes: 3 additions & 0 deletions megatron/core/packed_seq_params.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved.
from dataclasses import dataclass

import torch.distributed as dist
from torch import Tensor


Expand All @@ -18,3 +19,5 @@ class PackedSeqParams:
cu_seqlens_kv_padded: Tensor = None
max_seqlen_q: int = None
max_seqlen_kv: int = None
local_cp_size: int = None
cp_group: dist.ProcessGroup = None
Loading