-
Notifications
You must be signed in to change notification settings - Fork 765
Expand file tree
/
Copy pathquantize_ops.py
More file actions
2339 lines (1888 loc) · 69.6 KB
/
Copy pathquantize_ops.py
File metadata and controls
2339 lines (1888 loc) · 69.6 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) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
# Keep a registry of all quantize operators.
import abc
from typing import List, Tuple
import fbgemm_gpu.experimental.gen_ai # noqa: F401
import numpy as np
import torch
import triton # @manual=//triton:triton
from fbgemm_gpu.experimental.gemm.triton_gemm.fp4_quantize import (
triton_quantize_mx4_unpack,
triton_scale_nvfp4_quant,
)
from fbgemm_gpu.experimental.gemm.triton_gemm.fp8_gemm import (
get_fp8_constants,
matmul_fp8_block,
matmul_fp8_row,
quantize_fp8_block,
quantize_fp8_row,
scale_fp8_row,
triton_quantize_fp8_row,
)
from fbgemm_gpu.experimental.gemm.triton_gemm.grouped_gemm import (
grouped_gemm,
grouped_gemm_fp8_rowwise,
)
from fbgemm_gpu.experimental.gen_ai.quantize import (
quantize_int4_preshuffle,
scale_nvfp4_quant,
)
try:
from tinygemm.utils import group_quantize_tensor
if torch.cuda.is_available() and torch.version.cuda:
torch.ops.load_library("//tinygemm:tinygemm")
TINYGEMM_ENABLED = True
except ImportError:
TINYGEMM_ENABLED = False
# Marlin currently only is supported only internally at Meta.
try:
from marlin.quantize import marlin_quantize
torch.ops.load_library("//ai_codesign/gen_ai/marlin:marlin_ops")
MARLIN_ENABLED = True
except ImportError:
MARLIN_ENABLED = False
try:
from deep_gemm import (
gemm_fp8_fp8_bf16_nt,
get_col_major_tma_aligned_tensor,
m_grouped_gemm_fp8_fp8_bf16_nt_contiguous,
m_grouped_gemm_fp8_fp8_bf16_nt_masked,
)
DEEPGEMM_ENABLED = True
except ImportError:
DEEPGEMM_ENABLED = False
# Machete is also only supported internally at Meta for now.
try:
from machete.machete import machete_gemm
from machete.quantize import machete_quantize_and_pack
MACHETE_ENABLED = True
except ImportError:
MACHETE_ENABLED = False
quantize_op_registry = []
class QuantizeOpBase(metaclass=abc.ABCMeta):
"""Helper abstract class to define expected methods of quantize ops."""
@abc.abstractmethod
def quantize(self, *args):
"""Function which quantizes inputs."""
pass
@abc.abstractmethod
def compute(self, *args, **kwargs):
"""Function which performs main compute operation."""
pass
@abc.abstractmethod
def quantize_and_compute(self, *args, **kwargs):
"""Function which quantizes inputs and performs main compute operation."""
pass
def preprocess(self, *args):
"""Preprocess inputs before benchmarking. These outputs will be passed to quantize."""
return args
def bench_with_rotating_buffer(self, fn, args, use_cuda_graph: bool = True):
import copy
import pickle
# torch.cuda.get_device_properties does not have L2/L3 cache size,
# so hard code an overapproximation of L2/L3 cache size to ensure L2/L3 cache flush
total_buffer_size = 512 * 1024 * 1024
# Use pickle to serialize model input to estimate total sizes of input
input_sizes = len(pickle.dumps(args))
# Make at least one copy of the inputs
copy_cnt = total_buffer_size // input_sizes
if copy_cnt == 0:
copy_cnt = 1
args_list = [args]
for _ in range(copy_cnt):
args_list.append(copy.deepcopy(args))
def rotating_buffer_fn(fn, args_list, copy_cnt):
for i in range(copy_cnt):
fn(*(args_list[i]))
if use_cuda_graph:
with torch.cuda.stream(torch.cuda.Stream()):
# A rotating_buffer_fn contains multiple runs of the fn to benchmark,
# so divide time accordingly
return triton.testing.do_bench_cudagraph(
lambda: rotating_buffer_fn(self.compute, args_list, copy_cnt + 1),
rep=200,
) / (copy_cnt + 1)
else:
return triton.testing.do_bench(
lambda: rotating_buffer_fn(self.compute, args_list, copy_cnt + 1),
rep=200,
) / (copy_cnt + 1)
def benchmark(
self,
*args,
bench_quantize: bool = False,
use_rotating_buffer_bench: bool = False,
use_cuda_graph: bool = True,
**kwargs,
) -> float:
"""Benchmark runtime of this operator."""
if bench_quantize:
if use_cuda_graph:
with torch.cuda.stream(torch.cuda.Stream()):
t = triton.testing.do_bench_cudagraph(
lambda: self.quantize_and_compute(*args, **kwargs)
)
else:
t = triton.testing.do_bench(
lambda: self.quantize_and_compute(*args, **kwargs)
)
else:
if use_rotating_buffer_bench:
t = self.bench_with_rotating_buffer(self.compute, args, use_cuda_graph)
else:
if use_cuda_graph:
with torch.cuda.stream(torch.cuda.Stream()):
t = triton.testing.do_bench_cudagraph(
lambda: self.compute(*args, **kwargs)
)
else:
t = triton.testing.do_bench(lambda: self.compute(*args, **kwargs))
return t
@abc.abstractproperty
def name(self) -> str:
"""Name of the operator."""
pass
@abc.abstractproperty
def hip(self) -> bool:
"""Whether this operator supports AMD or not."""
pass
@abc.abstractproperty
def cuda(self) -> bool:
"""Whether this operator supports Nvidia or not."""
pass
@property
def supported(self) -> bool:
"""Whether this op will run on the current device."""
if torch.version.hip is not None:
return self.hip
elif torch.version.cuda is not None:
return self.cuda
else:
return False
def register_quantize_op(op):
"""Decorator function for assembling all quantize ops."""
quantize_op_registry.append(op())
return op
def get_quantize_ops() -> List[QuantizeOpBase]:
"""Get all registered quantize ops."""
return quantize_op_registry
@register_quantize_op
class BF16Baseline(QuantizeOpBase):
"""
Baseline BF16 matmul.
"""
def quantize(self, x, w):
if isinstance(x, list):
x = [i.bfloat16() for i in x]
w = [torch.transpose(i, -2, -1).bfloat16() for i in w]
else:
x = x.bfloat16()
w = torch.transpose(w, -2, -1).bfloat16()
return x, w
def compute(self, x, w):
# Handle both grouped and standard gemm.
if isinstance(x, list):
output = []
for i in range(len(x)):
output.append(torch.matmul(x[i], w[i]))
return output
return torch.matmul(x, w)
def quantize_and_compute(self, x, w):
return self.compute(*self.quantize(x, w))
@property
def name(self) -> str:
return "bf16_baseline"
@property
def hip(self) -> bool:
return True
@property
def cuda(self) -> bool:
return True
@register_quantize_op
class ScaledMMBaseline(QuantizeOpBase):
"""
Reference FP8 matmul implemented in native torch with cublas or hipblas.
"""
def __init__(self):
self.fp8_dtype, _, _, _ = get_fp8_constants()
self.E4M3_MAX_POS: float = torch.finfo(self.fp8_dtype).max
self.E5M2_MAX_POS: float = torch.finfo(torch.float8_e5m2).max
self.FP16_MAX_POS: float = torch.finfo(torch.float16).max
self.EPS: float = 1e-12
self.fast_accum = True
def _amax_to_scale(
self, amax: torch.Tensor, float8_dtype: torch.dtype, orig_dtype: torch.dtype
) -> torch.Tensor:
# To make scale dtype to be fp32 for accuracy
amax = amax.float()
if float8_dtype == self.fp8_dtype:
# pyre-fixme[58]: `/` is not supported for operand types `float` and `Tensor`.
res = self.E4M3_MAX_POS / torch.clamp(amax, min=self.EPS)
else: # e5m2
# pyre-fixme[58]: `/` is not supported for operand types `float` and `Tensor`.
res = self.E5M2_MAX_POS / torch.clamp(amax, min=self.EPS)
# pyre-fixme[7]: Expected `Tensor` but got `Union[float, Tensor]`.
return res
def _to_fp8_saturated(
self, x: torch.Tensor, float8_dtype: torch.dtype
) -> torch.Tensor:
if float8_dtype == torch.float8_e4m3fn:
x = x.clamp(min=-1 * self.E4M3_MAX_POS, max=self.E4M3_MAX_POS)
else:
x = x.clamp(min=-1 * self.E5M2_MAX_POS, max=self.E5M2_MAX_POS)
return x.to(float8_dtype)
def _quantize_tensor(self, x):
x_amax = torch.max(torch.abs(x))
scale = self._amax_to_scale(x_amax, self.fp8_dtype, x.dtype)
scaled_x = self._to_fp8_saturated(x * scale, self.fp8_dtype)
x_inverse_scale = scale.reciprocal()
return scaled_x, x_inverse_scale
def quantize(self, x, w):
xq, x_scale = self._quantize_tensor(x)
wq, w_scale = self._quantize_tensor(w.t())
return xq, wq, x_scale, w_scale
def compute(self, xq, wq, x_scale, w_scale):
output = torch._scaled_mm(
xq,
wq,
bias=None,
out_dtype=torch.bfloat16,
scale_a=x_scale,
scale_b=w_scale,
scale_result=None,
use_fast_accum=self.fast_accum,
)
return output
def quantize_and_compute(self, x, w):
return self.compute(*self.quantize(x, w))
@property
def name(self) -> str:
return "scaled_mm"
@property
def hip(self) -> bool:
return True
@property
def cuda(self) -> bool:
return True
@register_quantize_op
class ScaledMMRowwise(QuantizeOpBase):
def __init__(self):
self.fast_accum = True
def quantize(self, x, w):
xq, x_scale = quantize_fp8_row(x)
wq, w_scale = quantize_fp8_row(w)
dummy_scale = torch.tensor([1.0], device=x.device, dtype=torch.float32)
return xq, wq.t(), x_scale, w_scale, dummy_scale
def compute(self, xq, wq, x_scale, w_scale, dummy_scale):
output = torch._scaled_mm(
xq,
wq,
bias=None,
out_dtype=torch.bfloat16,
scale_a=dummy_scale,
scale_b=dummy_scale,
scale_result=None,
use_fast_accum=self.fast_accum,
)
# Apply separate rowwise scaling.
output = scale_fp8_row(output, x_scale, w_scale)
return output
def quantize_and_compute(self, x, w):
return self.compute(*self.quantize(x, w))
@property
def name(self) -> str:
return "scaled_mm_rowwise"
@property
def hip(self) -> bool:
return True
@property
def cuda(self) -> bool:
return True
@register_quantize_op
class FP8TensorwiseGemm(QuantizeOpBase):
"""
FP8 matmul with tensorwise scaling.
"""
def quantize(self, x, w):
# Quantize both input tensors.
xq, x_scale = torch.ops.fbgemm.quantize_fp8_per_tensor(x)
wq, w_scale = torch.ops.fbgemm.quantize_fp8_per_tensor(w)
return xq, wq, x_scale, w_scale
def compute(self, xq, wq, x_scale, w_scale):
return torch.ops.fbgemm.f8f8bf16(xq, wq, x_scale * w_scale)
def quantize_and_compute(self, x, w):
xq, wq, x_scale, w_scale = self.quantize(x, w)
return self.compute(xq, wq, x_scale, w_scale)
@property
def name(self) -> str:
return "cutlass_tensorwise"
@property
def hip(self) -> bool:
# Need to add support for better quantize kernel.
# Also may have an issue with cuda graphs.
return False
@property
def cuda(self) -> bool:
return True
@register_quantize_op
class BF16OSSFastGemv(QuantizeOpBase):
"""
BF16 OSS fast gemv kernel.
"""
def quantize(self, x, w):
# dummy quantize
return x, w
def compute(self, x, w):
out = torch.ops.fbgemm.bf16_fast_gemv(x, w)
return out
def quantize_and_compute(self, x, w):
x, w = self.quantize(x, w)
return self.compute(x, w)
@property
def name(self) -> str:
return "bf16_oss_fast_gemv"
@property
def hip(self) -> bool:
# This implementation is specific to cublas.
return False
@property
def cuda(self) -> bool:
return True
@register_quantize_op
class BF16Fp8OSSFastGemv(QuantizeOpBase):
"""
BF16FP8 OSS fast gemv kernel.
"""
def quantize(self, x, w):
wq, w_scale = torch.ops.fbgemm.quantize_fp8_per_tensor(w)
return x, wq, w_scale
def compute(self, x, wq, w_scale):
out = torch.ops.fbgemm.bf16fp8bf16_fast_gemv(x, wq, w_scale)
return out
def quantize_and_compute(self, x, w):
x, wq, w_scale = self.quantize(x, w)
return self.compute(x, wq, w_scale)
@property
def name(self) -> str:
return "bf16fp8_oss_fast_gemv"
@property
def hip(self) -> bool:
# This implementation is specific to cublas.
return False
@property
def cuda(self) -> bool:
return True
@register_quantize_op
class Fp8Fp8OSSFastGemv(QuantizeOpBase):
"""
FP8FP8 OSS fast gemv kernel.
"""
def quantize(self, x, w):
# rowwise quantize
xq, x_scale = torch.ops.fbgemm.quantize_fp8_per_row(x)
wq, w_scale = torch.ops.fbgemm.quantize_fp8_per_row(w)
return xq, wq, x_scale, w_scale
def compute(self, xq, wq, x_scale, w_scale):
out = torch.ops.fbgemm.fp8fp8bf16_fast_gemv(
xq, wq, x_scale, w_scale, is_batched=False
)
return out
def quantize_and_compute(self, x, w):
xq, wq, x_scale, w_scale = self.quantize(x, w)
return self.compute(xq, wq, x_scale, w_scale)
@property
def name(self) -> str:
return "fp8fp8_oss_fast_gemv"
@property
def hip(self) -> bool:
# This implementation is specific to cublas.
return False
@property
def cuda(self) -> bool:
return True
@register_quantize_op
class Fp8OSSFastGemvBatched(QuantizeOpBase):
"""
Batched fp8 fast gemv kernel
"""
def quantize(self, x, w):
# rowwise quantize
xq, x_scale = torch.ops.fbgemm.quantize_fp8_per_row(x)
wq, w_scale = torch.ops.fbgemm.quantize_fp8_per_row(w)
return xq, wq, x_scale, w_scale
def compute(self, xq, wq, x_scale, w_scale):
out = torch.ops.fbgemm.fp8fp8bf16_fast_gemv(
xq, wq, x_scale, w_scale, is_batched=True
)
return out
def quantize_and_compute(self, x, w):
xq, wq, x_scale, w_scale = self.quantize(x, w)
return self.compute(xq, wq, x_scale, w_scale)
@property
def name(self) -> str:
return "fp8fp8_oss_fast_gemv_batched"
@property
def hip(self) -> bool:
# This implementation is specific to cublas.
return False
@property
def cuda(self) -> bool:
return True
@register_quantize_op
class FP8CublasRowwiseGemm(QuantizeOpBase):
"""
FP8 cublas matmul with rowwise scaling.
"""
def quantize(self, x, w):
# Quantize both input tensors.
xq, x_scale = torch.ops.fbgemm.quantize_fp8_per_row(x)
wq, w_scale = torch.ops.fbgemm.quantize_fp8_per_row(w)
return xq, wq, x_scale, w_scale
def compute(self, xq, wq, x_scale, w_scale):
out = torch.ops.fbgemm.f8f8bf16_cublas(xq, wq)
scaled_out = scale_fp8_row(out, x_scale, w_scale)
return scaled_out
def quantize_and_compute(self, x, w):
xq, wq, x_scale, w_scale = self.quantize(x, w)
return self.compute(xq, wq, x_scale, w_scale)
@property
def name(self) -> str:
return "cublas_rowwise"
@property
def hip(self) -> bool:
# This implementation is specific to cublas.
return False
@property
def cuda(self) -> bool:
return True
@register_quantize_op
class FP8CublasTensorwiseGemm(QuantizeOpBase):
"""
FP8 cublas matmul with tensorwise scaling.
"""
def quantize(self, x, w):
# Quantize both input tensors.
xq, x_scale = torch.ops.fbgemm.quantize_fp8_per_tensor(x)
wq, w_scale = torch.ops.fbgemm.quantize_fp8_per_tensor(w)
return xq, wq, x_scale, w_scale
def compute(self, xq, wq, x_scale, w_scale):
return torch.ops.fbgemm.f8f8bf16_cublas(xq, wq, x_scale * w_scale)
def quantize_and_compute(self, x, w):
xq, wq, x_scale, w_scale = self.quantize(x, w)
return self.compute(xq, wq, x_scale * w_scale)
@property
def name(self) -> str:
return "cublas_tensorwise"
@property
def hip(self) -> bool:
# This implementation is specific to cublas.
return False
@property
def cuda(self) -> bool:
return True
@register_quantize_op
class FP8RowwiseGemm(QuantizeOpBase):
"""
FP8 matmul with rowwise scaling.
"""
def __init__(self):
self.fast_accum = True
def preprocess(self, x, w):
# Prequantize weights.
if isinstance(w, (list, tuple)):
wq, w_scale = zip(*[quantize_fp8_row(i) for i in w])
else:
wq, w_scale = quantize_fp8_row(w)
if wq.dim() == 3:
w_scale = w_scale.view(wq.size(0), -1)
return x, wq, w_scale
def quantize(self, x, wq, w_scale):
# Quantize both input tensors.
# Handle both grouped and standard gemm.
if isinstance(x, (list, tuple)):
xq, x_scale = zip(*[quantize_fp8_row(i) for i in x])
else:
xq, x_scale = quantize_fp8_row(x)
# Set proper batch dimension shapes.
if xq.dim() == 3:
x_scale = x_scale.view(xq.size(0), -1)
return xq, wq, x_scale, w_scale
def compute(self, xq, wq, x_scale, w_scale):
# Handle group gemm if inputs are grouped.
if isinstance(xq, (list, tuple)):
output = []
for i in range(len(xq)):
output.append(
torch.ops.fbgemm.f8f8bf16_rowwise(
xq[i],
wq[i],
x_scale[i],
w_scale[i],
use_fast_accum=self.fast_accum,
)
)
return output
# Unroll batched gemm if needed.
elif xq.dim() == 3 and wq.dim() == 3:
B, M, _ = xq.shape
_, N, _ = wq.shape
y = torch.empty((B, M, N), device=xq.device, dtype=torch.bfloat16)
for i in range(B):
y[i] = torch.ops.fbgemm.f8f8bf16_rowwise(
xq[i], wq[i], x_scale[i], w_scale[i], use_fast_accum=self.fast_accum
)
return y
# Otherwise return normal gemm result.
return torch.ops.fbgemm.f8f8bf16_rowwise(
xq, wq, x_scale, w_scale, use_fast_accum=self.fast_accum
)
def quantize_and_compute(self, x, wq, w_scale):
xq, wq, x_scale, w_scale = self.quantize(x, wq, w_scale)
return self.compute(xq, wq, x_scale, w_scale)
@property
def name(self) -> str:
if torch.version.cuda:
return "cutlass_rowwise"
else:
return "ck_rowwise"
@property
def hip(self) -> bool:
return True
@property
def cuda(self) -> bool:
return True
@register_quantize_op
class FP8RowwiseGroupedGemm(QuantizeOpBase):
"""
FP8 grouped matmul with rowwise scaling.
"""
def preprocess(self, x, w):
# Apply sparsity to inputs if appropriate.
# First check if N and K are fixed.
m_values = [i.shape[0] for i in x]
n_values = [i.shape[0] for i in w]
k_values = [i.shape[1] for i in w]
# If so, do specialized version of initialization.
if len(np.unique(n_values)) == 1 and len(np.unique(k_values)) == 1:
m_values = [i.shape[0] for i in x]
# Inputs for fixed nk mode must be contiguous, however in the benchmark
# script they typically are not. Do a little special processing to make them
# work. In practice this wont be needed.
# Start by padding along m dimension with zeros.
max_m = max(m_values)
x = [
torch.nn.functional.pad(i, (0, 0, 0, max_m - i.shape[0]), value=0)
for i in x
]
# Stack inputs into groups.
x = torch.stack(x).contiguous()
w = torch.stack(w).contiguous()
# Preapply weight quantization.
wq, w_scale = quantize_fp8_row(w)
# Return processed tensors.
return (
x,
wq,
w_scale,
torch.tensor(m_values).to(dtype=torch.int64, device=x[0].device),
)
# Otherwise run without sparsity.
wq, w_scale = zip(*[quantize_fp8_row(i) for i in w])
return x, wq, w_scale, None
def quantize(self, x, wq, w_scale, m_values=None):
# Handle case where inputs are explicitly grouped and non-sparse.
if isinstance(x, (tuple, list)):
xq, x_scale = zip(*[triton_quantize_fp8_row(i) for i in x])
return xq, wq, x_scale, w_scale, m_values
# Otherwise inputs are unified tensors and sparse.
else:
B = x.shape[0]
xq, x_scale = triton_quantize_fp8_row(x, zero_start_index_M=m_values)
x_scale = x_scale.view(B, -1)
return xq, wq, x_scale, w_scale, m_values
def compute(self, xq, wq, x_scale, w_scale, m_values):
if m_values is None:
return torch.ops.fbgemm.f8f8bf16_rowwise_grouped(
xq,
wq,
x_scale,
w_scale,
)
else:
# Break tensor into groups, simulates what is done e2e.
return torch.ops.fbgemm.f8f8bf16_rowwise_grouped_dynamic(
xq,
wq,
x_scale,
w_scale,
zero_start_index_M=m_values,
)
def quantize_and_compute(self, x, wq, w_scale, m_values=None):
xq, wq, x_scale, w_scale, m_values = self.quantize(x, wq, w_scale, m_values)
return self.compute(xq, wq, x_scale, w_scale, m_values)
@property
def name(self) -> str:
if torch.version.cuda:
return "cutlass_rowwise_grouped"
else:
return "ck_rowwise_grouped"
@property
def hip(self) -> bool:
return True
@property
def cuda(self) -> bool:
return True
@register_quantize_op
class BF16TritonStackedGroupedGemm(QuantizeOpBase):
"""
BF16 grouped matmul with stacked inputs implemented with triton.
"""
def preprocess(self, x, w):
m_values = [i.shape[0] for i in x]
# Convert m_values into offsets into grouped tensor.
m_sizes = torch.tensor(m_values).to(dtype=torch.int32, device=x[0].device)
w = torch.concat(w, dim=0).contiguous()
# Also view input as flattened.
x = torch.concat(x, dim=0).contiguous()
# Return processed tensors.
return x, w, m_sizes
def quantize(self, x, w, m_sizes):
return x, w, m_sizes
def compute(self, x, w, m_sizes):
return grouped_gemm(x, w, m_sizes, _use_warp_specialization=True)
def quantize_and_compute(self, x, w, m_sizes):
x, w, m_sizes = self.quantize(x, w, m_sizes)
return self.compute(x, w, m_sizes)
@property
def name(self) -> str:
return "triton_bf16_grouped_stacked"
@property
def hip(self) -> bool:
return True
@property
def cuda(self) -> bool:
return True
@register_quantize_op
class BF16TritonStackedGroupedGemmFuseScatterAdd(BF16TritonStackedGroupedGemm):
"""
BF16 grouped matmul with stacked inputs implemented with triton. Fused with ScatterAdd.
"""
def preprocess(self, x, w):
x, w, m_sizes = super().preprocess(x, w)
M = x.shape[0]
N = w.shape[0] // m_sizes.shape[0]
output = torch.zeros(M, N, dtype=torch.bfloat16, device=x.device)
indices = torch.randperm(M, dtype=torch.int32, device=x.device)
return x, w, m_sizes, output, indices
def quantize(self, x, w, m_sizes, *args):
return *super().quantize(x, w, m_sizes), *args
def compute(self, x, w, m_sizes, output, indices):
return grouped_gemm(
x,
w,
m_sizes,
_use_warp_specialization=True,
_output_tensor=output,
_scatter_add_indices=indices,
)
def quantize_and_compute(self, x, w, m_sizes, *args):
x, w, m_sizes, *ret = self.quantize(x, w, m_sizes, *args)
return self.compute(x, w, m_sizes, *ret)
@property
def name(self) -> str:
return "triton_bf16_grouped_stacked_fuse_scatter_add"
@register_quantize_op
class FP8TritonStackedGroupedGemm(QuantizeOpBase):
"""
FP8 grouped matmul with rowwise scaling and stacked inputs implemented with triton.
"""
def preprocess(self, x, w):
m_values = [i.shape[0] for i in x]
# Convert m_values into offsets into grouped tensor.
m_sizes = torch.tensor(m_values).to(dtype=torch.int32, device=x[0].device)
# Quantize weights.
wq, w_scale = zip(*[quantize_fp8_row(i) for i in w])
# Group weights as single tensor.
wq = torch.concat(wq, dim=0).contiguous()
w_scale = torch.concat(w_scale, dim=0).contiguous()
# Also view input as flattened.
x = torch.concat(x, dim=0).contiguous()
# Return processed tensors.
return x, wq, w_scale, m_sizes
def quantize(self, x, wq, w_scale, m_sizes):
B = x.shape[0]
xq, x_scale = triton_quantize_fp8_row(x)
x_scale = x_scale.view(B, -1)
return xq, wq, x_scale, w_scale, m_sizes
def compute(self, xq, wq, x_scale, w_scale, m_sizes):
return grouped_gemm_fp8_rowwise(
xq, wq, m_sizes, x_scale, w_scale, _use_warp_specialization=True
)
def quantize_and_compute(self, x, wq, w_scale, m_sizes):
xq, wq, x_scale, w_scale, m_sizes = self.quantize(x, wq, w_scale, m_sizes)
return self.compute(xq, wq, x_scale, w_scale, m_sizes)
@property
def name(self) -> str:
return "triton_grouped_stacked"
@property
def hip(self) -> bool:
return True
@property
def cuda(self) -> bool:
return True
@register_quantize_op
class FP8TritonStackedGroupedGemmFuseScatterAdd(FP8TritonStackedGroupedGemm):
"""
FP8 grouped matmul with stacked inputs implemented with triton. Fused with ScatterAdd.
"""
def preprocess(self, x, w):
x, wq, w_scale, m_sizes = super().preprocess(x, w)
M = x.shape[0]
N = wq.shape[0] // m_sizes.shape[0]
output = torch.zeros(M, N, dtype=torch.bfloat16, device=x.device)
indices = torch.randperm(M, dtype=torch.int32, device=x.device)
return x, wq, w_scale, m_sizes, output, indices
def quantize(self, x, wq, w_scale, m_sizes, *args):
return *super().quantize(x, wq, w_scale, m_sizes), *args
def compute(self, xq, wq, x_scale, w_scale, m_sizes, output, indices):
return grouped_gemm_fp8_rowwise(
xq,
wq,
m_sizes,
x_scale,
w_scale,
_use_warp_specialization=True,
_output_tensor=output,
_scatter_add_indices=indices,
)
def quantize_and_compute(self, x, wq, w_scale, m_sizes, *args):
xq, wq, x_scale, w_scale, m_sizes, *ret = self.quantize(
x, wq, w_scale, m_sizes, *args
)
return self.compute(xq, wq, x_scale, w_scale, m_sizes, *ret)
@property
def name(self) -> str:
return "triton_grouped_stacked_fuse_scatter_add"
@register_quantize_op
class DeepGemmStacked(QuantizeOpBase):
"""
FP8 grouped matmul with blockwise scaling implemented with DeepGemm.
"""
def preprocess(self, x, w):
m_values = [i.shape[0] for i in x]
# Convert m_values into offsets into grouped tensor.
indices = torch.arange(len(m_values))
m_indices = indices.repeat_interleave(torch.tensor(m_values)).to(
device=x[0].device, dtype=torch.int
)
# Quantize weights.
wq, w_scale = zip(*[quantize_fp8_block(i, block_k=128, block_m=128) for i in w])
# Group weights as single tensor.
wq = torch.stack(wq, dim=0).contiguous()
w_scale = torch.stack(w_scale, dim=0).contiguous()
# Also view input as flattened.
x = torch.concat(x, dim=0).contiguous()
# Return processed tensors.
return x, wq, w_scale, m_indices
def quantize(self, x, wq, w_scale, m_indices):
xq, x_scale = quantize_fp8_block(x, block_m=1, block_k=128)
# Pretranspose scales to deepgemm format.
x_scale = get_col_major_tma_aligned_tensor(x_scale)
return xq, wq, x_scale, w_scale, m_indices
def compute(self, xq, wq, x_scale, w_scale, m_indices):
# Preallocate output.
out = torch.empty(
[xq.shape[0], wq.shape[1]], device=xq.device, dtype=torch.bfloat16
)
m_grouped_gemm_fp8_fp8_bf16_nt_contiguous(
(xq, x_scale), (wq, w_scale), out, m_indices
)
return out
def quantize_and_compute(self, x, wq, w_scale, m_indices):
xq, wq, x_scale, w_scale, m_indices = self.quantize(x, wq, w_scale, m_indices)
return self.compute(xq, wq, x_scale, w_scale, m_indices)
@property
def name(self) -> str:
return "deepgemm_stacked"
@property
def hip(self) -> bool:
return False
@property
def cuda(self) -> bool:
return DEEPGEMM_ENABLED