Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 10 additions & 2 deletions experiments/35-full-rag-benchmark-2026-11-01/answers35.py
Original file line number Diff line number Diff line change
Expand Up @@ -291,6 +291,13 @@ def answer_row(
}


def failed_usage(result: Mapping[str, Any]) -> dict[str, Any] | None:
"""Return the tokens and cost a failed answer call reported, else ``None`` (task 16.20)."""
usage = result.get("usage") or {}
kept = {k: usage[k] for k in ("input_tokens", "output_tokens", "cost_usd") if k in usage}
return kept or None


def _trace(
ctx: stages35.Ctx,
qid: str,
Expand Down Expand Up @@ -365,7 +372,7 @@ async def answer_stage(ctx: stages35.Ctx) -> int:

async def one(qid: str) -> None:
question = by_id[qid]
error = None
error, usage = None, None
try:
async with searching:
found, line = await stagekit35.ranked(ctx, question.text)
Expand All @@ -388,12 +395,13 @@ async def one(qid: str) -> None:
result = {**result, "answer": ""}
elif result.get("answer") is None:
error = ctx.redact(str(result.get("error") or "no answer text"))[:500]
usage = failed_usage(result)
except (stagekit35.RerankFailed, RateLimitStop):
raise
except Exception as exc: # noqa: BLE001 - an error is not a result (section 12)
error = stages35._error(ctx, exc)
if error is not None:
kept.fail(qid, error, _trace(ctx, qid, None, error))
kept.fail(qid, error, _trace(ctx, qid, None, error), usage=usage)
say(f"[answer] {qid}: ERROR {error}")
return
cut = frozenset(str(r["chunk_id"]) for r in rows if r.get("truncated"))
Expand Down
4 changes: 2 additions & 2 deletions experiments/35-full-rag-benchmark-2026-11-01/arms.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,8 @@
ANSWER_CONTEXT_WINDOW = 131072
ANSWER_MAX_ROUNDS = 1

#: Starting concurrency and attempt values (design D18). Task 9.2 replaces them
#: with the measured values before the freeze.
#: Concurrency and attempt values (design D18), confirmed by the test pod sessions
#: (task 10.4, 2026-11-27): no rate-limit stop at these values (protocol section 7).
CONCURRENCY_DEFAULTS: Mapping[str, int] = {
"answer_concurrency": 16,
"chat_concurrency": 4,
Expand Down
3 changes: 3 additions & 0 deletions experiments/35-full-rag-benchmark-2026-11-01/claimstage35.py
Original file line number Diff line number Diff line change
Expand Up @@ -248,6 +248,9 @@ async def one(item_id: str) -> None:
"version": version,
"model_returned": getattr(reply, "model_returned", None),
"provider_returned": getattr(reply, "provider_returned", None),
"input_tokens": getattr(reply, "input_tokens", None),
"output_tokens": getattr(reply, "output_tokens", None),
"cost_usd": getattr(reply, "cost_usd", None),
},
)

Expand Down
190 changes: 190 additions & 0 deletions experiments/35-full-rag-benchmark-2026-11-01/hostedusage35.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,190 @@
"""Hosted-call items of the Experiment 35 compute table (task 16.20; prereg sections 17, 21).

Each function reads saved files only; a value that is not defined reads
:data:`NOT_DEFINED`.

- :func:`hosted_usage`: per stage (the output kind, for example ``answer`` or
``closedbook-own``) and role, the rows, calls, error rows, harness resends
(``resent_calls``), calls closed as missing after the resend cap, and the
tokens and cost. The answer, Ragas and claim-classifier rows record tokens
and cost per call; a billed failed answer or classifier attempt keeps its
figures in the stage's ``<stage>.errors.jsonl`` line and is added (an error
line with no figures is counted in ``failed_attempts_without_usage``). The
GLM-5.3 claim checks record none; GLM-5.3 is the only Z.ai role, so its
tokens and cost are the Z.ai billing export (amendment A18 item 35).
A sum is defined only when every saved call reported the figure.
- :func:`billing_by_provider`: the ``usd`` of the billing rows per provider.
- :func:`energy_estimate`: closed GPU pod hours times the board power of the
RTX 4090 (450 W), in kWh (Strubell et al. 2019; Lacoste et al. 2019).
- :func:`record_stop` and :func:`stops`: every rate-limit and ``out_of_credit``
stop (``stops.jsonl``, written by ``run_arms.py``).
- :func:`returned_models`: the returned-model counts per role from ``join.json``.
"""

from __future__ import annotations

import json
import math
from collections.abc import Iterable, Mapping, Sequence
from datetime import UTC, datetime
from pathlib import Path
from typing import Any

from outputs35 import read_rows

