|
| 1 | +# Licensed to the Apache Software Foundation (ASF) under one |
| 2 | +# or more contributor license agreements. See the NOTICE file |
| 3 | +# distributed with this work for additional information |
| 4 | +# regarding copyright ownership. The ASF licenses this file |
| 5 | +# to you under the Apache License, Version 2.0 (the |
| 6 | +# "License"); you may not use this file except in compliance |
| 7 | +# with the License. You may obtain a copy of the License at |
| 8 | +# |
| 9 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +# |
| 11 | +# Unless required by applicable law or agreed to in writing, |
| 12 | +# software distributed under the License is distributed on an |
| 13 | +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 14 | +# KIND, either express or implied. See the License for the |
| 15 | +# specific language governing permissions and limitations |
| 16 | +# under the License. |
| 17 | +# |
| 18 | +import abc |
| 19 | +import torch |
| 20 | +from functools import cached_property |
| 21 | +from einops import einsum, rearrange, repeat |
| 22 | +from torch import nn |
| 23 | + |
| 24 | + |
| 25 | +class Projection(nn.Module, abc.ABC): |
| 26 | + def __init__(self, proj_width: int, num_heads: int, **kwargs): |
| 27 | + super().__init__() |
| 28 | + self.proj_width = proj_width |
| 29 | + self.num_heads = num_heads |
| 30 | + |
| 31 | + @abc.abstractmethod |
| 32 | + def forward(self, x, seq_id): ... |
| 33 | + |
| 34 | + |
| 35 | +class RotaryProjection(Projection): |
| 36 | + def __init__(self, *, proj_width: int, num_heads: int, max_len: int = 512, base: int = 10000): |
| 37 | + super().__init__(proj_width, num_heads) |
| 38 | + assert ( |
| 39 | + self.proj_width % 2 == 0 |
| 40 | + ), f"proj_width must be even, got {self.proj_width}" |
| 41 | + self.register_buffer( |
| 42 | + "theta", |
| 43 | + 1.0 |
| 44 | + / torch.pow( |
| 45 | + base, |
| 46 | + torch.arange(0, self.proj_width, 2, dtype=torch.float) |
| 47 | + / self.proj_width, |
| 48 | + ), |
| 49 | + persistent=False, |
| 50 | + ) |
| 51 | + self.register_buffer("cos", None, persistent=False) |
| 52 | + self.register_buffer("sin", None, persistent=False) |
| 53 | + self._init_freq(max_len=max_len) |
| 54 | + |
| 55 | + def _init_freq(self, max_len: int): |
| 56 | + if self.cos is None or self.cos.size(-2) < max_len: |
| 57 | + position = torch.arange( |
| 58 | + max_len, device=self.theta.device, dtype=self.theta.dtype |
| 59 | + ) |
| 60 | + m_theta = einsum(position, self.theta, |
| 61 | + "length, width -> length width") |
| 62 | + m_theta = repeat(m_theta, "length width -> length (width 2)") |
| 63 | + self.register_buffer("cos", torch.cos(m_theta), persistent=False) |
| 64 | + self.register_buffer("sin", torch.sin(m_theta), persistent=False) |
| 65 | + |
| 66 | + @staticmethod |
| 67 | + def _rotate(x): |
| 68 | + x1, x2 = rearrange(x, "... (dim r) -> r ... dim", r=2) |
| 69 | + return rearrange([-x2, x1], "r ... dim -> ... (dim r)", r=2) # noqa |
| 70 | + |
| 71 | + def forward(self, x, seq_id): |
| 72 | + self._init_freq(max_len=seq_id.max() + 1) |
| 73 | + rot_cos = self.cos[seq_id] |
| 74 | + rot_sin = self.sin[seq_id] |
| 75 | + return rot_cos * x + rot_sin * self._rotate(x) |
| 76 | + |
| 77 | + |
| 78 | +class QueryKeyProjection(nn.Module): |
| 79 | + def __init__(self, dim: int, num_heads: int, proj_layer, kwargs=None, partial_factor=None): |
| 80 | + super().__init__() |
| 81 | + if partial_factor is not None: |
| 82 | + assert ( |
| 83 | + 0.0 <= partial_factor[0] < partial_factor[1] <= 1.0 |
| 84 | + ), f"got {partial_factor[0]}, {partial_factor[1]}" |
| 85 | + assert num_heads > 0 and dim % num_heads == 0 |
| 86 | + |
| 87 | + self.head_dim = dim // num_heads |
| 88 | + self.partial_factor = partial_factor |
| 89 | + self.query_proj = proj_layer( |
| 90 | + proj_width=self.proj_width, |
| 91 | + num_heads=num_heads, |
| 92 | + **(kwargs or {}), |
| 93 | + ) |
| 94 | + self.key_proj = self.query_proj |
| 95 | + |
| 96 | + @cached_property |
| 97 | + def proj_width(self) -> int: |
| 98 | + if self.partial_factor is None: |
| 99 | + return self.head_dim |
| 100 | + return int(self.head_dim * (self.partial_factor[1] - self.partial_factor[0])) |
| 101 | + |
| 102 | + @cached_property |
| 103 | + def split_sizes(self): |
| 104 | + if self.partial_factor is None: |
| 105 | + return 0, self.head_dim, 0 |
| 106 | + return ( |
| 107 | + int(self.partial_factor[0] * self.head_dim), |
| 108 | + self.proj_width, |
| 109 | + int((1.0 - self.partial_factor[1]) * self.head_dim), |
| 110 | + ) |
| 111 | + |
| 112 | + def forward(self, query, key, query_id, kv_id): |
| 113 | + if self.partial_factor is not None: |
| 114 | + queries = list(query.split(self.split_sizes, dim=-1)) |
| 115 | + keys = list(key.split(self.split_sizes, dim=-1)) |
| 116 | + queries[1] = self.query_proj(queries[1], seq_id=query_id) |
| 117 | + keys[1] = self.key_proj(keys[1], seq_id=kv_id) |
| 118 | + query = torch.cat(queries, dim=-1) |
| 119 | + key = torch.cat(keys, dim=-1) |
| 120 | + else: |
| 121 | + query = self.query_proj(query, seq_id=query_id) |
| 122 | + key = self.key_proj(key, seq_id=kv_id) |
| 123 | + return query, key |
0 commit comments