File size: 7,202 Bytes
295b4c9
b684a6d
2d25b75
 
b684a6d
 
2d25b75
7d90c5c
 
 
d0b9a0c
b684a6d
 
 
 
 
2d25b75
295b4c9
b684a6d
 
 
 
 
 
 
 
 
 
d97d368
 
295b4c9
 
 
b684a6d
d97d368
b684a6d
 
d97d368
b684a6d
 
d97d368
b684a6d
 
 
d97d368
 
 
 
 
 
 
 
 
 
 
 
 
d0b9a0c
 
b684a6d
 
 
 
 
 
7d90c5c
b684a6d
 
 
7d90c5c
d97d368
 
 
2d25b75
b684a6d
295b4c9
b684a6d
 
 
d97d368
d0b9a0c
b684a6d
 
d0b9a0c
 
b684a6d
 
 
 
 
 
 
 
d0b9a0c
b684a6d
 
 
d97d368
 
2d25b75
 
d0b9a0c
d97d368
b684a6d
d97d368
b684a6d
d97d368
 
 
 
b684a6d
 
 
 
d97d368
b684a6d
 
 
295b4c9
d0b9a0c
d97d368
d0b9a0c
b684a6d
 
d97d368
 
2d25b75
d97d368
7d90c5c
d97d368
b684a6d
2d25b75
7d90c5c
d97d368
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b684a6d
295b4c9
b684a6d
 
 
 
 
7d90c5c
b684a6d
295b4c9
b684a6d
 
 
 
 
 
 
 
d97d368
b684a6d
d97d368
b684a6d
295b4c9
d0b9a0c
d97d368
 
 
 
 
 
b684a6d
d97d368
 
 
 
7d90c5c
d97d368
d0b9a0c
d97d368
 
7d90c5c
d97d368
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7d90c5c
295b4c9
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
import time
import json
import hashlib
import platform
import os
from datetime import datetime

import numpy as np
import gradio as gr

APP_TITLE = "Coherent Compute Engine"

# -----------------------------
# Core coherent update (NumPy)
# -----------------------------
def coherent_step(Psi, E, L):
    phase = 0.997 * Psi + 0.003 * E
    drive = np.tanh(phase)
    Psi = 0.999 * Psi + 0.001 * drive
    E   = 0.995 * E   + 0.004 * Psi
    L   = 0.998 * L   + 0.001 * (Psi * E)
    return Psi, E, L


# -----------------------------
# Metrics
# -----------------------------
def compute_coherence(a, b):
    num = float(np.dot(a, b))
    den = float(np.linalg.norm(a) * np.linalg.norm(b) + 1e-9)
    return float(abs(num / den))


# -----------------------------
# Optional baseline (context only, safety-capped)
# -----------------------------
def python_loop_baseline(n, steps, cap=50_000):
    n_cap = min(int(n), int(cap))
    x = [0.5] * n_cap
    t0 = time.time()
    for _ in range(int(steps)):
        for i in range(n_cap):
            x[i] = 0.999 * x[i] + 0.001
    elapsed = time.time() - t0
    items = n_cap * int(steps)
    return items / elapsed / 1e9, n_cap


# -----------------------------
# Receipt hashing
# IMPORTANT: sha256 is computed over receipt JSON WITHOUT the sha256 field
# -----------------------------
def compute_receipt_sha256(receipt_obj: dict) -> str:
    obj = dict(receipt_obj)
    obj.pop("sha256", None)
    payload = json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode("utf-8")
    return hashlib.sha256(payload).hexdigest()


