1
0
mirror of https://github.com/osmarks/nanogpt-experiments.git synced 2024-11-10 20:09:58 +00:00
nanogpt-experiments/sample.py

60 lines
2.4 KiB
Python
Raw Normal View History

2022-12-28 00:58:19 +00:00
"""
Sample from a trained model
"""
import os
from contextlib import nullcontext
2022-12-28 00:58:19 +00:00
import torch
import tiktoken
from model import GPTConfig, GPT
2023-01-02 02:11:39 +00:00
# -----------------------------------------------------------------------------
out_dir = 'out'
start = "\n" # or "<|endoftext|>" or whatever you like
num_samples = 10 # number of samples to draw
max_new_tokens = 500 # number of tokens generated in each sample
temperature = 0.8 # higher temperature (up to 1) is more random, lower (down to 0) means more greedy
top_k = 200 # retain only the top_k most likely tokens, clamp others to have 0 probability
seed = 1337
device = 'cuda' # examples: 'cpu', 'cuda', 'cuda:0', 'cuda:1', etc.
dtype = 'bfloat16' # 'float32' or 'bfloat16' or 'float16'
compile = False # use PyTorch 2.0 to compile the model to be faster
exec(open('configurator.py').read()) # overrides from command line or config file
2023-01-02 02:11:39 +00:00
# -----------------------------------------------------------------------------
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
2022-12-28 00:58:19 +00:00
torch.backends.cuda.matmul.allow_tf32 = True # allow tf32 on matmul
torch.backends.cudnn.allow_tf32 = True # allow tf32 on cudnn
device_type = 'cuda' if 'cuda' in device else 'cpu' # for later use in torch.autocast
ptdtype = {'float32': torch.float32, 'bfloat16': torch.bfloat16, 'float16': torch.float16}[dtype]
ctx = nullcontext() if device_type == 'cpu' else torch.amp.autocast(device_type=device_type, dtype=ptdtype)
2022-12-28 00:58:19 +00:00
2023-01-02 02:11:39 +00:00
# model
2022-12-28 00:58:19 +00:00
ckpt_path = os.path.join(out_dir, 'ckpt.pt')
checkpoint = torch.load(ckpt_path, map_location=device)
gptconf = GPTConfig(**checkpoint['model_args'])
model = GPT(gptconf)
state_dict = checkpoint['model']
unwanted_prefix = '_orig_mod.'
for k,v in list(state_dict.items()):
if k.startswith(unwanted_prefix):
state_dict[k[len(unwanted_prefix):]] = state_dict.pop(k)
model.load_state_dict(state_dict)
2022-12-28 00:58:19 +00:00
model.eval()
model.to(device)
2023-01-02 02:11:39 +00:00
if compile:
model = torch.compile(model) # requires PyTorch 2.0 (optional)
2022-12-28 00:58:19 +00:00
2023-01-02 02:11:39 +00:00
# encode the beginning of the prompt
2022-12-28 00:58:19 +00:00
enc = tiktoken.get_encoding("gpt2")
2023-01-02 02:11:39 +00:00
start_ids = enc.encode(start, allowed_special={"<|endoftext|>"})
x = (torch.tensor(start_ids, dtype=torch.long, device=device)[None, ...])
2022-12-28 00:58:19 +00:00
# run generation
with torch.no_grad():
with ctx:
for k in range(num_samples):
2023-01-02 02:11:39 +00:00
y = model.generate(x, max_new_tokens, temperature=temperature, top_k=top_k)
print(enc.decode(y[0].tolist()))
print('---------------')