Update crossexpertattention.py
Browse files- crossexpertattention.py +39 -2
crossexpertattention.py
CHANGED
@@ -1,3 +1,40 @@
|
|
1 |
-
|
2 |
-
|
|
|
|
|
|
|
|
|
3 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from transformers import PretrainedConfig, PreTrainedModel, AutoModelForCausalLM # Import AutoModelForCausalLM
|
2 |
+
import torch
|
3 |
+
import torch.nn as nn
|
4 |
+
import torch.nn.functional as F
|
5 |
+
import math
|
6 |
+
from transformers.modeling_outputs import CausalLMOutputWithPast # Import the necessary output class
|
7 |
|
8 |
+
# Define the Cross-Expert Attention mechanism
|
9 |
+
class CrossExpertAttention(nn.Module):
|
10 |
+
def __init__(self, config: MeshConfig):
|
11 |
+
super().__init__()
|
12 |
+
self.config = config
|
13 |
+
# Define multi-head attention layers or similar for cross-expert communication
|
14 |
+
# This is a placeholder and needs detailed implementation
|
15 |
+
self.cross_attention = nn.MultiheadAttention(
|
16 |
+
embed_dim=config.hidden_size,
|
17 |
+
num_heads=config.num_attention_heads, # Using model's attention heads for now
|
18 |
+
batch_first=True
|
19 |
+
)
|
20 |
+
|
21 |
+
def forward(self, expert_outputs):
|
22 |
+
# expert_outputs shape: (batch_size, sequence_length, num_experts, hidden_size)
|
23 |
+
|
24 |
+
if not self.config.cross_expert_attention_enabled:
|
25 |
+
return expert_outputs
|
26 |
+
|
27 |
+
# Reshape for attention: (batch_size * sequence_length, num_experts, hidden_size)
|
28 |
+
batch_seq_size = expert_outputs.shape[0] * expert_outputs.shape[1]
|
29 |
+
reshaped_outputs = expert_outputs.view(batch_seq_size, self.config.mesh_grid_size[0] * self.config.mesh_grid_size[1], self.config.hidden_size)
|
30 |
+
|
31 |
+
# Apply cross-expert attention. Query, Key, Value are the same here (self-attention across experts)
|
32 |
+
# Attention mask could be used to restrict communication if needed
|
33 |
+
cross_attn_output, _ = self.cross_attention(reshaped_outputs, reshaped_outputs, reshaped_outputs)
|
34 |
+
|
35 |
+
# Reshape back: (batch_size, sequence_length, num_experts, hidden_size)
|
36 |
+
cross_attn_output = cross_attn_output.view(
|
37 |
+
expert_outputs.shape[0], expert_outputs.shape[1], self.config.mesh_grid_size[0] * self.config.mesh_grid_size[1], self.config.hidden_size
|
38 |
+
)
|
39 |
+
|
40 |
+
return cross_attn_output
|