| """ |
| Sample from a trained model |
| """ |
| import os |
| import pickle |
| from contextlib import nullcontext |
| import torch |
| import tiktoken |
| from model import GPTConfig, GPT |
|
|
| |
| init_from = 'resume' |
| out_dir = 'out' |
| start = "\n" |
| num_samples = 10 |
| max_new_tokens = 500 |
| temperature = 0.0 |
| top_k = 200 |
| seed = 1337 |
| device = 'cuda' |
| dtype = 'float16' |
| compile = False |
| exec(open('configurator.py').read()) |
| |
|
|
| torch.manual_seed(seed) |
| torch.cuda.manual_seed(seed) |
| torch.backends.cuda.matmul.allow_tf32 = True |
| torch.backends.cudnn.allow_tf32 = True |
| device_type = 'cuda' if 'cuda' in device else 'cpu' |
| 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) |
|
|
| |
| if init_from == 'resume': |
| |
| 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) |
| elif init_from.startswith('gpt2'): |
| |
| model = GPT.from_pretrained(init_from, dict(dropout=0.0)) |
|
|
| model.eval() |
| model.to(device) |
| if compile: |
| model = torch.compile(model) |
|
|
| |
| load_meta = False |
| if init_from == 'resume' and 'config' in checkpoint and 'dataset' in checkpoint['config']: |
| meta_path = os.path.join('data', checkpoint['config']['dataset'], 'meta.pkl') |
| load_meta = os.path.exists(meta_path) |
| if load_meta: |
| print(f"Loading meta from {meta_path}...") |
| with open(meta_path, 'rb') as f: |
| meta = pickle.load(f) |
| stoi, itos = meta['stoi'], meta['itos'] |
| char_to_token = meta["char_to_token"] |
| chars_to_skip = meta["chars_to_skip"] |
| |
| def encode(s): |
| encoded = [] |
| skip = 0 |
| for char in s: |
| if skip: |
| skip -= 1 |
| continue |
| else: |
| skip = chars_to_skip[char] |
| encoded.append(stoi[char_to_token[char]]) |
| return encoded |
| |
| def decode(l): |
| return ''.join([itos[i] for i in l]) |
| else: |
| raise RuntimeError("No meta.pkl found for sorting! Cannot find token encoder or decoder.") |
|
|
| |
| if start.startswith('FILE:'): |
| with open(start[5:], 'r', encoding='utf-8') as f: |
| start = f.read() |
| start_ids = encode(start) |
| x = (torch.tensor(start_ids, dtype=torch.long, device=device)[None, ...]) |
|
|
| |
| with torch.no_grad(): |
| with ctx: |
| for k in range(num_samples): |
| y = model.generate(x, max_new_tokens, temperature=temperature, top_k=top_k) |
| print(decode(y[0].tolist())) |
| print('---------------') |
|
|