N-Q-26M-Chat / circuits.py
LakoMoor's picture
N-Q-26M-Chat: initial private release
61cba30 verified
Raw History Blame Contribute Delete
7.93 kB
"""Exact circuits (the "Q" tool mechanism, ported from Q-164M): the model *writes* a tool span, a fixed program
fills in the answer inside the same token stream.
<CALC> expr <EQ> result <ECALC>
expr kinds: arithmetic "347*86" | "date:2026-12-20+45" | "wd:2027-03-05" | "dur:2026-01-01,2026-03-15" |
"conv:10 km>mi" | "cmp:5.3,5.29" | "sort:5,2,9" | "filter:>5:1,6,3,8,2" | "count:banana" |
"mean/max/min/sum:1,2,3" | "gcd:12,18" | "lcm:4,6" | "prime:97" | "rev:hello" | "fact:5" | "sqrt:2" |
"pchg:100,120" | "words:a short sentence"
Difference from Q-164M: spans are tokenized by the ordinary tokenizer (digits are already one token each in
N-Q), and the executor decodes / re-encodes text with the tokenizer, so non-ASCII (Cyrillic) spans work."""
import ast, datetime as dt, math, operator as op
TEXT_VOCAB = 8192
USER, MODEL, EOT, THINK, ETHINK, CALC, EQ, ECALC, NEED, QUOTE, SYSTEM = range(TEXT_VOCAB, TEXT_VOCAB + 11)
PAD, BOS, EOS = 0, 1, 2
_OPS = {ast.Add: op.add, ast.Sub: op.sub, ast.Mult: op.mul, ast.Div: op.truediv, ast.Mod: op.mod, ast.Pow: op.pow,
ast.USub: op.neg, ast.FloorDiv: op.floordiv}
_UNITS = {("km", "mi"): 0.621371, ("mi", "km"): 1.609344, ("kg", "lb"): 2.204623, ("lb", "kg"): 0.453592, ("m", "ft"): 3.28084,
("ft", "m"): 0.3048, ("l", "gal"): 0.264172, ("gal", "l"): 3.78541, ("cm", "in"): 0.393701, ("in", "cm"): 2.54}
_CMP_OPS = {">": op.gt, "<": op.lt, ">=": op.ge, "<=": op.le, "==": op.eq}
_WD_RU = ["понедельник", "вторник", "среда", "четверг", "пятница", "суббота", "воскресенье"]
def _ev(n):
if isinstance(n, ast.Constant) and isinstance(n.value, (int, float)):
return n.value
if isinstance(n, ast.BinOp) and type(n.op) in _OPS:
a, b = _ev(n.left), _ev(n.right)
if isinstance(n.op, ast.Pow) and abs(b) > 12:
raise ValueError("pow too large")
return _OPS[type(n.op)](a, b)
if isinstance(n, ast.UnaryOp) and type(n.op) in _OPS:
return _OPS[type(n.op)](_ev(n.operand))
raise ValueError("disallowed expression")
def fmt_num(x):
if isinstance(x, float):
x = round(x, 6)
return str(int(x)) if isinstance(x, (int, float)) and float(x).is_integer() else str(x)
def evaluate(expr):
"""Return the result string for a span expression, or None if it cannot be computed."""
expr = expr.strip()
try:
if expr.startswith("date:"):
base, n = expr[5:].split("+")
return (dt.date.fromisoformat(base) + dt.timedelta(days=int(n))).isoformat()
if expr.startswith("wd:"):
return dt.date.fromisoformat(expr[3:]).strftime("%A")
if expr.startswith("wdru:"):
return _WD_RU[dt.date.fromisoformat(expr[5:]).weekday()]
if expr.startswith("dur:"):
a, b = expr[4:].split(",")
return str(abs((dt.date.fromisoformat(b) - dt.date.fromisoformat(a)).days))
if expr.startswith("conv:"):
v, rest = expr[5:].split(" ", 1)
a, b = rest.split(">")
if (a, b) in _UNITS:
return fmt_num(round(float(v) * _UNITS[(a, b)], 2))
if (a, b) == ("c", "f"):
return fmt_num(round(float(v) * 9 / 5 + 32, 2))
if (a, b) == ("f", "c"):
return fmt_num(round((float(v) - 32) * 5 / 9, 2))
return None
if expr.startswith("cmp:"):
a, b = expr[4:].split(",")
return "first" if float(a) > float(b) else "second" if float(a) < float(b) else "equal"
if expr.startswith("sort:"):
return ",".join(sorted(expr[5:].split(","), key=float))
if expr.startswith("filter:"):
cond, rest = expr[7:].split(":", 1)
for sym, fn in sorted(_CMP_OPS.items(), key=lambda kv: -len(kv[0])):
if cond.startswith(sym):
thr = float(cond[len(sym):])
xs = [x for x in rest.split(",") if fn(float(x), thr)]
return ",".join(xs) if xs else "none"
return None
if expr.startswith("count:"):
return str(len(expr[6:]))
for k, fn in (("mean:", lambda v: sum(v) / len(v)), ("max:", max), ("min:", min), ("sum:", sum)):
if expr.startswith(k):
return fmt_num(round(fn([float(x) for x in expr[len(k):].split(",")]), 4))
if expr.startswith("gcd:"):
a, b = expr[4:].split(","); return str(math.gcd(int(a), int(b)))
if expr.startswith("lcm:"):
a, b = expr[4:].split(","); return str(math.lcm(int(a), int(b)))
if expr.startswith("prime:"):
n = int(expr[6:]); return "yes" if n > 1 and all(n % d for d in range(2, int(n ** .5) + 1)) else "no"
if expr.startswith("rev:"):
return expr[4:][::-1]
if expr.startswith("fact:"):
n = int(expr[5:]); return str(math.factorial(n)) if 0 <= n <= 20 else None
if expr.startswith("sqrt:"):
return fmt_num(round(float(expr[5:]) ** 0.5, 3))
if expr.startswith("pchg:"):
a, b = expr[5:].split(","); return fmt_num(round((float(b) - float(a)) / float(a) * 100, 2))
if expr.startswith("words:"):
return str(len(expr[6:].split()))
r = _ev(ast.parse(expr.replace("×", "*").replace("÷", "/").replace(",", "."), mode="eval").body)
return fmt_num(round(r, 6) if isinstance(r, float) else r)
except Exception:
return None
def span(expr, result=None):
"""Text markup of a span; tokenized normally (control tokens are added special tokens)."""
return f"<CALC>{expr}<EQ>" + ("" if result is None else f"{result}<ECALC>")
def fill_spans(text):
"""Replace every '<CALC>expr<EQ>...<ECALC>' (or open '<CALC>expr<EQ>') with the executor's exact result."""
out, i = [], 0
while True:
s = text.find("<CALC>", i)
if s < 0:
out.append(text[i:]); return "".join(out)
e = text.find("<EQ>", s)
if e < 0:
out.append(text[i:]); return "".join(out)
expr = text[s + 6:e]
end = text.find("<ECALC>", e)
out.append(text[i:s]); out.append(span(expr, evaluate(expr) or "?"))
i = end + 7 if end >= 0 else len(text)
class CircuitExecutor:
"""Batched decode-time hook. Call `step(ids)` with every sequence's tokens so far (list of lists); it returns,
per row, the token id that MUST be emitted next (forced result / <ECALC>) or None (sample freely)."""
def __init__(self, tok, batch=1):
self.tok = tok
self.queue = [[] for _ in range(batch)]
self.calls = [0] * batch # number of executed spans per row
self.failed = [0] * batch # spans the executor could not compute
def step(self, ids_batch):
forced = []
for b, ids in enumerate(ids_batch):
if not self.queue[b] and ids and ids[-1] == EQ:
s = max((i for i, t in enumerate(ids) if t == CALC), default=-1)
res = evaluate(self.tok.decode(ids[s + 1:-1], skip_special_tokens=True)) if s >= 0 else None
self.calls[b] += 1
if res is None:
self.failed[b] += 1; res = "?"
self.queue[b] = self.tok.encode(res, add_special_tokens=False) + [ECALC]
forced.append(self.queue[b].pop(0) if self.queue[b] else None)
return forced
class CircuitLogitsProcessor:
"""HF `generate()` logits processor: when the model emits <EQ> after a <CALC> span, force the exact result + <ECALC>."""
def __init__(self, tok, batch=1):
self.ex = CircuitExecutor(tok, batch)
def __call__(self, input_ids, scores):
import torch
for b, t in enumerate(self.ex.step(input_ids.tolist())):
if t is not None:
scores[b] = float("-inf"); scores[b, t] = 0.0
return scores