luoke-bench / mail /run_decide.py
jason926's picture
luoke-bench (4745f55dec)
e39a6b5
Raw History Blame Contribute Delete
25.1 kB
#!/usr/bin/env python3
"""Email triage by reading answer probabilities, against generating the whole JSON.
The three answers that decide what the page does with a mail -- action, priority, suspicious -- asked four ways, on
the same prompt: luoke-mail's SYSTEM_PROMPT and build_messages, cut and told as the 16 GB recipe says (the body cut
to 6000 characters of prompt, the mailbox's sender verdict not told; RECIPE below).
G triage.analyze: the whole JSON under json_schema strict, asked again once if unusable (what the app does)
G3 the same prompt, a schema of only the three fields
D oMLX's POST /v1/decisions: the prompt as one user message, the three questions in one request
A AnyDecisionModel (mail/decide-adm, Swift, MLX backend): the prompt as the state, the three in one decide()
python3 mail/run_decide.py --arm D --omlx <oMLX.app> --models <dir> --model Qwen3.5-9B-4bit --set rewrite --label d9
python3 mail/run_decide.py --arm A --adm <decide-adm> --models <dir> --model gemma-4-e4b-it-4bit --set samples --label a4
The engine is started here (oMLX as luoke-core starts it: its own HOME, an API key in settings.json, --no-cache;
decide-adm loading the same model directory) and its footprint sampled every 0.5 s. --cache hot gives oMLX a
memory-only prefix cache instead; --prefix-caching and --rotation turn on decide-adm's options of those names, and
--mlx-cache-mb caps the buffers MLX keeps for reuse (left alone, it may keep up to MLX's memory limit);
--reverse lists every choice's options last to first. The first mail is asked once untimed (loading). Every answer's
probabilities are kept: the suspicious threshold is chosen afterwards (mail/decide_report.py); what is printed here
uses 0.5. A choice whose letters hold under half the next-token mass is a refusal in oMLX (no answer, counted
wrong); decide-adm answers anyway and reports the mass, kept beside the answer.
Results -> mail/results/decide/<set>/<label>.json. Stdlib only.
"""
from __future__ import annotations
import argparse
import http.client
import json
import os
import platform
import re
import secrets
import shutil
import socket
import statistics as st
import subprocess
import sys
import tempfile
import threading
import time
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
import run_triage # noqa: E402 -- puts luoke-mail and sets/ on the path
import runmeta # noqa: E402
from luoke_mail import engines, samples, triage # noqa: E402
import triage_real # noqa: E402
# luoke-core recipes/dev.json, luoke-mail.triage on the 16 GB tier (the 32 GB tier differs only in max_chars, 12000)
RECIPE = {"tier": "16", "max_chars": 6000, "sender_verdict": False, "batch": 1}
FIELDS = ("action", "priority", "suspicious")
ACTION_KEYS = list(triage.ACTIONS)
PRIORITY_KEYS = list(triage.PRIORITIES)
ACTION_Q = "这封邮件建议怎么处理(字段含义里的 action)?"
PRIORITY_Q = "这封邮件的优先级(字段含义里的 priority)?"
SUSPICIOUS_STATEMENT = "按上面的安全规则,这封邮件是可疑邮件(suspicious 为 true)。" # oMLX: a predicate is a statement
SUSPICIOUS_QUESTION = "按上面的安全规则,这封邮件是可疑邮件(suspicious 为 true)吗?" # AnyDecisionModel: yes / no
SCHEMA3 = {"type": "object", "additionalProperties": False, "required": list(FIELDS),
"properties": {k: triage.SCHEMA["properties"][k] for k in FIELDS}}
def meanings(field: str, keys: list[str]) -> list[dict]:
"""What SYSTEM_PROMPT says each value of a field means (its line `- field:key meaning / key meaning …`), in
the prompt's order -- so the options read as the generating model reads them."""
head = f"- {field}:"
line = next(x for x in triage.SYSTEM_PROMPT.splitlines() if x.startswith(head))[len(head):]
marks = list(re.finditer(r"(?:^|/\s*)(" + "|".join(map(re.escape, keys)) + r")\s", line))
said = {m.group(1): line[m.end():marks[i + 1].start() if i + 1 < len(marks) else len(line)].strip()
for i, m in enumerate(marks)}
if list(said) != keys:
raise SystemExit(f"SYSTEM_PROMPT's {field} line no longer lists {keys}: {list(said)}")
return [{"name": k, "description": said[k]} for k in keys]
ACTION_OPTIONS = meanings("action", ACTION_KEYS)
PRIORITY_OPTIONS = meanings("priority", PRIORITY_KEYS)
class RecipeLink(engines.Link):
"""luoke-mail's direct link, limited as the recipe's tier says."""
def __init__(self, base_url: str, model: str, api_key: str):
self.base_url, self.model, self.api_key, self.name = base_url, model, api_key, model
def limits(self, task: str) -> dict:
return {k: RECIPE[k] for k in ("max_chars", "batch", "sender_verdict")}
def chat(self, task, messages, schema, *, items=1, max_tokens=700, timeout=300):
return engines.chat_json(self.base_url, self.model, messages, schema, self.api_key, max_tokens=max_tokens,
timeout=timeout)
def prompt(it: dict, link: engines.Link) -> tuple[list[dict], bool]:
"""The messages triage.analyze sends for this mail, and whether the body was cut to fit."""
mail = it["mail"]
if link.limits("triage").get("sender_verdict") is False and mail.get("auth") == "pass":
mail = {**mail, "auth": None}
full = len(mail.get("body") or "")
def build(n: int) -> list[dict]:
return triage.build_messages(triage._shortened(mail, n), it.get("about", ""), "中文", samples.TODAY, samples.ME)
n = link.fit("triage", build, full)
return build(n), n < full
def one_text(messages: list[dict]) -> str:
"""System and user as one piece: oMLX's decisions take a user message only."""
return "\n\n".join(m["content"] for m in messages)
def footprint_gb(pid: int) -> float:
o = subprocess.run(["/usr/bin/footprint", "-p", str(pid)], capture_output=True, text=True).stdout
m = re.search(r"Footprint:\s*([\d.]+)\s*([KMG])B", o)
return round(float(m.group(1)) / {"K": 1048576, "M": 1024, "G": 1}[m.group(2)], 3) if m else -1.0
class Peak(threading.Thread):
"""The largest footprint of a process, sampled every 0.5 s."""
def __init__(self, pid: int):
super().__init__(daemon=True)
self.pid, self.peak, self.n, self.halt = pid, 0.0, 0, threading.Event()
def run(self) -> None:
while not self.halt.is_set():
self.peak, self.n = max(self.peak, footprint_gb(self.pid)), self.n + 1
self.halt.wait(0.5)
def stop(self) -> float:
self.halt.set()
self.join(5)
return self.peak
def free_port() -> int:
s = socket.socket()
s.bind(("127.0.0.1", 0))
p = s.getsockname()[1]
s.close()
return p
class Omlx:
"""oMLX serving one model, started as luoke-core starts it (luoke_core/engine.py)."""
def __init__(self, app: str, models: str, model: str, cache: str, work: str):
base, mdir, home = (os.path.join(work, x) for x in ("engine", "models", "home"))
for d in (base, mdir, home):
os.makedirs(d)
os.symlink(os.path.join(models, model), os.path.join(mdir, model))
self.key = secrets.token_hex(16)
settings: dict = {"auth": {"api_key": self.key}}
cache_args = ["--no-cache"]
if cache == "hot":
settings["cache"] = {"enabled": True, "hot_cache_only": True}
cache_args = ["--hot-cache-max-size", "4GB"]
fd = os.open(os.path.join(base, "settings.json"), os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
with os.fdopen(fd, "w") as f:
json.dump(settings, f)
self.port = free_port()
self.base_url = f"http://127.0.0.1:{self.port}/v1"
env = {k: v for k, v in os.environ.items() if not (k.startswith("HF_") or k.startswith("OMLX_"))}
env.update(PATH="/usr/bin:/bin:/usr/sbin:/sbin", HF_HUB_OFFLINE="1", HOME=home)
cmd = [os.path.join(app, "Contents/MacOS/omlx-cli"), "serve", "--base-path", base, "--model-dir", mdir,
"--host", "127.0.0.1", "--port", str(self.port), *cache_args, "--no-hf-cache", "--log-level", "info"]
self.log = os.path.join(work, "engine.log")
self.proc = subprocess.Popen(cmd, env=env, stdout=open(self.log, "a"), stderr=subprocess.STDOUT, cwd="/")
self.pid = self.proc.pid
t0 = time.time()
while time.time() - t0 < 180:
if self.proc.poll() is not None:
raise SystemExit(f"oMLX exited ({self.proc.returncode}), see {self.log}")
try:
ids = [m["id"] for m in self.get("/v1/models")["data"]]
if model in ids:
self.mid = model
break
except (OSError, ValueError, KeyError):
pass
time.sleep(0.5)
else:
raise SystemExit(f"oMLX did not come up in 3 minutes, see {self.log}")
def headers(self) -> dict:
return {"Authorization": "Bearer " + self.key, "Content-Type": "application/json"}
def get(self, path: str) -> dict:
c = http.client.HTTPConnection("127.0.0.1", self.port, timeout=10)
c.request("GET", path, headers=self.headers())
return json.loads(c.getresponse().read())
def post(self, path: str, body: dict, timeout: float = 600) -> tuple[int, dict]:
c = http.client.HTTPConnection("127.0.0.1", self.port, timeout=timeout)
c.request("POST", path, body=json.dumps(body, ensure_ascii=False).encode(), headers=self.headers())
r = c.getresponse()
raw = r.read()
try:
return r.status, json.loads(raw)
except ValueError:
return r.status, {"error": raw[:300].decode("utf-8", "replace")}
def stop(self) -> None:
self.proc.terminate()
try:
self.proc.wait(30)
except subprocess.TimeoutExpired:
self.proc.kill()
class Adm:
"""mail/decide-adm, built, loading one model directory; one request per line."""
def __init__(self, binary: str, models: str, model: str, prefix_caching: bool, rotation: bool, work: str,
cache_mb: int | None = None):
cmd = [binary, "--model-dir", os.path.join(models, model)]
cmd += ["--prefix-caching"] * prefix_caching + ["--rotation"] * rotation
cmd += ["--cache-limit-mb", str(cache_mb)] if cache_mb is not None else []
env = {k: v for k, v in os.environ.items() if not k.startswith("HF_")}
env.update(HF_HUB_OFFLINE="1")
self.log = os.path.join(work, "adm.log")
self.proc = subprocess.Popen(cmd, env=env, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=open(self.log, "a"), text=True, bufsize=1, cwd="/")
self.pid = self.proc.pid
def ask(self, req: dict) -> dict:
self.proc.stdin.write(json.dumps(req, ensure_ascii=False) + "\n")
self.proc.stdin.flush()
line = self.proc.stdout.readline()
if not line:
raise SystemExit(f"decide-adm exited ({self.proc.poll()}), see {self.log}")
return json.loads(line)
def stop(self) -> None:
self.proc.stdin.close()
try:
self.proc.wait(30)
except subprocess.TimeoutExpired:
self.proc.kill()
def ordered(options: list[dict], reverse: bool) -> list[dict]:
return options[::-1] if reverse else options
def ask_omlx(eng: Omlx, text: str, reverse: bool) -> dict:
body = {"model": eng.mid, "input": text, "questions": [
{"type": "choice", "name": "action", "instructions": ACTION_Q,
"choices": [{"value": o["name"], "description": o["description"]} for o in ordered(ACTION_OPTIONS, reverse)]},
{"type": "choice", "name": "priority", "instructions": PRIORITY_Q,
"choices": [{"value": o["name"], "description": o["description"]} for o in ordered(PRIORITY_OPTIONS, reverse)]},
{"type": "predicate", "name": "suspicious", "instructions": SUSPICIOUS_STATEMENT}]}
t0 = time.time()
status, d = eng.post("/v1/decisions", body)
secs = time.time() - t0
if status != 200:
raise RuntimeError(f"HTTP {status} {str(d)[:200]}")
probs: dict = {}
for a in d["answers"]:
if a["type"] == "refusal":
probs[a["name"]] = None
elif a["type"] == "predicate":
probs[a["name"]] = a["probability"]
else:
probs[a["name"]] = {p["value"]: p["probability"] for p in a["probabilities"]}
return {"probs": probs, "seconds": round(secs, 3), "tokens_in": (d.get("usage") or {}).get("input_tokens")}
def ask_adm(eng: Adm, tag: str, text: str, reverse: bool) -> dict:
req = {"id": tag, "state": text, "questions": [
{"type": "choice", "name": "action", "instructions": ACTION_Q, "options": ordered(ACTION_OPTIONS, reverse)},
{"type": "choice", "name": "priority", "instructions": PRIORITY_Q, "options": ordered(PRIORITY_OPTIONS, reverse)},
{"type": "binary", "name": "suspicious", "instructions": SUSPICIOUS_QUESTION}]}
t0 = time.time()
d = eng.ask(req)
secs = time.time() - t0
if d.get("error"):
raise RuntimeError(d["error"][:300])
probs, mass, cached = {}, {}, {}
for a in d["answers"]:
probs[a["name"]] = a["probabilities"]["yes"] if a["name"] == "suspicious" else a["probabilities"]
mass[a["name"]], cached[a["name"]] = round(a["mass"], 4), a["cached"]
return {"probs": probs, "mass": mass, "cached": cached, "seconds": round(d["seconds"], 3),
"seconds_round_trip": round(secs, 3), "tokens_in": d.get("input_tokens"),
"mlx_mb": {k: d.get("mlx_" + k + "_mb") for k in ("active", "cache", "peak")}}
def ask_g3(link: RecipeLink, messages: list[dict]) -> dict:
tokens_in = tokens_out = 0
secs = 0.0
for attempt in range(2):
content, usage, s = link.chat("triage", messages, SCHEMA3, max_tokens=60)
tokens_in += usage.get("prompt_tokens") or 0
tokens_out += usage.get("completion_tokens") or 0
secs += s
try:
obj = triage._loads(content)
if obj.get("action") in ACTION_KEYS and obj.get("priority") in PRIORITY_KEYS and isinstance(obj.get("suspicious"), bool):
return {"answer": {k: obj[k] for k in FIELDS}, "seconds": round(secs, 3), "tokens_in": tokens_in,
"tokens_out": tokens_out, "retried": attempt > 0}
except (ValueError, AttributeError):
pass
messages = link.again("triage", messages, content, "上面的输出不符合要求。请只输出一个符合字段说明的 JSON 对象,不要任何其他文字。")
raise RuntimeError("unusable output twice")
def best(p: dict | None) -> str | None:
return max(p, key=p.get) if p else None
def decision(r: dict, it: dict, threshold: float) -> dict | None:
"""What the page would show, as G gives it: suspicious mail turns to ignore (triage.parse_output), a cc'd mail is
not high (triage.settle_cc). A refusal stays None and counts wrong. None when the mail failed."""
if "triage" in r: # G: analyze did all of it
t = r["triage"]
return {"action": t["action"], "action_raw": None, "priority": t["priority"], "suspicious": t["suspicious"]}
if "answer" in r: # G3
a = r["answer"]
sus, act, pri = a["suspicious"], a["action"], a["priority"]
elif "probs" in r:
p = r["probs"]
sus = None if p.get("suspicious") is None else p["suspicious"] >= threshold
act, pri = best(p.get("action")), best(p.get("priority"))
else:
return None
if pri == "high" and triage.cc_only(it["mail"], samples.ME):
pri = "medium"
return {"action": "ignore" if sus else act, "action_raw": act, "priority": pri, "suspicious": sus}
def tally(items: list[dict], results: list[dict], threshold: float = 0.5) -> dict:
"""The three answers over the scored mails (not `watch`), the same way for every arm."""
pairs = [(it, r, decision(r, it, threshold)) for it, r in zip(items, results) if not it.get("watch")]
ok = lambda xs: sum(1 for x in xs if x) # noqa: E731
sus = [(it, d) for it, _, d in pairs if it["expect"]["suspicious"]]
normal = [(it, d) for it, _, d in pairs if not it["expect"]["suspicious"]]
pri = [(it, d) for it, d in normal if it["expect"]["priority"]]
secs = [r["seconds"] for _, r, d in pairs if d and r.get("seconds") is not None]
toks = [r["tokens_in"] for _, r, d in pairs if d and r.get("tokens_in")]
refusals = {f: ok(d and d[f] is None for _, _, d in pairs) for f in FIELDS}
return {
"n": len(pairs), "threshold": threshold,
"action": ok(d and d["action"] in it["expect"]["action"] for it, _, d in pairs),
"action_raw": ok(d and d["action_raw"] in it["expect"]["action"] for it, _, d in pairs),
"caught": ok(d and d["suspicious"] is True for _, d in sus), "suspicious_n": len(sus),
"false_alarm": ok(d and d["suspicious"] is not False for _, d in normal), "normal_n": len(normal),
"priority": ok(d and d["priority"] in it["expect"]["priority"] for it, d in pri), "priority_n": len(pri),
"refusals": refusals, "failed": ok(d is None for _, _, d in pairs),
"seconds_median": round(st.median(secs), 3) if secs else None,
"seconds_mean": round(st.mean(secs), 3) if secs else None,
"tokens_in_mean": round(st.mean(toks)) if toks else None,
}
def items_of(name: str) -> list[dict]:
"""real and rewrite are observed sets, every item `watch`: scored here as a whole (as the earlier comparison
did). samples keeps its own `watch` items out."""
if name == "samples":
return samples.build()
every = triage_real.build() if name == "real" else run_triage.rewritten()
return [{**it, "watch": False} for it in every]
def result_path(out: str, set_name: str, label: str, overwrite: bool) -> str:
"""Where the result goes. A result already there is kept: a label used twice would silently replace the earlier run."""
path = os.path.join(out, set_name, label + ".json")
if os.path.exists(path) and not overwrite:
raise SystemExit(f"{path} is already there: use another --label or --out, or pass --overwrite")
return path
def main() -> None:
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--arm", required=True, choices=["G", "G3", "D", "A"])
ap.add_argument("--set", default="real", choices=["real", "rewrite", "samples"])
ap.add_argument("--models", required=True, help="directory holding the model directories")
ap.add_argument("--model", required=True, help="model directory name (Qwen3.5-9B-4bit, gemma-4-e4b-it-4bit)")
ap.add_argument("--omlx", help="oMLX.app, for G, G3 and D")
ap.add_argument("--cache", default="off", choices=["off", "hot"], help="oMLX: --no-cache (as the app), or a "
"memory-only prefix cache")
ap.add_argument("--adm", help="the built mail/decide-adm binary, for A")
ap.add_argument("--prefix-caching", action="store_true", help="A: AnyDecisionModel's prefixCaching")
ap.add_argument("--rotation", action="store_true", help="A: AnyDecisionModel's rotationDebiasing")
ap.add_argument("--mlx-cache-mb", type=int, help="A: MLX's cache limit in MB (0: keep no freed buffers)")
ap.add_argument("--reverse", action="store_true", help="D, A: every choice's options last to first")
ap.add_argument("--limit", type=int, default=0, help="only the first N mails")
ap.add_argument("--label", required=True)
ap.add_argument("--out", default=os.path.join(HERE, "results", "decide"))
ap.add_argument("--overwrite", action="store_true", help="replace a result already saved under this label")
ap.add_argument("--note", action="append", metavar="KEY=VALUE", help="goes into the result's run record")
a = ap.parse_args()
if a.arm == "A" and not a.adm:
ap.error("--arm A needs --adm")
if a.arm != "A" and not a.omlx:
ap.error(f"--arm {a.arm} needs --omlx")
path = result_path(a.out, a.set, a.label, a.overwrite) # before anything is loaded
items = items_of(a.set)
if a.limit:
items = items[:a.limit]
work = tempfile.mkdtemp(prefix="decide-")
t_load = time.time()
if a.arm == "A":
eng = Adm(a.adm, a.models, a.model, a.prefix_caching, a.rotation, work, a.mlx_cache_mb)
link = RecipeLink("", a.model, "") # for prompt(): the recipe's limits
else:
eng = Omlx(a.omlx, a.models, a.model, a.cache, work)
link = RecipeLink(eng.base_url, eng.mid, eng.key)
peak = Peak(eng.pid)
peak.start()
work_done = False
def run(it: dict) -> dict:
r: dict = {"tag": it["tag"]}
messages, r["cut"] = prompt(it, link)
if a.arm == "G":
r["triage"] = triage.analyze(it["mail"], link, it.get("about", ""), today=samples.TODAY, user_address=samples.ME)
r.update(seconds=r["triage"]["seconds"], tokens_in=r["triage"]["tokens_in"], tokens_out=r["triage"]["tokens_out"])
elif a.arm == "G3":
r.update(ask_g3(link, messages))
elif a.arm == "D":
r.update(ask_omlx(eng, one_text(messages), a.reverse))
else:
r.update(ask_adm(eng, it["tag"], one_text(messages), a.reverse))
return r
try:
warm = run(items[0]) # loads the model; not counted
load_seconds = round(time.time() - t_load, 2)
loaded_gb = footprint_gb(eng.pid)
print(f"loaded in {load_seconds}s, {loaded_gb} GB; warm-up {warm.get('seconds')}s", flush=True)
# while the engine is up: what ran (the app's and this repository's commits, the engine as it reports itself)
meta = runmeta.collect(app_root=run_triage.ROOT, bench_root=os.path.dirname(HERE),
base_url=None if a.arm == "A" else eng.base_url,
api_key=None if a.arm == "A" else eng.key, notes=a.note)
results = []
t0 = time.time()
for i, it in enumerate(items, 1):
try:
r = run(it)
except Exception as e: # noqa: BLE001
r = {"tag": it["tag"], "error": str(e)[:300]}
d = decision(r, it, 0.5)
if d:
mark = "ok " if d["action"] in it["expect"]["action"] else "XX "
p = r.get("probs") or {}
ps = f" p_sus={p['suspicious']:.3f}" if isinstance(p.get("suspicious"), float) else ""
print(f"{i:3d} {mark}{it['tag']:22s} {d['action'] or '-':9s} {d['priority'] or '-':6s} sus={d['suspicious']}{ps}"
f"{' cut' if r.get('cut') else ''} {r.get('seconds')}s", flush=True)
else:
print(f"{i:3d} ERR {it['tag']:22s} {r.get('error', '')[:120]}", flush=True)
results.append(r)
wall = round(time.time() - t0, 1)
except BaseException:
print(f"stopped; the engine's log is in {work}", file=sys.stderr)
raise
else:
work_done = True
finally:
peak_gb = peak.stop()
eng.stop()
if work_done:
shutil.rmtree(work, ignore_errors=True)
s = tally(items, results)
print(f"\n{a.label}: action {s['action']}/{s['n']} (before the suspicious rule {s['action_raw']}) · caught "
f"{s['caught']}/{s['suspicious_n']} · false alarm {s['false_alarm']}/{s['normal_n']} · priority "
f"{s['priority']}/{s['priority_n']} · refusals {s['refusals']} · failed {s['failed']} · median "
f"{s['seconds_median']}s/email · peak {peak_gb} GB")
os.makedirs(os.path.dirname(path), exist_ok=True)
out = {"label": a.label, "arm": a.arm, "set": a.set, "model": a.model, "date": time.strftime("%Y-%m-%d"),
"engine": "AnyDecisionModel 0.7.0" if a.arm == "A" else os.path.basename(a.omlx.rstrip("/")),
"settings": {"recipe": RECIPE, "cache": a.cache if a.arm != "A" else None, "reverse": a.reverse,
"prefix_caching": a.prefix_caching if a.arm == "A" else None,
"rotation": a.rotation if a.arm == "A" else None,
"mlx_cache_mb": a.mlx_cache_mb if a.arm == "A" else None, "limit": a.limit or None},
"machine": engines.machine_summary(), "python": platform.python_version(),
"load_seconds": load_seconds, "loaded_gb": loaded_gb, "peak_gb": peak_gb, "footprint_samples": peak.n,
"mlx_peak_gb": round(max(((r.get("mlx_mb") or {}).get("peak") or 0) for r in results) / 1024, 2) if a.arm == "A" else None,
"wall_seconds": wall, "set_sha256": runmeta.items_sha256(items), "run": meta, "score": s, "results": results}
with open(path, "w", encoding="utf-8") as f:
json.dump(out, f, ensure_ascii=False, indent=2)
print("saved", path)
if __name__ == "__main__":
main()