Skip to content
Merged
Show file tree
Hide file tree
Changes from 27 commits
Commits
Show all changes
34 commits
Select commit Hold shift + click to select a range
9ac259b
[DRAFT] Refactor provider_bridge for Llama and Qwen models
yaoyu-33 Jan 23, 2026
ab8a5e4
refactor(bridge): Introduce MLAModelProvider for DeepSeek/Kimi MLA mo…
yaoyu-33 Jan 23, 2026
0a12eb7
refactor(bridge): Refactor Gemma bridges to use specialized providers
yaoyu-33 Jan 24, 2026
aa54966
Merge branch 'main' into feature/provider-bridge-refactor
yaoyu-33 Jan 24, 2026
4ade385
update
yaoyu-33 Jan 26, 2026
3ec0b0a
remove MEGATRON_DEFAULTS
yaoyu-33 Jan 26, 2026
c100b4a
remove testing scripts
yaoyu-33 Jan 26, 2026
3c709c5
yarn fix
yaoyu-33 Jan 26, 2026
9eb8542
clean ups
yaoyu-33 Jan 27, 2026
2cc3b35
fix
yaoyu-33 Jan 27, 2026
ca54e4f
fix unit tests
yaoyu-33 Jan 27, 2026
1ed2069
unit test fix
yaoyu-33 Jan 27, 2026
9facb3e
functional test fix
yaoyu-33 Jan 27, 2026
b753ab8
code rabbit
yaoyu-33 Jan 27, 2026
ab24acf
fix functional tests
yaoyu-33 Jan 28, 2026
b6f8e29
remove KimiK2Bridge from init
yaoyu-33 Jan 28, 2026
167055a
clean up deprecated functional tests
yaoyu-33 Jan 28, 2026
22a6321
Merge branch 'main' into feature/provider-bridge-refactor
yaoyu-33 Feb 2, 2026
f9a3231
olmoe update
yaoyu-33 Feb 3, 2026
d5b7890
Fix kv_channels calculation for OLMoE bridge
yaoyu-33 Feb 3, 2026
ada7d05
fix: always set yarn params with None defaults for MCoreGPTModel comp…
yaoyu-33 Feb 3, 2026
5f24f9b
Merge branch 'main' into feature/provider-bridge-refactor
yaoyu-33 Feb 3, 2026
057175f
lint
yaoyu-33 Feb 3, 2026
54e0971
Merge branch 'main' into feature/provider-bridge-refactor-2
yaoyu-33 Feb 4, 2026
6c6a3b9
nemotron H bridge update
yaoyu-33 Feb 4, 2026
0c94698
nemotron bridge update
yaoyu-33 Feb 4, 2026
4d827e6
nemotron bridge update
yaoyu-33 Feb 5, 2026
db38206
Merge branch 'main' into feature/provider-bridge-refactor-2
yaoyu-33 Feb 5, 2026
9618f91
fix: remove generation_config from GPTModelProvider and tests
yaoyu-33 Feb 5, 2026
2b0bb06
Merge branch 'main' into feature/provider-bridge-refactor-2
yaoyu-33 Feb 5, 2026
58b2c6e
fix: remove additional generation_config tests from bridge test files
yaoyu-33 Feb 5, 2026
2310230
fix: add relu2 activation support and fix Nemotron/NemotronH tests
yaoyu-33 Feb 5, 2026
77a567b
fix: update Nemotron bridge tests for correct provider types
yaoyu-33 Feb 5, 2026
dabe9d5
remove deprecated provider test
yaoyu-33 Feb 5, 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
352 changes: 328 additions & 24 deletions src/megatron/bridge/models/conversion/model_bridge.py

Large diffs are not rendered by default.

1 change: 0 additions & 1 deletion src/megatron/bridge/models/deepseek/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,6 @@ def get_common_configs(hf_pretrained: PreTrainedCausalLM) -> dict:

# Ensure MLA is enabled
configs["multi_latent_attention"] = True
configs["generation_config"] = hf_pretrained.generation_config
configs["vocab_size"] = hf_config.vocab_size
configs["rotary_base"] = hf_config.rope_theta
configs["init_method_std"] = hf_config.initializer_range
Expand Down
214 changes: 52 additions & 162 deletions src/megatron/bridge/models/deepseek/deepseek_provider.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,110 +13,57 @@
# limitations under the License.
import warnings
from dataclasses import dataclass, field
from functools import partial
from typing import TYPE_CHECKING, Callable, List, Optional, Union
from typing import Callable, List, Optional, Union

import torch
import torch.nn.functional as F
from megatron.core.models.gpt.gpt_layer_specs import get_gpt_decoder_block_spec

from megatron.bridge.models.gpt_provider import GPTModelProvider
from megatron.bridge.models.transformer_config import MLATransformerConfig
from megatron.bridge.models.mla_provider import MLAModelProvider
from megatron.bridge.utils.common_utils import get_rank_safe


try:
import transformer_engine # type: ignore # noqa: F401

HAVE_TE = True
except (ImportError, ModuleNotFoundError):
HAVE_TE = False

