forked from ROCm/aiter
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_kvcache.py
More file actions
364 lines (338 loc) · 10.4 KB
/
Copy pathtest_kvcache.py
File metadata and controls
364 lines (338 loc) · 10.4 KB
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
28
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
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
145
146
147
148
149
150
151
152
153
154
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
193
194
195
196
197
198
199
200
201
202
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
244
245
246
247
248
249
250
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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
# SPDX-License-Identifier: MIT
# Copyright (C) 2024-2025, Advanced Micro Devices, Inc. All rights reserved.
import torch
import aiter
from aiter.test_common import checkAllclose, perftest, benchmark
from aiter import dtypes
from typing import Tuple
import argparse
import itertools
import pandas as pd
MAX_TOKEN_SUPPORTED = 16384
@perftest()
def run_torch(
key, value, k_cache, v_cache, slot_mapping, block_size, x, asm_layout, quantCfg={}
):
num_batch, num_tokens, num_heads, head_size = key.shape
num_blocks = k_cache.shape[0]
dtype = k_cache.dtype
device = k_cache.device
k_scale = None
v_scale = None
key = key.contiguous()
value = value.contiguous()
if quantCfg:
k_scale = quantCfg["k_scale"]
v_scale = quantCfg["v_scale"]
key, k_scale_ = aiter.pertoken_quant(key, quant_dtype=quantCfg["quant_dtype"])
k_scale_ = (
k_scale_.permute(0, 1, 3, 2)
.view(num_batch * num_tokens, num_heads)
.contiguous()
)
if asm_layout:
k_scale = k_scale.permute(0, 2, 1).contiguous().view(-1, num_heads)
k_scale[slot_mapping] = k_scale_
k_scale = (
k_scale.view(num_blocks, block_size, num_heads)
.permute(0, 2, 1)
.contiguous()
)
else:
k_scale = k_scale.permute(1, 0).contiguous()
k_scale[slot_mapping] = k_scale_
k_scale = k_scale.permute(1, 0).contiguous()
k_cache = k_cache.permute(0, 3, 1, 2, 4).contiguous().view(-1, num_heads, head_size)
k_cache[slot_mapping] = key.view(-1, num_heads, head_size)
k_cache = k_cache.view(
num_blocks, block_size, num_heads, head_size // x, x
).permute(0, 2, 3, 1, 4)
if quantCfg:
value, v_scale_ = aiter.pertoken_quant(
value, quant_dtype=quantCfg["quant_dtype"]
)
v_scale_ = (
v_scale_.permute(0, 1, 3, 2)
.view(num_batch * num_tokens, num_heads)
.contiguous()
)
if asm_layout:
v_scale = v_scale.permute(0, 2, 1).contiguous().view(-1, num_heads)
v_scale[slot_mapping] = v_scale_
v_scale = (
v_scale.view(num_blocks, block_size, num_heads)
.permute(0, 2, 1)
.contiguous()
)
else:
v_scale = v_scale.permute(1, 0).contiguous()
v_scale[slot_mapping] = v_scale_
v_scale = v_scale.permute(1, 0).contiguous()
if asm_layout:
v_cache = (
v_cache.permute(0, 2, 4, 1, 3).contiguous().view(-1, num_heads, head_size)
)
else:
v_cache = (
v_cache.permute(0, 3, 1, 2).contiguous().view(-1, num_heads, head_size)
)
v_cache[slot_mapping] = value.view(-1, num_heads, head_size)
if asm_layout:
v_cache = v_cache.view(
num_blocks, block_size // x, x, num_heads, head_size
).permute(0, 3, 1, 4, 2)
else:
# [num_blocks, num_heads, head_size, block_size]
v_cache = v_cache.view(num_blocks, block_size, num_heads, head_size).permute(
0, 2, 3, 1
)
return k_cache, v_cache, k_scale, v_scale
@perftest()
def run_aiter(
key, value, k_cache, v_cache, slot_mapping, block_size, x, asm_layout, quantCfg={}
):
if quantCfg:
k_scale = quantCfg["k_scale"]
v_scale = quantCfg["v_scale"]
aiter.reshape_and_cache_with_pertoken_quant(
key, value, k_cache, v_cache, k_scale, v_scale, slot_mapping, asm_layout
)
else:
k_scale = None
v_scale = None
aiter.reshape_and_cache(
key, value, k_cache, v_cache, slot_mapping, "auto", asm_layout=asm_layout
)
return k_cache, v_cache, k_scale, v_scale
@benchmark()
def test_reshape_and_cache(
ctx_lens: int,
bs: int,
num_heads: Tuple[int, int],
head_size: int,
block_size: int,
DType_KV: torch.dtype,
DType_KVCache: torch.dtype,
):
ret = {}
quantCfg = (
{}
if DType_KVCache in [dtypes.bf16, dtypes.fp16]
else {"quant_dtype": DType_KVCache}
)
asm_layout = True
qhead, kvhead = num_heads
num_blocks = (MAX_TOKEN_SUPPORTED + block_size - 1) // block_size
# num_blocks = (ctx_lens+1+block_size-1)//block_size
max_token_num_support = num_blocks * block_size
x = 16 // DType_KVCache.itemsize
if asm_layout:
k_cache_shape = (bs * num_blocks, kvhead, head_size // x, block_size, x)
v_cache_shape = (bs * num_blocks, kvhead, block_size // x, head_size, x)
kv_scale_shape = (bs * num_blocks, kvhead, block_size)
else:
k_cache_shape = (bs * num_blocks, kvhead, head_size // x, block_size, x)
v_cache_shape = (bs * num_blocks, kvhead, head_size, block_size)
kv_scale_shape = (kvhead, bs * max_token_num_support)
# ##################################################### prefill part
qkv = torch.randn(
bs * ctx_lens, qhead + 2 * kvhead, head_size, dtype=DType_KV, device="cuda"
)
_, key, value = torch.split(qkv, [qhead, kvhead, kvhead], dim=1)
device = key.device
k_cache = torch.empty(k_cache_shape, dtype=DType_KVCache, device=device)
v_cache = torch.empty(v_cache_shape, dtype=DType_KVCache, device=device)
if quantCfg:
k_scale = torch.empty(kv_scale_shape, device=key.device)
v_scale = torch.empty_like(k_scale)
quantCfg["k_scale"] = k_scale.clone()
quantCfg["v_scale"] = v_scale.clone()
slot_mapping = torch.tensor(
[
bsID * max_token_num_support + i
for bsID in range(bs)
for i in range(ctx_lens)
]
).cuda()
k_cache_ref = k_cache.clone()
v_cache_ref = v_cache.clone()
out_ref, us_ref = run_torch(
key.view(bs, ctx_lens, kvhead, head_size),
value.view(bs, ctx_lens, kvhead, head_size),
k_cache_ref,
v_cache_ref,
slot_mapping,
block_size,
x,
asm_layout,
quantCfg,
)
k_cache_a = k_cache.clone()
v_cache_a = v_cache.clone()
if quantCfg:
quantCfg["k_scale"] = k_scale.clone()
quantCfg["v_scale"] = v_scale.clone()
out_a, us_a = run_aiter(
key,
value,
k_cache_a,
v_cache_a,
slot_mapping,
block_size,
x,
asm_layout,
quantCfg,
)
ret["us_prefill"] = us_a
print(f"prefill part: ref vs aiter {us_ref:>8.2f}us vs {us_a:>8.2f}us")
names = ["k_cache", "v_cache", "k_scale", "v_scale"]
for i, el in enumerate(out_ref):
if el is None:
continue
checkAllclose(
el.to(dtypes.fp32),
out_a[i].to(dtypes.fp32),
msg=f"{names[i]} {el.shape}",
)
# ##################################################### decode part
qkv = torch.randn(bs, qhead + 2 * kvhead, head_size, dtype=DType_KV, device="cuda")
_, key, value = torch.split(qkv, [qhead, kvhead, kvhead], dim=1)
if quantCfg:
quantCfg["k_scale"] = k_scale.clone()
quantCfg["v_scale"] = v_scale.clone()
slot_mapping = torch.tensor(
[bsID * max_token_num_support + ctx_lens for bsID in range(bs)]
).cuda()
k_cache_ref = k_cache.clone()
v_cache_ref = v_cache.clone()
out_ref, us_ref = run_torch(
key.view(bs, 1, kvhead, head_size),
value.view(bs, 1, kvhead, head_size),
k_cache_ref,
v_cache_ref,
slot_mapping,
block_size,
x,
asm_layout,
quantCfg,
)
k_cache_a = k_cache.clone()
v_cache_a = v_cache.clone()
if quantCfg:
quantCfg["k_scale"] = k_scale.clone()
quantCfg["v_scale"] = v_scale.clone()
out_a, us_a = run_aiter(
key,
value,
k_cache_a,
v_cache_a,
slot_mapping,
block_size,
x,
asm_layout,
quantCfg,
)
ret["us_decode"] = us_a
print(f"decode part: ref vs aiter {us_ref:>8.2f}us vs {us_a:>8.2f}us")
names = ["k_cache", "v_cache", "k_scale", "v_scale"]
for i, el in enumerate(out_ref):
if el is None:
continue
checkAllclose(
el.to(dtypes.fp32),
out_a[i].to(dtypes.fp32),
msg=f"{names[i]} {el.shape}",
)
print(
f"finish test {ctx_lens=} {bs=} {num_heads=} {head_size=} {block_size=} {DType_KV=} {DType_KVCache=}"
)
return ret
parser = argparse.ArgumentParser(
formatter_class=argparse.RawTextHelpFormatter,
description="Test different data types of quant.",
)
parser.add_argument(
"-t",
"--test",
type=str,
choices=["bf16tobf16", "fp16tofp8", "fp16toi8", "bf16toi8"],
default=["bf16tobf16", "fp16tofp8", "fp16toi8", "bf16toi8"],
nargs="*",
help="""select which test to run, default is all
e.g.: -t fp16tofp8""",
)
parser.add_argument(
"-b",
"--batch_size",
type=int,
nargs="*",
default=[64, 128, 257],
help="""Batch size. Default is 2.
e.g.: -b 16""",
)
parser.add_argument(
"-c",
"--ctx",
type=int,
nargs="*",
default=[4097, 12800],
help="""num of context lenth.
e.g.: -c 32""",
)
args = parser.parse_args()
df = []
for (
test,
bs,
ctx,
) in itertools.product(args.test, args.batch_size, args.ctx):
if test == "bf16tobf16":
print("\nstart quant bf16->bf16")
ret = test_reshape_and_cache(
ctx,
bs,
(8, 1),
128,
16,
dtypes.bf16,
dtypes.bf16,
)
elif test == "fp16tofp8":
print("\nstart quant fp16->fp8")
ret = test_reshape_and_cache(
ctx,
bs,
(8, 1),
128,
16,
dtypes.fp16,
dtypes.fp8,
)
elif test == "fp16toi8":
print("\nstart quant fp16->i8")
ret = test_reshape_and_cache(
ctx,
bs,
(8, 1),
128,
16,
dtypes.fp16,
dtypes.i8,
)
elif test == "bf16toi8":
print("\nstart quant bf16->i8")
ret = test_reshape_and_cache(
ctx,
bs,
(10, 1),
128,
16,
dtypes.bf16,
dtypes.i8,
)
else:
raise ValueError(f"Unknown test type: {test}")
df.append(ret)
df = pd.DataFrame(df)
df_md = df.to_markdown(index=False)
aiter.logger.info("kvcache summary (markdown):\n%s", df_md)