File size: 16,474 Bytes
5be082c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
#!/usr/bin/env python3
"""Exact finite checks of the manuscript's complete restricted realization.

Twenty-four seeded streams interleave legal clamped-affine actions, positive
invertible affine evolution, transported-prefix rebases, presentation-only
evaluations, and separately sampled native-history commits. The independent
reference directly executes every semantic event and the full affine image
recipe. The candidate uses a prepared base, ordered transported residual,
periodic source decoder, and compact effect context.

Only fractions.Fraction and Python's standard library are used. These finite
mathematical checks are neither a proof for all programs nor measurements of
hardware, floating-point engines, latency, or NVIDIA software.
"""

from __future__ import annotations

import argparse
import hashlib
import json
import random
from dataclasses import dataclass
from fractions import Fraction as F
from pathlib import Path
from typing import Optional


SEED = 20261030
STREAMS = 24
EVENTS_PER_STREAM = 40
PIXELS = 7
RGB = tuple[F, F, F]
Image = tuple[RGB, ...]


def require(condition: bool, message: str) -> None:
    if not condition:
        raise AssertionError(message)


def clip(value: F, lo: F, hi: F) -> F:
    return min(hi, max(lo, value))


@dataclass(frozen=True)
class ClampAffine:
    a: F
    b: F
    lo: F
    hi: F

    def __post_init__(self) -> None:
        require(self.a >= 0 and self.lo <= self.hi, "invalid action")

    def __call__(self, value: F) -> F:
        return clip(self.a * value + self.b, self.lo, self.hi)


# None is the expressly adjoined empty-word identity, not a finite-bound clip.
Residual = Optional[ClampAffine]


def apply(residual: Residual, value: F) -> F:
    return value if residual is None else residual(value)


def compose(outer: Residual, inner: Residual) -> Residual:
    if outer is None:
        return inner
    if inner is None:
        return outer
    return ClampAffine(
        outer.a * inner.a,
        outer.a * inner.b + outer.b,
        outer(inner.lo),
        outer(inner.hi),
    )


def transport(residual: Residual, alpha: F, beta: F) -> Residual:
    require(alpha > 0, "slow affine evolution must be invertible and positive")
    if residual is None:
        return None
    return ClampAffine(
        residual.a,
        alpha * residual.b + (1 - residual.a) * beta,
        alpha * residual.lo + beta,
        alpha * residual.hi + beta,
    )


def aggregate(word: list[tuple[int, ClampAffine]]) -> Residual:
    residual: Residual = None
    for _, action in word:
        residual = compose(action, residual)
    return residual


def source_reference(source: Image, coordinate: F) -> RGB:
    """Floor the unwrapped coordinate, then wrap the two endpoint indices."""
    lower = coordinate.numerator // coordinate.denominator
    weight = coordinate - lower
    left, right = source[lower % len(source)], source[(lower + 1) % len(source)]
    return tuple((1 - weight) * left[c] + weight * right[c] for c in range(3))


def source_candidate(source: Image, coordinate: F) -> RGB:
    """Wrap first; this also checks negative-coordinate periodic agreement."""
    position = coordinate % len(source)
    lower = position.numerator // position.denominator
    weight = position - lower
    left, right = source[lower], source[(lower + 1) % len(source)]
    return tuple(left[c] + weight * (right[c] - left[c]) for c in range(3))


def matvec(matrix: tuple[RGB, RGB, RGB], value: RGB) -> RGB:
    return tuple(sum((row[c] * value[c] for c in range(3)), F(0)) for row in matrix)


@dataclass(frozen=True)
class Recipe:
    source: Image
    scale: F
    weights: tuple[F, ...]
    matrix: tuple[RGB, RGB, RGB]
    bias: RGB
    hud: Image
    hud_alpha: tuple[F, ...]


@dataclass(frozen=True)
class Context:
    coefficient: tuple[F, ...]
    bias: Image
    history_tail: Image


def prepare(recipe: Recipe, history: Image) -> Context:
    tails = tuple(
        tuple((1 - recipe.weights[p]) * history[p][c] for c in range(3))
        for p in range(PIXELS)
    )
    coefficients = tuple(
        (1 - recipe.hud_alpha[p]) * recipe.weights[p] for p in range(PIXELS)
    )
    biases = []
    for p in range(PIXELS):
        graded_tail = matvec(recipe.matrix, tails[p])
        biases.append(tuple(
            recipe.hud[p][c]
            + (1 - recipe.hud_alpha[p]) * (graded_tail[c] + recipe.bias[c])
            for c in range(3)
        ))
    return Context(coefficients, tuple(biases), tails)


def render_reference(recipe: Recipe, history: Image, state: F) -> tuple[Image, Image]:
    visible, next_history = [], []
    for p in range(PIXELS):
        z = source_reference(recipe.source, F(p) + recipe.scale * state)
        mixed = tuple(
            recipe.weights[p] * z[c] + (1 - recipe.weights[p]) * history[p][c]
            for c in range(3)
        )
        next_history.append(mixed)
        graded = tuple(
            sum((recipe.matrix[c][j] * mixed[j] for j in range(3)), F(0))
            + recipe.bias[c]
            for c in range(3)
        )
        visible.append(tuple(
            recipe.hud[p][c] + (1 - recipe.hud_alpha[p]) * graded[c]
            for c in range(3)
        ))
    return tuple(visible), tuple(next_history)


