""" generate.py - next-token generation from a trained checkpoint. Takes a prompt, feeds it to the model, and prints the text one token at a time as each next token is sampled. Examples: python generate.py --ckpt out_tiny/ckpt.pt --prompt "The capital of France is" python generate.py --ckpt out_124M/ckpt.pt --prompt "Photosynthesis is" --max-new-tokens 300 --temperature 0.7 """ import argparse import sys import tiktoken import torch from model import GPT, GPTConfig def main(): ap = argparse.ArgumentParser() ap.add_argument("--ckpt", required=True) ap.add_argument("--prompt", default="\n") ap.add_argument("--max-new-tokens", type=int, default=200) ap.add_argument("--temperature", type=float, default=0.8, help="lower is more predictable, 1.0 is the raw model") ap.add_argument("--top-k", type=int, default=50, help="sample only among the k most likely next tokens; 0 disables") ap.add_argument("--samples", type=int, default=1) 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) cfg = GPTConfig(**ckpt["config"]) model = GPT(cfg).to(device) model.load_state_dict(ckpt["model"]) model.eval() print(f"loaded {args.ckpt}: {model.num_params()/1e6:.1f}M parameters, trained {ckpt['step']} steps, device {device}", file=sys.stderr) enc = tiktoken.get_encoding("gpt2") prompt_ids = enc.encode_ordinary(args.prompt) top_k = args.top_k if args.top_k > 0 else None for s in range(args.samples): if args.samples > 1: print(f"\n----- sample {s + 1} -----") idx = torch.tensor([prompt_ids], dtype=torch.long, device=device) print(args.prompt, end="", flush=True) generated = [] shown = "" for tok in model.generate(idx, args.max_new_tokens, temperature=args.temperature, top_k=top_k): generated.append(tok) # decode the whole sequence each time so multi-byte characters print correctly text = enc.decode(generated) print(text[len(shown):], end="", flush=True) shown = text print() if __name__ == "__main__": main()