FarhanAK128 commited on
Commit
368be8b
·
verified ·
1 Parent(s): 83f83a5

Create model_class.py

Browse files
Files changed (1) hide show
  1. model_class.py +176 -0
model_class.py ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ from transformers import PreTrainedModel, PretrainedConfig
4
+
5
+
6
+ class MultiheadAttention(nn.Module):
7
+ def __init__(self, d_in, d_out, context_length, dropout, num_heads, qkv_bias=False):
8
+ super().__init__()
9
+
10
+ self.d_out = d_out
11
+ self.num_heads = num_heads
12
+ self.head_dim = d_out // num_heads
13
+
14
+ #step 3
15
+ self.W_query = nn.Linear(d_in, d_out, bias=qkv_bias)
16
+ self.W_key = nn.Linear(d_in, d_out, bias=qkv_bias)
17
+ self.W_value = nn.Linear(d_in, d_out, bias=qkv_bias)
18
+
19
+ self.out_proj = nn.Linear(d_out, d_out)
20
+ self.dropout = nn.Dropout(dropout)
21
+ self.register_buffer("mask",torch.triu(torch.ones(context_length, context_length), diagonal=1))
22
+
23
+
24
+ def forward(self, x):
25
+ b, num_tokens, d_in = x.shape
26
+
27
+ #step 4
28
+ keys = self.W_key(x)
29
+ queries = self.W_query(x)
30
+ values = self.W_value(x)
31
+
32
+ #step 5
33
+ keys = keys.view(b, num_tokens, self.num_heads, self.head_dim)
34
+ queries = queries.view(b, num_tokens, self.num_heads, self.head_dim)
35
+ values = values.view(b, num_tokens, self.num_heads, self.head_dim)
36
+
37
+ #step 6
38
+ keys = keys.transpose(1,2)
39
+ queries = queries.transpose(1,2)
40
+ values = values.transpose(1,2)
41
+
42
+ #step 7
43
+ attn_scores = queries @ keys.transpose(2,3)
44
+
45
+ #step 8
46
+ mask_bool = self.mask.bool()[:num_tokens, :num_tokens]
47
+ attn_scores.masked_fill_(mask_bool, -torch.inf)
48
+
49
+ attn_weights = torch.softmax(attn_scores / keys.shape[-1]**0.5, dim=-1)
50
+ attn_weights = self.dropout(attn_weights)
51
+
52
+ #step 9 - 11
53
+ ctx_vec = (attn_weights @ values).transpose(1, 2)
54
+
55
+ #step 12
56
+ ctx_vec = ctx_vec.contiguous().view(b, num_tokens, self.d_out)
57
+ ctx_vec = self.out_proj(ctx_vec)
58
+
59
+ return ctx_vec
60
+
61
+ #==========================================================================
62
+
63
+
64
+ class LayerNorm(nn.Module):
65
+ def __init__(self, emb_dim):
66
+ super().__init__()
67
+ self.eps = 1e-5
68
+ self.scale = nn.Parameter(torch.ones(emb_dim))
69
+ self.shift = nn.Parameter(torch.zeros(emb_dim))
70
+
71
+ def forward(self, x):
72
+ mean = x.mean(dim=-1, keepdim=True)
73
+ var = x.var(dim=-1, keepdim=True, unbiased=False)
74
+ norm_x = (x - mean) / torch.sqrt(var + self.eps)
75
+ return self.scale * norm_x + self.shift
76
+
77
+ #==========================================================================
78
+
79
+
80
+ class GeLU(nn.Module):
81
+ def __init__(self):
82
+ super().__init__()
83
+
84
+ def forward(self, x):
85
+ return 0.5 * x * (1 + torch.tanh(torch.sqrt(torch.tensor(2.0/torch.pi)) * (x + 0.044715 * torch.pow(x,3))))
86
+
87
+ #==========================================================================
88
+
89
+
90
+ class FeedForward(nn.Module):
91
+ def __init__(self, cfg):
92
+ super().__init__()
93
+ self.layers = nn.Sequential(
94
+ nn.Linear(cfg.emb_dim, 4*cfg.emb_dim),
95
+ GeLU(),
96
+ nn.Linear(4*cfg.emb_dim, cfg.emb_dim)
97
+ )
98
+ def forward(self, x):
99
+ return self.layers(x)
100
+
101
+ #==========================================================================
102
+
103
+ class TransformerBlock(nn.Module):
104
+ def __init__(self, cfg):
105
+ super().__init__()
106
+ self.att = MultiheadAttention(
107
+ d_in = cfg.emb_dim,
108
+ d_out = cfg.emb_dim,
109
+ context_length = cfg.context_length,
110
+ dropout = cfg.drop_rate,
111
+ num_heads = cfg.n_heads,
112
+ qkv_bias = cfg.qkv_bias
113
+ )
114
+ self.ff = FeedForward(cfg)
115
+ self.norm1 = LayerNorm(cfg.emb_dim)
116
+ self.norm2 = LayerNorm(cfg.emb_dim)
117
+ self.drop_shortcut = nn.Dropout(cfg.drop_rate)
118
+
119
+ def forward(self, x):
120
+ shortcut = x
121
+ x = self.norm1(x)
122
+ x = self.att(x)
123
+ x = self.drop_shortcut(x)
124
+ x = x + shortcut
125
+
126
+ shortcut = x
127
+ x = self.norm2(x)
128
+ x = self.ff(x)
129
+ x = self.drop_shortcut(x)
130
+ x = x + shortcut
131
+
132
+ return x
133
+
134
+ #==========================================================================
135
+
136
+ class CustomGPTConfig(PretrainedConfig):
137
+ model_type = "custom_gpt" # Unique identifier for the AutoClass
138
+ def __init__(self, context_length=1024, drop_rate=0.0, emb_dim=1024, n_heads=16, n_layers=24, qkv_bias=True, vocab_size=50257, **kwargs):
139
+ super().__init__(**kwargs)
140
+ self.context_length = context_length
141
+ self.drop_rate = drop_rate
142
+ self.emb_dim = emb_dim
143
+ self.n_heads = n_heads
144
+ self.n_layers = n_layers
145
+ self.qkv_bias = qkv_bias
146
+ self.vocab_size = vocab_size
147
+
148
+ #==========================================================================
149
+
150
+ class CustomGPT(
151
+ PreTrainedModel,
152
+ ):
153
+ config_class = CustomGPTConfig
154
+ def __init__(self, config):
155
+ super().__init__(config)
156
+ self.tok_emb = nn.Embedding(config.vocab_size, config.emb_dim)
157
+ self.pos_emb = nn.Embedding(config.context_length, config.emb_dim)
158
+ self.drop_emb = nn.Dropout(config.drop_rate)
159
+
160
+ self.trf_blocks = nn.Sequential(
161
+ *[TransformerBlock(config) for _ in range(config.n_layers)]
162
+ )
163
+
164
+ self.final_norm = LayerNorm(config.emb_dim)
165
+ self.out_head = nn.Linear(config.emb_dim, config.vocab_size, bias=False)
166
+
167
+ def forward(self, x):
168
+ batch_size, seq_len = x.shape
169
+ tok_embeddings = self.tok_emb(x) #[2,4,768]
170
+ pos_embeddings = self.pos_emb(torch.arange(seq_len, device=x.device)) #[2,4,768]
171
+ x = tok_embeddings + pos_embeddings #[2,4,768]
172
+ x = self.drop_emb(x)
173
+ x = self.trf_blocks(x)
174
+ x = self.final_norm(x)
175
+ logits = self.out_head(x) #[2,4,50257]
176
+ return logits