Datasets:
Download src/explicit_learning/c2/request.py from sungguk/visual-answerability: direct link, hf CLI and curl.
- Browser
- Download file 7.4 kB
-
https://huggingface.co/datasets/sungguk/visual-answerability/resolve/main/src/explicit_learning/c2/request.py
- Command line
-
hf download hf://datasets/sungguk/visual-answerability/src/explicit_learning/c2/request.py
-
curl -L -o request.py https://huggingface.co/datasets/sungguk/visual-answerability/resolve/main/src/explicit_learning/c2/request.py
7.4 kB
| """C2 compile request construction (``docs/02`` §7.1). | |
| A C2 compile request is sent *independently* to each model. §7.1 fixes what it | |
| carries and — just as importantly — what it hides: | |
| * **sends** — the *untransformed* image (by content hash; bytes travel | |
| out-of-band to the model client), the raw question + choices, the source | |
| structured table / recognized formal candidates when present, the DSL | |
| grammar, and the ``astNode`` JSON schema the response must match. | |
| * **hides** — the other model's output, the intended intervention / state, and | |
| any candidate *transformed* image. The two models must compile from the same | |
| untouched evidence; neither sees what the other produced or what the | |
| intervention layer plans to do. | |
| ``request_sha256`` is the canonical-JSON hash of the payload, the idempotency key | |
| for response caching and the field recorded on the ``compiled_program`` record. | |
| """ | |
| from __future__ import annotations | |
| from dataclasses import dataclass | |
| from typing import Any | |
| from ..dsl.ast import Dsl | |
| from ..dsl.typecheck import signatures | |
| from ..hashing import canonical_json_hash | |
| from ..sources.base import World | |
| # Fields the request payload is *forbidden* to carry (§7.1 hiding rule). The | |
| # builder asserts none are present so a future caller cannot leak the | |
| # intervention or a sibling model's output into an independent request. | |
| _FORBIDDEN_PAYLOAD_KEYS = frozenset( | |
| { | |
| "intended_state", | |
| "intended_intervention", | |
| "operator_name", | |
| "proposer_output", | |
| "verifier_output", | |
| "other_model_output", | |
| "transformed_image_sha256", | |
| "transformed_image", | |
| "candidate_transformed_image", | |
| "original_answer", | |
| } | |
| ) | |
| class C2Candidate: | |
| """One C2-eligible item presented to both compilers. | |
| C2 applies only to ChartQA-H / MMK12 / MMR1-RL / MMMU candidates (§7); the | |
| assembler (P11) selects them, not the compiler. ``world`` carries the source | |
| structured table / formal candidates when available (§7.1 "source structured | |
| table / recognized formal candidates가 있으면 그것"); it may be empty for | |
| image-only candidates, in which case the models compile from the image alone. | |
| """ | |
| base_id: str | |
| dsl: Dsl | |
| question_sha256: str | |
| choices_sha256: str | |
| question_text: str | |
| choices: tuple[tuple[str, str], ...] # (key, text) pairs | |
| image_sha256: str | |
| world: World | |
| class CompileRequest: | |
| """The independent, §7.1-compliant compile request for one model.""" | |
| base_id: str | |
| dsl: Dsl | |
| request_sha256: str | |
| payload: dict[str, Any] | |
| prompt: str | |
| image_sha256: str = "" | |
| def to_dict(self) -> dict[str, Any]: | |
| return { | |
| "base_id": self.base_id, | |
| "dsl": self.dsl, | |
| "request_sha256": self.request_sha256, | |
| "image_sha256": self.image_sha256, | |
| "payload": self.payload, | |
| } | |
| def _grammar(dsl: Dsl) -> list[dict[str, Any]]: | |
| """A deterministic, JSON-serializable summary of the DSL operator table.""" | |
| out: list[dict[str, Any]] = [] | |
| for op, sig in sorted(signatures(dsl).items()): | |
| out.append( | |
| { | |
| "op": op, | |
| "arg_types": list(sig.arg_types), | |
| "return_type": sig.return_type, | |
| "commutative": sig.commutative, | |
| "selector_kind": sig.selector_kind, | |
| "variadic": sig.variadic, | |
| } | |
| ) | |
| return out | |
| def _ast_node_schema_ref() -> dict[str, Any]: | |
| """A compact pointer to the response schema (the model emits an ``astNode``).""" | |
| return { | |
| "$ref": "schemas/compiled_program.schema.json#/$defs/astNode", | |
| "shape": { | |
| "op": "string", | |
| "args": "array of astNode | string | number | boolean", | |
| "return_type": "string (optional)", | |
| }, | |
| } | |
| def _world_candidates(world: World) -> dict[str, Any] | None: | |
| """The structured evidence §7.1 permits sending, pruned to serializable form. | |
| Only the data-bearing slices a program references are sent (series/points, | |
| table rows/cells, geometry entities/constraints) — never the rendered image | |
| bytes, and never any intervention metadata. Returns ``None`` for an empty | |
| world so image-only candidates carry no ``world_candidates`` key. | |
| """ | |
| slices: dict[str, Any] = {} | |
| for key in ("series", "rows", "entities", "constraints"): | |
| value = world.get(key) | |
| if value: | |
| slices[key] = value | |
| return slices or None | |
| def build_compile_request(candidate: C2Candidate) -> CompileRequest: | |
| """Assemble the §7.1 independent compile request for ``candidate``. | |
| The payload carries the DSL, grammar, astNode schema ref, question, choices, | |
| image content hash, and (when present) the source structured candidates. It | |
| never carries an intervention, a transformed image, or another model's output. | |
| """ | |
| candidates = _world_candidates(candidate.world) | |
| payload: dict[str, Any] = { | |
| "dsl": candidate.dsl, | |
| "grammar": _grammar(candidate.dsl), | |
| "ast_node_schema": _ast_node_schema_ref(), | |
| "question": candidate.question_text, | |
| "choices": [{"key": k, "text": t} for k, t in candidate.choices], | |
| "image_sha256": candidate.image_sha256, | |
| "base_id": candidate.base_id, | |
| } | |
| if candidates is not None: | |
| payload["world_candidates"] = candidates | |
| leaked = _FORBIDDEN_PAYLOAD_KEYS & payload.keys() | |
| if leaked: | |
| raise AssertionError(f"§7.1 leak in compile request payload: {sorted(leaked)!r}") | |
| request_sha = canonical_json_hash(payload) | |
| prompt = _render_prompt(payload) | |
| return CompileRequest( | |
| base_id=candidate.base_id, | |
| dsl=candidate.dsl, | |
| request_sha256=request_sha, | |
| payload=payload, | |
| prompt=prompt, | |
| image_sha256=candidate.image_sha256, | |
| ) | |
| def _render_prompt(payload: dict[str, Any]) -> str: | |
| """The natural-language prompt wrapping the JSON payload for the model. | |
| The model is instructed to emit *only* a JSON object with the program | |
| envelope subset (``dsl`` / ``program`` / ``referent_selector`` / | |
| ``required_referent_cardinality``) conforming to ``$defs/astNode``. The | |
| payload is embedded verbatim; the prompt itself is deterministic and | |
| hash-stable so ``request_sha256`` (over the payload) is the canonical key. | |
| """ | |
| grammar = payload["grammar"] | |
| ops = ", ".join(f"{g['op']}/{g['return_type']}" for g in grammar) | |
| return ( | |
| "You are an independent program compiler. Compile a single deterministic " | |
| "question program for the question below using ONLY the given DSL grammar. " | |
| f"DSL={payload['dsl']}. Operators: {ops}. " | |
| "Emit ONLY a JSON object: " | |
| '{"dsl": "<dsl>", "program": <astNode>, ' | |
| '"referent_selector": <astNode|null>, ' | |
| '"required_referent_cardinality": <int|null>}. ' | |
| "An astNode is {op: string, args: [astNode|string|number|boolean], " | |
| "return_type?: string}. Do not include explanations. " | |
| f"Payload={_compact_json(payload)}" | |
| ) | |
| def _compact_json(obj: Any) -> str: | |
| import json | |
| return json.dumps(obj, sort_keys=True, ensure_ascii=False, separators=(",", ":")) | |
| __all__ = ["C2Candidate", "CompileRequest", "build_compile_request"] | |