fp8_utils.py 28.5 KB
Newer Older
1
from typing import Callable, List, Optional, Tuple
HAI's avatar
HAI committed
2
3

import torch
HandH1998's avatar
HandH1998 committed
4

fzyzcjy's avatar
fzyzcjy committed
5
from sglang.srt import offloader
6
from sglang.srt.layers.quantization import deep_gemm_wrapper
Yineng Zhang's avatar
Yineng Zhang committed
7
from sglang.srt.layers.quantization.fp8_kernel import sglang_per_token_group_quant_fp8
8
from sglang.srt.layers.quantization.mxfp4_tensor import MXFP4QuantizeUtil
9
from sglang.srt.utils import is_sm100_supported
Yineng Zhang's avatar
Yineng Zhang committed
10

Lianmin Zheng's avatar
Lianmin Zheng committed
11
try:
12
    from vllm import _custom_ops as ops
Lianmin Zheng's avatar
Lianmin Zheng committed
13
14
15
16
17

    VLLM_AVAILABLE = True
except ImportError:
    VLLM_AVAILABLE = False

HandH1998's avatar
HandH1998 committed
18
from sglang.srt.layers.quantization.fp8_kernel import (
19
20
21
    fp8_dtype,
    fp8_max,
    is_fp8_fnuz,
HandH1998's avatar
HandH1998 committed
22
    per_token_group_quant_fp8,
Lianmin Zheng's avatar
Lianmin Zheng committed
23
24
    scaled_fp8_quant,
    sglang_per_token_quant_fp8,
HandH1998's avatar
HandH1998 committed
25
    static_quant_fp8,
26
    triton_scaled_mm,
27
28
    w8a8_block_fp8_matmul_deepgemm,
    w8a8_block_fp8_matmul_triton,
HandH1998's avatar
HandH1998 committed
29
)
HandH1998's avatar
HandH1998 committed
30
from sglang.srt.utils import (
31
    align,
32
    ceil_div,
HandH1998's avatar
HandH1998 committed
33
34
35
    get_bool_env_var,
    get_cuda_version,
    get_device_capability,
Lianmin Zheng's avatar
Lianmin Zheng committed
36
    is_cuda,
37
    is_flashinfer_available,
HandH1998's avatar
HandH1998 committed
38
39
40
    is_hip,
)

41
_is_hip = is_hip()
Lianmin Zheng's avatar
Lianmin Zheng committed
42
_is_cuda = is_cuda()
43
_is_fp8_fnuz = is_fp8_fnuz()
Lianmin Zheng's avatar
Lianmin Zheng committed
44

45
_use_aiter = get_bool_env_var("SGLANG_USE_AITER") and _is_hip
46

47
if _use_aiter:
48
    import aiter
49
    from aiter import gemm_a8w8_blockscale, gemm_a8w8_bpreshuffle, get_hip_quant
50
51

    aiter_per1x128_quant = get_hip_quant(aiter.QuantType.per_1x128)
yigex's avatar
yigex committed
52

53
if _is_cuda:
54
    from sgl_kernel import fp8_blockwise_scaled_mm, fp8_scaled_mm
HAI's avatar
HAI committed
55

Lianmin Zheng's avatar
Lianmin Zheng committed
56
use_vllm_cutlass_w8a8_fp8_kernel = get_bool_env_var("USE_VLLM_CUTLASS_W8A8_FP8_KERNEL")
57
use_triton_w8a8_fp8_kernel = get_bool_env_var("USE_TRITON_W8A8_FP8_KERNEL")
HandH1998's avatar
HandH1998 committed
58

HandH1998's avatar
HandH1998 committed
59
60
# Input scaling factors are no longer optional in _scaled_mm starting
# from pytorch 2.5. Allocating a dummy tensor to pass as input_scale
Lianmin Zheng's avatar
Lianmin Zheng committed
61
TORCH_DEVICE_IDENTITY = None
HandH1998's avatar
HandH1998 committed
62

63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79

def use_rowwise_torch_scaled_mm():
    _TORCH_VERSION = torch.__version__.split("+")[0]
    try:
        _TORCH_VERSION_TUPLE = tuple(map(int, _TORCH_VERSION.split(".")[:3]))
    except ValueError:
        _TORCH_VERSION_TUPLE = (0, 0, 0)
    if _is_hip:
        # The condition to determine if it is on a platform that supports
        # torch._scaled_mm rowwise feature.
        # The condition is determined once as the operations
        # are time consuming.
        return get_device_capability() >= (9, 4) and _TORCH_VERSION_TUPLE >= (2, 7, 0)
    return False


