sglang 0.1.20__py3-none-any.whl → 0.1.22__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. sglang/__init__.py +8 -8
  2. sglang/api.py +1 -1
  3. sglang/backend/runtime_endpoint.py +14 -4
  4. sglang/backend/vertexai.py +5 -4
  5. sglang/bench.py +627 -0
  6. sglang/bench_latency.py +22 -20
  7. sglang/bench_serving.py +758 -0
  8. sglang/check_env.py +171 -0
  9. sglang/global_config.py +3 -1
  10. sglang/lang/backend/__init__.py +0 -0
  11. sglang/lang/backend/anthropic.py +77 -0
  12. sglang/lang/backend/base_backend.py +80 -0
  13. sglang/lang/backend/litellm.py +90 -0
  14. sglang/lang/backend/openai.py +438 -0
  15. sglang/lang/backend/runtime_endpoint.py +283 -0
  16. sglang/lang/backend/vertexai.py +149 -0
  17. sglang/lang/chat_template.py +2 -2
  18. sglang/lang/ir.py +3 -3
  19. sglang/lang/tracer.py +1 -1
  20. sglang/launch_server.py +1 -1
  21. sglang/launch_server_llavavid.py +1 -4
  22. sglang/srt/conversation.py +1 -1
  23. sglang/srt/layers/context_flashattention_nopad.py +0 -29
  24. sglang/srt/layers/extend_attention.py +0 -39
  25. sglang/srt/layers/linear.py +869 -0
  26. sglang/srt/layers/quantization/__init__.py +49 -0
  27. sglang/srt/layers/quantization/fp8.py +662 -0
  28. sglang/srt/layers/radix_attention.py +31 -5
  29. sglang/srt/layers/token_attention.py +1 -51
  30. sglang/srt/managers/controller/cuda_graph_runner.py +44 -18
  31. sglang/srt/managers/controller/infer_batch.py +76 -72
  32. sglang/srt/managers/controller/manager_multi.py +109 -98
  33. sglang/srt/managers/controller/manager_single.py +105 -50
  34. sglang/srt/managers/controller/model_runner.py +42 -18
  35. sglang/srt/managers/controller/radix_cache.py +4 -3
  36. sglang/srt/managers/controller/schedule_heuristic.py +4 -0
  37. sglang/srt/managers/controller/tp_worker.py +143 -156
  38. sglang/srt/managers/detokenizer_manager.py +49 -5
  39. sglang/srt/managers/io_struct.py +36 -17
  40. sglang/srt/managers/tokenizer_manager.py +228 -125
  41. sglang/srt/memory_pool.py +46 -58
  42. sglang/srt/model_loader/model_loader.py +277 -0
  43. sglang/srt/model_loader/utils.py +260 -0
  44. sglang/srt/models/chatglm.py +1 -0
  45. sglang/srt/models/dbrx.py +1 -0
  46. sglang/srt/models/grok.py +1 -0
  47. sglang/srt/models/internlm2.py +317 -0
  48. sglang/srt/models/llama2.py +65 -16
  49. sglang/srt/models/llama_classification.py +1 -0
  50. sglang/srt/models/llava.py +1 -0
  51. sglang/srt/models/llavavid.py +1 -0
  52. sglang/srt/models/minicpm.py +2 -8
  53. sglang/srt/models/mixtral.py +1 -0
  54. sglang/srt/models/mixtral_quant.py +1 -0
  55. sglang/srt/models/qwen.py +1 -0
  56. sglang/srt/models/qwen2.py +6 -0
  57. sglang/srt/models/qwen2_moe.py +130 -108
  58. sglang/srt/models/stablelm.py +1 -0
  59. sglang/srt/openai_api/adapter.py +432 -0
  60. sglang/srt/openai_api/api_adapter.py +432 -0
  61. sglang/srt/openai_api/openai_api_adapter.py +431 -0
  62. sglang/srt/openai_api/openai_protocol.py +207 -0
  63. sglang/srt/openai_api/protocol.py +208 -0
  64. sglang/srt/openai_protocol.py +17 -0
  65. sglang/srt/sampling_params.py +2 -0
  66. sglang/srt/server.py +114 -90
  67. sglang/srt/server_args.py +27 -17
  68. sglang/srt/utils.py +17 -118
  69. sglang/test/test_conversation.py +1 -1
  70. sglang/test/test_openai_protocol.py +1 -1
  71. sglang/test/test_programs.py +1 -1
  72. sglang/test/test_utils.py +2 -2
  73. {sglang-0.1.20.dist-info → sglang-0.1.22.dist-info}/METADATA +157 -159
  74. sglang-0.1.22.dist-info/RECORD +103 -0
  75. {sglang-0.1.20.dist-info → sglang-0.1.22.dist-info}/WHEEL +1 -1
  76. sglang-0.1.20.dist-info/RECORD +0 -82
  77. {sglang-0.1.20.dist-info → sglang-0.1.22.dist-info}/LICENSE +0 -0
  78. {sglang-0.1.20.dist-info → sglang-0.1.22.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,662 @@
1
+ # adapted from https://github.com/vllm-project/vllm/blob/e76466dde2bc9525d55165ceaa600d298c7bf773/vllm/model_executor/layers/quantization/fp8.py
2
+ # FIXME refactor in progress
3
+ from typing import Any, Dict, List, Optional, Union
4
+
5
+ import torch
6
+ from torch.nn import Module
7
+ from torch.nn.parameter import Parameter
8
+ from vllm import _custom_ops as ops
9
+ from vllm.logger import init_logger
10
+ from vllm.model_executor.layers.fused_moe import FusedMoE, FusedMoEMethodBase, fused_moe
11
+ from vllm.model_executor.layers.quantization.base_config import (
12
+ QuantizationConfig,
13
+ QuantizeMethodBase,
14
+ )
15
+ from vllm.model_executor.layers.quantization.gptq_marlin import (
16
+ GPTQ_MARLIN_MAX_PARALLEL,
17
+ GPTQ_MARLIN_MIN_THREAD_N,
18
+ GPTQMarlinState,
19
+ marlin_permute_scales,
20
+ )
21
+ from vllm.model_executor.layers.quantization.utils.marlin_utils import pack_fp8_to_int32
22
+ from vllm.model_executor.utils import set_weight_attrs
23
+ from vllm.platforms import current_platform
24
+ from vllm.utils import print_warning_once
25
+
26
+ from sglang.srt.layers.linear import LinearBase, LinearMethodBase
27
+
28
+ ACTIVATION_SCHEMES = ["static", "dynamic"]
29
+
30
+ logger = init_logger(__name__)
31
+
32
+
33
+ def cutlass_fp8_supported() -> bool:
34
+ capability = current_platform.get_device_capability()
35
+ capability = capability[0] * 10 + capability[1]
36
+
37
+ return ops.cutlass_scaled_mm_supports_fp8(capability)
38
+
39
+
40
+ class Fp8Config(QuantizationConfig):
41
+ """Config class for FP8."""
42
+
43
+ def __init__(
44
+ self,
45
+ is_checkpoint_fp8_serialized: bool = False,
46
+ activation_scheme: str = "dynamic",
47
+ ) -> None:
48
+ self.is_checkpoint_fp8_serialized = is_checkpoint_fp8_serialized
49
+ if is_checkpoint_fp8_serialized:
50
+ logger.warning(
51
+ "Detected fp8 checkpoint. Please note that the "
52
+ "format is experimental and subject to change."
53
+ )
54
+ if activation_scheme not in ACTIVATION_SCHEMES:
55
+ raise ValueError(f"Unsupported activation scheme {activation_scheme}")
56
+ self.activation_scheme = activation_scheme
57
+
58
+ @classmethod
59
+ def get_name(cls) -> str:
60
+ return "fp8"
61
+
62
+ @classmethod
63
+ def get_supported_act_dtypes(cls) -> List[torch.dtype]:
64
+ return [torch.bfloat16, torch.half]
65
+
66
+ @classmethod
67
+ def get_min_capability(cls) -> int:
68
+ return 80
69
+
70
+ @classmethod
71
+ def get_config_filenames(cls) -> List[str]:
72
+ return []
73
+
74
+ @classmethod
75
+ def from_config(cls, config: Dict[str, Any]) -> "Fp8Config":
76
+ quant_method = cls.get_from_keys(config, ["quant_method"])
77
+ is_checkpoint_fp8_serialized = "fp8" in quant_method
78
+ activation_scheme = cls.get_from_keys(config, ["activation_scheme"])
79
+ return cls(
80
+ is_checkpoint_fp8_serialized=is_checkpoint_fp8_serialized,
81
+ activation_scheme=activation_scheme,
82
+ )
83
+
84
+ def get_quant_method(
85
+ self, layer: torch.nn.Module
86
+ ) -> Optional["QuantizeMethodBase"]:
87
+
88
+ if isinstance(layer, LinearBase):
89
+ return Fp8LinearMethod(self)
90
+ elif isinstance(layer, FusedMoE):
91
+ return Fp8MoEMethod(self)
92
+ return None
93
+
94
+ def get_scaled_act_names(self) -> List[str]:
95
+ return []
96
+
97
+
98
+ class Fp8LinearMethod(LinearMethodBase):
99
+ """Linear method for FP8.
100
+ Supports loading FP8 checkpoints with static weight scale and
101
+ dynamic/static activation scale.
102
+
103
+ Also supports loading quantized FP16/BF16 model checkpoints with dynamic
104
+ activation scaling. The weight scaling factor will be initialized after
105
+ the model weights are loaded.
106
+
107
+ Limitations:
108
+ 1. Only support per-tensor quantization due to torch._scaled_mm support.
109
+ 2. Only support float8_e4m3fn data type due to the limitation of
110
+ torch._scaled_mm (https://github.com/pytorch/pytorch/blob/2e48b39603411a41c5025efbe52f89560b827825/aten/src/ATen/native/cuda/Blas.cpp#L854-L856)
111
+
112
+ Args:
113
+ quant_config: The quantization config.
114
+ """
115
+
116
+ def __init__(self, quant_config: Fp8Config):
117
+ self.quant_config = quant_config
118
+ self.cutlass_fp8_supported = cutlass_fp8_supported()
119
+
120
+ # For GPUs that lack FP8 hardware support, we can leverage the Marlin
121
+ # kernel for fast weight-only FP8 quantization
122
+ capability = current_platform.get_device_capability()
123
+ capability = capability[0] * 10 + capability[1]
124
+ self.use_marlin = capability < 89
125
+
126
+ def _create_scale_param(
127
+ self,
128
+ scale_name: str,
129
+ layer: torch.nn.Module,
130
+ output_partition_sizes: List[int],
131
+ **extra_weight_attrs,
132
+ ) -> None:
133
+ scale = Parameter(
134
+ torch.empty(len(output_partition_sizes), dtype=torch.float32),
135
+ requires_grad=False,
136
+ )
137
+ scale[:] = torch.finfo(torch.float8_e4m3fn).min
138
+ layer.register_parameter(scale_name, scale)
139
+ set_weight_attrs(
140
+ scale,
141
+ {
142
+ **extra_weight_attrs,
143
+ "needs_scalar_to_array": True,
144
+ },
145
+ )
146
+
147
+ def create_weights(
148
+ self,
149
+ layer: torch.nn.Module,
150
+ input_size_per_partition: int,
151
+ output_partition_sizes: List[int],
152
+ input_size: int,
153
+ output_size: int,
154
+ params_dtype: torch.dtype,
155
+ **extra_weight_attrs,
156
+ ):
157
+ del input_size, output_size
158
+ output_size_per_partition = sum(output_partition_sizes)
159
+
160
+ layer.process_after_load = True
161
+ layer.logical_widths = output_partition_sizes
162
+
163
+ layer.input_size_per_partition = input_size_per_partition
164
+ layer.output_size_per_partition = output_size_per_partition
165
+ layer.orig_dtype = params_dtype
166
+
167
+ # WEIGHT
168
+ # weight_dtype = (torch.float8_e4m3fn
169
+ # if self.quant_config.is_checkpoint_fp8_serialized else
170
+ # params_dtype)
171
+ weight_dtype = torch.float8_e4m3fn
172
+ weight = Parameter(
173
+ torch.empty(
174
+ output_size_per_partition, input_size_per_partition, dtype=weight_dtype
175
+ ),
176
+ requires_grad=False,
177
+ )
178
+ layer.register_parameter("weight", weight)
179
+ set_weight_attrs(
180
+ weight,
181
+ {
182
+ **extra_weight_attrs,
183
+ "input_dim": 1,
184
+ "output_dim": 0,
185
+ },
186
+ )
187
+
188
+ # If checkpoint is serialized fp8, load them.
189
+ # Otherwise, wait until process_weights_after_loading.
190
+ if self.quant_config.is_checkpoint_fp8_serialized:
191
+ # WEIGHT SCALE
192
+ self._create_scale_param(
193
+ scale_name="weight_scale",
194
+ layer=layer,
195
+ output_partition_sizes=output_partition_sizes,
196
+ **extra_weight_attrs,
197
+ )
198
+
199
+ # INPUT ACTIVATION SCALE
200
+ if self.quant_config.activation_scheme == "static":
201
+ self._create_scale_param(
202
+ scale_name="input_scale",
203
+ layer=layer,
204
+ output_partition_sizes=output_partition_sizes,
205
+ **extra_weight_attrs,
206
+ )
207
+
208
+ # For GPUs without FP8 hardware support, we use Marlin for fast
209
+ # fused dequantization
210
+ if self.use_marlin:
211
+ layer.marlin_state = GPTQMarlinState.REPACK
212
+
213
+ def prepare_layer_for_marlin(self, layer: Module) -> None:
214
+ print_warning_once(
215
+ "Your GPU does not have native support for FP8 computation but "
216
+ "FP8 quantization is being used. Weight-only FP8 compression will "
217
+ "be used leveraging the Marlin kernel. This may degrade "
218
+ "performance for compute-heavy workloads."
219
+ )
220
+
221
+ part_size_n = layer.output_size_per_partition
222
+ part_size_k = layer.input_size_per_partition
223
+
224
+ assert layer.marlin_state == GPTQMarlinState.REPACK
225
+ layer.marlin_state = GPTQMarlinState.READY
226
+
227
+ device = layer.weight.device
228
+
229
+ # WEIGHTS
230
+ # Repack weights to gptq format (packed int32 elements)
231
+ packed_gptq_qweight = pack_fp8_to_int32(layer.weight)
232
+
233
+ # Repack weights to marlin format
234
+ marlin_qweight = ops.gptq_marlin_repack(
235
+ b_q_weight=packed_gptq_qweight,
236
+ perm=torch.empty(0, dtype=torch.int, device=device),
237
+ size_k=part_size_k,
238
+ size_n=part_size_n,
239
+ num_bits=8,
240
+ )
241
+ layer.weight = Parameter(marlin_qweight, requires_grad=False)
242
+
243
+ # WEIGHT SCALES
244
+ # Currently Marlin doesn't support per-tensor scales, so we
245
+ # expand it to channelwise
246
+ scales = (
247
+ layer.weight_scale.repeat(1, part_size_n).to(layer.orig_dtype).to(device)
248
+ )
249
+ # Permute scales
250
+ marlin_scales = marlin_permute_scales(
251
+ s=scales,
252
+ size_k=part_size_k,
253
+ size_n=part_size_n,
254
+ group_size=-1,
255
+ num_bits=8,
256
+ )
257
+ layer.weight_scale = Parameter(marlin_scales, requires_grad=False)
258
+
259
+ # Allocate marlin workspace
260
+ max_workspace_size = (
261
+ part_size_n // GPTQ_MARLIN_MIN_THREAD_N
262
+ ) * GPTQ_MARLIN_MAX_PARALLEL
263
+ workspace = torch.zeros(
264
+ max_workspace_size, dtype=torch.int, device=device, requires_grad=False
265
+ )
266
+
267
+ layer.workspace = workspace
268
+
269
+ def process_weights_after_loading(self, layer: Module) -> None:
270
+ if not hasattr(layer, "process_after_load") or not layer.process_after_load:
271
+ return
272
+
273
+ # If checkpoint is fp/bf16 (not serialized fp8), quantize the weights.
274
+ if not self.quant_config.is_checkpoint_fp8_serialized:
275
+ qweight, weight_scale = ops.scaled_fp8_quant(layer.weight, scale=None)
276
+ layer.weight = Parameter(qweight.t(), requires_grad=False)
277
+ layer.weight_scale = Parameter(weight_scale, requires_grad=False)
278
+ layer.logical_widths = None
279
+ layer.input_scale = None
280
+ if self.use_marlin:
281
+ self.prepare_layer_for_marlin(layer)
282
+ return
283
+
284
+ # If checkpoint is fp8, requantize the separately quantized logical
285
+ # weights into a single fp8 weight with a single weight scale.
286
+ else:
287
+ # WEIGHT_SCALE / WEIGHT
288
+ # Loop over logical weights, requantizing with single scale.
289
+ max_w_scale = layer.weight_scale.max()
290
+
291
+ # QKV / MLP is fused in the on disk checkpoint if any of the
292
+ # weight scales are still set to the default since we initialize
293
+ # N weight scales for N shards but we only load 1 weight scale
294
+ # from disk in this case. As a result, we skip dequant -> requant
295
+ # since we already have quantized QKV together.
296
+ # Sample Model with fused checkpoint:
297
+ # * nm-testing/Phi-3-mini-128k-instruct-FP8
298
+ unfused_module_in_checkpoint = (
299
+ layer.weight_scale[-1] > torch.finfo(torch.float8_e4m3fn).min
300
+ )
301
+
302
+ if unfused_module_in_checkpoint:
303
+ start = 0
304
+ for idx, logical_width in enumerate(layer.logical_widths):
305
+ end = start + logical_width
306
+ weight_dq = per_tensor_dequantize(
307
+ layer.weight[start:end, :], layer.weight_scale[idx]
308
+ )
309
+
310
+ layer.weight[start:end, :] = per_tensor_quantize(
311
+ weight_dq, layer.weight_scale.max()
312
+ )
313
+ start = end
314
+ layer.weight_scale = Parameter(max_w_scale, requires_grad=False)
315
+
316
+ # WEIGHT
317
+ # Transpose weight for passing to torch._scaled_mm
318
+ weight = layer.weight
319
+ layer.weight = Parameter(weight.t(), requires_grad=False)
320
+
321
+ # INPUT ACTIVATION SCALE
322
+ # Dynamic: set to None (required input to ops.scaled_fp8_quant).
323
+ # Static: set to max of the input_scales (since they are equal).
324
+ if self.quant_config.activation_scheme == "dynamic":
325
+ layer.input_scale = None
326
+ elif self.quant_config.activation_scheme == "static":
327
+ layer.input_scale = Parameter(
328
+ layer.input_scale.max(), requires_grad=False
329
+ )
330
+ else:
331
+ raise ValueError(
332
+ f"Unknown scheme {self.quant_config.activation_scheme}"
333
+ )
334
+
335
+ if self.use_marlin:
336
+ self.prepare_layer_for_marlin(layer)
337
+
338
+ def apply(
339
+ self,
340
+ layer: torch.nn.Module,
341
+ x: torch.Tensor,
342
+ bias: Optional[torch.Tensor] = None,
343
+ ) -> torch.Tensor:
344
+
345
+ if self.use_marlin:
346
+ # For GPUs that lack FP8 hardware support, we can leverage the
347
+ # Marlin kernel for fast weight-only FP8 quantization
348
+
349
+ reshaped_x = x.reshape(-1, x.shape[-1])
350
+ out_shape = x.shape[:-1] + (layer.output_size_per_partition,)
351
+
352
+ output = ops.fp8_marlin_gemm(
353
+ a=reshaped_x,
354
+ b_q_weight=layer.weight,
355
+ b_scales=layer.weight_scale,
356
+ workspace=layer.workspace,
357
+ num_bits=8,
358
+ size_m=reshaped_x.shape[0],
359
+ size_n=layer.output_size_per_partition,
360
+ size_k=layer.input_size_per_partition,
361
+ )
362
+
363
+ if bias is not None:
364
+ output.add_(bias) # In-place add
365
+
366
+ return output.reshape(out_shape)
367
+
368
+ else:
369
+
370
+ # ops.scaled_fp8_quant supports both dynamic and static quant.
371
+ # If dynamic, layer.input_scale is None and x_scale computed from x
372
+ # If static, layer.input_scale is scalar and x_scale is input_scale
373
+
374
+ if bias is None and self.cutlass_fp8_supported:
375
+ qinput, x_scale = ops.scaled_fp8_quant(x, layer.input_scale)
376
+
377
+ # Fused GEMM_DQ
378
+ output = ops.cutlass_scaled_mm(
379
+ qinput,
380
+ layer.weight,
381
+ out_dtype=x.dtype,
382
+ scale_a=x_scale,
383
+ scale_b=layer.weight_scale,
384
+ )
385
+
386
+ else:
387
+ qinput, x_scale = ops.scaled_fp8_quant(
388
+ x, layer.input_scale, batch_dim_padding=17
389
+ )
390
+
391
+ # Fused GEMM_DQ -- note we padded the input above because
392
+ # torch._scaled_mm is more performant for matrices with
393
+ # batch dimension > 16. Note that this could change
394
+ # in the future.
395
+ output, _ = torch._scaled_mm(
396
+ qinput,
397
+ layer.weight,
398
+ out_dtype=x.dtype,
399
+ scale_a=x_scale,
400
+ scale_b=layer.weight_scale,
401
+ bias=bias,
402
+ )
403
+
404
+ return torch.narrow(output, 0, 0, x.shape[0])
405
+
406
+
407
+ class Fp8MoEMethod(FusedMoEMethodBase):
408
+ """MoE method for FP8.
409
+ Supports loading FP8 checkpoints with static weight scale and
410
+ dynamic/static activation scale.
411
+
412
+ Also supports loading quantized FP16/BF16 model checkpoints with dynamic
413
+ activation scaling. The weight scaling factor will be initialized after
414
+ the model weights are loaded.
415
+
416
+ Args:
417
+ quant_config: The quantization config.
418
+ """
419
+
420
+ def __init__(self, quant_config: Fp8Config):
421
+ self.quant_config = quant_config
422
+
423
+ def create_weights(
424
+ self,
425
+ layer: Module,
426
+ num_experts: int,
427
+ hidden_size: int,
428
+ intermediate_size: int,
429
+ params_dtype: torch.dtype,
430
+ **extra_weight_attrs,
431
+ ):
432
+
433
+ layer.process_after_load = True
434
+
435
+ if self.quant_config.is_checkpoint_fp8_serialized:
436
+ params_dtype = torch.float8_e4m3fn
437
+
438
+ # WEIGHTS
439
+ w13_weight = torch.nn.Parameter(
440
+ torch.empty(
441
+ num_experts, 2 * intermediate_size, hidden_size, dtype=params_dtype
442
+ ),
443
+ requires_grad=False,
444
+ )
445
+ layer.register_parameter("w13_weight", w13_weight)
446
+ set_weight_attrs(w13_weight, extra_weight_attrs)
447
+
448
+ w2_weight = torch.nn.Parameter(
449
+ torch.empty(
450
+ num_experts, hidden_size, intermediate_size, dtype=params_dtype
451
+ ),
452
+ requires_grad=False,
453
+ )
454
+ layer.register_parameter("w2_weight", w2_weight)
455
+ set_weight_attrs(w2_weight, extra_weight_attrs)
456
+
457
+ # WEIGHT_SCALES
458
+ # Allocate 2 scales for w1 and w3 respectively.
459
+ # They will be combined to a single scale after weight loading.
460
+ w13_scale = torch.nn.Parameter(
461
+ torch.ones(num_experts, 2, dtype=torch.float32), requires_grad=False
462
+ )
463
+ layer.register_parameter("w13_scale", w13_scale)
464
+
465
+ w2_scale = torch.nn.Parameter(
466
+ torch.ones(num_experts, dtype=torch.float32), requires_grad=False
467
+ )
468
+ layer.register_parameter("w2_scale", w2_scale)
469
+
470
+ # If loading fp8 checkpoint, pass the weight loaders.
471
+ # If loading an fp16 checkpoint, do not (we will quantize in
472
+ # process_weights_after_loading()
473
+ if self.quant_config.is_checkpoint_fp8_serialized:
474
+ set_weight_attrs(w13_scale, extra_weight_attrs)
475
+ set_weight_attrs(w2_scale, extra_weight_attrs)
476
+
477
+ # INPUT_SCALES
478
+ if self.quant_config.activation_scheme == "static":
479
+ if not self.quant_config.is_checkpoint_fp8_serialized:
480
+ raise ValueError(
481
+ "Found static activation scheme for checkpoint that "
482
+ "was not serialized fp8."
483
+ )
484
+
485
+ a13_scale = torch.nn.Parameter(
486
+ torch.ones(num_experts, dtype=torch.float32), requires_grad=False
487
+ )
488
+ layer.register_parameter("a13_scale", a13_scale)
489
+ set_weight_attrs(a13_scale, extra_weight_attrs)
490
+
491
+ a2_scale = torch.nn.Parameter(
492
+ torch.ones(num_experts, dtype=torch.float32), requires_grad=False
493
+ )
494
+ layer.register_parameter("a2_scale", a2_scale)
495
+ set_weight_attrs(a2_scale, extra_weight_attrs)
496
+ else:
497
+ layer.a13_scale = None
498
+ layer.a2_scale = None
499
+
500
+ def process_weights_after_loading(self, layer: Module) -> None:
501
+ if not hasattr(layer, "process_after_load") or not layer.process_after_load:
502
+ return
503
+
504
+ # If checkpoint is fp16, quantize in place.
505
+ if not self.quant_config.is_checkpoint_fp8_serialized:
506
+ w13_weight = torch.empty_like(
507
+ layer.w13_weight.data, dtype=torch.float8_e4m3fn
508
+ )
509
+ w2_weight = torch.empty_like(
510
+ layer.w2_weight.data, dtype=torch.float8_e4m3fn
511
+ )
512
+
513
+ # Re-initialize w13_scale because we directly quantize
514
+ # merged w13 weights and generate a single scaling factor.
515
+ layer.w13_scale = torch.nn.Parameter(
516
+ torch.ones(
517
+ layer.num_experts, dtype=torch.float32, device=w13_weight.device
518
+ ),
519
+ requires_grad=False,
520
+ )
521
+ for expert in range(layer.num_experts):
522
+ w13_weight[expert, :, :], layer.w13_scale[expert] = (
523
+ ops.scaled_fp8_quant(layer.w13_weight.data[expert, :, :])
524
+ )
525
+ w2_weight[expert, :, :], layer.w2_scale[expert] = ops.scaled_fp8_quant(
526
+ layer.w2_weight.data[expert, :, :]
527
+ )
528
+ layer.w13_weight = torch.nn.Parameter(w13_weight, requires_grad=False)
529
+ layer.w2_weight = torch.nn.Parameter(w2_weight, requires_grad=False)
530
+ return
531
+
532
+ # If checkpoint is fp8, we need to handle that the
533
+ # MoE kernels require single activation scale and single weight
534
+ # scale for w13 per expert.
535
+ else:
536
+ # Fp8 moe kernels require a single activation scale.
537
+ # We take the max of all the scales in case they differ.
538
+ if self.quant_config.activation_scheme == "static":
539
+ if layer.a13_scale is None or layer.a2_scale is None:
540
+ raise ValueError(
541
+ "QuantConfig has static quantization, but found "
542
+ "activation scales are None."
543
+ )
544
+ if not all_close_1d(layer.a13_scale) or not all_close_1d(
545
+ layer.a2_scale
546
+ ):
547
+ print_warning_once(
548
+ "Found input_scales that are not equal for "
549
+ "fp8 MoE layer. Using the maximum across experts "
550
+ "for each layer. "
551
+ )
552
+ layer.a13_scale = torch.nn.Parameter(
553
+ layer.a13_scale.max(), requires_grad=False
554
+ )
555
+ layer.a2_scale = torch.nn.Parameter(
556
+ layer.a2_scale.max(), requires_grad=False
557
+ )
558
+
559
+ # Fp8 moe kernel needs single weight scale for w13 per expert.
560
+ # We take the max then dequant and requant each expert.
561
+ assert layer.w13_scale is not None
562
+ shard_size = layer.intermediate_size_per_partition
563
+ max_w13_scales = layer.w13_scale.max(dim=1).values
564
+ for expert_id in range(layer.num_experts):
565
+ start = 0
566
+ for shard_id in range(2):
567
+ dq_weight = per_tensor_dequantize(
568
+ layer.w13_weight[expert_id][start : start + shard_size, :],
569
+ layer.w13_scale[expert_id][shard_id],
570
+ )
571
+ layer.w13_weight[expert_id][start : start + shard_size, :] = (
572
+ per_tensor_quantize(dq_weight, max_w13_scales[expert_id])
573
+ )
574
+ start += shard_size
575
+
576
+ layer.w13_scale = torch.nn.Parameter(max_w13_scales, requires_grad=False)
577
+ return
578
+
579
+ def apply(
580
+ self,
581
+ layer: torch.nn.Module,
582
+ x: torch.Tensor,
583
+ router_logits: torch.Tensor,
584
+ top_k: int,
585
+ renormalize: bool = True,
586
+ ) -> torch.Tensor:
587
+
588
+ return fused_moe(
589
+ x,
590
+ layer.w13_weight,
591
+ layer.w2_weight,
592
+ router_logits,
593
+ top_k,
594
+ renormalize=renormalize,
595
+ inplace=True,
596
+ use_fp8=True,
597
+ w1_scale=layer.w13_scale,
598
+ w2_scale=layer.w2_scale,
599
+ a1_scale=layer.a13_scale,
600
+ a2_scale=layer.a2_scale,
601
+ )
602
+
603
+
604
+ # FIXME: not used
605
+ class Fp8KVCacheMethod(QuantizeMethodBase):
606
+ """Supports loading kv-cache scaling factors from FP8 checkpoints."""
607
+
608
+ def __init__(self, quant_config: Fp8Config):
609
+ self.quant_config = quant_config
610
+
611
+ def create_weights(self, layer: torch.nn.Module):
612
+ """Create "weight" (aka kv_scale) for an attention layer.
613
+
614
+ Args:
615
+ layer: The layer that is using the QuantizeMethodBase factory.
616
+ """
617
+ # Initialize the KV cache scale to 1.0 as the default value.
618
+ # If the kv_scale appears in the checkpoint, it will be
619
+ # overwritten when loading weights.
620
+ layer.kv_scale = Parameter(torch.tensor(1.0), requires_grad=False)
621
+
622
+ def apply(self, layer: torch.nn.Module) -> torch.Tensor:
623
+ raise RuntimeError("Fp8KVCacheMethod.apply should not be called.")
624
+
625
+ def process_weights_after_loading(self, layer: Module) -> None:
626
+ # If the kv-cache dtype is auto, we enforce the kv-scale to be 1.0
627
+ # regardless whether the kv-scale is available in the checkpoint.
628
+ if layer.kv_cache_dtype != "auto":
629
+ kv_scale = layer.kv_scale.to("cpu").tolist()
630
+ if not isinstance(kv_scale, float):
631
+ raise ValueError(
632
+ "Only support per-tensor scaling factor " "for fp8 KV cache"
633
+ )
634
+ layer._kv_scale = kv_scale
635
+ if layer._kv_scale == 1.0 and "e5m2" not in layer.kv_cache_dtype:
636
+ print_warning_once(
637
+ "Using KV cache scaling factor 1.0 for fp8_e4m3. This may "
638
+ "cause accuracy issues. Please make sure kv-cache scaling "
639
+ "factor is available in the fp8 checkpoint."
640
+ )
641
+ del layer.kv_scale
642
+
643
+
644
+ def per_tensor_quantize(
645
+ tensor: torch.Tensor, inv_scale: Union[float, torch.Tensor]
646
+ ) -> torch.Tensor:
647
+ finfo = torch.finfo(torch.float8_e4m3fn)
648
+ qweight = (tensor / inv_scale).clamp(min=finfo.min, max=finfo.max)
649
+ return qweight.to(torch.float8_e4m3fn)
650
+
651
+
652
+ def per_tensor_dequantize(
653
+ tensor: torch.Tensor, inv_scale: Union[float, torch.Tensor]
654
+ ) -> torch.Tensor:
655
+ fake_qweight = tensor.to(torch.float16)
656
+ dq_weight = fake_qweight * inv_scale
657
+ return dq_weight
658
+
659
+
660
+ def all_close_1d(x: torch.Tensor) -> bool:
661
+ assert len(x.shape) == 1
662
+ return all(torch.allclose(x[0], x[i]) for i in range(x.shape[0]))