Repository navigation
Expand file tree
/
Copy pathparam_mapping.py
More file actions
4480 lines (3743 loc) · 186 KB
/
Copy pathparam_mapping.py
File metadata and controls
4480 lines (3743 loc) · 186 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 json
import re
from abc import ABC, abstractmethod
from contextlib import contextmanager
from contextvars import ContextVar
from dataclasses import dataclass
from types import SimpleNamespace
from typing import Any, Callable, Dict, Generic, Iterator, List, Literal, Optional, Tuple, TypeVar, Union, cast
import torch
import torch.distributed
import torch.nn as nn
from megatron.core import mpu
from megatron.core.fp8_utils import FP8_TENSOR_CLASS, HAVE_TE_FP8_TENSOR_CLASS
from megatron.core.transformer.module import MegatronModule
from megatron.core.transformer.transformer_config import TransformerConfig
from megatron.core.utils import (
get_pg_rank,
get_pg_size,
)
from torch.distributed._tensor import DTensor
from megatron.bridge.models.conversion.gtp import _get_mapping_shape, _is_gtp_param
from megatron.bridge.models.conversion.utils import (
get_module_and_param_from_name,
is_modelopt_dynamic_module,
remove_non_pickleables,
)
from megatron.bridge.utils.common_utils import extract_expert_number_from_param
WeightType = TypeVar("WeightType", torch.Tensor, Dict[str, torch.Tensor])
MXFP8ShardGroup = Literal["tp", "etp", "replicated"]
LocalHFShardGroup = Literal["tp", "etp", "replicated"]
import logging
logger = logging.getLogger(__name__)
# Export policy is scoped to one conversion operation rather than stored on a
# mapping instance. Some mappings (notably AutoMapping) create their concrete
# delegate lazily while ``megatron_to_hf`` is running, so an instance property
# would not reliably reach the object that performs the PP broadcast.
_SKIP_PP_BROADCAST: ContextVar[bool] = ContextVar("megatron_bridge_skip_pp_broadcast", default=False)
@dataclass(frozen=True)
class LocalHFParamSpec:
"""A canonical HF-compatible view of one local logical Megatron parameter.
A spec describes only how to name and, optionally, split an already-local
logical tensor. It does not perform Bridge collectives, layout conversion,
or destination-backend/topology validation.
"""
name: str
split_dim: Optional[int] = None
split_index: int = 0
split_count: int = 1
def __post_init__(self) -> None:
if self.split_count < 1:
raise ValueError("split_count must be positive.")
if not 0 <= self.split_index < self.split_count:
raise ValueError("split_index must be within split_count.")
if self.split_count > 1 and self.split_dim is None:
raise ValueError("split_dim is required when split_count is greater than one.")
def select(self, tensor: torch.Tensor) -> torch.Tensor:
"""Select this HF component from a logical Megatron tensor."""
if self.split_count == 1:
return tensor
dim = self.split_dim % tensor.ndim
if tensor.shape[dim] % self.split_count:
raise ValueError(
f"Cannot split dimension {dim} of shape {tuple(tensor.shape)} into {self.split_count} equal parts."
)
return torch.chunk(tensor, self.split_count, dim=dim)[self.split_index]
def selected_shape(self, shape: torch.Size) -> torch.Size:
"""Return the shape selected from a logical Megatron tensor."""
if self.split_count == 1:
return torch.Size(shape)
selected = list(shape)
dim = self.split_dim % len(selected)
if selected[dim] % self.split_count:
raise ValueError(
f"Cannot split dimension {dim} of shape {tuple(shape)} into {self.split_count} equal parts."
)
selected[dim] //= self.split_count
return torch.Size(selected)
@dataclass(frozen=True)
class LocalMXFP8Param:
"""A local native MXFP8 weight and its matching E8M0 scale tensor."""
name: str
weight: torch.Tensor
weight_scale: torch.Tensor
global_weight_shape: torch.Size
shard_group: MXFP8ShardGroup
shard_dim: int | None
def _validate_native_mxfp8_pair(
weight: torch.Tensor,
weight_scale: torch.Tensor,
global_param_name: str,
) -> None:
if weight.ndim != 2:
raise ValueError(f"{global_param_name}: native MXFP8 weights must be two-dimensional")
if weight.shape[-1] % 32:
raise ValueError(f"{global_param_name}: K={weight.shape[-1]} is not divisible by 32")
expected_scale_shape = torch.Size((*weight.shape[:-1], weight.shape[-1] // 32))
if weight_scale.shape != expected_scale_shape:
raise ValueError(
f"{global_param_name}: expected native MXFP8 scale shape {tuple(expected_scale_shape)}, "
f"got {tuple(weight_scale.shape)}"
)
def _project_gated_native_mxfp8(
weight: torch.Tensor,
weight_scale: torch.Tensor,
*,
names: tuple[str, str],
global_param_name: str,
shard_group: MXFP8ShardGroup,
shard_size: int,
) -> tuple[LocalMXFP8Param, ...]:
_validate_native_mxfp8_pair(weight, weight_scale, global_param_name)
if weight.shape[-2] % 2:
raise ValueError(f"{global_param_name}: fused FC1 output rows must be even")
gate_weight, up_weight = torch.chunk(weight, 2, dim=-2)
gate_scale, up_scale = torch.chunk(weight_scale, 2, dim=-2)
global_weight_shape = list(gate_weight.shape)
global_weight_shape[-2] *= shard_size
return tuple(
LocalMXFP8Param(
name=name,
weight=projected_weight,
weight_scale=projected_scale,
global_weight_shape=torch.Size(global_weight_shape),
shard_group=shard_group,
shard_dim=0,
)
for name, projected_weight, projected_scale in zip(
names,
(gate_weight, up_weight),
(gate_scale, up_scale),
)
)
@dataclass(frozen=True)
class LocalHFParam:
"""A canonical HF-compatible view of one local unquantized BF16 parameter.
The tensor remains a live view of the local Megatron parameter. Its global
shape and sharding fields describe how an M-to-N transport can reconstruct
the corresponding logical HF parameter without Bridge collectives.
"""
name: str
weight: torch.Tensor
global_weight_shape: torch.Size
shard_group: LocalHFShardGroup
shard_dim: int | None
def _module_uses_fsdp(megatron_module: nn.Module) -> bool:
"""Return True if the module uses Megatron-FSDP"""
return hasattr(megatron_module, "_parameters") and any(
key.startswith("weight") and isinstance(value, DTensor) for key, value in megatron_module._parameters.items()
)
class MegatronParamMapping(ABC, Generic[WeightType]):
"""
Abstract base class for weight conversion between Megatron and external formats.
This class provides the foundation for all weight mappings, handling the complex
conversions between Megatron-Core's distributed tensor formats and standard
(typically HuggingFace) formats. Each concrete mapping implements specific
transformation logic while inheriting common parallel communication patterns.
Key responsibilities:
- Format transformation (e.g., QKV merging/splitting, gated MLP handling)
- Tensor parallel (TP) distribution and gathering across GPUs
- Pipeline parallel (PP) broadcasting between pipeline stages
- Wildcard pattern resolution for layer-wise mappings
The mapping abstraction ensures that higher-level code doesn't need to know
about the parallel topology or format differences - it just requests a
conversion and the mapping handles all the complexity.
Public helper methods for subclasses:
- broadcast_from_pp_rank: Broadcast tensors across pipeline stages
- broadcast_obj_from_pp_rank: Broadcast Python objects across PP ranks
- broadcast_tensor_to_tp_ranks: Broadcast within TP group
- scatter_to_tp_ranks: Distribute tensor shards to TP ranks
- gather_from_tp_ranks: Collect tensor shards from TP ranks
Example:
.. code-block:: python
class MyCustomMapping(MegatronParamMapping[torch.Tensor]):
def hf_to_megatron(self, hf_weights, megatron_module):
# Custom transformation logic
transformed = hf_weights.t() # Example: transpose
# Use helpers for distribution
return self.scatter_to_tp_ranks(...)
def megatron_to_hf(self, megatron_weights, megatron_module):
# Broadcast from owning PP rank
weight = self.broadcast_from_pp_rank(megatron_weights)
# Gather from TP ranks and transform
gathered = self.gather_from_tp_ranks(weight)
return {"custom_weight": gathered[0].t()}
"""
def __init__(self, megatron_param: str, hf_param: Union[str, Dict[str, str]]):
"""Initialize the weight mapping.
Args:
megatron_param (str): Megatron parameter name pattern (supports *
wildcards).
hf_param (Union[str, Dict[str, str]]): External format name pattern(s).
"""
self.megatron_param = megatron_param
self.hf_param = hf_param
self._validate_patterns()
# Cache for metadata and tensor_spec_output
self._broadcast_obj_cache = {}
self._tensor_spec_output_cache = {}
self._pg_collection = None
if mpu.is_initialized():
self.pp_group = mpu.get_pipeline_model_parallel_group()
self.ep_group = mpu.get_expert_model_parallel_group()
self._tp_group = mpu.get_tensor_model_parallel_group()
self._etp_group = mpu.get_expert_tensor_parallel_group()
else:
self.pp_group = None
self.ep_group = None
self._tp_group = None
self._etp_group = None
# Set allow_hf_name_mismatch to True when the declared HF name will not be found verbatim
# in the checkpoint's key set. That covers two cases: a name that is rewritten or
# synthesized (see maybe_modify_loaded_hf_weight), and a weight that is legitimately
# absent for some layers or configurations. Both bypass the hf_keys check in
# `build_conversion_tasks`, which raises otherwise.
self.allow_hf_name_mismatch = False
@classmethod
@contextmanager
def skip_pp_broadcast(cls) -> Iterator[None]:
"""Disable PP replication for the duration of one HF export.
In this mode ``broadcast_from_pp_rank`` and
``broadcast_obj_from_pp_rank`` return the value local to the current
rank. TP/EP collectives remain enabled, so mappings still perform all
required shard reconstruction and HF layout conversion on the owning
pipeline stage.
The policy is held in a :class:`ContextVar` so it also applies to
mappings created lazily by wrappers such as :class:`AutoMapping`.
"""
token = _SKIP_PP_BROADCAST.set(True)
try:
yield
finally:
_SKIP_PP_BROADCAST.reset(token)
def local_hf_param_specs(self, global_param_name: Optional[str] = None) -> tuple[LocalHFParamSpec, ...]:
"""Describe canonical local HF views for one mapped parameter.
A non-empty result means this parameter's local logical Megatron tensor
can be transferred as the described HF-compatible views without first
running Bridge collectives or layout conversion. It is a per-parameter
contract, not a declaration that the model supports general HF
conversion or M-to-N refit.
Mappings that require transpose, permutation, interleaving, or grouped
export transforms must return an empty tuple unless they implement an
explicit safe override. An empty tuple selects the normal Bridge
conversion/packed-broadcast path; it does not mean the model is
unsupported. Consumers must separately qualify the destination backend
and source/destination topology.
The contract is independent of the source and destination storage
precision. For example, an MXFP8 transport may materialize these
canonical logical views from quantized source storage and requantize a
persistent MXFP8 destination in place. Direct transfer of physical
MXFP8 data and scales requires separate backend/layout qualification.
Args:
global_param_name: Resolved global Megatron parameter name. Custom
mappings may use it to derive an HF view name.
Returns:
Per-parameter local HF view specifications, or an empty tuple when
the normal Bridge conversion path is required.
"""
if not isinstance(self.hf_param, str):
return ()
# Grouped exports and dimension permutations need conversion work. Grouped
# mappings must explicitly override this method when a canonical local view exists.
if (
getattr(self, "is_grouped_export", False)
or getattr(self, "permute_dims", None) is not None
or getattr(self, "transpose_on_export", False)
):
return ()
return (LocalHFParamSpec(self.hf_param),)
def local_mxfp8_params(
self,
weight: torch.Tensor,
weight_scale: torch.Tensor,
*,
global_param_name: str,
megatron_module: nn.Module,
) -> tuple[LocalMXFP8Param, ...]:
raise ValueError(
f"Mapping {type(self).__name__} for {global_param_name!r} does not support direct native MXFP8 export."
)
def _local_hf_sharding(
self, weight: torch.Tensor, megatron_module: nn.Module
) -> tuple[LocalHFShardGroup, int | None, int]:
"""Describe the local tensor sharding for canonical HF views."""
if self.tp_size == 1:
return "replicated", None, 1
raise ValueError(
f"mapping {type(self).__name__} does not describe local HF sharding "
f"when tensor parallel size is {self.tp_size}"
)
def local_hf_params(
self,
weight: torch.Tensor,
*,
global_param_name: str,
megatron_module: nn.Module,
) -> tuple[LocalHFParam, ...]:
"""Materialize canonical local HF views for an unquantized BF16 parameter.
This method only selects views from local storage. It does not gather,
broadcast, dequantize, cast, or emit quantization sidecars.
Args:
weight: Local logical Megatron parameter storage.
global_param_name: Resolved global Megatron parameter name.
megatron_module: Local module that owns ``weight``.
Returns:
Canonical local HF parameter views in mapping-defined order.
Raises:
ValueError: If the storage is not plain BF16 or the mapping cannot
represent the parameter as local HF views.
"""
if HAVE_TE_FP8_TENSOR_CLASS and isinstance(weight, FP8_TENSOR_CLASS):
raise ValueError(f"{global_param_name}: local HF parameter iteration does not support quantized storage")
if weight.dtype != torch.bfloat16:
raise ValueError(
f"{global_param_name}: local HF parameter iteration requires unquantized BF16 storage, "
f"got {weight.dtype}"
)
if isinstance(weight, DTensor) or _module_uses_fsdp(megatron_module):
raise ValueError(f"{global_param_name}: local HF parameter iteration does not support DTensor/FSDP")
if _is_gtp_param(weight):
raise ValueError(
f"{global_param_name}: local HF parameter views cannot represent GTP sharding; "
"use the gathered HF weight export instead"
)
specs = self.local_hf_param_specs(global_param_name)
if not specs:
raise ValueError(
f"{global_param_name}: mapping {type(self).__name__} cannot be represented as canonical local HF views"
)
shard_group, shard_dim, shard_size = self._local_hf_sharding(weight, megatron_module)
params = []
for spec in specs:
selected = spec.select(weight)
global_shape = list(selected.shape)
if shard_dim is not None:
normalized_shard_dim = shard_dim % selected.ndim
global_shape[normalized_shard_dim] *= shard_size
else:
normalized_shard_dim = None
params.append(
LocalHFParam(
name=spec.name,
weight=selected,
global_weight_shape=torch.Size(global_shape),
shard_group=shard_group,
shard_dim=normalized_shard_dim,
)
)
return tuple(params)
def set_process_groups_from_pg_collection(self, pg_collection: Any) -> None:
"""Override snapshotted Megatron-Core globals with a ``ProcessGroupCollection``.
Used by the decentralized PG path where ``mpu`` is never initialized.
``__init__`` runs at registry construction time and snapshots whatever
Megatron-Core globals exist then; in the decentralized path those are
absent, so ``tp_size`` would default to ``world_size`` and conversions
would compute the wrong shard sizes. ``MegatronModelBridge`` calls this
right before running tasks to install the user-supplied groups.
"""
if pg_collection is None:
return
self._pg_collection = pg_collection
for attr, field in (
("pp_group", "pp"),
("ep_group", "ep"),
("_tp_group", "tp"),
("_etp_group", "expt_tp"),
):
group = getattr(pg_collection, field, None)
if group is not None:
setattr(self, attr, group)
for child in vars(self).values():
if isinstance(child, MegatronParamMapping):
child.set_process_groups_from_pg_collection(pg_collection)
@property
def tp_group(self):
"""Get the tensor model parallel group."""
if self.is_expert:
return self._etp_group
return self._tp_group
@property
def tp_rank(self) -> int:
"""Get the tensor model parallel rank."""
return get_pg_rank(self.tp_group)
@property
def tp_size(self) -> int:
"""Get the tensor model parallel size."""
return get_pg_size(self.tp_group)
@property
def pp_rank(self) -> int:
"""Get the pipeline model parallel rank."""
return get_pg_rank(self.pp_group)
@property
def pp_size(self) -> int:
"""Get the pipeline model parallel size."""
return get_pg_size(self.pp_group)
@property
def ep_rank(self) -> int:
"""Get the expert model parallel rank."""
return get_pg_rank(self.ep_group)
@property
def ep_size(self) -> int:
"""Get the expert model parallel size."""
return get_pg_size(self.ep_group)
@property
def etp_rank(self) -> int:
"""Get the expert tensor parallel rank."""
return get_pg_rank(self.etp_group)
@property
def etp_size(self) -> int:
"""Get the expert tensor parallel size."""
return get_pg_size(self.etp_group)
@property
def is_expert(self) -> bool:
"""Check if this mapping is for an expert parameter.
Matches both TEGroupedMLP (.experts.linear_fc) and
SequentialMLP (.experts.local_experts.*.linear_fc) patterns.
Uses ``.experts.`` rather than ``.mlp.experts.`` so models with an
intermediate sub-module (e.g. ``.mlp.<pool>.experts.``) are matched too.
"""
return ".experts.linear_fc" in self.megatron_param or ".experts.local_experts." in self.megatron_param
@property
def is_adapter(self) -> bool:
"""Check if this mapping is for an adapter parameter."""
return ".adapter." in self.megatron_param
def _resolve_names(self, captures: Tuple[str, ...]) -> Tuple[str, Union[str, Dict[str, str]]]:
"""Resolve wildcard patterns with captured values.
Handles both ** (any characters) and * (digits) wildcards in order.
** patterns are processed before * patterns to avoid conflicts.
"""
resolved_megatron_param = self.megatron_param
capture_index = 0
# First pass: resolve ** wildcards
while "**" in resolved_megatron_param and capture_index < len(captures):
resolved_megatron_param = resolved_megatron_param.replace("**", captures[capture_index], 1)
capture_index += 1
# Second pass: resolve * wildcards
while "*" in resolved_megatron_param and capture_index < len(captures):
resolved_megatron_param = resolved_megatron_param.replace("*", captures[capture_index], 1)
capture_index += 1
if isinstance(self.hf_param, str):
resolved_hf_param = self.hf_param
capture_index = 0
# First pass: resolve ** wildcards
while "**" in resolved_hf_param and capture_index < len(captures):
resolved_hf_param = resolved_hf_param.replace("**", captures[capture_index], 1)
capture_index += 1
# Second pass: resolve * wildcards
while "*" in resolved_hf_param and capture_index < len(captures):
resolved_hf_param = resolved_hf_param.replace("*", captures[capture_index], 1)
capture_index += 1
else:
resolved_hf_param = {}
for k, v in self.hf_param.items():
resolved_v = v
capture_index = 0
# First pass: resolve ** wildcards
while "**" in resolved_v and capture_index < len(captures):
resolved_v = resolved_v.replace("**", captures[capture_index], 1)
capture_index += 1
# Second pass: resolve * wildcards
while "*" in resolved_v and capture_index < len(captures):
resolved_v = resolved_v.replace("*", captures[capture_index], 1)
capture_index += 1
resolved_hf_param[k] = resolved_v
return resolved_megatron_param, resolved_hf_param
def resolve(self, captures: Tuple[str, ...]) -> "MegatronParamMapping":
"""Create a new mapping with resolved wildcards.
This default implementation works for mappings with a
(megatron_param, hf_param) constructor.
Args:
captures (Tuple[str, ...]): Captured wildcard values.
Returns:
MegatronParamMapping: A new mapping instance with resolved names.
"""
resolved_megatron_param, resolved_hf_param = self._resolve_names(captures)
return type(self)(resolved_megatron_param, resolved_hf_param)
@abstractmethod
def hf_to_megatron(
self,
hf_weights: WeightType,
megatron_module: nn.Module,
) -> torch.Tensor:
"""Convert hf_weights TO Megatron format.
This method handles:
1. Format transformation (if needed)
2. Tensor parallel distribution (if self.tp_size > 1)
Args:
hf_weights (WeightType): Source hf_weights in external format.
megatron_module (nn.Module): Target Megatron module (for config
access).
Returns:
torch.Tensor: Weight tensor ready for the current TP rank.
"""
...
@abstractmethod
def megatron_to_hf(
self,
megatron_weights: Optional[torch.Tensor],
megatron_module: Optional[nn.Module],
) -> Dict[str, torch.Tensor]:
"""Convert weights FROM Megatron format.
This method handles:
1. Pipeline parallel broadcasting (if weight is on different PP rank)
2. Tensor parallel gathering (if needed)
3. Format transformation
Args:
megatron_weights (Optional[torch.Tensor]): Weight tensor from current
rank (None if on different PP rank).
megatron_module (Optional[nn.Module]): Module for config access
(None if on different PP rank).
Returns:
Dict[str, torch.Tensor]: Converted weights (empty dict if not on
TP rank 0).
"""
...
def megatron_to_hf_quant(
self,
megatron_weights: Optional[torch.Tensor],
megatron_module: Optional[nn.Module],
quantization_checker: Callable[[str], bool],
quant_fn: Callable[..., Tuple[torch.Tensor, torch.Tensor]],
quant_block_size: Optional[Tuple[int, int]] = None,
) -> Dict[str, torch.Tensor]:
"""Convert weights FROM Megatron format with quantization."""
raise NotImplementedError("megatron_to_hf_quant not implemented for this mapping")
def broadcast_from_pp_rank(
self, tensor: Optional[torch.Tensor], cache_key: Optional[str] = None
) -> Optional[torch.Tensor]:
"""Broadcast a tensor from the pipeline-parallel rank that owns it.
Broadcasts to **all** PP ranks. This mirrors the behaviour of
`broadcast_from_megatron_pp` in the original MMapping implementation and
additionally keeps the tensor-parallel metadata (`tensor_model_parallel`,
`partition_dim`) consistent on every rank.
Args:
tensor (Optional[torch.Tensor]): The local tensor if the current PP
rank owns it. ``None`` otherwise.
Returns:
Optional[torch.Tensor]: The broadcasted tensor on every PP rank, or
``None`` if *no* PP rank owned the tensor (which indicates a bug
in the calling code).
"""
# PP-local export deliberately leaves non-owning stages with ``None``.
# The caller filters those tasks, while the owning stage continues into
# the normal TP/EP gathering and layout-conversion code below.
if _SKIP_PP_BROADCAST.get():
return tensor
# Fast-path when we are not using pipeline parallelism.
if self.pp_size == 1:
return tensor
# ------------------------------------------------------------------
# 1. Gather (shape, dtype, tensor_parallel flag, partition_dim) from
# every PP rank so that we can find the source rank.
# ------------------------------------------------------------------
if cache_key is not None and cache_key in self._tensor_spec_output_cache:
tensor_spec_output = self._tensor_spec_output_cache[cache_key]
else:
if tensor is not None:
shape = tensor.shape
dtype = tensor.dtype
tensor_parallel = getattr(tensor, "tensor_model_parallel", None)
partition_dim = getattr(tensor, "partition_dim", None)
tensor_spec = (shape, dtype, tensor_parallel, partition_dim)
else:
tensor_spec = None
tensor_spec_output: list[Optional[tuple]] = [None] * self.pp_size
torch.distributed.all_gather_object(tensor_spec_output, tensor_spec, group=self.pp_group)
self._tensor_spec_output_cache[cache_key] = tensor_spec_output
# ------------------------------------------------------------------
# 2. Identify the first owning rank (pick the lowest-ranked PP stage
# that holds the tensor). Certain architectures (MLA / DeepSeek-V3,
# MTP, or models with tied embeddings) legitimately place the same
# weight on more than one PP rank, so we must *not* raise on
# duplicates – instead we deterministically pick the first owner
# as the broadcast source.
# ------------------------------------------------------------------
target_tensor_spec = None
src_rank = None # Rank *inside* the PP group.
for rank, spec in enumerate(tensor_spec_output):
if spec is not None and target_tensor_spec is None:
target_tensor_spec = spec
src_rank = rank
if target_tensor_spec is None:
# No rank had the tensor – this is an error in the caller.
raise ValueError(
f"Object must exist on at least one PP rank. "
f"megatron_param={self.megatron_param}, hf_param={self.hf_param}, "
f"cache_key={cache_key}"
)
# ------------------------------------------------------------------
# 3. Ensure every rank has an allocated tensor with the right shape
# and dtype before the broadcast.
# ------------------------------------------------------------------
if tensor is None:
shape, dtype, tensor_parallel, partition_dim = target_tensor_spec
# Use CPU by default, unless CUDA is available
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
tensor = torch.empty(shape, dtype=dtype, device=device)
if tensor_parallel is not None:
tensor.tensor_model_parallel = tensor_parallel
if partition_dim is not None:
tensor.partition_dim = partition_dim
# ------------------------------------------------------------------
# 4. Broadcast from the source PP rank to all other PP ranks.
# ------------------------------------------------------------------
global_src = torch.distributed.get_global_rank(group=self.pp_group, group_rank=src_rank)
torch.distributed.broadcast(tensor, src=global_src, group=self.pp_group)
return tensor
def broadcast_obj_from_pp_rank(self, obj: Optional[Any], cache_key: Optional[str] = None) -> Any:
"""Broadcast any Python object from the PP rank that owns it.
This method is useful for broadcasting configuration objects or
other metadata across pipeline parallel ranks. Results are cached
after the first call to avoid redundant broadcasts.
Args:
obj (Optional[Any]): Object to broadcast (None on non-owning ranks).
cache_key (Optional[str]): Optional cache key. If not provided,
no caching will be performed.
Returns:
Any: Broadcasted object on all ranks.
Raises:
ValueError: If object does not exist on any rank.
"""
if _SKIP_PP_BROADCAST.get():
return obj
if self.pp_size == 1:
if obj is None:
raise ValueError(f"{self.megatron_param}: Object must exist on at least one PP rank")
return obj
# Check if we already have a cached result (only if cache_key is provided)
if cache_key is not None and cache_key in self._broadcast_obj_cache:
return self._broadcast_obj_cache[cache_key]
# ------------------------------------------------------------------
# 1. Gather presence flags from all PP ranks to find the source rank
# ------------------------------------------------------------------
has_obj = obj is not None
obj_flags = [None] * self.pp_size
torch.distributed.all_gather_object(obj_flags, has_obj, group=self.pp_group)
# ------------------------------------------------------------------
# 2. Identify the first owning rank (lowest PP stage with the object).
# Certain architectures (MLA, MTP, tied embeddings) place the same
# parameter on multiple PP ranks — pick the first owner.
# ------------------------------------------------------------------
src_rank = None # Rank *inside* the PP group
for rank, flag in enumerate(obj_flags):
if flag:
src_rank = rank
break
if src_rank is None:
raise ValueError(f"{self.megatron_param}: Object must exist on at least one PP rank")
# ------------------------------------------------------------------
# 3. Broadcast the object from the source rank to all ranks
# ------------------------------------------------------------------
# Use broadcast_object_list which is more robust than all_gather_object
obj_list = [obj]
pp_ranks = torch.distributed.get_process_group_ranks(self.pp_group)
global_src = pp_ranks[src_rank]
torch.distributed.broadcast_object_list(obj_list, src=global_src, group=self.pp_group)
result = obj_list[0]
# Cache the result for future calls (only if cache_key is provided)
if cache_key is not None:
self._broadcast_obj_cache[cache_key] = result
return result
def clear_broadcast_cache(self):
"""Clear the broadcast object cache.
This can be useful for testing or if the objects being broadcast
might change during the lifetime of the mapping.
"""
self._broadcast_obj_cache.clear()
def clear_tensor_spec_output_cache(self):
"""Clear the tensor spec output cache.
This can be useful for testing or if the tensor spec output
might change during the lifetime of the mapping.
"""
self._tensor_spec_output_cache.clear()
def broadcast_tensor_to_tp_ranks(self, tensor: torch.Tensor, src_rank: int = 0) -> torch.Tensor:
"""Broadcast a tensor to all TP ranks.
Args:
tensor (torch.Tensor): The tensor to broadcast.
src_rank (int, optional): The source rank within the TP group.
Defaults to 0.
Returns:
torch.Tensor: The broadcasted tensor.
"""
if self.tp_size == 1:
return tensor
global_src = torch.distributed.get_global_rank(group=self.tp_group, group_rank=src_rank)
torch.distributed.broadcast(tensor, src=global_src, group=self.tp_group)
return tensor
def _get_shard_spec(
self,
*,
shard_size: int,
megatron_module: nn.Module | None = None,
global_size: int | None = None,
global_size_attr: str | None = None,
) -> tuple[int, int]:
"""Get the unique TP shard count and shard rank for the current TP rank.
This supports layouts where TP ranks may contain replicated copies of a
smaller set of unique shards, such as KV-head sharding when
``num_query_groups < tensor_model_parallel_size``.
Args:
shard_size: Number of elements in the local shard along the sharded axis.
megatron_module: Optional Megatron module carrying layout metadata.
global_size: Explicit global size along the sharded axis.
global_size_attr: Optional module attribute that stores the global
size along the sharded axis.
Returns:
Tuple of ``(shard_world_size, shard_rank)`` where ``shard_world_size``
is the number of unique shards and ``shard_rank`` is the current
rank's unique shard index.
"""
resolved_global_size = shard_size * self.tp_size
if global_size is not None:
resolved_global_size = global_size
elif megatron_module is not None and global_size_attr is not None:
resolved_global_size = getattr(megatron_module, global_size_attr, resolved_global_size)
if resolved_global_size % shard_size != 0:
raise ValueError(f"Invalid sharded layout: global_size={resolved_global_size}, shard_size={shard_size}")
shard_world_size = resolved_global_size // shard_size
if self.tp_size % shard_world_size != 0:
raise ValueError(
f"Invalid replicated shard layout: tp_size={self.tp_size}, shard_world_size={shard_world_size}"
)
replicas = self.tp_size // shard_world_size
shard_rank = self.tp_rank // replicas
return shard_world_size, shard_rank
def scatter_to_tp_ranks(
self,
splits: Optional[List[torch.Tensor]],
output_shape: torch.Size,
dtype: torch.dtype,
device: torch.device,
src_rank: int = 0,
) -> torch.Tensor:
"""Scatter tensor splits to TP ranks.
Args:
splits (Optional[List[torch.Tensor]]): A list of tensor shards to
scatter. Only rank `src_rank` needs this.
output_shape (torch.Size): The shape of the output tensor on each rank.
dtype (torch.dtype): The data type of the output tensor.
device (torch.device): The device for the output tensor.
src_rank (int, optional): The source rank for the scatter operation.
Defaults to 0.
Returns:
torch.Tensor: The scattered tensor shard on the current rank.
"""
if self.tp_size == 1:
return splits[0].to(device=device, dtype=dtype) if splits else None
output = torch.empty(output_shape, dtype=dtype, device=device)
global_src = torch.distributed.get_global_rank(group=self.tp_group, group_rank=src_rank)
scatter_list = None
if self.tp_rank == src_rank and splits:
scatter_list = [s.to(device=device, dtype=dtype).contiguous() for s in splits]
torch.distributed.scatter(
output,
scatter_list,
src=global_src,
group=self.tp_group,
)
return output
def gather_from_tp_ranks(self, tensor: torch.Tensor) -> List[torch.Tensor]:
"""Gather tensors from all TP ranks.
Args:
tensor (torch.Tensor): The tensor shard to be gathered from the
current rank.
Returns:
List[torch.Tensor]: A list of tensor shards from all TP ranks.
"""
if self.tp_size == 1:
return [tensor]
gathered = [torch.empty_like(tensor) for _ in range(self.tp_size)]
torch.distributed.all_gather(gathered, tensor, group=self.tp_group)
return gathered
@staticmethod
def _count_wildcard_groups(pattern: str) -> int:
"""Count the number of wildcard capture groups in a pattern.
Args:
pattern: Pattern string with * and ** wildcards
Returns:
Number of capture groups that will be generated
Note:
** counts as 1 group, * counts as 1 group
** must be counted before * to avoid double-counting
"""
count = 0
remaining = pattern
# Count ** patterns first
while "**" in remaining:
count += 1
remaining = remaining.replace("**", "", 1)
# Count remaining * patterns
count += remaining.count("*")
return count
def _validate_patterns(self):
"""Validate wildcard consistency between patterns.
Skipped automatically for grouped-export mappings where the megatron
side intentionally has more wildcards than the HF side.
"""
if getattr(self, "is_grouped_export", False):
return
megatron_param_wildcards = self._count_wildcard_groups(self.megatron_param)
if isinstance(self.hf_param, str):
hf_param_wildcards = self._count_wildcard_groups(self.hf_param)
if megatron_param_wildcards != hf_param_wildcards:
raise ValueError(
f"Wildcard count mismatch: megatron_param='{self.megatron_param}' has "
f"{megatron_param_wildcards} wildcards, hf_param='{self.hf_param}' has {hf_param_wildcards}"
)
else:
for key, pattern in self.hf_param.items():
hf_param_wildcards = self._count_wildcard_groups(pattern)
if megatron_param_wildcards != hf_param_wildcards:
raise ValueError(
f"Wildcard count mismatch: megatron_param='{self.megatron_param}' has "
f"{megatron_param_wildcards} wildcards, hf_param['{key}']='{pattern}' has {hf_param_wildcards}"
)
def _normalize_expert_param_name(self, param_name: str) -> str:
"""Normalize expert parameter name by replacing trailing numbers with 0.
e.g. experts.weight15 -> experts.weight0, experts.bias15 -> experts.bias0
Args:
param_name (str): Parameter name that may end with a number.
Returns:
str: Parameter name with trailing number replaced by 0.