File size: 15,154 Bytes
c6a1af0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
#!/usr/bin/env python3
"""State, sampling, and scoring contracts for the selective-update pilot.

This module is dependency-free. State oracles are privileged validation tools,
not image-only models. A manifest is a stimulus specification, not rendered data.
"""

from dataclasses import asdict, dataclass
import hashlib
import json
import math
from pathlib import Path
import random


def content_hash(path):
    digest = hashlib.sha256()
    with Path(path).open("rb") as handle:
        for chunk in iter(lambda: handle.read(8 * 1024 * 1024), b""):
            digest.update(chunk)
    return digest.hexdigest()


def seed_for(master, identity, stream):
    value = f"{master}:{identity}:{stream}".encode()
    return int.from_bytes(hashlib.sha256(value).digest()[:8], "big")


def opaque_id(master, identity, stream):
    return hashlib.sha256(f"{master}:{identity}:{stream}".encode()).hexdigest()[:20]


def write_new_json(path, value):
    """Never silently replace a manifest or an experimental result."""
    path = Path(path)
    path.parent.mkdir(parents=True, exist_ok=True)
    with path.open("x") as handle:
        json.dump(value, handle, indent=2, allow_nan=False)
        handle.write("\n")


@dataclass(frozen=True)
class State:
    updated_present: bool
    retained_slot: int

    def __post_init__(self):
        if type(self.updated_present) is not bool:
            raise ValueError("Presence must be a Boolean")
        if type(self.retained_slot) is not int or self.retained_slot not in range(3):
            raise ValueError("Retained slot must be an integer in [0, 2]")

    def transition(self, event):
        if event == "remove" and self.updated_present:
            return State(False, self.retained_slot)
        if event == "return" and not self.updated_present:
            return State(True, self.retained_slot)
        raise ValueError(f"Invalid event {event!r} for {self}")


def final_state(history):
    state = State(**history["initial_state"])
    for event in history["events"]:
        state = state.transition(event)
    return state


