Download chat.py from Kat-AI/Kat: direct link, hf CLI and curl.
- Browser
- Download file 3.87 kB
-
https://huggingface.co/Kat-AI/Kat/resolve/main/chat.py
- Command line
-
hf download hf://Kat-AI/Kat/chat.py
-
curl -L -o chat.py https://huggingface.co/Kat-AI/Kat/resolve/main/chat.py
3.87 kB
| """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()) | |