codewithdark commited on
Commit
2c9dd59
·
verified ·
1 Parent(s): b0b037f

Delete multi_head_Attention.py

Browse files
Files changed (1) hide show
  1. multi_head_Attention.py +0 -44
multi_head_Attention.py DELETED
@@ -1,44 +0,0 @@
1
- import torch
2
- import torch.nn as nn
3
- import torch.nn.functional as F
4
- from typing import Optional, Tuple
5
-
6
- # Multi-Head Attention Mechanism
7
- class MultiHeadAttention(nn.Module):
8
- def __init__(self, d_model: int, num_heads: int, dropout: float = 0.1):
9
- super().__init__()
10
- assert d_model % num_heads == 0
11
-
12
- self.d_model = d_model
13
- self.num_heads = num_heads
14
- self.head_dim = d_model // num_heads
15
-
16
- self.q_proj = nn.Linear(d_model, d_model)
17
- self.k_proj = nn.Linear(d_model, d_model)
18
- self.v_proj = nn.Linear(d_model, d_model)
19
- self.o_proj = nn.Linear(d_model, d_model)
20
-
21
- self.dropout = nn.Dropout(dropout)
22
-
23
- def forward(self, x: torch.Tensor, mask: Optional[torch.Tensor] = None) -> torch.Tensor:
24
- batch_size, seq_len, d_model = x.shape
25
-
26
- # Project and reshape for multi-head attention
27
- q = self.q_proj(x).reshape(batch_size, seq_len, self.num_heads, self.head_dim)
28
- k = self.k_proj(x).reshape(batch_size, seq_len, self.num_heads, self.head_dim)
29
- v = self.v_proj(x).reshape(batch_size, seq_len, self.num_heads, self.head_dim)
30
-
31
- # Transpose for attention computation
32
- q, k, v = q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2)
33
-
34
- # Compute attention scores
35
- scores = torch.matmul(q, k.transpose(-2, -1)) / math.sqrt(self.head_dim)
36
- if mask is not None:
37
- scores = scores.masked_fill(mask == 0, float('-inf'))
38
-
39
- attn_weights = F.softmax(scores, dim=-1)
40
- attn_weights = self.dropout(attn_weights)
41
-
42
- # Apply attention to values
43
- out = torch.matmul(attn_weights, v).transpose(1, 2).reshape(batch_size, seq_len, d_model)
44
- return self.o_proj(out)