benchmark_moe.py 28.6 KB
Newer Older
1
# SPDX-License-Identifier: Apache-2.0
2
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3

4
import argparse
5
import json
6
import time
7
from contextlib import nullcontext
8
from datetime import datetime
9
from itertools import product
10
from typing import Any, TypedDict, Optional
11
12
13
14
15
16

import ray
import torch
from ray.experimental.tqdm_ray import tqdm

from vllm.model_executor.layers.fused_moe.fused_moe import *
17
from vllm.transformers_utils.config import get_config
18
from vllm.triton_utils import triton
19
from vllm.utils import FlexibleArgumentParser
20

21
22
# 移除全局的 current_platform 导入,改为在需要时局部导入
# FP8_DTYPE = current_platform.fp8_dtype()
23
24


25
26
27
28
29
30
31
class BenchmarkConfig(TypedDict):
    BLOCK_SIZE_M: int
    BLOCK_SIZE_N: int
    BLOCK_SIZE_K: int
    GROUP_SIZE_M: int
    num_warps: int
    num_stages: int
zhuwenwen's avatar
zhuwenwen committed
32
    num_ldmatrixes: Optional[int]
33
34


35
36
37
38
39
40
41
42
43
44
45
def benchmark_config(
    config: BenchmarkConfig,
    num_tokens: int,
    num_experts: int,
    shard_intermediate_size: int,
    hidden_size: int,
    topk: int,
    dtype: torch.dtype,
    use_fp8_w8a8: bool,
    use_int8_w8a16: bool,
    num_iters: int = 100,
46
    block_quant_shape: list[int] = None,
47
    use_deep_gemm: bool = False,
zhuwenwen's avatar
zhuwenwen committed
48
    nn_moe: Optional[bool] = False
49
) -> float:
50
51
52
    from vllm.platforms import current_platform
    device = torch.cuda.current_device()

53
    init_dtype = torch.float16 if use_fp8_w8a8 else dtype
54
    x = torch.randn(num_tokens, hidden_size, dtype=dtype, device=device)
55
    if use_int8_w8a16:
zhuwenwen's avatar
zhuwenwen committed
56
        if not nn_moe:
zhuwenwen's avatar
zhuwenwen committed
57
58
59
60
61
62
63
64
65
            w1 = torch.randint(
                -127,
                127,
                (
                    num_experts,
                    shard_intermediate_size,
                    hidden_size,
                ),
                dtype=torch.int8,
66
                device=device,
zhuwenwen's avatar
zhuwenwen committed
67
68
69
70
71
72
73
74
75
76
            )
            w2 = torch.randint(
                -127,
                127,
                (
                    num_experts,
                    hidden_size,
                    shard_intermediate_size // 2,
                ),
                dtype=torch.int8,
77
                device=device,
zhuwenwen's avatar
zhuwenwen committed
78
            )
zhuwenwen's avatar
zhuwenwen committed
79
        else:
zhuwenwen's avatar
zhuwenwen committed
80
81
82
83
84
85
86
87
88
            w1 = torch.randint(
                -127,
                127,
                (
                    num_experts,
                    hidden_size,
                    shard_intermediate_size,
                ),
                dtype=torch.int8,
89
                device=device,
zhuwenwen's avatar
zhuwenwen committed
90
91
92
93
94
95
96
97
98
99
            )
            w2 = torch.randint(
                -127,
                127,
                (
                    num_experts,
                    shard_intermediate_size // 2,
                    hidden_size,
                ),
                dtype=torch.int8,
100
                device=device,
zhuwenwen's avatar
zhuwenwen committed
101
            )
102
    else:
zhuwenwen's avatar
zhuwenwen committed
103
        if not nn_moe:
zhuwenwen's avatar
zhuwenwen committed
104
            w1 = torch.randn(
105
                num_experts, shard_intermediate_size, hidden_size, dtype=init_dtype, device=device
zhuwenwen's avatar
zhuwenwen committed
106
107
            )
            w2 = torch.randn(
108
                num_experts, hidden_size, shard_intermediate_size // 2, dtype=init_dtype, device=device
zhuwenwen's avatar
zhuwenwen committed
109
            )
zhuwenwen's avatar
zhuwenwen committed
110
        else:
zhuwenwen's avatar
zhuwenwen committed
111
            w1 = torch.randn(
112
                num_experts, hidden_size, shard_intermediate_size, dtype=init_dtype, device=device
zhuwenwen's avatar
zhuwenwen committed
113
114
            )
            w2 = torch.randn(
115
                num_experts, shard_intermediate_size // 2, hidden_size, dtype=init_dtype, device=device
zhuwenwen's avatar
zhuwenwen committed
116
            )
