yat343 commited on
Commit
48b29a6
·
verified ·
1 Parent(s): e91718f

Upload generate.py

Browse files
Files changed (1) hide show
  1. generate.py +177 -0
generate.py ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Inference script for nano GPT.
3
+
4
+ Usage:
5
+ python generate.py --prompt "ROMEO:" --length 500 --temperature 0.8
6
+
7
+ Loads best.pt (saved by train_standalone.py) and generates text.
8
+ """
9
+
10
+ import argparse
11
+ import torch
12
+ import torch.nn as nn
13
+ from torch.nn import functional as F
14
+ from dataclasses import dataclass
15
+
16
+
17
+ @dataclass
18
+ class GPTConfig:
19
+ block_size: int = 256
20
+ vocab_size: int = 65
21
+ n_layer: int = 4
22
+ n_head: int = 4
23
+ n_embd: int = 256
24
+ dropout: float = 0.0
25
+
26
+
27
+ class CausalSelfAttention(nn.Module):
28
+ def __init__(self, config: GPTConfig):
29
+ super().__init__()
30
+ assert config.n_embd % config.n_head == 0
31
+ self.c_attn = nn.Linear(config.n_embd, 3 * config.n_embd)
32
+ self.c_proj = nn.Linear(config.n_embd, config.n_embd)
33
+ self.n_head = config.n_head
34
+ self.n_embd = config.n_embd
35
+ self.register_buffer(
36
+ "bias",
37
+ torch.tril(torch.ones(config.block_size, config.block_size))
38
+ .view(1, 1, config.block_size, config.block_size)
39
+ )
40
+
41
+ def forward(self, x):
42
+ B, T, C = x.size()
43
+ qkv = self.c_attn(x)
44
+ q, k, v = qkv.split(self.n_embd, dim=2)
45
+ head_size = C // self.n_head
46
+ q = q.view(B, T, self.n_head, head_size).transpose(1, 2)
47
+ k = k.view(B, T, self.n_head, head_size).transpose(1, 2)
48
+ v = v.view(B, T, self.n_head, head_size).transpose(1, 2)
49
+ att = (q @ k.transpose(-2, -1)) * (1.0 / (head_size ** 0.5))
50
+ att = att.masked_fill(self.bias[:, :, :T, :T] == 0, float("-inf"))
51
+ att = F.softmax(att, dim=-1)
52
+ y = att @ v
53
+ y = y.transpose(1, 2).contiguous().view(B, T, C)
54
+ y = self.c_proj(y)
55
+ return y
56
+
57
+
58
+ class MLP(nn.Module):
59
+ def __init__(self, config: GPTConfig):
60
+ super().__init__()
61
+ self.c_fc = nn.Linear(config.n_embd, 4 * config.n_embd)
62
+ self.gelu = nn.GELU()
63
+ self.c_proj = nn.Linear(4 * config.n_embd, config.n_embd)
64
+ self.dropout = nn.Dropout(config.dropout)
65
+
66
+ def forward(self, x):
67
+ x = self.c_fc(x)
68
+ x = self.gelu(x)
69
+ x = self.c_proj(x)
70
+ x = self.dropout(x)
71
+ return x
72
+
73
+
74
+ class Block(nn.Module):
75
+ def __init__(self, config: GPTConfig):
76
+ super().__init__()
77
+ self.ln_1 = nn.LayerNorm(config.n_embd)
78
+ self.attn = CausalSelfAttention(config)
79
+ self.ln_2 = nn.LayerNorm(config.n_embd)
80
+ self.mlp = MLP(config)
81
+
82
+ def forward(self, x):
83
+ x = x + self.attn(self.ln_1(x))
84
+ x = x + self.mlp(self.ln_2(x))
85
+ return x
86
+
87
+
88
+ class GPT(nn.Module):
89
+ def __init__(self, config: GPTConfig):
90
+ super().__init__()
91
+ self.config = config
92
+ self.transformer = nn.ModuleDict({
93
+ "wte": nn.Embedding(config.vocab_size, config.n_embd),
94
+ "wpe": nn.Embedding(config.block_size, config.n_embd),
95
+ "h": nn.ModuleList([Block(config) for _ in range(config.n_layer)]),
96
+ "ln_f": nn.LayerNorm(config.n_embd),
97
+ })
98
+ self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
99
+ self.transformer.wte.weight = self.lm_head.weight
100
+ self.apply(self._init_weights)
101
+
102
+ def _init_weights(self, module):
103
+ if isinstance(module, nn.Linear):
104
+ torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
105
+ if module.bias is not None:
106
+ torch.nn.init.zeros_(module.bias)
107
+ elif isinstance(module, nn.Embedding):
108
+ torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
109
+
110
+ def forward(self, idx, targets=None):
111
+ B, T = idx.size()
112
+ assert T <= self.config.block_size
113
+ pos = torch.arange(0, T, dtype=torch.long, device=idx.device)
114
+ x = self.transformer.wte(idx) + self.transformer.wpe(pos)
115
+ for block in self.transformer.h:
116
+ x = block(x)
117
+ x = self.transformer.ln_f(x)
118
+ logits = self.lm_head(x)
119
+ loss = None
120
+ if targets is not None:
121
+ loss = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1), ignore_index=-1)
122
+ return logits, loss
123
+
124
+ def generate(self, idx, max_new_tokens, temperature=1.0, top_k=None):
125
+ for _ in range(max_new_tokens):
126
+ idx_cond = idx if idx.size(1) <= self.config.block_size else idx[:, -self.config.block_size:]
127
+ logits, _ = self(idx_cond)
128
+ logits = logits[:, -1, :]
129
+ if top_k is not None:
130
+ v, _ = torch.topk(logits, top_k, dim=-1)
131
+ logits[logits < v[:, [-1]]] = float("-inf")
132
+ probs = F.softmax(logits / temperature, dim=-1)
133
+ idx_next = torch.multinomial(probs, num_samples=1)
134
+ idx = torch.cat((idx, idx_next), dim=1)
135
+ return idx
136
+
137
+
138
+ def main():
139
+ parser = argparse.ArgumentParser()
140
+ parser.add_argument("--checkpoint", default="best.pt", help="Path to checkpoint")
141
+ parser.add_argument("--prompt", default="\n", help="Starting text")
142
+ parser.add_argument("--length", type=int, default=500, help="Tokens to generate")
143
+ parser.add_argument("--temperature", type=float, default=1.0, help="Sampling temperature")
144
+ parser.add_argument("--top_k", type=int, default=40, help="Top-k sampling")
145
+ parser.add_argument("--seed", type=int, default=1337, help="Random seed")
146
+ args = parser.parse_args()
147
+
148
+ torch.manual_seed(args.seed)
149
+ device = "cuda" if torch.cuda.is_available() else "cpu"
150
+
151
+ # Load checkpoint
152
+ ckpt = torch.load(args.checkpoint, map_location=device, weights_only=False)
153
+ config = ckpt["config"]
154
+ stoi = ckpt["stoi"]
155
+ itos = ckpt["itos"]
156
+
157
+ # Build model and load weights
158
+ model = GPT(config)
159
+ model.load_state_dict(ckpt["model_state_dict"])
160
+ model.to(device)
161
+ model.eval()
162
+
163
+ # Encode prompt
164
+ encode = lambda s: [stoi[c] for c in s]
165
+ decode = lambda l: "".join([itos[i] for i in l])
166
+
167
+ context = torch.tensor(encode(args.prompt), dtype=torch.long, device=device).unsqueeze(0)
168
+
169
+ # Generate
170
+ with torch.no_grad():
171
+ generated = model.generate(context, args.length, temperature=args.temperature, top_k=args.top_k)
172
+
173
+ print(decode(generated[0].tolist()))
174
+
175
+
176
+ if __name__ == "__main__":
177
+ main()