forked from NVIDIA/TensorRT-LLM
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinear.py
More file actions
2105 lines (1794 loc) · 92.2 KB
/
linear.py
File metadata and controls
2105 lines (1794 loc) · 92.2 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
from __future__ import annotations
import enum
import math
import os
from abc import ABC, abstractmethod
from dataclasses import dataclass
from typing import Dict, List, Optional, Union
import torch
import torch.nn.functional as F
from torch import nn
from torch.nn.parameter import Parameter
import tensorrt_llm.quantization.utils.fp4_utils as fp4_utils
from tensorrt_llm._torch.peft.lora.layer import LoraLayer
from tensorrt_llm._utils import is_device_integrated
from tensorrt_llm.functional import (AllReduceFusionOp, AllReduceParams,
AllReduceStrategy)
from tensorrt_llm.logger import logger
from tensorrt_llm.mapping import Mapping
from tensorrt_llm.quantization.functional import \
preprocess_weights_for_mixed_gemm
from tensorrt_llm.quantization.mode import QuantAlgo
from tensorrt_llm.quantization.utils.fp8_utils import (
resmooth_to_fp8_e8m0, transform_sf_into_required_layout)
from ..._utils import is_sm_100f
from ...models.modeling_utils import QuantConfig
from ..cublaslt_utils import IS_CUBLASLT_AVAILABLE
from ..cute_dsl_utils import IS_CUTLASS_DSL_AVAILABLE
from ..utils import Fp4QuantizedTensor, unswizzle_sf
class WeightMode(str, enum.Enum):
# weight of a vanilla layer
VANILLA = 'vanilla'
# weight of a fused QKV linear layer
FUSED_QKV_LINEAR = 'fused_qkv_linear'
# weight of a fused gate and up linear layer
FUSED_GATE_UP_LINEAR = 'fused_gate_up_linear'
@dataclass(kw_only=True)
class WeightsLoadingConfig:
weight_mode: WeightMode = WeightMode.VANILLA
ignore_tensor_parallel: bool = False
class TensorParallelMode(str, enum.Enum):
COLUMN = 'column'
ROW = 'row'
@classmethod
def split_dim(cls, mode):
return 1 if mode == cls.ROW else 0
# Helper to shard the corresponding per-channel activation scales
# Which shard along the dimension orthogonal to the weights
@classmethod
def flip(cls, mode):
return cls.ROW if mode == cls.COLUMN else cls.COLUMN
def load_weight_shard(
weight,
tensor_parallel_size: int = 1,
tensor_parallel_rank: int = 0,
tensor_parallel_mode: Optional[TensorParallelMode] = None,
device: torch.device = torch.device('cpu'),
return_slice_indices: bool = False,
) -> torch.Tensor:
# Skip device transfers on integrated GPUs to conserve shared memory
if weight.device.type != device.type and is_device_integrated():
# For integrated GPU systems (e.g., DGX Spark), CPU and GPU share limited physical memory.
# Avoiding device transfers reduces memory consumption and unnecessary data copies,
# enabling support for larger models on memory-constrained systems.
logger.warning_once(
f"[load_weight_shard] Skipping device transfer from {weight.device} to {device} on integrated GPU to conserve shared memory.",
key="load_weight_shard_skip_device_transfer_with_integrated_gpu")
device = weight.device
if isinstance(weight, torch.Tensor):
tensor_shape = weight.shape
def maybe_convert_to_torch_tensor(tensor: torch.Tensor,
indices: list[slice] | None = None):
if indices is None:
# Avoid unnecessary copy
result = (tensor.to(device), [slice(d) for d in tensor.shape])
else:
result = (tensor[indices].to(device), indices)
return result if return_slice_indices else result[0]
# WAR to check whether it is a safetensor slice since safetensor didn't register the type to the module
# safetensors slice, supports lazy loading, type(weight) is `builtin.PySafeSlice`
elif hasattr(weight, "get_shape"):
tensor_shape = weight.get_shape()
def maybe_convert_to_torch_tensor(
tensor, indices: Union[slice, tuple[slice]] = slice(None)):
return tensor[indices].to(device)
else:
raise ValueError(f'unsupported weight type: {type(weight)}')
if tensor_parallel_mode is None or tensor_parallel_size <= 1:
return maybe_convert_to_torch_tensor(weight)
split_dim = TensorParallelMode.split_dim(tensor_parallel_mode)
if len(tensor_shape) == 1 and split_dim == 1:
return maybe_convert_to_torch_tensor(weight)
width = tensor_shape[split_dim]
if width == 1:
return maybe_convert_to_torch_tensor(weight)
slice_width = math.ceil(width / tensor_parallel_size)
slice_start = tensor_parallel_rank * slice_width
slice_end = min((tensor_parallel_rank + 1) * slice_width, width)
slice_obj = [slice(d) for d in tensor_shape]
slice_obj[split_dim] = slice(slice_start, slice_end)
return maybe_convert_to_torch_tensor(weight, tuple(slice_obj))
def copy_weight(dst: Parameter, src: torch.Tensor):
# TODO check that is it a reasonable change or not
if dst.dtype != src.dtype:
src = src.to(dst.dtype)
assert dst.dtype == src.dtype, f"Incompatible dtype. dst: {dst.dtype}, src: {src.dtype}"
dst.data.copy_(src)
def load_weights_vanilla_helper(module: Linear,
weights: List[Dict],
weight_transform=lambda x: x,
bias_transform=lambda x: x):
assert len(weights) == 1
device = torch.device('cuda')
weight = load_weight_shard(weights[0]['weight'], module.tp_size,
module.tp_rank, module.tp_mode, device)
if module.has_weight_only_quant:
# NOTE: without the preprocess during the runtime, the gemm output nan's. in order to use the preprocess_weights_for_mixed_gemm
# we need to cast the weight to int8 first.
activation_dtype = torch.float8_e4m3fn if module.has_w4a8_awq else torch.float16
weight_dtype, _ = get_weight_dtype_and_id(module)
weight = preprocess_weights_for_mixed_gemm(
weight.T.to(torch.int8).contiguous().cpu(), weight_dtype,
activation_dtype).cuda().contiguous()
copy_weight(module.weight, weight_transform(weight))
if module.bias is not None:
bias = load_weight_shard(weights[0]['bias'], module.tp_size,
module.tp_rank, module.tp_mode, device)
copy_weight(module.bias, bias_transform(bias))
def load_weights_fused_qkv_helper(
module: Linear,
weights: List[Dict],
weight_transform=lambda x: x,
bias_transform=lambda x: x
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
assert len(weights) == 3
device = torch.device('cuda')
q_weight = load_weight_shard(weights[0]['weight'], module.tp_size,
module.tp_rank, module.tp_mode, device)
k_weight = load_weight_shard(weights[1]['weight'], module.tp_size,
module.tp_rank, module.tp_mode, device)
v_weight = load_weight_shard(weights[2]['weight'], module.tp_size,
module.tp_rank, module.tp_mode, device)
if module.bias is not None:
q_bias = load_weight_shard(weights[0]['bias'], module.tp_size,
module.tp_rank, module.tp_mode, device)
k_bias = load_weight_shard(weights[1]['bias'], module.tp_size,
module.tp_rank, module.tp_mode, device)
v_bias = load_weight_shard(weights[2]['bias'], module.tp_size,
module.tp_rank, module.tp_mode, device)
copy_weight(module.bias,
bias_transform(torch.cat((q_bias, k_bias, v_bias))))
return tuple(map(weight_transform, (q_weight, k_weight, v_weight)))
def load_weights_fused_gate_up_helper(
module: Linear,
weights: List[Dict],
weight_transform=lambda x: x,
bias_transform=lambda x: x) -> tuple[torch.Tensor, torch.Tensor]:
assert len(weights) == 2
device = torch.device('cuda')
gate_weight = load_weight_shard(weights[0]['weight'], module.tp_size,
module.tp_rank, module.tp_mode, device)
up_weight = load_weight_shard(weights[1]['weight'], module.tp_size,
module.tp_rank, module.tp_mode, device)
if module.bias is not None:
gate_bias = load_weight_shard(weights[0]['bias'], module.tp_size,
module.tp_rank, module.tp_mode, device)
up_bias = load_weight_shard(weights[1]['bias'], module.tp_size,
module.tp_rank, module.tp_mode, device)
copy_weight(module.bias, bias_transform(torch.cat(
(gate_bias, up_bias))))
return tuple(map(weight_transform, (gate_weight, up_weight)))
def get_weight_dtype_and_id(module: Linear) -> tuple[torch.dtype, int]:
"""
Get weight dtype and weight_id for weight only quantization mode.
Returns:
tuple[torch.dtype, int]: (weight_dtype, weight_id) where:
- weight_dtype: torch.int8 for INT8 weights, torch.quint4x2 for INT4 weights
- weight_id: 1 for INT8, 2 for INT4 (used for weight packing)
"""
assert module.quant_config is not None and module.quant_config.layer_quant_mode.is_weight_only(
), "This function should only be called when the module has weight-only quantization enabled."
if module.quant_config.layer_quant_mode.is_int8_weight_only():
return torch.int8, 1
elif module.quant_config.layer_quant_mode.is_int4_weight_only():
return torch.quint4x2, 2
else:
raise ValueError(
f"Unsupported quant_mode: {module.quant_config.layer_quant_mode}")
class LinearMethodBase(ABC):
"""
Base class for all linear methods.
"""
@abstractmethod
def create_weights(self, module: Linear, in_features: int,
out_features: int, bias: bool, dtype: torch.dtype, *args,
**kwargs):
raise NotImplementedError
@abstractmethod
def apply(self, module: Linear, input: torch.Tensor,
bias: Optional[torch.Tensor], *args, **kwargs):
raise NotImplementedError
def load_weights(self, module: Linear, weights: List[Dict],
weight_mode: WeightMode):
"""
Load weights from the checkpoint.
"""
if weight_mode == WeightMode.VANILLA:
self.load_weights_vanilla(module, weights)
elif weight_mode == WeightMode.FUSED_QKV_LINEAR:
self.load_weights_fused_qkv_linear(module, weights)
elif weight_mode == WeightMode.FUSED_GATE_UP_LINEAR:
self.load_weights_fused_gate_up_linear(module, weights)
else:
raise ValueError(f'unsupported weight mode: {weight_mode}')
def post_load_weights(self, module: Linear):
pass
def load_weight_scales(self, weights: List[Dict], *args, **kwargs):
"""
Load quantized weight scales from the checkpoint.
"""
@abstractmethod
def load_weights_vanilla(self, module: Linear, weights: List[Dict]) -> None:
"""
Load weights for the VANILLA weight mode.
"""
raise NotImplementedError
@abstractmethod
def load_weights_fused_qkv_linear(self, module: Linear,
weights: List[Dict]) -> None:
"""
Load weights for the FUSED_QKV_LINEAR weight mode.
"""
raise NotImplementedError
@abstractmethod
def load_weights_fused_gate_up_linear(self, module: Linear,
weights: List[Dict]) -> None:
"""
Load weights for the FUSED_GATE_UP_LINEAR weight mode.
"""
raise NotImplementedError
class UnquantizedLinearMethod(LinearMethodBase):
def create_weights(self, module: Linear, in_features: int,
out_features: int, bias: bool, dtype: torch.dtype):
weight_shape = (out_features, in_features)
module.weight = Parameter(torch.empty(weight_shape, dtype=dtype),
requires_grad=False)
if bias:
module.bias = Parameter(torch.empty((out_features), dtype=dtype),
requires_grad=False)
else:
module.register_parameter("bias", None)
def apply(self, module: Linear, input: torch.Tensor,
bias: Optional[torch.Tensor]):
if module.use_custom_cublas_mm:
output = torch.ops.trtllm.cublas_mm(input,
module.weight.t(),
bias,
out_dtype=None)
else:
output = F.linear(input, module.weight, bias)
return output
def load_weights_vanilla(self, module: Linear, weights: List[Dict]) -> None:
load_weights_vanilla_helper(module, weights)
def load_weights_fused_qkv_linear(self, module: Linear,
weights: List[Dict]) -> None:
q_weight, k_weight, v_weight = load_weights_fused_qkv_helper(
module, weights)
fused_weight = torch.cat((q_weight, k_weight, v_weight))
copy_weight(module.weight, fused_weight)
def load_weights_fused_gate_up_linear(self, module: Linear,
weights: List[Dict]) -> None:
gate_weight, up_weight = load_weights_fused_gate_up_helper(
module, weights)
fused_weight = torch.cat((gate_weight, up_weight))
copy_weight(module.weight, fused_weight)
class FP8QDQLinearMethod(LinearMethodBase):
def create_weights(self, module: Linear, in_features: int,
out_features: int, bias: bool, dtype: torch.dtype):
weight_shape = (out_features, in_features)
module.weight = Parameter(torch.empty(weight_shape,
dtype=torch.float8_e4m3fn),
requires_grad=False)
module.weight_scale = Parameter(torch.tensor(1., dtype=torch.float32),
requires_grad=False)
module.input_scale = Parameter(torch.tensor(1., dtype=torch.float32),
requires_grad=False)
module.inv_input_scale = Parameter(torch.tensor(1.,
dtype=torch.float32),
requires_grad=False)
# K, V scales for NVFP4 KV cache
module.kv_scales = Parameter(torch.ones(3, dtype=torch.float32),
requires_grad=False)
# K, V scales for NVFP4 KV cache
module.inv_kv_scales = Parameter(torch.ones(3, dtype=torch.float32),
requires_grad=False)
if bias:
module.bias = Parameter(torch.empty((out_features), dtype=dtype),
requires_grad=False)
else:
module.register_parameter("bias", None)
def apply(self, module: Linear, input: torch.Tensor,
bias: Optional[torch.Tensor]):
cur_input_scale = module.input_scale
if input.dtype != torch.float8_e4m3fn:
if module.input_scale is not None and not module.force_dynamic_quantization:
# Static quantization
qinput, _ = torch.ops.tensorrt_llm.static_quantize_e4m3_per_tensor(
input, module.input_scale)
else:
# Dynamic quantization
qinput, cur_input_scale = torch.ops.tensorrt_llm.quantize_e4m3_per_tensor(
input)
cur_input_scale = cur_input_scale.to(torch.float32)
else:
qinput = input
# This op does not support bias now.
if module.enable_cuda_core and qinput.shape[0] <= 8:
# use cuda core for small m dimension
output = torch.ops.trtllm.cuda_scaled_mm(
qinput,
module.weight.t(),
scale_a=cur_input_scale,
scale_b=module.weight_scale,
bias=None,
out_dtype=module.dtype or input.dtype,
)
else:
output = torch.ops.trtllm.cublas_scaled_mm(
qinput,
module.weight.t(),
scale_a=cur_input_scale,
scale_b=module.weight_scale,
bias=None,
out_dtype=module.dtype or input.dtype,
)
if bias is not None:
output = output + bias
return output
def load_kv_scales(self, weights: List[Dict]):
k_scale, v_scale = [], []
for w in weights:
if "k_scale" in w:
k_scale.append(w["k_scale"][...].reshape([]))
if "v_scale" in w:
v_scale.append(w["v_scale"][...].reshape([]))
return k_scale, v_scale
def load_weight_scales(self, weights: List[Dict]):
input_scale, weight_scale = [], []
for w in weights:
if "input_scale" in w:
input_scale.append(w["input_scale"][...].reshape([]))
if "weight_scale" in w:
weight_scale.append(w["weight_scale"][...].reshape([]))
return input_scale, weight_scale
def load_weights_vanilla(self, module: Linear, weights: List[Dict]) -> None:
load_weights_vanilla_helper(module, weights)
input_scale, weight_scale = self.load_weight_scales(weights)
if len(input_scale) != 0:
# Static quantization
copy_weight(module.input_scale, input_scale[0])
module.inv_input_scale.data = 1.0 / module.input_scale
else:
# Dynamic quantization
module.input_scale = None
module.inv_input_scale = None
copy_weight(module.weight_scale, weight_scale[0])
def load_weights_fused_qkv_linear(self, module: Linear,
weights: List[Dict]) -> None:
q_weight, k_weight, v_weight = load_weights_fused_qkv_helper(
module, weights)
input_scale, weight_scale = self.load_weight_scales(weights)
if len(input_scale) != 0:
# Static quantization
copy_weight(module.input_scale, max(input_scale))
else:
# Dynamic quantization
module.input_scale = None
copy_weight(module.weight_scale, max(weight_scale))
# use in-place multiplication and division to avoid extra memory allocation
q_weight = q_weight.to(module.dtype).mul_(weight_scale[0])
k_weight = k_weight.to(module.dtype).mul_(weight_scale[1])
v_weight = v_weight.to(module.dtype).mul_(weight_scale[2])
fused_weight = torch.cat((q_weight, k_weight, v_weight))
fused_weight = fused_weight.div_(
module.weight_scale.to(fused_weight.device)).to(torch.float8_e4m3fn)
copy_weight(module.weight, fused_weight)
# Load k and v scales, used for NVFP4 KV cache
k_scale, v_scale = self.load_kv_scales(weights)
# NOTE: Currently the calibrated kv scales may cause overflow for certain input, disabling by default.
if os.environ.get("TRTLLM_LOAD_KV_SCALES", "0") == "1":
if len(k_scale) != 0:
assert len(v_scale) != 0
# The calibrated KV scales are amax / (6 * 448), but the requested KV scales are amax / 448,
# to avoid overflow when dequantizing NVFP4 in attention kernels.
copy_weight(
module.kv_scales,
torch.tensor(
[1.0, max(k_scale) * 6.0,
max(v_scale) * 6.0],
dtype=torch.float32))
module.inv_kv_scales.data = 1.0 / module.kv_scales
def load_weights_fused_gate_up_linear(self, module: Linear,
weights: List[Dict]) -> None:
input_scale, weight_scale = self.load_weight_scales(weights)
if len(input_scale) != 0:
# Static quantization
copy_weight(module.input_scale, max(input_scale))
else:
# Dynamic quantization
module.input_scale = None
copy_weight(module.weight_scale, max(weight_scale))
gate_weight, up_weight = load_weights_fused_gate_up_helper(
module, weights)
# use in-place multiplication and division to avoid extra memory allocation
gate_weight = gate_weight.to(module.dtype).mul_(weight_scale[0])
up_weight = up_weight.to(module.dtype).mul_(weight_scale[1])
fused_weight = torch.cat((gate_weight, up_weight))
fused_weight = fused_weight.div_(
module.weight_scale.to(fused_weight.device)).to(torch.float8_e4m3fn)
copy_weight(module.weight, fused_weight)
class FP8RowwiseLinearMethod(LinearMethodBase):
def create_weights(self, module: Linear, in_features: int,
out_features: int, bias: bool, dtype: torch.dtype):
weight_shape = (out_features, in_features)
module.weight = Parameter(torch.empty(weight_shape,
dtype=torch.float8_e4m3fn),
requires_grad=False)
module.weight_scale = Parameter(torch.empty(out_features),
requires_grad=False)
# Not really used for Gemm now.
# Only used to quantize output of FP8 attention.
module.input_scale = Parameter(torch.tensor(1., dtype=torch.float32),
requires_grad=False)
module.inv_input_scale = Parameter(torch.tensor(1.,
dtype=torch.float32),
requires_grad=False)
if bias:
module.bias = Parameter(torch.empty((out_features), dtype=dtype),
requires_grad=False)
else:
module.register_parameter("bias", None)
def apply(self, module: Linear, input: torch.Tensor,
bias: Optional[torch.Tensor]):
# FP8 tensor inputs are from attention. Directly use ones as scale.
if input.dtype == torch.float8_e4m3fn:
qinput = input
cur_input_scale = torch.ones(input.shape[0],
device=input.device,
dtype=torch.float32)
else:
# Use dynamic per-token quantization for activation
qinput, cur_input_scale = torch.ops.tensorrt_llm.quantize_e4m3_activation(
input)
# This op does not support bias now.
output = torch.ops.trtllm.fp8_rowwise_gemm(
qinput,
module.weight,
cur_input_scale.float(),
module.weight_scale,
module.dtype or input.dtype,
)
if bias is not None:
output = output + bias
return output
def _get_scale_name(self, weights: List[Dict]):
# `weight_scale_inv` for DS recipe and `weight_scale` for ModelOpt recipe.
# Actually they hold identical values of data_amax / 448.
scale_name = "weight_scale_inv"
if scale_name not in weights[0]:
scale_name = "weight_scale"
return scale_name
def load_weights_vanilla(self, module: Linear, weights: List[Dict]):
load_weights_vanilla_helper(module, weights)
scale_name = self._get_scale_name(weights)
weight_scale = load_weight_shard(weights[0][scale_name], module.tp_size,
module.tp_rank, module.tp_mode)
copy_weight(module.weight_scale, weight_scale)
if "input_scale" in weights[0]:
copy_weight(module.input_scale, weights[0]["input_scale"])
module.inv_input_scale.data = 1.0 / module.input_scale
def load_weights_fused_qkv_linear(self, module: Linear,
weights: List[Dict]):
q_weight, k_weight, v_weight = load_weights_fused_qkv_helper(
module, weights)
fused_weight = torch.cat((q_weight, k_weight, v_weight))
copy_weight(module.weight, fused_weight)
scale_name = self._get_scale_name(weights)
q_scale = load_weight_shard(weights[0][scale_name], module.tp_size,
module.tp_rank, module.tp_mode)
k_scale = load_weight_shard(weights[1][scale_name], module.tp_size,
module.tp_rank, module.tp_mode)
v_scale = load_weight_shard(weights[2][scale_name], module.tp_size,
module.tp_rank, module.tp_mode)
fused_fp8_block_scale = torch.cat((q_scale, k_scale, v_scale))
copy_weight(module.weight_scale, fused_fp8_block_scale)
def load_weights_fused_gate_up_linear(self, module: Linear,
weights: List[Dict]):
gate_weight, up_weight = load_weights_fused_gate_up_helper(
module, weights)
fused_weight = torch.cat((gate_weight, up_weight))
copy_weight(module.weight, fused_weight)
scale_name = self._get_scale_name(weights)
left_scale = load_weight_shard(weights[0][scale_name], module.tp_size,
module.tp_rank, module.tp_mode)
right_scale = load_weight_shard(weights[1][scale_name], module.tp_size,
module.tp_rank, module.tp_mode)
fused_scale = torch.cat((left_scale, right_scale))
copy_weight(module.weight_scale, fused_scale)
class FP8BlockScalesLinearMethod(LinearMethodBase):
def create_weights(self, module: Linear, in_features: int,
out_features: int, bias: bool, dtype: torch.dtype):
weight_shape = (out_features, in_features)
module.weight = Parameter(torch.empty(weight_shape,
dtype=torch.float8_e4m3fn),
requires_grad=False)
scale_shape = (math.ceil(out_features / 128),
math.ceil(in_features / 128))
module.weight_scale = Parameter(torch.empty(scale_shape,
dtype=torch.float32),
requires_grad=False)
# Not really used for Gemm now.
# Only used to quantize output of FP8 attention.
module.input_scale = Parameter(torch.tensor(1., dtype=torch.float32),
requires_grad=False)
module.inv_input_scale = Parameter(torch.tensor(1.,
dtype=torch.float32),
requires_grad=False)
if bias:
module.bias = Parameter(torch.empty((out_features), dtype=dtype),
requires_grad=False)
else:
module.register_parameter("bias", None)
def apply(self, module: Linear, input: torch.Tensor,
bias: Optional[torch.Tensor]):
if input.dtype == torch.float8_e4m3fn:
input = input.to(torch.bfloat16) * module.input_scale
assert input.dtype == torch.bfloat16
if is_sm_100f():
if module.use_cute_dsl_blockscaling_mm or module.disable_deep_gemm:
# TODO (@lmin): replace with cute_dsl gemm
act_input_fp8, act_input_sf = torch.ops.trtllm.fp8_quantize_1x128(
input)
output = torch.ops.trtllm.fp8_block_scaling_gemm(
act_input_fp8, module.weight, act_input_sf,
module.weight_scale)
else:
output = torch.ops.trtllm.fp8_swap_ab_gemm(
input,
module.weight,
module.weight_scale,
disable_ue8m0_cast=True,
)
else:
act_input_fp8, act_input_sf = torch.ops.trtllm.fp8_quantize_1x128(
input)
output = torch.ops.trtllm.fp8_block_scaling_gemm(
act_input_fp8, module.weight, act_input_sf, module.weight_scale)
if bias is not None:
output = output + bias
return output
def _get_scale_name(self, weights: List[Dict]):
# `weight_scale_inv` for DS recipe and `weight_scale` for ModelOpt recipe.
# Actually they hold identical values of data_amax / 448.
scale_name = "weight_scale_inv"
if scale_name not in weights[0]:
scale_name = "weight_scale"
return scale_name
def load_weights_vanilla(self, module: Linear, weights: List[Dict]) -> None:
load_weights_vanilla_helper(module, weights)
scale_name = self._get_scale_name(weights)
full_weight_scale = weights[0][scale_name]
# modelopt fp8_pb_wo can have 2 extra singleton dimensions
if full_weight_scale.dim() == 4:
full_weight_scale = full_weight_scale.squeeze(1).squeeze(-1)
weight_scale = load_weight_shard(full_weight_scale, module.tp_size,
module.tp_rank, module.tp_mode)
copy_weight(module.weight_scale, weight_scale)
if "input_scale" in weights[0]:
copy_weight(module.input_scale, weights[0]["input_scale"])
module.inv_input_scale.data = 1.0 / module.input_scale
def load_weights_fused_qkv_linear(self, module: Linear,
weights: List[Dict]) -> None:
q_weight, k_weight, v_weight = load_weights_fused_qkv_helper(
module, weights)
fused_weight = torch.cat((q_weight, k_weight, v_weight))
scale_name = self._get_scale_name(weights)
full_q_scale = weights[0][scale_name]
full_k_scale = weights[1][scale_name]
full_v_scale = weights[2][scale_name]
# modelopt fp8_pb_wo can have 2 extra singleton dimensions
if full_q_scale.dim() == 4:
full_q_scale = full_q_scale.squeeze(1).squeeze(-1)
if full_k_scale.dim() == 4:
full_k_scale = full_k_scale.squeeze(1).squeeze(-1)
if full_v_scale.dim() == 4:
full_v_scale = full_v_scale.squeeze(1).squeeze(-1)
q_scale = load_weight_shard(full_q_scale, module.tp_size,
module.tp_rank, module.tp_mode)
k_scale = load_weight_shard(full_k_scale, module.tp_size,
module.tp_rank, module.tp_mode)
v_scale = load_weight_shard(full_v_scale, module.tp_size,
module.tp_rank, module.tp_mode)
fused_fp8_block_scale = torch.cat((q_scale, k_scale, v_scale))
copy_weight(module.weight, fused_weight)
copy_weight(module.weight_scale, fused_fp8_block_scale)
def load_weights_fused_gate_up_linear(self, module: Linear,
weights: List[Dict]) -> None:
gate_weight, up_weight = load_weights_fused_gate_up_helper(
module, weights)
fused_weight = torch.cat((gate_weight, up_weight))
scale_name = self._get_scale_name(weights)
full_left_scale = weights[0][scale_name]
full_right_scale = weights[1][scale_name]
# modelopt fp8_pb_wo can have 2 extra singleton dimensions
if full_left_scale.dim() == 4:
full_left_scale = full_left_scale.squeeze(1).squeeze(-1)
if full_right_scale.dim() == 4:
full_right_scale = full_right_scale.squeeze(1).squeeze(-1)
left_scale = load_weight_shard(full_left_scale, module.tp_size,
module.tp_rank, module.tp_mode)
right_scale = load_weight_shard(full_right_scale, module.tp_size,
module.tp_rank, module.tp_mode)
fused_scale = torch.cat([left_scale, right_scale], dim=0)
copy_weight(module.weight, fused_weight)
copy_weight(module.weight_scale, fused_scale)
def post_load_weights(self, module: Linear):
super().post_load_weights(module)
if is_sm_100f() and not (module.use_cute_dsl_blockscaling_mm
or module.disable_deep_gemm):
weight, weight_scale = resmooth_to_fp8_e8m0(module.weight,
module.weight_scale)
transfromed_scale = transform_sf_into_required_layout(
weight_scale,
mn=weight.shape[0],
k=weight.shape[1],
recipe=(1, 128, 128),
is_sfa=False)
module.weight = nn.Parameter(weight, requires_grad=False)
module.weight_scale = nn.Parameter(
transfromed_scale,
requires_grad=False,
)
class NVFP4LinearMethod(LinearMethodBase):
def create_weights(self, module: Linear, in_features: int,
out_features: int, bias: bool, dtype: torch.dtype):
module.scaling_vector_size = 16
assert in_features % module.scaling_vector_size == 0, f"in_features {in_features} must be divisible by scaling_vector_size {module.scaling_vector_size}"
# Quantized weights
module.weight = Parameter(torch.empty([out_features, in_features // 2],
dtype=fp4_utils.float4_e2m1x2),
requires_grad=False)
# FP8 per-block scaling factors. dtype must be aligned with SF_DTYPE
# Padding is required. See computeSFSize in quantization.h
nrows = fp4_utils.pad_up(out_features, 128)
ncols = fp4_utils.pad_up(in_features // module.scaling_vector_size, 4)
module.weight_scale = Parameter(torch.empty(
[nrows * ncols], dtype=fp4_utils.float4_sf_dtype),
requires_grad=False)
# FP32 per-tensor global scaling factor = 448*6/amax_input
module.input_scale = Parameter(torch.empty([1], dtype=torch.float32),
requires_grad=False)
module.inv_input_scale = Parameter(torch.empty([1],
dtype=torch.float32),
requires_grad=False)
# (amax_input * amax_weight) / (448*6 * 448*6)
module.alpha = Parameter(torch.empty([1], dtype=torch.float32),
requires_grad=False)
# K, V scales for NVFP4 KV cache
module.kv_scales = Parameter(torch.ones(3, dtype=torch.float32),
requires_grad=False)
# K, V scales for NVFP4 KV cache
module.inv_kv_scales = Parameter(torch.ones(3, dtype=torch.float32),
requires_grad=False)
if bias:
module.bias = Parameter(torch.empty((out_features), dtype=dtype),
requires_grad=False)
else:
module.register_parameter("bias", None)
def apply(self, module: Linear, input: torch.Tensor,
bias: Optional[torch.Tensor]):
if isinstance(input, Fp4QuantizedTensor):
act_fp4, act_sf = input.fp4_tensor, input.scaling_factor
elif isinstance(input, tuple):
act_fp4, act_sf = input
else:
act_fp4, act_sf = torch.ops.trtllm.fp4_quantize(
input, module.input_scale, module.scaling_vector_size, False)
if IS_CUTLASS_DSL_AVAILABLE and module.use_cute_dsl_nvfp4_blockscaling_mm:
output = torch.ops.trtllm.cute_dsl_nvfp4_gemm_blackwell(
act_fp4, module.weight, act_sf, module.weight_scale,
module.scalar_alpha, module.dtype)
elif IS_CUBLASLT_AVAILABLE and module.use_cublaslt_nvfp4_blockscaling_mm:
output = torch.ops.trtllm.nvfp4_gemm_cublaslt(
act_fp4, module.weight, act_sf, module.weight_scale,
module.alpha, module.dtype)
else:
if module.enable_cuda_core and act_fp4.shape[0] <= 8:
act_sf_unswizzled = torch.ops.trtllm.block_scale_interleave_reverse(
act_sf.view((act_fp4.shape[0] + 128 - 1) // 128 * 128, -1))
output = torch.ops.trtllm.cuda_core_nvfp4_gemm(
act_fp4,
module.weight,
scale_a=act_sf_unswizzled,
scale_b=module.weight_scale,
alpha=module.alpha,
bias=None,
out_dtype=module.dtype or input.dtype,
)
else:
output = torch.ops.trtllm.nvfp4_gemm(act_fp4, module.weight,
act_sf,
module.weight_scale,
module.alpha, module.dtype)
# Take the dim of out_features if padded. Make sure the output is contiguous
if output.shape[-1] > module.out_features:
output = output[..., :module.out_features].contiguous()
if bias is not None:
output = output + bias
return output
def load_kv_scales(self, weights: List[Dict]):
k_scale, v_scale = [], []
for w in weights:
if "k_scale" in w:
k_scale.append(w["k_scale"][...].reshape([]))
if "v_scale" in w:
v_scale.append(w["v_scale"][...].reshape([]))
return k_scale, v_scale
def load_weight_scales(self,
weights: List[Dict],
tp_size: int = 1,
tp_rank: int = 0,
tp_mode: Optional[TensorParallelMode] = None):
# For concatenated weights (qkv_proj / up_gate_proj), the global scaling factors and input scaling factors should be shared.
input_scale = None
weight_scale_2 = None
weight_scale = []
device = torch.device("cuda")
for w in weights:
if "input_scale" in w:
if input_scale is None:
input_scale = w["input_scale"][...]
else:
assert input_scale == w["input_scale"][
...], "The input_scale should be same for all the weights"
if "weight_scale" in w:
ws = load_weight_shard(w["weight_scale"],
tp_size,
tp_rank,
tp_mode,
device=device).contiguous()
assert ws.dtype == torch.float8_e4m3fn # TODO: or e8m0 for mxfp4 recipe?
weight_scale.append(ws.view(fp4_utils.float4_sf_dtype))
if "weight_scale_2" in w:
if weight_scale_2 is None:
weight_scale_2 = w["weight_scale_2"][...]
else:
assert weight_scale_2 == w["weight_scale_2"][
...], "The weight_scale_2 should be same for all the weights"
# Compute scaling factor and alpha required by GEMM kernels
# TODO: ModelOpt's o_proj.weight_scale_2 is bfloat16, which should be float32
alpha = input_scale.float() * weight_scale_2.float()
# modelopt ckpt stores amax/(448*6), convert to (448*6)/amax
input_scale = 1.0 / input_scale
return input_scale, weight_scale, alpha
def load_weights_vanilla(self, module: Linear, weights: List[Dict]) -> None:
load_weights_vanilla_helper(module, weights)
input_scale, weight_scale, alpha = self.load_weight_scales(
weights,
tp_size=module.tp_size,
tp_rank=module.tp_rank,
tp_mode=module.tp_mode)
assert len(weights) == 1
weight_scale = weight_scale[0]
# Swizzle weight scale
weight_scale = torch.ops.trtllm.block_scale_interleave(weight_scale)
copy_weight(module.input_scale, input_scale)
copy_weight(module.weight_scale, weight_scale)
E2M1_MAX = 6.0
module.inv_input_scale.data = module.input_scale / E2M1_MAX
copy_weight(module.alpha, alpha)
module.scalar_alpha = alpha.item()
def load_weights_fused_qkv_linear(self, module: Linear,
weights: List[Dict]) -> None:
q_weight, k_weight, v_weight = load_weights_fused_qkv_helper(
module, weights)
input_scale, weight_scales, alpha = self.load_weight_scales(
weights,
tp_size=module.tp_size,
tp_rank=module.tp_rank,
tp_mode=module.tp_mode)
# Swizzle weight scales after concatenation
weight_scale = torch.cat(weight_scales, 0)
weight_scale = torch.ops.trtllm.block_scale_interleave(weight_scale)
copy_weight(module.input_scale, input_scale)
copy_weight(module.weight_scale, weight_scale)
copy_weight(module.alpha, alpha)
module.scalar_alpha = alpha.item()
fused_weight = torch.cat((q_weight, k_weight, v_weight))
copy_weight(module.weight, fused_weight)
# Load k and v scales, used for NVFP4 KV cache
k_scale, v_scale = self.load_kv_scales(weights)
# NOTE: Currently the calibrated kv scales may cause overflow for certain input, disabling by default.
if os.environ.get("TRTLLM_LOAD_KV_SCALES", "0") == "1":
if len(k_scale) != 0:
assert len(v_scale) != 0
# The calibrated KV scales are amax / (6 * 448), but the requested KV scales are amax / 448,
# to avoid overflow when dequantizing NVFP4 in attention kernels using FP8 math.
copy_weight(
module.kv_scales,
torch.tensor(
[1.0, max(k_scale) * 6.0,
max(v_scale) * 6.0],
dtype=torch.float32))
module.inv_kv_scales.data = 1.0 / module.kv_scales
def load_weights_fused_gate_up_linear(self, module: Linear,
weights: List[Dict]) -> None:
gate_weight, up_weight = load_weights_fused_gate_up_helper(
module, weights)
fused_weight = torch.cat((gate_weight, up_weight))
copy_weight(module.weight, fused_weight)
input_scale, weight_scales, alpha = self.load_weight_scales(
weights,
tp_size=module.tp_size,
tp_rank=module.tp_rank,
tp_mode=module.tp_mode)
# Swizzle weight scales after concatenation
weight_scale = torch.cat(weight_scales, 0)
weight_scale = torch.ops.trtllm.block_scale_interleave(weight_scale)
copy_weight(module.input_scale, input_scale)
copy_weight(module.weight_scale, weight_scale)
copy_weight(module.alpha, alpha)
module.scalar_alpha = alpha.item()
def post_load_weights(self, module: Linear):
super().post_load_weights(module)
"""
Pad weight and weight_scale tensors to meet torch trtllm NVFP4 GEMM alignment requirements.
Args:
row_alignment: Required row alignment (default: 32)
col_alignment: Required column alignment (default: 16)
"""
row_alignment, col_alignment = 32, 16
row_pad_size = (row_alignment - module.weight.size(0)) % row_alignment
col_pad_size = (col_alignment - module.weight.size(1)) % col_alignment
if row_pad_size != 0 or col_pad_size != 0:
# Pad weight to meet NVFP4 GEMM kernel alignment requirements
module.weight = Parameter(F.pad(module.weight,
(0, col_pad_size, 0, row_pad_size),
mode='constant',
value=0),
requires_grad=False)
weight_col_size = module.weight.size(1)
assert (
weight_col_size * 2
) % module.scaling_vector_size == 0, f"weight column size after padding {weight_col_size} must be divisible by scaling_vector_size {module.scaling_vector_size}"
# Pad weight_scale to match padded weight dimensions
# Padding should be performed on unswizzled weight_scale tensor
scale_rows = fp4_utils.pad_up(module.out_features, 128)
scale_cols = fp4_utils.pad_up(
module.in_features // module.scaling_vector_size, 4)
weight_scale_unswizzle = unswizzle_sf(module.weight_scale.data,
scale_rows, scale_cols,
module.scaling_vector_size)
weight_scale_unswizzle_pad = F.pad(
weight_scale_unswizzle,
(0, (col_pad_size * 2) // module.scaling_vector_size, 0,
row_pad_size),