117
    gating_output = torch.randn(num_iters, num_tokens, num_experts, dtype=torch.float32, device=device)
118
119
120
121
122

    w1_scale = None
    w2_scale = None
    a1_scale = None
    a2_scale = None
123
    if use_int8_w8a16:
124
        w1_scale = torch.randn(
125
            (num_experts, 2 * shard_intermediate_size), dtype=torch.float32, device=device
126
        )
127
        w2_scale = torch.randn((hidden_size, num_experts), dtype=torch.float32, device=device)
128
129
130
    if use_deep_gemm:
        # we use the default block shape for deepgemm
        block_quant_shape = [128, 128]
131
    if use_fp8_w8a8:
132
133
134
135
136
137
138
139
140
141
        if block_quant_shape:
            block_n, block_k = block_quant_shape[0], block_quant_shape[1]
            E = num_experts
            N = shard_intermediate_size // 2
            K = hidden_size
            factor_for_scale = 1e-2
            n_tiles_w1 = (2 * N + block_n - 1) // block_n
            n_tiles_w2 = (K + block_n - 1) // block_n
            k_tiles_w1 = (K + block_k - 1) // block_k
            k_tiles_w2 = (N + block_k - 1) // block_k
142
            w1_scale = (
143
                torch.rand((E, n_tiles_w1, k_tiles_w1), dtype=torch.float32, device=device)
144
145
146
                * factor_for_scale
            )
            w2_scale = (
147
                torch.rand((E, n_tiles_w2, k_tiles_w2), dtype=torch.float32, device=device)
148
149
                * factor_for_scale
            )
150
        else:
151
152
            w1_scale = torch.randn(num_experts, dtype=torch.float32, device=device)
            w2_scale = torch.randn(num_experts, dtype=torch.float32, device=device)
153

154
155
        a1_scale = torch.randn(1, dtype=torch.float32, device=device)
        a2_scale = torch.randn(1, dtype=torch.float32, device=device)
156

157
158
        # 获取 FP8_DTYPE
        FP8_DTYPE = current_platform.fp8_dtype()
159
160
        w1 = w1.to(FP8_DTYPE)
        w2 = w2.to(FP8_DTYPE)
161

162
    input_gating = torch.empty(num_tokens, num_experts, dtype=torch.float32, device=device)
163
164
165
166
167

    def prepare(i: int):
        input_gating.copy_(gating_output[i])

    def run():
168
        from vllm.model_executor.layers.fused_moe import override_config
169

170
        with override_config(config):
171
            if use_deep_gemm:
172
                topk_weights, topk_ids, token_expert_indices = fused_topk(
173
174
                    x, input_gating, topk, False
                )
175
176
177
178
179
180
181
182
183
184
185
186
187
188
                return fused_experts(
                    x,
                    w1,
                    w2,
                    topk_weights,
                    topk_ids,
                    inplace=True,
                    use_fp8_w8a8=use_fp8_w8a8,
                    w1_scale=w1_scale,
                    w2_scale=w2_scale,
                    a1_scale=a1_scale,
                    a2_scale=a2_scale,
                    block_shape=block_quant_shape,
                    allow_deep_gemm=True,
zhuwenwen's avatar
zhuwenwen committed
189
                    use_nn_moe=nn_moe,
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
                )
            else:
                fused_moe(
                    x,
                    w1,
                    w2,
                    input_gating,
                    topk,
                    renormalize=True,
                    inplace=True,
                    use_fp8_w8a8=use_fp8_w8a8,
                    use_int8_w8a16=use_int8_w8a16,
                    w1_scale=w1_scale,
                    w2_scale=w2_scale,
                    a1_scale=a1_scale,
                    a2_scale=a2_scale,
                    block_shape=block_quant_shape,
zhuwenwen's avatar
zhuwenwen committed
207
                    use_nn_moe=nn_moe,
208
                )
209
210
211
212
213
214

    # JIT compilation & warmup
    run()
    torch.cuda.synchronize()

    # Capture 10 invocations with CUDA graph
215
216
217
218
219
    graph = torch.cuda.CUDAGraph()
    with torch.cuda.graph(graph):
        for _ in range(10):
            run()
    torch.cuda.synchronize()
220
221
222

    # Warmup
    for _ in range(5):
223
224
        graph.replay()
        # run()
