Arko007 commited on
Commit
f55bc2e
·
verified ·
1 Parent(s): a8244ed

Upload model.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. model.py +131 -0
model.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Zenyx Model Architecture - Clean Version
3
+ No config import needed!
4
+ """
5
+
6
+ import math
7
+ import torch
8
+ import torch.nn as nn
9
+ from torch.nn import functional as F
10
+
11
+ class CausalSelfAttention(nn.Module):
12
+ def __init__(self, config):
13
+ super().__init__()
14
+ assert config.n_embd % config.n_heads == 0
15
+ self.c_attn = nn.Linear(config.n_embd, 3 * config.n_embd, bias=config.bias)
16
+ self.c_proj = nn.Linear(config.n_embd, config.n_embd, bias=config.bias)
17
+ self.attn_dropout = nn.Dropout(config.dropout)
18
+ self.resid_dropout = nn.Dropout(config.dropout)
19
+ self.n_heads = config.n_heads
20
+ self.n_embd = config.n_embd
21
+ self.dropout = config.dropout
22
+ self.register_buffer("bias", torch.tril(torch.ones(config.block_size, config.block_size))
23
+ .view(1, 1, config.block_size, config.block_size))
24
+
25
+ def forward(self, x):
26
+ B, T, C = x.size()
27
+ q, k, v = self.c_attn(x).split(self.n_embd, dim=2)
28
+ k = k.view(B, T, self.n_heads, C // self.n_heads).transpose(1, 2)
29
+ q = q.view(B, T, self.n_heads, C // self.n_heads).transpose(1, 2)
30
+ v = v.view(B, T, self.n_heads, C // self.n_heads).transpose(1, 2)
31
+ att = (q @ k.transpose(-2, -1)) * (1.0 / math.sqrt(k.size(-1)))
32
+ att = att.masked_fill(self.bias[:,:,:T,:T] == 0, float('-inf'))
33
+ att = F.softmax(att, dim=-1)
34
+ att = self.attn_dropout(att)
35
+ y = att @ v
36
+ y = y.transpose(1, 2).contiguous().view(B, T, C)
37
+ y = self.resid_dropout(self.c_proj(y))
38
+ return y
39
+
40
+ class MLP(nn.Module):
41
+ def __init__(self, config):
42
+ super().__init__()
43
+ self.c_fc = nn.Linear(config.n_embd, 4 * config.n_embd, bias=config.bias)
44
+ self.gelu = nn.GELU()
45
+ self.c_proj = nn.Linear(4 * config.n_embd, config.n_embd, bias=config.bias)
46
+ self.dropout = nn.Dropout(config.dropout)
47
+
48
+ def forward(self, x):
49
+ x = self.c_fc(x)
50
+ x = self.gelu(x)
51
+ x = self.c_proj(x)
52
+ x = self.dropout(x)
53
+ return x
54
+
55
+ class Block(nn.Module):
56
+ def __init__(self, config):
57
+ super().__init__()
58
+ self.ln_1 = nn.LayerNorm(config.n_embd)
59
+ self.attn = CausalSelfAttention(config)
60
+ self.ln_2 = nn.LayerNorm(config.n_embd)
61
+ self.mlp = MLP(config)
62
+
63
+ def forward(self, x):
64
+ x = x + self.attn(self.ln_1(x))
65
+ x = x + self.mlp(self.ln_2(x))
66
+ return x
67
+
68
+ class NanoGPT(nn.Module):
69
+ """Zenyx/NanoGPT Model"""
70
+
71
+ def __init__(self, config):
72
+ super().__init__()
73
+ self.config = config
74
+ self.transformer = nn.ModuleDict(dict(
75
+ wte = nn.Embedding(config.vocab_size, config.n_embd),
76
+ wpe = nn.Embedding(config.block_size, config.n_embd),
77
+ drop = nn.Dropout(config.dropout),
78
+ h = nn.ModuleList([Block(config) for _ in range(config.n_layers)]),
79
+ ln_f = nn.LayerNorm(config.n_embd),
80
+ ))
81
+ self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
82
+ self.transformer.wte.weight = self.lm_head.weight
83
+ self.apply(self._init_weights)
84
+ for pn, p in self.named_parameters():
85
+ if pn.endswith('c_proj.weight'):
86
+ torch.nn.init.normal_(p, mean=0.0, std=0.02/math.sqrt(2 * config.n_layers))
87
+ print(f"Number of parameters: {self.get_num_params()/1e6:.2f}M")
88
+
89
+ def get_num_params(self):
90
+ return sum(p.numel() for p in self.parameters())
91
+
92
+ def _init_weights(self, module):
93
+ if isinstance(module, nn.Linear):
94
+ torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
95
+ if module.bias is not None:
96
+ torch.nn.init.zeros_(module.bias)
97
+ elif isinstance(module, nn.Embedding):
98
+ torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
99
+
100
+ def forward(self, idx, targets=None):
101
+ device = idx.device
102
+ b, t = idx.size()
103
+ assert t <= self.config.block_size
104
+ pos = torch.arange(0, t, dtype=torch.long, device=device)
105
+ tok_emb = self.transformer.wte(idx)
106
+ pos_emb = self.transformer.wpe(pos)
107
+ x = self.transformer.drop(tok_emb + pos_emb)
108
+ for block in self.transformer.h:
109
+ x = block(x)
110
+ x = self.transformer.ln_f(x)
111
+ if targets is not None:
112
+ logits = self.lm_head(x)
113
+ loss = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1), ignore_index=-1)
114
+ else:
115
+ logits = self.lm_head(x[:, [-1], :])
116
+ loss = None
117
+ return logits, loss
118
+
119
+ @torch.no_grad()
120
+ def generate(self, idx, max_new_tokens, temperature=1.0, top_k=None):
121
+ for _ in range(max_new_tokens):
122
+ idx_cond = idx if idx.size(1) <= self.config.block_size else idx[:, -self.config.block_size:]
123
+ logits, _ = self(idx_cond)
124
+ logits = logits[:, -1, :] / temperature
125
+ if top_k is not None:
126
+ v, _ = torch.topk(logits, min(top_k, logits.size(-1)))
127
+ logits[logits < v[:, [-1]]] = -float('Inf')
128
+ probs = F.softmax(logits, dim=-1)
129
+ idx_next = torch.multinomial(probs, num_samples=1)
130
+ idx = torch.cat((idx, idx_next), dim=1)
131
+ return idx