cache.py 1.8 KB
Newer Older
Woosuk Kwon's avatar
Woosuk Kwon committed
1
2
3
4
import random

import torch

5
from cacheflow import cache_ops
Woosuk Kwon's avatar
Woosuk Kwon committed
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28


def test_reshape_and_cache(
    num_tokens: int,
    num_heads: int,
    head_size: int,
    block_size: int,
    num_blocks: int,
    dtype: torch.dtype,
) -> None:
    num_slots = block_size * num_blocks
    slot_mapping = random.sample(range(num_slots), num_tokens)
    slot_mapping = torch.tensor(slot_mapping, dtype=torch.int, device='cuda')

    kv_shape = (num_tokens, num_heads, head_size)
    key = torch.randn(size=kv_shape, dtype=dtype, device='cuda')
    value = torch.randn(size=kv_shape, dtype=dtype, device='cuda')
    
    x = 16 // torch.tensor([], dtype=dtype).element_size()
    key_cache_shape = (num_blocks, num_heads, head_size // x, block_size, x)
    key_cache = torch.randn(size=key_cache_shape, dtype=dtype, device='cuda')
    cloned_key_cache = key_cache.clone()

29
    value_cache_shape = (num_blocks, num_heads, head_size, block_size)
Woosuk Kwon's avatar
Woosuk Kwon committed
30
31
32
33
    value_cache = torch.randn(
        size=value_cache_shape, dtype=dtype, device='cuda')
    cloned_value_cache = value_cache.clone()

34
    cache_ops.reshape_and_cache(key, value, key_cache, value_cache, slot_mapping)
Woosuk Kwon's avatar
Woosuk Kwon committed
35
36
37
38
39
40

    for i in range(num_tokens):
        reshaped_key = key.reshape(num_tokens, num_heads, head_size // x, x)
        block_idx = slot_mapping[i] // block_size
        block_offset = slot_mapping[i] % block_size
        cloned_key_cache[block_idx, :, :, block_offset, :] = reshaped_key[i]
41
        cloned_value_cache[block_idx, :, :, block_offset] = value[i]
Woosuk Kwon's avatar
Woosuk Kwon committed
42
43
44
45
46

    assert torch.allclose(key_cache, cloned_key_cache)
    assert torch.allclose(value_cache, cloned_value_cache)


47
48
@torch.inference_mode()
def test_cache() -> None:
Woosuk Kwon's avatar
Woosuk Kwon committed
49
    test_reshape_and_cache(
50
        num_tokens=3, num_heads=2, head_size=16, block_size=8, num_blocks=2,
Woosuk Kwon's avatar
Woosuk Kwon committed
51
52
53
54
        dtype=torch.half)


if __name__ == '__main__':
55
    test_cache()