# -----------------------------
# Main engine
# -----------------------------
def run_engine(n_osc, steps, include_baselines):
    n = int(n_osc)
    steps = int(steps)

    Psi = np.random.rand(n).astype(np.float32)
    E   = np.random.rand(n).astype(np.float32)
    L   = np.random.rand(n).astype(np.float32)

    # sample slice for coherence proxy (keeps runtime sane)
    sample = min(n, 200_000)
    Psi_start = Psi[:sample].copy()

    t0 = time.time()
    for _ in range(steps):
        Psi, E, L = coherent_step(Psi, E, L)
    elapsed = time.time() - t0

    Psi_end = Psi[:sample].copy()

    coherence = compute_coherence(Psi_start, Psi_end)
    mean_energy = float(np.mean(E))

    items = n * steps
    throughput_items = items / elapsed
    throughput_b = throughput_items / 1e9

    result = {
        "Throughput (B items/s)": f"{throughput_b:.3f}",
        "Throughput (items/s)": f"{int(throughput_items):,}",
        "Coherence (|C|)": f"{coherence:.5f}",
        "Mean Energy": f"{mean_energy:.5f}",
        "Elapsed Time (s)": f"{elapsed:.2f}",
        "Oscillators": f"{n:,}",
        "Steps": f"{steps}",
        "Engine": "numpy",
        "CPU": platform.processor() or "",
        "Cores Available": os.cpu_count() or 0,
    }

    if include_baselines:
        py_b, py_ncap = python_loop_baseline(n, steps)
        result.update({
            "Baseline: numpy (B items/s)": f"{throughput_b:.3f}",
            "Baseline: python_loop (B items/s)": f"{py_b:.3f}",
            "Baseline: python_loop items measured": f"{py_ncap:,}",
            "Speedup vs python_loop (x)": f"{(throughput_b / max(py_b, 1e-12)):.1f}",
            "Speedup vs numpy (x)": f"{(throughput_b / max(throughput_b, 1e-12)):.2f}",
            "Note": "Baselines are context-only; python loop is safety-capped and measured live."
        })

    receipt = {
        "timestamp_utc": datetime.utcnow().isoformat() + "Z",
        "app": APP_TITLE,
        "results": result,
        "platform": platform.platform(),
        "python": platform.python_version(),
    }

    receipt["sha256"] = compute_receipt_sha256(receipt)

    os.makedirs("receipts", exist_ok=True)
    fname = f"receipts/receipt_{datetime.utcnow().strftime('%Y-%m-%dT%H-%M-%S')}.json"
    with open(fname, "w", encoding="utf-8") as f:
        json.dump(receipt, f, indent=2, ensure_ascii=False)

    result["Receipt SHA-256 (in file)"] = receipt["sha256"]

    # Return pretty results + receipt file
    return json.dumps(result, indent=2), fname


# -----------------------------
# Receipt verifier
# -----------------------------
def verify_receipt(uploaded_file):
    if uploaded_file is None:
        return "No file uploaded.", ""

    path = uploaded_file.name if hasattr(uploaded_file, "name") else str(uploaded_file)
    try:
        with open(path, "r", encoding="utf-8") as f:
            receipt = json.load(f)
    except Exception as e:
        return f"Invalid JSON file: {e}", ""

    claimed = str(receipt.get("sha256", "")).strip()
    computed = compute_receipt_sha256(receipt)

    ok = (claimed != "" and claimed.lower() == computed.lower())

    verdict = {
        "verified": bool(ok),
        "claimed_sha256": claimed,
        "computed_sha256": computed,
        "note": "Verified means: sha256(receipt_without_sha256_field) matches the sha256 stored in the receipt."
    }

    banner = "✅ Receipt verified (SHA-256 match)" if ok else "❌ Receipt FAILED verification (SHA-256 mismatch)"
    return banner, json.dumps(verdict, indent=2)


# -----------------------------
# UI
# -----------------------------
with gr.Blocks(title=APP_TITLE) as demo:
    gr.Markdown(
        f"""
# {APP_TITLE}

Everything you see below is computed **right now**, on this machine.

**What an “item” is**  
• One coherent state update of **[Ψ, E, L]** per oscillator per step

**What you get**  
• Real throughput (items/sec)  
• Stability proxy (|C|)  
• Energy behaviour  
• A downloadable **receipt with SHA-256** (verification-first)  
• A built-in **receipt verifier** (upload → verify → done)

No precomputed results. No estimates.
"""
    )

    with gr.Tabs():
        with gr.Tab("Run"):
            n_slider = gr.Slider(250_000, 8_000_000, value=6_400_000, step=250_000,
                                 label="Number of Oscillators")
            steps_slider = gr.Slider(50, 1_000, value=650, step=25,
                                     label="Simulation Steps")

            baseline_toggle = gr.Checkbox(
                label="Include baselines (context only)",
                value=True
            )

            run_btn = gr.Button("Run Engine")

            output = gr.Code(label="Results", language="json")
            receipt_file = gr.File(label="Receipt (download)")

            run_btn.click(
                fn=run_engine,
                inputs=[n_slider, steps_slider, baseline_toggle],
                outputs=[output, receipt_file]
            )

        with gr.Tab("Verify receipt"):
            gr.Markdown(
                """
Upload a receipt JSON generated by this Space.

This verifier recomputes the SHA-256 (over the receipt JSON **without** the `sha256` field) and checks it matches the stored value.
"""
            )
            up = gr.File(label="Upload receipt (.json)")
            verify_btn = gr.Button("Verify")
            banner = gr.Textbox(label="Verification result", interactive=False)
            detail = gr.Code(label="Details", language="json")
            verify_btn.click(fn=verify_receipt, inputs=[up], outputs=[banner, detail])

demo.launch()