Text Generation
PyTorch
English
recurrent-depth
fineweb-edu
constoloop / chat.py
aldigobbler's picture
Use Constoloop name in the chat runner
f8ab417 verified
Raw History Blame Contribute Delete
7 kB
# /// script
# requires-python = ">=3.11,<3.14"
# dependencies = ["huggingface_hub", "numpy", "tokenizers", "torch"]
# ///
"""Chat with a fine-tuned model, or continue text with a base model.
uv run chat.py ../models/chunklm/chat.pt ["one-off message"]
uv run chat.py ../models/chunklm/base.pt --raw ["text to continue"]
"""
import argparse
import math
from concurrent.futures import ThreadPoolExecutor
from difflib import SequenceMatcher
import re
import sys
from threading import Event
import time
import torch
from chat_format import BOS, END_DOC, IM_END, encode_chat, load_tokenizer
from model import Config, LoopLM
from model2 import ChunkLM, Config2
ap = argparse.ArgumentParser()
ap.add_argument("checkpoint")
ap.add_argument("message", nargs="?")
ap.add_argument("--raw", action="store_true", help="continue the text instead of chatting (base models)")
loop_options = ap.add_mutually_exclusive_group()
loop_options.add_argument("--compare-loops", action="store_true", help="compare R=1, R=2 and R=3 (LoopLM)")
loop_options.add_argument("--loops", type=int,
help="passes through the core; default is what the model was trained for")
ap.add_argument("--device", choices=["cpu", "mps", "cuda"], help="default: fastest measured for the model")
ap.add_argument("--rep", type=float, default=1.1, help="repetition penalty; 1 = off")
ap.add_argument("--max-new", type=int, default=300, help="soft limit; the current sentence is finished")
ap.add_argument("--sampler", choices=["sample", "greedy"], default="sample",
help="sample by token probability or always pick the highest-scoring token")
ap.add_argument("--temperature", type=float, default=0.7, help="sampling temperature; 0 is greedy")
ap.add_argument("--top-k", type=int, default=0, help="sample from at most K candidates; 0 disables")
ap.add_argument("--top-p", type=float, default=0.9, help="nucleus probability threshold; 1 disables")
args = ap.parse_intermixed_args()
if not math.isfinite(args.temperature) or args.temperature < 0:
ap.error("--temperature must be finite and nonnegative")
if args.top_k < 0:
ap.error("--top-k must be nonnegative")
if not 0 < args.top_p <= 1:
ap.error("--top-p must be greater than 0 and at most 1")
temperature = 0 if args.sampler == "greedy" else args.temperature
ck = torch.load(args.checkpoint, map_location="cpu", weights_only=True)
chunked = "experts" in ck["config"]
if args.compare_loops and chunked:
ap.error("--compare-loops requires a LoopLM checkpoint")
gpu = "mps" if torch.backends.mps.is_available() else "cuda" if torch.cuda.is_available() else "cpu"
device = args.device or ("cpu" if chunked else gpu)
loops = args.loops or (1 if chunked else 2)
model = ChunkLM(Config2(**ck["config"])) if chunked else LoopLM(Config(**ck["config"]))
model.load_state_dict(ck["model"])
model.eval().to(device)
loop_label = "R=1 / R=2 / R=3" if args.compare_loops else f"{loops} loop(s)"
model_name = "ChunkLM" if chunked else "Constoloop"
print(f"{model_name} step {ck['step']:,} on {device}, {loop_label}", file=sys.stderr)
tok = load_tokenizer()
def complete(ids, loops, *, stream=False, generator=None, cancelled=None):
start = time.perf_counter()
out, shown, why = [], "", "end token"
try:
# Past --max-new, finish the sentence instead of cutting off mid-word.
for t in model.generate(ids, args.max_new + 60, {IM_END, END_DOC},
loops, temperature, top_p=args.top_p, rep=args.rep,
top_k=args.top_k, generator=generator):
if cancelled is not None and cancelled.is_set():
why = "Ctrl-C"
break
out.append(t)
full = tok.decode(out)
if stream and not full.endswith("\ufffd"): # wait for complete characters
sys.stdout.write(full[len(shown):])
sys.stdout.flush()
shown = full
if len(out) >= args.max_new and full.rstrip(" \"')”’").endswith((".", "!", "?", "\n")):
why = "length limit, at sentence end"
break
else:
if len(out) >= args.max_new + 60:
why = "length limit"
except KeyboardInterrupt:
if not stream:
raise
why = "Ctrl-C"
rate = len(out) / (time.perf_counter() - start)
return tok.decode(out), f"[{len(out)} tokens, {rate:.0f} tok/s; stopped: {why}]"
def run_prompt(text, history, loops, *, seed=None, cancelled=None):
if args.raw:
ids = [BOS] + tok.encode(text, add_special_tokens=False).ids
if seed is None:
print(text, end="", flush=True)
else:
history.append({"role": "user", "content": text})
ids, _ = encode_chat(tok, history, add_reply=True)
generator = torch.Generator().manual_seed(seed) if seed is not None else None
reply, stats = complete(ids, loops, stream=seed is None, generator=generator,
cancelled=cancelled)
if not args.raw:
history.append({"role": "assistant", "content": reply})
return reply, stats
def highlight(baseline, reply, color):
if not sys.stdout.isatty():
return reply
# Align words and punctuation so a small insertion doesn't color the entire suffix.
words = r"\s*(?:\w+|[^\w\s])|\s+"
reference, actual = re.findall(words, baseline), re.findall(words, reply)
diff = SequenceMatcher(None, reference, actual, autojunk=False)
return "".join(
("\033[37m" if tag == "equal" else color) + "".join(actual[lo:hi])
for tag, _, _, lo, hi in diff.get_opcodes() if lo != hi
) + "\033[0m"
loop_counts = (1, 2, 3)
histories = {r: [] for r in loop_counts} if args.compare_loops else {loops: []}
while True:
if args.message is None:
try:
text = input("\n> ").strip()
except (EOFError, KeyboardInterrupt):
break
if not text:
continue
else:
text = args.message
if args.compare_loops:
seed = torch.seed()
cancelled = Event()
with ThreadPoolExecutor(max_workers=3) as pool:
jobs = [
pool.submit(run_prompt, text, histories[r], r, seed=seed, cancelled=cancelled)
for r in loop_counts
]
try:
results = [job.result() for job in jobs]
except KeyboardInterrupt:
cancelled.set()
break
baseline = results[1][0]
print("R=2 reference · yellow R=1 changes · red R=3 changes")
for r, (reply, stats), color in zip(loop_counts, results, ("\033[33m", "\033[37m", "\033[31m")):
print(f"\nR={r} {stats}")
print((text if args.raw else "") + highlight(baseline, reply, color))
else:
_, stats = run_prompt(text, histories[loops], loops)
print()
print(stats, file=sys.stderr)
if args.message is not None:
break