Download chat_cli.py from tennant/rule-lm: direct link, hf CLI and curl.
- Browser
- Download file 7.73 kB
-
https://huggingface.co/tennant/rule-lm/resolve/main/chat_cli.py
- Command line
-
hf download hf://tennant/rule-lm/chat_cli.py
-
curl -L -o chat_cli.py https://huggingface.co/tennant/rule-lm/resolve/main/chat_cli.py
7.73 kB
| #!/usr/bin/env python3 | |
| """Chat with (or continue text from) a rule-based language model in the terminal. | |
| A "model" is a directory of learned tables (n-gram counts, suffix array, word classes, retrieval index, knowledge base), | |
| written by train.py (pre-training) or sft.py (chat fine-tune on top of a pre-trained model). Load any of them: | |
| python chat_cli.py --model models/p3_1b_alpaca # an SFT'd model: chat | |
| python chat_cli.py --model models/p3_1b --complete # a pre-trained model: prompt continuation | |
| python chat_cli.py --model models/p3_1b_alpaca --show-plan # also show what the chat engine planned | |
| python chat_cli.py --model models/p3_1b_alpaca --threads 1 # single core (default 2: same outputs, ~1.5x faster) | |
| In-chat commands: /reset (new conversation) /complete /chat (switch mode) /temp 0.5 /max 200 /quit | |
| Decoding is the one every evaluation uses: temperature 0.8 over the 40 most likely tokens, stop at a new "User:" line. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import os | |
| import re | |
| import sys | |
| import time | |
| from pathlib import Path | |
| import numpy as np | |
| ROOT = Path(__file__).resolve().parent | |
| sys.path.insert(0, str(ROOT)) | |
| STOP = re.compile(r"\n\s*(User|Assistant)\s*:|\nUSER:|\nASSISTANT:") | |
| def pick(ids, probs, rng, temp, top_k): | |
| ids, probs = np.asarray(ids), np.asarray(probs, dtype=np.float64) | |
| if probs.size == 0: | |
| return None | |
| k = min(top_k, probs.size) | |
| top = np.argpartition(-probs, k - 1)[:k] | |
| if temp <= 0: | |
| return int(ids[top[np.argmax(probs[top])]]) | |
| w = np.maximum(probs[top], 1e-300) ** (1.0 / temp) | |
| return int(ids[top[rng.choice(k, p=w / w.sum())]]) | |
| def generate(model, vocab, ids, max_new, temp, top_k, rng, stop_at_turn, stream=True): | |
| ctx, new, printed = list(ids), [], "" | |
| for _ in range(max_new): | |
| out = model.next_dist(ctx) | |
| if isinstance(out[0], dict): | |
| tok = pick(list(out[0].keys()), list(out[0].values()), rng, temp, top_k) | |
| else: | |
| tok = pick(out[0], out[1], rng, temp, top_k) | |
| if tok is None or tok == vocab.bos: | |
| break | |
| ctx.append(tok) | |
| new.append(tok) | |
| text = vocab.decode(new) | |
| m = STOP.search(text) if stop_at_turn else None | |
| if m: | |
| text = text[: m.start()] | |
| safe = text | |
| if stop_at_turn and not m: # hold back a line that may be the start of "User:" / "Assistant:" | |
| j = text.rfind("\n") | |
| tail = text[j + 1:].strip() if j >= 0 else None | |
| if tail is not None and any(w.startswith(tail) for w in ("User:", "Assistant:", "USER:", "ASSISTANT:")): | |
| safe = text[:j] | |
| if stream and safe.startswith(printed) and len(safe) > len(printed): | |
| sys.stdout.write(safe[len(printed):]) | |
| sys.stdout.flush() | |
| printed = safe | |
| if m: | |
| break | |
| if stream: | |
| print() | |
| text = vocab.decode(new) | |
| m = STOP.search(text) if stop_at_turn else None | |
| return (text[: m.start()] if m else text).strip() | |
| def main(): | |
| ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) | |
| ap.add_argument("--model", required=True, help="model directory (pre-trained or SFT)") | |
| ap.add_argument("--code", default=str(ROOT / "rlm"), help="model code directory (default: ./rlm)") | |
| ap.add_argument("--complete", action="store_true", help="prompt-continuation mode instead of chat") | |
| ap.add_argument("--temp", type=float, default=0.8) | |
| ap.add_argument("--top-k", type=int, default=40) | |
| ap.add_argument("--max", type=int, default=160, help="max new tokens per reply") | |
| ap.add_argument("--seed", type=int, default=0) | |
| ap.add_argument("--show-plan", action="store_true", help="print the chat engine's parsed request and planned reply") | |
| ap.add_argument("--prompt", default=None, help="one prompt, print the output and exit") | |
| ap.add_argument("--threads", type=int, default=min(2, os.cpu_count() or 1), | |
| help="cores for one generation (default 2): the knowledge-base search runs in parallel with document " | |
| "retrieval at each access step; outputs are identical to --threads 1 (~1.5x faster on the large models)") | |
| ap.add_argument("--prefetch", action="store_true", | |
| help="read every model file once at load (faster replies afterwards on a fast local disk; on a slow or " | |
| "shared disk this can take a long time for the large models)") | |
| a = ap.parse_args() | |
| if not a.prefetch: | |
| os.environ["RLM_NO_PREFETCH"] = "1" | |
| from rlm_harness.chat import render | |
| from rlm_harness.data import Vocab | |
| from rlm_harness.loader import load_model | |
| t0 = time.time() | |
| print(f"loading {a.model} ... (tables are memory-mapped: the first replies read them from disk and are slower)", | |
| file=sys.stderr) | |
| model = load_model(a.model, Path(a.code)) | |
| from rlm_harness.fast import accelerate | |
| model = accelerate(model, threads=a.threads) | |
| vocab = Vocab() | |
| is_sft = getattr(model, "chat", None) is not None | |
| print(f"loaded in {time.time() - t0:.1f}s - {'SFT (chat engine on)' if is_sft else 'pre-trained (no chat engine)'}" | |
| + ("" if is_sft or a.complete else " - tip: pre-trained models are better with --complete"), file=sys.stderr) | |
| rng = np.random.default_rng(a.seed) | |
| mode, msgs = ("complete" if a.complete else "chat"), [] | |
| def respond(line): | |
| nonlocal msgs | |
| if hasattr(model, "_doc_reset"): | |
| model._doc_reset() | |
| if mode == "complete": | |
| ids = vocab.encode(line, prepend_bos=True) | |
| if not a.prompt: | |
| sys.stdout.write(line) | |
| return generate(model, vocab, ids, a.max, a.temp, a.top_k, rng, stop_at_turn=False) | |
| msgs.append({"role": "user", "content": line}) | |
| if a.show_plan and is_sft: | |
| try: | |
| from chat.understand import parse | |
| r = parse(msgs, model.chat.stop) | |
| print(f" [parsed] intent={r.intent} topic={r.topic!r} keywords={r.keywords[:6]}", file=sys.stderr) | |
| mod_, plan, conf, _ = model.chat.reply(msgs) | |
| print(f" [plan] module={mod_} confidence={conf}: {plan[:300]!r}", file=sys.stderr) | |
| except Exception as e: # noqa: BLE001 | |
| print(f" [plan unavailable: {e}]", file=sys.stderr) | |
| ids = vocab.encode(render(msgs) + "\nAssistant:", prepend_bos=True)[-900:] | |
| sys.stdout.write("assistant> ") | |
| reply = generate(model, vocab, ids, a.max, a.temp, a.top_k, rng, stop_at_turn=True) | |
| msgs.append({"role": "assistant", "content": reply}) | |
| return reply | |
| if a.prompt: | |
| respond(a.prompt) | |
| return | |
| print("commands: /reset /complete /chat /temp X /max N /quit", file=sys.stderr) | |
| while True: | |
| try: | |
| line = input("you> " if mode == "chat" else "prompt> ").strip() | |
| except (EOFError, KeyboardInterrupt): | |
| print() | |
| return | |
| if not line: | |
| continue | |
| if line.startswith("/"): | |
| cmd, *arg = line.split() | |
| if cmd == "/quit": | |
| return | |
| if cmd == "/reset": | |
| msgs = [] | |
| elif cmd in ("/complete", "/chat"): | |
| mode, msgs = cmd[1:], [] | |
| elif cmd == "/temp" and arg: | |
| a.temp = float(arg[0]) | |
| elif cmd == "/max" and arg: | |
| a.max = int(arg[0]) | |
| print(f" [mode={mode} temp={a.temp} max={a.max} turns={len(msgs) // 2}]", file=sys.stderr) | |
| continue | |
| respond(line) | |
| if __name__ == "__main__": | |
| main() | |