USE_ROWWISE_TORCH_SCALED_MM = use_rowwise_torch_scaled_mm()
80

HandH1998's avatar
HandH1998 committed
81
82
83
84
85
86
87
88
89
90
91
92

def cutlass_fp8_supported():
    if not _is_cuda:
        return False
    major, minor = get_device_capability()
    cuda_version = get_cuda_version()
    if major >= 9:
        return cuda_version >= (12, 0)
    elif major == 8 and minor == 9:
        return cuda_version >= (12, 4)
    return False

HAI's avatar
HAI committed
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115

def normalize_e4m3fn_to_e4m3fnuz(
    weight: torch.Tensor,
    weight_scale: torch.Tensor,
    input_scale: Optional[torch.Tensor] = None,
) -> Tuple[torch.Tensor, torch.Tensor, Optional[torch.Tensor]]:
    assert weight.dtype == torch.float8_e4m3fn
    # The bits pattern 10000000(-128) represents zero in e4m3fn
    # but NaN in e4m3fnuz. So here we set it to 0.
    # https://onnx.ai/onnx/technical/float8.html
    weight_as_int8 = weight.view(torch.int8)
    ROCM_FP8_NAN_AS_INT = -128
    weight_as_int8[weight_as_int8 == ROCM_FP8_NAN_AS_INT] = 0
    weight = weight_as_int8.view(torch.float8_e4m3fnuz)

    # For the same bits representation, e4m3fnuz value is half of
    # the e4m3fn value, so we should double the scaling factor to
    # get the same dequantized value.
    # https://onnx.ai/onnx/technical/float8.html
    weight_scale = weight_scale * 2.0
    if input_scale is not None:
        input_scale = input_scale * 2.0
    return weight, weight_scale, input_scale
HandH1998's avatar
HandH1998 committed
116
117


118
# TODO(ch-wan): define these backends in --moe-runner-backend
119
def cutlass_block_fp8_supported() -> bool:
120
    if not get_bool_env_var("SGLANG_SUPPORT_CUTLASS_BLOCK_FP8"):
121
        return False
122
123
124
125
126
127
128
129
130
131
    if _is_cuda:
        major, minor = torch.cuda.get_device_capability()
        sm_version = major * 10 + minor
        cuda_version = tuple(map(int, torch.version.cuda.split(".")))
        if cuda_version >= (12, 0) and sm_version >= 90:
            return True
    return False


CUTLASS_BLOCK_FP8_SUPPORTED = cutlass_block_fp8_supported()
132
133
134
135
136
137
138
ENABLE_FLASHINFER_GEMM = (
    get_bool_env_var("SGLANG_ENABLE_FLASHINFER_GEMM")
    and is_sm100_supported()
    and is_flashinfer_available()
)
if ENABLE_FLASHINFER_GEMM:
    from flashinfer.gemm import gemm_fp8_nt_groupwise
139
140


141
142
143
144
145
def dispatch_w8a8_block_fp8_linear() -> Callable:
    if ENABLE_FLASHINFER_GEMM:
        return flashinfer_gemm_w8a8_block_fp8_linear
    elif CUTLASS_BLOCK_FP8_SUPPORTED:
        return cutlass_w8a8_block_fp8_linear_with_fallback
146
    elif _use_aiter:
147
        return aiter_w8a8_block_fp8_linear
148
    elif deep_gemm_wrapper.ENABLE_JIT_DEEPGEMM:
149
150
151
152
153
154
        return deepgemm_w8a8_block_fp8_linear_with_fallback
    else:
        return triton_w8a8_block_fp8_linear


def flashinfer_gemm_w8a8_block_fp8_linear(
HandH1998's avatar
HandH1998 committed
155
156
157
158
159
160
161
162
    input: torch.Tensor,
    weight: torch.Tensor,
    block_size: List[int],
    weight_scale: torch.Tensor,
    input_scale: Optional[torch.Tensor] = None,
    bias: Optional[torch.Tensor] = None,
) -> torch.Tensor:
    assert input_scale is None
163

HandH1998's avatar
HandH1998 committed
164
165
    input_2d = input.view(-1, input.shape[-1])
    output_shape = [*input.shape[:-1], weight.shape[0]]