NOT_DEFINED = "not defined"
#: RTX 4090 board power in watts (NVIDIA specification), the only GPU type (protocol 9.3).
BOARD_WATTS = 450
GLM_SOURCE = "billing export (Z.ai)"
#: Row file, role, summary file, error file of failed attempts, and the figures' source.
ROLES = (
("answer.jsonl", "answer", "answer-summary.json", "answer.errors.jsonl", "rows"),
("ragas.jsonl", "ragas-judge", "ragas-summary.json", None, "rows"),
("judge-chat.jsonl", "judge-glm", "judge-chat-summary.json", None, GLM_SOURCE),
(
"claim-kinds.jsonl",
"claim-classifier",
"claimkinds-summary.json",
"claimkinds.errors.jsonl",
"rows",
),
)


def _calls(role: str, row: Mapping[str, Any]) -> list[Mapping[str, Any]]:
"""Return the hosted calls one row holds, each with its figures and error."""
if role == "ragas-judge":
return list(row.get("calls") or [])
if role == "judge-glm":
return [v.get("call") or {} for v in row.get("verdicts") or []]
return [row]


def _is_error(call: Mapping[str, Any]) -> bool:
return call.get("status") == "error" or bool(call.get("error"))


def _first(call: Mapping[str, Any], names: Sequence[str]) -> float | None:
return next((call[n] for n in names if isinstance(call.get(n), (int, float))), None)


def _total(calls: Sequence[Mapping[str, Any]], *names: str) -> float | str:
values = [_first(c, names) for c in calls]
if not values or None in values:
return NOT_DEFINED
return round(sum(v for v in values if v is not None), 12)


def _empty(stage: str, role: str, source: str) -> dict[str, Any]:
return {
"stage": stage,
"role": role,
"source": source,
"rows": 0,
"calls": [],
"error_rows": 0,
"resent_calls": 0,
"closed_missing": 0,
"summaries_missing": 0,
"failed_attempts": 0,
"failed_attempts_without_usage": 0,
}


def hosted_usage(out: Path) -> dict[str, Any]:
"""Return per stage and role the hosted calls, errors, resends, tokens and cost."""
found: dict[tuple[str, str], dict[str, Any]] = {}
for name, role, summary_name, errors_name, source in ROLES:
for path in sorted(out.glob(f"*/*/*/run*/{name}")):
stage = path.parts[-4]
per = found.setdefault((stage, role), _empty(stage, role, source))
for row in read_rows(path):
if row.get("missing"):
continue
calls = _calls(role, row)
per["rows"] += 1
per["calls"].extend(calls)
Comment thread
cmdaltctr marked this conversation as resolved.
Resolved
per["error_rows"] += any(_is_error(c) for c in calls)
for line in read_rows(path.parent / errors_name) if errors_name else []:
per["failed_attempts"] += 1
if line.get("usage"):
per["calls"].append(line["usage"])
else:
per["failed_attempts_without_usage"] += 1
summary_path = path.parent / summary_name
if summary_path.is_file():
summary = json.loads(summary_path.read_text(encoding="utf-8"))
per["resent_calls"] += int(summary.get("resent_calls") or 0)
per["closed_missing"] += len(summary.get("closed_missing") or [])
else:
per["summaries_missing"] += 1
Comment thread
cmdaltctr marked this conversation as resolved.
Resolved
rows = []
for _, per in sorted(found.items()):
calls = per.pop("calls")
by_rows = per["source"] == "rows"
rows.append(
{
**per,
"calls": len(calls),
"resent_calls": NOT_DEFINED if per["summaries_missing"] else per["resent_calls"],
"closed_missing": NOT_DEFINED
if per["summaries_missing"]
else per["closed_missing"],
"input_tokens": _total(calls, "input_tokens") if by_rows else NOT_DEFINED,
"output_tokens": _total(calls, "output_tokens") if by_rows else NOT_DEFINED,
"cost_usd": _total(calls, "cost_usd", "reported_cost_usd")
if by_rows
else NOT_DEFINED,
}
)
return {"roles": rows}


def billing_by_provider(paths: Iterable[Path]) -> dict[str, float] | str:
"""Return the billed ``usd`` per provider, else "not defined" without billing files."""
totals: dict[str, float] = {}
for path in paths:
for row in json.loads(path.read_text(encoding="utf-8")):
provider = str(row["provider"])
usd = float(row["usd"])
if not math.isfinite(usd):
raise ValueError(f"{path}: {provider} usd {row['usd']!r} is not a finite amount")
totals[provider] = round(totals.get(provider, 0.0) + usd, 12)
return dict(sorted(totals.items())) if totals else NOT_DEFINED


def energy_estimate(compute: Mapping[str, Any] | str) -> dict[str, Any] | str:
"""Return the closed GPU pod hours times the board power, in kWh."""
if not isinstance(compute, Mapping):
return NOT_DEFINED
hours = sum(float(s["closed_pod_hours"]) for s in compute["stages"])
return {"gpu_hours": hours, "board_watts": BOARD_WATTS, "kwh": hours * BOARD_WATTS / 1000}


