ibrim commited on
Commit
23e3cac
1 Parent(s): ab422cd

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +78 -61
app.py CHANGED
@@ -1,3 +1,6 @@
 
 
 
1
  import os
2
  import pickle
3
  from contextlib import nullcontext
@@ -5,74 +8,88 @@ 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)
 
1
+ """
2
+ Sample from a trained model
3
+ """
4
  import os
5
  import pickle
6
  from contextlib import nullcontext
 
8
  import tiktoken
9
  from model import GPTConfig, GPT
10
  import gradio as gr
11
+ # -----------------------------------------------------------------------------
12
+ init_from = 'resume' # either 'resume' (from an out_dir) or a gpt2 variant (e.g. 'gpt2-xl')
13
+ out_dir = 'out-shakespeare-char' # ignored if init_from is not 'resume'
14
+ start = "\n" # or "<|endoftext|>" or etc. Can also specify a file, use as: "FILE:prompt.txt"
15
+ num_samples = 10 # number of samples to draw
16
+ max_new_tokens = 500 # number of tokens generated in each sample
17
+ temperature = 0.8 # 1.0 = no change, < 1.0 = less random, > 1.0 = more random, in predictions
18
+ top_k = 200 # retain only the top_k most likely tokens, clamp others to have 0 probability
19
+ seed = 1337
20
+ device = 'cpu' # examples: 'cpu', 'cuda', 'cuda:0', 'cuda:1', etc.
21
+ dtype = 'bfloat16' if torch.cuda.is_available() and torch.cuda.is_bf16_supported() else 'float16' # 'float32' or 'bfloat16' or 'float16'
22
+ compile = False # use PyTorch 2.0 to compile the model to be faster
23
+ #exec(open('configurator.py').read()) # overrides from command line or config file
24
+ # -----------------------------------------------------------------------------
25
 
26
+ torch.manual_seed(seed)
27
+ torch.cuda.manual_seed(seed)
28
+ torch.backends.cuda.matmul.allow_tf32 = True # allow tf32 on matmul
29
+ torch.backends.cudnn.allow_tf32 = True # allow tf32 on cudnn
30
+ device_type = 'cuda' if 'cuda' in device else 'cpu' # for later use in torch.autocast
31
+ ptdtype = {'float32': torch.float32, 'bfloat16': torch.bfloat16, 'float16': torch.float16}[dtype]
32
+ ctx = nullcontext() if device_type == 'cpu' else torch.amp.autocast(device_type=device_type, dtype=ptdtype)
 
 
 
 
 
 
33
 
34
+ # model
35
+ if init_from == 'resume':
36
+ # init from a model saved in a specific directory
37
+ ckpt_path = os.path.join(out_dir, 'ckpt.pt')
38
+ checkpoint = torch.load(ckpt_path, map_location=device)
39
+ gptconf = GPTConfig(**checkpoint['model_args'])
40
+ model = GPT(gptconf)
41
+ state_dict = checkpoint['model']
42
+ unwanted_prefix = '_orig_mod.'
43
+ for k,v in list(state_dict.items()):
44
+ if k.startswith(unwanted_prefix):
45
+ state_dict[k[len(unwanted_prefix):]] = state_dict.pop(k)
46
+ model.load_state_dict(state_dict)
47
+ elif init_from.startswith('gpt2'):
48
+ # init from a given GPT-2 model
49
+ model = GPT.from_pretrained(init_from, dict(dropout=0.0))
50
 
51
+ model.eval()
52
+ model.to(device)
53
+ if compile:
54
+ model = torch.compile(model) # requires PyTorch 2.0 (optional)
55
 
56
+ # look for the meta pickle in case it is available in the dataset folder
57
+ load_meta = False
58
+ if init_from == 'resume' and 'config' in checkpoint and 'dataset' in checkpoint['config']: # older checkpoints might not have these...
59
+ meta_path = os.path.join('data', checkpoint['config']['dataset'], 'meta.pkl')
60
+ load_meta = os.path.exists(meta_path)
61
+ if load_meta:
62
+ print(f"Loading meta from {meta_path}...")
63
+ with open(meta_path, 'rb') as f:
64
+ meta = pickle.load(f)
65
+ # TODO want to make this more general to arbitrary encoder/decoder schemes
66
+ stoi, itos = meta['stoi'], meta['itos']
67
+ encode = lambda s: [stoi[c] for c in s]
68
+ decode = lambda l: ''.join([itos[i] for i in l])
69
+ else:
70
+ # ok let's assume gpt-2 encodings by default
71
+ print("No meta.pkl found, assuming GPT-2 encodings...")
72
+ enc = tiktoken.get_encoding("gpt2")
73
+ encode = lambda s: enc.encode(s, allowed_special={"<|endoftext|>"})
74
+ decode = lambda l: enc.decode(l)
75
 
76
+ # encode the beginning of the prompt
77
+ if start.startswith('FILE:'):
78
+ with open(start[5:], 'r', encoding='utf-8') as f:
79
+ start = f.read()
80
+ start_ids = encode(start)
81
+ x = (torch.tensor(start_ids, dtype=torch.long, device=device)[None, ...])
82
 
83
+ # run generation
84
+ with torch.no_grad():
85
+ with ctx:
86
+ for k in range(num_samples):
87
+ y = model.generate(x, max_new_tokens, temperature=temperature, top_k=top_k)
88
+ z = decode(y[0].tolist())
89
 
90
+ def show_text(prompt=z):
91
+ return prompt
92
+ iface = gr.Interface(fn=show_text, inputs=[], outputs="textbox",
93
  title="GPT Text Generator", description="Enter a prompt to generate text.")
94
 
95
  iface.launch(share=True)