Repository navigation
Expand file tree
/
Copy pathmodel_bridge.py
More file actions
2912 lines (2493 loc) · 134 KB
/
Copy pathmodel_bridge.py
File metadata and controls
2912 lines (2493 loc) · 134 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import abc
import contextlib
import fnmatch
import gc
import itertools
import logging
import math
import re
import warnings
from dataclasses import dataclass, field, fields, is_dataclass
from pathlib import Path
from typing import (
Any,
Callable,
ClassVar,
Dict,
Generic,
Iterable,
List,
Literal,
Mapping,
NamedTuple,
Optional,
Tuple,
Type,
TypeVar,
Union,
cast,
)
import torch
from megatron.core import parallel_state
from megatron.core.pipeline_parallel.utils import is_pp_first_stage, is_pp_last_stage
from megatron.core.transformer.module import MegatronModule
from megatron.core.transformer.transformer_config import TransformerConfig
from megatron.core.utils import get_pg_size
from megatron.training.models.base import ModelConfig
from rich.progress import BarColumn, Progress, TextColumn, TimeRemainingColumn
from torch.distributed._tensor import DTensor
from transformers.configuration_utils import PretrainedConfig
from transformers.modeling_utils import PreTrainedModel
from megatron.bridge.models.common import ModelConfigOverrideMixin
from megatron.bridge.models.conversion.fp8_export import (
FP8ExportLayout,
detect_fp8_export_layout,
get_fp8_export_tensors,
)
from megatron.bridge.models.conversion.gtp import (
_gather_gtp_weight,
_get_mapping_shape,
_gtp_weight_load_context,
_is_gtp_param,
_slice_gtp_weight,
)
from megatron.bridge.models.conversion.mapping_registry import MegatronMappingRegistry
from megatron.bridge.models.conversion.param_mapping import (
LocalHFParam,
LocalHFParamSpec,
MegatronParamMapping,
)
from megatron.bridge.models.conversion.peft_bridge import (
AdapterWeight,
AdapterWeightConversionTask,
MegatronPeftBridge,
)
from megatron.bridge.models.conversion.quant_bridge import MegatronQuantizationBridge
from megatron.bridge.models.conversion.transformers_compat import (
rope_theta_from_hf,
)
from megatron.bridge.models.conversion.utils import (
extract_sort_key,
get_module_and_param_from_name,
persistent_buffers,
unwrap_model,
)
from megatron.bridge.models.decorators.dispatch import dispatch
from megatron.bridge.models.gpt.model_config import BridgeGPTModelConfig
from megatron.bridge.models.hf_pretrained.causal_lm import PreTrainedCausalLM
from megatron.bridge.models.model_provider import ModelProviderMixin
from megatron.bridge.models.transformer_config import TransformerConfig as BridgeTransformerConfig
from megatron.bridge.utils import fusions
from megatron.bridge.utils.activation_map import ACTIVATION_FUNC_MAP
from megatron.bridge.utils.common_utils import print_rank_0
logger = logging.getLogger(__name__)
MappingT = TypeVar("MappingT", bound=MegatronParamMapping)
HFPreTrained = TypeVar("HFPreTrained")
ModelProviderTarget = TypeVar("ModelProviderTarget", bound=ModelProviderMixin)
MegatronModel = TypeVar("MegatronModel", bound=MegatronModule)
_BridgeImplClass = TypeVar("_BridgeImplClass", bound="MegatronModelBridge")
class ModelConfigNotSupportedError(NotImplementedError):
"""Raised when a bridge has no builder-backed model config path."""
class MegatronWeightTuple(NamedTuple):
"""Tuple representing a Megatron model weight with its metadata."""
param_name: str
weight: torch.Tensor
vp_stage: int
class HFWeightTuple(NamedTuple):
"""Tuple representing a HuggingFace model weight with its metadata."""
param_name: str
weight: torch.Tensor
def iter_finalized(
self,
*,
cpu: bool,
export_hook: Callable[[str, torch.Tensor], Iterable["HFWeightTuple"]] | None = None,
clone_identity_output: bool = False,
megatron_param_names: tuple[str, ...] | None = None,
) -> Iterable["HFWeightTuple | HFSourcedWeightTuple"]:
"""Apply an optional export hook and yield finalized weights.
Export hooks run on a detached tensor before final device placement and may
emit zero, one, or multiple weights. Identity outputs can optionally be
cloned so independently named tied weights do not share storage.
Args:
cpu: Whether to move exported tensors to CPU.
export_hook: Optional transformation applied before device placement.
clone_identity_output: Clone an output when it is the detached input.
megatron_param_names: When given (possibly empty), yield :class:`HFSourcedWeightTuple`
carrying these source Megatron parameter names next to each exported weight.
Yields:
Finalized HuggingFace weights in export-hook order.
"""
source_tensor = self.weight.detach()
exported_weights = (
export_hook(self.param_name, source_tensor)
if export_hook is not None
else ((self.param_name, source_tensor),)
)
for exported_name, exported_tensor in exported_weights:
is_identity_output = exported_tensor is source_tensor
exported_tensor = exported_tensor.detach()
if clone_identity_output and is_identity_output:
exported_tensor = exported_tensor.clone().detach()
exported_tensor = exported_tensor.cpu() if cpu else exported_tensor
if megatron_param_names is not None:
yield HFSourcedWeightTuple(exported_name, exported_tensor, megatron_param_names)
else:
yield HFWeightTuple(exported_name, exported_tensor)
class HFSourcedWeightTuple(NamedTuple):
"""A :class:`HFWeightTuple` that also names the Megatron parameters it was exported from.
Only produced when a streaming export is called with ``with_megatron_names=True``;
the default export keeps yielding plain two-field :class:`HFWeightTuple` values so
``for name, weight in ...`` unpacking keeps working for existing callers.
``megatron_param_names`` holds the unwrapped local Megatron parameter names of the
conversion tasks behind the weight, in accumulation order:
* one name for a weight converted from a single Megatron parameter (for adapters,
the ``linear_in`` / ``linear_out`` weight name);
* one name per contributing per-expert task for a grouped-expert export that packs
several Megatron parameters into one HF tensor;
* no names for HF-only passthrough tensors that a bridge copies from the source
checkpoint without any Megatron counterpart.
"""
param_name: str
weight: torch.Tensor
megatron_param_names: tuple[str, ...]
@property
def megatron_param_name(self) -> str | None:
"""The single source Megatron parameter name, or ``None`` for zero or several sources."""
return self.megatron_param_names[0] if len(self.megatron_param_names) == 1 else None
@dataclass(frozen=True)
class WeightConversionTask(Generic[MappingT]):
"""A unified task for converting weights between HuggingFace and Megatron formats.
This class combines both HF->Megatron and Megatron->HF conversion tasks since they
have different method names (hf_to_megatron vs megatron_to_hf) and can coexist safely.
The task encapsulates all information needed for weight conversion in either direction,
with different fields being relevant depending on the conversion type.
Attributes:
param_name (str): *unwrapped, local* parameter name (no ``module.`` prefixes).
global_param_name (str): *unwrapped, global* parameter name (no ``module.`` prefixes).
mapping (MappingT): Concrete :pyclass:`MegatronParamMapping` instance responsible
for weight transformation and distribution.
pp_rank (Optional[int]): Pipeline-parallel rank that owns the parameter (required for saves).
vp_stage (Optional[int]): Virtual-pipeline stage index (required for loads).
megatron_module (Optional[torch.nn.Module]): Reference to the Megatron model or
sub-module that owns the parameter (required for loads).
param_weight (Optional[torch.Tensor]): The actual parameter tensor that will
receive the converted weight (required for loads).
weight_dtype (Optional[torch.dtype]): Export only. Cast float weights to this
dtype; bridges that requantize on export skip it (no scale companions).
export_hook: Export-only transformation applied after mapping conversion and
before final device placement.
required_hf_param_names: Import-only source tensors consumed by the loading
hook. Defaults to the parameter names declared by ``mapping.hf_param``.
"""
param_name: str
global_param_name: str
mapping: MappingT
pp_rank: Optional[int] = None
vp_stage: Optional[int] = None
megatron_module: Optional[torch.nn.Module] = None
param_weight: Optional[torch.Tensor] = None
weight_dtype: Optional[torch.dtype] = None
export_hook: Optional[Callable[[str, torch.Tensor], Iterable[HFWeightTuple]]] = field(
default=None, compare=False, repr=False
)
required_hf_param_names: tuple[str, ...] | None = field(default=None, compare=False)
@property
def hf_param_names(self) -> tuple[str, ...]:
"""HF tensors required to import this Megatron parameter."""
if self.required_hf_param_names is not None:
return self.required_hf_param_names
hf_param = self.mapping.hf_param
names = (hf_param,) if isinstance(hf_param, str) else tuple(hf_param.values())
return tuple(dict.fromkeys(names))
def local_hf_param_specs(self) -> tuple[LocalHFParamSpec, ...]:
"""Return this parameter's canonical local HF-compatible views.
An empty tuple means the caller must use the normal Bridge conversion
path; it does not declare the model unsupported for HF conversion or
M-to-N refit. Destination backend and topology compatibility are outside
this per-parameter contract, including whether MXFP8 is transferred as
qualified physical data/scales or requantized from a logical view.
"""
return self.mapping.local_hf_param_specs(self.global_param_name)
def combine_local_hf_weights(self, weights: Mapping[str, torch.Tensor]) -> torch.Tensor:
"""Reassemble transferred local HF views into this Megatron parameter."""
specs = self.local_hf_param_specs()
if not specs:
raise ValueError(f"{self.param_name!r} has no local HF parameter views.")
if len(specs) == 1:
return weights[specs[0].name]
split_dims = {spec.split_dim for spec in specs}
if len(split_dims) != 1 or None in split_dims:
raise ValueError(f"{self.param_name!r} local HF views cannot be combined generically.")
ordered = sorted(specs, key=lambda spec: spec.split_index)
return torch.cat([weights[spec.name] for spec in ordered], dim=ordered[0].split_dim)
class _HFNameSuffixMapping:
"""A lightweight wrapper mapping that appends a suffix to all HF param names on export.
This is used by FP8 scale tasks: the task's `param_name/global_param_name` may carry
`*_scale_inv`, but the exported output names come from `mapping.megatron_to_hf()`.
Reusing the base mapping would otherwise emit the original HF weight names (no suffix).
"""
def __init__(self, base_mapping: Any, suffix: str, scale_block_size: int | None = None):
self._base_mapping = base_mapping
self._suffix = suffix
self.scale_block_size = scale_block_size
def __getattr__(self, name: str) -> Any:
# Delegate everything else (e.g., broadcast/gather helpers, megatron_param, etc.)
return getattr(self._base_mapping, name)
def resolve(self, captures: Tuple[str, ...]) -> "_HFNameSuffixMapping":
# Preserve wildcard resolution behavior if the base mapping supports it.
if hasattr(self._base_mapping, "resolve"):
return _HFNameSuffixMapping(self._base_mapping.resolve(captures), self._suffix, self.scale_block_size)
return _HFNameSuffixMapping(self._base_mapping, self._suffix, self.scale_block_size)
def hf_to_megatron(self, hf_weights: Any, megatron_module: torch.nn.Module) -> torch.Tensor:
# Pass-through (not used by our export path, but keeps the wrapper mapping "complete").
return self._base_mapping.hf_to_megatron(hf_weights, megatron_module)
def megatron_to_hf(
self,
megatron_weights: Optional[torch.Tensor],
megatron_module: Optional[torch.nn.Module],
) -> Dict[str, torch.Tensor]:
scale_export = getattr(self._base_mapping, "megatron_to_hf_scale", None)
row_block_size = self.scale_block_size
if callable(scale_export) and isinstance(row_block_size, int):
out = scale_export(megatron_weights, megatron_module, row_block_size=row_block_size)
else:
out = self._base_mapping.megatron_to_hf(megatron_weights, megatron_module)
if not out:
return out
# Append suffix to every exported HF parameter name.
return {f"{k}{self._suffix}": v for k, v in out.items()}
def _get_pg_collection_from_model(
megatron_model: MegatronModule | List[MegatronModule] | None,
):
"""Return the ProcessGroupCollection attached to a Megatron model, if any.
Megatron-Core's ``LanguageModule`` (parent of ``GPTModel``) stores the
``ProcessGroupCollection`` it was constructed with on ``self.pg_collection``.
When users wire process groups manually via ``HyperCommGrid`` (decentralized
PG path) the global ``parallel_state`` singleton is never populated, but the
same groups are available through the model. Return ``None`` when no model
is supplied or no ``pg_collection`` is reachable so callers can fall back to
``parallel_state``.
"""
if megatron_model is None:
return None
models_list = megatron_model if isinstance(megatron_model, list) else [megatron_model]
if not models_list:
return None
unwrapped = unwrap_model(models_list[0])
# VLM wrappers expose the language model on ``.language_model``; the
# ``pg_collection`` lives on the inner ``LanguageModule``.
inner = getattr(unwrapped, "language_model", None)
if inner is not None:
unwrapped = inner
return getattr(unwrapped, "pg_collection", None)
def _get_pp_group(megatron_model: MegatronModule | List[MegatronModule] | None):
"""Return the pipeline-parallel group, preferring the model's pg_collection."""
pg = _get_pg_collection_from_model(megatron_model)
pp_group = getattr(pg, "pp", None) if pg is not None else None
if pp_group is not None:
return pp_group
return parallel_state.get_pipeline_model_parallel_group()
def _get_pp_rank(megatron_model: MegatronModule | List[MegatronModule] | None) -> int:
"""Return the pipeline-parallel rank, preferring the model's pg_collection."""
pg = _get_pg_collection_from_model(megatron_model)
pp_group = getattr(pg, "pp", None) if pg is not None else None
if pp_group is not None:
return torch.distributed.get_rank(group=pp_group)
return parallel_state.get_pipeline_model_parallel_rank()
def _get_embedding_group(megatron_model: MegatronModule | List[MegatronModule] | None):
"""Return the embedding group, preferring the model's pg_collection."""
pg = _get_pg_collection_from_model(megatron_model)
embd_group = getattr(pg, "embd", None) if pg is not None else None
if embd_group is not None:
return embd_group
return parallel_state.get_embedding_group()
def _get_ep_group(megatron_model: MegatronModule | List[MegatronModule] | None):
"""Return the expert-parallel group, preferring the model's pg_collection.
Returns ``None`` if the model has a ``pg_collection`` whose ``ep`` is ``None``
(typical for dense models in the decentralized PG path), so callers must
treat ``None`` as "EP size 1".
"""
pg = _get_pg_collection_from_model(megatron_model)
if pg is not None:
return getattr(pg, "ep", None)
return parallel_state.get_expert_model_parallel_group()
def _megatron_local_name_to_global(
models: MegatronModule | List[MegatronModule],
config: TransformerConfig,
param_name: str,
vp_stage: Optional[int] = None,
) -> str:
"""Adjust layer number and expert number from local to global numbering."""
# PP
pp_group = _get_pp_group(models)
if "layers." in param_name and get_pg_size(pp_group) > 1:
match = re.match(r"^(.+?\.layers\.\d+)", param_name)
assert match is not None
layer_prefix = match.group(1)
_, layer_module = get_module_and_param_from_name(models=models, param_name=layer_prefix, vp_stage=vp_stage)
local_layer_number = int(param_name.split("layers.")[1].split(".")[0])
if isinstance(layer_module, MegatronModule):
global_layer_number = layer_module.layer_number - 1
param_name = param_name.replace(
f"layers.{local_layer_number}.",
f"layers.{global_layer_number}.",
)
# EP — fetched lazily because dense models may not have an EP group at all
# (and for the decentralized PG path, ``pg_collection.ep`` may be ``None``).
# For now adapters are not sharded across EP ranks.
is_grouped_expert_param = ".experts.linear_fc" in param_name
is_local_expert_param = ".experts.local_experts." in param_name
is_expert_param = (is_grouped_expert_param or is_local_expert_param) and ".adapter." not in param_name
ep_group = _get_ep_group(models) if is_expert_param else None
if is_expert_param and ep_group is not None and get_pg_size(ep_group) > 1:
num_experts = config.num_moe_experts
num_experts_per_rank = num_experts // ep_group.size()
def _update_grouped_expert_number(param_name: str, param_type: str) -> str:
"""Update expert number from local to global for weight or bias parameters."""
expert_match = re.search(rf"\.{param_type}(\d+)(?=$|\.)", param_name)
if expert_match is None:
return param_name
local_expert_number = int(expert_match.group(1))
global_expert_number = num_experts_per_rank * ep_group.rank() + local_expert_number
return f"{param_name[: expert_match.start(1)]}{global_expert_number}{param_name[expert_match.end(1) :]}"
if is_local_expert_param:
local_experts_match = re.search(r"\.local_experts\.(\d+)\.", param_name)
if local_experts_match:
local_expert_number = int(local_experts_match.group(1))
global_expert_number = num_experts_per_rank * ep_group.rank() + local_expert_number
param_name = param_name.replace(
f".local_experts.{local_expert_number}.",
f".local_experts.{global_expert_number}.",
1,
)
# Grouped MoE uses numeric suffixes for per-expert weight and bias
# parameters, e.g. .weight0 and .bias1. Shared quantizer buffers such
# as .weight_quantizer._amax must not go through EP renumbering.
elif re.search(r"\.weight\d+(?=$|\.)", param_name):
param_name = _update_grouped_expert_number(param_name, "weight")
elif re.search(r"\.bias\d+(?=$|\.)", param_name):
param_name = _update_grouped_expert_number(param_name, "bias")
return param_name
class MegatronModelBridge(
MegatronPeftBridge, MegatronQuantizationBridge, Generic[HFPreTrained, ModelProviderTarget, MegatronModel]
):
"""
High-level orchestrator for HuggingFace ↔ Megatron model conversions.
This abstract base class provides the framework for converting models between
HuggingFace and Megatron formats. It acts as an orchestrator that coordinates
the conversion process without directly handling the complex details of
tensor parallelism or weight transformations.
The bridge pattern separates concerns:
- MegatronModelBridge: Orchestrates the overall conversion process
- MegatronMappingRegistry: Manages parameter name mappings
- MegatronParamMapping: Handles actual weight transformations and distribution
Key responsibilities:
1. Build conversion tasks that map each parameter to its appropriate bridge
2. Execute tasks with proper error handling and progress tracking
3. Provide utilities for configuration translation
4. Handle virtual pipeline parallelism (VP) complexities
To implement a bridge for a new model architecture:
1. Create a subclass decorated with @MegatronModelBridge.register_bridge:
.. code-block:: python
@MegatronModelBridge.register_bridge(source=LlamaForCausalLM, target=GPTModel)
class MegatronCausalLlamaBridge(MegatronModelBridge):
pass
2. Implement provider_bridge to create Megatron configurations:
.. code-block:: python
def provider_bridge(self, hf_pretrained) -> GPTModelProvider:
return GPTModelProvider(
num_layers=hf_pretrained.config.num_hidden_layers,
hidden_size=hf_pretrained.config.hidden_size,
...
)
3. Implement mapping_registry to define weight mappings:
.. code-block:: python
def mapping_registry(self) -> MegatronMappingRegistry:
return MegatronMappingRegistry(
AutoMapping(
megatron_param="embedding.word_embeddings.weight",
hf_param="model.embed_tokens.weight"
),
...
)
Example:
.. code-block:: python
# The bridge is typically not instantiated directly
# Instead, use AutoBridge or AutoBridge which handle this
bridge = AutoBridge.from_hf_pretrained("meta-llama/Meta-Llama-3-8B")
provider = bridge.to_megatron_provider()
Note:
This class uses generic type parameters to ensure type safety:
- HFPreTrained: The HuggingFace model type
- ModelProviderTarget: The Megatron model provider type
- MegatronModel: The Megatron model type
"""
# These are extension points, not a setup checklist. Most new model bridges should keep all defaults below.
# Set to False only when this bridge cannot produce a standalone Hugging Face checkpoint.
SUPPORTS_HF_PRETRAINED_EXPORT: ClassVar[bool] = True
# None selects GPTModelProvider. Pass provider=... to @register_bridge only for a specialized
# provider, such as one implementing MLA.
PROVIDER_CLASS = None
# Builder-backed construction is rolling out incrementally by model family. Override this
# when the standard GPT model config cannot represent the model, and set it to None for
# families that have not yet migrated. The selected model config owns its nested
# transformer config class.
MODEL_CONFIG_CLASS: ClassVar[type[ModelConfig] | None] = BridgeGPTModelConfig
# Conversion still uses the provider-backed construction path unless a model family has
# explicitly migrated its conversion lifecycle to ModelBuilder. Keeping this separate
# from MODEL_CONFIG_CLASS preserves get_model_config() for legacy families without
# silently changing how their checkpoints are constructed.
USE_MODEL_CONFIG_FOR_CONVERSION: ClassVar[bool] = False
# Leave unset unless HF export must copy nonstandard files in addition to the usual artifacts,
# for example ``["*reasoning_parser.py"]``.
ADDITIONAL_FILE_PATTERNS = None
def postprocess_hf_export_artifacts(self, path: Path) -> None:
"""Apply model-specific fixes after Hugging Face artifacts are saved.
Args:
path: Directory containing the exported Hugging Face artifacts.
"""
def postprocess_hf_export_weights(self, path: Path) -> None:
"""Apply model-specific fixes after Hugging Face weights are saved.
Args:
path: Directory containing the complete exported Hugging Face checkpoint.
"""
# HuggingFace PretrainedConfig, set by register_bridge_implementation dispatch.
# Available in mapping_registry(), stream_weights_*(), and build_conversion_tasks().
hf_config = None
# Optional MIMO conversion metadata. Subclasses set this when the standard
# bridge registry can be split into MIMO component routes.
mimo_source_prefixes: ClassVar[Mapping[str, str] | None] = None
# Common bidirectional config field name mapping: (hf_name, megatron_name)
# Some mappings may not be used by all models - that's fine, unused fields are skipped
CONFIG_MAPPING = [
# Core architecture
("num_hidden_layers", "num_layers"),
("hidden_size", "hidden_size"),
("intermediate_size", "ffn_hidden_size"),
("num_attention_heads", "num_attention_heads"),
("num_key_value_heads", "num_query_groups"),
("head_dim", "kv_channels"),
("vocab_size", "vocab_size"),
("max_position_embeddings", "seq_length"),
("rms_norm_eps", "layernorm_epsilon"),
("initializer_range", "init_method_std"),
# Attention and dropout
("attention_dropout", "attention_dropout"),
("hidden_dropout", "hidden_dropout"),
("tie_word_embeddings", "share_embeddings_and_output_weights"),
("attention_bias", "add_qkv_bias"),
("mlp_bias", "add_bias_linear"),
("use_qk_norm", "qk_layernorm"),
# RoPE
("rope_theta", "rotary_base"),
("partial_rotary_factor", "rotary_percent"),
# MoE
("num_experts", "num_moe_experts"),
("num_local_experts", "num_moe_experts"),
("num_experts_per_tok", "moe_router_topk"),
("moe_intermediate_size", "moe_ffn_hidden_size"),
("aux_loss_alpha", "moe_aux_loss_coeff"),
("router_aux_loss_coef", "moe_aux_loss_coeff"),
("scoring_func", "moe_router_score_function"),
("n_routed_experts", "num_moe_experts"),
("n_group", "moe_router_num_groups"),
("topk_group", "moe_router_group_topk"),
("routed_scaling_factor", "moe_router_topk_scaling_factor"),
# MLA
("q_lora_rank", "q_lora_rank"),
("kv_lora_rank", "kv_lora_rank"),
("qk_nope_head_dim", "qk_head_dim"),
("qk_rope_head_dim", "qk_pos_emb_head_dim"),
("v_head_dim", "v_head_dim"),
# MTP
("num_nextn_predict_layers", "mtp_num_layers"),
("mtp_num_hidden_layers", "mtp_num_layers"),
]
# YARN rope scaling field mapping for GPT models: (hf_rope_scaling_key, megatron_yarn_param)
# These are only applied when rope_scaling.type == "yarn" and provider is GPTModelProvider
# Uses yarn_ prefix (e.g., yarn_mscale, yarn_rotary_scaling_factor)
YARN_ROPE_SCALING_MAPPING = [
("factor", "yarn_rotary_scaling_factor"),
("original_max_position_embeddings", "yarn_original_max_position_embeddings"),
("beta_fast", "yarn_beta_fast"),
("beta_slow", "yarn_beta_slow"),
("mscale", "yarn_mscale"),
("mscale_all_dim", "yarn_mscale_all_dim"),
]
# MLA rope scaling field mapping: (hf_rope_scaling_key, megatron_mla_param)
# These are applied for MLA models (DeepSeek, Kimi, etc.) which use MLATransformerConfig
# Uses direct field names without yarn_ prefix (e.g., mscale, rotary_scaling_factor)
MLA_ROPE_SCALING_MAPPING = [
("factor", "rotary_scaling_factor"),
("original_max_position_embeddings", "original_max_position_embeddings"),
("beta_fast", "beta_fast"),
("beta_slow", "beta_slow"),
("mscale", "mscale"),
("mscale_all_dim", "mscale_all_dim"),
]
@classmethod
def hf_to_megatron_activation(cls, hidden_act: str):
"""Convert HF activation name string to Megatron activation function."""
if hidden_act not in ACTIVATION_FUNC_MAP:
raise ValueError(
f"Unsupported activation function: {hidden_act}. Supported: {list(ACTIVATION_FUNC_MAP.keys())}"
)
return ACTIVATION_FUNC_MAP[hidden_act]
@classmethod
def megatron_to_hf_activation(cls, activation_func) -> str:
"""Convert Megatron activation function to HF activation name string."""
for hf_name, megatron_func in ACTIVATION_FUNC_MAP.items():
if activation_func is megatron_func:
return hf_name
raise ValueError(
f"Unsupported activation function: {activation_func}. Supported: {list(ACTIVATION_FUNC_MAP.values())}"
)
def _should_map_hf_config_field(self, hf_config: Any, hf_name: str, megatron_name: str, value: Any) -> bool:
"""Return whether an HF config field should be mapped to provider kwargs."""
return True
def _hf_config_to_megatron_kwargs(self, hf_config: PretrainedConfig) -> dict[str, Any]:
"""Convert an HF config to flat Megatron config kwargs.
Args:
hf_config: HuggingFace model configuration object
Returns:
Megatron fields derived from ``CONFIG_MAPPING``.
"""
provider_kwargs = {}
# Map config fields using CONFIG_MAPPING
# Supports dot notation for nested dict access (e.g., "rope_scaling.factor")
for hf_name, megatron_name in self.CONFIG_MAPPING:
has_value = False
value = None
if "." in hf_name:
# Nested dict access: "parent.child" -> getattr(config, parent).get(child)
parts = hf_name.split(".", 1)
parent = getattr(hf_config, parts[0], None)
if parent is not None and isinstance(parent, dict):
if parts[1] in parent:
value = parent[parts[1]]
has_value = True
else:
value = getattr(hf_config, hf_name, None)
has_value = hasattr(hf_config, hf_name)
if (
has_value
and megatron_name not in provider_kwargs
and self._should_map_hf_config_field(hf_config, hf_name, megatron_name, value)
):
provider_kwargs[megatron_name] = value
# Extract rotary_base via compat function (handles both legacy rope_theta
# attribute and transformers 5.0+ rope_parameters dict)
if "rotary_base" not in provider_kwargs:
try:
provider_kwargs["rotary_base"] = rope_theta_from_hf(hf_config)
except ValueError:
pass
# Handle rope scaling: extract params from rope_scaling dict
# HF configs use either "type" or "rope_type" key for the scaling type
from megatron.bridge.models.mla_provider import MLAModelProvider
is_mla_provider = self.PROVIDER_CLASS is not None and issubclass(self.PROVIDER_CLASS, MLAModelProvider)
rope_scaling = getattr(hf_config, "rope_scaling", None)
rope_type = None
if rope_scaling is not None and isinstance(rope_scaling, dict) and rope_scaling != {}:
rope_type = rope_scaling.get("type") or rope_scaling.get("rope_type")
if rope_type == "yarn":
# Check if this is an MLA provider (uses direct field names)
# or a GPT provider (uses yarn_ prefixed field names)
if is_mla_provider:
# MLA models: use direct field names (mscale, rotary_scaling_factor, etc.)
mla_params = {}
for hf_key, megatron_key in self.MLA_ROPE_SCALING_MAPPING:
value = rope_scaling.get(hf_key)
if value is not None:
mla_params[megatron_key] = value
if mla_params:
provider_kwargs["_mla_rope_params"] = mla_params
else:
# GPT models: use yarn_ prefixed field names (dataclass fields on GPTModelProvider)
provider_kwargs["position_embedding_type"] = "yarn"
for hf_key, megatron_key in self.YARN_ROPE_SCALING_MAPPING:
value = rope_scaling.get(hf_key)
if value is not None:
provider_kwargs[megatron_key] = value
if "truncate" in rope_scaling:
provider_kwargs["yarn_correction_range_round_to_int"] = rope_scaling["truncate"]
elif is_mla_provider:
if rope_type not in (None, "default"):
logger.warning(
f"Unsupported {rope_type=} for MLA model; "
"defaulting to no scaling (rotary_scaling_factor=1.0, mscale_all_dim=1.0). "
"Add explicit handling for this rope_type if the model requires it."
)
# Fill in 1.0 for any missing keys to avoid Megatron's MLATransformerConfig defaults
# (rotary_scaling_factor=40, mscale_all_dim=0.0), which are hardcoded for DeepSeek-V3's
# YaRN config and are wrong for models without yarn scaling.
provider_kwargs["_mla_rope_params"] = {"rotary_scaling_factor": 1.0, "mscale_all_dim": 1.0}
# Handle vocab_size_divisible_by
vocab_size = provider_kwargs.get("vocab_size")
if vocab_size is not None:
provider_kwargs["make_vocab_size_divisible_by"] = self.make_vocab_size_divisible_by(vocab_size)
# Determine dtype
params_dtype = self.dtype_from_hf(hf_config, default=torch.float32)
provider_kwargs["fp16"] = params_dtype == torch.float16
provider_kwargs["bf16"] = params_dtype == torch.bfloat16
provider_kwargs["params_dtype"] = params_dtype
# Convert activation function (some models use hidden_act, others use hidden_activation)
hidden_act = getattr(hf_config, "hidden_act", None) or getattr(hf_config, "hidden_activation", "silu")
provider_kwargs["activation_func"] = self.hf_to_megatron_activation(hidden_act)
return provider_kwargs
def hf_config_to_provider_kwargs(self, hf_config: PretrainedConfig) -> dict[str, Any]:
"""Return kwargs for the legacy provider compatibility path."""
return self._hf_config_to_megatron_kwargs(hf_config)
def hf_config_to_model_config_kwargs(self, hf_config: PretrainedConfig) -> dict[str, Any]:
"""Return flat kwargs for a builder-backed model config.
Model-family bridges should call ``super()`` and add their architecture
defaults here. This path intentionally does not call the provider-era
override hook.
"""
config_kwargs = self._hf_config_to_megatron_kwargs(hf_config)
config_kwargs.update(
attention_softmax_in_fp32=False,
cross_entropy_loss_fusion=True,
deallocate_pipeline_outputs=True,
gradient_accumulation_fusion=fusions.can_enable_gradient_accumulation_fusion(),
)
return config_kwargs
@staticmethod
def _partition_model_config_kwargs(
config_kwargs: Mapping[str, Any],
model_config_class: type[ModelConfig],
transformer_config_class: type[BridgeTransformerConfig],
) -> tuple[dict[str, Any], dict[str, Any]]:
"""Partition flat kwargs between outer and nested config dataclasses."""
if not is_dataclass(model_config_class):
raise TypeError(f"Model config class {model_config_class.__name__} must be a dataclass.")
if not is_dataclass(transformer_config_class):
raise TypeError(f"Transformer config class {transformer_config_class.__name__} must be a dataclass.")
model_fields = {field.name for field in fields(model_config_class) if field.init} - {"transformer"}
transformer_fields = {field.name for field in fields(transformer_config_class) if field.init}
unknown_fields = set(config_kwargs) - model_fields - transformer_fields
if unknown_fields:
raise ValueError(
"Cannot map Hugging Face config fields to "
f"{model_config_class.__name__} + {transformer_config_class.__name__}: "
f"{sorted(unknown_fields)}. Override hf_config_to_model_config() for model-specific fields."
)
model_kwargs = {name: value for name, value in config_kwargs.items() if name in model_fields}
transformer_kwargs = {
name: value
for name, value in config_kwargs.items()
if name not in model_fields and name in transformer_fields
}
return model_kwargs, transformer_kwargs
def hf_config_to_model_config(self, hf_config: PretrainedConfig) -> ModelConfig:
"""Convert a Hugging Face config directly to a builder-backed config.
GPT-style model families use ``BridgeGPTModelConfig`` by default.
A bridge may select a specialized config class or explicitly disable
this path by setting ``MODEL_CONFIG_CLASS`` to ``None``.
Args:
hf_config: Hugging Face architecture configuration.
Returns:
Serializable model configuration linked to its builder.
Raises:
ModelConfigNotSupportedError: If the model family explicitly disables this path.
ValueError: If mapped fields do not belong to either config dataclass.
"""
model_config_class = self.MODEL_CONFIG_CLASS
if model_config_class is None:
raise ModelConfigNotSupportedError(
f"ModelConfig conversion is not implemented for {type(self).__name__}. "
"This model family sets MODEL_CONFIG_CLASS to None."
)
config_kwargs = self.hf_config_to_model_config_kwargs(hf_config)
if not issubclass(model_config_class, ModelConfigOverrideMixin):
raise TypeError(f"{model_config_class.__name__} must inherit {ModelConfigOverrideMixin.__name__}.")
model_config_with_overrides = cast(type[ModelConfigOverrideMixin], model_config_class)
transformer_config_class = model_config_with_overrides.transformer_config_class
if not isinstance(transformer_config_class, type) or not issubclass(
transformer_config_class, BridgeTransformerConfig
):
raise TypeError(
f"{model_config_class.__name__}.transformer_config_class must be a "
f"{BridgeTransformerConfig.__name__} subclass."
)
model_kwargs, transformer_kwargs = self._partition_model_config_kwargs(
config_kwargs,
model_config_class,
transformer_config_class,
)
transformer_config = transformer_config_class(**transformer_kwargs)
return model_config_class(transformer=transformer_config, **model_kwargs)
# Set by @register_bridge decorator
SOURCE_NAME: str | None = None
MODEL_TYPE: str | None = None
def text_only_pretrained(self, hf_pretrained: PreTrainedCausalLM) -> PreTrainedCausalLM:
"""Select a standalone language checkpoint view for an opted-in family.
Implementations must preserve language weights and tokenizer semantics
and return a config registered with the corresponding text bridge.
"""
raise ValueError(f"{type(self).__name__} does not support text_only=True.")
def provider_bridge(self, hf_pretrained: HFPreTrained) -> ModelProviderTarget:
"""Create a Megatron model provider from HuggingFace configuration.
Default implementation that:
1. Converts HF config to provider kwargs using CONFIG_MAPPING
2. Creates and returns a GPTModelProvider
Subclasses should override this to add model-specific configuration
by calling super().provider_bridge() then setting properties directly
on the returned provider (e.g., provider.normalization = "RMSNorm").
Args:
hf_pretrained (HFPreTrained): HuggingFace model or configuration
containing the source model's architecture details.
Returns:
ModelProviderTarget: A configured model provider instance
"""
from megatron.bridge.models.gpt_provider import GPTModelProvider
from megatron.bridge.models.mla_provider import MLAModelProvider
if self.MODEL_CONFIG_CLASS is not None:
warnings.warn(
f"{type(self).__name__}.provider_bridge() and AutoBridge.to_megatron_provider() "
"are deprecated for builder-backed models. Use AutoBridge.get_model_config() "
"for training recipes or AutoBridge.get_model() to construct a model. "
"Legacy provider support will be removed in a future release.",
FutureWarning,
stacklevel=2,
)
hf_config = hf_pretrained.config
# Build base provider kwargs using CONFIG_MAPPING
provider_kwargs = self.hf_config_to_provider_kwargs(hf_config)
mla_rope_params = provider_kwargs.pop("_mla_rope_params", None)
# Use specified provider class, defaulting to GPTModelProvider
provider_class = self.PROVIDER_CLASS if self.PROVIDER_CLASS is not None else GPTModelProvider
is_mla_provider = issubclass(provider_class, MLAModelProvider)
# Filter kwargs to only fields the provider dataclass accepts, so that MLA-only None
# values (q_lora_rank, kv_lora_rank, …) are silently dropped for non-MLA providers
# while still being passed through for MLA providers that declare them as fields.
valid_fields = provider_class.__dataclass_fields__
provider = provider_class(**{k: v for k, v in provider_kwargs.items() if k in valid_fields})
# Determine position_embedding_type from HF rope_scaling.
# For GPT providers: rope_type=="yarn" → "yarn"; everything else → "rope".
# For MLA providers: always "rope" — YaRN scaling parameters are applied
# separately via mla_rope_params (rotary_scaling_factor, mscale, etc.) and
# position_embedding_type="yarn" is not a valid MLA config value.
hf_rope_scaling = getattr(hf_config, "rope_scaling", None)
rope_type = None
if hf_rope_scaling:
rope_type = hf_rope_scaling.get("type") or hf_rope_scaling.get("rope_type")
if rope_type == "yarn" and not is_mla_provider:
provider.position_embedding_type = "yarn"
else:
provider.position_embedding_type = "rope"
# Apply MLA rope params via setattr (for MLA models like DeepSeek, Kimi)
if mla_rope_params:
for key, value in mla_rope_params.items():
setattr(provider, key, value)
return provider
@classmethod
def megatron_to_hf_config(cls, provider) -> dict:
"""Convert Megatron provider config to HuggingFace config dict.
Default implementation that:
1. Converts provider to HF config using CONFIG_MAPPING
2. Handles YARN rope scaling parameters
3. Converts activation function and dtype
4. Adds architectures and model_type from decorator
Subclasses should override this to add model-specific configuration
by calling super().megatron_to_hf_config() then setting values directly
on the returned dict (e.g., hf_config["rope_scaling"] = {...}).
Args:
provider: Megatron model provider instance
Returns:
dict: HuggingFace config dictionary
"""
hf_config = {}
# Map config fields using CONFIG_MAPPING (reverse direction)
# Supports dot notation for nested dict building (e.g., "rope_scaling.factor")
for hf_name, megatron_name in cls.CONFIG_MAPPING:
has_value = hasattr(provider, megatron_name)
value = getattr(provider, megatron_name, None)
if has_value:
if "." in hf_name:
# Nested dict: "parent.child" -> hf_config["parent"]["child"] = value
parts = hf_name.split(".", 1)
if parts[0] not in hf_config:
hf_config[parts[0]] = {}
hf_config[parts[0]][parts[1]] = value
else:
hf_config[hf_name] = value
# Handle YARN rope scaling: check if provider has yarn_* params and build rope_scaling dict
yarn_rotary_scaling_factor = getattr(provider, "yarn_rotary_scaling_factor", None)
if yarn_rotary_scaling_factor is not None:
if "rope_scaling" not in hf_config:
hf_config["rope_scaling"] = {}
hf_config["rope_scaling"]["rope_type"] = "yarn"
for hf_key, megatron_key in cls.YARN_ROPE_SCALING_MAPPING:
value = getattr(provider, megatron_key, None)
if value is not None:
hf_config["rope_scaling"][hf_key] = value
yarn_correction_range_round_to_int = getattr(provider, "yarn_correction_range_round_to_int", None)
if yarn_correction_range_round_to_int is not None:
hf_config["rope_scaling"]["truncate"] = yarn_correction_range_round_to_int
# Convert activation function back to HF format
activation_func = getattr(provider, "activation_func", None)
if activation_func is not None:
hf_config["hidden_act"] = cls.megatron_to_hf_activation(activation_func)
# Determine torch_dtype
if getattr(provider, "bf16", False):