Download htr/rewrite/engine.py from spboucher04/htr-tiny: direct link, hf CLI and curl.
- Browser
- Download file 12 kB
-
https://huggingface.co/spboucher04/htr-tiny/resolve/main/htr/rewrite/engine.py
- Command line
-
hf download hf://spboucher04/htr-tiny/htr/rewrite/engine.py
-
curl -L -o engine.py https://huggingface.co/spboucher04/htr-tiny/resolve/main/htr/rewrite/engine.py
12 kB
| """Rewrite job engine: request planning, deduplication, on-disk cache, ledger (resume), budget ceiling, | |
| live or batch execution. Originals and rewrites are never overwritten; every rewrite row carries model, | |
| prompt version, request id, usage and cost. | |
| Layout under ``<job_dir>/``: plan.jsonl (requests), rewrites.jsonl (append-only results), ledger.json | |
| (spend, counts, batch ids), batches/<id>.json (submitted custom_ids), manifest.json (provenance). | |
| """ | |
| from __future__ import annotations | |
| import json | |
| import time | |
| from concurrent.futures import ThreadPoolExecutor, as_completed | |
| from pathlib import Path | |
| from htr.data.schema import Rewrite, RewriteRequest | |
| from htr.parse.protect import PROTECT_VERSION, protect | |
| from htr.rewrite.prompts import PROMPT_VERSION, build_messages, prompt_fingerprint | |
| from htr.rewrite.provider import Provider | |
| from htr.utils.hashing import sha256_text, short_id | |
| from htr.utils.io import append_jsonl, ensure_dir, read_json, read_jsonl, write_json, write_jsonl | |
| from htr.utils.provenance import run_header, utc_now | |
| class BudgetExceeded(RuntimeError): | |
| pass | |
| def plan_requests(passages: list[dict], variants: list[str], samples: dict[str, int], provider_name: str, model: str, max_tokens: int, effort: str) -> list[RewriteRequest]: | |
| """One request per (passage, variant, sample). Request ids are deterministic → natural dedup across runs.""" | |
| reqs: list[RewriteRequest] = [] | |
| for p in passages: | |
| for v in variants: | |
| for s in range(samples.get(v, 1)): | |
| rid = short_id("req", p["passage_id"], v, str(s), provider_name, model, PROMPT_VERSION) | |
| reqs.append(RewriteRequest(request_id=rid, passage_id=p["passage_id"], variant=v, sample_index=s, provider=provider_name, model=model, prompt_version=PROMPT_VERSION, params={"max_tokens": max_tokens, "effort": effort})) | |
| return reqs | |
| def _protected_text(p: dict) -> str: | |
| """Passages are sent with citations/math/urls replaced by placeholders so the LLM cannot alter them; the | |
| engine stores the placeholder form and the validator checks placeholder multisets.""" | |
| return protect(p["text"]).text | |
| def merge_plan(job_dir: Path, reqs: list[RewriteRequest]) -> dict[str, RewriteRequest]: | |
| """plan.jsonl accumulates every request ever planned for the job (needed to interpret batch results).""" | |
| existing = {r["request_id"]: RewriteRequest(**r) for r in read_jsonl(job_dir / "plan.jsonl")} | |
| for r in reqs: | |
| existing[r.request_id] = r | |
| write_jsonl(job_dir / "plan.jsonl", existing.values()) | |
| return existing | |
| class RewriteEngine: | |
| def __init__(self, job_dir: Path, provider: Provider, budget_usd: float, batch: bool = False, concurrency: int = 4): | |
| self.job_dir = ensure_dir(job_dir) | |
| self.provider = provider | |
| self.budget = budget_usd | |
| self.batch = batch | |
| self.concurrency = concurrency | |
| self.ledger_path = self.job_dir / "ledger.json" | |
| self.ledger = read_json(self.ledger_path) if self.ledger_path.exists() else {"spent_usd": 0.0, "n_ok": 0, "n_error": 0, "n_refused": 0, "n_truncated": 0, "n_empty": 0, "batches": [], "created_at": utc_now()} | |
| self.done: set[str] = {r["request_id"] for r in read_jsonl(self.job_dir / "rewrites.jsonl")} | |
| def _save_ledger(self) -> None: | |
| self.ledger["updated_at"] = utc_now() | |
| write_json(self.ledger_path, self.ledger) | |
| def _record(self, req: RewriteRequest, passage: dict, res, batch_id: str | None = None) -> Rewrite: | |
| rw = Rewrite( | |
| rewrite_id=short_id("rw", req.request_id), | |
| request_id=req.request_id, | |
| passage_id=req.passage_id, | |
| doc_id=passage["doc_id"], | |
| variant=req.variant, | |
| sample_index=req.sample_index, | |
| provider=self.provider.name, | |
| model=res.model or req.model, | |
| prompt_version=req.prompt_version, | |
| text=res.text, | |
| status=res.status, # type: ignore[arg-type] | |
| error=res.error, | |
| provider_request_id=res.provider_request_id, | |
| usage={k: v for k, v in (res.usage or {}).items() if v is not None}, | |
| cost_usd=res.cost_usd, | |
| stop_reason=res.stop_reason, | |
| created_at=utc_now(), | |
| latency_s=res.latency_s, | |
| batch_id=batch_id, | |
| protect_version=PROTECT_VERSION, | |
| prompt_input_sha256=sha256_text(_protected_text(passage)), | |
| ) | |
| append_jsonl(self.job_dir / "rewrites.jsonl", rw) | |
| self.done.add(req.request_id) | |
| self.ledger["spent_usd"] = round(self.ledger["spent_usd"] + (res.cost_usd or 0.0), 6) | |
| self.ledger[f"n_{res.status}"] = self.ledger.get(f"n_{res.status}", 0) + 1 | |
| return rw | |
| # Calibration from the pilot job (5 801 Opus 5.5 requests, 2026-11-09): measured 691 input / 323 output tokens per | |
| # request vs the naive chars/4 estimate (492 / 259) → multiply by 1.40 / 1.25. | |
| EST_IN_FACTOR = 1.40 | |
| EST_OUT_FACTOR = 1.25 | |
| def estimate(self, reqs: list[RewriteRequest], passages: dict[str, dict], pricing: dict | None) -> dict: | |
| """Pre-flight estimate: chars/4 ≈ tokens, prompt overhead ≈ 260 tokens, calibrated on the pilot (see constants).""" | |
| pend = [r for r in reqs if r.request_id not in self.done] | |
| toks_in = int(self.EST_IN_FACTOR * sum(260 + len(_protected_text(passages[r.passage_id])) // 4 for r in pend)) | |
| toks_out = int(self.EST_OUT_FACTOR * sum(int(1.1 * len(passages[r.passage_id]["text"]) // 4) for r in pend)) | |
| est = None | |
| if pricing and self.provider.model in pricing["models"]: | |
| m = pricing["models"][self.provider.model] | |
| est = (toks_in * m["input"] + toks_out * m["output"]) / 1e6 * (pricing.get("batch_discount", 0.5) if self.batch else 1.0) | |
| return {"pending_requests": len(pend), "done": len(self.done), "est_input_tokens": toks_in, "est_output_tokens": toks_out, "est_cost_usd": None if est is None else round(est, 2), "budget_usd": self.budget, "spent_usd": self.ledger["spent_usd"]} | |
| # ---- live ---------------------------------------------------------------------------------------------- | |
| def run_live(self, reqs: list[RewriteRequest], passages: dict[str, dict], max_requests: int | None = None) -> dict: | |
| pend = [r for r in reqs if r.request_id not in self.done][: max_requests or None] | |
| merge_plan(self.job_dir, reqs) | |
| n = 0 | |
| def work(req: RewriteRequest): | |
| p = passages[req.passage_id] | |
| system, messages = build_messages(_protected_text(p), req.variant) | |
| return req, p, self.provider.rewrite(system, messages, req.params["max_tokens"], {"variant": req.variant, "sample_index": req.sample_index}) | |
| with ThreadPoolExecutor(max_workers=self.concurrency) as ex: | |
| futs = [ex.submit(work, r) for r in pend] | |
| for f in as_completed(futs): | |
| req, p, res = f.result() | |
| self._record(req, p, res) | |
| n += 1 | |
| if n % 25 == 0: | |
| self._save_ledger() | |
| if self.ledger["spent_usd"] > self.budget: | |
| self._save_ledger() | |
| for g in futs: | |
| g.cancel() | |
| raise BudgetExceeded(f"spent {self.ledger['spent_usd']:.2f} USD > ceiling {self.budget:.2f} USD") | |
| self._save_ledger() | |
| return {"processed": n, **self.ledger} | |
| # ---- batch --------------------------------------------------------------------------------------------- | |
| def submit_batches(self, reqs: list[RewriteRequest], passages: dict[str, dict], chunk: int = 2000, max_requests: int | None = None, pricing: dict | None = None) -> list[str]: | |
| if not self.provider.supports_batch(): | |
| raise RuntimeError("provider has no batch support") | |
| pend = [r for r in reqs if r.request_id not in self.done] | |
| submitted = {cid for b in self.ledger["batches"] for cid in read_json(self.job_dir / "batches" / f"{b}.json")["custom_ids"]} if self.ledger["batches"] else set() | |
| pend = [r for r in pend if r.request_id not in submitted][: max_requests or None] | |
| merge_plan(self.job_dir, reqs) | |
| # pre-flight budget check: estimated cost of what is about to be submitted + spent + already-submitted estimate | |
| if pricing is not None: | |
| est_new = self.estimate(pend, passages, pricing)["est_cost_usd"] or 0.0 | |
| est_sub = self.ledger.get("submitted_est_usd", 0.0) | |
| if self.ledger["spent_usd"] + est_sub + est_new > self.budget: | |
| raise BudgetExceeded(f"estimated {self.ledger['spent_usd'] + est_sub + est_new:.2f} USD (spent + submitted + new) > ceiling {self.budget:.2f} USD; nothing submitted") | |
| self.ledger["submitted_est_usd"] = round(est_sub + est_new, 4) | |
| ids: list[str] = [] | |
| for i in range(0, len(pend), chunk): | |
| part = pend[i : i + chunk] | |
| items = [] | |
| for r in part: | |
| p = passages[r.passage_id] | |
| system, messages = build_messages(_protected_text(p), r.variant) | |
| items.append((r.request_id, system, messages, r.params["max_tokens"])) | |
| bid = self.provider.submit_batch(items) # type: ignore[attr-defined] | |
| write_json(ensure_dir(self.job_dir / "batches") / f"{bid}.json", {"batch_id": bid, "submitted_at": utc_now(), "custom_ids": [r.request_id for r in part], "model": self.provider.model, "prompt_version": PROMPT_VERSION}) | |
| self.ledger["batches"].append(bid) | |
| ids.append(bid) | |
| self._save_ledger() | |
| return ids | |
| def collect_batches(self, reqs: list[RewriteRequest], passages: dict[str, dict]) -> dict: | |
| by_id = merge_plan(self.job_dir, reqs) # all requests ever planned, not only the current selection | |
| collected = 0 | |
| unresolved = 0 | |
| pending_batches = [] | |
| for bid in list(self.ledger["batches"]): | |
| meta = read_json(self.job_dir / "batches" / f"{bid}.json") | |
| if meta.get("collected"): | |
| continue | |
| st = self.provider.batch_status(bid) # type: ignore[attr-defined] | |
| if st["status"] != "ended": | |
| pending_batches.append(st) | |
| continue | |
| results = self.provider.batch_results(bid) # type: ignore[attr-defined] | |
| for cid, res in results.items(): | |
| if cid in self.done: | |
| continue | |
| if cid not in by_id or by_id[cid].passage_id not in passages: | |
| unresolved += 1 | |
| continue | |
| self._record(by_id[cid], passages[by_id[cid].passage_id], res, batch_id=bid) | |
| collected += 1 | |
| if unresolved: | |
| meta["unresolved"] = unresolved | |
| write_json(self.job_dir / "batches" / f"{bid}.json", meta) | |
| self._save_ledger() | |
| continue # leave the batch uncollected so a later call with the full plan can finish it | |
| meta["collected"] = True | |
| meta["collected_at"] = utc_now() | |
| meta["status"] = st | |
| write_json(self.job_dir / "batches" / f"{bid}.json", meta) | |
| self._save_ledger() | |
| if self.ledger["spent_usd"] > self.budget: | |
| self._save_ledger() | |
| raise BudgetExceeded(f"spent {self.ledger['spent_usd']:.2f} USD > ceiling {self.budget:.2f} USD (collected results are kept)") | |
| return {"collected": collected, "unresolved": unresolved, "pending_batches": pending_batches, **self.ledger} | |
| def write_manifest(self, extra: dict) -> None: | |
| write_json(self.job_dir / "manifest.json", {**run_header({"job": "rewrite"}), "provider": self.provider.name, "model": self.provider.model, "prompt_version": PROMPT_VERSION, "prompt_fingerprint": prompt_fingerprint(), "budget_usd": self.budget, "batch": self.batch, **extra}) | |