def render_candidate(recipe: Recipe, context: Context, state: F) -> tuple[Image, Image]:
    visible, next_history = [], []
    for p in range(PIXELS):
        z = source_candidate(recipe.source, F(p) + recipe.scale * state)
        graded = matvec(recipe.matrix, z)
        visible.append(tuple(
            context.coefficient[p] * graded[c] + context.bias[p][c]
            for c in range(3)
        ))
        next_history.append(tuple(
            recipe.weights[p] * z[c] + context.history_tail[p][c]
            for c in range(3)
        ))
    return tuple(visible), tuple(next_history)


class NativeHistoryOwner:
    """A mathematical single-owner/version gate, not an engine adapter."""

    def __init__(self, history: Image):
        self.history = history
        self.version = 0
        self.committed_ids: set[int] = set()

    def commit(self, commit_id: int, expected_version: int, proposed: Image) -> bool:
        if commit_id in self.committed_ids or expected_version != self.version:
            return False
        self.history = proposed
        self.version += 1
        self.committed_ids.add(commit_id)
        return True


def random_image(rng: random.Random) -> Image:
    return tuple(tuple(F(rng.randint(0, 12), 12) for _ in range(3)) for _ in range(PIXELS))


def random_recipe(rng: random.Random) -> Recipe:
    source = random_image(rng)
    alpha = tuple(F(rng.randint(0, 6), 6) for _ in range(PIXELS))
    hud_color = random_image(rng)
    hud = tuple(tuple(alpha[p] * hud_color[p][c] for c in range(3)) for p in range(PIXELS))
    matrix = tuple(
        tuple(F(int(i == j)) + F(rng.randint(-2, 2), 12) for j in range(3))
        for i in range(3)
    )
    return Recipe(
        source=source,
        scale=F(rng.choice((-3, -2, -1, 1, 2, 3)), rng.choice((2, 3))),
        weights=tuple(F(rng.randint(0, 6), 6) for _ in range(PIXELS)),
        matrix=matrix,
        bias=tuple(F(rng.randint(-2, 2), 24) for _ in range(3)),
        hud=hud,
        hud_alpha=alpha,
    )


def random_action(rng: random.Random) -> ClampAffine:
    lo = F(rng.randint(-12, 0), 6)
    hi = F(rng.randint(0, 12), 6)
    return ClampAffine(
        rng.choice((F(0), F(1, 2), F(1), F(3, 2), F(2))),
        F(rng.randint(-12, 12), 6), lo, hi,
    )