225
226
227
228
229
    torch.cuda.synchronize()

    start_event = torch.cuda.Event(enable_timing=True)
    end_event = torch.cuda.Event(enable_timing=True)

230
    latencies: list[float] = []
231
232
233
234
235
    for i in range(num_iters):
        prepare(i)
        torch.cuda.synchronize()

        start_event.record()
236
237
        graph.replay()
        # run()
238
239
240
241
        end_event.record()
        end_event.synchronize()
        latencies.append(start_event.elapsed_time(end_event))
    avg = sum(latencies) / (num_iters * 10) * 1000  # us
242
    graph.reset()
243
244
245
    return avg


zhuwenwen's avatar
zhuwenwen committed
246
def get_rocm_tuning_space(use_fp16, nn_moe: Optional[bool] = False):
247
248
    block_m_range = [16, 32, 64, 128, 256]
    block_n_range = [32, 64, 128, 256]
249
    block_k_range = [32, 64, 128, 256]
250
251
    if not use_fp16:
        block_k_range.remove(16)  # BLOCK_K=16 not supported for fp8
252
253
254
255
256
257
    num_warps_range = [2, 4, 8]
    group_m_range = [1, 16, 32, 64]
    num_stage_range = [2, 3, 4, 5]
    # waves_per_eu_range = [0]
    # matrix_instr_nonkdim_range = [16, 32] if use_fp16 else []
    # kpack_range = [1, 2] if use_fp16 else []
258
259

    param_ranges = {
260
261
        "BLOCK_SIZE_M": block_m_range,
        "BLOCK_SIZE_N": block_n_range,
262
263
264
265
        "BLOCK_SIZE_K": block_k_range,
        "GROUP_SIZE_M": group_m_range,
        "num_warps": num_warps_range,
        "num_stages": num_stage_range,
266
        # "waves_per_eu": waves_per_eu_range,
267
    }
zhuwenwen's avatar
zhuwenwen committed
268
    if nn_moe:
269
270
271
272
273
274
        param_ranges["num_ldmatrixes"] = [1]
    
    # DCU currently does not support the following parameters
    # if use_fp16:
    #     param_ranges["matrix_instr_nonkdim"] = matrix_instr_nonkdim_range
    #     param_ranges["kpack"] = kpack_range
275
276
277
278

    return param_ranges


zhuwenwen's avatar
zhuwenwen committed
279
def get_configs_compute_bound(use_fp16, block_quant_shape, nn_moe: Optional[bool] = False) -> list[dict[str, int]]:
280
    configs: list[BenchmarkConfig] = []
281
282
283
    
    # 局部导入 current_platform
    from vllm.platforms import current_platform
284
285

    if current_platform.is_rocm():
zhuwenwen's avatar
zhuwenwen committed
286
        param_ranges = get_rocm_tuning_space(use_fp16, nn_moe)
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
    else:
        # Reduced search space for faster tuning.
        # TODO(woosuk): Increase the search space and use a performance model to
        # prune the search space.
        block_m_range = [16, 32, 64, 128, 256]
        block_n_range = [32, 64, 128, 256]
        block_k_range = [64, 128, 256]
        num_warps_range = [4, 8]
        group_m_range = [1, 16, 32, 64]
        num_stage_range = [2, 3, 4, 5]

        param_ranges = {
            "BLOCK_SIZE_M": block_m_range,
            "BLOCK_SIZE_N": block_n_range,
            "BLOCK_SIZE_K": block_k_range,
            "GROUP_SIZE_M": group_m_range,
            "num_warps": num_warps_range,
            "num_stages": num_stage_range,
        }

    keys, values = zip(*param_ranges.items())
    for config_values in product(*values):
        config = dict(zip(keys, config_values))
        configs.append(config)
311
312
313
314
315
316
317

    # Remove configs that are not compatible with fp8 block quantization
    # BLOCK_SIZE_K must be a multiple of block_k
    # BLOCK_SIZE_N must be a multiple of block_n
    if block_quant_shape is not None and not use_fp16:
        block_n, block_k = block_quant_shape[0], block_quant_shape[1]
        for config in configs[:]:
318
319
320
321
            if (
                config["BLOCK_SIZE_K"] % block_k != 0
                or config["BLOCK_SIZE_N"] % block_n != 0
            ):
322
                configs.remove(config)
323
324
325
    return configs


