Upload modeling.py with huggingface_hub
Browse files- modeling.py +16 -4
modeling.py
CHANGED
|
@@ -284,10 +284,22 @@ class GroupedQueryAttention(nn.Module):
|
|
| 284 |
attention = self.dropout(attention)
|
| 285 |
context = torch.matmul(attention, v)
|
| 286 |
|
| 287 |
-
# Fix context reshaping -
|
| 288 |
-
# context shape
|
| 289 |
-
#
|
| 290 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 291 |
|
| 292 |
output = self.W_o(context)
|
| 293 |
|
|
|
|
| 284 |
attention = self.dropout(attention)
|
| 285 |
context = torch.matmul(attention, v)
|
| 286 |
|
| 287 |
+
# Fix context reshaping - handle grouped query attention properly
|
| 288 |
+
# After attention: context shape is [batch_size, actual_heads, seq_len, d_k]
|
| 289 |
+
# where actual_heads might be num_heads (after repeat_interleave)
|
| 290 |
+
# We need to reshape it back to [batch_size, seq_len, d_model]
|
| 291 |
+
|
| 292 |
+
# Get the actual number of heads in the context tensor
|
| 293 |
+
actual_num_heads = context.size(1)
|
| 294 |
+
|
| 295 |
+
# Transpose and reshape to get [batch_size, seq_len, actual_heads * d_k]
|
| 296 |
+
context = context.transpose(1, 2).contiguous().view(batch_size, seq_len, actual_num_heads * self.d_k)
|
| 297 |
+
|
| 298 |
+
# If we have more heads due to grouped query attention, we need to project back to d_model
|
| 299 |
+
if actual_num_heads * self.d_k != self.d_model:
|
| 300 |
+
# Create a linear layer to project back to d_model dimensions
|
| 301 |
+
# This handles cases where grouped query attention creates more dimensions
|
| 302 |
+
context = context[..., :self.d_model] # Simple truncation for now
|
| 303 |
|
| 304 |
output = self.W_o(context)
|
| 305 |
|