if TYPE_CHECKING:
from megatron.core.transformer import ModuleSpec

if HAVE_TE:
from megatron.core.utils import is_te_min_version
def _warn_deprecated(old_cls: str, new_cls: str = "MLAModelProvider") -> None:
if get_rank_safe() == 0:
warnings.warn(
f"{old_cls} is deprecated and will be removed in a future release. "
f"Use {new_cls} with MEGATRON_DEFAULTS in the bridge instead.",
DeprecationWarning,
stacklevel=3,
)


@dataclass
class DeepSeekModelProvider(MLATransformerConfig, GPTModelProvider):
"""
Base config for DeepSeek V2 and V3 models.
"""
class DeepSeekModelProvider(MLAModelProvider):
"""Deprecated alias for ``MLAModelProvider``.

transformer_layer_spec: Union["ModuleSpec", Callable[["GPTModelProvider"], "ModuleSpec"]] = partial(
get_gpt_decoder_block_spec, use_transformer_engine=HAVE_TE
)
Deprecated:
This alias remains for backward compatibility and will be removed in a
future release. Use ``MLAModelProvider`` instead.
"""

# Model
# Common DeepSeek defaults
normalization: str = "RMSNorm"
activation_func: Callable = F.silu
gated_linear_unit: bool = True # swiglu
gated_linear_unit: bool = True
position_embedding_type: str = "rope"
add_bias_linear: bool = False
share_embeddings_and_output_weights: bool = False
num_attention_heads: int = 128
kv_channels: int = 128
max_position_embeddings: int = 4096
seq_length: int = 4096
rotary_base: float = 10000.0
make_vocab_size_divisible_by: int = 3200
mtp_num_layers: Optional[int] = None
mtp_loss_scaling_factor: Optional[float] = None

# Regularization
attention_dropout: float = 0.0
hidden_dropout: float = 0.0
qk_layernorm: bool = True

# MoE
bf16: bool = True
params_dtype: torch.dtype = torch.bfloat16
moe_grouped_gemm: bool = True
moe_router_pre_softmax: bool = True
moe_token_dispatcher_type: str = "alltoall"
moe_router_load_balancing_type: str = "seq_aux_loss"
moe_shared_expert_overlap: bool = True
moe_router_dtype: Optional[str] = "fp32"

# MLA
q_lora_rank: int = 1536
# MLA defaults
q_lora_rank: Optional[int] = 1536
kv_lora_rank: int = 512
qk_head_dim: int = 128
qk_pos_emb_head_dim: int = 64
v_head_dim: int = 128
rotary_scaling_factor: float = 40
mscale: float = 1.0
mscale_all_dim: float = 1.0

# Miscellaneous
init_method_std: float = 0.006
layernorm_epsilon: float = 1e-6
bf16: bool = True
params_dtype: torch.dtype = torch.bfloat16
async_tensor_model_parallel_allreduce: bool = True
attention_softmax_in_fp32: bool = False
persist_layer_norm: bool = True
num_layers_in_first_pipeline_stage: Optional[int] = None
num_layers_in_last_pipeline_stage: Optional[int] = None
account_for_embedding_in_pipeline_split: bool = False
account_for_loss_in_pipeline_split: bool = False

# MLA specific
multi_latent_attention: bool = True

# fusions
apply_rope_fusion: bool = False
bias_activation_fusion: bool = True
bias_dropout_fusion: bool = True
masked_softmax_fusion: bool = True
gradient_accumulation_fusion: bool = True
cross_entropy_loss_fusion: bool = True
cross_entropy_fusion_impl: str = "te"
moe_permute_fusion: bool = is_te_min_version("2.1.0") if HAVE_TE else False
def __post_init__(self) -> None:
_warn_deprecated("DeepSeekModelProvider")
super().__post_init__()


@dataclass
class DeepSeekV2ModelProvider(DeepSeekModelProvider):
class DeepSeekV2ModelProvider(MLAModelProvider):
"""
DeepSeek-V2 Model: https://github.com/deepseek-ai/DeepSeek-V2
"""
Expand All @@ -137,9 +84,13 @@ class DeepSeekV2ModelProvider(DeepSeekModelProvider):
mscale_all_dim: float = 0.707
vocab_size: int = 102400

def __post_init__(self) -> None:
_warn_deprecated("DeepSeekV2ModelProvider")
super().__post_init__()