326
327
328
def prune_rocm_search_space(
    num_tokens, shard_intermediate_size, hidden_size, search_space, is_fp16, topk
):
329
330
    N1, K1 = shard_intermediate_size, hidden_size
    N2, K2 = hidden_size, shard_intermediate_size // 2
331
332
333
334
335
336
    pruned_space_1 = prune_rocm_configs(
        num_tokens * topk, N1, K1, search_space, is_fp16
    )
    pruned_space_2 = prune_rocm_configs(
        num_tokens * topk, N2, K2, search_space, is_fp16
    )
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
    search_space = merge_unique_dicts(pruned_space_1, pruned_space_2)
    return search_space


# The following code is inspired by ROCm/Triton GEMM tuning script:
# https://github.com/ROCm/triton/blob/triton-mlir/scripts/amd/gemm/tune_gemm.py#L89
def prune_rocm_configs(M, N, K, configs, is_fp16=True):
    pruned_configs = []
    elemBytes_a = 2 if is_fp16 else 1
    elemBytes_b = 2 if is_fp16 else 1

    mfma = 16 if M < 32 or N < 32 else 32

    # TODO (zhanglx): figure out the boundary between large and small gemms
    large_gemm = False
    if M >= 2048 and N >= 2048:
        large_gemm = True

    for config in configs:
        BLOCK_SIZE_M = config.get("BLOCK_SIZE_M")
        BLOCK_SIZE_N = config.get("BLOCK_SIZE_N")
        BLOCK_SIZE_K = config.get("BLOCK_SIZE_K")
        num_warps = config.get("num_warps")

361
362
363
364
365
        # DCU currently does not support matrix_instr_nonkdim param
        # if is_fp16:
        #     matrix_instr_nonkdim = config.get("matrix_instr_nonkdim")
        #     if matrix_instr_nonkdim > mfma:
        #         continue
366
367
368
369
370
371
372
373
        if mfma == 4 and BLOCK_SIZE_K < 64:
            continue
        # some layouts could not work properly in case
        # number elements per thread is less 1
        if BLOCK_SIZE_M * BLOCK_SIZE_N < 64:
            continue
        SPLIT_K = config.get("SPLIT_K", 1)
        GROUP_M = config.get("GROUP_SIZE_M")
374
375
376

        # DCU currently does not support matrix_instr_nonkdim param
        # if is_fp16:
zhuwenwen's avatar
zhuwenwen committed
377
378
379
380
        #     if (
        #         matrix_instr_nonkdim > BLOCK_SIZE_M
        #         or matrix_instr_nonkdim > BLOCK_SIZE_N
        #     ):
381
        #         continue
zhuwenwen's avatar
zhuwenwen committed
382
        #     if matrix_instr_nonkdim >= M and matrix_instr_nonkdim != BLOCK_SIZE_M:
383
        #         continue
zhuwenwen's avatar
zhuwenwen committed
384
        #     if matrix_instr_nonkdim >= N and matrix_instr_nonkdim != BLOCK_SIZE_N:
385
        #         continue
zhuwenwen's avatar
zhuwenwen committed
386
        
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
        # Skip BLOCK_SIZE that is too large compare to M/N
        # unless BLOCK_SIZE is already small enough
        if M * 2 < BLOCK_SIZE_M and BLOCK_SIZE_M != 16:
            continue
        if N * 2 < BLOCK_SIZE_N and BLOCK_SIZE_N != 16:
            continue
        # skip large split_k when not necessary
        if SPLIT_K != 1 and not need_split_k(M, N, K):
            continue
        # skip split_k that leads to EVEN_K = false
        leap = SPLIT_K * BLOCK_SIZE_K
        modv = K % leap
        if modv != 0:
            continue
        # skip large GROUP_M
        if GROUP_M * BLOCK_SIZE_M > M and GROUP_M != 1:
            continue
        # out of shared memory resource
        # TODO (zhanglx): This does not consider the LDS usage in the epilogue
406
407
408
409
        LDS = (
            BLOCK_SIZE_K * BLOCK_SIZE_M * elemBytes_a
            + BLOCK_SIZE_K * BLOCK_SIZE_N * elemBytes_b
        )
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
        if LDS > 65536:
            continue
        # Skip small block sizes and num_warps for large gemm
        # For fp16 and f8, we want to only use BLOCK_SIZE >= 64
        if large_gemm:
            if BLOCK_SIZE_M < 64 or BLOCK_SIZE_N < 64:
                continue
            if BLOCK_SIZE_K < 64:
                continue
            if num_warps < 4:
                continue

        pruned_configs.append(config)

    return pruned_configs


