File size: 2,009 Bytes
673d750 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | """Generate text from a trained GPT checkpoint."""
from __future__ import annotations
import argparse
from pathlib import Path
import torch
from tokenizers import Tokenizer
from model import GPT, GPTConfig
from train import autocast_context
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--checkpoint", type=Path, default=Path("checkpoints/best.pt"))
parser.add_argument("--tokenizer", type=Path, default=Path("tokenizer.json"))
parser.add_argument("--prompt", required=True)
parser.add_argument("--max-new-tokens", type=int, default=200)
parser.add_argument("--temperature", type=float, default=0.8)
parser.add_argument("--top-k", type=int, default=40)
parser.add_argument("--device", choices=("auto", "cuda", "cpu"), default="auto")
args = parser.parse_args()
if not args.checkpoint.is_file():
parser.error(f"Checkpoint not found: {args.checkpoint}")
if not args.tokenizer.is_file():
parser.error(f"Tokenizer not found: {args.tokenizer}")
if args.device == "cuda" and not torch.cuda.is_available():
parser.error("CUDA was requested but is unavailable")
device = torch.device(
"cuda" if args.device == "cuda" or (args.device == "auto" and torch.cuda.is_available()) else "cpu"
)
checkpoint = torch.load(args.checkpoint, map_location=device, weights_only=False)
config = GPTConfig(**checkpoint["config"])
model = GPT(config).to(device)
model.load_state_dict(checkpoint["model"])
model.eval()
tokenizer = Tokenizer.from_file(str(args.tokenizer))
eos_token_id = tokenizer.token_to_id("<|endoftext|>")
input_ids = torch.tensor([tokenizer.encode(args.prompt).ids], dtype=torch.long, device=device)
with torch.inference_mode(), autocast_context(device):
output = model.generate(
input_ids,
max_new_tokens=args.max_new_tokens,
temperature=args.temperature,
top_k=args.top_k,
eos_token_id=eos_token_id,
)
print(tokenizer.decode(output[0].tolist(), skip_special_tokens=True))
if __name__ == "__main__":
main() |