| 1 | # SPDX-License-Identifier: Apache-2.0 |
| 2 | # SPDX-FileCopyrightText: Copyright contributors to the vLLM project |
| 3 | |
| 4 | import pytest |
| 5 | import torch |
| 6 | |
| 7 | from vllm.v1.kv_cache_interface import FullAttentionSpec, KVCacheGroupSpec |
| 8 | from vllm.v1.worker.utils import add_kv_sharing_layers_to_kv_cache_groups |
| 9 | |
| 10 | pytestmark = pytest.mark.cpu_test |
| 11 | |
| 12 | |
| 13 | def new_kv_cache_spec(): |
| 14 | return FullAttentionSpec( |
| 15 | block_size=16, num_kv_heads=1, head_size=1, dtype=torch.float32 |
| 16 | ) |
| 17 | |
| 18 | |
| 19 | def test_initialize_kv_cache_for_kv_sharing_same_attn_groups(): |
| 20 | """Test case assuming that all layers in the same KV cache group have the same |
| 21 | attention backends. This is true for most models. |
| 22 | """ |
| 23 | shared_kv_cache_layers = { |
| 24 | "model.layers.2": "model.layers.0", |
| 25 | "model.layers.3": "model.layers.1", |
| 26 | } |
| 27 | |
| 28 | kv_cache_groups = [ |
| 29 | KVCacheGroupSpec(["model.layers.0", "model.layers.1"], new_kv_cache_spec()), |
| 30 | ] |
| 31 | |
| 32 | add_kv_sharing_layers_to_kv_cache_groups( |
| 33 | shared_kv_cache_layers=shared_kv_cache_layers, |
| 34 | kv_cache_groups=kv_cache_groups, |
| 35 | ) |
| 36 | |
| 37 | # Check that the layers were added to the correct KV cache group |
| 38 | assert len(kv_cache_groups) == 1 |
| 39 | assert kv_cache_groups[0].layer_names == [ |
| 40 | "model.layers.0", |
| 41 | "model.layers.1", |
| 42 | "model.layers.2", |
| 43 | "model.layers.3", |
| 44 | ] |
| 45 | |
| 46 | |
| 47 | def test_initialize_kv_cache_for_kv_sharing_no_attn_groups(): |
| 48 | """Test KV sharing set up when no attention groups are provided. |
| 49 | This is the case for the TPU model runner, which doesn't have |
| 50 | support for attention groups yet. |
| 51 | """ |
| 52 | shared_kv_cache_layers = { |
| 53 | "model.layers.2": "model.layers.0", |
| 54 | "model.layers.3": "model.layers.1", |
| 55 | } |
| 56 | |
| 57 | kv_cache_groups = [ |
| 58 | KVCacheGroupSpec(["model.layers.0"], new_kv_cache_spec()), |
| 59 | KVCacheGroupSpec(["model.layers.1"], new_kv_cache_spec()), |
| 60 | ] |
| 61 | |
| 62 | add_kv_sharing_layers_to_kv_cache_groups( |
| 63 | shared_kv_cache_layers=shared_kv_cache_layers, |
| 64 | kv_cache_groups=kv_cache_groups, |
| 65 | ) |
| 66 | |
| 67 | # Check that the layers were added to the correct KV cache group |
| 68 | assert len(kv_cache_groups) == 2 |
| 69 | assert kv_cache_groups[0].layer_names == ["model.layers.0", "model.layers.2"] |
| 70 | assert kv_cache_groups[1].layer_names == ["model.layers.1", "model.layers.3"] |