def need_split_k(SIZE_M, SIZE_N, SIZE_K):
    return (SIZE_M < 64 or SIZE_N < 64) and SIZE_K > 1024


def merge_unique_dicts(list1, list2):
    result = []
    combined_list = list1.copy()
    combined_list.extend(list2)
    for dictionary in combined_list:
        if dictionary not in result:
            result.append(dictionary)
    return result


441
442
@ray.remote(num_gpus=1)
class BenchmarkWorker:
王敏's avatar
王敏 committed
443
    def __init__(self, seed: int, device_id: int) -> None:
444
445
446
447
448
449
450
451
452
        from vllm.platforms import current_platform
        import os
        
        if current_platform.is_rocm():
            # In ROCm environment with Ray, let Ray handle device assignment
            # Don't manually set default device as it may conflict with Ray's device mapping
            pass
        else:
            torch.set_default_device("cuda:"+ str(device_id))
453
        current_platform.seed_everything(seed)
454
        self.seed = seed
455
        # Store the logical device ID for Ray
王敏's avatar
王敏 committed
456
        self.device_id = device_id
457
458
459
460
461
462
463
464
465

    def benchmark(
        self,
        num_tokens: int,
        num_experts: int,
        shard_intermediate_size: int,
        hidden_size: int,
        topk: int,
        dtype: torch.dtype,
466
467
        use_fp8_w8a8: bool,
        use_int8_w8a16: bool,
468
        block_quant_shape: list[int] = None,
469
        use_deep_gemm: bool = False,
470
        nn_moe: Optional[bool] = False,
471
    ) -> tuple[dict[str, int], float]:
472
473
        # 局部导入 current_platform
        from vllm.platforms import current_platform
474
        current_platform.seed_everything(self.seed)
475
476
477
478
        from vllm.model_executor.layers.fused_moe.fused_moe import (
            get_config_dtype_str, get_moe_configs, get_default_config
        )

479
480
481
        dtype_str = get_config_dtype_str(
            dtype, use_int8_w8a16=use_int8_w8a16, use_fp8_w8a8=use_fp8_w8a8
        )
482
483
        # NOTE(woosuk): The current naming convention uses w2.shape[2], which
        # is the intermediate size after silu_and_mul.
484
        op_config = get_moe_configs(
zhuwenwen's avatar
zhuwenwen committed
485
            num_experts, shard_intermediate_size // 2, dtype_str, use_nn_moe=nn_moe
486
        )
487
        if op_config is None:
488
489
490
491
492
493
494
495
            config = get_default_config(
                num_tokens,
                num_experts,
                shard_intermediate_size,
                hidden_size,
                topk,
                dtype_str,
                is_marlin=False,
zhuwenwen's avatar
zhuwenwen committed
496
                use_nn_moe=nn_moe
497
            )
498
        else:
499
500
501
502
503
504
505
506
507
508
509
510
511
512
            config = op_config[min(op_config.keys(), key=lambda x: abs(x - num_tokens))]
        kernel_time = benchmark_config(
            config,
            num_tokens,
            num_experts,
            shard_intermediate_size,
            hidden_size,
            topk,
            dtype,
            use_fp8_w8a8,
            use_int8_w8a16,
            num_iters=100,
            block_quant_shape=block_quant_shape,
            use_deep_gemm=use_deep_gemm,
zhuwenwen's avatar
zhuwenwen committed
513
            use_nn_moe=nn_moe
514
        )
515
516
517
518
519
520
521
522
523
524
        return config, kernel_time

    def tune(
        self,
        num_tokens: int,
        num_experts: int,
        shard_intermediate_size: int,
        hidden_size: int,
        topk: int,
        dtype: torch.dtype,
525
526
        use_fp8_w8a8: bool,
        use_int8_w8a16: bool,
527
        search_space: list[dict[str, int]],
528
        block_quant_shape: list[int],
529
        use_deep_gemm: bool,
王敏's avatar
王敏 committed
530
        nn_moe: Optional[bool] = False,
531
    ) -> dict[str, int]:
532
533
534
        from vllm.platforms import current_platform
        import os

535
536
        best_config = None
        best_time = float("inf")
537
538
        if current_platform.is_rocm():
            is_fp16 = not (use_fp8_w8a8 or use_int8_w8a16)
539
540
541
542
543
544
545
546
            search_space = prune_rocm_search_space(
                num_tokens,
                shard_intermediate_size,
                hidden_size,
                search_space,
                is_fp16,
                topk,
            )
