|
| 1 | +import random |
| 2 | +import time |
| 3 | +from typing import Optional |
| 4 | + |
| 5 | +import pytest |
| 6 | +import torch |
| 7 | + |
| 8 | +import flag_gems |
| 9 | + |
| 10 | +from . import accuracy_utils as utils |
| 11 | +from . import conftest as cfg |
| 12 | + |
| 13 | +random.seed(time.time() // 100) |
| 14 | + |
| 15 | + |
| 16 | +# Copied from transformers.models.llama.modeling_llama.rotate_half |
| 17 | +# https://github.com/huggingface/transformers/blob/main/src/transformers/models/llama/modeling_llama.py |
| 18 | +def rotate_half(x): |
| 19 | + """Rotates half the hidden dims of the input.""" |
| 20 | + x1 = x[..., : x.shape[-1] // 2] |
| 21 | + x2 = x[..., x.shape[-1] // 2 :] |
| 22 | + return torch.cat((-x2, x1), dim=-1) |
| 23 | + |
| 24 | + |
| 25 | +# Copied from transformers.models.cohere.modeling_cohere.rotate_half |
| 26 | +# https://github.com/huggingface/transformers/blob/main/src/transformers/models/cohere/modeling_cohere.py |
| 27 | +def rotate_interleave(x): |
| 28 | + """Rotates interleave the hidden dims of the input.""" |
| 29 | + x1 = x[..., ::2] |
| 30 | + x2 = x[..., 1::2] |
| 31 | + return torch.stack((-x2, x1), dim=-1).flatten(-2) |
| 32 | + |
| 33 | + |
| 34 | +def _torch_apply_rotary_pos_emb( |
| 35 | + q, |
| 36 | + k, |
| 37 | + cos, |
| 38 | + sin, |
| 39 | + position_ids: Optional[torch.Tensor] = None, |
| 40 | + rotary_interleaved: bool = False, |
| 41 | +): |
| 42 | + q = q.float() |
| 43 | + k = k.float() |
| 44 | + if position_ids is None: |
| 45 | + cos = cos[None, : q.size(-3), None, :] |
| 46 | + sin = sin[None, : q.size(-3), None, :] |
| 47 | + else: |
| 48 | + cos = cos[position_ids].unsqueeze(-2) # [bs, seq_len, 1, dim/2] |
| 49 | + sin = sin[position_ids].unsqueeze(-2) # [bs, seq_len, 1, dim/2] |
| 50 | + if rotary_interleaved: |
| 51 | + cos = torch.repeat_interleave(cos, 2, dim=-1) # [bs, seq_len, 1, dim] |
| 52 | + sin = torch.repeat_interleave(sin, 2, dim=-1) # [bs, seq_len, 1, dim] |
| 53 | + rotate_fn = rotate_interleave |
| 54 | + else: |
| 55 | + cos = torch.cat([cos, cos], dim=-1) # [bs, seq_len, 1, dim] |
| 56 | + sin = torch.cat([sin, sin], dim=-1) # [bs, seq_len, 1, dim] |
| 57 | + rotate_fn = rotate_half |
| 58 | + |
| 59 | + q_embed = (q * cos) + (rotate_fn(q) * sin) |
| 60 | + k_embed = (k * cos) + (rotate_fn(k) * sin) |
| 61 | + |
| 62 | + return q_embed, k_embed |
| 63 | + |
| 64 | + |
| 65 | +def _get_rope_cos_sin(max_seq_len, dim, dtype, base=10000, device=flag_gems.device): |
| 66 | + inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float().to(device) / dim)) |
| 67 | + t = torch.arange(max_seq_len, device=device, dtype=inv_freq.dtype) |
| 68 | + freqs = torch.outer(t, inv_freq) |
| 69 | + cos = freqs.cos().to(dtype) |
| 70 | + sin = freqs.sin().to(dtype) |
| 71 | + |
| 72 | + return cos, sin |
| 73 | + |
| 74 | + |
| 75 | +@pytest.mark.apply_rotary_pos_emb |
| 76 | +@pytest.mark.parametrize("batch_size", [2] if cfg.TO_CPU else [4, 8]) |
| 77 | +@pytest.mark.parametrize("max_seq_len", [16] if cfg.TO_CPU else [512, 2048]) |
| 78 | +@pytest.mark.parametrize("q_heads,k_heads", [(8, 1), (6, 2), (1, 1), (8, 8)]) |
| 79 | +@pytest.mark.parametrize("head_dim", [8] if cfg.TO_CPU else [64, 96, 128, 256]) |
| 80 | +@pytest.mark.parametrize("dtype", utils.FLOAT_DTYPES) |
| 81 | +@pytest.mark.parametrize("rotary_interleaved", [True, False]) |
| 82 | +@pytest.mark.parametrize("has_pos_id", [True, False]) |
| 83 | +def test_apply_rotary_pos_emb( |
| 84 | + batch_size, |
| 85 | + max_seq_len, |
| 86 | + q_heads, |
| 87 | + k_heads, |
| 88 | + head_dim, |
| 89 | + dtype, |
| 90 | + has_pos_id, |
| 91 | + rotary_interleaved, |
| 92 | +): |
| 93 | + seq_len = torch.randint(1, max_seq_len, (1,)).item() |
| 94 | + q = torch.randn( |
| 95 | + (batch_size, seq_len, q_heads, head_dim), dtype=dtype, device=flag_gems.device |
| 96 | + ) |
| 97 | + k = torch.randn( |
| 98 | + (batch_size, seq_len, k_heads, head_dim), dtype=dtype, device=flag_gems.device |
| 99 | + ) |
| 100 | + |
| 101 | + position_ids = torch.randint( |
| 102 | + 0, max_seq_len, (batch_size, seq_len), device=flag_gems.device |
| 103 | + ) |
| 104 | + cos, sin = _get_rope_cos_sin(max_seq_len, head_dim, dtype, device=flag_gems.device) |
| 105 | + |
| 106 | + ref_q = utils.to_reference(q, True) |
| 107 | + ref_k = utils.to_reference(k, True) |
| 108 | + ref_cos = utils.to_reference(cos, True) |
| 109 | + ref_sin = utils.to_reference(sin, True) |
| 110 | + ref_position_ids = utils.to_reference(position_ids) |
| 111 | + |
| 112 | + q_embed_ref, k_embed_ref = _torch_apply_rotary_pos_emb( |
| 113 | + q=ref_q, |
| 114 | + k=ref_k, |
| 115 | + cos=ref_cos, |
| 116 | + sin=ref_sin, |
| 117 | + position_ids=ref_position_ids if has_pos_id else None, |
| 118 | + rotary_interleaved=rotary_interleaved, |
| 119 | + ) |
| 120 | + q_embed_out, k_embed_out = flag_gems.apply_rotary_pos_emb( |
| 121 | + q=q, |
| 122 | + k=k, |
| 123 | + cos=cos, |
| 124 | + sin=sin, |
| 125 | + position_ids=position_ids if has_pos_id else None, |
| 126 | + rotary_interleaved=rotary_interleaved, |
| 127 | + ) |
| 128 | + |
| 129 | + utils.gems_assert_close(q_embed_out, q_embed_ref, dtype) |
| 130 | + utils.gems_assert_close(k_embed_out, k_embed_ref, dtype) |
0 commit comments