SPB Git

spb/wp30_uqo

Public
22.5 KB · 339 lines python
1"""Trial planner and executor for single-handoff experiments (Tracks A and B; one process; laptop).23A *condition* is a method + parameters + question-access regime. A *trial* is (condition, model pair, document, question).4Question-blind messages/caches are built once per (condition, document) and reused across that document's questions —5this is the reuse scenario, and the build cost is recorded on every trial as `doc_build_ms` with `reuse_count` = number of6questions that shared it. The runner is resumable: successful trial keys are skipped; failures are kept and retried once.7"""8from __future__ import annotations9import json, time, traceback, yaml, sys, os10from pathlib import Path11import numpy as np12import mlx.core as mx1314from .util import ROOT, read_json, write_json, sha256_json, sha256_text, utc_now, Timer, read_jsonl15from .records import new_record, write_record, trial_key16from .data.prepare import load_doc, load_key17from .scoring import score_synthetic, score_public18from .data.exec_tasks import run_hidden_tests19from .prompts import SYSTEM_RECEIVER, SYSTEM_RECEIVER_NOMSG, receiver_user_text, receiver_question_only20from .backends.mlx_backend import MLXModel, deep_copy_cache, memory_snapshot, reset_peak21from .cache.sparse import quantize_cache, cache_tensor_bytes, to_sparse_all22from .cache.selection import select_cache23from .cache.serialize import build_manifest, serialize_cache, deserialize_cache, codec_compress, codec_decompress24from .methods import text as TM2526FIDELITY = {"A0": "custom", "A1": "custom", "A2": "custom", "A3": "custom", "A4": "custom", "A5": "custom", "A6": "custom", "A7": "custom",27            "A8": "official", "B0": "custom", "B1": "custom", "B2": "custom", "B2b": "inspired", "B3": "inspired", "B4": "custom",28            "B5": "faithful_reimplementation", "B6": "faithful_reimplementation", "B9": "custom"}2930HARDWARE_ID = "laptop-m5max-48g"3132def _load_models(cfg):33    mcfg = yaml.safe_load(open(ROOT / "configs/models.yaml"))["models"]34    cache = {}35    def get(alias):36        if alias not in cache:37            cache[alias] = MLXModel(mcfg[alias]["repo"])38        return cache[alias]39    return get, mcfg4041def _select_items(cfg):42    man = read_json(ROOT / "data/manifests/splits.json")43    items = [it for it in man["items"] if it["split"] in cfg["splits"] and it["family"] in cfg["families"]]44    if cfg.get("lengths"):45        items = [it for it in items if it.get("target_tokens") is None or it["target_tokens"] in cfg["lengths"]]46    lim = cfg.get("limit_docs_per_family")47    if lim:48        out = []49        for fam in cfg["families"]:50            out += [it for it in items if it["family"] == fam][:lim]51        items = out52    return items5354def _cond_id(c: dict) -> str:55    parts = [c["method"]]56    for k in sorted(c):57        if k not in ("method", "access", "note"):58            parts.append(f"{k}={c[k]}")59    if "access" in c:60        parts.append(c["access"])61    return "|".join(parts)6263def plan(config_path: str, output: str) -> int:64    cfg = yaml.safe_load(open(config_path))65    items = _select_items(cfg)66    rows = []67    pairs = cfg["model_pairs"]68    for it in items:69        doc = load_doc(it["document_id"], it["family"])70        nq = len(doc["questions"]) if not cfg.get("max_questions_per_doc") else min(len(doc["questions"]), cfg["max_questions_per_doc"])71        for pair in pairs:72            for c in cfg["conditions"]:73                for seed in cfg.get("seeds", [0]):74                    rows.append({"experiment_id": cfg["experiment_id"], "condition": _cond_id(c), "method": c["method"], "access": c.get("access", "none"),75                                 "sender": pair["sender"], "receiver": pair["receiver"], "family": it["family"], "document_id": it["document_id"],76                                 "split": it["split"], "target_tokens": it.get("target_tokens"), "n_questions": nq, "seed": seed, "expected_trials": nq})77    import csv78    Path(output).parent.mkdir(parents=True, exist_ok=True)79    with open(output, "w", newline="") as f:80        w = csv.DictWriter(f, fieldnames=list(rows[0].keys())); w.writeheader(); w.writerows(rows)81    tot = sum(r["expected_trials"] for r in rows)82    print(f"plan: {len(items)} documents, {len(cfg['conditions'])} conditions, {len(pairs)} model pairs -> {len(rows)} doc-conditions, {tot} trials -> {output}")83    return 08485# --------------------------------------------------------------------------------------------------------------------86class DocContext:87    """Per-document receiver state: tokenized prefix and dense cache (built lazily once)."""88    def __init__(self, receiver: MLXModel, doc_text: str, family: str):89        self.receiver = receiver; self.doc_text = doc_text; self.family = family90        self._dense = None; self.build_ms = None; self.prefix_ids = None; self.full_ids_fn = None91        self.sys = SYSTEM_RECEIVER92    def prefix_tokens(self):93        """Receiver prefix = chat tokens up to (and including) the document and the blank line before 'Question:'.94        Computed as the longest common token prefix between the prefix text and a full prompt with a canonical question."""95        if self.prefix_ids is None:96            pre_txt = self.receiver.tokenizer.apply_chat_template([{"role": "system", "content": self.sys}, {"role": "user", "content": "Document:\n" + self.doc_text + "\n\n"}], add_generation_prompt=False, tokenize=False)97            pre = self.receiver.encode(pre_txt)98            full = self.receiver.chat_prompt_tokens([{"role": "system", "content": self.sys}, {"role": "user", "content": receiver_user_text("Document", self.doc_text, "What is stated?", self.family)}])99            n = 0100            while n < min(len(pre), len(full)) and pre[n] == full[n]:101                n += 1102            self.prefix_ids = full[:n]103        return self.prefix_ids104    def split_ids(self, question: str):105        """Full chat tokens for (doc, question); returns (prefix_ids, query_ids) with prefix a true token prefix."""106        full = self.receiver.chat_prompt_tokens([{"role": "system", "content": self.sys}, {"role": "user", "content": receiver_user_text("Document", self.doc_text, question, self.family)}])107        pre = self.prefix_tokens()108        if full[:len(pre)] != pre:109            raise RuntimeError("prefix_boundary: question tokenization altered the document prefix")110        return pre, full[len(pre):]111    def dense_cache(self, prefix_ids):112        if self._dense is None or self._dense_len != len(prefix_ids):113            reset_peak()114            c, t = self.receiver.prefill(prefix_ids)115            self._dense = c; self._dense_len = len(prefix_ids); self.build_ms = t["prefill_ms"]; self.build_peak = int(mx.get_peak_memory())116        return self._dense117118def _score(family: str, pred: str, qkey: dict, key: dict) -> dict:119    if family == "exec":120        r = run_hidden_tests(pred, key["hidden_tests"])121        return {"correct": r["correct"], "pass_rate": r["pass_rate"], "error": r.get("error")}122    if family.startswith("public_"):123        return score_public(pred, [qkey["answer"]] + list(qkey.get("aliases", [])))124    return score_synthetic(pred, qkey)125126def run(config_path: str, resume: bool = False, limit: int | None = None, dry_run: bool = False) -> int:127    cfg = yaml.safe_load(open(config_path))128    res = yaml.safe_load(open(ROOT / "configs/resources.yaml"))129    protocol_hash = cfg.get("protocol_hash") or "unfrozen"130    config_hash = sha256_json(cfg)131    out_path = ROOT / "runs/raw" / f"{cfg['experiment_id']}.jsonl"132    done = set()133    if resume and out_path.exists():134        for r in read_jsonl(out_path):135            if r["status"] == "success":136                done.add(r["trial_id"])137    items = _select_items(cfg)138    get_model, mcfg = _load_models(cfg)139    gen_cfg = cfg.get("generation", {})140    gen_max = gen_cfg.get("max_tokens", 48)141    n_done = n_run = n_fail = 0142    log_path = ROOT / "runs/logs" / f"{cfg['experiment_id']}.log"143    log_path.parent.mkdir(parents=True, exist_ok=True)144    def log(msg):145        line = f"{utc_now()} {msg}"146        print(line, flush=True)147        with open(log_path, "a") as f: f.write(line + "\n")148    log(f"run start experiment={cfg['experiment_id']} config_hash={config_hash[:12]} protocol={protocol_hash[:12]} items={len(items)} resume={resume} already_done={len(done)}")149    if dry_run:150        return plan(config_path, str(ROOT / "protocol" / f"{cfg['experiment_id']}_dryrun.csv"))151    t_start = time.time()152    for it in items:153        fam = it["family"]; doc = load_doc(it["document_id"], fam); key = load_key(it["document_id"], fam)154        qs = doc["questions"][: cfg.get("max_questions_per_doc") or None]155        gen_max = gen_cfg.get("per_family", {}).get(fam, gen_cfg.get("max_tokens", 48))156        qkeys = {q["question_id"]: q for q in key["questions"]}157        for pair in cfg["model_pairs"]:158            receiver = get_model(pair["receiver"]); sender = get_model(pair["sender"])159            dc = DocContext(receiver, doc["text"], fam)160            for cond in cfg["conditions"]:161                cid = _cond_id(cond); method = cond["method"]; access = cond.get("access", "none")162                if method.startswith("B"):163                    access = cond.get("access", "blind")164                for seed in cfg.get("seeds", [0]):165                    # trials for this (doc, cond, pair, seed)166                    pending = []167                    for q in qs:168                        tk = trial_key(cfg["experiment_id"], it["document_id"], q["question_id"], method, {k: v for k, v in cond.items() if k != "method"},169                                       pair["sender"], pair["receiver"], access, protocol_hash, seed)170                        if tk in done:171                            n_done += 1; continue172                        pending.append((q, tk))173                    if not pending:174                        continue175                    if limit is not None and n_run >= limit:176                        log(f"limit {limit} reached"); return 0177                    # ---- build the question-blind message / cache once per document (reuse scenario)178                    shared = None; shared_err = None179                    if access in ("blind", "none"):180                        try:181                            shared = _build_message(method, cond, doc["text"], None, sender, receiver, dc, seed)182                        except Exception as e:183                            shared_err = e184                            log(f"BUILD FAIL {cid} {it['document_id']}: {type(e).__name__}: {str(e)[:200]}")185                    for q, tk in pending:186                        rec = _run_one(cfg, cond, cid, method, access, pair, it, doc, q, qkeys.get(q["question_id"]), key, sender, receiver, dc, seed, tk, shared, shared_err, gen_max, protocol_hash, config_hash, len(pending))187                        write_record(rec, out_path)188                        n_run += 1189                        if rec["status"] != "success": n_fail += 1190                        sc = rec["task_scores"] or {}191                        log(f"{cid:>40s} {it['document_id']:>28s} {q['question_id']:>14s} {rec['status']:>10s} corr={sc.get('correct', sc.get('f1'))} bytes={rec['serialized_payload_bytes']} ms={rec['total_wall_ms'] and round(rec['total_wall_ms'])} ans={json.dumps((rec['prediction_artifact'] or '')[:60])}")192                        if limit is not None and n_run >= limit:193                            log(f"limit {limit} reached"); return 0194            mx.clear_cache()195    log(f"run end: ran={n_run} skipped_done={n_done} failed={n_fail} elapsed_s={round(time.time()-t_start)}")196    return 0197198def _build_message(method, cond, doc_text, question, sender, receiver, dc: DocContext, seed):199    """Returns dict with message (Track A) or cache payload info (Track B); encode timings included."""200    t = Timer(); t.start("encode")201    out = {"method": method}202    if method == "A0":203        out["msg"] = TM.a0_no_message()204    elif method == "A1":205        out["msg"] = TM.a1_full(doc_text)206    elif method == "A2":207        out["msg"] = TM.a2_truncate(doc_text, cond["budget_tokens"], receiver.tokenizer)208    elif method == "A3":209        out["msg"] = TM.a3_extractive(doc_text, cond["budget_tokens"], receiver.tokenizer, question)210    elif method == "A4":211        out["msg"] = TM.a4_summary(doc_text, cond["budget_tokens"], sender, question)212    elif method == "A5":213        out["msg"] = TM.a5_structured(doc_text, cond["budget_tokens"], sender, question)214    elif method == "A6":215        out["msg"] = TM.a6_references(doc_text, cond["budget_tokens"], sender, question)216    elif method == "A7":217        out["msg"] = TM.a7_codec(doc_text, cond.get("codec", "zstd"))218    elif method == "A8":219        out["msg"] = TM.a8_llmlingua(doc_text, cond["budget_tokens"], receiver.tokenizer, question, device=cond.get("device", "mps"))220    elif method.startswith("B"):221        pre = dc.prefix_tokens()222        dense = dc.dense_cache(pre)223        out["doc_build_ms"] = dc.build_ms; out["doc_build_peak"] = dc.build_peak; out["prefix_tokens"] = len(pre)224        out["dense_bytes"] = cache_tensor_bytes(dense)225        t.start("compress")226        if method == "B0":227            c = to_sparse_all(deep_copy_cache(dense)); info = {}228        elif method == "B1":229            c = to_sparse_all(deep_copy_cache(dense)); info = {"serialize_roundtrip": True}230        elif method == "B2":231            c = quantize_cache(dense, cond["bits"], cond.get("group_size", 64)); info = {"bits": cond["bits"]}232        elif method in ("B3", "B4", "B5", "B6", "B9"):233            policy = {"B3": "sink_recent", "B4": "random", "B5": "attention", "B6": "pyramid", "B9": cond.get("policy", "sink_recent")}[method]234            window = None235            if policy in ("attention", "pyramid"):236                if question is not None:237                    window = dc.split_ids(question)[1]          # question-aware: the fresh query tokens are the observation window238                else:239                    window = receiver.encode("\n\nSummarize the key facts, identifiers, amounts, dates and statuses of this document.")  # question-blind generic instruction240            c, info = select_cache(receiver, dense, policy, cond["keep_frac"], window_token_ids=window, seed=seed, sinks=cond.get("sinks", 4), window_keep=cond.get("window_keep", 32))241            if method == "B9":242                c = quantize_cache(c, cond["bits"], cond.get("group_size", 64)); info["bits"] = cond["bits"]243        else:244            raise NotImplementedError(method)245        mx.eval([x for cc in c for x in (cc.keys if isinstance(cc.keys, tuple) else (cc.keys,))])246        mx.synchronize()247        t.stop("compress")248        t.start("serialize")249        man = build_manifest(receiver.info, pre, c, "doc", method, {k: v for k, v in cond.items() if k != "method"}, {"selection_info": {k: v for k, v in info.items() if k != "layer_budgets"}})250        payload = serialize_cache(c, man)251        t.stop("serialize")252        codec = cond.get("codec", "none")253        comp, comp_ms = codec_compress(payload, codec) if codec != "none" else (payload, 0.0)254        out.update({"cache": c, "payload": comp, "payload_bytes": len(comp), "raw_payload_bytes": len(payload), "cache_bytes": cache_tensor_bytes(c), "manifest": man,255                    "compress_ms": t.spans.get("compress", 0.0), "serialize_ms": t.spans["serialize"] + comp_ms, "codec": codec, "select_info": info})256    else:257        raise NotImplementedError(method)258    t.stop("encode")259    out["encode_ms"] = t.spans["encode"]260    return out261262def _run_one(cfg, cond, cid, method, access, pair, it, doc, q, qkey, key, sender, receiver, dc, seed, tk, shared, shared_err, gen_max, protocol_hash, config_hash, reuse_count):263    fam = it["family"]264    rec = new_record(experiment_id=cfg["experiment_id"], trial_id=tk, run_group_id=cfg["experiment_id"] + ":" + cid, protocol_hash=protocol_hash, config_hash=config_hash,265                     task_family=fam, document_id=it["document_id"], document_hash=it["document_hash"], question_id=q["question_id"], split=it["split"], cluster_id=it["cluster_id"],266                     sender_model_revision=f"{sender.info.repo_id}@{sender.info.revision}", receiver_model_revision=f"{receiver.info.repo_id}@{receiver.info.revision}",267                     tokenizer_hashes={"sender": sender.info.tokenizer_hash, "receiver": receiver.info.tokenizer_hash},268                     backend_versions={"mlx": mx.__version__, "mlx_lm": receiver.info.mlx_lm_version}, hardware_id=HARDWARE_ID, device_state={"mlx_active_before": int(mx.get_active_memory())},269                     weight_precision="bf16", method_id=method, implementation_fidelity=FIDELITY.get(method, "custom"),270                     compression_config={k: v for k, v in cond.items() if k != "method"}, question_access=access, topology="single_handoff", handoff_index=1 if method != "A0" else 0,271                     reuse_count=reuse_count if access in ("blind", "none") else 1, cache_hit=(access in ("blind", "none") and method.startswith("B")), cache_compatibility_hash=None,272                     random_seed=seed, query_tokens=None, message_tokens=None, message_utf8_bytes=None, cache_tensor_bytes=None, serialized_payload_bytes=None,273                     input_usage={}, output_usage={}, provider_cached_usage=None, process_memory=None, backend_memory=None, peak_prefill_memory=None, peak_decode_memory=None,274                     mapper_memory=None, cost_with_source=None, prediction_artifact=None, evidence_artifact=None, reference_key_id=f"keys/{fam}/{it['document_id']}.json",275                     task_scores=None, status="implementation_error", error_code=None, log_artifact=f"runs/logs/{cfg['experiment_id']}.log", payload_hash=None, output_hash=None)276    rec["source_tokens_sender"] = len(sender.encode(doc["text"])); rec["source_tokens_receiver"] = len(receiver.encode(doc["text"]))277    t_total0 = time.perf_counter()278    try:279        if shared_err is not None:280            raise shared_err281        built = shared if shared is not None else _build_message(method, cond, doc["text"], q["question"], sender, receiver, dc, seed)282        spans = {"encode_ms": built["encode_ms"]}283        reset_peak()284        if method.startswith("A"):285            msg = built["msg"]286            if method == "A6":287                material, rinfo = TM.a6_retrieve(msg, q["question"], cond.get("max_fetch_bytes", 2000), cond.get("max_lookups", 6))288                rec["fetched_bytes"] = rinfo["fetched_bytes"]; rec["evidence_artifact"] = rinfo289            else:290                material = msg.text291            if method == "A0":292                ids = receiver.chat_prompt_tokens([{"role": "system", "content": SYSTEM_RECEIVER_NOMSG}, {"role": "user", "content": receiver_question_only(q["question"], fam)}])293            else:294                ids = receiver.chat_prompt_tokens([{"role": "system", "content": SYSTEM_RECEIVER}, {"role": "user", "content": receiver_user_text(msg.material_label, material, q["question"], fam)}])295            spans["decode_payload_ms"] = msg.decode_ms296            g = receiver.generate_text(ids, max_tokens=gen_max)297            spans.update({"receiver_prefill_ms": g["prefill_ms"], "ttft_ms": g["ttft_ms"], "decode_ms": g["decode_ms"]})298            rec.update({"message_tokens": len(receiver.encode(material)), "message_utf8_bytes": msg.utf8_bytes, "serialized_payload_bytes": msg.payload_bytes,299                        "side_information_bytes": msg.side_information_bytes, "query_tokens": len(ids), "input_usage": {"receiver_prompt_tokens": len(ids), **msg.sender_usage},300                        "payload_hash": sha256_text(material)})301            if msg.meta: rec["compression_config"] = {**rec["compression_config"], "realized": {k: v for k, v in msg.meta.items() if k not in ("question_aware",)}}302            if method == "A5": rec["evidence_artifact"] = {"n_facts": msg.meta.get("n_facts"), "unresolved_quotes": msg.meta.get("unresolved_quotes"), "parse_ok": msg.meta.get("parse_ok")}303        else:304            pre, query_ids = dc.split_ids(q["question"])305            assert len(pre) == built["prefix_tokens"], "prefix mismatch"306            c = built["cache"]307            spans.update({"doc_prefill_ms": built["doc_build_ms"], "compress_ms": built["compress_ms"], "serialize_ms": built["serialize_ms"]})308            t = Timer(); t.start("load")309            if method == "B1" or cond.get("roundtrip", False):310                raw, dms = codec_decompress(built["payload"], built["codec"]) if built["codec"] != "none" else (built["payload"], 0.0)311                c_use, man = deserialize_cache(raw, receiver.info, built["manifest"]["prefix_token_hash"])312                rec["cache_compatibility_hash"] = man["prefix_token_hash"][:16]313            else:314                c_use = deep_copy_cache(c)315            t.stop("load"); spans["load_ms"] = t.spans["load"]316            g = receiver.generate_from_cache(c_use, query_ids, max_tokens=gen_max)317            spans.update({"receiver_prefill_ms": 0.0, "query_prefill_ms": g["query_prefill_ms"], "ttft_ms": g["ttft_ms"], "decode_ms": g["decode_ms"]})318            rec.update({"message_tokens": built["prefix_tokens"], "message_utf8_bytes": len(doc["text"].encode("utf-8")), "serialized_payload_bytes": built["payload_bytes"],319                        "cache_tensor_bytes": built["cache_bytes"], "side_information_bytes": built["payload_bytes"] - built["cache_bytes"] if built["codec"] == "none" else None,320                        "query_tokens": len(query_ids), "input_usage": {"receiver_prefix_tokens": built["prefix_tokens"], "dense_cache_bytes": built["dense_bytes"], "query_tokens": len(query_ids)},321                        "payload_hash": sha256_text(str(len(built["payload"]))) , "peak_prefill_memory": built["doc_build_peak"]})322            rec["compression_config"] = {**rec["compression_config"], "realized": {k: v for k, v in built["select_info"].items() if k not in ("layer_budgets",)}}323        pred = g["text"]324        rec["prediction_artifact"] = pred; rec["output_hash"] = sha256_text(pred); rec["output_usage"] = {"output_tokens": g["output_tokens"]}325        rec["ttft_ms"] = spans["ttft_ms"]; rec["timing_spans"] = spans326        rec["total_wall_ms"] = (time.perf_counter() - t_total0) * 1000327        rec["peak_decode_memory"] = int(mx.get_peak_memory()); rec["backend_memory"] = memory_snapshot(); rec["process_memory"] = rec["backend_memory"]["process_rss_bytes"]328        if qkey is None:329            rec["status"] = "implementation_error"; rec["error_code"] = "missing_key"330        else:331            rec["task_scores"] = _score(fam, pred, qkey, key)332            rec["status"] = "success" if pred.strip() else "invalid_output"333    except Exception as e:334        rec["status"] = "oom" if "memory" in str(e).lower() else "implementation_error"335        rec["error_code"] = f"{type(e).__name__}: {str(e)[:300]}"336        rec["total_wall_ms"] = (time.perf_counter() - t_total0) * 1000337        traceback.print_exc()338    return rec339
Files · c1d4b3900e40473a307dd7a405fffb0fb01ebc3b
Menu

Theme