-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathmoe.py
More file actions
2604 lines (2347 loc) · 97.7 KB
/
moe.py
File metadata and controls
2604 lines (2347 loc) · 97.7 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
# SPDX-License-Identifier: MIT
# Copyright (C) 2024-2025, Advanced Micro Devices, Inc. All rights reserved.
from abc import abstractmethod
from dataclasses import dataclass
from enum import Enum
from typing import Callable, List, Optional, Tuple
import torch
from aiter import ActivationType, QuantType, dtypes, get_hip_quant
from aiter.dist.parallel_state import get_dp_group, get_tp_group
from aiter.fused_moe import fused_moe
from aiter.jit.utils.chip_info import get_gfx
from aiter.jit.utils.torch_guard import torch_compile_guard
from aiter.ops.shuffle import shuffle_scale_a16w4, shuffle_weight_a16w4
from aiter.utility import fp4_utils
from atom.config import (
Config,
QuantizationConfig,
get_current_atom_config,
LayerQuantConfig,
)
from atom.model_loader.weight_utils import set_weight_attrs
from atom.model_ops.base_config import QuantizeMethodBase
from atom.model_ops.fused_moe.config import (
FUSED_MOE_UNQUANTIZED_CONFIG,
FusedMoEConfig,
FusedMoEQuantConfig,
fp8_w8a8_moe_quant_config,
mxfp4_w4a16_moe_quant_config,
)
from atom.model_ops.fused_moe.modular_kernel import (
FusedMoEModularKernel,
FusedMoEPrepareAndFinalize,
)
from atom.model_ops.fused_moe.mori_prepare_finalize import MoriPrepareAndFinalize
from atom.model_ops.topK import (
init_aiter_topK_meta_data,
is_rocm_aiter_fuse_routed_scaling_factor,
is_rocm_aiter_fusion_shared_expert_enabled,
)
from atom.model_ops.topK import rocm_aiter_grouped_topk as grouped_topk
from atom.model_ops.topK import rocm_aiter_topk_softmax as fused_topk
from atom.model_ops.utils import (
_has_module,
normalize_e4m3fn_to_e4m3fnuz,
per_tensor_dequantize,
shuffle_weights,
)
from atom.utils import envs
from atom.utils.custom_register import direct_register_custom_op
from atom.utils.forward_context import get_forward_context
from atom.utils.decorators import mark_trace
from torch import nn
from transformers import PretrainedConfig
from atom.plugin.moe import FusedMoEDecoratorForPluginMode
class FusedMoeWeightScaleSupported(Enum):
"""Supported quantization strategies for MoE weight scales."""
TENSOR = "tensor"
CHANNEL = "channel"
GROUP = "group"
BLOCK = "block"
@dataclass
class FusedMoEParallelConfig:
tp_size: int
dp_size: int
ep_size: int
tp_rank: int
dp_rank: int
ep_rank: int
use_ep: bool # whether to use EP or not
local_ep_size: int
@property
def use_all2all_kernels(self):
# Only use mori all2all kernels when expert parallel is enabled
return self.dp_size > 1 and self.use_ep and _has_module("mori")
@property
def use_mori_kernels(self):
return True
@staticmethod
def make(
tp_size_: int, dp_size_: int, parallel_config: Config
) -> "FusedMoEParallelConfig":
def flatten_tp_across_dp(dp_rank: int):
tp_rank = 0 if tp_size_ == 1 else get_tp_group().rank_in_group
# There are actually dp_size_ * tp_size_ devices. Update tp_size
# and tp_rank so we shard across all devices.
tp_size = dp_size_ * tp_size_
tp_rank = dp_rank * tp_size_ + tp_rank
return tp_size, tp_rank
# Only flatten DP into TP/EP when enable_dp_attention is True.
# Otherwise, use pure DP for MoE.
enable_dp_attention = parallel_config.enable_dp_attention
use_ep = dp_size_ * tp_size_ > 1 and parallel_config.enable_expert_parallel
dp_size = dp_size_
dp_rank = get_dp_group().rank_in_group if dp_size > 1 else 0
if enable_dp_attention:
tp_size, tp_rank = flatten_tp_across_dp(dp_rank)
else:
tp_size = tp_size_
tp_rank = 0 if tp_size_ == 1 else get_tp_group().rank_in_group
atom_config = get_current_atom_config()
if not use_ep:
return FusedMoEParallelConfig(
tp_size=tp_size,
tp_rank=tp_rank,
dp_size=dp_size,
dp_rank=dp_rank,
ep_size=1,
ep_rank=0,
use_ep=False,
local_ep_size=1,
)
# DP + EP / TP + EP / DP + TP + EP
assert use_ep
# In EP, each device owns a set of experts fully. There is no tensor
# parallel update tp_size, tp_rank, ep_size and ep_rank to reflect that.
ep_size = tp_size
ep_rank = tp_rank
return FusedMoEParallelConfig(
tp_size=1,
tp_rank=0,
dp_size=dp_size,
dp_rank=dp_rank,
ep_size=ep_size,
ep_rank=ep_rank,
use_ep=True,
local_ep_size=atom_config.parallel_config.data_parallel_size_local
* tp_size_,
)
def naive_multicast_fake(
x: torch.Tensor, cu_tokens_across_dp_cpu: torch.Tensor
) -> torch.Tensor:
assert len(x.shape) == 2
# print(f"cu_tokens_across_dp_cpu: {cu_tokens_across_dp_cpu}")
buffer = torch.empty(
(cu_tokens_across_dp_cpu[-1], x.size(1)), device=x.device, dtype=x.dtype
)
return buffer
@torch_compile_guard()
def naive_multicast(
x: torch.Tensor, cu_tokens_across_dp_cpu: torch.Tensor
) -> torch.Tensor:
dp_rank = get_dp_group().rank_in_group
assert len(x.shape) == 2
# print(f"cu_tokens_across_dp_cpu: {cu_tokens_across_dp_cpu}")
buffer = torch.empty(
(cu_tokens_across_dp_cpu[-1], x.size(1)), device=x.device, dtype=x.dtype
)
start = 0 if dp_rank == 0 else cu_tokens_across_dp_cpu[dp_rank - 1]
end = cu_tokens_across_dp_cpu[dp_rank]
buffer[start:end, :].copy_(x)
for idx in range(get_dp_group().world_size):
start = 0 if idx == 0 else cu_tokens_across_dp_cpu[idx - 1]
end = cu_tokens_across_dp_cpu[idx]
get_dp_group().broadcast(buffer[start:end, :], idx)
return buffer
def all_gather_with_padding(x: torch.Tensor):
max_batch_size = get_forward_context().context.graph_bs
dim = 0
original_batch_size = x.shape[dim]
padded_x = x
if original_batch_size < max_batch_size:
padding_size = max_batch_size - original_batch_size
padding_shape = list(x.shape)
padding_shape[dim] = padding_size
padding = torch.empty(padding_shape, dtype=x.dtype, device=x.device)
padding.zero_()
padded_x = torch.cat([x, padding], dim=dim)
gathered_hidden_states = get_dp_group().all_gather(padded_x, dim=dim)
return gathered_hidden_states, original_batch_size
def reduce_scatter_with_unpadding(
x: torch.Tensor, original_batch_size: int
) -> torch.Tensor:
dim = 0
dp_group = get_dp_group()
# scattered_output = dp_group.reduce_scatter(x, dim=dim)
scattered_output = dp_group.reduce_scatter_tensor(x)
if scattered_output.shape[dim] > original_batch_size:
slices = [slice(None)] * scattered_output.ndim
slices[dim] = slice(0, original_batch_size)
scattered_output = scattered_output[slices]
return scattered_output
@torch_compile_guard()
def get_max_tokens_across_dispatchers(input: torch.Tensor) -> int:
return input.item()
class FusedMoEMethodBase(QuantizeMethodBase):
def __init__(self, moe: FusedMoEConfig):
super().__init__()
self.moe = moe
self.moe_quant_config: FusedMoEQuantConfig | None = None
self.fused_experts: FusedMoEModularKernel | None = None
self.topk_indices_dtype = None
@abstractmethod
def create_weights(
self,
layer: torch.nn.Module,
num_experts: int,
hidden_size: int,
intermediate_size_per_partition: int,
params_dtype: torch.dtype,
**extra_weight_attrs,
):
raise NotImplementedError
@abstractmethod
def apply(
self,
layer: torch.nn.Module,
x: torch.Tensor,
router_logits: torch.Tensor,
top_k: int,
renormalize: bool,
use_grouped_topk: bool = False,
topk_group: Optional[int] = None,
num_expert_group: Optional[int] = None,
global_num_experts: int = -1,
expert_map: Optional[torch.Tensor] = None,
custom_routing_function: Optional[Callable] = None,
scoring_func: str = "softmax",
e_score_correction_bias: Optional[torch.Tensor] = None,
fused_shared_experts_scoring_func: Optional[str] = None,
apply_router_weight_on_input: bool = False,
activation: str = "silu",
) -> torch.Tensor:
raise NotImplementedError
@abstractmethod
def get_fused_moe_quant_config(
self, layer: torch.nn.Module
) -> FusedMoEQuantConfig | None:
raise NotImplementedError
@staticmethod
def _maybe_make_prepare_finalize(
moe: FusedMoEConfig,
quant_config: FusedMoEQuantConfig | None,
) -> FusedMoEPrepareAndFinalize | None:
from aiter.dist.parallel_state import get_ep_group
all2all_manager = get_ep_group().device_communicator.all2all_manager
assert all2all_manager is not None
prepare_finalize: FusedMoEPrepareAndFinalize | None = None
# TODO: could allow this now
# assert not moe.use_flashinfer_cutlass_kernels, "Must be created in modelopt.py"
if moe.use_mori_kernels:
assert quant_config is not None
# For PTPC (per token per channel) quant, the scale dim for each token is 1
# For 1x128 quant, the scale dim for each token is hidden_dim // 128
scale_dim = 1 if quant_config.is_per_act_token else moe.hidden_dim // 128
# Check if quant_dtype is an FP8 type
from aiter import QuantType
fp8_dtypes = (
torch.float8_e4m3fn,
torch.float8_e4m3fnuz,
torch.float8_e5m2,
torch.float8_e5m2fnuz,
)
is_fp8 = quant_config.quant_dtype in fp8_dtypes
# For FP8: enable FP8 dispatch in Mori (quantize before communication)
# Note: per_Tensor quant doesn't support num_local_tokens, so we use per_Token
use_fp8_dispatch = is_fp8
quant_type = None
if use_fp8_dispatch:
if quant_config.is_block_quantized:
quant_type = QuantType.per_1x128
elif quant_config.is_per_act_token:
quant_type = QuantType.per_Token
# For FP8: use FP8 dtype for communication
# For FP4/no quant: use bfloat16
# mori_dtype = (
# quant_config.quant_dtype
# if is_fp8 and quant_type is not None
# else torch.bfloat16
# )
# mori_dtype = torch.bfloat16
all_to_all_args = dict(
rank=all2all_manager.rank,
num_ep_ranks=all2all_manager.world_size,
# quant_dtype=mori_dtype,
# We now use bfloat16 for mori
# TODO: To support quant
quant_dtype=moe.in_dtype,
token_hidden_size=moe.hidden_dim,
scale_dim=scale_dim,
scale_type_size=torch.float32.itemsize,
max_num_tokens_per_dp_rank=16384,
# input_dtype=moe.in_dtype,
input_dtype=moe.in_dtype,
num_local_experts=moe.num_experts // all2all_manager.world_size,
num_experts_per_token=moe.experts_per_token,
gpu_per_node=moe.moe_parallel_config.local_ep_size,
)
handle = all2all_manager.get_handle(all_to_all_args)
# We not use quant for mori now
use_fp8_dispatch = False
quant_type = None
prepare_finalize = MoriPrepareAndFinalize(
handle,
max_tokens_per_rank=moe.max_num_tokens,
num_dispatchers=all2all_manager.world_size,
use_fp8_dispatch=use_fp8_dispatch,
quant_type=quant_type,
)
return prepare_finalize
def maybe_make_prepare_finalize(self) -> FusedMoEPrepareAndFinalize | None:
# if True:
if self.moe.moe_parallel_config.use_all2all_kernels:
return FusedMoEMethodBase._maybe_make_prepare_finalize(
self.moe, self.moe_quant_config
)
else:
return None
# Note: init_prepare_finalize should only be called by
# prepare_communication_buffer_for_model.
def init_prepare_finalize(self, layer: torch.nn.Module):
# print("init_prepare_finalize")
assert self.moe is not None
# We must get the quant config here so that the layer is
# completely initialized, i.e. all weights loaded and post
# processed.
self.moe_quant_config = self.get_fused_moe_quant_config(layer)
prepare_finalize = self.maybe_make_prepare_finalize()
if prepare_finalize is not None:
# logger.debug(
# "%s for %s(%s)", prepare_finalize.__class__.__name__, self, id(self)
# )
assert self.topk_indices_dtype is None
assert (
self.fused_experts is None
), f"Attempt to override experts for {id(self)}!"
self.topk_indices_dtype = prepare_finalize.topk_indices_dtype()
# experts = self.select_gemm_impl(prepare_finalize, layer)
self.fused_experts = FusedMoEModularKernel(
prepare_finalize,
# experts,
# layer.shared_experts,
quant_config=self.moe_quant_config,
)
@property
def using_modular_kernel(self) -> bool:
return self.fused_experts is not None
class UnquantizedFusedMoEMethod(FusedMoEMethodBase):
"""MoE method without quantization."""
def create_weights(
self,
layer: torch.nn.Module,
num_experts: int,
hidden_size: int,
intermediate_size_per_partition: int,
params_dtype: torch.dtype,
**extra_weight_attrs,
):
# Fused gate_up_proj (column parallel)
w13_weight = torch.nn.Parameter(
torch.empty(
num_experts,
2 * intermediate_size_per_partition,
hidden_size,
dtype=params_dtype,
),
requires_grad=False,
)
layer.register_parameter("w13_weight", w13_weight)
set_weight_attrs(w13_weight, extra_weight_attrs)
# down_proj (row parallel)
w2_weight = torch.nn.Parameter(
torch.empty(
num_experts,
hidden_size,
intermediate_size_per_partition,
dtype=params_dtype,
),
requires_grad=False,
)
layer.register_parameter("w2_weight", w2_weight)
set_weight_attrs(w2_weight, extra_weight_attrs)
def _maybe_pad_weight(self, weight: torch.Tensor) -> torch.Tensor:
return weight
def process_weights_after_loading(self, layer: torch.nn.Module) -> None:
super().process_weights_after_loading(layer)
layer.w13_weight = torch.nn.Parameter(
self._maybe_pad_weight(layer.w13_weight.data), requires_grad=False
)
layer.w2_weight = torch.nn.Parameter(
self._maybe_pad_weight(layer.w2_weight.data), requires_grad=False
)
# reshaping weights is required for aiter moe kernel.
shuffle_weights(layer.w13_weight, layer.w2_weight)
def get_fused_moe_quant_config(
self, layer: torch.nn.Module
) -> FusedMoEQuantConfig | None:
return FUSED_MOE_UNQUANTIZED_CONFIG
@mark_trace(prefix="unquantized_moe", torch_compile=False)
def apply(
self,
layer: torch.nn.Module,
x: torch.Tensor,
router_logits: torch.Tensor,
top_k: int,
renormalize: bool,
use_grouped_topk: bool = False,
topk_group: Optional[int] = None,
num_expert_group: Optional[int] = None,
global_num_experts: int = -1,
expert_map: Optional[torch.Tensor] = None,
custom_routing_function: Optional[Callable] = None,
scoring_func: str = "softmax",
e_score_correction_bias: Optional[torch.Tensor] = None,
fused_shared_experts_scoring_func: Optional[str] = None,
apply_router_weight_on_input: bool = False,
activation: ActivationType = ActivationType.Silu,
) -> torch.Tensor:
topk_weights, topk_ids = FusedMoE.select_experts(
hidden_states=x,
router_logits=router_logits,
use_grouped_topk=use_grouped_topk,
top_k=top_k,
renormalize=renormalize,
topk_group=topk_group,
num_expert_group=num_expert_group,
custom_routing_function=custom_routing_function,
scoring_func=scoring_func,
e_score_correction_bias=e_score_correction_bias,
num_routing_experts=global_num_experts,
num_fused_shared_experts=layer.num_fused_shared_experts,
fused_shared_experts_scoring_func=fused_shared_experts_scoring_func,
routed_scaling_factor=layer.routed_scaling_factor,
)
if self.fused_experts:
return self.fused_experts(
hidden_states=x,
w1=layer.w13_weight,
w2=layer.w2_weight,
topk_weights=topk_weights,
topk_ids=topk_ids,
inplace=False,
activation=activation,
quant_type=QuantType.No,
global_num_experts=global_num_experts,
expert_map=expert_map,
)
return fused_moe(
hidden_states=x,
w1=layer.w13_weight,
w2=layer.w2_weight,
topk_weight=topk_weights,
topk_ids=topk_ids,
expert_mask=expert_map,
activation=activation,
)
def rocm_asm_moe_impl(
hidden_states: torch.Tensor,
w1: torch.Tensor,
w2: torch.Tensor,
topk_weight: torch.Tensor,
topk_ids: torch.Tensor,
expert_mask: Optional[torch.Tensor] = None,
activation: int = ActivationType.Silu.value,
quant_type: int = QuantType.No.value,
doweight_stage1: bool = False,
w1_scale: Optional[torch.Tensor] = None,
w2_scale: Optional[torch.Tensor] = None,
a1_scale: Optional[torch.Tensor] = None,
a2_scale: Optional[torch.Tensor] = None,
) -> torch.Tensor:
from aiter import ActivationType, QuantType
from aiter.fused_moe_bf16_asm import asm_moe
activation_ = ActivationType(activation)
quant_type_ = QuantType(quant_type)
# - fc1_scale: [E, inter_dim*2, 1]
# - fc2_scale: [E, model_dim, 1]
# - fc1_smooth_scale: [E, model_dim]
# - fc2_smooth_scale: [E, inter_dim]
fc1_scale_fixed = w1_scale
fc2_scale_fixed = w2_scale
fc1_smooth_scale_fixed = a1_scale
fc2_smooth_scale_fixed = a2_scale
a16_mode = (
quant_type_ in [QuantType.per_Token, QuantType.per_1x128]
and hidden_states.dtype in [torch.float16, torch.bfloat16]
and w1.dtype in [torch.int8, torch.uint8, torch.float8_e4m3fnuz]
and fc1_smooth_scale_fixed is not None
and fc2_smooth_scale_fixed is not None
)
return asm_moe(
hidden_states,
w1,
w2,
topk_weight,
topk_ids,
fc1_scale=fc1_scale_fixed,
fc2_scale=fc2_scale_fixed,
fc1_smooth_scale=fc1_smooth_scale_fixed,
fc2_smooth_scale=fc2_smooth_scale_fixed,
a16=a16_mode,
per_tensor_quant_scale=None,
block_shape=None,
expert_mask=expert_mask,
activation=activation_,
)
def rocm_aiter_fused_moe_impl(
hidden_states: torch.Tensor,
w1: torch.Tensor,
w2: torch.Tensor,
topk_weight: torch.Tensor,
topk_ids: torch.Tensor,
expert_mask: Optional[torch.Tensor] = None,
activation: int = ActivationType.Silu.value,
quant_type: int = QuantType.No.value,
doweight_stage1: bool = False,
w1_scale: Optional[torch.Tensor] = None,
w2_scale: Optional[torch.Tensor] = None,
a1_scale: Optional[torch.Tensor] = None,
a2_scale: Optional[torch.Tensor] = None,
) -> torch.Tensor:
from aiter import ActivationType, QuantType
activation_ = ActivationType(activation)
quant_type_ = QuantType(quant_type)
return fused_moe(
hidden_states,
w1,
w2,
topk_weight,
topk_ids,
expert_mask,
activation_,
quant_type_,
doweight_stage1,
w1_scale,
w2_scale,
a1_scale,
a2_scale,
)
def rocm_aiter_fused_moe_fake(
hidden_states: torch.Tensor,
w1: torch.Tensor,
w2: torch.Tensor,
topk_weight: torch.Tensor,
topk_ids: torch.Tensor,
expert_mask: Optional[torch.Tensor] = None,
activation: int = ActivationType.Silu.value,
quant_type: int = QuantType.No.value,
doweight_stage1: bool = False,
w1_scale: Optional[torch.Tensor] = None,
w2_scale: Optional[torch.Tensor] = None,
a1_scale: Optional[torch.Tensor] = None,
a2_scale: Optional[torch.Tensor] = None,
) -> torch.Tensor:
return torch.empty_like(hidden_states)
direct_register_custom_op(
op_name="rocm_aiter_fused_moe",
op_func=rocm_aiter_fused_moe_impl,
mutates_args=[],
fake_impl=rocm_aiter_fused_moe_fake,
)
class Mxfp4MoEMethod(FusedMoEMethodBase):
def __init__(self, quant_config: LayerQuantConfig, moe: FusedMoEConfig):
super().__init__(moe)
self.quant_config = quant_config
self.quant_type = self.quant_config["quant_type"]
self.quant_dtype = self.quant_config["quant_dtype"]
self.quant_method = self.quant_config["quant_method"]
self.block_quant = (
self.quant_type == QuantType.per_1x128
or self.quant_type == QuantType.per_1x32
)
gfx = get_gfx()
self.use_triton = gfx.startswith("gfx94") or (
gfx.startswith("gfx95") and envs.ATOM_USE_TRITON_GEMM
)
if self.use_triton:
from atom.model_ops.utils import has_triton_kernels
assert has_triton_kernels(), "triton_kernels is not installed"
def create_weights(
self,
layer: torch.nn.Module,
num_experts: int,
hidden_size: int,
intermediate_size_per_partition: int,
params_dtype: torch.dtype,
**extra_weight_attrs,
):
self.num_experts = num_experts
weight_dtype = params_dtype
scale_dtype = torch.uint8
mxfp4_block = 32
pad_align = 256
intermediate_size_per_partition_after_pad = (
(intermediate_size_per_partition + pad_align - 1) // pad_align * pad_align
)
hidden_size = (hidden_size + pad_align - 1) // pad_align * pad_align
self.intermediate_size = intermediate_size_per_partition_after_pad
self.hidden_size = hidden_size
self.hidden_pad = self.hidden_size - layer.hidden_size
# Update moe.hidden_dim to match the padded hidden size for Mori kernels
self.moe.hidden_dim = hidden_size
self.intermediate_pad = (
self.intermediate_size - layer.intermediate_size_per_partition
)
# Fused gate_up_proj (column parallel)
w13_weight = torch.nn.Parameter(
torch.empty(
num_experts,
2 * intermediate_size_per_partition_after_pad,
hidden_size // 2,
dtype=weight_dtype,
),
requires_grad=False,
)
layer.register_parameter("w13_weight", w13_weight)
set_weight_attrs(w13_weight, extra_weight_attrs)
w13_weight_scale = torch.nn.Parameter(
torch.zeros(
num_experts,
2 * intermediate_size_per_partition_after_pad,
hidden_size // mxfp4_block,
dtype=scale_dtype,
),
requires_grad=False,
)
layer.register_parameter("w13_weight_scale", w13_weight_scale)
set_weight_attrs(w13_weight_scale, extra_weight_attrs)
if layer.has_bias:
w13_bias = torch.nn.Parameter(
torch.empty(
num_experts,
2 * intermediate_size_per_partition_after_pad,
dtype=torch.bfloat16,
),
requires_grad=False,
)
layer.register_parameter("w13_bias", w13_bias)
set_weight_attrs(w13_bias, extra_weight_attrs)
else:
layer.register_parameter("w13_bias", None)
# down_proj (row parallel)
w2_weight = torch.nn.Parameter(
torch.empty(
num_experts,
hidden_size,
intermediate_size_per_partition_after_pad // 2,
dtype=weight_dtype,
),
requires_grad=False,
)
layer.register_parameter("w2_weight", w2_weight)
set_weight_attrs(w2_weight, extra_weight_attrs)
w2_weight_scale = torch.nn.Parameter(
torch.zeros(
num_experts,
hidden_size,
intermediate_size_per_partition_after_pad // mxfp4_block,
dtype=scale_dtype,
),
requires_grad=False,
)
layer.register_parameter("w2_weight_scale", w2_weight_scale)
set_weight_attrs(w2_weight_scale, extra_weight_attrs)
if layer.has_bias:
w2_bias = torch.nn.Parameter(
torch.empty(
num_experts,
hidden_size,
dtype=torch.bfloat16,
),
requires_grad=False,
)
layer.register_parameter("w2_bias", w2_bias)
set_weight_attrs(w2_bias, extra_weight_attrs)
else:
layer.register_parameter("w2_bias", None)
def process_weights_after_loading(self, layer):
if layer.w13_bias is not None:
layer.w13_bias.data = layer.w13_bias.data.to(torch.float32)
if layer.w2_bias is not None:
layer.w2_bias.data = layer.w2_bias.data.to(torch.float32)
if self.use_triton:
from atom.model_ops.fused_moe_triton import _swizzle_mxfp4
from triton_kernels.matmul_ogs import FlexCtx, PrecisionConfig
w13_weight, w13_flex, w13_scale = _swizzle_mxfp4(
layer.w13_weight.view(torch.uint8),
layer.w13_weight_scale,
)
w2_weight, w2_flex, w2_scale = _swizzle_mxfp4(
layer.w2_weight.view(torch.uint8),
layer.w2_weight_scale,
)
self.w13_precision_config = PrecisionConfig(
weight_scale=w13_scale, flex_ctx=FlexCtx(rhs_data=w13_flex)
)
self.w2_precision_config = PrecisionConfig(
weight_scale=w2_scale, flex_ctx=FlexCtx(rhs_data=w2_flex)
)
del layer.w13_weight
del layer.w2_weight
del layer.w13_weight_scale
del layer.w2_weight_scale
layer.w13_weight = w13_weight
layer.w2_weight = w2_weight
layer.w13_weight_scale = None
layer.w2_weight_scale = None
return
elif layer.activation == ActivationType.Swiglu and layer.w13_bias is not None:
e, n, k = layer.w13_weight.shape
layer.w13_weight.view(torch.uint8).copy_(
layer.w13_weight.data.view(torch.uint8)
.view(e, n // 2, 2, k)
.permute(0, 2, 1, 3)
.contiguous()
.view(e, n, k)
)
layer.w13_weight_scale.data = (
layer.w13_weight_scale.data.view(e, n // 2, 2, -1)
.permute(0, 2, 1, 3)
.contiguous()
.view(e, n, -1)
)
layer.w13_weight.data = shuffle_weight_a16w4(layer.w13_weight, 16, True)
shuffled_w13_scale = shuffle_scale_a16w4(
layer.w13_weight_scale.view(-1, layer.w13_weight_scale.shape[-1]),
self.num_experts,
True,
)
layer.w2_weight.data = shuffle_weight_a16w4(layer.w2_weight, 16, False)
shuffled_w2_scale = shuffle_scale_a16w4(
layer.w2_weight_scale.view(-1, layer.w2_weight_scale.shape[-1]),
self.num_experts,
False,
)
layer.w13_bias.data = (
layer.w13_bias.data.view(-1, n // 2, 2)
.permute(0, 2, 1)
.contiguous()
.view(-1, n)
)
# quark method for moe, split it out?
elif self.quant_method == "quark":
shuffle_weights(layer.w13_weight, layer.w2_weight)
s0, s1, _ = layer.w13_weight_scale.shape
w13_weight_scale = layer.w13_weight_scale.view(s0 * s1, -1)
w13_weight_scale = fp4_utils.e8m0_shuffle(w13_weight_scale)
layer.w13_weight_scale.data = w13_weight_scale.view(s0, s1, -1)
s0, s1, _ = layer.w2_weight_scale.shape
w2_weight_scale = layer.w2_weight_scale.view(s0 * s1, -1)
w2_weight_scale = fp4_utils.e8m0_shuffle(w2_weight_scale)
layer.w2_weight_scale.data = w2_weight_scale.view(s0, s1, -1)
return
else:
shuffle_weights(layer.w13_weight, layer.w2_weight)
shuffled_w13_scale = fp4_utils.e8m0_shuffle(
layer.w13_weight_scale.view(self.num_experts, -1)
)
shuffled_w2_scale = fp4_utils.e8m0_shuffle(
layer.w2_weight_scale.view(self.num_experts, -1)
)
layer.w13_weight_scale = torch.nn.Parameter(
shuffled_w13_scale, requires_grad=False
)
layer.w2_weight_scale = torch.nn.Parameter(
shuffled_w2_scale, requires_grad=False
)
def get_fused_moe_quant_config(
self, layer: torch.nn.Module
) -> FusedMoEQuantConfig | None:
return mxfp4_w4a16_moe_quant_config(
w1_bias=layer.w13_bias,
w2_bias=layer.w2_bias,
w1_scale=layer.w13_weight_scale,
w2_scale=layer.w2_weight_scale,
)
@mark_trace(prefix="mxfp4_moe", torch_compile=False)
def apply(
self,
layer: torch.nn.Module,
x: torch.Tensor,
router_logits: torch.Tensor,
top_k: int,
renormalize: bool,
use_grouped_topk: bool = False,
topk_group: Optional[int] = None,
num_expert_group: Optional[int] = None,
global_num_experts: int = -1,
expert_map: Optional[torch.Tensor] = None,
custom_routing_function: Optional[Callable] = None,
scoring_func: str = "softmax",
e_score_correction_bias: Optional[torch.Tensor] = None,
apply_router_weight_on_input: bool = False,
fused_shared_experts_scoring_func: Optional[str] = None,
activation: ActivationType = ActivationType.Silu,
) -> torch.Tensor:
if self.use_triton:
from atom.model_ops.fused_moe_triton import triton_kernel_moe_forward
assert (
fused_shared_experts_scoring_func is None
), "triton kernel does not support fused shared experts func"
return triton_kernel_moe_forward(
x,
layer.w13_weight,
layer.w2_weight,
router_logits,
topk=top_k,
renormalize=renormalize,
activation=activation,
w13_precision_config=self.w13_precision_config,
w2_precision_config=self.w2_precision_config,
w1_bias=layer.w13_bias,
w2_bias=layer.w2_bias,
expert_map=expert_map,
apply_router_weight_on_input=layer.apply_router_weight_on_input,
global_num_experts=global_num_experts,
)
topk_weights, topk_ids = FusedMoE.select_experts(
hidden_states=x,
router_logits=router_logits,
use_grouped_topk=use_grouped_topk,
top_k=top_k,
renormalize=renormalize,
topk_group=topk_group,
num_expert_group=num_expert_group,
custom_routing_function=custom_routing_function,
scoring_func=scoring_func,
e_score_correction_bias=e_score_correction_bias,
num_routing_experts=global_num_experts,
num_fused_shared_experts=layer.num_fused_shared_experts,
fused_shared_experts_scoring_func=fused_shared_experts_scoring_func,
routed_scaling_factor=layer.routed_scaling_factor,
)
if self.fused_experts is None:
return fused_moe(
x,
layer.w13_weight,
layer.w2_weight,
topk_weights,
topk_ids,
expert_mask=expert_map,
activation=activation,
quant_type=self.quant_type,
w1_scale=layer.w13_weight_scale,
w2_scale=layer.w2_weight_scale,
doweight_stage1=apply_router_weight_on_input,
hidden_pad=self.hidden_pad,
intermediate_pad=self.intermediate_pad,
bias1=layer.w13_bias,
bias2=layer.w2_bias,
)
return self.fused_experts(
hidden_states=x,
w1=layer.w13_weight,
w2=layer.w2_weight,
topk_weights=topk_weights,
topk_ids=topk_ids,
inplace=False,
activation=activation,
quant_type=self.quant_type,
apply_router_weight_on_input=apply_router_weight_on_input,
global_num_experts=global_num_experts,
expert_map=expert_map,
w1_scale=layer.w13_weight_scale,
w2_scale=layer.w2_weight_scale,
a1_scale=None,
a2_scale=None,
bias1=layer.w13_bias,
bias2=layer.w2_bias,
hidden_pad=self.hidden_pad,
intermediate_pad=self.intermediate_pad,
)
# Refer to CompressedTensorsW8A8Fp8MoEMethod in vllm
class CompressedTensorsFp8MoEMethod(FusedMoEMethodBase):
def __init__(self, quant_config: LayerQuantConfig, moe: FusedMoEConfig):
super().__init__(moe)
self.quant_config = quant_config
self.quant_type = quant_config["quant_type"]
self.quant_dtype = quant_config["quant_dtype"]
# Check if we need to normalize e4m3fn to e4m3fnuz (AMD GPUs)
self.need_normalize_e4m3fn_to_e4m3fnuz = (
self.quant_dtype == torch.float8_e4m3fnuz
)
# Determine if this is block quantization
self.block_quant = self.quant_type in [
QuantType.per_1x128,
QuantType.per_1x32,
]
# For compressed-tensors, check if per-channel quantization
self.per_channel = self.quant_type == QuantType.per_Token
# Check if static input scales (activation quantization)
self.static_input_scales = not quant_config.get("is_dynamic", True)
# Block sizes for block quantization
if self.block_quant:
if self.quant_type == QuantType.per_1x128:
self.block_n = 128
self.block_k = 128
elif self.quant_type == QuantType.per_1x32:
self.block_n = 1
self.block_k = 32
def create_weights(