def record_stop(args: Any, stop: BaseException) -> None:
"""Append one stop to ``<out-dir>/stops.jsonl`` (``run_arms.py`` calls it on exit code 5)."""
folder = Path(args.out_dir)
folder.mkdir(parents=True, exist_ok=True)
line = {
"kind": getattr(stop, "kind", "rate_limit"),
"stage": args.stage,
"dataset": args.dataset,
"setup": getattr(args, "setup", None) or getattr(args, "index", None),
"message": str(stop),
"at": datetime.now(UTC).isoformat(),
}
with (folder / "stops.jsonl").open("a", encoding="utf-8") as handle:
handle.write(json.dumps(line, ensure_ascii=False) + "\n")


def stops(out: Path) -> list[dict[str, Any]]:
"""Return every rate-limit and ``out_of_credit`` stop the runner saved."""
return read_rows(out / "stops.jsonl")


def returned_models(out: Path) -> dict[str, Any] | str:
"""Return the returned-model counts per role from ``join.json``, else "not defined"."""
path = out / "join.json"
if not path.is_file():
return NOT_DEFINED
return json.loads(path.read_text(encoding="utf-8")).get("returned_model", NOT_DEFINED)
Original file line number Diff line number Diff line change
Expand Up @@ -419,7 +419,7 @@ The word "sealed" applies to indexes only. Half B is held out from every selecti
## 17. Budget, ceiling, stop rule and drop order

