sandyGPT / chat.py
sandysanta's picture
Initial upload: 107M nanoGPT, val loss 3.41
2a4bfe1 verified
Raw History Blame Contribute Delete
1.36 kB
# Interactive prompt loop. Run from this folder: python chat.py (needs torch, tiktoken, safetensors)
# Commands: /t 0.9 (temperature) /n 150 (max new tokens) /k 50 (top_k) empty line or Ctrl-D quits.
import json, torch, tiktoken
from safetensors.torch import load_file
from model import GPT, GPTConfig
dev = 'cuda' if torch.cuda.is_available() else 'cpu'
c = json.load(open('config.json'))
model = GPT(GPTConfig(**{k: c[k] for k in ('n_layer', 'n_head', 'n_embd', 'block_size', 'bias', 'vocab_size', 'dropout')}))
model.load_state_dict(load_file('model.safetensors'), strict=False) # lm_head is tied to wte, absent from file
model.eval().to(dev)
enc = tiktoken.get_encoding('gpt2')
cfg = {'t': 0.8, 'n': 150, 'k': 50}
print(f"loaded {sum(p.numel() for p in model.parameters())/1e6:.1f}M params. base model: it continues text, it does not answer.")
while True:
try:
s = input('\n> ')
except EOFError:
break
if not s.strip():
break
if s.startswith('/') and s[1:2] in cfg:
cfg[s[1]] = (float if s[1] == 't' else int)(s[2:].strip())
print(cfg)
continue
x = torch.tensor([enc.encode_ordinary(s)], device=dev)
with torch.no_grad(), torch.autocast(dev, dtype=torch.bfloat16):
y = model.generate(x, cfg['n'], temperature=cfg['t'], top_k=cfg['k'])
print(enc.decode(y[0].tolist()))