""" chat.py - ask the fine-tuned model questions. Wraps your question in the same format finetune.py trained on, generates one token at a time, and stops when the model emits end-of-text. python chat.py --ckpt out_chat/ckpt.pt # interactive python chat.py --ckpt out_chat/ckpt.pt --question "What is the capital of France?" """ import argparse import sys import tiktoken import torch from model import GPT, GPTConfig EOT = 50256 def main(): ap = argparse.ArgumentParser() ap.add_argument("--ckpt", required=True) ap.add_argument("--question", default=None, help="ask one question and exit") ap.add_argument("--context", default="", help="optional passage the answer should come from") ap.add_argument("--max-new-tokens", type=int, default=200) ap.add_argument("--temperature", type=float, default=0.3) ap.add_argument("--top-k", type=int, default=50) ap.add_argument("--seed", type=int, default=None) args = ap.parse_args() device = "cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu" if args.seed is not None: torch.manual_seed(args.seed) ckpt = torch.load(args.ckpt, map_location=device) model = GPT(GPTConfig(**ckpt["config"])).to(device) model.load_state_dict(ckpt["model"]) model.eval() enc = tiktoken.get_encoding("gpt2") top_k = args.top_k if args.top_k > 0 else None print(f"loaded {args.ckpt} on {device}. Empty line or Ctrl-C to quit.", file=sys.stderr) def answer(question): prompt = "" if args.context: prompt += "Context: " + args.context.strip() + "\n\n" prompt += "Question: " + question.strip() + "\nAnswer:" idx = torch.tensor([enc.encode_ordinary(prompt)], dtype=torch.long, device=device) generated, shown = [], "" for tok in model.generate(idx, args.max_new_tokens, temperature=args.temperature, top_k=top_k): if tok == EOT: break generated.append(tok) text = enc.decode(generated) print(text[len(shown):], end="", flush=True) shown = text print() if args.question: answer(args.question) return while True: try: q = input("You: ") except (EOFError, KeyboardInterrupt): print() break if not q.strip(): break print("Model:", end="") answer(q) if __name__ == "__main__": main()