File size: 11,178 Bytes
0c1817e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 | #!/usr/bin/env python3
"""Build deterministic, provenance-bound router training records without sealed-eval leakage."""
from __future__ import annotations
import argparse
from collections import defaultdict
from datetime import datetime, timezone
import hashlib
import json
from pathlib import Path
from typing import Any
ROOT = Path(__file__).resolve().parents[2]
REASONING = ROOT / "downloads/datasets/_acquisition/fable-reasoning-440267f/Fable-5-Distill-5500x.jsonl"
CODING = ROOT / "downloads/datasets/_acquisition/fable-agent-coding-c63e82a/data"
TOKENIZER = ROOT / "downloads/models/_acquisition/lfm25-fable5-72d68fc/tokenizer.json"
CONTRACT = ROOT / "config/benching/fable-router-curriculum.v2.json"
def sha256(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as handle:
for block in iter(lambda: handle.read(1024 * 1024), b""):
digest.update(block)
return digest.hexdigest()
def identity(text: str) -> str:
return hashlib.sha256(text.strip().encode("utf-8")).hexdigest()
def stable_split(value: str) -> str:
bucket = int(hashlib.sha256(value.encode("utf-8")).hexdigest()[:8], 16) % 1000
return "train" if bucket < 900 else "validation" if bucket < 950 else "test"
def flattened_message_text(messages: list[dict[str, Any]]) -> str:
chunks: list[str] = []
for message in messages:
chunks.extend([str(message.get("role") or ""), str(message.get("reasoning_content") or ""),
str(message.get("content") or "")])
for call in message.get("tool_calls") or []:
function = call.get("function") or {}
chunks.extend([str(function.get("name") or ""), str(function.get("arguments") or "")])
return "\n".join(chunks)
def token_count(tokenizer: Any, text: str) -> int:
return len(tokenizer.encode(text).ids)
def choose_shortest(rows: list[dict[str, str]], tokenizer: Any, maximum: int) -> tuple[dict[str, str] | None, int]:
candidates = []
for row in rows:
if not all((row.get(key) or "").strip() for key in ("prompt", "reasoning", "answer")):
continue
count = token_count(tokenizer, "\n".join([row["prompt"], row["reasoning"], row["answer"]]))
if count <= maximum:
candidates.append((count, len(row["reasoning"]) + len(row["answer"]), row))
if not candidates:
return None, 0
count, _, selected = min(candidates, key=lambda item: (item[0], item[1], identity(item[2]["answer"])))
return selected, count
def target_message(row: dict[str, Any]) -> dict[str, Any]:
messages = row.get("messages") or []
if not messages or messages[-1].get("role") != "assistant":
raise ValueError("cumulative prefix does not end in an assistant target")
return messages[-1]
def has_tool_target(row: dict[str, Any]) -> bool:
return bool(target_message(row).get("tool_calls"))
def select_historical_prefixes(rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
ordered = sorted(rows, key=lambda row: (int(row["assistant_step"]), int(row["target_message_index"])))
selected = []
first_tool = next((row for row in ordered if has_tool_target(row)), None)
if first_tool is not None:
selected.append(first_tool)
if not selected or selected[-1] is not ordered[-1]:
selected.append(ordered[-1])
return selected
def rejected_target(target: dict[str, Any]) -> tuple[str, dict[str, Any]] | None:
calls = target.get("tool_calls") or []
if calls:
rejected = dict(target)
rejected["tool_calls"] = calls + calls
return "duplicate_tool_call", rejected
content = str(target.get("content") or "").strip()
reasoning = str(target.get("reasoning_content") or "").strip()
if not content and not reasoning:
return None
rejected = dict(target)
if content:
rejected["content"] = content + "\n\n" + content
else:
rejected["reasoning_content"] = reasoning + "\n\n" + reasoning
return "repeated_completion", rejected
def write_jsonl(path: Path, rows: list[dict[str, Any]]) -> None:
with path.open("w", encoding="utf-8", newline="\n") as handle:
for row in rows:
handle.write(json.dumps(row, ensure_ascii=False, separators=(",", ":")) + "\n")
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--output-root", type=Path)
parser.add_argument("--maximum-tokens-before-template", type=int, default=1900)
args = parser.parse_args()
if not 256 <= args.maximum_tokens_before_template <= 2048:
raise SystemExit("maximum token count must be between 256 and 2048")
from tokenizers import Tokenizer
try:
import polars as pl
except ImportError as exc:
raise SystemExit("polars is required") from exc
tokenizer = Tokenizer.from_file(str(TOKENIZER))
stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
output = (args.output_root or ROOT / "downloads/audits" / f"fable-router-curriculum-data-{stamp}").resolve()
output.mkdir(parents=True, exist_ok=False)
sft: dict[str, list[dict[str, Any]]] = defaultdict(list)
preferences: list[dict[str, Any]] = []
excluded = defaultdict(int)
reasoning_groups: dict[str, list[dict[str, str]]] = defaultdict(list)
with REASONING.open("r", encoding="utf-8") as handle:
for line in handle:
row = json.loads(line)
reasoning_groups[identity(row.get("prompt") or "")].append(row)
for prompt_id, rows in sorted(reasoning_groups.items()):
chosen, tokens = choose_shortest(rows, tokenizer, args.maximum_tokens_before_template)
if chosen is None:
excluded["reasoning_empty_or_overflow"] += 1
continue
split = stable_split(prompt_id)
sft[split].append({
"schema": "AutonomaFableRouterRecord.v2", "id": f"reasoning:{prompt_id}", "split": split,
"lane": "host_preservation", "routerEligibility": "preserve", "lossPolicyKey": "host_preservation",
"messages": [{"role": "user", "content": chosen["prompt"]},
{"role": "assistant", "reasoning_content": chosen["reasoning"], "content": chosen["answer"]}],
"tokensBeforeTemplate": tokens,
"source": {"repo": "HelioAI/Claude-Fable-5-5500x", "revision": "440267fbdb1b00a40216e7233dbce25530a0ed09",
"promptSha256": prompt_id, "duplicateCandidates": len(rows)}
})
frames = [pl.read_parquet(path) for path in sorted(CODING.glob("*.parquet"))]
grouped: dict[str, list[dict[str, Any]]] = defaultdict(list)
for row in pl.concat(frames, how="vertical_relaxed").to_dicts():
grouped[str(row["source_trajectory_sha256"])].append(row)
for trajectory_id, rows in sorted(grouped.items()):
attested = [row for row in rows if row.get("model_attested") and str(row.get("verifier") or "").strip()]
chosen_rows = sorted(attested, key=lambda row: int(row["assistant_step"])) if attested else select_historical_prefixes(rows)
lane = "verified_expert" if attested else "interaction_pattern"
eligibility = "expert" if attested else "conditional"
for row in chosen_rows:
messages = row.get("messages") or []
tokens = token_count(tokenizer, flattened_message_text(messages))
if tokens > args.maximum_tokens_before_template:
excluded[f"{lane}_overflow"] += 1
continue
split = stable_split(trajectory_id)
record_id = f"agent:{trajectory_id}:{int(row['assistant_step'])}"
sft[split].append({
"schema": "AutonomaFableRouterRecord.v2", "id": record_id, "split": split,
"lane": lane, "routerEligibility": eligibility, "lossPolicyKey": lane, "messages": messages,
"tokensBeforeTemplate": tokens,
"target": {"assistantStep": int(row["assistant_step"]), "toolCall": has_tool_target(row),
"terminal": not has_tool_target(row)},
"source": {"repo": "greghavens/fable-5-coding-and-debugging-traces",
"revision": "c63e82adec30798edcbd6e1dcb0014d2b15de236",
"trajectorySha256": trajectory_id, "task": row.get("task"), "verifier": row.get("verifier"),
"modelAttested": bool(row.get("model_attested")), "derivation": row.get("derivation")}
})
if split == "train":
negative = rejected_target(target_message(row))
if negative:
kind, rejected = negative
preferences.append({
"schema": "AutonomaFableRouterPreference.v2", "id": record_id + ":" + kind,
"split": "train", "lane": "loop_negative", "routerEligibility": eligibility,
"lossPolicyKey": "loop_negative", "context": messages[:-1], "chosen": messages[-1],
"rejected": rejected, "negativeType": kind, "sourceRecordId": record_id
})
files = []
for split in ("train", "validation", "test"):
rows = sorted(sft[split], key=lambda row: row["id"])
path = output / f"sft-{split}.jsonl"
write_jsonl(path, rows)
files.append({"path": path.name, "rows": len(rows), "bytes": path.stat().st_size, "sha256": sha256(path),
"lanes": {lane: sum(row["lane"] == lane for row in rows) for lane in sorted({r["lane"] for r in rows})}})
preference_path = output / "preference-train.jsonl"
write_jsonl(preference_path, sorted(preferences, key=lambda row: row["id"]))
files.append({"path": preference_path.name, "rows": len(preferences), "bytes": preference_path.stat().st_size,
"sha256": sha256(preference_path),
"negativeTypes": {kind: sum(row["negativeType"] == kind for row in preferences)
for kind in sorted({r["negativeType"] for r in preferences})}})
result = {
"schema": "AutonomaFableRouterCurriculumBuild.v2", "status": "curriculum_built_nonrouting",
"nonRouting": True, "trainingAuthorized": False, "createdAt": datetime.now(timezone.utc).isoformat(),
"contract": {"path": str(CONTRACT), "sha256": sha256(CONTRACT)},
"sources": [{"path": str(REASONING), "sha256": sha256(REASONING)},
{"path": str(TOKENIZER), "sha256": sha256(TOKENIZER)},
{"path": str(CODING.parent / "dataset-manifest.json"),
"sha256": sha256(CODING.parent / "dataset-manifest.json")}],
"maximumTokensBeforeTemplate": args.maximum_tokens_before_template,
"finalTrainerRetokenizationRequired": True, "files": files, "excluded": dict(sorted(excluded.items())),
"frozenEvaluationRead": False
}
result_path = output / "result.json"
result_path.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8")
print(result_path)
return 0
if __name__ == "__main__":
raise SystemExit(main())
|