547

548
549
        # In ROCm environments with Ray, device context is already handled by Ray
        # Using torch.cuda.device() may cause device ordinal conflicts
550
551
        need_device_guard = False
        if current_platform.is_rocm():
552
553
554
555
556
557
            # For ROCm with Ray, skip additional device context management
            need_device_guard = False
        else:
            # For other platforms, use device guard if needed
            visible_devices = os.environ.get("CUDA_VISIBLE_DEVICES", None)
            if visible_devices is not None and len(visible_devices.split(',')) > 1:
558
                need_device_guard = True
559

560
        with torch.cuda.device(self.device_id) if need_device_guard else nullcontext():
561
562
            for config in tqdm(search_space):
                try:
563
564
565
566
567
568
569
570
571
572
573
                    kernel_time = benchmark_config(
                        config,
                        num_tokens,
                        num_experts,
                        shard_intermediate_size,
                        hidden_size,
                        topk,
                        dtype,
                        use_fp8_w8a8,
                        use_int8_w8a16,
                        num_iters=20,
zhuwenwen's avatar
zhuwenwen committed
574
                        block_quant_shape=block_quant_shape,
zhuwenwen's avatar
zhuwenwen committed
575
576
                        use_deep_gemm=use_deep_gemm,
                        nn_moe=nn_moe)
577
578
579
580
581
582
583
                except triton.runtime.autotuner.OutOfResources:
                    # Some configurations may be invalid and fail to compile.
                    continue

                if kernel_time < best_time:
                    best_time = kernel_time
                    best_config = config
584
585
        now = datetime.now()
        print(f"{now.ctime()}] Completed tuning for batch_size={num_tokens}")
586
        assert best_config is not None
587
588
589
        return best_config


590
def sort_config(config: BenchmarkConfig) -> BenchmarkConfig:
591
592

    return {
593
594
595
596
597
598
        "BLOCK_SIZE_M": config["BLOCK_SIZE_M"],
        "BLOCK_SIZE_N": config["BLOCK_SIZE_N"],
        "BLOCK_SIZE_K": config["BLOCK_SIZE_K"],
        "GROUP_SIZE_M": config["GROUP_SIZE_M"],
        "num_warps": config["num_warps"],
        "num_stages": config["num_stages"],
zhuwenwen's avatar
zhuwenwen committed
599
600
601
        **(
            {"num_ldmatrixes": config["num_ldmatrixes"]} if "num_ldmatrixes" in config else {}
        ),
602
603
604
605
606
607
608
609
610
        **(
            {"waves_per_eu": config["waves_per_eu"]} if "waves_per_eu" in config else {}
        ),
        **(
            {"matrix_instr_nonkdim": config["matrix_instr_nonkdim"]}
            if "matrix_instr_nonkdim" in config
            else {}
        ),
        **({"kpack": config["kpack"]} if "kpack" in config else {}),
611
612
613
    }


614
615
616
617
618
619
620
621
622
def save_configs(
    configs: dict[int, BenchmarkConfig],
    num_experts: int,
    shard_intermediate_size: int,
    hidden_size: int,
    topk: int,
    dtype: torch.dtype,
    use_fp8_w8a8: bool,
    use_int8_w8a16: bool,
623
    block_quant_shape: list[int],
zhuwenwen's avatar
zhuwenwen committed
624
    use_nn_moe: Optional[bool] = False,
625
) -> None:
626
627
628
629
    from vllm.model_executor.layers.fused_moe.fused_moe import (
        get_config_dtype_str, get_config_file_name
    )

630
631
632
    dtype_str = get_config_dtype_str(
        dtype, use_int8_w8a16=use_int8_w8a16, use_fp8_w8a8=use_fp8_w8a8
    )
633

634
635
    # NOTE(woosuk): The current naming convention uses w2.shape[2], which
    # is the intermediate size after silu_and_mul.
636
    filename = get_config_file_name(
zhuwenwen's avatar
zhuwenwen committed
637
        num_experts, shard_intermediate_size // 2, dtype_str, block_quant_shape, use_nn_moe=use_nn_moe
638
    )
639

640
641
642
643
644
645
    print(f"Writing best config to {filename}...")
    with open(filename, "w") as f:
        json.dump(configs, f, indent=4)
        f.write("\n")


646
def get_weight_block_size_safety(config, default_value=None):
647
    quantization_config = getattr(config, "quantization_config", {})
648
    if isinstance(quantization_config, dict):