def verify() -> dict:
    rng = random.Random(SEED)
    counts = {name: 0 for name in (
        "actions", "slow_affine_transitions", "identity_transport_events",
        "state_equalities", "native_rebases", "consumed_input_ids",
        "native_captures", "native_history_commits", "duplicate_commit_rejections",
        "explicit_presentations", "presentation_history_unchanged_checks",
        "visible_channel_equalities", "candidate_history_channel_equalities",
        "capture_vs_later_state_distinctions",
    )}
    stream_summaries = []

    for stream in range(STREAMS):
        recipe = random_recipe(rng)
        reference_history = random_image(rng)
        owner = NativeHistoryOwner(reference_history)
        context = prepare(recipe, owner.history)
        reference_state = F(rng.randint(-6, 6), 3)
        base = reference_state
        residual: Residual = None
        pending: list[tuple[int, ClampAffine]] = []
        next_input_id = 1
        consumed_prefix = 0
        consumed_ids: set[int] = set()
        captured = None

        def rebase(number: int) -> None:
            nonlocal base, residual, pending, consumed_prefix
            require(0 <= number <= len(pending), "invalid prefix length")
            old_state = apply(residual, base)
            prefix, suffix = pending[:number], pending[number:]
            # Execute the transported prefix directly, rather than by its summary.
            for input_id, action in prefix:
                require(input_id == consumed_prefix + 1, "noncontiguous consumed prefix")
                require(input_id not in consumed_ids, "duplicate input consumption")
                base = action(base)
                consumed_ids.add(input_id)
                consumed_prefix = input_id
                counts["consumed_input_ids"] += 1
            pending = suffix
            residual = aggregate(suffix)
            require(apply(residual, base) == old_state == reference_state, "rebase changed state")
            counts["native_rebases"] += 1

        # One cycle samples a native candidate before newer input arrives, and
        # commits that sampled candidate only at the cycle's final event.
        for event in range(EVENTS_PER_STREAM):
            phase, cycle = event % 10, event // 10
            if phase in (0, 3, 8):
                action = random_action(rng)
                reference_state = action(reference_state)
                residual = compose(action, residual)
                pending.append((next_input_id, action))
                next_input_id += 1
                counts["actions"] += 1
            elif phase in (1, 6):
                alpha = rng.choice((F(1, 2), F(2, 3), F(1), F(3, 2), F(2)))
                beta = F(rng.randint(-6, 6), 6)
                reference_state = alpha * reference_state + beta
                base = alpha * base + beta
                if residual is None:
                    counts["identity_transport_events"] += 1
                residual = transport(residual, alpha, beta)
                pending = [
                    (input_id, transport(action, alpha, beta))
                    for input_id, action in pending
                ]
                counts["slow_affine_transitions"] += 1
            elif phase == 2:
                require(captured is None, "native capture overwritten before commit")
                _, reference_next = render_reference(recipe, reference_history, reference_state)
                _, candidate_next = render_candidate(recipe, context, apply(residual, base))
                require(reference_next == candidate_next, "sampled native histories differ")
                captured = (cycle, owner.version, reference_next, candidate_next, reference_state)
                counts["native_captures"] += 1
            elif phase in (4, 7):
                counts["explicit_presentations"] += 1
            elif phase == 5:
                number = len(pending) if (stream + cycle) % 2 == 0 else max(1, len(pending) // 2)
                rebase(number)
            elif phase == 9:
                require(captured is not None, "native commit has no sampled candidate")
                commit_id, expected, reference_next, candidate_next, capture_state = captured
                if capture_state != reference_state:
                    counts["capture_vs_later_state_distinctions"] += 1
                reference_history = reference_next
                require(owner.commit(commit_id, expected, candidate_next), "valid native commit rejected")
                require(owner.history == reference_history, "native history continuation differs")
                counts["native_history_commits"] += 1
                committed_state = (owner.history, owner.version)
                require(not owner.commit(commit_id, expected, candidate_next), "duplicate history commit accepted")
                require((owner.history, owner.version) == committed_state, "rejected commit changed history")
                counts["duplicate_commit_rejections"] += 1
                context = prepare(recipe, owner.history)
                captured = None

            candidate_state = apply(residual, base)
            require(candidate_state == reference_state, "transported state differs from direct execution")
            counts["state_equalities"] += 1
            before = (owner.history, owner.version)
            reference_image, reference_next = render_reference(recipe, reference_history, reference_state)
            candidate_image, candidate_next = render_candidate(recipe, context, candidate_state)
            require(reference_image == candidate_image, "compact image differs from complete recipe")
            require(reference_next == candidate_next, "candidate next history differs")
            require((owner.history, owner.version) == before, "presentation advanced native history")
            counts["presentation_history_unchanged_checks"] += 1
            counts["visible_channel_equalities"] += PIXELS * 3
            counts["candidate_history_channel_equalities"] += PIXELS * 3

        rebase(len(pending))
        require(residual is None and base == reference_state, "final catch-up did not reach direct state")
        require(consumed_prefix == next_input_id - 1, "final catch-up lost an input")
        require(owner.version == 4 and len(owner.committed_ids) == 4, "wrong native-history cadence")
        require(captured is None, "uncommitted native candidate")
        digest = hashlib.sha256(json.dumps(
            [[str(value) for value in pixel] for pixel in owner.history],
            separators=(",", ":"),
        ).encode()).hexdigest()
        stream_summaries.append({
            "stream": stream,
            "final_state": str(reference_state),
            "consumed_input_prefix": consumed_prefix,
            "native_history_version": owner.version,
            "native_history_sha256": digest,
        })

    require(counts["identity_transport_events"] > 0, "identity transport not exercised")
    require(counts["capture_vs_later_state_distinctions"] > 0, "native sampling boundary not distinguished")
    return {
        "status": "passed",
        "scope": "Finite integrated mathematical witness for the declared periodic-strip model",
        "arithmetic": "fractions.Fraction; exact rational arithmetic",
        "seed": SEED,
        "streams": STREAMS,
        "events_per_stream": EVENTS_PER_STREAM,
        "total_stream_events": STREAMS * EVENTS_PER_STREAM,
        "pixels_per_image": PIXELS,
        "counts": counts,
        "reference": "Direct ordered state updates and full temporal/grade/HUD recipe",
        "candidate": "Transported clamped-affine residual, prefix rebase, periodic decoder, compact context",
        "native_history_rule": "One commit per sampled native boundary; intervening presentations cannot commit",
        "limitations": [
            "Finite examples supplement the analytical proofs; they are not exhaustive for all states.",
            "Exact rational equality does not imply equivalence to IEEE engine arithmetic.",
            "Periodic static texture and frozen affine effects do not cover general 3D visibility.",
            "No game process, GPU, physical input, optical detector, or NVIDIA method was tested.",
            "No latency or hardware-performance reduction is measured or asserted.",
        ],
        "stream_summaries": stream_summaries,
    }


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--output", type=Path, default=Path(__file__).with_name("constructive_system_validation.json"))
    args = parser.parse_args()
    result = verify()
    args.output.write_text(json.dumps(result, indent=2, sort_keys=True) + "\n", encoding="utf-8")
    print(json.dumps({key: result[key] for key in ("status", "streams", "total_stream_events", "counts")}, indent=2))


if __name__ == "__main__":
    main()