"""Serve a Jev-style request: state + typed questions -> typed answers. Usage: python -m alea.predict --ckpt runs/alea_mini/final.pt --request req.json echo '{"state":"...","questions":{...}}' | python -m alea.predict --ckpt ... --stdin """ import argparse import json import sys import torch from .dataset import row_to_specs from .eval import load_model from .model import collate from .packing import QuestionSpec, pack_request def request_to_specs(req): row = {"state": req["state"], "questions": req["questions"], "targets": {qid: [0.0] * len(s.get("criteria", s.get("levels", {}))) if s["type"] in ("choice", "score") else 0.0 for qid, s in req["questions"].items()}} return row_to_specs(row)[:2] @torch.no_grad() def answer(model, tok, req, device, max_len=4096): state = req["state"] if not isinstance(state, str): state = json.dumps(state) qs = [] for qid, s in req["questions"].items(): qt = s["type"] if qt in ("choice", "score"): crit = s.get("criteria") or s.get("levels") or {} # canonical ordering: caller's dict order never reaches the model, # so identical semantic requests produce identical responses keys = sorted(crit.keys()) opts = [f"{k}: {crit[k]}" for k in keys] qs.append(QuestionSpec(qid, qt, s["instructions"], opts, keys)) elif qt == "regress": instr = s["instructions"] if s.get("unit"): instr += f" (unit: {s['unit']})" qs.append(QuestionSpec(qid, "regress", instr, [], None)) else: qs.append(QuestionSpec(qid, "noul", s["instructions"], [], None)) pk = pack_request(tok, state, qs, max_len=max_len) ids, mask, pos = collate([pk], tok.pad_token_id or tok.eos_token_id) out = model(ids.to(device), mask.to(device).to(torch.bfloat16), pos.to(device), [pk])[0] answers = {} for r in out: spec = next(s for s in qs if s.qid == r["qid"]) if r["qtype"] == "choice": p = torch.softmax(r["logits"], -1).tolist() keys = spec.option_keys or [str(i) for i in range(len(p))] pm = max(p) K = len(p) answers[r["qid"]] = { "type": "choice", "choice": keys[p.index(pm)], "probabilities": dict(zip(keys, [round(x, 4) for x in p])), "confidence": round((pm - 1 / K) / (1 - 1 / K), 4) if K > 1 else 1.0} elif r["qtype"] == "score": p = torch.softmax(r["logits"], -1).tolist() keys = spec.option_keys or [str(i) for i in range(len(p))] answers[r["qid"]] = { "type": "score", "score": round(sum(i * x for i, x in enumerate(p)), 3), "probabilities": dict(zip(keys, [round(x, 4) for x in p]))} elif r["qtype"] == "regress": from .heads import TAUS qv = [round(x, 3) for x in r["quantiles"].tolist()] answers[r["qid"]] = { "type": "regress", "mean": round(sum(qv) / len(qv), 3), "median": qv[9], "q05": qv[0], "q95": qv[-1], "quantiles": {f"{t:.2f}": v for t, v in zip(TAUS, qv)}} else: answers[r["qid"]] = {"type": "noul", "noul": round(r["p_yes"].item(), 4)} return {"model": "alea-mini", "answers": answers} def main(): ap = argparse.ArgumentParser() ap.add_argument("--ckpt", required=True) ap.add_argument("--request") ap.add_argument("--stdin", action="store_true") ap.add_argument("--model", default="Qwen/Qwen3-0.6B") args = ap.parse_args() from transformers import AutoTokenizer dev = torch.device("cuda" if torch.cuda.is_available() else "cpu") tok = AutoTokenizer.from_pretrained(args.model) model = load_model(args.ckpt, args.model, dev) req = json.loads(sys.stdin.read() if args.stdin else open(args.request, encoding="utf-8").read()) print(json.dumps(answer(model, tok, req, dev), indent=2)) if __name__ == "__main__": main()