-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdecoder_block.py
More file actions
99 lines (79 loc) · 2.08 KB
/
Copy pathdecoder_block.py
File metadata and controls
99 lines (79 loc) · 2.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
"""
decoder_block.py
Builds a complete Transformer Decoder Block by combining:
1. Multi-Head Self Attention
2. Residual Connection
3. Layer Normalization
4. Feed Forward Network
5. Residual Connection
6. Layer Normalization
This is the fundamental building block used in decoder-only
Large Language Models such as GPT, Llama, Mistral, Gemma,
Qwen, Phi and DeepSeek.
"""
import torch
import torch.nn as nn
from attention import MultiHeadSelfAttention
from feed_forward import FeedForward
from config import DROPOUT
class DecoderBlock(nn.Module):
"""
A single Transformer Decoder Block.
Architecture:
Input
│
▼
Multi-Head Self Attention
│
Add (Residual)
│
LayerNorm
│
Feed Forward Network
│
Add (Residual)
│
LayerNorm
│
Output
"""
def __init__(
self,
embed_dim: int,
num_heads: int,
ff_hidden_dim: int,
):
super().__init__()
# Multi-Head Self Attention
self.attention = MultiHeadSelfAttention(
embed_dim,
num_heads,
)
# Feed Forward Network
self.feed_forward = FeedForward(
embed_dim,
ff_hidden_dim,
)
# Layer Normalization
self.norm1 = nn.LayerNorm(embed_dim)
self.norm2 = nn.LayerNorm(embed_dim)
# Dropout
self.dropout = nn.Dropout(DROPOUT)
def forward(self, x: torch.Tensor) -> torch.Tensor:
# -------------------------------
# Multi-Head Self Attention
# -------------------------------
attention_output = self.attention(x)
# Residual Connection + LayerNorm
x = self.norm1(
x + self.dropout(attention_output)
)
# -------------------------------
# Feed Forward Network
# -------------------------------
ff_output = self.feed_forward(x)
# Residual Connection + LayerNorm
x = self.norm2(
x + self.dropout(ff_output)
)
return x