166
167

    q_input, x_scale = sglang_per_token_group_quant_fp8(
168
        input_2d, block_size[1], column_major_scales=True
HandH1998's avatar
HandH1998 committed
169
    )
170
    # TRTLLM requires column-major scaling factors
171
    output = gemm_fp8_nt_groupwise(
172
173
174
175
176
        q_input,
        weight,
        x_scale,
        weight_scale,
        out_dtype=input_2d.dtype,
177
        backend="trtllm",
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
    )

    if bias is not None:
        output += bias

    return output.to(dtype=input_2d.dtype).view(*output_shape)


def cutlass_w8a8_block_fp8_linear_with_fallback(
    input: torch.Tensor,
    weight: torch.Tensor,
    block_size: List[int],
    weight_scale: torch.Tensor,
    input_scale: Optional[torch.Tensor] = None,
    bias: Optional[torch.Tensor] = None,
) -> torch.Tensor:
    assert input_scale is None

    # TODO: add more robust shape check here
    shape_supported = weight.shape[0] % 128 == 0 and weight.shape[1] % 128 == 0

    if not shape_supported:
        # fallback to triton
        return triton_w8a8_block_fp8_linear(
            input, weight, block_size, weight_scale, input_scale, bias
yigex's avatar
yigex committed
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

    input_2d = input.view(-1, input.shape[-1])
    output_shape = [*input.shape[:-1], weight.shape[0]]

    q_input, x_scale = per_token_group_quant_fp8(
        input_2d, block_size[1], column_major_scales=True
    )
    output = fp8_blockwise_scaled_mm(
        q_input, weight.T, x_scale, weight_scale.T, out_dtype=input_2d.dtype
    )
    if bias is not None:
        output += bias
    return output.to(dtype=input_2d.dtype).view(*output_shape)


def deepgemm_w8a8_block_fp8_linear_with_fallback(
    input: torch.Tensor,
    weight: torch.Tensor,
    block_size: List[int],
    weight_scale: torch.Tensor,
    input_scale: Optional[torch.Tensor] = None,
    bias: Optional[torch.Tensor] = None,
) -> torch.Tensor:
    assert input_scale is None

    output_dtype = input.dtype
    dtype_supported = output_dtype == torch.bfloat16

232
233
    # TODO: https://github.com/sgl-project/sglang/pull/6890#issuecomment-2943395737
    shape_supported = weight.shape[0] % 64 == 0 and weight.shape[1] % 128 == 0
234
235
236
237
238

    if not (shape_supported and dtype_supported):
        # fall back to triton
        return triton_w8a8_block_fp8_linear(
            input, weight, block_size, weight_scale, input_scale, bias
239
        )
HandH1998's avatar
HandH1998 committed
240

241
242
243
244
245
246
247
248
    input_2d = input.view(-1, input.shape[-1])
    output_shape = [*input.shape[:-1], weight.shape[0]]

    q_input, x_scale = sglang_per_token_group_quant_fp8(
        input_2d,
        block_size[1],
        column_major_scales=True,
        scale_tma_aligned=True,
fzyzcjy's avatar
fzyzcjy committed
249
        scale_ue8m0=deep_gemm_wrapper.DEEPGEMM_SCALE_UE8M0,
250
    )
251

252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
    output = w8a8_block_fp8_matmul_deepgemm(
        q_input, weight, x_scale, weight_scale, block_size, output_dtype=output_dtype
    )
    if bias is not None:
        output += bias
    return output.to(dtype=output_dtype).view(*output_shape)


def aiter_w8a8_block_fp8_linear(
    input: torch.Tensor,
    weight: torch.Tensor,
    block_size: List[int],
    weight_scale: torch.Tensor,
    input_scale: Optional[torch.Tensor] = None,
    bias: Optional[torch.Tensor] = None,
) -> torch.Tensor:
    assert input_scale is None
    input_2d = input.view(-1, input.shape[-1])
    output_shape = [*input.shape[:-1], weight.shape[0]]

272
    q_input, x_scale = aiter_per1x128_quant(input_2d, quant_dtype=aiter.dtypes.fp8)
273
    output = gemm_a8w8_blockscale(
274
        q_input, weight, x_scale, weight_scale, dtype=input.dtype
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
    )

    if bias is not None:
        output += bias

    return output.to(dtype=input_2d.dtype).view(*output_shape)


def triton_w8a8_block_fp8_linear(
    input: torch.Tensor,
    weight: torch.Tensor,
    block_size: List[int],
    weight_scale: torch.Tensor,
    input_scale: Optional[torch.Tensor] = None,
    bias: Optional[torch.Tensor] = None,
) -> torch.Tensor:
    assert input_scale is None
    input_2d = input.view(-1, input.shape[-1])
    output_shape = [*input.shape[:-1], weight.shape[0]]

    q_input, x_scale = per_token_group_quant_fp8(
        input_2d, block_size[1], column_major_scales=False
    )
    output = w8a8_block_fp8_matmul_triton(
        q_input, weight, x_scale, weight_scale, block_size, output_dtype=input_2d.dtype
    )
HandH1998's avatar
HandH1998 committed
301
    if bias is not None:
302
303
        output += bias
    return output.to(dtype=input_2d.dtype).view(*output_shape)
HandH1998's avatar
HandH1998 committed
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
def dequant_mxfp4(
    w_block: torch.Tensor,
    w_scale: torch.Tensor,
    out_dtype,
) -> torch.Tensor:
    """
    :param w_block: (batch, n, k, 16), uint8, pack two mxfp4 into one byte
    :param w_scale: (batch, n, k), uint8
    :return: (batch, n, k * 32), float32
    """

    assert w_block.dtype == torch.uint8
    assert w_scale.dtype == torch.uint8

    batch, n, k, pack_dim = w_block.shape
    batch_, n_, k_ = w_scale.shape
    assert pack_dim == 16
    assert batch == batch_
    assert n == n_
    assert k == k_

    out_raw = MXFP4QuantizeUtil.dequantize(
        quantized_data=w_block, scale=w_scale, dtype=out_dtype, block_sizes=[32]
    )
    return out_raw.reshape(batch, n, k * 32)


HandH1998's avatar
HandH1998 committed
333
def input_to_float8(
334
    x: torch.Tensor, dtype: torch.dtype = fp8_dtype
HandH1998's avatar
HandH1998 committed
335
336
337
) -> Tuple[torch.Tensor, torch.Tensor]:
    """This function quantizes input values to float8 values with tensor-wise quantization."""
    min_val, max_val = x.aminmax()
338
    amax = torch.maximum(min_val.abs(), max_val.abs()).float().clamp(min=1e-12)
339
340
341
342
343
344
345
346
347
348

    if _is_fp8_fnuz:
        dtype = fp8_dtype
        fp_max = fp8_max
    else:
        finfo = torch.finfo(dtype)
        fp_max = finfo.max

    scale = fp_max / amax
    x_scl_sat = (x.float() * scale).clamp(min=-fp_max, max=fp_max)
HandH1998's avatar
HandH1998 committed
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
    return x_scl_sat.to(dtype).contiguous(), scale.float().reciprocal()


def block_quant_to_tensor_quant(
    x_q_block: torch.Tensor,
    x_s: torch.Tensor,
    block_size: List[int],
) -> Tuple[torch.Tensor, torch.Tensor]:
    """This function converts block-wise quantization to tensor-wise quantization.
    The inputs are block-wise quantization tensor `x_q_block`, block-wise quantization scale
    and the block size.
    The outputs are tensor-wise quantization tensor and tensor-wise quantization scale.
    Note only float8 is supported for now.
    """
    block_n, block_k = block_size[0], block_size[1]
    n, k = x_q_block.shape
    n_tiles = (n + block_n - 1) // block_n
    k_tiles = (k + block_k - 1) // block_k
    assert n_tiles == x_s.shape[0]
    assert k_tiles == x_s.shape[1]

    x_dq_block = x_q_block.to(torch.float32)

    x_dq_block_tiles = [
        [
            x_dq_block[
                j * block_n : min((j + 1) * block_n, n),
                i * block_k : min((i + 1) * block_k, k),
            ]
            for i in range(k_tiles)
        ]
        for j in range(n_tiles)
    ]

    for i in range(k_tiles):
        for j in range(n_tiles):
            x_dq_block_tiles[j][i][:, :] = x_dq_block_tiles[j][i] * x_s[j][i]

387
    x_q_tensor, scale = (
Lianmin Zheng's avatar
Lianmin Zheng committed
388
        scaled_fp8_quant(x_dq_block)
389
390
391
        if _is_cuda
        else input_to_float8(x_dq_block, dtype=x_q_block.dtype)
    )
HandH1998's avatar
HandH1998 committed
392
393
394
    return x_q_tensor, scale


395
396
397
398
399
400
401
402
403
404
405
406
def block_quant_dequant(
    x_q_block: torch.Tensor,
    x_s: torch.Tensor,
    block_size: List[int],
    dtype: torch.dtype,
) -> torch.Tensor:
    """This function converts block-wise quantization to unquantized.
    The inputs are block-wise quantization tensor `x_q_block`, block-wise quantization scale
    and the block size.
    The output is an unquantized tensor with dtype.
    """
    block_n, block_k = block_size[0], block_size[1]
407
    *_, n, k = x_q_block.shape
408

409
410
411
412
413
    # ... n_scale k_scale -> ... (n_scale block_n) (k_scale block_k)
    x_scale_repeat = x_s.repeat_interleave(block_n, dim=-2).repeat_interleave(
        block_k, dim=-1
    )
    x_scale_repeat = x_scale_repeat[..., :n, :k]
414

415
    return (x_q_block.to(torch.float32) * x_scale_repeat).to(dtype)
416
417


418
419
420
def requant_weight_ue8m0_inplace(weight, weight_scale_inv, weight_block_size):
    assert isinstance(weight, torch.nn.Parameter)
    assert isinstance(weight_scale_inv, torch.nn.Parameter)
fzyzcjy's avatar
fzyzcjy committed
421
422
423

    new_weight, new_weight_scale_inv = _requant_weight_ue8m0(
        weight.to(weight_scale_inv.device), weight_scale_inv, weight_block_size
424
425
    )

fzyzcjy's avatar
fzyzcjy committed
426
427
428
    offloader.update_param(weight, new_weight)
    weight_scale_inv.data = new_weight_scale_inv

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

def _requant_weight_ue8m0(
    weight: torch.Tensor,
    weight_scale_inv: torch.Tensor,
    weight_block_size: List[int],
):
    assert weight_block_size == [128, 128]

    *_, n, k = weight.shape

    weight_dequant = block_quant_dequant(
        weight,
        weight_scale_inv,
        weight_block_size,
        torch.bfloat16,
    )

    weight_dequant_flat = weight_dequant.view((-1, k))
    out_w_flat, out_s_flat = per_block_cast_to_fp8(weight_dequant_flat)

    out_w = out_w_flat.view(weight.shape)
    out_s = out_s_flat.view(weight_scale_inv.shape)

    # NOTE copy and modified from DeepGEMM
    def _transform_scale(sf, mn: int):
        import deep_gemm.utils.layout

        sf = sf.index_select(-2, torch.arange(mn, device=sf.device) // 128)
457
        sf = deep_gemm.utils.layout.get_mn_major_tma_aligned_packed_ue8m0_tensor(sf)
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
        return sf

    out_s = _transform_scale(out_s, mn=out_w.shape[-2])

    return out_w, out_s


# COPIED FROM DeepGEMM
def per_block_cast_to_fp8(x: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
    assert x.dim() == 2
    m, n = x.shape
    x_padded = torch.zeros(
        (align(m, 128), align(n, 128)), dtype=x.dtype, device=x.device
    )
    x_padded[:m, :n] = x
    x_view = x_padded.view(-1, 128, x_padded.size(1) // 128, 128)
    x_amax = x_view.abs().float().amax(dim=(1, 3), keepdim=True).clamp(1e-4)
    sf = ceil_to_ue8m0(x_amax / 448.0)
    x_scaled = (x_view * (1.0 / sf)).to(torch.float8_e4m3fn)
    return x_scaled.view_as(x_padded)[:m, :n].contiguous(), sf.view(
        x_view.size(0), x_view.size(2)
    )


482
483
484
485
486
# COPIED FROM DeepGEMM
def ceil_to_ue8m0(x: torch.Tensor):
    return torch.pow(2.0, torch.ceil(torch.log2(x.abs())))


487
488
489
490
491
def channel_quant_to_tensor_quant(
    x_q_channel: torch.Tensor,
    x_s: torch.Tensor,
) -> Tuple[torch.Tensor, torch.Tensor]:
    x_dq_channel = x_q_channel.to(torch.float32) * x_s
492
    x_q_tensor, scale = (
Lianmin Zheng's avatar
Lianmin Zheng committed
493
        scaled_fp8_quant(x_dq_channel)
494
495
496
        if _is_cuda
        else input_to_float8(x_dq_channel, dtype=x_q_channel.dtype)
    )
497
498
499
    return x_q_tensor, scale


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
def _process_scaled_mm_output(output, input_2d_shape, output_shape):
    if type(output) is tuple and len(output) == 2:
        output = output[0]
    return torch.narrow(output, 0, 0, input_2d_shape[0]).view(*output_shape)


def _apply_fallback_scaled_mm(
    qinput,
    weight,
    x_scale,
    weight_scale,
    input_2d_shape,
    output_shape,
    bias,
    input_dtype,
):
    global TORCH_DEVICE_IDENTITY
    if TORCH_DEVICE_IDENTITY is None:
        TORCH_DEVICE_IDENTITY = torch.ones(1, dtype=torch.float32, device=weight.device)

    output = torch._scaled_mm(
        qinput,
        weight,
        scale_a=TORCH_DEVICE_IDENTITY,
        scale_b=TORCH_DEVICE_IDENTITY,
        out_dtype=torch.float32,
    )

    output = _process_scaled_mm_output(output, input_2d_shape, output_shape)
    x_scale = torch.narrow(x_scale, 0, 0, input_2d_shape[0])

    output = output * x_scale * weight_scale.t()
    if bias is not None:
        output = output + bias
    return output.to(dtype=input_dtype)


HandH1998's avatar
HandH1998 committed
537
538
539
540
541
542
543
def apply_fp8_linear(
    input: torch.Tensor,
    weight: torch.Tensor,
    weight_scale: torch.Tensor,
    input_scale: Optional[torch.Tensor] = None,
    input_scale_ub: Optional[torch.Tensor] = None,
    bias: Optional[torch.Tensor] = None,
544
    cutlass_fp8_supported: bool = cutlass_fp8_supported(),
HandH1998's avatar
HandH1998 committed
545
    use_per_token_if_dynamic: bool = False,
546
547
    pad_output: Optional[bool] = None,
    compressed_tensor_quant: bool = False,
HandH1998's avatar
HandH1998 committed
548
) -> torch.Tensor:
549
550
551
552
553
554
    # Note: we pad the input because torch._scaled_mm is more performant
    # for matrices with batch dimension > 16.
    # This could change in the future.
    # We also don't pad when using torch.compile,
    # as it breaks with dynamic shapes.
    if pad_output is None:
555
556
557
558
        pad_output = (
            not get_bool_env_var("SGLANG_ENABLE_TORCH_COMPILE")
            and not cutlass_fp8_supported
        )
559
560
    output_padding = 17 if pad_output else None

HandH1998's avatar
HandH1998 committed
561
562
563
564
    # View input as 2D matrix for fp8 methods
    input_2d = input.view(-1, input.shape[-1])
    output_shape = [*input.shape[:-1], weight.shape[1]]

565
    if compressed_tensor_quant:
566
567
        # cutlass_scaled_mm supports per tensor/channel W and per tensor/token A
        # for sgl-kernel fp8_scaled_mm, it support per channel W now
568
569
570
571
572
573
        if cutlass_fp8_supported and weight_scale.numel() == weight.shape[1]:
            qinput, x_scale = scaled_fp8_quant(
                input_2d,
                input_scale,
                use_per_token_if_dynamic=use_per_token_if_dynamic,
            )
574
575
576

            # Fused GEMM_DQ
            if VLLM_AVAILABLE and use_vllm_cutlass_w8a8_fp8_kernel:
577
                # Fall back to vllm cutlass w8a8 fp8 kernel
578
                output = ops.cutlass_scaled_mm(
579
580
581
582
583
584
585
586
587
588
589
                    qinput,
                    weight,
                    out_dtype=input.dtype,
                    scale_a=x_scale,
                    scale_b=weight_scale,
                    bias=bias,
                )
            else:
                assert (
                    weight_scale.numel() == weight.shape[1]
                ), "cutlass w8a8 fp8 sgl-kernel only supports per-channel scale"
590
591
592

                cutlass_compatible_b = (
                    weight.shape[0] % 16 == 0 and weight.shape[1] % 16 == 0
593
                )
594
                if not cutlass_compatible_b or use_triton_w8a8_fp8_kernel:
595
596
597
598
599
600
601
602
603
604
605
606
607
608
                    # Massage the input to be 2D
                    qinput = qinput.view(-1, qinput.shape[-1])
                    output = triton_scaled_mm(
                        qinput, weight, x_scale, weight_scale, input.dtype, bias
                    )
                else:
                    output = fp8_scaled_mm(
                        qinput,
                        weight,
                        x_scale,
                        weight_scale,
                        out_dtype=input.dtype,
                        bias=bias,
                    )
609
610
611
612
613
614
            return output.view(*output_shape)

        # torch.scaled_mm supports per tensor weights + activations only
        # so fallback to naive if per channel or per token
        else:
            # Maybe apply padding to output, see comment in __init__
615
616
            qinput, x_scale = (
                scaled_fp8_quant(
617
618
                    input_2d,
                    input_scale,
619
                    num_token_padding=output_padding,
620
621
                    use_per_token_if_dynamic=use_per_token_if_dynamic,
                )
622
623
                if _is_cuda
                else ops.scaled_fp8_quant(
624
625
                    input_2d,
                    input_scale,
626
                    num_token_padding=output_padding,
627
628
                    use_per_token_if_dynamic=use_per_token_if_dynamic,
                )
629
            )
630
631
632
633
634
635
636
637
638
639
640
641
642
643

            per_tensor_weights = weight_scale.numel() == 1
            per_tensor_activations = x_scale.numel() == 1

            if per_tensor_weights and per_tensor_activations:
                # Fused GEMM_DQ
                output = torch._scaled_mm(
                    qinput,
                    weight,
                    out_dtype=input.dtype,
                    scale_a=x_scale,
                    scale_b=weight_scale,
                    bias=bias,
                )
644
                return _process_scaled_mm_output(output, input_2d.shape, output_shape)
645
646
647
648
649

            elif (
                use_per_token_if_dynamic
                and not per_tensor_weights
                and not per_tensor_activations
650
                and (USE_ROWWISE_TORCH_SCALED_MM or _use_aiter)
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
                # into this sector means use dynamic per-token-per-channel quant
                # per-token scale quant for input matrix, every row(one token) have one scale factor
                # per-channel scale quant for weight matrix, every col(one channel) have one scale factor
                if _use_aiter:
                    # gemm_a8w8_bpreshuffle(XQ, WQ, x_scale, w_scale, dtype)
                    # XQ -> input tensor, shape = (m, k)
                    # WQ -> weight tensor, shape = (n, k), with preshuffe get better perf
                    # x_scale -> input scale tensor, shape = (m, 1)
                    # w_scale -> weight scale tensor, shape = (n ,1)
                    # dtype -> output dtype
                    output = gemm_a8w8_bpreshuffle(
                        XQ=qinput,
                        WQ=weight,
                        x_scale=x_scale,
                        w_scale=weight_scale,
                        dtype=input.dtype,
                    )
                    if bias is not None:
                        output += bias
                    return _process_scaled_mm_output(
                        output, input_2d.shape, [*input.shape[:-1], weight.shape[0]]
                    )
                else:
                    # For now validated on ROCm platform
                    # fp8 rowwise scaling in torch._scaled_mm is introduced in
                    # https://github.com/pytorch/pytorch/pull/144432 using hipBLASLt
                    # and ROCm 6.3, which only exists in torch 2.7 and above.
                    # For CUDA platform please validate if the
                    # torch._scaled_mm support rowwise scaled GEMM
                    # Fused GEMM_DQ Rowwise GEMM
                    output = torch._scaled_mm(
                        qinput,
                        weight,
                        out_dtype=input.dtype,
                        scale_a=x_scale,
                        scale_b=weight_scale.t(),
                        bias=bias,
                    )
                    return _process_scaled_mm_output(
                        output, input_2d.shape, output_shape
                    )
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
            else:
                # Fallback for channelwise case, where we use unfused DQ
                # due to limitations with scaled_mm

                # Symmetric quantized GEMM by definition computes the following:
                #   C = (s_x * X) (s_w * W) + bias
                # This is equivalent to dequantizing the weights and activations
                # before applying a GEMM.
                #
                # In order to compute quantized operands, a quantized kernel
                # will rewrite the above like so:
                #   C = s_w * s_x * (X * W) + bias
                #
                # For the scaled_mm fallback case, we break this down, since it
                # does not support s_w being a vector.
708
                return _apply_fallback_scaled_mm(
709
710
                    qinput,
                    weight,
711
712
713
714
715
716
                    x_scale,
                    weight_scale,
                    input_2d.shape,
                    output_shape,
                    bias,
                    input.dtype,
717
                )
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
    else:
        # cutlass w8a8 fp8 sgl-kernel only supports per-token scale
        if input_scale is not None:
            assert input_scale.numel() == 1
            # broadcast per-tensor scale to per-token scale when supporting cutlass
            qinput, x_scale = static_quant_fp8(
                input_2d, input_scale, repeat_scale=cutlass_fp8_supported
            )
        else:
            # default use per-token quantization if dynamic
            if _is_cuda:
                qinput, x_scale = sglang_per_token_quant_fp8(input_2d)
            else:
                # TODO(kkhuang): temporarily enforce per-tensor activation scaling if weight is per-tensor scaling
                # final solution should be: 1. add support to per-tensor activation scaling.
                # 2. solve the torch.compile error from weight_scale.numel() == 1 and x_scale.numel() > 1 (below line#308)
                if _is_hip and weight_scale.numel() == 1:
735
                    qinput, x_scale = scaled_fp8_quant(
736
737
738
739
740
741
742
743
744
745
746
747
                        input_2d,
                        input_scale,
                        use_per_token_if_dynamic=use_per_token_if_dynamic,
                    )
                else:
                    qinput, x_scale = per_token_group_quant_fp8(
                        input_2d, group_size=input_2d.shape[1]
                    )

        if cutlass_fp8_supported:
            try:
                if VLLM_AVAILABLE and use_vllm_cutlass_w8a8_fp8_kernel:
748
                    # Fall back to vllm cutlass w8a8 fp8 kernel
749
750
751
752
753
754
755
756
757
758
759
760
                    output = ops.cutlass_scaled_mm(
                        qinput,
                        weight,
                        out_dtype=input.dtype,
                        scale_a=x_scale,
                        scale_b=weight_scale,
                        bias=bias,
                    )
                else:
                    assert (
                        weight_scale.numel() == weight.shape[1]
                    ), "cutlass w8a8 fp8 sgl-kernel only supports per-channel scale"
761
762
763

                    cutlass_compatible_b = (
                        weight.shape[0] % 16 == 0 and weight.shape[1] % 16 == 0
764
                    )
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
                    if not cutlass_compatible_b or use_triton_w8a8_fp8_kernel:
                        # Massage the input to be 2D
                        qinput = qinput.view(-1, qinput.shape[-1])
                        output = triton_scaled_mm(
                            qinput, weight, x_scale, weight_scale, input.dtype, bias
                        )
                    else:
                        output = fp8_scaled_mm(
                            qinput,
                            weight,
                            x_scale,
                            weight_scale,
                            out_dtype=input.dtype,
                            bias=bias,
                        )
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
                return output.view(*output_shape)
            except (ImportError, NameError, AttributeError):
                pass

        # torch.scaled_mm supports per tensor weights + activations only
        # so fallback to naive if per channel or per token
        per_tensor_weights = weight_scale.numel() == 1
        per_tensor_activations = x_scale.numel() == 1

        if per_tensor_weights and per_tensor_activations:
            # Fused GEMM_DQ
            output = torch._scaled_mm(
                qinput,
                weight,
                out_dtype=input.dtype,
                scale_a=x_scale,
                scale_b=weight_scale,
                bias=bias,
            )
            return _process_scaled_mm_output(output, input_2d.shape, output_shape)

        else:
            # Fallback for channelwise case, where we use unfused DQ
            # due to limitations with scaled_mm

            # Symmetric quantized GEMM by definition computes the following:
            #   C = (s_x * X) (s_w * W) + bias
            # This is equivalent to dequantizing the weights and activations
            # before applying a GEMM.
            #
            # In order to compute quantized operands, a quantized kernel
            # will rewrite the above like so:
            #   C = s_w * s_x * (X * W) + bias
            #
            # For the scaled_mm fallback case, we break this down, since it
            # does not support s_w being a vector.
            return _apply_fallback_scaled_mm(
                qinput,
                weight,
                x_scale,
                weight_scale,
                input_2d.shape,
                output_shape,
                bias,
                input.dtype,
            )
826
827
828
829
830
831
832
833
834


def can_auto_enable_marlin_fp8() -> bool:
    try:
        major, minor = get_device_capability()
        sm = major * 10 + minor
        return 80 <= sm < 89
    except Exception:
        return False