File size: 2,524 Bytes
dc9424f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
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()