mnauf/redditGPT
0
1"""2Sample from a trained model3"""4import os5import pickle6from contextlib import nullcontext7import torch8import tiktoken9from model import GPTConfig, GPT10import gradio as gr11# -----------------------------------------------------------------------------12init_from = 'resume' # either 'resume' (from an out_dir) or a gpt2 variant (e.g. 'gpt2-xl')13out_dir = 'model' # ignored if init_from is not 'resume'14start = "\n" # or "<|endoftext|>" or etc. Can also specify a file, use as: "FILE:prompt.txt"15num_samples = 1 # number of samples to draw16max_new_tokens = 500 # number of tokens generated in each sample17temperature = 0.8 # 1.0 = no change, < 1.0 = less random, > 1.0 = more random, in predictions18top_k = 200 # retain only the top_k most likely tokens, clamp others to have 0 probability19seed = 133720device = 'cpu' # examples: 'cpu', 'cuda', 'cuda:0', 'cuda:1', etc.21dtype = 'bfloat16' # 'float32' or 'bfloat16' or 'float16'22compile = True # use PyTorch 2.0 to compile the model to be faster23exec(open('configurator.py').read()) # overrides from command line or config file24# -----------------------------------------------------------------------------25 26# torch.manual_seed(seed)27# torch.cuda.manual_seed(seed)28torch.backends.cuda.matmul.allow_tf32 = True # allow tf32 on matmul29torch.backends.cudnn.allow_tf32 = True # allow tf32 on cudnn30device_type = 'cuda' if 'cuda' in device else 'cpu' # for later use in torch.autocast31ptdtype = {'float32': torch.float32, 'bfloat16': torch.bfloat16, 'float16': torch.float16}[dtype]32ctx = nullcontext() if device_type == 'cpu' else torch.amp.autocast(device_type=device_type, dtype=ptdtype)33 34# model35if init_from == 'resume':36 # init from a model saved in a specific directory37 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)47elif init_from.startswith('gpt2'):48 # init from a given GPT-2 model49 model = GPT.from_pretrained(init_from, dict(dropout=0.0))50 51model.eval()52model.to(device)53if 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 folder57load_meta = False58if 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)61if 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 schemes66 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])69else:70 # ok let's assume gpt-2 encodings by default71 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 77def generate_text(start):78 start_ids = encode(start)79 x = (torch.tensor(start_ids, dtype=torch.long, device=device)[None, ...])80 output = ""81 # run generation82 with torch.no_grad():83 with ctx:84 for k in range(num_samples):85 y = model.generate(x, max_new_tokens, temperature=temperature, top_k=top_k)86 output += decode(y[0].tolist())87 return output