649
        return quantization_config.get("weight_block_size", default_value)
650
651
652
    return default_value


653
def main(args: argparse.Namespace):
654
655
    import os
    import logging
656

657
658
659
660
    from vllm.platforms import current_platform
    
    logger = logging.getLogger(__name__)

661
    print(args)
zhuwenwen's avatar
zhuwenwen committed
662
    
王敏's avatar
王敏 committed
663
    tp_size = args.tp_size
664
    config = get_config(model=args.model, trust_remote_code=args.trust_remote_code)
665
666
    if args.model_prefix:
        config = getattr(config, args.model_prefix)
王敏's avatar
王敏 committed
667

668
669
670
671
    if config.architectures[0] == "DbrxForCausalLM":
        E = config.ffn_config.moe_num_experts
        topk = config.ffn_config.moe_top_k
        intermediate_size = config.ffn_config.ffn_hidden_size
王敏's avatar
王敏 committed
672
        shard_intermediate_size = 2 * intermediate_size // tp_size
673
674
675
676
    elif config.architectures[0] == "JambaForCausalLM":
        E = config.num_experts
        topk = config.num_experts_per_tok
        intermediate_size = config.intermediate_size
王敏's avatar
王敏 committed
677
        shard_intermediate_size = 2 * intermediate_size // tp_size
Yuxuan Zhang's avatar
Yuxuan Zhang committed
678
679
680
681
682
    elif config.architectures[0] in (
        "DeepseekV3ForCausalLM",
        "DeepseekV2ForCausalLM",
        "Glm4MoeForCausalLM",
    ):
683
        E = config.n_routed_experts
王敏's avatar
王敏 committed
684
685
686
        topk = config.num_experts_per_tok
        intermediate_size = config.moe_intermediate_size
        shard_intermediate_size = 2 * intermediate_size // tp_size
687
    elif config.architectures[0] in ("Qwen2MoeForCausalLM", "Qwen3MoeForCausalLM"):
王敏's avatar
王敏 committed
688
        E = config.num_experts
689
690
        topk = config.num_experts_per_tok
        intermediate_size = config.moe_intermediate_size
王敏's avatar
王敏 committed
691
        shard_intermediate_size = 2 * intermediate_size // tp_size
692
693
694
695
696
    elif config.architectures[0] in ("HunYuanMoEV1ForCausalLM"):
        E = config.num_experts
        topk = config.moe_topk[0]
        intermediate_size = config.moe_intermediate_size[0]
        shard_intermediate_size = 2 * intermediate_size // args.tp_size
zhuwenwen's avatar
zhuwenwen committed
697
698
699
700
701
    elif config.architectures[0] in ("Step3VLForConditionalGeneration"):
        E = config.text_config.moe_num_experts
        topk = config.text_config.moe_top_k
        intermediate_size = config.text_config.moe_intermediate_size
        shard_intermediate_size = 2 * intermediate_size // tp_size
702
    else:
703
704
        # Support for llama4
        config = config.get_text_config()
705
706
707
708
        # Default: Mixtral.
        E = config.num_local_experts
        topk = config.num_experts_per_tok
        intermediate_size = config.intermediate_size
王敏's avatar
王敏 committed
709
        shard_intermediate_size = 2 * intermediate_size // tp_size
710
711

    hidden_size = config.hidden_size
712
    dtype = torch.float16 if current_platform.is_rocm() else config.torch_dtype
713
714
    use_fp8_w8a8 = args.dtype == "fp8_w8a8"
    use_int8_w8a16 = args.dtype == "int8_w8a16"
715
    block_quant_shape = get_weight_block_size_safety(config)
716
717

    if args.batch_size is None:
718
        batch_sizes = [
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
            1,
            2,
            4,
            8,
            16,
            24,
            32,
            48,
            64,
            96,
            128,
            256,
            512,
            1024,
            1536,
            2048,
            3072,
            4096,
737
        ]
738
    else:
739
        batch_sizes = args.batch_size
740

741
742
    use_deep_gemm = bool(args.use_deep_gemm)

743
744
745
746
    if current_platform.is_rocm() and "HIP_VISIBLE_DEVICES" in os.environ:
        # Ray will set ROCR_VISIBLE_DEVICES for device visibility
        logger.warning(
            "Ray uses ROCR_VISIBLE_DEVICES to control device accessibility."
747
748
            "Replacing HIP_VISIBLE_DEVICES with ROCR_VISIBLE_DEVICES."
        )
