attention_test.py 16.5 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import os
import time
import sys
import safetensors
import torch
from transformers import AutoConfig
from transformers import DynamicCache
from transformers.models import qwen3_moe

WARMUPS = 10
RUNS = 100
PREFILL_TESTCASES = {"seqlens": [64, 128, 256, 256], "pastlens": [512, 0, 0, 256]}

DECODE_TESTCASES = {
    "seqlens": [1 for _ in range(16)],
    "pastlens": [50 for _ in range(4)]
    + [100 for _ in range(4)]
    + [200 for _ in range(4)]
    + [400 for _ in range(4)],
}


def get_args():
    import argparse

    parser = argparse.ArgumentParser(description="Test Operator")
    parser.add_argument(
28
        "--model_path",
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
        action="store",
        help="The directory of the model to be tested",
    )

    parser.add_argument(
        "--cpu",
        action="store_true",
        help="Run cpu test",
    )

    parser.add_argument(
        "--nvidia",
        action="store_true",
        help="Run nvidia test",
    )

    parser.add_argument(
        "--metax",
        action="store_true",
        help="Run metax test",
    )
    parser.add_argument(
        "--moore",
        action="store_true",
        help="Run moore test",
    )
    parser.add_argument(
        "--iluvatar",
        action="store_true",
58
        help="Run iluvatar test",
59
60
61
62
    )
    return parser.parse_args()


63
64
65
66
67
68
69
70
71
72
73
74
75
76
def torch_synchronize(_device):
    if _device == "cuda":
        torch.cuda.synchronize()
    elif _device == "musa":
        torch.musa.synchronize()


def torch_empty_cache(_device):
    if _device == "cuda":
        torch.cuda.empty_cache()
    elif _device == "musa":
        torch.musa.empty_cache()


77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
def create_Qwen3attention_torch(dir_path, *, device, dtype=torch.bfloat16):
    config = AutoConfig.from_pretrained(dir_path)
    config.num_hidden_layers = 1
    config._attn_implementation = "sdpa"

    # --------------------------------------------------------------------------------#
    #                创建只包含 attention的模型
    # --------------------------------------------------------------------------------#
    model = qwen3_moe.modeling_qwen3_moe.Qwen3MoeAttention(config, layer_idx=0).to(
        device=device, dtype=dtype
    )
    tensors = {}
    for fname in sorted(os.listdir(dir_path)):
        if not fname.endswith(".safetensors"):
            continue
        fpath = os.path.join(dir_path, fname)
        with safetensors.safe_open(fpath, framework="pt") as f:
            for key in f.keys():
                if "model.layers.0.self_attn." in key:
                    tensors[key[len("model.layers.0.self_attn.") :]] = f.get_tensor(key)
        break
    model.load_state_dict(tensors)

    # --------------------------------------------------------------------------------#
    #                创建 rotary_emb 类
    # --------------------------------------------------------------------------------#
    rotary_emb = qwen3_moe.modeling_qwen3_moe.Qwen3MoeRotaryEmbedding(
        config, device=device
    )
    return model, rotary_emb


def generate_attention_input_torch(
    model, rotary_emb, testcase, device, dtype=torch.bfloat16
):
    config = model.config
    hidden_size = config.hidden_size  # 2048
    head_dim = config.head_dim  # 128
    num_key_value_heads = config.num_key_value_heads
    bs = 1

    req_list = []
    for seq_lens, past_lens in zip(testcase["seqlens"], testcase["pastlens"]):
        hidden_states = torch.rand(
            (bs, seq_lens, hidden_size), device=device, dtype=dtype
        )

        attention_mask = None

        past_key_values = DynamicCache(config=config)
        key_states = torch.rand(
            (bs, num_key_value_heads, past_lens, head_dim), device=device, dtype=dtype
        )
        value_states = torch.rand(
            (bs, num_key_value_heads, past_lens, head_dim), device=device, dtype=dtype
        )
        past_key_values.update(key_states, value_states, 0)

        req = {
            "hidden_states": hidden_states,
            "attention_mask": attention_mask,
            "past_key_values": past_key_values,
        }
        req_list.append(req)

    return req_list


