Datasets:
File size: 9,799 Bytes
e1ced61 | 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 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 | """``explicit-c2`` — independent dual-compile of a candidate (``docs/02`` §7).
The one implemented subcommand, ``dual-compile``, runs the C2 compiler over a
single candidate described by a JSON file: it builds the two pinned model
clients (proposer = Qwen3.5-9B, verifier = Gemma-4-12B-it) from the resource
manifest, sends the §7.1 independent request to each, and reconciles their
outputs through the §7.2/§7.3 gate. The two ``compiled_program`` records and the
:class:`C2Outcome` are written to ``--output``.
Model calls go through the real :class:`HfModelClient`, which is **gated and
never fakes a response**: when a pinned snapshot is absent, LFS-pointer-only,
or the accelerator/``transformers`` stack is missing, it raises
:class:`ModelUnavailable`. The CLI surfaces that as exit code ``2`` with a
``BLOCKED`` notice — the candidate is skipped, never substituted (runbook:
blocked → skip, never replace). A successful dual-compile exits ``0``; a bad
candidate/config exits ``1``.
Candidate sourcing at scale (selecting ChartQA-H / MMK12 / MMR1-RL / MMMU rows
and building their worlds) is the P11 assembler; this driver consumes one
candidate from disk so the gate is exercisable end-to-end before P11 lands.
"""
from __future__ import annotations
import argparse
import json
import sys
from pathlib import Path
from typing import Any
from ..c2 import C2Candidate, C2Compiler, ModelUnavailable
from ..c2.client import HfModelClient
from ..config import ConfigError, load_resources
from ..hashing import choices_sha256, question_sha256
from ..paths import repo_root
from ..resources import plan
from ._stub import dispatch
_PROG = "explicit-c2"
_SUBCOMMANDS = {
"dual-compile": "Run the §7 independent dual-compile over one candidate (P4).",
}
# Roles pinned in ``configs/resources.yaml`` (ADR-0002).
_PROPOSER_ROLE = "program_proposer"
_VERIFIER_ROLE = "independent_program_verifier"
def _utc_now() -> str:
from datetime import UTC, datetime
return datetime.now(tz=UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
def _load_resources(path: Path) -> Any:
try:
return load_resources(path)
except (ConfigError, FileNotFoundError) as exc:
print(f"{_PROG} dual-compile: resources load failed: {exc}", file=sys.stderr)
raise _Handled(1) from exc
class _Handled(Exception):
"""Internal signal that a nonzero exit has already been printed."""
def __init__(self, code: int) -> None:
super().__init__()
self.code = code
def _model_client(resources: Any, role: str, resources_path: Path) -> HfModelClient:
"""Build the :class:`HfModelClient` for the manifest entry with ``role``.
Raises :class:`_Handled(1)` if no entry (or more than one) carries the role.
"""
matches = [ref for ref in plan(resources) if ref.kind == "model" and ref.role == role]
if not matches:
disabled_role = f"disabled_future_c2_{role}"
disabled = [
entry
for entry in resources.models.values()
if getattr(entry, "role", None) == disabled_role
]
if disabled:
print(
f"{_PROG} dual-compile: BLOCKED — {role!r} is disabled for the v1 release",
file=sys.stderr,
)
raise _Handled(2)
print(
f"{_PROG} dual-compile: no model with role {role!r} in {resources_path}",
file=sys.stderr,
)
raise _Handled(1)
if len(matches) > 1:
print(
f"{_PROG} dual-compile: multiple models with role {role!r}; expected exactly one",
file=sys.stderr,
)
raise _Handled(1)
ref = matches[0]
return HfModelClient(
logical_name=ref.logical_name,
repo_id=ref.repo_id,
revision=ref.revision,
local_path=ref.local_path,
)
def _load_candidate(path: Path) -> C2Candidate:
"""Parse a candidate JSON file into a :class:`C2Candidate`.
The file carries ``base_id``, ``dsl``, ``question_text``, ``choices``
(``[{key, text}, ...]``), ``image_sha256``, and ``world``. The question/
choices hashes are computed from the text when not supplied, so the caller
cannot accidentally desync them.
"""
try:
raw = json.loads(path.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError) as exc:
print(f"{_PROG} dual-compile: cannot read candidate {path}: {exc}", file=sys.stderr)
raise _Handled(1) from exc
if not isinstance(raw, dict):
print(f"{_PROG} dual-compile: candidate must be a JSON object: {path}", file=sys.stderr)
raise _Handled(1)
base_id = raw.get("base_id")
dsl = raw.get("dsl")
question_text = raw.get("question_text")
choices_raw = raw.get("choices")
world = raw.get("world")
if not (isinstance(base_id, str) and isinstance(dsl, str) and isinstance(question_text, str)):
print(
f"{_PROG} dual-compile: candidate needs string base_id, dsl, question_text: {path}",
file=sys.stderr,
)
raise _Handled(1)
if dsl not in ("plotqa_dsl_v1", "geometry_dsl_v1", "table_dsl_v1"):
print(f"{_PROG} dual-compile: unknown dsl {dsl!r}: {path}", file=sys.stderr)
raise _Handled(1)
if not isinstance(choices_raw, list) or not isinstance(world, dict):
print(
f"{_PROG} dual-compile: candidate needs list 'choices' and object 'world': {path}",
file=sys.stderr,
)
raise _Handled(1)
choices: tuple[tuple[str, str], ...] = tuple(
(str(c["key"]), str(c["text"])) for c in choices_raw
)
q_sha = raw.get("question_sha256") or question_sha256(question_text)
c_sha = raw.get("choices_sha256") or choices_sha256([{"key": k, "text": t} for k, t in choices])
return C2Candidate(
base_id=base_id,
dsl=dsl, # type: ignore[arg-type]
question_sha256=q_sha,
choices_sha256=c_sha,
question_text=question_text,
choices=choices,
image_sha256=str(raw.get("image_sha256", "")),
world=world,
)
def _outcome_to_json(outcome: Any) -> dict[str, Any]:
"""Serialize a :class:`C2Outcome` to a JSON-safe dict."""
return {
"state": outcome.state,
"accepted": outcome.accepted,
"reason": outcome.reason,
"canonical_hash_proposer": outcome.canonical_hash_proposer,
"canonical_hash_verifier": outcome.canonical_hash_verifier,
"full_answer_proposer": list(outcome.full_answer_proposer)
if outcome.full_answer_proposer is not None
else None,
"full_answer_verifier": list(outcome.full_answer_verifier)
if outcome.full_answer_verifier is not None
else None,
"mutation_evidence": [
{
"leaf": e.leaf,
"kind": e.kind,
"description": e.description,
"proposer_status": e.proposer_status,
"proposer_answer": e.proposer_answer,
"verifier_status": e.verifier_status,
"verifier_answer": e.verifier_answer,
"agree": e.agree,
}
for e in outcome.mutation_evidence
],
"proposer_record": outcome.proposer_record,
"verifier_record": outcome.verifier_record,
}
def cmd_dual_compile(argv: list[str]) -> int:
parser = argparse.ArgumentParser(prog=f"{_PROG} dual-compile")
parser.add_argument(
"--candidate", type=Path, required=True, help="candidate JSON file (§7.1 evidence)."
)
parser.add_argument(
"--resources",
type=Path,
default=repo_root() / "configs" / "resources.yaml",
)
parser.add_argument("--output", type=Path, required=True, help="output JSON path.")
parser.add_argument("--seed", type=int, default=0, help="deterministic mutation-suite seed.")
args = parser.parse_args(argv)
try:
resources = _load_resources(args.resources)
candidate = _load_candidate(args.candidate)
proposer = _model_client(resources, _PROPOSER_ROLE, args.resources)
verifier = _model_client(resources, _VERIFIER_ROLE, args.resources)
except _Handled as exc:
return exc.code
compiler = C2Compiler(proposer=proposer, verifier=verifier)
try:
outcome = compiler.compile(candidate, seed=args.seed)
except ModelUnavailable as exc:
# Blocked → skip, never substitute (runbook). Surface as exit 2, not a
# faked success and not a silent empty output.
print(f"{_PROG} dual-compile: BLOCKED — model unavailable: {exc}", file=sys.stderr)
return 2
payload = {
"schema_version": 1,
"produced_at": _utc_now(),
"candidate_base_id": candidate.base_id,
"seed": args.seed,
"outcome": _outcome_to_json(outcome),
}
args.output.parent.mkdir(parents=True, exist_ok=True)
args.output.write_text(json.dumps(payload, indent=2, sort_keys=True), encoding="utf-8")
print(
json.dumps(
{"state": outcome.state, "accepted": outcome.accepted, "output": str(args.output)},
sort_keys=True,
)
)
return 0
_IMPLEMENTATIONS = {
"dual-compile": cmd_dual_compile,
}
def main(argv: list[str] | None = None) -> int:
# When invoked as a console entry point, ``argv`` is ``None`` and the real
# arguments live on ``sys.argv``. Fall back to those (rather than the empty
# list the stub dispatcher treats as "no subcommand") so the ``explicit-c2``
# script is genuinely usable — never a faked success.
if argv is None:
argv = sys.argv[1:]
return dispatch(_PROG, argv, _SUBCOMMANDS, _IMPLEMENTATIONS)
if __name__ == "__main__":
raise SystemExit(main())
|