solhost commited on
Commit
3a141cf
·
verified ·
1 Parent(s): 51e8d2e

Create model.py

Browse files
Files changed (1) hide show
  1. model.py +161 -0
model.py ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ model.py -- standalone architecture definition for GTM-v2-base.
3
+
4
+ This is a plain PyTorch nanoGPT-style GPT model, NOT a HuggingFace
5
+ `transformers` AutoModel. To load the released weights:
6
+
7
+ pip install torch safetensors tiktoken
8
+
9
+ import json, torch
10
+ from safetensors.torch import load_file
11
+ from model import GPT, GPTConfig
12
+
13
+ with open("config.json") as f:
14
+ config = GPTConfig(**json.load(f))
15
+ model = GPT(config)
16
+ state_dict = load_file("model.safetensors")
17
+ model.load_state_dict(state_dict)
18
+ model.eval()
19
+
20
+ import tiktoken
21
+ enc = tiktoken.get_encoding("gpt2")
22
+ ids = enc.encode_ordinary("Once upon a time,")
23
+ x = torch.tensor([ids], dtype=torch.long)
24
+ out = model.generate(x, max_new_tokens=100, temperature=0.8, top_k=50,
25
+ eot_token=enc.eot_token, repetition_penalty=1.3)
26
+ print(enc.decode(out[0].tolist()))
27
+ """
28
+
29
+ import math
30
+ from dataclasses import dataclass
31
+
32
+ import torch
33
+ import torch.nn as nn
34
+ import torch.nn.functional as F
35
+
36
+
37
+ @dataclass
38
+ class GPTConfig:
39
+ vocab_size: int = 50257
40
+ block_size: int = 1024
41
+ n_layer: int = 14
42
+ n_head: int = 10
43
+ n_embd: int = 640
44
+ dropout: float = 0.0
45
+ bias: bool = True
46
+
47
+
48
+ class CausalSelfAttention(nn.Module):
49
+ def __init__(self, config):
50
+ super().__init__()
51
+ assert config.n_embd % config.n_head == 0
52
+ self.n_head = config.n_head
53
+ self.n_embd = config.n_embd
54
+ self.c_attn = nn.Linear(config.n_embd, 3 * config.n_embd, bias=config.bias)
55
+ self.c_proj = nn.Linear(config.n_embd, config.n_embd, bias=config.bias)
56
+ self.attn_dropout = nn.Dropout(config.dropout)
57
+ self.resid_dropout = nn.Dropout(config.dropout)
58
+ self.dropout = config.dropout
59
+
60
+ def forward(self, x):
61
+ B, T, C = x.shape
62
+ q, k, v = self.c_attn(x).split(self.n_embd, dim=2)
63
+ q = q.view(B, T, self.n_head, C // self.n_head).transpose(1, 2)
64
+ k = k.view(B, T, self.n_head, C // self.n_head).transpose(1, 2)
65
+ v = v.view(B, T, self.n_head, C // self.n_head).transpose(1, 2)
66
+ y = F.scaled_dot_product_attention(
67
+ q, k, v, is_causal=True,
68
+ dropout_p=self.dropout if self.training else 0.0,
69
+ )
70
+ y = y.transpose(1, 2).contiguous().view(B, T, C)
71
+ return self.resid_dropout(self.c_proj(y))
72
+
73
+
74
+ class MLP(nn.Module):
75
+ def __init__(self, config):
76
+ super().__init__()
77
+ self.c_fc = nn.Linear(config.n_embd, 4 * config.n_embd, bias=config.bias)
78
+ self.gelu = nn.GELU()
79
+ self.c_proj = nn.Linear(4 * config.n_embd, config.n_embd, bias=config.bias)
80
+ self.dropout = nn.Dropout(config.dropout)
81
+
82
+ def forward(self, x):
83
+ return self.dropout(self.c_proj(self.gelu(self.c_fc(x))))
84
+
85
+
86
+ class Block(nn.Module):
87
+ def __init__(self, config):
88
+ super().__init__()
89
+ self.ln_1 = nn.LayerNorm(config.n_embd)
90
+ self.attn = CausalSelfAttention(config)
91
+ self.ln_2 = nn.LayerNorm(config.n_embd)
92
+ self.mlp = MLP(config)
93
+
94
+ def forward(self, x):
95
+ x = x + self.attn(self.ln_1(x))
96
+ x = x + self.mlp(self.ln_2(x))
97
+ return x
98
+
99
+
100
+ class GPT(nn.Module):
101
+ def __init__(self, config):
102
+ super().__init__()
103
+ self.config = config
104
+ self.transformer = nn.ModuleDict(dict(
105
+ wte=nn.Embedding(config.vocab_size, config.n_embd),
106
+ wpe=nn.Embedding(config.block_size, config.n_embd),
107
+ drop=nn.Dropout(config.dropout),
108
+ h=nn.ModuleList([Block(config) for _ in range(config.n_layer)]),
109
+ ln_f=nn.LayerNorm(config.n_embd),
110
+ ))
111
+ self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
112
+ self.transformer.wte.weight = self.lm_head.weight
113
+ self.apply(self._init_weights)
114
+ for pn, p in self.named_parameters():
115
+ if pn.endswith("c_proj.weight"):
116
+ nn.init.normal_(p, mean=0.0, std=0.02 / math.sqrt(2 * config.n_layer))
117
+
118
+ def _init_weights(self, module):
119
+ if isinstance(module, nn.Linear):
120
+ nn.init.normal_(module.weight, mean=0.0, std=0.02)
121
+ if module.bias is not None:
122
+ nn.init.zeros_(module.bias)
123
+ elif isinstance(module, nn.Embedding):
124
+ nn.init.normal_(module.weight, mean=0.0, std=0.02)
125
+
126
+ def forward(self, idx, targets=None):
127
+ B, T = idx.shape
128
+ assert T <= self.config.block_size, "sequence longer than block_size"
129
+ pos = torch.arange(0, T, dtype=torch.long, device=idx.device)
130
+ x = self.transformer.drop(self.transformer.wte(idx) + self.transformer.wpe(pos))
131
+ for block in self.transformer.h:
132
+ x = block(x)
133
+ x = self.transformer.ln_f(x)
134
+ logits = self.lm_head(x)
135
+ loss = None
136
+ if targets is not None:
137
+ loss = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1), ignore_index=-1)
138
+ return logits, loss
139
+
140
+ @torch.no_grad()
141
+ def generate(self, idx, max_new_tokens, temperature=1.0, top_k=None, eot_token=None,
142
+ repetition_penalty=1.0):
143
+ for _ in range(max_new_tokens):
144
+ idx_cond = idx if idx.size(1) <= self.config.block_size else idx[:, -self.config.block_size:]
145
+ logits, _ = self(idx_cond)
146
+ logits = logits[:, -1, :] / temperature
147
+ if repetition_penalty != 1.0:
148
+ for seen_id in set(idx[0].tolist()):
149
+ if logits[0, seen_id] > 0:
150
+ logits[0, seen_id] /= repetition_penalty
151
+ else:
152
+ logits[0, seen_id] *= repetition_penalty
153
+ if top_k is not None:
154
+ v, _ = torch.topk(logits, min(top_k, logits.size(-1)))
155
+ logits[logits < v[:, [-1]]] = float("-inf")
156
+ probs = F.softmax(logits, dim=-1)
157
+ idx_next = torch.multinomial(probs, num_samples=1)
158
+ idx = torch.cat((idx, idx_next), dim=1)
159
+ if eot_token is not None and idx_next.item() == eot_token:
160
+ break
161
+ return idx