| 1 | # SPDX-License-Identifier: Apache-2.0 |
| 2 | # SPDX-FileCopyrightText: Copyright contributors to the vLLM project |
| 3 | """Tests for miscellaneous utilities.""" |
| 4 | |
| 5 | import pytest |
| 6 | import torch |
| 7 | |
| 8 | from tests.kernels.utils import opcheck |
| 9 | from vllm.model_executor.layers.rotary_embedding import RotaryEmbedding |
| 10 | |
| 11 | |
| 12 | def rotary_embedding_opcheck( |
| 13 | rot, |
| 14 | positions: torch.Tensor, |
| 15 | query: torch.Tensor, |
| 16 | key: torch.Tensor | None = None, |
| 17 | ): |
| 18 | cos_sin_cache = rot.cos_sin_cache.to(query.device, dtype=query.dtype) |
| 19 | |
| 20 | # ops.rotary_embedding() is a in-place operation |
| 21 | # that updates the query and key tensors. |
| 22 | opcheck( |
| 23 | torch.ops._C.rotary_embedding, |
| 24 | (positions, query, key, rot.head_size, cos_sin_cache, rot.is_neox_style), |
| 25 | ) |
| 26 | |
| 27 | |
| 28 | @pytest.mark.parametrize("device", ["cuda"]) |
| 29 | @pytest.mark.parametrize("max_position", [11, 4096, 32768]) |
| 30 | @pytest.mark.parametrize("is_neox_style", [True, False]) |
| 31 | @pytest.mark.parametrize("rotary_dim", [32]) |
| 32 | @pytest.mark.parametrize("head_size", [32, 108]) |
| 33 | @pytest.mark.parametrize("seq_len", [11, 1024]) |
| 34 | @pytest.mark.parametrize("use_key", [True, False]) |
| 35 | @pytest.mark.parametrize("head_stride_is_contiguous", [True, False]) |
| 36 | @pytest.mark.parametrize("dtype", [torch.float32, torch.bfloat16]) |
| 37 | def test_rotary_embedding_opcheck( |
| 38 | default_vllm_config, |
| 39 | dist_init, |
| 40 | device, |
| 41 | max_position, |
| 42 | is_neox_style, |
| 43 | rotary_dim, |
| 44 | head_size, |
| 45 | seq_len, |
| 46 | use_key, |
| 47 | head_stride_is_contiguous, |
| 48 | dtype, |
| 49 | ): |
| 50 | batch_size = 1 |
| 51 | base = 10000 |
| 52 | num_heads = 7 |
| 53 | rot = RotaryEmbedding( |
| 54 | head_size, rotary_dim, max_position, base, is_neox_style, dtype |
| 55 | ) |
| 56 | |
| 57 | positions = torch.randint(0, max_position, (batch_size, seq_len), device=device) |
| 58 | head_stride = head_size + (64 if head_stride_is_contiguous else 0) |
| 59 | |
| 60 | query = torch.randn( |
| 61 | batch_size, seq_len, num_heads, head_stride, dtype=dtype, device=device |
| 62 | ) |
| 63 | key = torch.randn_like(query) if use_key else None |
| 64 | query = query[..., :head_size] |
| 65 | key = key[..., :head_size] if key is not None else None |
| 66 | |
| 67 | rotary_embedding_opcheck(rot, positions, query, key) |
| 68 | |
| 69 | # if we have a contiguous head stride, test the alternate |
| 70 | # [..., num_heads * head_dim] shape/layout |
| 71 | if head_stride_is_contiguous: |
| 72 | rotary_embedding_opcheck( |
| 73 | rot, |
| 74 | positions, |
| 75 | query.flatten(start_dim=-2), |
| 76 | key.flatten(start_dim=-2) if key is not None else None, |
| 77 | ) |