@dataclass(frozen=True)
class FramePlan:
    sample_frames: int
    context_frames: int
    score_start_frame: int
    score_end_frame: int
    input_size: int
    patch_size: int = 16
    tubelet_size: int = 2
    sample_step: int = 5

    def __post_init__(self):
        for name, value in asdict(self).items():
            if type(value) is not int or value <= 0:
                raise ValueError(f"{name} must be a positive integer")
        if not 0 < self.context_frames <= self.score_start_frame < self.score_end_frame <= self.sample_frames:
            raise ValueError("Context and target scoring windows must be disjoint and ordered")
        if any(x % self.tubelet_size for x in (
            self.sample_frames, self.context_frames,
            self.score_start_frame, self.score_end_frame,
        )):
            raise ValueError("All temporal boundaries must align to complete tubelets")
        if self.input_size % self.patch_size:
            raise ValueError("Input dimensions must contain whole patches")

    @property
    def spatial_tokens(self):
        return (self.input_size // self.patch_size) ** 2

    @property
    def total_tokens(self):
        return self.sample_frames // self.tubelet_size * self.spatial_tokens

    @property
    def context_tokens(self):
        return self.context_frames // self.tubelet_size * self.spatial_tokens

    @property
    def future_tokens(self):
        return self.total_tokens - self.context_tokens

    def indices(self):
        """Indices identify KEPT tokens, in time-major, row-major order."""
        spatial = self.spatial_tokens
        return {
            "context": list(range(self.context_tokens)),
            "future": list(range(self.context_tokens, self.total_tokens)),
            "score_absolute": list(range(
                self.score_start_frame // self.tubelet_size * spatial,
                self.score_end_frame // self.tubelet_size * spatial,
            )),
            "score_in_future": list(range(
                (self.score_start_frame - self.context_frames) // self.tubelet_size * spatial,
                (self.score_end_frame - self.context_frames) // self.tubelet_size * spatial,
            )),
        }

    def summary(self, master_fps=30):
        sampled = [j * self.sample_step for j in range(self.sample_frames)]
        return {
            "sampled_master_indices": sampled,
            "sampled_timestamps_seconds": [i / master_fps for i in sampled],
            "last_context_timestamp_seconds": sampled[self.context_frames - 1] / master_fps,
            "context_tokens": self.context_tokens,
            "future_tokens": self.future_tokens,
            "total_tokens": self.total_tokens,
            "score_tokens_full_frame": len(self.indices()["score_absolute"]),
        }


def read_protocol(path):
    protocol = json.loads(Path(path).read_text())
    if protocol["schema_version"] != 1:
        raise ValueError("Unsupported protocol schema")
    plan = FramePlan(**protocol["sampling"])
    scene = protocol["scene"]
    if (scene["cups"], scene["balls"], scene["swaps"]) != (3, 2, 0):
        raise ValueError("This version implements only the two-ball, three-cup, zero-swap core")
    if (plan.sample_frames - 1) * plan.sample_step >= scene["master_frames"]:
        raise ValueError("A sampled frame falls outside the master video")
    reveal_start = protocol["events_master_frames"]["reveal"][0]
    if (plan.context_frames - 1) * plan.sample_step >= reveal_start:
        raise ValueError("Context includes the reveal")
    terminal_start, terminal_end = protocol["events_master_frames"]["terminal_visible"]
    if plan.score_start_frame * plan.sample_step < terminal_start:
        raise ValueError("Scoring begins before the terminal visibility window")
    if (plan.score_end_frame - 1) * plan.sample_step >= terminal_end:
        raise ValueError("Scoring exceeds the terminal visibility window")
    return protocol, plan


def make_pilot(protocol):
    count = protocol["pilot_blocks"]
    if type(count) is not int or count < 1:
        raise ValueError("Pilot block count must be positive")
    master = protocol["master_seed"]
    factor_values = {
        "updated_slot": [i % 3 for i in range(count)],
        "updated_color": [protocol["scene"]["colors"][i % 2] for i in range(count)],
        "removal_direction": [-1 if i % 2 else 1 for i in range(count)],
    }
    for name, values in factor_values.items():
        random.Random(seed_for(master, "all_blocks", name)).shuffle(values)
    blocks = []
    for index in range(count):
        block_id = opaque_id(master, index, "scene_block")
        updated_slot = factor_values["updated_slot"][index]
        slots = [slot for slot in range(3) if slot != updated_slot]
        histories, candidates = [], []
        for slot in slots:
            for present in (False, True):
                identity = f"{slot}:{present}"
                histories.append({
                    "history_id": opaque_id(master, block_id, "history:" + identity),
                    "initial_state": asdict(State(True, slot)),
                    "events": ["remove", "return"] if present else ["remove"],
                })
                candidates.append({
                    "candidate_id": opaque_id(master, block_id, "candidate:" + identity),
                    "state": asdict(State(present, slot)),
                })
        order_rng = random.Random(seed_for(master, block_id, "orders"))
        order_rng.shuffle(histories)
        order_rng.shuffle(candidates)
        candidate_ids = [c["candidate_id"] for c in candidates]
        nuisance_rng = random.Random(seed_for(master, block_id, "nuisance"))
        updated_color = factor_values["updated_color"][index]
        blocks.append({
            "block_id": block_id,
            "split": "pilot",
            "render_status": "not_rendered",
            "updated_slot": updated_slot,
            "updated_color": updated_color,
            "retained_color": next(c for c in protocol["scene"]["colors"] if c != updated_color),
            "removal_direction": factor_values["removal_direction"][index],
            "render_seed": seed_for(master, block_id, "render") % (2 ** 31),
            "nuisance_specification_not_yet_rendered": {
                "camera_azimuth_delta_degrees": nuisance_rng.uniform(-4.0, 4.0),
                "key_light_multiplier": nuisance_rng.uniform(0.9, 1.1),
                "cup_roughness": nuisance_rng.uniform(0.24, 0.38),
            },
            "histories": histories,
            "candidates": candidates,
            "answer_orders": [candidate_ids[i:] + candidate_ids[:i] for i in range(4)],
        })
    return {
        "schema_version": 1,
        "protocol_id": protocol["protocol_id"],
        "status": "planned_stimuli_not_rendered_data",
        "independent_unit": "block_id",
        "privileged_labels": True,
        "blocks": blocks,
    }


def compatible_candidates(block, history, observation):
    """Information-limited oracle, given the experiment's balanced event policy."""
    if observation not in {"full", "early_only", "event_only", "neither"}:
        raise ValueError(f"Unknown observation mode: {observation}")
    actual = final_state(history)
    compatible = []
    for i, candidate in enumerate(block["candidates"]):
        state = State(**candidate["state"])
        retained_known = observation in {"full", "early_only"}
        updated_known = observation in {"full", "event_only"}
        if retained_known and state.retained_slot != actual.retained_slot:
            continue
        if updated_known and state.updated_present != actual.updated_present:
            continue
        compatible.append(i)
    if not compatible:
        raise ValueError("Candidate set omits a compatible state")
    return compatible


def oracle_scores(block, observation):
    return [
        [0.0 if i in compatible_candidates(block, history, observation) else 1.0
         for i in range(len(block["candidates"]))]
        for history in block["histories"]
    ]


def score_matrix(block, energies, tolerance=1e-7):
    if not math.isfinite(tolerance) or tolerance < 0:
        raise ValueError("Tie tolerance must be finite and nonnegative")
    if len(energies) != len(block["histories"]):
        raise ValueError("One energy row is required per history")
    rows = []
    candidates = [State(**c["state"]) for c in block["candidates"]]
    if len(set(candidates)) != len(candidates):
        raise ValueError("Duplicate semantic candidates are not allowed")
    for history, raw in zip(block["histories"], energies):
        if len(raw) != len(candidates) or not all(math.isfinite(v) for v in raw):
            raise ValueError("Each score row must contain finite energies for all candidates")
        actual = final_state(history)
        if actual not in candidates:
            raise ValueError("Correct state is missing from candidates")
        best = min(raw)
        winners = [i for i, energy in enumerate(raw) if energy <= best + tolerance]
        weight = 1 / len(winners)
        updated = sum(weight for i in winners if candidates[i].updated_present == actual.updated_present)
        retained = sum(weight for i in winners if candidates[i].retained_slot == actual.retained_slot)
        joint = sum(weight for i in winners if candidates[i] == actual)
        rows.append({
            "history_id": history["history_id"],
            "joint_accuracy": joint,
            "updated_accuracy": updated,
            "retained_accuracy": retained,
            "tied_choices": len(winners),
            "correctness_contingency": {
                "both_correct": joint,
                "updated_only_correct": updated - joint,
                "retained_only_correct": retained - joint,
                "both_wrong": 1 - updated - retained + joint,
            },
        })
    return {
        "block_id": block["block_id"],
        **{name: sum(r[name] for r in rows) / len(rows)
           for name in ("joint_accuracy", "updated_accuracy", "retained_accuracy")},
        "all_histories_uniquely_correct": all(r["joint_accuracy"] == 1 and r["tied_choices"] == 1 for r in rows),
        "rows": rows,
    }


def validate_manifest(manifest, protocol):
    blocks = manifest["blocks"]
    if len(blocks) != protocol["pilot_blocks"]:
        raise ValueError("Unexpected number of independent blocks")
    if len({b["block_id"] for b in blocks}) != len(blocks):
        raise ValueError("Duplicate parent blocks")
    totals = {mode: [] for mode in ("full", "early_only", "event_only", "neither")}
    for block in blocks:
        if block["split"] != "pilot":
            raise ValueError("Exploratory pilot manifest contains a non-pilot block")
        if len(block["histories"]) != 4 or len(block["candidates"]) != 4:
            raise ValueError("Every block must cross four histories with four candidates")
        expected = {State(present, slot) for present in (False, True)
                    for slot in range(3) if slot != block["updated_slot"]}
        actual_candidates = {State(**c["state"]) for c in block["candidates"]}
        actual_histories = {final_state(h) for h in block["histories"]}
        if actual_candidates != expected or actual_histories != expected:
            raise ValueError("Incomplete or invalid factorial state set")
        if any(not State(**h["initial_state"]).updated_present for h in block["histories"]):
            raise ValueError("Updated object must initially be present")
        for key, entries in (("history_id", block["histories"]), ("candidate_id", block["candidates"])):
            if len({e[key] for e in entries}) != 4:
                raise ValueError(f"Duplicate {key}")
        ids = [c["candidate_id"] for c in block["candidates"]]
        if len(block["answer_orders"]) != 4:
            raise ValueError("Four balanced answer orders are required")
        for order in block["answer_orders"]:
            if sorted(order) != sorted(ids):
                raise ValueError("Invalid answer permutation")
        for candidate_id in ids:
            if sorted(order.index(candidate_id) for order in block["answer_orders"]) != list(range(4)):
                raise ValueError("Answer positions are not counterbalanced")
        for mode in totals:
            totals[mode].append(score_matrix(block, oracle_scores(block, mode))["joint_accuracy"])
    results = {mode: sum(values) / len(values) for mode, values in totals.items()}
    expected_accuracy = {"full": 1.0, "early_only": 0.5, "event_only": 0.5, "neither": 0.25}
    if results != expected_accuracy:
        raise ValueError(f"Information-limit check failed: {results}")
    return {
        "status": "structural_contract_passed_render_validity_pending",
        "independent_scene_blocks": len(blocks),
        "histories": len(blocks) * 4,
        "candidate_combinations_not_independent": len(blocks) * 16,
        "privileged_information_oracle_joint_accuracy": results,
        "rendered_frames_checked": 0,
    }