sglang 0.1.16__py3-none-any.whl → 0.1.18__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 (68) hide show
  1. sglang/__init__.py +3 -1
  2. sglang/api.py +7 -7
  3. sglang/backend/anthropic.py +1 -1
  4. sglang/backend/litellm.py +90 -0
  5. sglang/backend/openai.py +158 -11
  6. sglang/backend/runtime_endpoint.py +18 -10
  7. sglang/bench_latency.py +299 -0
  8. sglang/global_config.py +12 -2
  9. sglang/lang/compiler.py +2 -2
  10. sglang/lang/interpreter.py +114 -67
  11. sglang/lang/ir.py +28 -3
  12. sglang/launch_server.py +4 -1
  13. sglang/launch_server_llavavid.py +2 -1
  14. sglang/srt/constrained/__init__.py +13 -6
  15. sglang/srt/constrained/fsm_cache.py +8 -2
  16. sglang/srt/constrained/jump_forward.py +113 -25
  17. sglang/srt/conversation.py +2 -0
  18. sglang/srt/flush_cache.py +3 -1
  19. sglang/srt/hf_transformers_utils.py +130 -1
  20. sglang/srt/layers/extend_attention.py +17 -0
  21. sglang/srt/layers/fused_moe.py +582 -0
  22. sglang/srt/layers/logits_processor.py +65 -32
  23. sglang/srt/layers/radix_attention.py +41 -7
  24. sglang/srt/layers/token_attention.py +16 -1
  25. sglang/srt/managers/controller/dp_worker.py +113 -0
  26. sglang/srt/managers/{router → controller}/infer_batch.py +242 -100
  27. sglang/srt/managers/controller/manager_multi.py +191 -0
  28. sglang/srt/managers/{router/manager.py → controller/manager_single.py} +34 -14
  29. sglang/srt/managers/{router → controller}/model_runner.py +262 -158
  30. sglang/srt/managers/{router → controller}/radix_cache.py +11 -1
  31. sglang/srt/managers/{router/scheduler.py → controller/schedule_heuristic.py} +9 -7
  32. sglang/srt/managers/{router/model_rpc.py → controller/tp_worker.py} +298 -267
  33. sglang/srt/managers/detokenizer_manager.py +42 -46
  34. sglang/srt/managers/io_struct.py +22 -12
  35. sglang/srt/managers/tokenizer_manager.py +151 -87
  36. sglang/srt/model_config.py +83 -5
  37. sglang/srt/models/chatglm.py +399 -0
  38. sglang/srt/models/commandr.py +10 -13
  39. sglang/srt/models/dbrx.py +9 -15
  40. sglang/srt/models/gemma.py +12 -15
  41. sglang/srt/models/grok.py +738 -0
  42. sglang/srt/models/llama2.py +26 -15
  43. sglang/srt/models/llama_classification.py +104 -0
  44. sglang/srt/models/llava.py +86 -19
  45. sglang/srt/models/llavavid.py +11 -20
  46. sglang/srt/models/mixtral.py +282 -103
  47. sglang/srt/models/mixtral_quant.py +372 -0
  48. sglang/srt/models/qwen.py +9 -13
  49. sglang/srt/models/qwen2.py +11 -13
  50. sglang/srt/models/stablelm.py +9 -15
  51. sglang/srt/models/yivl.py +17 -22
  52. sglang/srt/openai_api_adapter.py +150 -95
  53. sglang/srt/openai_protocol.py +11 -2
  54. sglang/srt/server.py +124 -48
  55. sglang/srt/server_args.py +128 -48
  56. sglang/srt/utils.py +234 -67
  57. sglang/test/test_programs.py +65 -3
  58. sglang/test/test_utils.py +32 -1
  59. sglang/utils.py +23 -4
  60. {sglang-0.1.16.dist-info → sglang-0.1.18.dist-info}/METADATA +40 -27
  61. sglang-0.1.18.dist-info/RECORD +78 -0
  62. {sglang-0.1.16.dist-info → sglang-0.1.18.dist-info}/WHEEL +1 -1
  63. sglang/srt/backend_config.py +0 -13
  64. sglang/srt/models/dbrx_config.py +0 -281
  65. sglang/srt/weight_utils.py +0 -417
  66. sglang-0.1.16.dist-info/RECORD +0 -72
  67. {sglang-0.1.16.dist-info → sglang-0.1.18.dist-info}/LICENSE +0 -0
  68. {sglang-0.1.16.dist-info → sglang-0.1.18.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,582 @@
1
+ # Adapted from
2
+ # https://github.com/vllm-project/vllm/blob/c7f2cf2b7f67bce5842fedfdba508440fe257375/vllm/model_executor/layers/fused_moe/fused_moe.py#L1
3
+ """Fused MoE kernel."""
4
+ import functools
5
+ import json
6
+ import os
7
+ from typing import Any, Dict, Optional, Tuple
8
+
9
+ import torch
10
+ import triton
11
+ import triton.language as tl
12
+
13
+ from vllm import _custom_ops as ops
14
+ from vllm.logger import init_logger
15
+
16
+ logger = init_logger(__name__)
17
+
18
+
19
+ @triton.jit
20
+ def fused_moe_kernel(
21
+ # Pointers to matrices
22
+ a_ptr,
23
+ b_ptr,
24
+ c_ptr,
25
+ a_scale_ptr,
26
+ b_scale_ptr,
27
+ topk_weights_ptr,
28
+ sorted_token_ids_ptr,
29
+ expert_ids_ptr,
30
+ num_tokens_post_padded_ptr,
31
+ # Matrix dimensions
32
+ N,
33
+ K,
34
+ EM,
35
+ num_valid_tokens,
36
+ # The stride variables represent how much to increase the ptr by when
37
+ # moving by 1 element in a particular dimension. E.g. `stride_am` is
38
+ # how much to increase `a_ptr` by to get the element one row down
39
+ # (A has M rows).
40
+ stride_am,
41
+ stride_ak,
42
+ stride_be,
43
+ stride_bk,
44
+ stride_bn,
45
+ stride_cm,
46
+ stride_cn,
47
+ # Meta-parameters
48
+ BLOCK_SIZE_M: tl.constexpr,
49
+ BLOCK_SIZE_N: tl.constexpr,
50
+ BLOCK_SIZE_K: tl.constexpr,
51
+ GROUP_SIZE_M: tl.constexpr,
52
+ MUL_ROUTED_WEIGHT: tl.constexpr,
53
+ top_k: tl.constexpr,
54
+ compute_type: tl.constexpr,
55
+ use_fp8: tl.constexpr,
56
+ ):
57
+ """
58
+ Implements the fused computation for a Mixture of Experts (MOE) using
59
+ token and expert matrices.
60
+
61
+ Key Parameters:
62
+ - A: The input tensor representing tokens with shape (*, K), where '*' can
63
+ be any shape representing batches and K is the feature dimension of
64
+ each token.
65
+ - B: The stacked MOE weight tensor with shape (E, N, K), where E is
66
+ the number of experts, K is the input feature dimension, and N is
67
+ the output feature dimension.
68
+ - C: The output cache tensor with shape (M, topk, N), where M is the
69
+ total number of tokens post padding, topk is the number of times
70
+ each token is repeated, and N is the output feature dimension.
71
+ - sorted_token_ids: A tensor containing the sorted indices of tokens,
72
+ repeated topk times and arranged by the expert index they are
73
+ assigned to.
74
+ - expert_ids: A tensor containing the indices of the expert for each
75
+ block. It determines which expert matrix from B should be used for
76
+ each block in A.
77
+ This kernel performs the multiplication of a token by its corresponding
78
+ expert matrix as determined by `expert_ids`. The sorting of
79
+ `sorted_token_ids` by expert index and padding ensures divisibility by
80
+ BLOCK_SIZE_M, which is necessary to maintain consistency in block matrix
81
+ multiplication across different blocks processed by the same expert.
82
+ """
83
+ # -----------------------------------------------------------
84
+ # Map program ids `pid` to the block of C it should compute.
85
+ # This is done in a grouped ordering to promote L2 data reuse.
86
+ pid = tl.program_id(axis=0)
87
+ num_pid_m = tl.cdiv(EM, BLOCK_SIZE_M)
88
+ num_pid_n = tl.cdiv(N, BLOCK_SIZE_N)
89
+ num_pid_in_group = GROUP_SIZE_M * num_pid_n
90
+ group_id = pid // num_pid_in_group
91
+ first_pid_m = group_id * GROUP_SIZE_M
92
+ group_size_m = min(num_pid_m - first_pid_m, GROUP_SIZE_M)
93
+ pid_m = first_pid_m + ((pid % num_pid_in_group) % group_size_m)
94
+ pid_n = (pid % num_pid_in_group) // group_size_m
95
+
96
+ # ----------------------------------------------------------
97
+ # Create pointers for the first blocks of A and B.
98
+ # We will advance this pointer as we move in the K direction
99
+ # and accumulate
100
+ # `a_ptrs` is a block of [BLOCK_SIZE_M, BLOCK_SIZE_K] pointers
101
+ # `b_ptrs` is a block of [BLOCK_SIZE_K, BLOCK_SIZE_N] pointers
102
+ num_tokens_post_padded = tl.load(num_tokens_post_padded_ptr)
103
+ if pid_m * BLOCK_SIZE_M >= num_tokens_post_padded:
104
+ return
105
+ offs_token_id = pid_m * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M)
106
+ offs_token = tl.load(sorted_token_ids_ptr + offs_token_id)
107
+ token_mask = offs_token < num_valid_tokens
108
+
109
+ offs_bn = (pid_n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N)) % N
110
+ offs_k = tl.arange(0, BLOCK_SIZE_K)
111
+ a_ptrs = a_ptr + (offs_token[:, None] // top_k * stride_am +
112
+ offs_k[None, :] * stride_ak)
113
+
114
+ off_experts = tl.load(expert_ids_ptr + pid_m)
115
+ b_ptrs = b_ptr + off_experts * stride_be + (offs_k[:, None] * stride_bk +
116
+ offs_bn[None, :] * stride_bn)
117
+
118
+ if use_fp8:
119
+ a_scale = tl.load(a_scale_ptr)
120
+ b_scale = tl.load(b_scale_ptr + off_experts)
121
+
122
+ # -----------------------------------------------------------
123
+ # Iterate to compute a block of the C matrix.
124
+ # We accumulate into a `[BLOCK_SIZE_M, BLOCK_SIZE_N]` block
125
+ # of fp32 values for higher accuracy.
126
+ # `accumulator` will be converted back to fp16 after the loop.
127
+ accumulator = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_N), dtype=tl.float32)
128
+
129
+ for k in range(0, tl.cdiv(K, BLOCK_SIZE_K)):
130
+ # Load the next block of A and B, generate a mask by checking the
131
+ # K dimension.
132
+ a = tl.load(a_ptrs,
133
+ mask=token_mask[:, None] &
134
+ (offs_k[None, :] < K - k * BLOCK_SIZE_K),
135
+ other=0.0)
136
+ b = tl.load(b_ptrs,
137
+ mask=offs_k[:, None] < K - k * BLOCK_SIZE_K,
138
+ other=0.0)
139
+ # We accumulate along the K dimension.
140
+ if use_fp8:
141
+ accumulator = tl.dot(a, b, acc=accumulator)
142
+ else:
143
+ accumulator += tl.dot(a, b)
144
+ # Advance the ptrs to the next K block.
145
+ a_ptrs += BLOCK_SIZE_K * stride_ak
146
+ b_ptrs += BLOCK_SIZE_K * stride_bk
147
+
148
+ if MUL_ROUTED_WEIGHT:
149
+ moe_weight = tl.load(topk_weights_ptr + offs_token,
150
+ mask=token_mask,
151
+ other=0)
152
+ accumulator = accumulator * moe_weight[:, None]
153
+
154
+ if use_fp8:
155
+ accumulator = (accumulator * a_scale * b_scale).to(compute_type)
156
+ else:
157
+ accumulator = accumulator.to(compute_type)
158
+ # -----------------------------------------------------------
159
+ # Write back the block of the output
160
+ offs_cn = pid_n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N)
161
+ c_ptrs = c_ptr + stride_cm * offs_token[:, None] + stride_cn * offs_cn[
162
+ None, :]
163
+ c_mask = token_mask[:, None] & (offs_cn[None, :] < N)
164
+ tl.store(c_ptrs, accumulator, mask=c_mask)
165
+
166
+
167
+ def moe_align_block_size(
168
+ topk_ids: torch.Tensor, block_size: int,
169
+ num_experts: int) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
170
+ """
171
+ Aligns the token distribution across experts to be compatible with block
172
+ size for matrix multiplication.
173
+
174
+ Parameters:
175
+ - topk_ids: A tensor of shape [total_tokens, top_k] representing the
176
+ top-k expert indices for each token.
177
+ - block_size: The block size used in block matrix multiplication.
178
+ - num_experts: The total number of experts.
179
+
180
+ Returns:
181
+ - sorted_token_ids: A tensor containing the sorted token indices according
182
+ to their allocated expert.
183
+ - expert_ids: A tensor indicating the assigned expert index for each block.
184
+ - num_tokens_post_padded: The total number of tokens after padding,
185
+ ensuring divisibility by block_size.
186
+
187
+ This function pads the number of tokens that each expert needs to process
188
+ so that it is divisible by block_size.
189
+ Padding ensures that during block matrix multiplication, the dimensions
190
+ align correctly.
191
+
192
+ Example:
193
+ Given topk_ids = [[2, 3, 4], [1, 2, 4], [1, 3, 4], [1, 2, 3]],
194
+ block_size = 4, and num_experts = 4:
195
+ - We initially have 12 tokens (after repeating 'top_k' times) and 4 experts,
196
+ with each expert needing to process 3 tokens.
197
+ - As block_size is 4, we pad 1 token for each expert.
198
+ - First, flatten topk_ids to [2, 3, 4, 1, 2, 4, 1, 3, 4, 1, 2, 3].
199
+ - Then append padding tokens [12, 12, 12, 12] for each block.
200
+ - After sorting by expert index, we obtain token_ids
201
+ [3, 6, 9, 12, 0, 4, 10, 12, 1, 7, 11, 12, 2, 5, 8, 12].
202
+ Tokens 12 are non-existent (padding) and are ignored in
203
+ the subsequent matrix multiplication.
204
+ - The padding ensures that the total number of tokens is now divisible
205
+ by block_size for proper block matrix operations.
206
+ """
207
+ max_num_tokens_padded = topk_ids.numel() + num_experts * (block_size - 1)
208
+ sorted_ids = torch.empty((max_num_tokens_padded, ),
209
+ dtype=torch.int32,
210
+ device=topk_ids.device)
211
+ sorted_ids.fill_(topk_ids.numel())
212
+ max_num_m_blocks = triton.cdiv(max_num_tokens_padded, block_size)
213
+ expert_ids = torch.empty((max_num_m_blocks, ),
214
+ dtype=torch.int32,
215
+ device=topk_ids.device)
216
+ num_tokens_post_pad = torch.empty((1),
217
+ dtype=torch.int32,
218
+ device=topk_ids.device)
219
+ ops.moe_align_block_size(topk_ids, num_experts, block_size, sorted_ids,
220
+ expert_ids, num_tokens_post_pad)
221
+ return sorted_ids, expert_ids, num_tokens_post_pad
222
+
223
+
224
+ def invoke_fused_moe_kernel(A: torch.Tensor, B: torch.Tensor, C: torch.Tensor,
225
+ A_scale: Optional[torch.Tensor],
226
+ B_scale: Optional[torch.Tensor],
227
+ topk_weights: torch.Tensor, topk_ids: torch.Tensor,
228
+ sorted_token_ids: torch.Tensor,
229
+ expert_ids: torch.Tensor,
230
+ num_tokens_post_padded: torch.Tensor,
231
+ mul_routed_weight: bool, top_k: int,
232
+ config: Dict[str, Any], compute_type: tl.dtype,
233
+ use_fp8: bool) -> None:
234
+ assert topk_weights.stride(1) == 1
235
+ assert sorted_token_ids.stride(0) == 1
236
+
237
+ if not use_fp8:
238
+ assert A_scale is None
239
+ assert B_scale is None
240
+ else:
241
+ A, A_scale = ops.scaled_fp8_quant(A, A_scale)
242
+ assert B_scale is not None
243
+
244
+ grid = lambda META: (triton.cdiv(sorted_token_ids.shape[0], META[
245
+ 'BLOCK_SIZE_M']) * triton.cdiv(B.shape[1], META['BLOCK_SIZE_N']), )
246
+
247
+ fused_moe_kernel[grid](
248
+ A,
249
+ B,
250
+ C,
251
+ A_scale,
252
+ B_scale,
253
+ topk_weights,
254
+ sorted_token_ids,
255
+ expert_ids,
256
+ num_tokens_post_padded,
257
+ B.shape[1],
258
+ B.shape[2],
259
+ sorted_token_ids.shape[0],
260
+ topk_ids.numel(),
261
+ A.stride(0),
262
+ A.stride(1),
263
+ B.stride(0),
264
+ B.stride(2),
265
+ B.stride(1),
266
+ C.stride(1),
267
+ C.stride(2),
268
+ MUL_ROUTED_WEIGHT=mul_routed_weight,
269
+ top_k=top_k,
270
+ compute_type=compute_type,
271
+ use_fp8=use_fp8,
272
+ **config,
273
+ )
274
+
275
+
276
+ def get_config_file_name(E: int, N: int, dtype: Optional[str]) -> str:
277
+ device_name = torch.cuda.get_device_name().replace(" ", "_")
278
+ dtype_selector = "" if not dtype else f",dtype={dtype}"
279
+ return f"E={E},N={N},device_name={device_name}{dtype_selector}.json"
280
+
281
+
282
+ @functools.lru_cache
283
+ def get_moe_configs(E: int, N: int,
284
+ dtype: Optional[str]) -> Optional[Dict[int, Any]]:
285
+ """
286
+ Return optimized configurations for the fused MoE kernel.
287
+
288
+ The return value will be a dictionary that maps an irregular grid of
289
+ batch sizes to configurations of the fused_moe kernel. To evaluate the
290
+ kernel on a given batch size bs, the closest batch size in the grid should
291
+ be picked and the associated configuration chosen to invoke the kernel.
292
+ """
293
+
294
+ # First look up if an optimized configuration is available in the configs
295
+ # directory
296
+ json_file_name = get_config_file_name(E, N, dtype)
297
+
298
+ config_file_path = os.path.join(
299
+ os.path.dirname(os.path.realpath(__file__)), "configs", json_file_name)
300
+ if os.path.exists(config_file_path):
301
+ with open(config_file_path) as f:
302
+ logger.info("Using configuration from %s for MoE layer.",
303
+ config_file_path)
304
+ # If a configuration has been found, return it
305
+ return {int(key): val for key, val in json.load(f).items()}
306
+
307
+ # If no optimized configuration is available, we will use the default
308
+ # configuration
309
+ return None
310
+
311
+
312
+ def get_default_config(
313
+ M: int,
314
+ E: int,
315
+ N: int,
316
+ K: int,
317
+ topk: int,
318
+ dtype: Optional[str],
319
+ ) -> Dict[str, int]:
320
+ if dtype == "float8":
321
+ config = {
322
+ 'BLOCK_SIZE_M': 128,
323
+ 'BLOCK_SIZE_N': 256,
324
+ 'BLOCK_SIZE_K': 128,
325
+ 'GROUP_SIZE_M': 32,
326
+ "num_warps": 8,
327
+ "num_stages": 4
328
+ }
329
+ if M <= E:
330
+ config = {
331
+ 'BLOCK_SIZE_M': 64,
332
+ 'BLOCK_SIZE_N': 128,
333
+ 'BLOCK_SIZE_K': 128,
334
+ 'GROUP_SIZE_M': 1,
335
+ "num_warps": 4,
336
+ "num_stages": 4
337
+ }
338
+ else:
339
+ config = {
340
+ 'BLOCK_SIZE_M': 64,
341
+ 'BLOCK_SIZE_N': 64,
342
+ 'BLOCK_SIZE_K': 32,
343
+ 'GROUP_SIZE_M': 8
344
+ }
345
+ if M <= E:
346
+ config = {
347
+ 'BLOCK_SIZE_M': 16,
348
+ 'BLOCK_SIZE_N': 32,
349
+ 'BLOCK_SIZE_K': 64,
350
+ 'GROUP_SIZE_M': 1
351
+ }
352
+ return config
353
+
354
+
355
+ def fused_topk(
356
+ hidden_states: torch.Tensor,
357
+ gating_output: torch.Tensor,
358
+ topk: int,
359
+ renormalize: bool,
360
+ ):
361
+ assert hidden_states.shape[0] == gating_output.shape[0], (
362
+ "Number of tokens mismatch")
363
+
364
+ M, _ = hidden_states.shape
365
+
366
+ topk_weights = torch.empty(M,
367
+ topk,
368
+ dtype=torch.float32,
369
+ device=hidden_states.device)
370
+ topk_ids = torch.empty(M,
371
+ topk,
372
+ dtype=torch.int32,
373
+ device=hidden_states.device)
374
+ token_expert_indicies = torch.empty(M,
375
+ topk,
376
+ dtype=torch.int32,
377
+ device=hidden_states.device)
378
+ ops.topk_softmax(
379
+ topk_weights,
380
+ topk_ids,
381
+ token_expert_indicies,
382
+ gating_output.float(), # TODO(woosuk): Optimize this.
383
+ )
384
+ del token_expert_indicies # Not used. Will be used in the future.
385
+
386
+ if renormalize:
387
+ topk_weights = topk_weights / topk_weights.sum(dim=-1, keepdim=True)
388
+ return topk_weights, topk_ids
389
+
390
+
391
+ def fused_experts(hidden_states: torch.Tensor,
392
+ w1: torch.Tensor,
393
+ w2: torch.Tensor,
394
+ topk_weights: torch.Tensor,
395
+ topk_ids: torch.Tensor,
396
+ inplace: bool = False,
397
+ override_config: Optional[Dict[str, Any]] = None,
398
+ use_fp8: bool = False,
399
+ w1_scale: Optional[torch.Tensor] = None,
400
+ w2_scale: Optional[torch.Tensor] = None,
401
+ a1_scale: Optional[torch.Tensor] = None,
402
+ a2_scale: Optional[torch.Tensor] = None):
403
+ # Check constraints.
404
+ assert hidden_states.shape[1] == w1.shape[2], "Hidden size mismatch"
405
+ assert topk_weights.shape == topk_ids.shape, "topk shape mismatch"
406
+ assert hidden_states.is_contiguous(), "Hidden_states must be contiguous"
407
+ assert w1.is_contiguous(), "Expert weights1 must be contiguous"
408
+ assert w2.is_contiguous(), "Expert weights2 must be contiguous"
409
+ assert hidden_states.dtype in [
410
+ torch.float32, torch.float16, torch.bfloat16
411
+ ]
412
+
413
+ M, _ = hidden_states.shape
414
+ E, N, _ = w1.shape
415
+
416
+ if override_config:
417
+ config = override_config
418
+ else:
419
+ # First try to load optimal config from the file
420
+ configs = get_moe_configs(E, w2.shape[2],
421
+ "float8" if use_fp8 else None)
422
+
423
+ if configs:
424
+ # If an optimal configuration map has been found, look up the
425
+ # optimal config
426
+ config = configs[min(configs.keys(), key=lambda x: abs(x - M))]
427
+ else:
428
+ # Else use the default config
429
+ config = get_default_config(M, E, N, w1.shape[2],
430
+ topk_ids.shape[1],
431
+ "float8" if use_fp8 else None)
432
+
433
+ intermediate_cache1 = torch.empty((M, topk_ids.shape[1], N),
434
+ device=hidden_states.device,
435
+ dtype=hidden_states.dtype)
436
+ intermediate_cache2 = torch.empty((M * topk_ids.shape[1], N // 2),
437
+ device=hidden_states.device,
438
+ dtype=hidden_states.dtype)
439
+ intermediate_cache3 = torch.empty((M, topk_ids.shape[1], w2.shape[1]),
440
+ device=hidden_states.device,
441
+ dtype=hidden_states.dtype)
442
+
443
+ sorted_token_ids, expert_ids, num_tokens_post_padded = moe_align_block_size(
444
+ topk_ids, config['BLOCK_SIZE_M'], E)
445
+ compute_type = (tl.bfloat16
446
+ if hidden_states.dtype == torch.bfloat16 else tl.float16)
447
+
448
+ invoke_fused_moe_kernel(hidden_states,
449
+ w1,
450
+ intermediate_cache1,
451
+ a1_scale,
452
+ w1_scale,
453
+ topk_weights,
454
+ topk_ids,
455
+ sorted_token_ids,
456
+ expert_ids,
457
+ num_tokens_post_padded,
458
+ False,
459
+ topk_ids.shape[1],
460
+ config,
461
+ compute_type=compute_type,
462
+ use_fp8=use_fp8)
463
+
464
+ ops.gelu_and_mul(intermediate_cache2, intermediate_cache1.view(-1, N))
465
+
466
+ invoke_fused_moe_kernel(intermediate_cache2,
467
+ w2,
468
+ intermediate_cache3,
469
+ a2_scale,
470
+ w2_scale,
471
+ topk_weights,
472
+ topk_ids,
473
+ sorted_token_ids,
474
+ expert_ids,
475
+ num_tokens_post_padded,
476
+ True,
477
+ 1,
478
+ config,
479
+ compute_type=compute_type,
480
+ use_fp8=use_fp8)
481
+
482
+ if inplace:
483
+ return torch.sum(intermediate_cache3.view(*intermediate_cache3.shape),
484
+ dim=1,
485
+ out=hidden_states)
486
+ return torch.sum(intermediate_cache3.view(*intermediate_cache3.shape),
487
+ dim=1)
488
+
489
+
490
+ def fused_moe(
491
+ hidden_states: torch.Tensor,
492
+ w1: torch.Tensor,
493
+ w2: torch.Tensor,
494
+ gating_output: torch.Tensor,
495
+ topk: int,
496
+ renormalize: bool,
497
+ inplace: bool = False,
498
+ override_config: Optional[Dict[str, Any]] = None,
499
+ use_fp8: bool = False,
500
+ w1_scale: Optional[torch.Tensor] = None,
501
+ w2_scale: Optional[torch.Tensor] = None,
502
+ a1_scale: Optional[torch.Tensor] = None,
503
+ a2_scale: Optional[torch.Tensor] = None,
504
+ ) -> torch.Tensor:
505
+ """
506
+ This function computes a Mixture of Experts (MoE) layer using two sets of
507
+ weights, w1 and w2, and top-k gating mechanism.
508
+
509
+ Parameters:
510
+ - hidden_states (torch.Tensor): The input tensor to the MoE layer.
511
+ - w1 (torch.Tensor): The first set of expert weights.
512
+ - w2 (torch.Tensor): The second set of expert weights.
513
+ - gating_output (torch.Tensor): The output of the gating operation
514
+ (before softmax).
515
+ - topk (int): The number of top-k experts to select.
516
+ - renormalize (bool): If True, renormalize the top-k weights to sum to 1.
517
+ - inplace (bool): If True, perform the operation in-place.
518
+ Defaults to False.
519
+ - override_config (Optional[Dict[str, Any]]): Optional override
520
+ for the kernel configuration.
521
+ - use_fp8 (bool): If True, use fp8 arithmetic to compute the inner
522
+ products for w1 and w2. Defaults to False.
523
+ - w1_scale (Optional[torch.Tensor]): Optional scale to be used for
524
+ w1.
525
+ - w2_scale (Optional[torch.Tensor]): Optional scale to be used for
526
+ w2.
527
+
528
+ Returns:
529
+ - torch.Tensor: The output tensor after applying the MoE layer.
530
+ """
531
+ # Check constraints.
532
+ assert gating_output.shape[1] == w1.shape[0], "Number of experts mismatch"
533
+
534
+ if hasattr(ops, "topk_softmax"):
535
+ topk_weights, topk_ids = fused_topk(hidden_states, gating_output, topk,
536
+ renormalize)
537
+ else:
538
+ topk_weights, topk_ids = fused_topk_v0_4_3(hidden_states, gating_output, topk,
539
+ renormalize)
540
+
541
+ return fused_experts(hidden_states,
542
+ w1,
543
+ w2,
544
+ topk_weights,
545
+ topk_ids,
546
+ inplace=inplace,
547
+ override_config=override_config,
548
+ use_fp8=use_fp8,
549
+ w1_scale=w1_scale,
550
+ w2_scale=w2_scale,
551
+ a1_scale=a1_scale,
552
+ a2_scale=a2_scale)
553
+
554
+
555
+
556
+ def fused_topk_v0_4_3(
557
+ hidden_states: torch.Tensor,
558
+ gating_output: torch.Tensor,
559
+ topk: int,
560
+ renormalize: bool,
561
+ ):
562
+ import vllm._moe_C as moe_kernels
563
+ M, _ = hidden_states.shape
564
+
565
+ topk_weights = torch.empty(
566
+ M, topk, dtype=torch.float32, device=hidden_states.device
567
+ )
568
+ topk_ids = torch.empty(M, topk, dtype=torch.int32, device=hidden_states.device)
569
+ token_expert_indicies = torch.empty(
570
+ M, topk, dtype=torch.int32, device=hidden_states.device
571
+ )
572
+ moe_kernels.topk_softmax(
573
+ topk_weights,
574
+ topk_ids,
575
+ token_expert_indicies,
576
+ gating_output.float(), # TODO(woosuk): Optimize this.
577
+ )
578
+ del token_expert_indicies # Not used. Will be used in the future.
579
+ if renormalize:
580
+ topk_weights = topk_weights / topk_weights.sum(dim=-1, keepdim=True)
581
+
582
+ return topk_weights, topk_ids