"""Chat with MangoShake-50M. pip install torch safetensors python chat.py # interactive ('reset' clears, 'quit' exits) python chat.py --prompt "hello" # one reply """ import argparse import os import torch from model import load, sample from tokenizer import BPETokenizer HERE = os.path.dirname(os.path.abspath(__file__)) MAX_NEW = 300 def build_prompt(tok, history): """history: list of (user, reply) pairs; the last reply is None.""" ids = [tok.eot_id] for user, reply in history: ids += tok.encode(f"<|user|>\n{user}\n<|assistant|>\n") if reply is not None: ids += tok.encode(reply) + [tok.eot_id] return ids def respond(model, tok, history, temperature=0.6): ids = build_prompt(tok, history) while len(ids) + MAX_NEW > model.cfg.ctx and len(history) > 1: # drop the oldest turns history = history[1:] ids = build_prompt(tok, history) ids = ids[-(model.cfg.ctx - MAX_NEW):] return tok.decode(sample(model, ids, MAX_NEW, tok.eot_id, temperature, top_k=30)).strip() if __name__ == "__main__": p = argparse.ArgumentParser() p.add_argument("--prompt") p.add_argument("--temp", type=float, default=0.6) p.add_argument("--device", default="cpu") a = p.parse_args() torch.set_num_threads(max(1, os.cpu_count() // 2)) model = load(HERE, a.device) tok = BPETokenizer.load(os.path.join(HERE, "tokenizer.json")) if a.prompt: print(respond(model, tok, [(a.prompt, None)], a.temp)) raise SystemExit print("MangoShake-50M. It's a small model and makes mistakes.\n") history = [] while True: try: msg = input("You: ").strip() except (EOFError, KeyboardInterrupt): print() break if msg in ("quit", "exit"): break if msg == "reset": history = [] continue if msg: reply = respond(model, tok, history + [(msg, None)], a.temp) history.append((msg, reply)) print(f"MangoShake: {reply}\n")