SarwarShafee commited on
Commit
52a08a7
·
verified ·
1 Parent(s): c2a52b3

Upload folder using huggingface_hub

Browse files
Files changed (5) hide show
  1. config.json +1 -0
  2. model.py +249 -0
  3. model_0.pt +3 -0
  4. tokenizer_en.json +0 -0
  5. tokenizer_hn.json +0 -0
config.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"source_vocab_size": 24136, "target_vocab_size": 29794, "max_seq_len": 380, "d_model": 32, "d_ff": 124, "num_heads": 4, "num_blocks": 3, "dropout_rate": 0.1}
model.py ADDED
@@ -0,0 +1,249 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # model.py
2
+ import torch
3
+ import torch.nn as nn
4
+ import math
5
+ from tokenizers import Tokenizer
6
+ import json
7
+
8
+ # Define all necessary classes
9
+ class EmbeddingLayer(nn.Module):
10
+ def __init__(self, vocab_size: int, d_model: int):
11
+ super().__init__()
12
+ self.embedding = nn.Embedding(vocab_size, d_model)
13
+ self.d_model = d_model
14
+
15
+ def forward(self, x):
16
+ return self.embedding(x) * math.sqrt(self.d_model)
17
+
18
+ class PositionalEncoding(nn.Module):
19
+ def __init__(self, max_seq_len: int, d_model: int, dropout_rate: float):
20
+ super().__init__()
21
+ self.dropout = nn.Dropout(dropout_rate)
22
+ pe = torch.zeros(max_seq_len, d_model)
23
+ pos = torch.arange(0, max_seq_len, dtype=torch.float).unsqueeze(1)
24
+ div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model))
25
+ pe[:, 0::2] = torch.sin(pos * div_term)
26
+ pe[:, 1::2] = torch.cos(pos * div_term)
27
+ pe = pe.unsqueeze(0)
28
+ self.register_buffer('pe', pe)
29
+
30
+ def forward(self, input_embedding):
31
+ input_embedding = input_embedding + self.pe[:, :input_embedding.shape[1], :].requires_grad_(False)
32
+ return self.dropout(input_embedding)
33
+
34
+ class MultiHeadAttention(nn.Module):
35
+ def __init__(self, d_model: int, num_heads: int, dropout_rate: float):
36
+ super().__init__()
37
+ self.dropout = nn.Dropout(dropout_rate)
38
+ self.W_q = nn.Linear(d_model, d_model)
39
+ self.W_k = nn.Linear(d_model, d_model)
40
+ self.W_v = nn.Linear(d_model, d_model)
41
+ self.W_o = nn.Linear(d_model, d_model)
42
+ self.num_heads = num_heads
43
+ self.d_k = d_model // num_heads
44
+
45
+ def forward(self, q, k, v, encoder_mask=None):
46
+ query = self.W_q(q)
47
+ key = self.W_k(k)
48
+ value = self.W_v(v)
49
+ query = query.view(query.shape[0], query.shape[1], self.num_heads, self.d_k).transpose(1, 2)
50
+ key = key.view(key.shape[0], key.shape[1], self.num_heads, self.d_k).transpose(1, 2)
51
+ value = value.view(value.shape[0], value.shape[1], self.num_heads, self.d_k).transpose(1, 2)
52
+ attention_score = (query @ key.transpose(-2, -1)) / math.sqrt(self.d_k)
53
+ if encoder_mask is not None:
54
+ attention_score = attention_score.masked_fill(encoder_mask == 0, -1e9)
55
+ attention_weight = torch.softmax(attention_score, dim=-1)
56
+ attention_weight = self.dropout(attention_weight)
57
+ attention_output = attention_weight @ value
58
+ attention_output = attention_output.transpose(1, 2).contiguous().view(attention_output.shape[0], -1, self.num_heads * self.d_k)
59
+ multihead_output = self.W_o(attention_output)
60
+ return multihead_output
61
+
62
+ class FeedForward(nn.Module):
63
+ def __init__(self, d_model: int, d_ff: int, dropout_rate: float):
64
+ super().__init__()
65
+ self.layer_1 = nn.Linear(d_model, d_ff)
66
+ self.activation_1 = nn.ReLU()
67
+ self.dropout = nn.Dropout(dropout_rate)
68
+ self.layer_2 = nn.Linear(d_ff, d_model)
69
+
70
+ def forward(self, input):
71
+ return self.layer_2(self.dropout(self.activation_1(self.layer_1(input))))
72
+
73
+ class LayerNorm(nn.Module):
74
+ def __init__(self, eps: float = 1e-5):
75
+ super().__init__()
76
+ self.eps = eps
77
+ self.gamma = nn.Parameter(torch.ones(32))
78
+ self.beta = nn.Parameter(torch.zeros(32))
79
+
80
+ def forward(self, input):
81
+ mean = input.mean(dim=-1, keepdim=True)
82
+ std = input.std(dim=-1, keepdim=True)
83
+ return self.gamma * ((input - mean) / (std + self.eps)) + self.beta
84
+
85
+ class AddAndNorm(nn.Module):
86
+ def __init__(self, dropout_rate: float):
87
+ super().__init__()
88
+ self.dropout = nn.Dropout(dropout_rate)
89
+ self.layer_norm = LayerNorm()
90
+
91
+ def forward(self, input, sub_layer):
92
+ return input + self.dropout(sub_layer(self.layer_norm(input)))
93
+
94
+ class EncoderBlock(nn.Module):
95
+ def __init__(self, multihead_attention: MultiHeadAttention, feed_forward: FeedForward, dropout_rate: float):
96
+ super().__init__()
97
+ self.multihead_attention = multihead_attention
98
+ self.feed_forward = feed_forward
99
+ self.add_and_norm_list = nn.ModuleList([AddAndNorm(dropout_rate) for _ in range(2)])
100
+
101
+ def forward(self, encoder_input, encoder_mask):
102
+ encoder_input = self.add_and_norm_list[0](encoder_input, lambda encoder_input: self.multihead_attention(encoder_input, encoder_input, encoder_input, encoder_mask))
103
+ encoder_input = self.add_and_norm_list[1](encoder_input, self.feed_forward)
104
+ return encoder_input
105
+
106
+ class Encoder(nn.Module):
107
+ def __init__(self, encoderblocklist: nn.ModuleList):
108
+ super().__init__()
109
+ self.encoderblocklist = encoderblocklist
110
+ self.layer_norm = LayerNorm()
111
+
112
+ def forward(self, encoder_input, encoder_mask):
113
+ for encoderblock in self.encoderblocklist:
114
+ encoder_input = encoderblock(encoder_input, encoder_mask)
115
+ encoder_output = self.layer_norm(encoder_input)
116
+ return encoder_output
117
+
118
+ class DecoderBlock(nn.Module):
119
+ def __init__(self, masked_multihead_attention: MultiHeadAttention, multihead_attention: MultiHeadAttention, feed_forward: FeedForward, dropout_rate: float):
120
+ super().__init__()
121
+ self.masked_multihead_attention = masked_multihead_attention
122
+ self.multihead_attention = multihead_attention
123
+ self.feed_forward = feed_forward
124
+ self.add_and_norm_list = nn.ModuleList([AddAndNorm(dropout_rate) for _ in range(3)])
125
+
126
+ def forward(self, decoder_input, decoder_mask, encoder_output, encoder_mask):
127
+ decoder_input = self.add_and_norm_list[0](decoder_input, lambda decoder_input: self.masked_multihead_attention(decoder_input, decoder_input, decoder_input, decoder_mask))
128
+ decoder_input = self.add_and_norm_list[1](decoder_input, lambda decoder_input: self.multihead_attention(decoder_input, encoder_output, encoder_output, encoder_mask))
129
+ decoder_input = self.add_and_norm_list[2](decoder_input, self.feed_forward)
130
+ return decoder_input
131
+
132
+ class Decoder(nn.Module):
133
+ def __init__(self, decoderblocklist: nn.ModuleList):
134
+ super().__init__()
135
+ self.decoderblocklist = decoderblocklist
136
+ self.layer_norm = LayerNorm()
137
+
138
+ def forward(self, decoder_input, decoder_mask, encoder_output, encoder_mask):
139
+ for decoderblock in self.decoderblocklist:
140
+ decoder_input = decoderblock(decoder_input, decoder_mask, encoder_output, encoder_mask)
141
+ decoder_output = self.layer_norm(decoder_input)
142
+ return decoder_output
143
+
144
+ class ProjectionLayer(nn.Module):
145
+ def __init__(self, vocab_size: int, d_model: int):
146
+ super().__init__()
147
+ self.projection_layer = nn.Linear(d_model, vocab_size)
148
+
149
+ def forward(self, decoder_output):
150
+ output = self.projection_layer(decoder_output)
151
+ return torch.log_softmax(output, dim=-1)
152
+
153
+ class Transformer(nn.Module):
154
+ def __init__(self, source_embed, target_embed, positional_encoding, multihead_attention, masked_multihead_attention, feed_forward, encoder, decoder, projection_layer, dropout_rate):
155
+ super().__init__()
156
+ self.source_embed = source_embed
157
+ self.target_embed = target_embed
158
+ self.positional_encoding = positional_encoding
159
+ self.multihead_attention = multihead_attention
160
+ self.masked_multihead_attention = masked_multihead_attention
161
+ self.feed_forward = feed_forward
162
+ self.encoder = encoder
163
+ self.decoder = decoder
164
+ self.projection_layer = projection_layer
165
+ self.dropout = nn.Dropout(dropout_rate)
166
+
167
+ def encode(self, encoder_input, encoder_mask):
168
+ encoder_input = self.source_embed(encoder_input)
169
+ encoder_input = self.positional_encoding(encoder_input)
170
+ encoder_output = self.encoder(encoder_input, encoder_mask)
171
+ return encoder_output
172
+
173
+ def decode(self, decoder_input, decoder_mask, encoder_output, encoder_mask):
174
+ decoder_input = self.target_embed(decoder_input)
175
+ decoder_input = self.positional_encoding(decoder_input)
176
+ decoder_output = self.decoder(decoder_input, decoder_mask, encoder_output, encoder_mask)
177
+ return decoder_output
178
+
179
+ def project(self, decoder_output):
180
+ return self.projection_layer(decoder_output)
181
+
182
+ def build_model(source_vocab_size, target_vocab_size, max_seq_len, d_model, d_ff, num_heads, num_blocks, dropout_rate):
183
+ source_embed = EmbeddingLayer(source_vocab_size, d_model)
184
+ target_embed = EmbeddingLayer(target_vocab_size, d_model)
185
+ positional_encoding = PositionalEncoding(max_seq_len, d_model, dropout_rate)
186
+ multihead_attention = MultiHeadAttention(d_model, num_heads, dropout_rate)
187
+ masked_multihead_attention = MultiHeadAttention(d_model, num_heads, dropout_rate)
188
+ feed_forward = FeedForward(d_model, d_ff, dropout_rate)
189
+ projection_layer = ProjectionLayer(target_vocab_size, d_model)
190
+ encoder_block = EncoderBlock(multihead_attention, feed_forward, dropout_rate)
191
+ decoder_block = DecoderBlock(masked_multihead_attention, multihead_attention, feed_forward, dropout_rate)
192
+ # encoderblocklist = nn.ModuleList([encoder_block for _ in range(num_blocks)])
193
+ # decoderblocklist = nn.ModuleList([decoder_block for _ in range(num_blocks)])
194
+ encoderblocklist = nn.ModuleList([EncoderBlock(MultiHeadAttention(d_model, num_heads, dropout_rate), FeedForward(d_model, d_ff, dropout_rate), dropout_rate) for _ in range(num_blocks)])
195
+ decoderblocklist = nn.ModuleList([DecoderBlock(MultiHeadAttention(d_model, num_heads, dropout_rate), MultiHeadAttention(d_model, num_heads, dropout_rate), FeedForward(d_model, d_ff, dropout_rate), dropout_rate) for _ in range(num_blocks)])
196
+ encoder = Encoder(encoderblocklist)
197
+ decoder = Decoder(decoderblocklist)
198
+ model = Transformer(source_embed, target_embed, positional_encoding, multihead_attention, masked_multihead_attention, feed_forward, encoder, decoder, projection_layer, dropout_rate)
199
+ for param in model.parameters():
200
+ if param.dim() > 1:
201
+ nn.init.xavier_uniform_(param)
202
+ return model
203
+
204
+ def causal_mask(size):
205
+ mask = torch.triu(torch.ones(1, size, size), diagonal=1).type(torch.int)
206
+ return mask == 0
207
+
208
+ def hindishpt(user_input_text, model, tokenizer_en, tokenizer_my, max_seq_len, device):
209
+ model.eval()
210
+ with torch.inference_mode():
211
+ user_input_text = user_input_text.strip()
212
+ user_input_text_encoded = torch.tensor(tokenizer_en.encode(user_input_text).ids, dtype=torch.int64).to(device)
213
+ PAD_ID = tokenizer_my.token_to_id("[PAD]")
214
+ CLS_ID = torch.tensor([tokenizer_my.token_to_id("[CLS]")], dtype=torch.int64).to(device)
215
+ SEP_ID = torch.tensor([tokenizer_my.token_to_id("[SEP]")], dtype=torch.int64).to(device)
216
+ num_source_padding = max_seq_len - len(user_input_text_encoded) - 2
217
+ encoder_padding = torch.tensor([PAD_ID] * num_source_padding, dtype=torch.int64).to(device)
218
+ encoder_input = torch.cat([CLS_ID, user_input_text_encoded, SEP_ID, encoder_padding], dim=0).unsqueeze(0).to(device)
219
+ encoder_mask = (encoder_input != PAD_ID).unsqueeze(1).unsqueeze(1).int().to(device)
220
+ encoder_output = model.encode(encoder_input, encoder_mask)
221
+ decoder_input = torch.tensor([[tokenizer_my.token_to_id('[CLS]')]], dtype=torch.int64, device=device)
222
+ while True:
223
+ if decoder_input.size(1) == max_seq_len:
224
+ break
225
+ decoder_mask = causal_mask(decoder_input.size(1)).type_as(encoder_mask).to(device)
226
+ decoder_output = model.decode(decoder_input, decoder_mask, encoder_output, encoder_mask)
227
+ projection = model.project(decoder_output[:, -1])
228
+ _, new_token = torch.max(projection, dim=1)
229
+ new_token = new_token.unsqueeze(1)
230
+ decoder_input = torch.cat([decoder_input, new_token], dim=1)
231
+ if new_token.item() == tokenizer_my.token_to_id('[SEP]'):
232
+ break
233
+ decoder_output = decoder_input.squeeze(0)
234
+ model_predicted_text = tokenizer_my.decode(decoder_output.detach().cpu().numpy())
235
+ return model_predicted_text
236
+
237
+ # # Example usage
238
+ # if __name__ == "__main__":
239
+ # device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
240
+ # tokenizer_en = Tokenizer.from_file("tokenizer_en.json")
241
+ # tokenizer_my = Tokenizer.from_file("tokenizer_hn.json")
242
+ # with open("config.json", "r") as f:
243
+ # config = json.load(f)
244
+ # model = build_model(**config)
245
+ # model.to(device)
246
+ # checkpoint = torch.load("model_1.pt", map_location=device)
247
+ # model.load_state_dict(checkpoint['model_state_dict'])
248
+ # model.eval()
249
+ # print(hindishpt("अब आप कैसे हैं?", model, tokenizer_en, tokenizer_my, 128, device))
model_0.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:46ab5e390661617d9a13185378d91719d28a9feb638e1946ab796d22ada19d79
3
+ size 33998688
tokenizer_en.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_hn.json ADDED
The diff for this file is too large to render. See raw diff