145
146
147
def benchmark_Qwen3attention_prefill_torch(
    model, rotary_emb, test_cases, device, dtype=torch.bfloat16
):
148
149
150
151
    """
    Test Qwen3attention.

    """
152
153
154
    req_list = generate_attention_input_torch(
        model, rotary_emb, test_cases, device, dtype=dtype
    )
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
    req_out_list = []
    for req in req_list:
        # ----------------------------------------- #
        #         获得每个req的数据
        # ----------------------------------------- #
        hidden_states = req["hidden_states"]
        attention_mask = req["attention_mask"]
        past_key_values = req["past_key_values"]

        # ----------------------------------------- #
        #         计算当前所需的sin_table,sin_table
        # ----------------------------------------- #
        cache_lens = past_key_values.get_seq_length()  # kv cache 现在的长度
        bs, seq_len, _ = hidden_states.shape

        position_ids = torch.arange(
            cache_lens, cache_lens + seq_len, dtype=torch.int64, device=device
        ).reshape((bs, seq_len))

        cos_table, sin_table = rotary_emb(hidden_states, position_ids)
        position_embeddings = (sin_table, cos_table)

        # ----------------------------------------- #
        #            计算一次
        # ----------------------------------------- #
        output_device, _ = model(
            hidden_states=hidden_states,
            position_embeddings=position_embeddings,
            attention_mask=attention_mask,
            past_key_values=past_key_values,
        )

        # ----------------------------------------- #
        #            得到结果,存储下来
        # ----------------------------------------- #
        output_host = output_device.to("cpu")
        req_out_list.append(output_host)

193
    torch_synchronize(device)
194
195

    for _ in range(WARMUPS):
196
197
198
199
200
201
202
        for i, req in enumerate(req_list):
            # ----------------------------------------- #
            #          恢复 kv chche的长度
            # ----------------------------------------- #
            origin_len = test_cases["pastlens"][i]
            req["past_key_values"].crop(origin_len)

203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
        for req in req_list:
            # ----------------------------------------- #
            #         获得每个req的数据
            # ----------------------------------------- #

            hidden_states = req["hidden_states"]
            attention_mask = req["attention_mask"]
            past_key_values = req["past_key_values"]

            # ----------------------------------------- #
            #         计算当前所需的sin_table,sin_table
            # ----------------------------------------- #
            cache_lens = past_key_values.get_seq_length()  # kv cache 现在的长度
            bs, seq_len, _ = hidden_states.shape

            position_ids = torch.arange(
                cache_lens, cache_lens + seq_len, dtype=torch.int64, device=device
            ).reshape((bs, seq_len))

            cos_table, sin_table = rotary_emb(hidden_states, position_ids)
            position_embeddings = (sin_table, cos_table)

            # ----------------------------------------- #
            #            计算一次
            # ----------------------------------------- #
            output_device, _ = model(
                hidden_states,
                position_embeddings=position_embeddings,
                attention_mask=attention_mask,
                past_key_values=past_key_values,
            )

    time_consuming = 0
    for _ in range(RUNS):
        for i, req in enumerate(req_list):
            # ----------------------------------------- #
            #          恢复 kv chche的长度
            # ----------------------------------------- #
            origin_len = test_cases["pastlens"][i]
            req["past_key_values"].crop(origin_len)

244
        torch_synchronize(device)
245
246
247
248
        # ----------------------------------------- #
        #       重要:每个req都按整个batch的起始时间计算
        # ----------------------------------------- #
        start_time = time.time()
249

