(
self,
x: torch.Tensor,
start_pos: int,
freqs_cis: torch.Tensor,
mask: Optional[torch.Tensor],
)
| 219 | ) |
| 220 | |
| 221 | def forward( |
| 222 | self, |
| 223 | x: torch.Tensor, |
| 224 | start_pos: int, |
| 225 | freqs_cis: torch.Tensor, |
| 226 | mask: Optional[torch.Tensor], |
| 227 | ): |
| 228 | bsz, seqlen, _ = x.shape |
| 229 | xqkv = self.qkv_proj(x) |
| 230 | xqkv = xqkv.view( |
| 231 | bsz, |
| 232 | seqlen, |
| 233 | self.n_local_heads + self.num_key_value_heads * 2, |
| 234 | self.head_dim, |
| 235 | ) |
| 236 | xq = xqkv[:, :, 0 : self.n_local_heads] |
| 237 | xk = xqkv[ |
| 238 | :, :, self.n_local_heads : (self.n_local_heads + self.num_key_value_heads) |
| 239 | ] |
| 240 | xv = xqkv[:, :, -self.num_key_value_heads :] |
| 241 | |
| 242 | if seqlen > 1: |
| 243 | xq = xq.view(bsz, seqlen, self.n_local_heads, self.head_dim) |
| 244 | xk = xk.view(bsz, seqlen, self.num_key_value_heads, self.head_dim) |
| 245 | xv = xv.view(bsz, seqlen, self.num_key_value_heads, self.head_dim) |
| 246 | |
| 247 | xq, xk = apply_rotary_emb(xq, xk, freqs_cis=freqs_cis) |
| 248 | |
| 249 | self.cache_k = self.cache_k.to(xq) |
| 250 | self.cache_v = self.cache_v.to(xq) |
| 251 | |
| 252 | values_store = xv.transpose(2, 1) |
| 253 | keys_store = ( |
| 254 | xk.reshape(bsz, seqlen, self.num_key_value_heads, self.head_dim // 8, 8) |
| 255 | .permute(0, 2, 3, 1, 4) |
| 256 | .contiguous() |
| 257 | ) |
| 258 | |
| 259 | self.cache_v[:bsz, :, start_pos : start_pos + seqlen, :] = values_store |
| 260 | self.cache_k[:bsz, :, :, start_pos : start_pos + seqlen, :] = keys_store |
| 261 | |
| 262 | keys = xk |
| 263 | values = xv |
| 264 | |
| 265 | keys = torch.repeat_interleave( |
| 266 | keys, dim=2, repeats=self.num_key_value_groups |
| 267 | ) |
| 268 | values = torch.repeat_interleave( |
| 269 | values, dim=2, repeats=self.num_key_value_groups |
| 270 | ) |
| 271 | |
| 272 | xq = xq.transpose(1, 2) |
| 273 | keys = keys.transpose(1, 2) |
| 274 | values = values.transpose(1, 2) |
| 275 | scores = torch.matmul(xq, keys.transpose(2, 3)) / math.sqrt(self.head_dim) |
| 276 | if mask is not None: |
| 277 | scores = scores + mask # (bs, n_local_heads, slen, cache_len + slen) |
| 278 | scores = F.softmax(scores.float(), dim=-1).type_as(xq) |
nothing calls this directly
no test coverage detected