sglang 0.3.6.post1__py3-none-any.whl → 0.3.6.post3__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.
- sglang/bench_offline_throughput.py +55 -2
- sglang/bench_one_batch.py +4 -8
- sglang/bench_one_batch_server.py +6 -5
- sglang/check_env.py +7 -1
- sglang/lang/tracer.py +1 -1
- sglang/launch_server.py +2 -4
- sglang/srt/configs/model_config.py +2 -6
- sglang/srt/layers/attention/flashinfer_backend.py +3 -3
- sglang/srt/layers/sampler.py +1 -1
- sglang/srt/managers/data_parallel_controller.py +7 -11
- sglang/srt/managers/detokenizer_manager.py +7 -6
- sglang/srt/managers/image_processor.py +7 -10
- sglang/srt/managers/io_struct.py +0 -10
- sglang/srt/managers/schedule_batch.py +51 -13
- sglang/srt/managers/scheduler.py +41 -29
- sglang/srt/managers/session_controller.py +15 -7
- sglang/srt/managers/tokenizer_manager.py +4 -33
- sglang/srt/managers/tp_worker_overlap_thread.py +11 -2
- sglang/srt/models/grok.py +11 -48
- sglang/srt/models/llava.py +16 -9
- sglang/srt/models/olmo2.py +392 -0
- sglang/srt/models/qwen2_vl.py +10 -3
- sglang/srt/openai_api/adapter.py +1 -1
- sglang/srt/server.py +48 -45
- sglang/srt/server_args.py +1 -1
- sglang/srt/utils.py +22 -24
- sglang/test/test_utils.py +21 -8
- sglang/utils.py +2 -2
- sglang/version.py +1 -1
- {sglang-0.3.6.post1.dist-info → sglang-0.3.6.post3.dist-info}/METADATA +4 -2
- {sglang-0.3.6.post1.dist-info → sglang-0.3.6.post3.dist-info}/RECORD +34 -36
- sglang/srt/layers/fused_moe_grok/__init__.py +0 -1
- sglang/srt/layers/fused_moe_grok/fused_moe.py +0 -692
- sglang/srt/layers/fused_moe_grok/layer.py +0 -630
- {sglang-0.3.6.post1.dist-info → sglang-0.3.6.post3.dist-info}/LICENSE +0 -0
- {sglang-0.3.6.post1.dist-info → sglang-0.3.6.post3.dist-info}/WHEEL +0 -0
- {sglang-0.3.6.post1.dist-info → sglang-0.3.6.post3.dist-info}/top_level.txt +0 -0
@@ -1,692 +0,0 @@
|
|
1
|
-
# Adapted from
|
2
|
-
# https://github.com/vllm-project/vllm/tree/v0.5.4/vllm/model_executor/layers/fused_moe
|
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
|
-
import vllm.envs as envs
|
13
|
-
from vllm import _custom_ops as ops
|
14
|
-
from vllm.logger import init_logger
|
15
|
-
|
16
|
-
logger = init_logger(__name__)
|
17
|
-
padding_size = 128 if bool(int(os.getenv("MOE_PADDING", "0"))) else 0
|
18
|
-
|
19
|
-
|
20
|
-
@triton.jit
|
21
|
-
def fused_moe_kernel(
|
22
|
-
# Pointers to matrices
|
23
|
-
a_ptr,
|
24
|
-
b_ptr,
|
25
|
-
c_ptr,
|
26
|
-
a_scale_ptr,
|
27
|
-
b_scale_ptr,
|
28
|
-
topk_weights_ptr,
|
29
|
-
sorted_token_ids_ptr,
|
30
|
-
expert_ids_ptr,
|
31
|
-
num_tokens_post_padded_ptr,
|
32
|
-
# Matrix dimensions
|
33
|
-
N,
|
34
|
-
K,
|
35
|
-
EM,
|
36
|
-
num_valid_tokens,
|
37
|
-
# The stride variables represent how much to increase the ptr by when
|
38
|
-
# moving by 1 element in a particular dimension. E.g. `stride_am` is
|
39
|
-
# how much to increase `a_ptr` by to get the element one row down
|
40
|
-
# (A has M rows).
|
41
|
-
stride_am,
|
42
|
-
stride_ak,
|
43
|
-
stride_be,
|
44
|
-
stride_bk,
|
45
|
-
stride_bn,
|
46
|
-
stride_cm,
|
47
|
-
stride_cn,
|
48
|
-
# Meta-parameters
|
49
|
-
BLOCK_SIZE_M: tl.constexpr,
|
50
|
-
BLOCK_SIZE_N: tl.constexpr,
|
51
|
-
BLOCK_SIZE_K: tl.constexpr,
|
52
|
-
GROUP_SIZE_M: tl.constexpr,
|
53
|
-
MUL_ROUTED_WEIGHT: tl.constexpr,
|
54
|
-
top_k: tl.constexpr,
|
55
|
-
compute_type: tl.constexpr,
|
56
|
-
use_fp8: tl.constexpr,
|
57
|
-
even_Ks: tl.constexpr,
|
58
|
-
):
|
59
|
-
"""
|
60
|
-
Implements the fused computation for a Mixture of Experts (MOE) using
|
61
|
-
token and expert matrices.
|
62
|
-
|
63
|
-
Key Parameters:
|
64
|
-
- A: The input tensor representing tokens with shape (*, K), where '*' can
|
65
|
-
be any shape representing batches and K is the feature dimension of
|
66
|
-
each token.
|
67
|
-
- B: The stacked MOE weight tensor with shape (E, N, K), where E is
|
68
|
-
the number of experts, K is the input feature dimension, and N is
|
69
|
-
the output feature dimension.
|
70
|
-
- C: The output cache tensor with shape (M, topk, N), where M is the
|
71
|
-
total number of tokens post padding, topk is the number of times
|
72
|
-
each token is repeated, and N is the output feature dimension.
|
73
|
-
- sorted_token_ids: A tensor containing the sorted indices of tokens,
|
74
|
-
repeated topk times and arranged by the expert index they are
|
75
|
-
assigned to.
|
76
|
-
- expert_ids: A tensor containing the indices of the expert for each
|
77
|
-
block. It determines which expert matrix from B should be used for
|
78
|
-
each block in A.
|
79
|
-
This kernel performs the multiplication of a token by its corresponding
|
80
|
-
expert matrix as determined by `expert_ids`. The sorting of
|
81
|
-
`sorted_token_ids` by expert index and padding ensures divisibility by
|
82
|
-
BLOCK_SIZE_M, which is necessary to maintain consistency in block matrix
|
83
|
-
multiplication across different blocks processed by the same expert.
|
84
|
-
"""
|
85
|
-
# -----------------------------------------------------------
|
86
|
-
# Map program ids `pid` to the block of C it should compute.
|
87
|
-
# This is done in a grouped ordering to promote L2 data reuse.
|
88
|
-
pid = tl.program_id(axis=0)
|
89
|
-
num_pid_m = tl.cdiv(EM, BLOCK_SIZE_M)
|
90
|
-
num_pid_n = tl.cdiv(N, BLOCK_SIZE_N)
|
91
|
-
num_pid_in_group = GROUP_SIZE_M * num_pid_n
|
92
|
-
group_id = pid // num_pid_in_group
|
93
|
-
first_pid_m = group_id * GROUP_SIZE_M
|
94
|
-
group_size_m = min(num_pid_m - first_pid_m, GROUP_SIZE_M)
|
95
|
-
pid_m = first_pid_m + ((pid % num_pid_in_group) % group_size_m)
|
96
|
-
pid_n = (pid % num_pid_in_group) // group_size_m
|
97
|
-
|
98
|
-
# ----------------------------------------------------------
|
99
|
-
# Create pointers for the first blocks of A and B.
|
100
|
-
# We will advance this pointer as we move in the K direction
|
101
|
-
# and accumulate
|
102
|
-
# `a_ptrs` is a block of [BLOCK_SIZE_M, BLOCK_SIZE_K] pointers
|
103
|
-
# `b_ptrs` is a block of [BLOCK_SIZE_K, BLOCK_SIZE_N] pointers
|
104
|
-
num_tokens_post_padded = tl.load(num_tokens_post_padded_ptr)
|
105
|
-
if pid_m * BLOCK_SIZE_M >= num_tokens_post_padded:
|
106
|
-
return
|
107
|
-
offs_token_id = pid_m * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M)
|
108
|
-
offs_token = tl.load(sorted_token_ids_ptr + offs_token_id)
|
109
|
-
token_mask = offs_token < num_valid_tokens
|
110
|
-
|
111
|
-
offs_bn = (pid_n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N)) % N
|
112
|
-
offs_k = tl.arange(0, BLOCK_SIZE_K)
|
113
|
-
a_ptrs = a_ptr + (
|
114
|
-
offs_token[:, None] // top_k * stride_am + offs_k[None, :] * stride_ak
|
115
|
-
)
|
116
|
-
|
117
|
-
off_experts = tl.load(expert_ids_ptr + pid_m)
|
118
|
-
b_ptrs = (
|
119
|
-
b_ptr
|
120
|
-
+ off_experts * stride_be
|
121
|
-
+ (offs_k[:, None] * stride_bk + offs_bn[None, :] * stride_bn)
|
122
|
-
)
|
123
|
-
|
124
|
-
if use_fp8:
|
125
|
-
a_scale = tl.load(a_scale_ptr)
|
126
|
-
b_scale = tl.load(b_scale_ptr + off_experts)
|
127
|
-
|
128
|
-
# -----------------------------------------------------------
|
129
|
-
# Iterate to compute a block of the C matrix.
|
130
|
-
# We accumulate into a `[BLOCK_SIZE_M, BLOCK_SIZE_N]` block
|
131
|
-
# of fp32 values for higher accuracy.
|
132
|
-
# `accumulator` will be converted back to fp16 after the loop.
|
133
|
-
accumulator = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_N), dtype=tl.float32)
|
134
|
-
for k in range(0, tl.cdiv(K, BLOCK_SIZE_K)):
|
135
|
-
# Load the next block of A and B, generate a mask by checking the
|
136
|
-
# K dimension.
|
137
|
-
if even_Ks:
|
138
|
-
a = tl.load(
|
139
|
-
a_ptrs,
|
140
|
-
mask=token_mask[:, None],
|
141
|
-
other=0.0,
|
142
|
-
)
|
143
|
-
b = tl.load(b_ptrs)
|
144
|
-
else:
|
145
|
-
a = tl.load(
|
146
|
-
a_ptrs,
|
147
|
-
mask=token_mask[:, None] & (offs_k[None, :] < K - k * BLOCK_SIZE_K),
|
148
|
-
other=0.0,
|
149
|
-
)
|
150
|
-
b = tl.load(b_ptrs, mask=offs_k[:, None] < K - k * BLOCK_SIZE_K, other=0.0)
|
151
|
-
|
152
|
-
# We accumulate along the K dimension.
|
153
|
-
if use_fp8:
|
154
|
-
accumulator = tl.dot(a, b, acc=accumulator)
|
155
|
-
else:
|
156
|
-
accumulator += tl.dot(a, b)
|
157
|
-
# Advance the ptrs to the next K block.
|
158
|
-
a_ptrs += BLOCK_SIZE_K * stride_ak
|
159
|
-
b_ptrs += BLOCK_SIZE_K * stride_bk
|
160
|
-
|
161
|
-
if MUL_ROUTED_WEIGHT:
|
162
|
-
moe_weight = tl.load(topk_weights_ptr + offs_token, mask=token_mask, other=0)
|
163
|
-
accumulator = accumulator * moe_weight[:, None]
|
164
|
-
|
165
|
-
if use_fp8:
|
166
|
-
accumulator = (accumulator * a_scale * b_scale).to(compute_type)
|
167
|
-
else:
|
168
|
-
accumulator = accumulator.to(compute_type)
|
169
|
-
# -----------------------------------------------------------
|
170
|
-
# Write back the block of the output
|
171
|
-
offs_cn = pid_n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N)
|
172
|
-
c_ptrs = c_ptr + stride_cm * offs_token[:, None] + stride_cn * offs_cn[None, :]
|
173
|
-
c_mask = token_mask[:, None] & (offs_cn[None, :] < N)
|
174
|
-
tl.store(c_ptrs, accumulator, mask=c_mask)
|
175
|
-
|
176
|
-
|
177
|
-
def moe_align_block_size(
|
178
|
-
topk_ids: torch.Tensor, block_size: int, num_experts: int
|
179
|
-
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
180
|
-
"""
|
181
|
-
Aligns the token distribution across experts to be compatible with block
|
182
|
-
size for matrix multiplication.
|
183
|
-
|
184
|
-
Parameters:
|
185
|
-
- topk_ids: A tensor of shape [total_tokens, top_k] representing the
|
186
|
-
top-k expert indices for each token.
|
187
|
-
- block_size: The block size used in block matrix multiplication.
|
188
|
-
- num_experts: The total number of experts.
|
189
|
-
|
190
|
-
Returns:
|
191
|
-
- sorted_token_ids: A tensor containing the sorted token indices according
|
192
|
-
to their allocated expert.
|
193
|
-
- expert_ids: A tensor indicating the assigned expert index for each block.
|
194
|
-
- num_tokens_post_padded: The total number of tokens after padding,
|
195
|
-
ensuring divisibility by block_size.
|
196
|
-
|
197
|
-
This function pads the number of tokens that each expert needs to process
|
198
|
-
so that it is divisible by block_size.
|
199
|
-
Padding ensures that during block matrix multiplication, the dimensions
|
200
|
-
align correctly.
|
201
|
-
|
202
|
-
Example:
|
203
|
-
Given topk_ids = [[2, 3, 4], [1, 2, 4], [1, 3, 4], [1, 2, 3]],
|
204
|
-
block_size = 4, and num_experts = 4:
|
205
|
-
- We initially have 12 tokens (after repeating 'top_k' times) and 4 experts,
|
206
|
-
with each expert needing to process 3 tokens.
|
207
|
-
- As block_size is 4, we pad 1 token for each expert.
|
208
|
-
- First, flatten topk_ids to [2, 3, 4, 1, 2, 4, 1, 3, 4, 1, 2, 3].
|
209
|
-
- Then append padding tokens [12, 12, 12, 12] for each block.
|
210
|
-
- After sorting by expert index, we obtain token_ids
|
211
|
-
[3, 6, 9, 12, 0, 4, 10, 12, 1, 7, 11, 12, 2, 5, 8, 12].
|
212
|
-
Tokens 12 are non-existent (padding) and are ignored in
|
213
|
-
the subsequent matrix multiplication.
|
214
|
-
- The padding ensures that the total number of tokens is now divisible
|
215
|
-
by block_size for proper block matrix operations.
|
216
|
-
"""
|
217
|
-
max_num_tokens_padded = topk_ids.numel() + num_experts * (block_size - 1)
|
218
|
-
sorted_ids = torch.empty(
|
219
|
-
(max_num_tokens_padded,), dtype=torch.int32, device=topk_ids.device
|
220
|
-
)
|
221
|
-
sorted_ids.fill_(topk_ids.numel())
|
222
|
-
max_num_m_blocks = triton.cdiv(max_num_tokens_padded, block_size)
|
223
|
-
expert_ids = torch.empty(
|
224
|
-
(max_num_m_blocks,), dtype=torch.int32, device=topk_ids.device
|
225
|
-
)
|
226
|
-
num_tokens_post_pad = torch.empty((1), dtype=torch.int32, device=topk_ids.device)
|
227
|
-
ops.moe_align_block_size(
|
228
|
-
topk_ids, num_experts, block_size, sorted_ids, expert_ids, num_tokens_post_pad
|
229
|
-
)
|
230
|
-
return sorted_ids, expert_ids, num_tokens_post_pad
|
231
|
-
|
232
|
-
|
233
|
-
def invoke_fused_moe_kernel(
|
234
|
-
A: torch.Tensor,
|
235
|
-
B: torch.Tensor,
|
236
|
-
C: torch.Tensor,
|
237
|
-
A_scale: Optional[torch.Tensor],
|
238
|
-
B_scale: Optional[torch.Tensor],
|
239
|
-
topk_weights: torch.Tensor,
|
240
|
-
topk_ids: torch.Tensor,
|
241
|
-
sorted_token_ids: torch.Tensor,
|
242
|
-
expert_ids: torch.Tensor,
|
243
|
-
num_tokens_post_padded: torch.Tensor,
|
244
|
-
mul_routed_weight: bool,
|
245
|
-
top_k: int,
|
246
|
-
config: Dict[str, Any],
|
247
|
-
compute_type: tl.dtype,
|
248
|
-
use_fp8: bool,
|
249
|
-
) -> None:
|
250
|
-
assert topk_weights.stride(1) == 1
|
251
|
-
assert sorted_token_ids.stride(0) == 1
|
252
|
-
|
253
|
-
padded_size = padding_size
|
254
|
-
if not use_fp8:
|
255
|
-
assert A_scale is None
|
256
|
-
assert B_scale is None
|
257
|
-
# MOE_PADDING FP8 only
|
258
|
-
padded_size = 0
|
259
|
-
else:
|
260
|
-
A, A_scale = ops.scaled_fp8_quant(A, A_scale)
|
261
|
-
assert B_scale is not None
|
262
|
-
|
263
|
-
grid = lambda META: (
|
264
|
-
triton.cdiv(sorted_token_ids.shape[0], META["BLOCK_SIZE_M"])
|
265
|
-
* triton.cdiv(B.shape[1], META["BLOCK_SIZE_N"]),
|
266
|
-
)
|
267
|
-
|
268
|
-
K = B.shape[2] - padded_size
|
269
|
-
if K % config["BLOCK_SIZE_K"] == 0:
|
270
|
-
even_ks = True
|
271
|
-
else:
|
272
|
-
even_ks = False
|
273
|
-
|
274
|
-
fused_moe_kernel[grid](
|
275
|
-
A,
|
276
|
-
B,
|
277
|
-
C,
|
278
|
-
A_scale,
|
279
|
-
B_scale,
|
280
|
-
topk_weights,
|
281
|
-
sorted_token_ids,
|
282
|
-
expert_ids,
|
283
|
-
num_tokens_post_padded,
|
284
|
-
B.shape[1],
|
285
|
-
B.shape[2] - padded_size,
|
286
|
-
sorted_token_ids.shape[0],
|
287
|
-
topk_ids.numel(),
|
288
|
-
A.stride(0),
|
289
|
-
A.stride(1),
|
290
|
-
B.stride(0),
|
291
|
-
B.stride(2),
|
292
|
-
B.stride(1),
|
293
|
-
C.stride(1),
|
294
|
-
C.stride(2),
|
295
|
-
MUL_ROUTED_WEIGHT=mul_routed_weight,
|
296
|
-
top_k=top_k,
|
297
|
-
compute_type=compute_type,
|
298
|
-
use_fp8=use_fp8,
|
299
|
-
even_Ks=even_ks,
|
300
|
-
**config,
|
301
|
-
)
|
302
|
-
|
303
|
-
|
304
|
-
def get_config_file_name(E: int, N: int, dtype: Optional[str]) -> str:
|
305
|
-
device_name = torch.cuda.get_device_name().replace(" ", "_")
|
306
|
-
dtype_selector = "" if not dtype else f",dtype={dtype}"
|
307
|
-
return f"E={E},N={N},device_name={device_name}{dtype_selector}.json"
|
308
|
-
|
309
|
-
|
310
|
-
@functools.lru_cache
|
311
|
-
def get_moe_configs(E: int, N: int, dtype: Optional[str]) -> Optional[Dict[int, Any]]:
|
312
|
-
"""
|
313
|
-
Return optimized configurations for the fused MoE kernel.
|
314
|
-
|
315
|
-
The return value will be a dictionary that maps an irregular grid of
|
316
|
-
batch sizes to configurations of the fused_moe kernel. To evaluate the
|
317
|
-
kernel on a given batch size bs, the closest batch size in the grid should
|
318
|
-
be picked and the associated configuration chosen to invoke the kernel.
|
319
|
-
"""
|
320
|
-
|
321
|
-
# First look up if an optimized configuration is available in the configs
|
322
|
-
# directory
|
323
|
-
json_file_name = get_config_file_name(E, N, dtype)
|
324
|
-
|
325
|
-
config_file_path = os.path.join(
|
326
|
-
os.path.dirname(os.path.realpath(__file__)), "configs", json_file_name
|
327
|
-
)
|
328
|
-
if os.path.exists(config_file_path):
|
329
|
-
with open(config_file_path) as f:
|
330
|
-
logger.info("Using configuration from %s for MoE layer.", config_file_path)
|
331
|
-
# If a configuration has been found, return it
|
332
|
-
return {int(key): val for key, val in json.load(f).items()}
|
333
|
-
|
334
|
-
# If no optimized configuration is available, we will use the default
|
335
|
-
# configuration
|
336
|
-
return None
|
337
|
-
|
338
|
-
|
339
|
-
def get_default_config(
|
340
|
-
M: int,
|
341
|
-
E: int,
|
342
|
-
N: int,
|
343
|
-
K: int,
|
344
|
-
topk: int,
|
345
|
-
dtype: Optional[str],
|
346
|
-
) -> Dict[str, int]:
|
347
|
-
if dtype == "float8":
|
348
|
-
config = {
|
349
|
-
"BLOCK_SIZE_M": 128,
|
350
|
-
"BLOCK_SIZE_N": 256,
|
351
|
-
"BLOCK_SIZE_K": 128,
|
352
|
-
"GROUP_SIZE_M": 32,
|
353
|
-
"num_warps": 8,
|
354
|
-
"num_stages": 4,
|
355
|
-
}
|
356
|
-
if M <= E:
|
357
|
-
config = {
|
358
|
-
"BLOCK_SIZE_M": 64,
|
359
|
-
"BLOCK_SIZE_N": 128,
|
360
|
-
"BLOCK_SIZE_K": 128,
|
361
|
-
"GROUP_SIZE_M": 1,
|
362
|
-
"num_warps": 4,
|
363
|
-
"num_stages": 4,
|
364
|
-
}
|
365
|
-
else:
|
366
|
-
config = {
|
367
|
-
"BLOCK_SIZE_M": 64,
|
368
|
-
"BLOCK_SIZE_N": 64,
|
369
|
-
"BLOCK_SIZE_K": 32,
|
370
|
-
"GROUP_SIZE_M": 8,
|
371
|
-
}
|
372
|
-
if M <= E:
|
373
|
-
config = {
|
374
|
-
"BLOCK_SIZE_M": 16,
|
375
|
-
"BLOCK_SIZE_N": 32,
|
376
|
-
"BLOCK_SIZE_K": 64,
|
377
|
-
"GROUP_SIZE_M": 1,
|
378
|
-
}
|
379
|
-
return config
|
380
|
-
|
381
|
-
|
382
|
-
def try_get_optimal_moe_config(
|
383
|
-
w1_shape: Tuple[int, ...],
|
384
|
-
w2_shape: Tuple[int, ...],
|
385
|
-
top_k: int,
|
386
|
-
dtype: Optional[str],
|
387
|
-
M: int,
|
388
|
-
override_config: Optional[Dict[str, Any]] = None,
|
389
|
-
):
|
390
|
-
if override_config:
|
391
|
-
config = override_config
|
392
|
-
else:
|
393
|
-
# First try to load optimal config from the file
|
394
|
-
E, _, N = w2_shape
|
395
|
-
configs = get_moe_configs(E, N, dtype)
|
396
|
-
|
397
|
-
if configs:
|
398
|
-
# If an optimal configuration map has been found, look up the
|
399
|
-
# optimal config
|
400
|
-
config = configs[min(configs.keys(), key=lambda x: abs(x - M))]
|
401
|
-
else:
|
402
|
-
# Else use the default config
|
403
|
-
config = get_default_config(M, E, N, w1_shape[2], top_k, dtype)
|
404
|
-
return config
|
405
|
-
|
406
|
-
|
407
|
-
def fused_topk(
|
408
|
-
hidden_states: torch.Tensor,
|
409
|
-
gating_output: torch.Tensor,
|
410
|
-
topk: int,
|
411
|
-
renormalize: bool,
|
412
|
-
):
|
413
|
-
assert hidden_states.shape[0] == gating_output.shape[0], "Number of tokens mismatch"
|
414
|
-
|
415
|
-
M, _ = hidden_states.shape
|
416
|
-
|
417
|
-
topk_weights = torch.empty(
|
418
|
-
M, topk, dtype=torch.float32, device=hidden_states.device
|
419
|
-
)
|
420
|
-
topk_ids = torch.empty(M, topk, dtype=torch.int32, device=hidden_states.device)
|
421
|
-
token_expert_indicies = torch.empty(
|
422
|
-
M, topk, dtype=torch.int32, device=hidden_states.device
|
423
|
-
)
|
424
|
-
ops.topk_softmax(
|
425
|
-
topk_weights,
|
426
|
-
topk_ids,
|
427
|
-
token_expert_indicies,
|
428
|
-
gating_output.float(), # TODO(woosuk): Optimize this.
|
429
|
-
)
|
430
|
-
del token_expert_indicies # Not used. Will be used in the future.
|
431
|
-
|
432
|
-
if renormalize:
|
433
|
-
topk_weights = topk_weights / topk_weights.sum(dim=-1, keepdim=True)
|
434
|
-
return topk_weights, topk_ids
|
435
|
-
|
436
|
-
|
437
|
-
# This is used by the Deepseek-V2 model
|
438
|
-
def grouped_topk(
|
439
|
-
hidden_states: torch.Tensor,
|
440
|
-
gating_output: torch.Tensor,
|
441
|
-
topk: int,
|
442
|
-
renormalize: bool,
|
443
|
-
num_expert_group: int = 0,
|
444
|
-
topk_group: int = 0,
|
445
|
-
):
|
446
|
-
|
447
|
-
assert hidden_states.shape[0] == gating_output.shape[0], "Number of tokens mismatch"
|
448
|
-
|
449
|
-
scores = torch.softmax(gating_output, dim=-1)
|
450
|
-
num_token = scores.shape[0]
|
451
|
-
group_scores = (
|
452
|
-
scores.view(num_token, num_expert_group, -1).max(dim=-1).values
|
453
|
-
) # [n, n_group]
|
454
|
-
group_idx = torch.topk(group_scores, k=topk_group, dim=-1, sorted=False)[
|
455
|
-
1
|
456
|
-
] # [n, top_k_group]
|
457
|
-
group_mask = torch.zeros_like(group_scores) # [n, n_group]
|
458
|
-
group_mask.scatter_(1, group_idx, 1) # [n, n_group]
|
459
|
-
score_mask = (
|
460
|
-
group_mask.unsqueeze(-1)
|
461
|
-
.expand(num_token, num_expert_group, scores.shape[-1] // num_expert_group)
|
462
|
-
.reshape(num_token, -1)
|
463
|
-
) # [n, e]
|
464
|
-
tmp_scores = scores.masked_fill(~score_mask.bool(), 0.0) # [n, e]
|
465
|
-
topk_weights, topk_ids = torch.topk(tmp_scores, k=topk, dim=-1, sorted=False)
|
466
|
-
|
467
|
-
if renormalize:
|
468
|
-
topk_weights = topk_weights / topk_weights.sum(dim=-1, keepdim=True)
|
469
|
-
return topk_weights, topk_ids
|
470
|
-
|
471
|
-
|
472
|
-
def fused_experts(
|
473
|
-
hidden_states: torch.Tensor,
|
474
|
-
w1: torch.Tensor,
|
475
|
-
w2: torch.Tensor,
|
476
|
-
topk_weights: torch.Tensor,
|
477
|
-
topk_ids: torch.Tensor,
|
478
|
-
inplace: bool = False,
|
479
|
-
override_config: Optional[Dict[str, Any]] = None,
|
480
|
-
use_fp8: bool = False,
|
481
|
-
w1_scale: Optional[torch.Tensor] = None,
|
482
|
-
w2_scale: Optional[torch.Tensor] = None,
|
483
|
-
a1_scale: Optional[torch.Tensor] = None,
|
484
|
-
a2_scale: Optional[torch.Tensor] = None,
|
485
|
-
):
|
486
|
-
padded_size = padding_size
|
487
|
-
if not use_fp8:
|
488
|
-
# MOE_PADDING FP8 only
|
489
|
-
padded_size = 0
|
490
|
-
# Check constraints.
|
491
|
-
assert hidden_states.shape[1] == w1.shape[2] - padded_size, "Hidden size mismatch"
|
492
|
-
assert topk_weights.shape == topk_ids.shape, "topk shape mismatch"
|
493
|
-
assert hidden_states.is_contiguous(), "Hidden_states must be contiguous"
|
494
|
-
assert w1.is_contiguous(), "Expert weights1 must be contiguous"
|
495
|
-
assert w2.is_contiguous(), "Expert weights2 must be contiguous"
|
496
|
-
assert hidden_states.dtype in [torch.float32, torch.float16, torch.bfloat16]
|
497
|
-
|
498
|
-
num_tokens, _ = hidden_states.shape
|
499
|
-
E, N, _ = w1.shape
|
500
|
-
# We execute the fused_moe kernel in chunks to circumvent this issue:
|
501
|
-
# https://github.com/vllm-project/vllm/issues/5938
|
502
|
-
CHUNK_SIZE = envs.VLLM_FUSED_MOE_CHUNK_SIZE
|
503
|
-
M = min(num_tokens, CHUNK_SIZE)
|
504
|
-
|
505
|
-
get_config_func = functools.partial(
|
506
|
-
try_get_optimal_moe_config,
|
507
|
-
w1.shape,
|
508
|
-
(w2.shape[0], w2.shape[1], w2.shape[2] - padded_size),
|
509
|
-
topk_ids.shape[1],
|
510
|
-
"float8" if use_fp8 else None,
|
511
|
-
override_config=override_config,
|
512
|
-
)
|
513
|
-
|
514
|
-
config = get_config_func(M)
|
515
|
-
|
516
|
-
intermediate_cache1 = torch.empty(
|
517
|
-
(M, topk_ids.shape[1], N),
|
518
|
-
device=hidden_states.device,
|
519
|
-
dtype=hidden_states.dtype,
|
520
|
-
)
|
521
|
-
intermediate_cache2 = torch.empty(
|
522
|
-
(M * topk_ids.shape[1], N // 2),
|
523
|
-
device=hidden_states.device,
|
524
|
-
dtype=hidden_states.dtype,
|
525
|
-
)
|
526
|
-
intermediate_cache3 = torch.empty(
|
527
|
-
(M, topk_ids.shape[1], w2.shape[1]),
|
528
|
-
device=hidden_states.device,
|
529
|
-
dtype=hidden_states.dtype,
|
530
|
-
)
|
531
|
-
|
532
|
-
compute_type = tl.bfloat16 if hidden_states.dtype == torch.bfloat16 else tl.float16
|
533
|
-
|
534
|
-
if inplace:
|
535
|
-
out_hidden_states = hidden_states
|
536
|
-
else:
|
537
|
-
out_hidden_states = torch.empty_like(hidden_states)
|
538
|
-
|
539
|
-
for chunk in range((num_tokens // CHUNK_SIZE) + 1):
|
540
|
-
begin_chunk_idx, end_chunk_idx = (
|
541
|
-
chunk * CHUNK_SIZE,
|
542
|
-
min((chunk + 1) * CHUNK_SIZE, num_tokens),
|
543
|
-
)
|
544
|
-
curr_hidden_states = hidden_states[begin_chunk_idx:end_chunk_idx]
|
545
|
-
tokens_in_chunk, _ = curr_hidden_states.shape
|
546
|
-
|
547
|
-
if tokens_in_chunk == 0:
|
548
|
-
break
|
549
|
-
|
550
|
-
if tokens_in_chunk < CHUNK_SIZE and chunk > 0:
|
551
|
-
# Adjust the intermediate cache size and config for the last
|
552
|
-
# chunk. Note that in most cases we only have one chunk
|
553
|
-
# so the cache size and config are already set correctly and
|
554
|
-
# do not need to be adjusted.
|
555
|
-
intermediate_cache1 = intermediate_cache1[:tokens_in_chunk]
|
556
|
-
intermediate_cache2 = intermediate_cache2[:tokens_in_chunk]
|
557
|
-
intermediate_cache3 = intermediate_cache3[:tokens_in_chunk]
|
558
|
-
config = get_config_func(tokens_in_chunk)
|
559
|
-
|
560
|
-
curr_topk_ids = topk_ids[begin_chunk_idx:end_chunk_idx]
|
561
|
-
curr_topk_weights = topk_weights[begin_chunk_idx:end_chunk_idx]
|
562
|
-
|
563
|
-
sorted_token_ids, expert_ids, num_tokens_post_padded = moe_align_block_size(
|
564
|
-
curr_topk_ids, config["BLOCK_SIZE_M"], E
|
565
|
-
)
|
566
|
-
|
567
|
-
invoke_fused_moe_kernel(
|
568
|
-
curr_hidden_states,
|
569
|
-
w1,
|
570
|
-
intermediate_cache1,
|
571
|
-
a1_scale,
|
572
|
-
w1_scale,
|
573
|
-
curr_topk_weights,
|
574
|
-
curr_topk_ids,
|
575
|
-
sorted_token_ids,
|
576
|
-
expert_ids,
|
577
|
-
num_tokens_post_padded,
|
578
|
-
False,
|
579
|
-
topk_ids.shape[1],
|
580
|
-
config,
|
581
|
-
compute_type=compute_type,
|
582
|
-
use_fp8=use_fp8,
|
583
|
-
)
|
584
|
-
|
585
|
-
ops.gelu_and_mul(intermediate_cache2, intermediate_cache1.view(-1, N))
|
586
|
-
|
587
|
-
invoke_fused_moe_kernel(
|
588
|
-
intermediate_cache2,
|
589
|
-
w2,
|
590
|
-
intermediate_cache3,
|
591
|
-
a2_scale,
|
592
|
-
w2_scale,
|
593
|
-
curr_topk_weights,
|
594
|
-
curr_topk_ids,
|
595
|
-
sorted_token_ids,
|
596
|
-
expert_ids,
|
597
|
-
num_tokens_post_padded,
|
598
|
-
True,
|
599
|
-
1,
|
600
|
-
config,
|
601
|
-
compute_type=compute_type,
|
602
|
-
use_fp8=use_fp8,
|
603
|
-
)
|
604
|
-
|
605
|
-
torch.sum(
|
606
|
-
intermediate_cache3.view(*intermediate_cache3.shape),
|
607
|
-
dim=1,
|
608
|
-
out=out_hidden_states[begin_chunk_idx:end_chunk_idx],
|
609
|
-
)
|
610
|
-
return out_hidden_states
|
611
|
-
|
612
|
-
|
613
|
-
def fused_moe(
|
614
|
-
hidden_states: torch.Tensor,
|
615
|
-
w1: torch.Tensor,
|
616
|
-
w2: torch.Tensor,
|
617
|
-
gating_output: torch.Tensor,
|
618
|
-
topk: int,
|
619
|
-
renormalize: bool,
|
620
|
-
inplace: bool = False,
|
621
|
-
override_config: Optional[Dict[str, Any]] = None,
|
622
|
-
use_grouped_topk: bool = False,
|
623
|
-
num_expert_group: Optional[int] = None,
|
624
|
-
topk_group: Optional[int] = None,
|
625
|
-
use_fp8: bool = False,
|
626
|
-
w1_scale: Optional[torch.Tensor] = None,
|
627
|
-
w2_scale: Optional[torch.Tensor] = None,
|
628
|
-
a1_scale: Optional[torch.Tensor] = None,
|
629
|
-
a2_scale: Optional[torch.Tensor] = None,
|
630
|
-
) -> torch.Tensor:
|
631
|
-
"""
|
632
|
-
This function computes a Mixture of Experts (MoE) layer using two sets of
|
633
|
-
weights, w1 and w2, and top-k gating mechanism.
|
634
|
-
|
635
|
-
Parameters:
|
636
|
-
- hidden_states (torch.Tensor): The input tensor to the MoE layer.
|
637
|
-
- w1 (torch.Tensor): The first set of expert weights.
|
638
|
-
- w2 (torch.Tensor): The second set of expert weights.
|
639
|
-
- gating_output (torch.Tensor): The output of the gating operation
|
640
|
-
(before softmax).
|
641
|
-
- topk (int): The number of top-k experts to select.
|
642
|
-
- renormalize (bool): If True, renormalize the top-k weights to sum to 1.
|
643
|
-
- inplace (bool): If True, perform the operation in-place.
|
644
|
-
Defaults to False.
|
645
|
-
- override_config (Optional[Dict[str, Any]]): Optional override
|
646
|
-
for the kernel configuration.
|
647
|
-
- num_expert_group: Optional[int]: additional parameter for grouped_topk
|
648
|
-
- topk_group: Optional[int]: additional parameter for grouped_topk
|
649
|
-
- use_grouped_topk: If True, use grouped_topk instead of fused_topk
|
650
|
-
note: Deepseekv2 model uses grouped_topk
|
651
|
-
- use_fp8 (bool): If True, use fp8 arithmetic to compute the inner
|
652
|
-
products for w1 and w2. Defaults to False.
|
653
|
-
- w1_scale (Optional[torch.Tensor]): Optional scale to be used for
|
654
|
-
w1.
|
655
|
-
- w2_scale (Optional[torch.Tensor]): Optional scale to be used for
|
656
|
-
w2.
|
657
|
-
|
658
|
-
Returns:
|
659
|
-
- torch.Tensor: The output tensor after applying the MoE layer.
|
660
|
-
"""
|
661
|
-
# Check constraints.
|
662
|
-
assert gating_output.shape[1] == w1.shape[0], "Number of experts mismatch"
|
663
|
-
|
664
|
-
if use_grouped_topk:
|
665
|
-
assert num_expert_group is not None and topk_group is not None
|
666
|
-
topk_weights, topk_ids = grouped_topk(
|
667
|
-
hidden_states,
|
668
|
-
gating_output,
|
669
|
-
topk,
|
670
|
-
renormalize,
|
671
|
-
num_expert_group,
|
672
|
-
topk_group,
|
673
|
-
)
|
674
|
-
else:
|
675
|
-
topk_weights, topk_ids = fused_topk(
|
676
|
-
hidden_states, gating_output, topk, renormalize
|
677
|
-
)
|
678
|
-
|
679
|
-
return fused_experts(
|
680
|
-
hidden_states,
|
681
|
-
w1,
|
682
|
-
w2,
|
683
|
-
topk_weights,
|
684
|
-
topk_ids,
|
685
|
-
inplace=inplace,
|
686
|
-
override_config=override_config,
|
687
|
-
use_fp8=use_fp8,
|
688
|
-
w1_scale=w1_scale,
|
689
|
-
w2_scale=w2_scale,
|
690
|
-
a1_scale=a1_scale,
|
691
|
-
a2_scale=a2_scale,
|
692
|
-
)
|