ibrim commited on
Commit
ebc297d
1 Parent(s): a2fec66

Upload 2 files

Browse files
nano_gpt/app.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import pickle
3
+ from contextlib import nullcontext
4
+ import torch
5
+ import tiktoken
6
+ from model import GPTConfig, GPT
7
+ import gradio as gr
8
+
9
+ def sample_from_trained_model(start="\n", init_from='resume', out_dir='out-shakespeare-char', num_samples=1,
10
+ max_new_tokens=500, temperature=0.8, top_k=200, seed=1337, device='cpu', compile=False):
11
+ # Set the dtype
12
+ dtype = 'bfloat16' if torch.cuda.is_available() and torch.cuda.is_bf16_supported() else 'float16'
13
+
14
+ # Setup seed and device
15
+ torch.manual_seed(seed)
16
+ torch.cuda.manual_seed(seed)
17
+ torch.backends.cuda.matmul.allow_tf32 = True
18
+ torch.backends.cudnn.allow_tf32 = True
19
+ device_type = 'cuda' if 'cuda' in device else 'cpu'
20
+ ptdtype = {'float32': torch.float32, 'bfloat16': torch.bfloat16, 'float16': torch.float16}[dtype]
21
+ ctx = nullcontext() if device_type == 'cpu' else torch.amp.autocast(device_type=device_type, dtype=ptdtype)
22
+
23
+ # Load model
24
+ if init_from == 'resume':
25
+ ckpt_path = os.path.join(out_dir, 'ckpt.pt')
26
+ checkpoint = torch.load(ckpt_path, map_location=device)
27
+ gptconf = GPTConfig(**checkpoint['model_args'])
28
+ model = GPT(gptconf)
29
+ state_dict = checkpoint['model']
30
+ unwanted_prefix = '_orig_mod.'
31
+ for k, v in list(state_dict.items()):
32
+ if k.startswith(unwanted_prefix):
33
+ state_dict[k[len(unwanted_prefix):]] = state_dict.pop(k)
34
+ model.load_state_dict(state_dict)
35
+ elif init_from.startswith('gpt2'):
36
+ model = GPT.from_pretrained(init_from, dict(dropout=0.0))
37
+
38
+ model.eval()
39
+ model.to(device)
40
+ if compile:
41
+ model = torch.compile(model)
42
+
43
+ # Load meta data if available
44
+ load_meta = False
45
+ if init_from == 'resume' and 'config' in checkpoint and 'dataset' in checkpoint['config']:
46
+ meta_path = os.path.join('data', checkpoint['config']['dataset'], 'meta.pkl')
47
+ load_meta = os.path.exists(meta_path)
48
+ if load_meta:
49
+ print(f"Loading meta from {meta_path}...")
50
+ with open(meta_path, 'rb') as f:
51
+ meta = pickle.load(f)
52
+ stoi, itos = meta['stoi'], meta['itos']
53
+ encode = lambda s: [stoi[c] for c in s]
54
+ decode = lambda l: ''.join([itos[i] for i in l])
55
+ else:
56
+ print("No meta.pkl found, assuming GPT-2 encodings...")
57
+ enc = tiktoken.get_encoding("gpt2")
58
+ encode = lambda s: enc.encode(s, allowed_special={""})
59
+ decode = lambda l: enc.decode(l)
60
+
61
+ # Encode the beginning of the prompt
62
+ if start.startswith('FILE:'):
63
+ with open(start[5:], 'r', encoding='utf-8') as f:
64
+ start = f.read()
65
+ start_ids = encode(start)
66
+ x = (torch.tensor(start_ids, dtype=torch.long, device=device)[None, ...])
67
+
68
+ # Run generation
69
+ with torch.no_grad():
70
+ with ctx:
71
+ for k in range(num_samples):
72
+ y = model.generate(x, max_new_tokens, temperature=temperature, top_k=top_k)
73
+ return decode(y[0].tolist())
74
+
75
+ iface = gr.Interface(fn=sample_from_trained_model, inputs="text", outputs="textbox",
76
+ title="GPT Text Generator", description="Enter a prompt to generate text.")
77
+
78
+ iface.launch(share=True)
nano_gpt/out-shakespeare-char/ckpt.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b46b1b2a1b037525c9c87dbc6b7f728851c729ecb4e43f81f3f56552147ada52
3
+ size 128986474