File size: 3,866 Bytes
cc7fa1f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
"""Interactive REPL for a trained Kat checkpoint.

  .venv/bin/python chat.py              # interactive
  .venv/bin/python chat.py --say "hi"   # one-shot, no stdin needed
"""
import argparse
import sys

import torch
from tokenizers import Tokenizer

from config import BOT, EOS, ROOT, USER
from model import Kat

CKPT_PATH = ROOT / "kat.pt"
TOKENIZER_PATH = ROOT / "tokenizer.json"


class KatChat:
    """Holds the rolling conversation as token ids and samples replies."""

    def __init__(self, temperature=0.8, top_k=40, max_new_tokens=60):
        if not CKPT_PATH.exists():
            sys.exit(f"no checkpoint at {CKPT_PATH} -- run train.py first")
        ckpt = torch.load(CKPT_PATH, map_location="cpu", weights_only=False)
        self.cfg = ckpt["cfg"]
        self.model = Kat(self.cfg)
        self.model.load_state_dict(ckpt["model"])
        self.model.eval()
        self.step, self.val_loss = ckpt["step"], ckpt["val_loss"]

        self.tok = Tokenizer.from_file(str(TOKENIZER_PATH))
        self.user_id = self.tok.token_to_id(USER)
        self.bot_id = self.tok.token_to_id(BOT)
        self.eos_id = self.tok.token_to_id(EOS)
        self.temperature, self.top_k, self.max_new_tokens = temperature, top_k, max_new_tokens
        self.history: list[int] = []

    def reset(self):
        self.history = []

    def say(self, text: str) -> str:
        self.history += [self.user_id] + self.tok.encode(text.strip().lower()).ids
        self.history.append(self.bot_id)

        # Leave room for the reply inside the context window, and drop whole
        # turns from the left rather than slicing mid-utterance.
        budget = self.cfg.block_size - self.max_new_tokens
        if len(self.history) > budget:
            self.history = self._trim(self.history, budget)

        idx = torch.tensor([self.history], dtype=torch.long)
        out = self.model.generate(
            idx, max_new_tokens=self.max_new_tokens,
            temperature=self.temperature, top_k=self.top_k,
            stop_tokens=(self.eos_id, self.user_id, self.bot_id),
        )
        new = out[0, len(self.history):].tolist()
        # Drop the trailing turn-boundary token: <|user|> belongs to the next
        # turn (say() re-adds it) and <|eos|> would end the dialogue.
        if new and new[-1] in (self.eos_id, self.user_id, self.bot_id):
            new = new[:-1]
        self.history += new
        # skip_special_tokens is the default and is what we want here: the
        # speaker tags should never reach the user.
        return self.tok.decode(new).strip()

    def _trim(self, ids: list[int], budget: int) -> list[int]:
        """Drop oldest turns until the history fits."""
        starts = [i for i, t in enumerate(ids) if t in (self.user_id, self.bot_id)]
        for start in starts:
            if len(ids) - start <= budget:
                return ids[start:]
        return ids[-budget:]


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("--say", help="send one message and exit")
    ap.add_argument("--temperature", type=float, default=0.8)
    ap.add_argument("--top-k", type=int, default=40)
    args = ap.parse_args()

    kat = KatChat(temperature=args.temperature, top_k=args.top_k)
    if args.say:
        print(kat.say(args.say))
        return

    print(f"kat (step {kat.step}, val loss {kat.val_loss:.3f}) -- "
          f"/reset to clear, /quit to exit")
    while True:
        try:
            text = input("you> ").strip()
        except (EOFError, KeyboardInterrupt):
            print()
            break
        if not text:
            continue
        if text == "/quit":
            break
        if text == "/reset":
            kat.reset()
            print("[context cleared]")
            continue
        print("kat>", kat.say(text))


if __name__ == "__main__":
    sys.exit(main())