250
        for i, req in enumerate(req_list):
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
            # ----------------------------------------- #
            #         获得每个req的数据
            # ----------------------------------------- #
            hidden_states = req["hidden_states"]
            attention_mask = req["attention_mask"]
            past_key_values = req["past_key_values"]

            # ----------------------------------------- #
            #         计算当前所需的sin_table,sin_table
            # ----------------------------------------- #
            cache_lens = past_key_values.get_seq_length()  # kv cache 现在的长度
            bs, seq_len, _ = hidden_states.shape

            position_ids = torch.arange(
                cache_lens, cache_lens + seq_len, dtype=torch.int64, device=device
            ).reshape((bs, seq_len))

            cos_table, sin_table = rotary_emb(hidden_states, position_ids)
            position_embeddings = (sin_table, cos_table)

            # ----------------------------------------- #
            #            计算一次
            # ----------------------------------------- #
            output_device, _ = model(
                hidden_states,
                position_embeddings=position_embeddings,
                attention_mask=attention_mask,
                past_key_values=past_key_values,
            )

281
            torch_synchronize(device)
282
283
            end_time = time.time()

284
285
            # 记录每个req从进入所有req进入推理到自己结束的时间
            time_consuming += end_time - start_time
286
287
288

    out_token_count = RUNS * len(req_list)

289
    latency = time_consuming * 1000 / out_token_count
290
291

    print(
292
        f"\t WARMUPS={WARMUPS} RUNS={RUNS}, Attention Torch, average TTFT: {round(latency, 2)} ms\n"
293
294
295
296
297
    )

    return req_out_list


298
299
300
def benchmark_Qwen3attention_decode_torch(
    model, rotary_emb, test_cases, device, dtype=torch.bfloat16
):
301
302
303
    """
    Test Qwen3attention_decode.
    """
304
305
306
    req_list = generate_attention_input_torch(
        model, rotary_emb, test_cases, device, dtype=dtype
    )
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
    req_out_list = []
    for req in req_list:
        # ----------------------------------------- #
        #         获得每个req的数据
        # ----------------------------------------- #
        hidden_states = req["hidden_states"]
        attention_mask = req["attention_mask"]
        past_key_values = req["past_key_values"]

        # ----------------------------------------- #
        #         计算当前所需的sin_table,sin_table
        # ----------------------------------------- #
        cache_lens = past_key_values.get_seq_length()  # kv cache 现在的长度
        bs, seq_len, _ = hidden_states.shape

        position_ids = torch.arange(
            cache_lens, cache_lens + seq_len, dtype=torch.int64, device=device
        ).reshape((bs, seq_len))

        cos_table, sin_table = rotary_emb(hidden_states, position_ids)
        position_embeddings = (sin_table, cos_table)

        ##
        output_device, _ = model(
            hidden_states=hidden_states,
            position_embeddings=position_embeddings,
            attention_mask=attention_mask,
            past_key_values=past_key_values,
        )
        output_host = output_device.to("cpu")

        req_out_list.append(output_host)

340
    torch_synchronize(device)
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378

    for req in req_list:
        for _ in range(WARMUPS):
            hidden_states = req["hidden_states"]
            attention_mask = req["attention_mask"]
            past_key_values = req["past_key_values"]

            # ----------------------------------------- #
            #         计算当前所需的sin_table,sin_table
            # ----------------------------------------- #
            cache_lens = past_key_values.get_seq_length()  # kv cache 现在的长度
            bs, seq_len, _ = hidden_states.shape

            position_ids = torch.arange(
                cache_lens, cache_lens + seq_len, dtype=torch.int64, device=device
            ).reshape((bs, seq_len))

            cos_table, sin_table = rotary_emb(hidden_states, position_ids)
            position_embeddings = (sin_table, cos_table)

            # ----------------------------------------- #
            #            计算一次
            # ----------------------------------------- #

            output_device, _ = model(
                hidden_states,
                position_embeddings=position_embeddings,
                attention_mask=attention_mask,
                past_key_values=past_key_values,
            )

    # ----------------------------------------- #
    #          恢复 kv chche的长度
    # ----------------------------------------- #
    for i, req in enumerate(req_list):
        origin_len = test_cases["pastlens"][i]
        req["past_key_values"].crop(origin_len)