@dataclass
class DeepSeekV2LiteModelProvider(DeepSeekV2ModelProvider):
class DeepSeekV2LiteModelProvider(MLAModelProvider):
"""
DeepSeek-V2-Lite Model: https://github.com/deepseek-ai/DeepSeek-V2
HuggingFace: https://huggingface.co/deepseek-ai/DeepSeek-V2-Lite
Expand All @@ -150,7 +101,7 @@ class DeepSeekV2LiteModelProvider(DeepSeekV2ModelProvider):
ffn_hidden_size: int = 10944
num_attention_heads: int = 16
kv_channels: int = 16
q_lora_rank: int = None
q_lora_rank: Optional[int] = None
num_moe_experts: int = 64
moe_ffn_hidden_size: int = 1408
moe_shared_expert_intermediate_size: int = 2816 # 1408 * 2 shared experts
Expand All @@ -159,18 +110,25 @@ class DeepSeekV2LiteModelProvider(DeepSeekV2ModelProvider):
moe_router_num_groups: int = 1
moe_router_group_topk: int = 1
moe_router_topk_scaling_factor: float = 1.0
mscale: float = 0.707
mscale_all_dim: float = 0.707
vocab_size: int = 102400

def __post_init__(self) -> None:
_warn_deprecated("DeepSeekV2LiteModelProvider")
super().__post_init__()


@dataclass
class DeepSeekV3ModelProvider(DeepSeekModelProvider):
class DeepSeekV3ModelProvider(MLAModelProvider):
"""
DeepSeek-V3 Model: https://github.com/deepseek-ai/DeepSeek-V3
"""

num_layers: int = 61
hidden_size: int = 7168
ffn_hidden_size: int = 18432
kv_channels: int = 128
num_moe_experts: int = 256
moe_ffn_hidden_size: int = 2048
moe_shared_expert_intermediate_size: int = 2048 # 2048 * 1 shared expert
Expand All @@ -190,9 +148,13 @@ class DeepSeekV3ModelProvider(DeepSeekModelProvider):
mscale_all_dim: float = 1.0
vocab_size: int = 129280

def __post_init__(self) -> None:
_warn_deprecated("DeepSeekV3ModelProvider")
super().__post_init__()


@dataclass
class MoonlightModelProvider16B(DeepSeekModelProvider):
class MoonlightModelProvider16B(MLAModelProvider):
"""
Moonlight-16B-A3B Model: https://github.com/moonshotai/Moonlight-16B-A3B

Expand Down Expand Up @@ -228,86 +190,14 @@ class MoonlightModelProvider16B(DeepSeekModelProvider):
rotary_percent: float = 1.0
vocab_size: int = 163842


# -----------------------------------------------------------------------------
# Deprecated aliases (to be removed in a future release)
# -----------------------------------------------------------------------------


def _warn_deprecated(old_cls: str, new_cls: str) -> None:
if get_rank_safe() == 0:
warnings.warn(
f"{old_cls} is deprecated and will be removed in a future release. Use {new_cls} instead.",
DeprecationWarning,
stacklevel=2,
)


@dataclass
class DeepSeekProvider(DeepSeekModelProvider):
"""Deprecated alias for ``DeepSeekModelProvider``.

Deprecated:
This alias remains for backward compatibility and will be removed in a
future release. Import and use ``DeepSeekModelProvider`` instead.
"""

def __post_init__(self) -> None:
_warn_deprecated("DeepSeekProvider", "DeepSeekModelProvider")
super().__post_init__()


@dataclass
class DeepSeekV2Provider(DeepSeekV2ModelProvider):
"""Deprecated alias for ``DeepSeekV2ModelProvider``.

Deprecated:
This alias remains for backward compatibility and will be removed in a
future release. Import and use ``DeepSeekV2ModelProvider`` instead.
"""

def __post_init__(self) -> None:
_warn_deprecated("DeepSeekV2Provider", "DeepSeekV2ModelProvider")
super().__post_init__()


@dataclass
class DeepSeekV2LiteProvider(DeepSeekV2LiteModelProvider):
"""Deprecated alias for ``DeepSeekV2LiteModelProvider``.

Deprecated:
This alias remains for backward compatibility and will be removed in a
future release. Import and use ``DeepSeekV2LiteModelProvider`` instead.
"""

def __post_init__(self) -> None:
_warn_deprecated("DeepSeekV2LiteProvider", "DeepSeekV2LiteModelProvider")
_warn_deprecated("MoonlightModelProvider16B")
super().__post_init__()


@dataclass
class DeepSeekV3Provider(DeepSeekV3ModelProvider):
"""Deprecated alias for ``DeepSeekV3ModelProvider``.

Deprecated:
This alias remains for backward compatibility and will be removed in a
future release. Import and use ``DeepSeekV3ModelProvider`` instead.
"""

def __post_init__(self) -> None:
_warn_deprecated("DeepSeekV3Provider", "DeepSeekV3ModelProvider")
super().__post_init__()


@dataclass
class MoonlightProvider(MoonlightModelProvider16B):
"""Deprecated alias for ``MoonlightModelProvider16B``.

Deprecated:
This alias remains for backward compatibility and will be removed in a
future release. Import and use ``MoonlightModelProvider16B`` instead.
"""

def __post_init__(self) -> None:
_warn_deprecated("MoonlightProvider", "MoonlightModelProvider16B")
super().__post_init__()
# Legacy aliases for backward compatibility
DeepSeekProvider = DeepSeekModelProvider
DeepSeekV2Provider = DeepSeekV2ModelProvider
DeepSeekV2LiteProvider = DeepSeekV2LiteModelProvider
DeepSeekV3Provider = DeepSeekV3ModelProvider
MoonlightProvider = MoonlightModelProvider16B
Loading