File size: 2,871 Bytes
7f1e014
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
"""Qualitative samples from the final checkpoint.

Loads the model once, then generates completions for several prompts at
different sampling settings (default temp 0.8/top_k 40, and greedy).

Usage:
    uv run python scripts/qualitative_samples.py
    uv run python scripts/qualitative_samples.py --max-new-tokens 150
"""

import argparse
import sys
import time
from pathlib import Path

import torch

PROJECT_ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(PROJECT_ROOT))

from src.model import GPT  # noqa: E402
from src.tokenizer import Tokenizer  # noqa: E402

# (label, prompt, temperature, top_k)
PROMPTS = [
    ("default sampling", "Once upon a time", 0.8, 40),
    ("default sampling", "One day, a little girl named Lily went to the park with her mom.", 0.8, 40),
    ("default sampling", "The little dog was very sad because", 0.8, 40),
    ("default sampling", "Tom and Ben were playing in the garden when they found a", 0.8, 40),
    ("lower temperature", "Once upon a time, there was a small rabbit who lived in the forest.", 0.5, 40),
    ("greedy (temp=0)", "Once upon a time, there was a little boy named Tim.", 0.0, None),
]


def load_model(checkpoint_path: str, device: torch.device):
    ckpt = torch.load(checkpoint_path, map_location="cpu", weights_only=False)
    model = GPT(ckpt["config"].model)
    model.load_state_dict(ckpt["model"])
    step = ckpt["step"]
    del ckpt  # free ~1.5 GB host RAM (optimizer state)
    model.to(device).to(torch.bfloat16)
    model.eval()
    return model, step


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--checkpoint", default="checkpoints/step_050000.pt")
    ap.add_argument("--max-new-tokens", type=int, default=180)
    ap.add_argument("--seed", type=int, default=42)
    args = ap.parse_args()

    if not torch.cuda.is_available():
        raise SystemExit("CUDA not available")
    device = torch.device("cuda")
    torch.manual_seed(args.seed)
    torch.cuda.manual_seed(args.seed)

    t0 = time.time()
    model, step = load_model(args.checkpoint, device)
    tokenizer = Tokenizer()
    print(f"Loaded step {step} in {time.time() - t0:.1f}s\n")

    for i, (label, prompt, temperature, top_k) in enumerate(PROMPTS, 1):
        input_ids = torch.tensor([tokenizer.encode(prompt)], device=device)
        t = time.time()
        out_ids = model.generate(
            input_ids,
            max_new_tokens=args.max_new_tokens,
            temperature=temperature,
            top_k=top_k,
        )
        text = tokenizer.decode(out_ids[0].tolist())
        dt = time.time() - t
        print("=" * 78)
        print(f"Sample {i}/{len(PROMPTS)} | {label} | temp={temperature} "
              f"top_k={top_k} | {args.max_new_tokens} tokens in {dt:.1f}s")
        print("-" * 78)
        print(text)
        print()


if __name__ == "__main__":
    main()