379
    torch_synchronize(device)
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
    start_time = time.time()

    for i, req in enumerate(req_list):
        for _ in range(RUNS):
            # ----------------------------------------- #
            #         获得每个req的数据
            # ----------------------------------------- #
            hidden_states = req["hidden_states"]
            attention_mask = req["attention_mask"]
            past_key_values = req["past_key_values"]

            # -------------------------------------------------------------- #
            #         计算当前所需的sin_table,sin_table
            # -------------------------------------------------------------- #
            cache_lens = past_key_values.get_seq_length()  # kv cache 现在的长度
            bs, seq_len, _ = hidden_states.shape

            position_ids = torch.arange(
                cache_lens, cache_lens + seq_len, dtype=torch.int64, device=device
            ).reshape((bs, seq_len))

            cos_table, sin_table = rotary_emb(hidden_states, position_ids)
            position_embeddings = (sin_table, cos_table)

            # -------------------------------------------------------------- #
            #            计算一次
            # -------------------------------------------------------------- #
            output_device, _ = model(
                hidden_states,
                position_embeddings=position_embeddings,
                attention_mask=attention_mask,
                past_key_values=past_key_values,
            )

            # -------------------------------------------------------------- #
            #            更新hidden_states, ( DynamicCache的类自动更新)
            # -------------------------------------------------------------- #
            req["hidden_states"] = output_device

419
    torch_synchronize(device)
420
421
422
423
424
425
426
427
    end_time = time.time()

    time_consuming = end_time - start_time
    out_token_count = RUNS * len(req_list)

    throughput = out_token_count / time_consuming

    print(
428
        f"\t WARMUPS={WARMUPS} RUNS={RUNS}, Attention Torch, average throughput: {round(throughput, 2)} tok/s \n"
429
430
431
432
433
434
435
436
437
    )

    return req_out_list


if __name__ == "__main__":
    args = get_args()
    print(args)

438
    model_path = args.model_path
439
440
441
442
443
444
445
446
447
448
449
450
    dtype = torch.bfloat16

    # Parse command line arguments
    device = "cpu"
    if args.cpu:
        device = "cpu"
    elif args.nvidia:
        device = "cuda"
    elif args.metax:
        device = "cuda"
    elif args.moore:
        device = "musa"
451
        import torch_musa
452
453
454
455
    elif args.iluvatar:
        device = "cuda"
    else:
        print(
456
            "Usage:  python test/models/qwen3_moe/attention_test.py [--cpu | --nvidia | --metax | --moore | --iluvatar] --model_path=<path/to/model_path>"
457
458
459
460
461
462
463
        )
        sys.exit(1)

    # -----------------------------------------------------------------------------
    # -----------------------------------------------------------------------------
    # -----------------------------------------------------------------------------
    model, rotary_emb = create_Qwen3attention_torch(
464
        model_path, device=device, dtype=dtype
465
466
467
468
469
470
471
    )
    print("\n")
    print("*" * 130)
    print("Test Qwen3attention ")
    print("*" * 130)
    print(f"Test Case PREFILL_TESTCASES : {PREFILL_TESTCASES}")
    output_prefill = benchmark_Qwen3attention_prefill_torch(
472
        model, rotary_emb, PREFILL_TESTCASES, device, dtype=dtype
473
474
475
476
477
478
    )

    print("\n")
    print("-" * 130)
    print(f"\nTest DECODE_TESTCASES: {DECODE_TESTCASES}")
    output_decode = benchmark_Qwen3attention_decode_torch(
479
        model, rotary_emb, DECODE_TESTCASES, device, dtype=dtype
480
481
482
483
    )

    # clean up device memory
    del model
484
    torch_empty_cache(device)