(
self,
x: torch.Tensor,
start_pos: int,
mask: Optional[torch.Tensor],
)
| 149 | self.alibi_bias = alibi_bias.to("cuda:0") |
| 150 | |
| 151 | def forward( |
| 152 | self, |
| 153 | x: torch.Tensor, |
| 154 | start_pos: int, |
| 155 | mask: Optional[torch.Tensor], |
| 156 | ): |
| 157 | bsz, seqlen, _ = x.shape |
| 158 | xqkv = self.Wqkv(x) |
| 159 | xqkv = xqkv.view(bsz, seqlen, -1, self.n_local_heads, self.head_dim) |
| 160 | xq = xqkv[:, :, 0] |
| 161 | xk = xqkv[:, :, 1] |
| 162 | xv = xqkv[:, :, 2] |
| 163 | |
| 164 | if seqlen > 1: |
| 165 | xq = xq.view(bsz, seqlen, self.n_local_heads, self.head_dim) |
| 166 | xk = xk.view(bsz, seqlen, self.n_local_heads, self.head_dim) |
| 167 | xv = xv.view(bsz, seqlen, self.n_local_heads, self.head_dim) |
| 168 | |
| 169 | self.cache_k = self.cache_k.to(xq) |
| 170 | self.cache_v = self.cache_v.to(xq) |
| 171 | |
| 172 | values_store = xv.transpose(2, 1) |
| 173 | keys_store = ( |
| 174 | xk.reshape(bsz, seqlen, self.n_local_heads, self.head_dim // 8, 8) |
| 175 | .permute(0, 2, 3, 1, 4) |
| 176 | .contiguous() |
| 177 | ) |
| 178 | |
| 179 | self.cache_v[:bsz, :, start_pos : start_pos + seqlen, :] = values_store |
| 180 | self.cache_k[:bsz, :, :, start_pos : start_pos + seqlen, :] = keys_store |
| 181 | |
| 182 | keys = xk |
| 183 | values = xv |
| 184 | |
| 185 | xq = xq.transpose(1, 2) |
| 186 | keys = keys.transpose(1, 2) |
| 187 | values = values.transpose(1, 2) |
| 188 | scores = torch.matmul(xq, keys.transpose(2, 3)) / math.sqrt(self.head_dim) |
| 189 | scores += self.alibi_bias[..., :seqlen] |
| 190 | if mask is not None: |
| 191 | scores = scores + mask # (bs, n_local_heads, slen, cache_len + slen) |
| 192 | scores = F.softmax(scores.float(), dim=-1).type_as(xq) |
| 193 | output = torch.matmul(scores, values) # (bs, n_local_heads, slen, head_dim) |
| 194 | output = output.transpose(1, 2).contiguous().view(bsz, seqlen, -1) |
| 195 | else: |
| 196 | # xq = xq[:, 0, :, :] |
| 197 | # xk = xk[:, 0, :, :] |
| 198 | # xv = xv[:, 0, :, :] |
| 199 | xq = xq.view(bsz, self.n_local_heads, self.head_dim) |
| 200 | xk = xk.view(bsz, self.n_local_heads, self.head_dim) |
| 201 | xv = xv.view(bsz, self.n_local_heads, self.head_dim) |
| 202 | output = awq_inference_engine.single_query_attention( |
| 203 | xq, |
| 204 | xk, |
| 205 | xv, |
| 206 | self.cache_k, |
| 207 | self.cache_v, |
| 208 | None, |
nothing calls this directly
no outgoing calls
no test coverage detected