-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathgpt_bridge.py
More file actions
1981 lines (1906 loc) · 110 KB
/
gpt_bridge.py
File metadata and controls
1981 lines (1906 loc) · 110 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) ModelScope Contributors. All rights reserved.
import math
import re
import torch
import torch.distributed as dist
import torch.nn.functional as F
from contextlib import contextmanager
from megatron.core import mpu
from peft import PeftModel
from peft.utils import ModulesToSaveWrapper
from tqdm import tqdm
from transformers import PreTrainedModel
from transformers.utils import ContextManagers
from typing import Callable, List, Optional, Union
from mcore_bridge.config import ModelConfig
from mcore_bridge.tuners import LoraParallelLinear
from mcore_bridge.utils import (MxFp4Dequantizer, SafetensorLazyLoader, StreamingSafetensorSaver, deep_getattr,
gc_collect, get_logger, is_master, unwrap_model)
logger = get_logger()
EP_PP_SIZE = None
EP_PP_GROUP = None
EP_PP_RANK = None
class GPTBridge:
fp8_block_size = 128
hf_layers_prefix = 'model.layers'
hf_mtp_prefix = 'model.layers'
hf_embed_key = 'model.embed_tokens.weight'
hf_final_layernorm_key = 'model.norm.weight'
hf_lm_head_key = 'lm_head.weight'
hf_score_key = 'score.weight'
hf_state_dict_mapping = {}
# HF Keys
hf_q_norm_key = 'q_norm.weight'
hf_k_norm_key = 'k_norm.weight'
hf_o_proj_key = 'o_proj'
hf_attn_prefix = 'self_attn'
hf_mlp_prefix = 'mlp'
hf_post_attention_layernorm = 'post_attention_layernorm'
hf_gate_key = 'gate.weight'
hf_shared_expert_key = None
hf_expert_bias_key = 'gate.e_score_correction_bias'
additional_dim0_keys = set()
additional_dim1_keys = set()
def __init__(self, config: ModelConfig):
self.config = config
self._disable_tqdm = False
self._target_device = None
self._only_master_rank = False
self._peft_target_modules = set()
self._peft_modules_to_save = set()
self._fp8_skip_modules = set()
self._peft_format = False
self._adapter_name = 'default'
self._is_saving = False
self.model_type = config.hf_model_type
self.llm_model_type = config.llm_model_type
self.is_multimodal = config.is_multimodal
self.module_mapping = config.model_meta.visual_cls.module_mapping if self.is_multimodal else {}
self.tp_size = self.config.tensor_model_parallel_size
self.pp_size = self.config.pipeline_model_parallel_size
self.etp_size = self.config.expert_tensor_parallel_size
self.ep_size = self.config.expert_model_parallel_size
self.tp_group = mpu.get_tensor_model_parallel_group()
self.pp_group = mpu.get_pipeline_model_parallel_group()
self.etp_group = mpu.get_expert_tensor_parallel_group()
self.ep_group = mpu.get_expert_model_parallel_group()
self.tp_rank = mpu.get_tensor_model_parallel_rank()
self.pp_rank = mpu.get_pipeline_model_parallel_rank()
self.etp_rank = mpu.get_expert_tensor_parallel_rank()
self.ep_rank = mpu.get_expert_model_parallel_rank()
self._fp8_quantizer = None
self.mxfp4_quantizer = MxFp4Dequantizer()
dp_size = dist.get_world_size() // self.etp_size // self.ep_size // self.pp_size
expert_decoder_rank_generator = mpu.RankGenerator(
tp=self.etp_size,
ep=self.ep_size,
dp=dp_size,
pp=self.pp_size,
cp=1,
order='tp-cp-ep-dp-pp',
rank_offset=0,
)
rank = dist.get_rank()
global EP_PP_GROUP, EP_PP_RANK, EP_PP_SIZE
if EP_PP_GROUP is None:
for ranks in expert_decoder_rank_generator.get_ranks('ep-pp'):
group = mpu.create_group(
ranks,
group_desc='EP-PP-GROUP',
)
if rank in ranks:
EP_PP_SIZE = self.ep_size * self.pp_size
EP_PP_GROUP = group
EP_PP_RANK = dist.get_rank(group)
self.ep_pp_size = EP_PP_SIZE
self.ep_pp_group = EP_PP_GROUP
self.ep_pp_rank = EP_PP_RANK
def _get_tp_split_dim(self, mg_key: Optional[str]) -> Optional[int]:
if mg_key is None:
return
if '.' not in mg_key:
if mg_key in {'dt_bias', 'A_log'}:
return 0
else:
return
# ColumnLinear
dim0_keys = {
'word_embeddings',
'linear_qkv',
'in_proj',
'in_proj_qkvz',
'in_proj_ba',
'conv1d',
# mla
'linear_q_proj',
'linear_q_up_proj',
'linear_kv_up_proj',
# mtp
'eh_proj',
} & self.additional_dim0_keys
if self.config.task_type in {'causal_lm', 'generative_reranker'}:
dim0_keys.add('output_layer')
# RowLinear
dim1_keys = {'out_proj', 'linear_proj', 'linear_fc2'} & self.additional_dim1_keys
if 'lora_A' not in mg_key and 'lora_B' not in mg_key:
key, suffix = mg_key.rsplit('.', 2)[-2:]
if suffix == 'layer_norm_weight':
return
elif mg_key == 'core_attention.softmax_offset':
return 0
elif key in dim0_keys:
return 0
elif key in {'linear_fc1'} | dim1_keys and suffix != 'bias':
# linear_fc1 shape [2, X, Y]
return 1
else:
mg_key_splited = mg_key.rsplit('.', 3)
key, lora_name = mg_key_splited[:2]
if lora_name == 'lora_A':
if key in dim1_keys:
return 1
elif lora_name == 'lora_B':
if key in dim0_keys:
return 0
elif key in {'linear_fc1'}:
return 1
def _split_tp(self, hf_weight, tp_dim, is_expert, is_embedding: bool):
tp_size = self.etp_size if is_expert else self.tp_size
tp_rank = self.etp_rank if is_expert else self.tp_rank
if is_embedding:
padding_size = math.ceil(hf_weight.shape[0] / tp_size) * tp_size - hf_weight.shape[0]
if padding_size > 0:
new_size = hf_weight.shape[0] + padding_size
logger.warning(
f'Padding embedding from {hf_weight.shape[0]} to {new_size} (padding size: {padding_size})')
hf_weight = F.pad(hf_weight, (0, 0, 0, padding_size))
if tp_dim is not None and tp_size > 1:
tensor = hf_weight.chunk(tp_size, dim=tp_dim)[tp_rank]
else:
tensor = hf_weight
return tensor
def _set_weight(
self,
mg_param: Union[torch.Tensor, List[torch.Tensor]],
hf_weight: torch.Tensor,
mg_key: str,
offset: float = 0,
is_expert: bool = False,
*,
hf_scale_inv: Optional[torch.Tensor] = None,
):
# tp/etp
tp_dim = self._get_tp_split_dim(mg_key)
is_embedding = mg_key in {'embedding.word_embeddings.weight', 'output_layer.weight'}
tensor = self._split_tp(hf_weight, tp_dim, is_expert, is_embedding=is_embedding)
del hf_weight
if not isinstance(mg_param, (list, tuple)):
mg_param = [mg_param]
if hf_scale_inv is not None:
hf_scale_inv = self._split_tp(hf_scale_inv, tp_dim, is_expert, is_embedding=is_embedding)
hf_scale_inv = hf_scale_inv.chunk(len(mg_param), dim=0)
if offset:
assert hf_scale_inv is None, f'mg_key: {mg_key}'
tensor = tensor + offset
tensor_list = tensor.chunk(len(mg_param), dim=0)
for i, param in enumerate(mg_param):
tensor = tensor_list[i].reshape(*param.shape)
if self._is_fp8_param(param):
if hf_scale_inv is None:
param.data.copy_(tensor)
param._high_precision_init_val.copy_(tensor)
else:
tensor = tensor.view(torch.uint8)
param._rowwise_data.data.copy_(tensor)
self._copy_scale_inv(param, hf_scale_inv[i])
del param.get_high_precision_init_val
else:
if hf_scale_inv is not None:
fp8_tensor = self.fp8_quantizer.make_empty(tensor.shape)
fp8_tensor._rowwise_data.copy_(tensor.view(torch.uint8))
self._copy_scale_inv(fp8_tensor, hf_scale_inv[i])
tensor = fp8_tensor
param.data.copy_(tensor)
@staticmethod
def _copy_scale_inv(tensor, scale_inv):
scale_inv = scale_inv.reshape(-1, scale_inv.shape[-1])
if scale_inv.shape[-1] < tensor._rowwise_scale_inv.shape[-1]:
scale_inv = torch.concat([
scale_inv,
scale_inv.new_zeros((scale_inv.shape[0], tensor._rowwise_scale_inv.shape[-1] - scale_inv.shape[1]))
],
dim=-1)
tensor._rowwise_scale_inv.data.copy_(scale_inv)
@property
def fp8_quantizer(self):
if self._fp8_quantizer is None:
from transformer_engine.pytorch import Float8BlockQuantizer
from transformer_engine_torch import DType as TE_DType
self._fp8_quantizer = Float8BlockQuantizer(TE_DType.kFloat8E4M3, rowwise=True, columnwise=True)
return self._fp8_quantizer
@staticmethod
def _is_fp8_param(param):
try:
from transformer_engine.pytorch import Float8BlockwiseQTensor
return isinstance(param, Float8BlockwiseQTensor)
except ImportError:
return False
def _set_module(self, mg_module, hf_state_dict, hf_prefix: str, to_mcore: bool):
if to_mcore:
if mg_module is None:
return {}
hf_state_dict = {k: v.load() for k, v in self._remove_prefix(hf_state_dict, hf_prefix).items()}
if self._peft_format:
new_state_dict = {}
for k, v in hf_state_dict.items():
k = k.replace('.lora_A.', f'.lora_A.{self._adapter_name}.')
k = k.replace('.lora_B.', f'.lora_B.{self._adapter_name}.')
k = k.replace('.modules_to_save.', f'.modules_to_save.{self._adapter_name}.')
new_state_dict[k] = v
hf_state_dict = new_state_dict
incompatible_keys = mg_module.load_state_dict(hf_state_dict, strict=False)
missing_keys = incompatible_keys.missing_keys
if self._peft_format:
missing_keys = [
k for k in incompatible_keys.missing_keys
if '.lora_A.' in k or '.lora_B.' in k or '.modules_to_save.' in k
]
assert len(missing_keys) == 0, f'incompatible_keys.missing_keys: {missing_keys}'
return {}
else:
hf_state_dict = None if mg_module is None else mg_module.state_dict()
if hf_state_dict is not None:
new_state_dict = {}
for k, v in hf_state_dict.items():
if self._peft_format:
# Without adding a leading '.' here (e.g., '.lora_A.'),
# we avoid the case where mg_module itself is a linear layer (such as proj1).
if ('lora_A.' in k or 'lora_B.' in k
or 'modules_to_save.' in k) and f'.{self._adapter_name}.' in k:
k = k.replace(f'.{self._adapter_name}.', '.')
new_state_dict[k] = v
if 'lora_A.' in k or 'lora_B.' in k:
parts = k.rsplit('.lora_', 1)
name = parts[0].rsplit('.')[-1] if len(parts) > 1 else hf_prefix.rstrip('.').rsplit(
'.')[-1]
if name:
self._peft_target_modules.add(name)
else:
parts = k.rsplit('.modules_to_save.', 1)
name = parts[0].rsplit('.')[-1] if len(parts) > 1 else hf_prefix.rstrip('.').rsplit(
'.')[-1]
if name:
self._peft_modules_to_save.add(name)
else:
if 'lora_A.' in k or 'lora_B.' in k or 'original_module.' in k:
continue
if 'modules_to_save.' in k and f'modules_to_save.{self._adapter_name}.' not in k:
continue
k = k.replace('base_layer.', '')
k = k.replace(f'modules_to_save.{self._adapter_name}.', '')
new_state_dict[k] = v
hf_state_dict = new_state_dict
if self.pp_size > 1:
src_rank = torch.tensor([0 if hf_state_dict is None else self.pp_rank],
dtype=torch.int64,
device='cuda')
dist.all_reduce(src_rank, group=self.pp_group)
src_rank = dist.get_global_rank(self.pp_group, src_rank.item())
meta_data = [None] if hf_state_dict is None else [list(hf_state_dict.keys())]
dist.broadcast_object_list(meta_data, src=src_rank, group=self.pp_group)
if meta_data[0] is None:
return {}
hf_state_dict = hf_state_dict or {k: None for k in meta_data[0]}
for k, v in hf_state_dict.items():
v, _ = self._get_weight(v, None)
hf_state_dict[k] = v
elif hf_state_dict is None:
return {}
else:
if self._target_device is not None:
for k, v in hf_state_dict.items():
hf_state_dict[k] = v.to(self._target_device)
return self._add_prefix(hf_state_dict, hf_prefix)
def _all_gather_tp(self, tensor, tp_dim, is_expert):
tensor = None if tensor is None else tensor.to('cuda')
tp_size = self.etp_size if is_expert else self.tp_size
tp_group = self.etp_group if is_expert else self.tp_group
if tensor is not None and tp_dim is not None and tp_size > 1:
if tp_dim == 0:
# save memory
tensor_shape = list(tensor.shape)
tensor_shape[0] *= tp_size
output = tensor.new_empty(tensor_shape)
dist.all_gather_into_tensor(
output,
tensor,
group=tp_group,
)
tensor = output
else:
output = [torch.empty_like(tensor) for _ in range(tp_size)]
dist.all_gather(
output,
tensor,
group=tp_group,
)
tensor = torch.cat(output, dim=tp_dim)
del output
return tensor
def _broadcast_ep_pp(self, tensor, is_expert):
pp_group = self.ep_pp_group if is_expert else self.pp_group
pp_size = self.ep_pp_size if is_expert else self.pp_size
pp_rank = self.ep_pp_rank if is_expert else self.pp_rank
# pp/ep
if pp_size > 1:
src_rank = torch.tensor([0 if tensor is None else pp_rank], dtype=torch.int64, device='cuda')
dist.all_reduce(src_rank, group=pp_group)
src_rank = dist.get_global_rank(pp_group, src_rank.item())
meta_data = torch.zeros(10, dtype=torch.int64, device='cuda')
dtype_mapping = {torch.float64: 0, torch.float32: 1, torch.float16: 2, torch.bfloat16: 3, torch.uint8: 4}
dtype_mapping_r = {v: k for k, v in dtype_mapping.items()}
if tensor is None:
dist.broadcast(meta_data, src=src_rank, group=pp_group)
assert meta_data[0].item() > 0, f'meta_data: {meta_data}'
shape = meta_data[1:1 + meta_data[0]].tolist()
dtype = dtype_mapping_r[meta_data[-1].item()]
tensor = torch.empty(shape, device='cuda', dtype=dtype)
dist.broadcast(tensor, src=src_rank, group=pp_group)
else:
meta_data[0] = tensor.ndim
meta_data[1:1 + tensor.ndim] = torch.tensor(tensor.shape, dtype=torch.int64, device='cuda')
meta_data[-1] = dtype_mapping[tensor.dtype]
dist.broadcast(meta_data, src=src_rank, group=pp_group)
dist.broadcast(tensor, src=src_rank, group=pp_group)
return tensor
def _get_weight(
self,
mg_weight: Union[torch.Tensor, List[torch.Tensor]],
mg_key: Optional[str],
offset: float = 0,
is_expert: bool = False,
):
# tp/etp
mg_scale_inv = None
tensor = mg_weight
if tensor is not None:
if not isinstance(tensor, (list, tuple)):
tensor = [tensor]
if self._is_fp8_param(tensor[0]):
mg_scale_inv = [
t._rowwise_scale_inv[..., :math.ceil(t._rowwise_data.shape[-1] / self.fp8_block_size)]
for t in tensor
]
tensor = [t._rowwise_data for t in tensor]
del mg_weight
if tensor is not None:
assert isinstance(tensor, (list, tuple)), f'mg_key: {mg_key}'
tensor = torch.concat(tensor, dim=0)
if mg_scale_inv is not None:
mg_scale_inv = torch.concat(mg_scale_inv, dim=0)
num_local_experts = self.config.num_moe_experts // self.ep_size if is_expert else 1
tp_dim = self._get_tp_split_dim(mg_key)
is_linear_fc1 = (mg_key is not None and mg_key.split('.', 1)[0] == 'linear_fc1' and tp_dim is not None)
if tensor is not None and is_linear_fc1:
tensor = tensor.view(num_local_experts * 2, -1, tensor.shape[-1])
if mg_scale_inv is not None:
mg_scale_inv = mg_scale_inv.view(num_local_experts * 2, -1, mg_scale_inv.shape[-1])
tensor = self._all_gather_tp(tensor, tp_dim, is_expert)
tensor = self._broadcast_ep_pp(tensor, is_expert)
if tensor.dtype == torch.uint8:
mg_scale_inv = self._all_gather_tp(mg_scale_inv, tp_dim, is_expert)
mg_scale_inv = self._broadcast_ep_pp(mg_scale_inv, is_expert)
tensor = tensor.view(torch.float8_e4m3fn)
assert tensor is not None, f'mg_key: {mg_key}'
if offset:
assert mg_scale_inv is None, f'mg_key: {mg_key}'
tensor = tensor + offset
is_embedding = mg_key in {'embedding.word_embeddings.weight', 'output_layer.weight'}
if is_embedding and self.config.padded_vocab_size < tensor.shape[0]:
tensor = tensor[:self.config.padded_vocab_size]
if self._target_device is not None:
tensor = tensor.to(device=self._target_device)
if mg_scale_inv is not None:
mg_scale_inv = mg_scale_inv.to(device=self._target_device)
if self._only_master_rank and not is_master():
tensor = None
mg_scale_inv = None
if is_expert and tensor is not None:
if mg_key.endswith('bias'):
tensor = tensor.view(num_local_experts, -1)
else:
tensor = tensor.view(num_local_experts, -1, tensor.shape[-1])
if mg_scale_inv is not None:
mg_scale_inv = mg_scale_inv.view(num_local_experts, -1, mg_scale_inv.shape[-1])
return tensor, mg_scale_inv
def _set_state_dict(self,
mg_module,
mg_key: str,
hf_state_dict,
hf_key: str,
to_mcore: bool,
*,
offset: float = 0,
is_expert: bool = False,
_check_mg_param: bool = True):
if '.' in mg_key:
module_key, param_key = mg_key.rsplit('.', 1)
else:
module_key, param_key = None, mg_key
if '.' in hf_key:
hf_module_key, hf_param_key = hf_key.rsplit('.', 1)
else:
hf_module_key, hf_param_key = None, hf_key
sub_module = mg_module if module_key is None else deep_getattr(mg_module, module_key)
is_lora = isinstance(sub_module, LoraParallelLinear)
is_modules_to_save = isinstance(sub_module, ModulesToSaveWrapper)
if not to_mcore:
state = torch.tensor([is_lora, is_modules_to_save], dtype=torch.bool, device='cuda')
if is_expert and self.ep_pp_size > 1:
dist.all_reduce(state, group=self.ep_pp_group)
elif not is_expert and self.pp_size > 1:
dist.all_reduce(state, group=self.pp_group)
is_lora, is_modules_to_save = state
if is_lora and self._peft_format and param_key != 'layer_norm_weight':
if to_mcore:
lora_A_key = f'{module_key}.lora_A.{self._adapter_name}.{param_key}'
lora_B_key = f'{module_key}.lora_B.{self._adapter_name}.{param_key}'
mg_lora_A = deep_getattr(mg_module, f'{lora_A_key}')
mg_lora_B = deep_getattr(mg_module, f'{lora_B_key}')
hf_lora_A = hf_state_dict[f'{hf_module_key}.lora_A.{hf_param_key}'].load()
hf_lora_B = hf_state_dict[f'{hf_module_key}.lora_B.{hf_param_key}'].load()
self._set_weight(mg_lora_A, hf_lora_A, lora_A_key, offset, is_expert)
self._set_weight(mg_lora_B, hf_lora_B, lora_B_key, offset, is_expert)
else:
lora_A_key = f'{module_key}.lora_A.{self._adapter_name}.{param_key}'
lora_B_key = f'{module_key}.lora_B.{self._adapter_name}.{param_key}'
lora_A_tensor = deep_getattr(mg_module, f'{lora_A_key}.data')
lora_B_tensor = deep_getattr(mg_module, f'{lora_B_key}.data')
hf_lora_A_key = f'{hf_module_key}.lora_A.{hf_param_key}'
hf_lora_B_key = f'{hf_module_key}.lora_B.{hf_param_key}'
lora_A, _ = self._get_weight(lora_A_tensor, lora_A_key, offset, is_expert)
lora_B, _ = self._get_weight(lora_B_tensor, lora_B_key, offset, is_expert)
if lora_A is not None:
self._peft_target_modules.add(hf_module_key)
hf_state_dict[hf_lora_A_key] = lora_A
hf_state_dict[hf_lora_B_key] = lora_B
elif not self._peft_format or is_modules_to_save:
if is_lora:
mg_param = deep_getattr(sub_module, f'base_layer.{param_key}')
else:
mg_param = deep_getattr(sub_module, param_key)
if to_mcore:
if mg_param is None:
if _check_mg_param:
raise ValueError(f'mg_module: {mg_module}, mg_key: {mg_key}')
else:
return
hf_weight = hf_state_dict[hf_key].load()
if module_key in {
'embedding.word_embeddings', 'output_layer'
} and hf_weight.shape[0] < self.config.padded_vocab_size and self.config.task_type != 'seq_cls':
hf_weight = F.pad(hf_weight, (0, 0, 0, self.config.padded_vocab_size - hf_weight.shape[0]))
hf_scale_inv = None
if f'{hf_key}_scale_inv' in hf_state_dict:
hf_scale_inv = hf_state_dict[f'{hf_key}_scale_inv'].load()
self._set_weight(mg_param, hf_weight, mg_key, offset, is_expert, hf_scale_inv=hf_scale_inv)
else:
if is_modules_to_save:
self._peft_modules_to_save.add(hf_module_key)
weight, scale_inv = self._get_weight(None if mg_param is None else mg_param.data, mg_key, offset,
is_expert)
if weight is not None:
hf_state_dict[hf_key] = weight
if scale_inv is not None:
hf_state_dict[f'{hf_key}_scale_inv'] = scale_inv
@staticmethod
def _remove_prefix(state_dict, prefix: str):
if not prefix:
return state_dict
return {k[len(prefix):]: v for k, v in state_dict.items() if k.startswith(prefix)}
@staticmethod
def _add_prefix(state_dict, prefix: str):
if not prefix:
return state_dict
return {f'{prefix}{k}': v for k, v in state_dict.items()}
@staticmethod
def _filter_prefix(state_dict, prefix: str):
if not prefix:
return state_dict
return {k: v for k, v in state_dict.items() if k.startswith(prefix)}
def _set_qkv(self, mg_attn, hf_state_dict, to_mcore: bool):
config = self.config
num_query_groups = (
config.num_query_groups if config.num_query_groups is not None else config.num_attention_heads)
hidden_size_block = config.hidden_size // self.fp8_block_size
if to_mcore:
if isinstance(mg_attn.linear_qkv, LoraParallelLinear):
lora_A = hf_state_dict['q_proj.lora_A.weight'].load()
assert (lora_A == hf_state_dict['k_proj.lora_A.weight'].load()).all() and (
lora_A == hf_state_dict['v_proj.lora_A.weight'].load()
).all(), 'Need to ensure QKV\'s lora_A are consistent'
q_lora_B = hf_state_dict['q_proj.lora_B.weight'].load()
lora_B = torch.cat([
q_lora_B.reshape((num_query_groups, -1, q_lora_B.shape[-1])),
hf_state_dict['k_proj.lora_B.weight'].load().reshape((num_query_groups, -1, q_lora_B.shape[-1])),
hf_state_dict['v_proj.lora_B.weight'].load().reshape((num_query_groups, -1, q_lora_B.shape[-1])),
],
dim=1).reshape((-1, q_lora_B.shape[-1]))
self._set_weight(mg_attn.linear_qkv.lora_A[self._adapter_name].weight, lora_A,
'linear_qkv.lora_A.weight')
self._set_weight(mg_attn.linear_qkv.lora_B[self._adapter_name].weight, lora_B,
'linear_qkv.lora_B.weight')
elif not self._peft_format:
linear_qkv_weight = torch.cat([
hf_state_dict['q_proj.weight'].load().reshape((num_query_groups, -1, config.hidden_size)),
hf_state_dict['k_proj.weight'].load().reshape((num_query_groups, -1, config.hidden_size)),
hf_state_dict['v_proj.weight'].load().reshape((num_query_groups, -1, config.hidden_size)),
],
dim=1).reshape((-1, config.hidden_size))
qkv_scale_inv = None
if 'q_proj.weight_scale_inv' in hf_state_dict:
qkv_scale_inv = torch.cat([
hf_state_dict['q_proj.weight_scale_inv'].load().reshape(
(num_query_groups, -1, hidden_size_block)),
hf_state_dict['k_proj.weight_scale_inv'].load().reshape(
(num_query_groups, -1, hidden_size_block)),
hf_state_dict['v_proj.weight_scale_inv'].load().reshape(
(num_query_groups, -1, hidden_size_block)),
],
dim=1).reshape((-1, hidden_size_block))
self._set_weight(
mg_attn.linear_qkv.weight, linear_qkv_weight, 'linear_qkv.weight', hf_scale_inv=qkv_scale_inv)
else:
q_dim = self.config.kv_channels * self.config.num_attention_heads // self.config.num_query_groups
if self.config.attention_output_gate:
q_dim *= 2
kv_dim = self.config.kv_channels
q_block = q_dim // self.fp8_block_size
kv_block = kv_dim // self.fp8_block_size
is_lora = False if mg_attn is None else isinstance(mg_attn.linear_qkv,
LoraParallelLinear) and self._peft_format
is_lora = torch.tensor([is_lora], dtype=torch.bool, device='cuda')
if self.pp_size > 1:
dist.all_reduce(is_lora, group=self.pp_group)
if is_lora:
lora_A, _ = self._get_weight(
None if mg_attn is None else mg_attn.linear_qkv.lora_A[self._adapter_name].weight.data,
f'linear_qkv.lora_A.{self._adapter_name}.weight')
lora_B, _ = self._get_weight(
None if mg_attn is None else mg_attn.linear_qkv.lora_B[self._adapter_name].weight.data,
f'linear_qkv.lora_B.{self._adapter_name}.weight')
if lora_A is not None:
self._peft_target_modules.update({'q_proj', 'k_proj', 'v_proj'})
for key in ['q_proj', 'k_proj', 'v_proj']:
hf_state_dict[f'{key}.lora_A.weight'] = lora_A.clone()
lora_B = lora_B.reshape((num_query_groups, -1, lora_B.shape[-1]))
hf_state_dict['q_proj.lora_B.weight'] = lora_B[:, :q_dim, :].reshape(-1, lora_B.shape[-1]).clone()
hf_state_dict['k_proj.lora_B.weight'] = lora_B[:,
q_dim:-kv_dim, :].reshape(-1,
lora_B.shape[-1]).clone()
hf_state_dict['v_proj.lora_B.weight'] = lora_B[:, -kv_dim:, :].reshape(-1, lora_B.shape[-1]).clone()
elif not self._peft_format:
mg_attn_weight, scale_inv = self._get_weight(
None if mg_attn is None else mg_attn.linear_qkv.weight.data, 'linear_qkv.weight')
if mg_attn_weight is not None:
mg_attn_weight = mg_attn_weight.reshape((num_query_groups, -1, config.hidden_size))
hf_state_dict['q_proj.weight'] = mg_attn_weight[:, :q_dim, :].reshape(-1,
config.hidden_size).clone()
hf_state_dict['k_proj.weight'] = mg_attn_weight[:, q_dim:-kv_dim, :].reshape(
-1, config.hidden_size).clone()
hf_state_dict['v_proj.weight'] = mg_attn_weight[:, -kv_dim:, :].reshape(-1,
config.hidden_size).clone()
if scale_inv is not None:
scale_inv = scale_inv.reshape((num_query_groups, -1, hidden_size_block))
hf_state_dict['q_proj.weight_scale_inv'] = scale_inv[:, :q_block, :].reshape(
-1, hidden_size_block).clone()
hf_state_dict['k_proj.weight_scale_inv'] = scale_inv[:, q_block:-kv_block, :].reshape(
-1, hidden_size_block).clone()
hf_state_dict['v_proj.weight_scale_inv'] = scale_inv[:, -kv_block:, :].reshape(
-1, hidden_size_block).clone()
del mg_attn_weight
# Copy bias
if (config.add_bias_linear or config.add_qkv_bias) and not self._peft_format:
if to_mcore:
linear_qkv_bias = torch.cat([
hf_state_dict['q_proj.bias'].load().reshape((num_query_groups, -1)),
hf_state_dict['k_proj.bias'].load().reshape((num_query_groups, -1)),
hf_state_dict['v_proj.bias'].load().reshape((num_query_groups, -1)),
],
dim=1).reshape(-1)
self._set_weight(mg_attn.linear_qkv.bias, linear_qkv_bias, 'linear_qkv.bias')
else:
mg_attn_bias, _ = self._get_weight(None if mg_attn is None else mg_attn.linear_qkv.bias.data,
'linear_qkv.bias')
if mg_attn_bias is not None:
mg_attn_bias = mg_attn_bias.reshape((num_query_groups, -1))
hf_state_dict['q_proj.bias'] = mg_attn_bias[:, :q_dim].reshape(-1).clone()
hf_state_dict['k_proj.bias'] = mg_attn_bias[:, q_dim:-kv_dim].reshape(-1).clone()
hf_state_dict['v_proj.bias'] = mg_attn_bias[:, -kv_dim:].reshape(-1).clone()
return hf_state_dict
def _set_attn_state(self, mg_attn, hf_state_dict, hf_prefix: str, layer_idx: int, to_mcore: bool):
if to_mcore:
hf_state_dict = self._remove_prefix(hf_state_dict, hf_prefix)
else:
hf_state_dict = {}
config = self.config
hf_state_dict.update(self._set_qkv(mg_attn, hf_state_dict, to_mcore))
self._set_state_dict(mg_attn, 'linear_proj.weight', hf_state_dict, f'{self.hf_o_proj_key}.weight', to_mcore)
if config.add_bias_linear:
self._set_state_dict(mg_attn, 'linear_proj.bias', hf_state_dict, f'{self.hf_o_proj_key}.bias', to_mcore)
if getattr(config, 'softmax_type', 'vanilla') == 'learnable':
self._set_state_dict(mg_attn, 'core_attention.softmax_offset', hf_state_dict, 'sinks', to_mcore)
if config.qk_layernorm:
self._set_qk_layernorm(mg_attn, hf_state_dict, to_mcore)
if to_mcore:
hf_state_dict = {}
else:
hf_state_dict = self._add_prefix(hf_state_dict, hf_prefix)
return hf_state_dict
def _set_qk_layernorm(self, mg_attn, hf_state_dict, to_mcore):
self._set_state_dict(mg_attn, 'q_layernorm.weight', hf_state_dict, self.hf_q_norm_key, to_mcore)
self._set_state_dict(mg_attn, 'k_layernorm.weight', hf_state_dict, self.hf_k_norm_key, to_mcore)
def _set_moe_state(
self,
mg_mlp,
hf_state_dict,
hf_prefix: str,
layer_idx: int,
to_mcore: bool,
is_mtp: bool = False,
):
if to_mcore:
hf_state_dict = self._remove_prefix(hf_state_dict, hf_prefix)
else:
hf_state_dict = {}
config = self.config
hf_gate_key = self.hf_gate_key
if self.llm_model_type == 'gpt_oss':
hf_gate_key = 'router.weight'
self._set_state_dict(mg_mlp, 'router.weight', hf_state_dict, hf_gate_key, to_mcore)
if config.add_bias_linear:
self._set_state_dict(mg_mlp, 'router.bias', hf_state_dict, hf_gate_key.replace('weight', 'bias'), to_mcore)
if config.moe_router_enable_expert_bias:
self._set_state_dict(mg_mlp, 'router.expert_bias', hf_state_dict, self.hf_expert_bias_key, to_mcore)
if config.moe_shared_expert_intermediate_size:
hf_shared_expert_key = self.hf_shared_expert_key
if hf_shared_expert_key is None:
if 'qwen' in self.llm_model_type or self.model_type == 'llama4':
hf_shared_expert_key = 'shared_expert'
else:
hf_shared_expert_key = 'shared_experts'
hf_state_dict.update(
self._set_mlp_state(None if mg_mlp is None else mg_mlp.shared_experts, hf_state_dict,
f'{hf_shared_expert_key}.', layer_idx, to_mcore))
if config.moe_shared_expert_gate:
self._set_state_dict(mg_mlp, 'shared_experts.gate_weight', hf_state_dict, 'shared_expert_gate.weight',
to_mcore)
for ep_rank in range(self.ep_size):
mg_experts = None if mg_mlp is None else mg_mlp.experts
expert_available = ep_rank == self.ep_rank
if not expert_available:
if to_mcore:
continue
else:
mg_experts = None
hf_state_dict.update(
self._set_mlp_state(
mg_experts,
hf_state_dict,
'experts.',
layer_idx,
to_mcore,
ep_rank=ep_rank,
is_mtp=is_mtp,
))
if to_mcore:
hf_state_dict = {}
else:
hf_state_dict = self._add_prefix(hf_state_dict, hf_prefix)
return hf_state_dict
def _get_hf_experts_attr(self, is_mtp: bool = False):
# return hf_grouped, is_gate_up
if (self._is_saving and not is_mtp and not self.config.fp8_param and not self._peft_format
and self.model_type == 'qwen3_5_moe'):
return True, True
if self.model_type in {'glm4v_moe', 'kimi_vl', 'qwen3_omni_moe', 'qwen3_5_moe'} or self.llm_model_type in {
'qwen2_moe', 'qwen3_moe', 'deepseek_v2', 'deepseek_v3', 'kimi_k2', 'dots1', 'ernie4_5_moe', 'glm4_moe',
'glm4_moe_lite', 'minimax_m2', 'olmoe', 'qwen3_next', 'glm_moe_dsa', 'deepseek_v32'
}:
return False, False
elif self.model_type in {'qwen3_vl_moe', 'llama4'} or self.llm_model_type in {'gpt_oss'}:
return True, True
else:
# default
return False, False
def _get_need_transpose(self):
if self.model_type in {'qwen3_vl_moe', 'llama4'} or self.llm_model_type in {'gpt_oss'}:
return True
else:
return False
def _set_mlp_state(
self,
mg_mlp,
hf_state_dict,
hf_prefix: str,
layer_idx: int,
to_mcore: bool,
ep_rank: Optional[int] = None,
is_mtp: bool = False,
):
if to_mcore:
hf_state_dict = self._remove_prefix(hf_state_dict, hf_prefix)
is_expert = ep_rank is not None
config = self.config
num_local_experts = 1 if config.num_moe_experts is None else config.num_moe_experts // self.ep_size
hf_grouped = False
is_gate_up = False
if to_mcore:
if is_expert:
pattern = r'\d+\.down_proj'
hf_grouped = not any(re.match(pattern, k) is not None for k in hf_state_dict.keys())
is_gate_up = any('gate_up_proj' in k for k in hf_state_dict.keys())
# transformers 5.0 compatibility
if not to_mcore and is_expert:
hf_grouped, is_gate_up = self._get_hf_experts_attr(is_mtp)
need_transpose = False
if hf_grouped:
need_transpose = self._get_need_transpose()
if hf_grouped and not to_mcore:
hf_state_dict = self._remove_prefix(hf_state_dict, hf_prefix)
elif not to_mcore:
hf_state_dict = {}
# linear_fc1
if to_mcore:
has_scale_inv = any('_scale_inv' in k for k in hf_state_dict.keys())
if isinstance(mg_mlp.linear_fc1, LoraParallelLinear):
mg_lora_B = mg_mlp.linear_fc1.lora_B[self._adapter_name]
mg_lora_B = [getattr(mg_lora_B, f'weight{i}')
for i in range(num_local_experts)] if is_expert else mg_lora_B.weight
if is_gate_up:
if is_expert:
lora_A = torch.stack([
hf_state_dict[f'{i + ep_rank * num_local_experts}.gate_up_proj.lora_A.weight'].load()
for i in range(num_local_experts)
])
lora_B = torch.concat([
hf_state_dict[f'{i + ep_rank * num_local_experts}.gate_up_proj.lora_B.weight'].load()
for i in range(num_local_experts)
])
else:
lora_A = hf_state_dict['gate_up_proj.lora_A.weight'].load()
lora_B = hf_state_dict['gate_up_proj.lora_B.weight'].load()
else:
if is_expert:
lora_A = torch.concat([
hf_state_dict[f'{i + ep_rank * num_local_experts}.gate_proj.lora_A.weight'].load()
for i in range(num_local_experts)
])
up_lora_A = torch.concat([
hf_state_dict[f'{i + ep_rank * num_local_experts}.up_proj.lora_A.weight'].load()
for i in range(num_local_experts)
])
weight_list = []
for i in range(num_local_experts):
gate_lora_B = hf_state_dict[
f'{i + ep_rank * num_local_experts}.gate_proj.lora_B.weight'].load()
up_lora_B = hf_state_dict[f'{i + ep_rank * num_local_experts}.up_proj.lora_B.weight'].load()
weight_list.append(torch.stack([gate_lora_B, up_lora_B], dim=0))
lora_B = torch.concat(weight_list, dim=0)
else:
lora_A = hf_state_dict['gate_proj.lora_A.weight'].load()
up_lora_A = hf_state_dict['up_proj.lora_A.weight'].load()
gate_lora_B = hf_state_dict['gate_proj.lora_B.weight'].load()
up_lora_B = hf_state_dict['up_proj.lora_B.weight'].load()
lora_B = torch.stack([gate_lora_B, up_lora_B], dim=0)
assert (
lora_A == up_lora_A).all(), 'Need to ensure lora_A consistency between gate_proj and up_proj'
mg_lora_A = mg_mlp.linear_fc1.lora_A[self._adapter_name]
mg_lora_A = [getattr(mg_lora_A, f'weight{i}')
for i in range(num_local_experts)] if is_expert else mg_lora_A.weight
self._set_weight(
mg_lora_A, lora_A, f'linear_fc1.lora_A.{self._adapter_name}.weight', is_expert=is_expert)
self._set_weight(
mg_lora_B, lora_B, f'linear_fc1.lora_B.{self._adapter_name}.weight', is_expert=is_expert)
elif not self._peft_format:
fc1_weight = [getattr(mg_mlp.linear_fc1, f'weight{i}')
for i in range(num_local_experts)] if is_expert else mg_mlp.linear_fc1.weight
fc1_bias = None
if config.add_bias_linear:
assert is_expert and not has_scale_inv, 'not support' # TODO
fc1_bias = [getattr(mg_mlp.linear_fc1, f'bias{i}') for i in range(num_local_experts)]
gate_up_scale_inv = None
if is_gate_up:
if is_expert:
if hf_grouped:
if 'gate_up_proj_blocks' in hf_state_dict:
blocks = hf_state_dict['gate_up_proj_blocks'].load()
scales = hf_state_dict['gate_up_proj_scales'].load()
gate_up_proj_weight = self.mxfp4_quantizer.convert(blocks, scales)
else:
gate_up_proj_weight = hf_state_dict['gate_up_proj'].load()
if need_transpose:
gate_up_proj_weight = gate_up_proj_weight.transpose(1, 2)
gate_up_proj_weight = gate_up_proj_weight[ep_rank * num_local_experts:(ep_rank + 1)
* num_local_experts]
if has_scale_inv:
gate_up_scale_inv = hf_state_dict['gate_up_proj_scale_inv'].load()
if need_transpose:
gate_up_scale_inv = gate_up_scale_inv.transpose(1, 2)
gate_up_scale_inv = gate_up_scale_inv[ep_rank * num_local_experts:(ep_rank + 1)
* num_local_experts]
if fc1_bias is not None:
gate_up_proj_bias = hf_state_dict['gate_up_proj_bias'].load()
gate_up_proj_bias = gate_up_proj_bias[ep_rank * num_local_experts:(ep_rank + 1)
* num_local_experts]
if self.llm_model_type == 'gpt_oss':
gate_proj_weight = gate_up_proj_weight[:, ::2]
up_proj_weight = gate_up_proj_weight[:, 1::2]
gate_proj_bias, up_proj_bias = gate_up_proj_bias[:, ::2], gate_up_proj_bias[:, 1::2]
gate_up_proj_weight = torch.concat([gate_proj_weight, up_proj_weight], dim=1)
gate_up_proj_bias = torch.concat([gate_proj_bias, up_proj_bias], dim=1)
del gate_proj_weight, up_proj_weight, gate_proj_bias, up_proj_bias
else:
gate_up_proj_weight = torch.concat([
hf_state_dict[f'{i + ep_rank * num_local_experts}.gate_up_proj.weight'].load()
for i in range(num_local_experts)
],
dim=0)
if has_scale_inv:
gate_up_scale_inv = torch.concat([
hf_state_dict[f'{i + ep_rank * num_local_experts}.gate_up_proj.weight_scale_inv'].
load() for i in range(num_local_experts)
],
dim=0)
gate_up_proj_weight = gate_up_proj_weight.reshape(num_local_experts * 2, -1,
gate_up_proj_weight.shape[-1])
if has_scale_inv:
gate_up_scale_inv = gate_up_scale_inv.reshape(num_local_experts * 2, -1,
gate_up_scale_inv.shape[-1])
else:
gate_up_proj_weight = hf_state_dict['gate_up_proj.weight'].load()
gate_up_proj_weight = gate_up_proj_weight.view(2, -1, gate_up_proj_weight.shape[-1])
if has_scale_inv:
gate_up_scale_inv = hf_state_dict['gate_up_proj.weight_scale_inv'].load()
gate_up_scale_inv = gate_up_scale_inv.view(2, -1, gate_up_scale_inv.shape[-1])
else:
if is_expert:
weight_list = []
start_idx = ep_rank * num_local_experts
for i in range(num_local_experts):
gate_proj_weight = hf_state_dict[f'{start_idx + i}.gate_proj.weight'].load()
up_proj_weight = hf_state_dict[f'{start_idx + i}.up_proj.weight'].load()
weight_list.append(torch.stack([gate_proj_weight, up_proj_weight], dim=0))
gate_up_proj_weight = torch.concat(weight_list, dim=0)
if has_scale_inv:
scale_inv_list = []
for i in range(num_local_experts):
gate_scale_inv = hf_state_dict[f'{start_idx + i}.gate_proj.weight_scale_inv'].load()
up_scale_inv = hf_state_dict[f'{start_idx + i}.up_proj.weight_scale_inv'].load()
scale_inv_list.append(torch.stack([gate_scale_inv, up_scale_inv], dim=0))
gate_up_scale_inv = torch.concat(scale_inv_list, dim=0)
del weight_list
else:
gate_proj_weight = hf_state_dict['gate_proj.weight'].load()
up_proj_weight = hf_state_dict['up_proj.weight'].load()
gate_up_proj_weight = torch.stack([gate_proj_weight, up_proj_weight], dim=0)
if has_scale_inv:
gate_scale_inv = hf_state_dict['gate_proj.weight_scale_inv'].load()
up_scale_inv = hf_state_dict['up_proj.weight_scale_inv'].load()
gate_up_scale_inv = torch.stack([gate_scale_inv, up_scale_inv], dim=0)
self._set_weight(
fc1_weight,
gate_up_proj_weight,
'linear_fc1.weight',
is_expert=is_expert,
hf_scale_inv=gate_up_scale_inv)
if fc1_bias is not None:
self._set_weight(
fc1_bias, gate_up_proj_bias, 'linear_fc1.bias', is_expert=is_expert, hf_scale_inv=None)
else:
is_lora = False if mg_mlp is None else isinstance(mg_mlp.linear_fc1,
LoraParallelLinear) and self._peft_format
is_lora = torch.tensor([is_lora], dtype=torch.bool, device='cuda')
if is_expert and self.ep_pp_size > 1:
dist.all_reduce(is_lora, group=self.ep_pp_group)
elif not is_expert and self.pp_size > 1:
dist.all_reduce(is_lora, group=self.pp_group)
if is_lora:
if hf_grouped:
raise ValueError('Since this model\'s transformers and megatron have different expert '
'weight organization methods, LoRA weight conversion is not supported. '
'You can solve this issue by setting `--merge_lora true`.')
if mg_mlp is None:
lora_A = None
lora_B = None
else:
if is_expert:
lora_A = [
getattr(mg_mlp.linear_fc1.lora_A[self._adapter_name], f'weight{i}')
for i in range(num_local_experts)
]
lora_B = [
getattr(mg_mlp.linear_fc1.lora_B[self._adapter_name], f'weight{i}')
for i in range(num_local_experts)
]
else:
lora_A = mg_mlp.linear_fc1.lora_A[self._adapter_name].weight
lora_B = mg_mlp.linear_fc1.lora_B[self._adapter_name].weight
lora_A, _ = self._get_weight(
lora_A, f'linear_fc1.lora_A.{self._adapter_name}.weight', is_expert=is_expert)
lora_B, _ = self._get_weight(
lora_B, f'linear_fc1.lora_B.{self._adapter_name}.weight', is_expert=is_expert)
if lora_A is not None:
if is_gate_up:
self._peft_target_modules.update({'gate_up_proj'})
if is_expert:
for i in range(num_local_experts):
hf_i = i + ep_rank * num_local_experts
hf_state_dict[f'{hf_i}.gate_up_proj.lora_A.weight'] = lora_A[i].clone()
hf_state_dict[f'{hf_i}.gate_up_proj.lora_B.weight'] = lora_B[i].clone()
else:
hf_state_dict['gate_up_proj.lora_A.weight'] = lora_A.clone()
hf_state_dict['gate_up_proj.lora_B.weight'] = lora_B.view(-1, lora_B.shape[-1]).clone()
else:
self._peft_target_modules.update({'gate_proj', 'up_proj'})
if is_expert:
lora_B = lora_B.view(num_local_experts, 2, -1, lora_B.shape[-1])
for i in range(num_local_experts):
hf_i = i + ep_rank * num_local_experts
hf_state_dict[f'{hf_i}.gate_proj.lora_A.weight'] = lora_A[i].clone()
hf_state_dict[f'{hf_i}.up_proj.lora_A.weight'] = lora_A[i].clone()
hf_state_dict[f'{hf_i}.gate_proj.lora_B.weight'] = lora_B[i][0].clone()
hf_state_dict[f'{hf_i}.up_proj.lora_B.weight'] = lora_B[i][1].clone()
else:
lora_B = lora_B.view(2, -1, lora_B.shape[-1])
hf_state_dict['gate_proj.lora_A.weight'] = lora_A.clone()
hf_state_dict['up_proj.lora_A.weight'] = lora_A.clone()
hf_state_dict['gate_proj.lora_B.weight'] = lora_B[0].clone()
hf_state_dict['up_proj.lora_B.weight'] = lora_B[1].clone()
elif not self._peft_format:
fc1_bias = None
if mg_mlp is None:
fc1_weight = None