749
750
751
752
        val = os.environ["HIP_VISIBLE_DEVICES"]
        os.environ["ROCR_VISIBLE_DEVICES"] = val
        del os.environ["HIP_VISIBLE_DEVICES"]

zhuwenwen's avatar
zhuwenwen committed
753
    ray.init(address=None, ignore_reinit_error=True, num_gpus=args.num_gpus)
754
    num_gpus = int(ray.available_resources()["GPU"])
王敏's avatar
王敏 committed
755
    workers = [BenchmarkWorker.remote(args.seed, i) for i in range(num_gpus)]
756

757
    def _distribute(method: str, inputs: list[Any]) -> list[Any]:
758
759
760
761
762
763
764
765
766
767
768
        outputs = []
        worker_idx = 0
        for input_args in inputs:
            worker = workers[worker_idx]
            worker_method = getattr(worker, method)
            output = worker_method.remote(*input_args)
            outputs.append(output)
            worker_idx = (worker_idx + 1) % num_gpus
        return ray.get(outputs)

    if args.tune:
769
        is_fp16 = not (use_fp8_w8a8 or use_int8_w8a16)
zhuwenwen's avatar
zhuwenwen committed
770
        search_space = get_configs_compute_bound(is_fp16, block_quant_shape, args.nn_moe)
771
772
773
774
        print(f"Start tuning over {len(search_space)} configurations...")

        start = time.time()
        configs = _distribute(
775
776
777
778
779
780
781
782
783
784
785
786
787
788
            "tune",
            [
                (
                    batch_size,
                    E,
                    shard_intermediate_size,
                    hidden_size,
                    topk,
                    dtype,
                    use_fp8_w8a8,
                    use_int8_w8a16,
                    search_space,
                    block_quant_shape,
                    use_deep_gemm,
zhuwenwen's avatar
zhuwenwen committed
789
                    args.nn_moe,
790
791
792
793
                )
                for batch_size in batch_sizes
            ],
        )
794
        best_configs = {
795
            M: sort_config(config) for M, config in zip(batch_sizes, configs)
796
        }
797
798
799
800
801
802
803
804
805
806
        save_configs(
            best_configs,
            E,
            shard_intermediate_size,
            hidden_size,
            topk,
            dtype,
            use_fp8_w8a8,
            use_int8_w8a16,
            block_quant_shape,
zhuwenwen's avatar
zhuwenwen committed
807
            use_nn_moe=args.nn_moe,
808
        )
809
810
811
        end = time.time()
        print(f"Tuning took {end - start:.2f} seconds")
    else:
812
        outputs = _distribute(
813
            "benchmark",
814
815
816
817
818
819
820
821
822
823
824
825
            [
                (
                    batch_size,
                    E,
                    shard_intermediate_size,
                    hidden_size,
                    topk,
                    dtype,
                    use_fp8_w8a8,
                    use_int8_w8a16,
                    block_quant_shape,
                    use_deep_gemm,
zhuwenwen's avatar
zhuwenwen committed
826
                    args.nn_moe,
827
828
829
830
                )
                for batch_size in batch_sizes
            ],
        )
831
832
833
834
835
836
837

        for batch_size, (config, kernel_time) in zip(batch_sizes, outputs):
            print(f"Batch size: {batch_size}, config: {config}")
            print(f"Kernel time: {kernel_time:.2f} us")


if __name__ == "__main__":
838
    parser = FlexibleArgumentParser()
839
840
841
842
843
844
845
846
847
    parser.add_argument(
        "--model", type=str, default="mistralai/Mixtral-8x7B-Instruct-v0.1"
    )
    parser.add_argument(
        "--tp-size", "-tp", "--tensor-parallel-size", type=int, default=2
    )
    parser.add_argument(
        "--dtype", type=str, choices=["auto", "fp8_w8a8", "int8_w8a16"], default="auto"
    )
848
    parser.add_argument("--use-deep-gemm", action="store_true")
849
    parser.add_argument("--seed", type=int, default=0)
850
    parser.add_argument("--batch-size", type=int, nargs="+", required=False)
851
    parser.add_argument("--tune", action="store_true")
王敏's avatar
王敏 committed
852
    parser.add_argument("--nn-moe", action='store_true', default=False)
853
    parser.add_argument("--trust-remote-code", action="store_true")
854
    parser.add_argument("--model-prefix", type=str, required=False)
王敏's avatar
王敏 committed
855
    parser.add_argument("--num-gpus", type=int, default=1)
856
857
858
    args = parser.parse_args()

    main(args)