(
q_in: torch.Tensor,
k_in: torch.Tensor,
v_in: torch.Tensor,
prefix: str,
weights: Dict[str, torch.Tensor],
num_heads: int,
rope_cis: torch.Tensor | None = None,
repeat_freqs_k: bool = False,
num_k_exclude_rope: int = 0,
)
| 217 | |
| 218 | |
| 219 | def attention_forward( |
| 220 | q_in: torch.Tensor, |
| 221 | k_in: torch.Tensor, |
| 222 | v_in: torch.Tensor, |
| 223 | prefix: str, |
| 224 | weights: Dict[str, torch.Tensor], |
| 225 | num_heads: int, |
| 226 | rope_cis: torch.Tensor | None = None, |
| 227 | repeat_freqs_k: bool = False, |
| 228 | num_k_exclude_rope: int = 0, |
| 229 | ) -> torch.Tensor: |
| 230 | q = F.linear(q_in, weights[prefix + ".q_proj.weight"].float(), weights[prefix + ".q_proj.bias"].float()) |
| 231 | k = F.linear(k_in, weights[prefix + ".k_proj.weight"].float(), weights[prefix + ".k_proj.bias"].float()) |
| 232 | v = F.linear(v_in, weights[prefix + ".v_proj.weight"].float(), weights[prefix + ".v_proj.bias"].float()) |
| 233 | |
| 234 | bsz, nq, dim = q.shape |
| 235 | nk = k.shape[1] |
| 236 | head_dim = dim // num_heads |
| 237 | |
| 238 | qh = q.view(bsz, nq, num_heads, head_dim).permute(0, 2, 1, 3) |
| 239 | kh = k.view(bsz, nk, num_heads, head_dim).permute(0, 2, 1, 3) |
| 240 | vh = v.view(bsz, nk, num_heads, head_dim).permute(0, 2, 1, 3) |
| 241 | |
| 242 | if rope_cis is not None: |
| 243 | nk_rope = kh.shape[2] - num_k_exclude_rope |
| 244 | if nk_rope > 0: |
| 245 | qh, kh_rope = apply_rotary_enc( |
| 246 | qh, |
| 247 | kh[:, :, :nk_rope, :], |
| 248 | rope_cis, |
| 249 | repeat_freqs_k=repeat_freqs_k, |
| 250 | ) |
| 251 | if nk_rope < kh.shape[2]: |
| 252 | kh = torch.cat([kh_rope, kh[:, :, nk_rope:, :]], dim=2) |
| 253 | else: |
| 254 | kh = kh_rope |
| 255 | |
| 256 | out = F.scaled_dot_product_attention(qh, kh, vh) |
| 257 | out = out.permute(0, 2, 1, 3).reshape(bsz, nq, dim) |
| 258 | return F.linear(out, weights[prefix + ".out_proj.weight"].float(), weights[prefix + ".out_proj.bias"].float()) |
| 259 | |
| 260 | |
| 261 | def mlp_forward(x: torch.Tensor, weights: Dict[str, torch.Tensor], prefix: str, num_layers: int) -> torch.Tensor: |
no test coverage detected