File size: 6,099 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
"""Synthetic CPU-only contract smoke that explicitly performs no training."""

from __future__ import annotations

import math
from typing import Any

from ..hashing import sha256_text
from .data import AdmissionRequest, admit_group
from .ledger import CompletionTokenLedger, completion_id
from .rewards import ALL_ARMS, RewardWeights, plan_all_arms, score_completion
from .slots import build_comparison_slots, comparison_slot_manifest_sha256


def _synthetic_group() -> dict[str, Any]:
    question = "Which option is supported by the visible diagram?"
    question_sha = sha256_text(question)
    choices = [{"key": "A", "text": "10"}, {"key": "B", "text": "20"}]
    choices_sha = sha256_text('[{"key":"A","text":"10"},{"key":"B","text":"20"}]')

    def view(
        view_id: str,
        role: str,
        state: str,
        operator: str,
        target: str,
    ) -> dict[str, Any]:
        certificate_id = sha256_text(f"certificate:{view_id}")
        return {
            "view_id": view_id,
            "role": role,
            "state": state,
            "operator": operator,
            "images": [
                {
                    "image_index": 0,
                    "path": f"synthetic/{view_id}.png",
                    "sha256": sha256_text(f"image:{view_id}"),
                    "width": 32,
                    "height": 32,
                }
            ],
            "question_sha256": question_sha,
            "choices_sha256": choices_sha,
            "target_raw": target,
            "target_canonical": target,
            "regions": [],
            "render_manifest_sha256": sha256_text(f"render:{view_id}"),
            "certificate_id": certificate_id,
            "certification_tier": "C1_SOURCE_NATIVE",
            "automated_audit": {
                "proposer_label_id": None,
                "verifier_label_id": None,
                "certificate_id": certificate_id,
                "reconciliation": "executor_certificate_confirmed",
            },
        }

    return {
        "schema_version": 2,
        "group_id": sha256_text("offline-group"),
        "base_id": sha256_text("offline-base"),
        "source": "offline_fixture",
        "source_revision": "0" * 40,
        "source_native_id": "offline-1",
        "split": "train",
        "subject": "contract",
        "question": question,
        "question_sha256": question_sha,
        "choices": choices,
        "choices_sha256": choices_sha,
        "full_answer_raw": "A",
        "full_answer_canonical": "A",
        "answer_type": "multiple_choice",
        "views": [
            view("full", "POSITIVE", "FULL", "NONE", "A"),
            view("control", "CONTROL", "A_SAME", "CONTROL_MATCHED_V1", "A"),
            view(
                "missing",
                "TARGET_EVIDENCE",
                "U_MISSING",
                "REDACT_SOLID_V1",
                "<UNANSWERABLE>",
            ),
            view(
                "invalid",
                "TARGET_REFERENT",
                "U_INVALID",
                "CLEAN_DELETE_V1",
                "<UNANSWERABLE>",
            ),
            view("changed", "SUBSTITUTE", "A_CHANGED", "SUBSTITUTE_V1", "B"),
        ],
    }


def offline_contract_smoke(
    *,
    steps_per_arm: int = 2,
    seed: int = 20260728,
    token_cap: int = 1024,
) -> dict[str, Any]:
    """Exercise admissions, slots, all rewards, and the ledger on CPU.

    The returned record always states ``trained=false``.  It is a contract test,
    not a proxy training run or a performance claim.
    """

    if steps_per_arm <= 0:
        raise ValueError("steps_per_arm must be positive")
    callback_kinds: list[str] = []

    def validator(request: AdmissionRequest) -> bool:
        callback_kinds.append(request.kind)
        return True

    admitted = admit_group(
        _synthetic_group(),
        dataset_root=".",
        validator=validator,
        verify_assets=False,
    )
    slots = build_comparison_slots([admitted], seed=seed)
    ledger = CompletionTokenLedger(run_id="offline-contract-smoke", max_tokens=token_cap)
    arms_seen: set[str] = set()
    minimum_reward = math.inf
    maximum_reward = -math.inf
    malformed_rejections = 0
    weights = RewardWeights(answer=1.0, format=0.0, invalid_format_penalty=-1.0)

    for step in range(steps_per_arm):
        slot = slots[step % len(slots)]
        for plan in plan_all_arms(slot):
            arms_seen.add(plan.arm)
            correct = score_completion(
                plan, f"<answer>{plan.gold_target}</answer>", weights=weights
            )
            malformed = score_completion(
                plan,
                f"<answer>{plan.gold_target}</answer> trailing",
                weights=weights,
            )
            if malformed.parser_valid:
                raise AssertionError("offline smoke accepted trailing answer text")
            malformed_rejections += 1
            minimum_reward = min(minimum_reward, correct.total_reward, malformed.total_reward)
            maximum_reward = max(maximum_reward, correct.total_reward, malformed.total_reward)
            key = completion_id(plan.arm, plan.slot_id, step)
            ledger.record(key, 8, slot_id=plan.slot_id, generation_index=step)

    if arms_seen != set(ALL_ARMS):
        raise AssertionError("offline smoke did not exercise all arms")
    return {
        "mode": "offline_contract_smoke",
        "trained": False,
        "gpu_used": False,
        "steps_per_arm": steps_per_arm,
        "arms": list(ALL_ARMS),
        "slot_count": len(slots),
        "slot_manifest_sha256": comparison_slot_manifest_sha256(slots),
        "admission_callback_counts": {
            kind: callback_kinds.count(kind) for kind in ("group", "image", "certificate")
        },
        "completion_count": ledger.completion_count,
        "completion_tokens": ledger.consumed_tokens,
        "remaining_token_budget": ledger.remaining_tokens,
        "malformed_rejections": malformed_rejections,
        "reward_min": minimum_reward,
        "reward_max": maximum_reward,
    }