- **Estimate (amended 2026-11-25, pre-freeze, owner approval).** **$1,122**: RunPod GPU (RTX 4090) $410; OpenRouter answers (DeepSeek V4.1 Flash) $180; OpenRouter Ragas judge and claim sorter (gpt-oss-120b) $142; GLM-5.3 claim checks (Z.ai API) $390. The old $730 assumed GLM-5.3 claim checks at no cost; they now run on the paid API. The RunPod line rests on P2 timing (pod `q2pr74unxye0mj`, 2026-11-25): one full FreshStack index (`e8b-c512`, 49,506 files) took 5.65 h; 2,747-file samples gave 0.20 to 0.31 s per file. The nine FreshStack indexes plus the `e4b-c1024` rebuild project to about 45 pod hours (about $40), with each sample rate scaled by 1.33, the full-to-sample ratio measured on `e8b-c512` before the compaction fix `784e478c`. With that fix the build should be faster (not yet measured on a pod), so the figure is conservative. These builds ran with file-type routing on (amendment A13). With routing off, the 600-file check gives 6.1% fewer chunks and 0.4% fewer embedded tokens, so the figure still holds as an upper bound.
- **Ceiling (amended 2026-11-25).** **$1,716** (was $975), pods and hosted calls together: the estimate plus $594 reserve (RunPod reserve for 3 times slower reranking $230; RunPod repeat runs, 10%, $64; price changes, about 10%, $150; failed calls rerun, 10%, $150). RunPod share $704; hosted share $1,012. The OpenRouter key carries a credit limit for the OpenRouter roles only (amended 2026-11-26, pre-freeze, owner; `plan.json` amendment A15): the hosted share $1,012 minus the $390 GLM-5.3 line, **$622**, so an OpenRouter overrun ends in a clean `out_of_credit` stop. GLM-5.3 runs on the owner's Z.ai API key, outside that limit; each run records its GLM-5.3 calls and tokens, and the budget checks count them. The Z.ai endpoint is pinned by SHA-256 and is never printed. The checks, run guard, drop order and stop rule are unchanged (`plan.json` amendment A8).
- **Ceiling (amended 2026-11-25).** **$1,716** (was $975), pods and hosted calls together: the estimate plus $594 reserve (RunPod reserve for 3 times slower reranking $230; RunPod repeat runs, 10%, $64; price changes, about 10%, $150; failed calls rerun, 10%, $150). RunPod share $704; hosted share $1,012. The OpenRouter key carries a credit limit for the OpenRouter roles only (amended 2026-11-26, pre-freeze, owner; `plan.json` amendment A15): the hosted share $1,012 minus the $390 GLM-5.3 line, **$622**, so an OpenRouter overrun ends in a clean `out_of_credit` stop. GLM-5.3 runs on the owner's Z.ai API key, outside that limit; each run records its GLM-5.3 calls, the Z.ai billing export gives their tokens and cost, and the budget checks count them. The Z.ai endpoint is pinned by SHA-256 and is never printed. The checks, run guard, drop order and stop rule are unchanged (`plan.json` amendment A8).
- **Checks**: before the freeze (test pod extrapolation), on the build pods after the search stage, and at each stage end while the replicate pods run. Each projection uses billing and measured rates only, never scores. Money spent is the sum of the `usd` values of the provider billing rows, each row given as `{provider, usd}`. A projection reaches the ceiling when it is $1,716 or more (amended 2026-11-25; was $975). A budget tool writes each projection to `budget-check.json` and each applied drop step to `drops.json`. The join of stage outputs, the label sampler and the report read the drop record.
- **Run guard.** A main stage refuses to start while `plan.json` `frozen` is empty, and refuses a dirty tree. A pre-freeze run needs an explicit flag. Like every run, it appends one line to `output/run-records.jsonl` (the repository rule), and that line carries `prefreeze: true`. A smoke run (a run with named questions, `--qids`) also appends one line, and that line carries `smoke: true`. The main join and every main-run check ignore lines with either field. A smoke join counts a `smoke: true` line as its run's record. Each run record holds the SHA-256 of this file. Every stage key and every done-marker also hold the run mode (`main`, `prefreeze` or `smoke`). A `--resume` with another run mode than the saved key refuses with exit code 2, so a main run never accepts a pre-freeze or smoke row as done. Every stage that reads an index (search, answer and judge) checks, before its first query, that the index's ingest done-marker holds the configuration its own key expects: the settings of `<index>-roff-hon` with no answer host and no judge. A difference stops the stage with exit code 2 and names each field. A main run also requires an index built by a main run. The oracle stage does not search, so it does not check the index.
- **Drop order at the ceiling** (results-blind, applied in order, each step recorded with the projection that triggered it): (1) Legal RAG Bench answer generation; (2) the length-controlled check; (3) the closed-book run with the RAG prompt; then stop. The owner approved this order on 2026-11-14. Step 1 also removes the 50 Legal correctness labels (section 11.2: correctness sample 150, L1 700, L2 700 in the full plan, 315 at the staged first stage or 630 under the A18 plan). After drop step 1 is recorded, the answer stage on Legal RAG Bench sends nothing, writes no file and exits with code 0; the analysis writes the Legal answer rows 12 to 19 as `dropped` and still computes the Legal search rows 1 to 11. Without a drop record, a dataset with no answers stops the analysis. E1 is not in this order: it has its own ceiling (P16). No confirmatory item is dropped by choice. If the closed-book RAG-prompt run is dropped, the contamination sensitivity (section 13) uses the own-knowledge closed-book run alone, and the report says so.
Expand Down Expand Up @@ -491,7 +491,7 @@ After the freeze, every change is a dated, numbered deviation. The report lists
- Counts per setup and dataset of chunks with no page label and of unmapped chunks (placeholder units, section 6), and the count of fenced rows per file extension in the FreshStack export (section 4).
- Per question and answer setup, the cut total and the realised evidence token total (section 3), with the share of questions where the assembled evidence is shorter than the cut total.
- Sensitivity tables: GEE against permutation disagreements; FinanceBench nDCG@10 for rows 9 and 10 (a chunk covers its page), with sign agreement per row against `evidence_recall_20k` (H6); FreshStack `evidence_recall_20k` for rows 9 to 11, descriptive; the four H7 corner-cell means with 95% intervals beside row 11; missing-outcome bounds; closed-book subset; length-controlled check; H8b on questions with a cut total of at least 95% of the token budget in all three `-t20k` setups, with both token totals (cut and realised) per setup; faithfulness with uncited factual segments as unsupported, beside the uncited-segment share.
- **Compute table**: GPU type, pod hours per stage including every pre-freeze pod (test pod, GPU timing, smoke runs), hosted tokens and cost per role, an energy estimate (GPU hours times board power; Strubell et al. 2019; Lacoste et al. 2019), `resent_calls` (harness-level resends only, section 12), calls closed as missing after the resend cap, error rows per stage and role, and every `out_of_credit` stop.
- **Compute table**: GPU type, pod hours per stage including every pre-freeze pod (test pod, GPU timing, smoke runs), hosted tokens and cost per role (answer, Ragas and claim-classifier calls from the saved rows, billed failed attempts included; GLM-5.3 calls from the Z.ai billing export, because those calls save no token counts and GLM-5.3 is the only Z.ai role), an energy estimate (GPU hours times board power; Strubell et al. 2019; Lacoste et al. 2019), `resent_calls` (harness-level resends only, section 12), calls closed as missing after the resend cap, error rows per stage and role, and every `out_of_credit` stop.
- Model labeller agreement per set beside the checker and judge agreements (section 11.3; descriptive).
- A18 additions: classifier development rounds 1 and 2 in full (section 11.1); all-claims faithfulness beside the primary measure (section 11.1); the pooled H8 estimate beside both per-dataset estimates (section 9 point 7); the relevance audit tables (section 11.3).
- Returned model ID and provider per hosted call, with the count of differences from the requested values.
Expand Down
Loading
Loading