Publish verified torch-cpu kernel v1
Browse filesDedicated Kernel Hub migration from legacy model commit 883050fab65a1bb2096c77526dbfdabaf3fc4a3a. Locally loaded with kernels 0.16.0 on CPU and passed its bounded verification.
- LICENSE +19 -0
- README.md +273 -0
- build/torch-cpu/metadata.json +10 -0
- build/torch-cpu/szl_kernels/__init__.py +257 -0
- build/torch-cpu/szl_kernels/_chain.py +265 -0
- build/torch-cpu/szl_kernels/_ops.py +220 -0
LICENSE
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Apache License
|
| 2 |
+
Version 2.0, January 2004
|
| 3 |
+
http://www.apache.org/licenses/
|
| 4 |
+
|
| 5 |
+
Copyright 2026 SZL Holdings
|
| 6 |
+
|
| 7 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
| 8 |
+
you may not use this file except in compliance with the License.
|
| 9 |
+
You may obtain a copy of the License at
|
| 10 |
+
|
| 11 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 12 |
+
|
| 13 |
+
Unless required by applicable law or agreed to in writing, software
|
| 14 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
| 15 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 16 |
+
See the License for the specific language governing permissions and
|
| 17 |
+
limitations under the License.
|
| 18 |
+
|
| 19 |
+
The full Apache License 2.0 text is available at the URL above.
|
README.md
ADDED
|
@@ -0,0 +1,273 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
tags:
|
| 3 |
+
- kernel
|
| 4 |
+
- governance
|
| 5 |
+
- provenance
|
| 6 |
+
- suite
|
| 7 |
+
- doi:10.5281/zenodo.19944926
|
| 8 |
+
library_name: kernels
|
| 9 |
+
license: apache-2.0
|
| 10 |
+
szl-governance:
|
| 11 |
+
verdict: ADVISORY
|
| 12 |
+
lambda: "Conjecture 1 (open) — uniqueness unproven; advisory only"
|
| 13 |
+
energy: MEASURED-only (real NVML delta; None when unavailable)
|
| 14 |
+
provenance: UnifiedReceiptChain (SHA3-256, op-agnostic, cross-kernel)
|
| 15 |
+
honest_blocked: "a failed check stays failed — never faked green"
|
| 16 |
+
---
|
| 17 |
+
|
| 18 |
+
<p align="center">
|
| 19 |
+
<a href="https://huggingface.co/SZLHOLDINGS/szl-kernels/tree/main/build/torch-universal/szl_kernels"><img src="https://img.shields.io/badge/kernel%20hub-torch--universal-5b8dee?style=flat-square" alt="kernel hub"></a>
|
| 20 |
+
<a href="https://huggingface.co/SZLHOLDINGS/szl-kernels/blob/main/MODEL_PROVENANCE.json"><img src="https://img.shields.io/badge/provenance-MODEL_PROVENANCE.json-3af4c8?style=flat-square" alt="provenance"></a>
|
| 21 |
+
<a href="https://huggingface.co/SZLHOLDINGS/szl-kernels/blob/main/LICENSE"><img src="https://img.shields.io/badge/license-Apache--2.0-7e8aa3?style=flat-square" alt="license"></a>
|
| 22 |
+
</p>
|
| 23 |
+
|
| 24 |
+
# szl-kernels — the unified governed-kernel suite
|
| 25 |
+
|
| 26 |
+
**The first kernel that governs provenance *across* ops, not just within one.** A `get_kernel`-discoverable suite that ties SZL Holdings' three governed kernels — [`szl-governed-norm`](https://huggingface.co/SZLHOLDINGS/szl-governed-norm), [`szl-lambda-gate`](https://huggingface.co/SZLHOLDINGS/szl-lambda-gate), and [`governed-inference-meter`](https://huggingface.co/SZLHOLDINGS/governed-inference-meter) — into **one shared, hash-chained `UnifiedReceiptChain`**, and anchors a governance/interop layer on top: [`szl-govsign`](https://huggingface.co/SZLHOLDINGS/szl-govsign) (signs the verdict), [`szl-blocked`](https://huggingface.co/SZLHOLDINGS/szl-blocked) (refuses honestly + derives EU AI Act Annex IV), and [`szl-provctl`](https://huggingface.co/SZLHOLDINGS/szl-provctl) (verifies the provenance DAG + bridges to in-toto/SLSA).
|
| 27 |
+
|
| 28 |
+
> Every Kernel Hub leader competes on **FLOPs per op**. They do not sign their build artifacts, they do not surface an honest BLOCKED verdict, and they do not stitch provenance *across* ops. `szl-kernels` opens that lane: a real forward pass touching norm + an advisory Λ gate + an energy reading produces **one auditable, tamper-evident log** — not three disconnected ones.
|
| 29 |
+
|
| 30 |
+
## Quickstart
|
| 31 |
+
|
| 32 |
+
```bash
|
| 33 |
+
pip install kernels torch
|
| 34 |
+
```
|
| 35 |
+
|
| 36 |
+
```python
|
| 37 |
+
import torch
|
| 38 |
+
from kernels import get_kernel
|
| 39 |
+
|
| 40 |
+
# Current `kernels` (>=0.15) requires an explicit revision/version + trust flag for org kernels:
|
| 41 |
+
suite = get_kernel("SZLHOLDINGS/szl-kernels", revision="main", trust_remote_code=True)
|
| 42 |
+
|
| 43 |
+
print(suite.list_kernels()) # the 3 numeric suite members + honest roles
|
| 44 |
+
print(suite.list_series()) # the governance/interop companions (govsign, blocked, provctl)
|
| 45 |
+
print(suite.selfcheck()) # one-shot CPU health: ALL checks pass
|
| 46 |
+
|
| 47 |
+
# ONE shared chain spanning multiple ops:
|
| 48 |
+
chain = suite.UnifiedReceiptChain()
|
| 49 |
+
x = torch.randn(4, 64)
|
| 50 |
+
y = suite.governed_rms_norm(chain, x, eps=1e-6) # governed_norm
|
| 51 |
+
gate = suite.governed_lambda_gate(chain, torch.tensor([0.9,0.8,0.95])) # lambda_gate (advisory)
|
| 52 |
+
e = suite.governed_measure_energy(chain) # energy_core (MEASURED-only)
|
| 53 |
+
|
| 54 |
+
ok, depth, brk = chain.verify() # the WHOLE pass verifies as ONE chain
|
| 55 |
+
print(ok, depth, chain.kernels_touched()) # True 3 ['governed_norm','lambda_gate','energy_core']
|
| 56 |
+
print(chain.to_json()) # export for offline third-party re-verification
|
| 57 |
+
```
|
| 58 |
+
|
| 59 |
+
### Flagship — a governed transformer sub-block
|
| 60 |
+
|
| 61 |
+
```python
|
| 62 |
+
blk = suite.GovernedBlock()
|
| 63 |
+
res = blk.forward(x, gov_axes=torch.tensor([0.95, 0.9, 0.92]))
|
| 64 |
+
print(res["chain_ok"], res["chain_depth"], res["kernels_touched"])
|
| 65 |
+
# norm + advisory Λ gate + energy + binding receipt = 4 ops, one verifiable chain.
|
| 66 |
+
# The Λ gate is ADVISORY: it is recorded for audit, it does NOT alter the numerics.
|
| 67 |
+
```
|
| 68 |
+
|
| 69 |
+
## Cookbook
|
| 70 |
+
|
| 71 |
+
Three copy-paste recipes spanning the governed-kernel series. Every printed value is
|
| 72 |
+
labeled **expected shape (not executed here)** — the shapes are transcribed from each
|
| 73 |
+
kernel's committed API, not from a run on this card (SZL doctrine: never self-download to
|
| 74 |
+
inflate counters, never fabricate an output). Λ stays **Conjecture 1 (OPEN)**; energy stays
|
| 75 |
+
**MEASURED-only**; a BLOCKED verdict stays BLOCKED.
|
| 76 |
+
|
| 77 |
+
### 1 — One receipt chain across three ops (suite)
|
| 78 |
+
|
| 79 |
+
```python
|
| 80 |
+
import torch
|
| 81 |
+
from kernels import get_kernel
|
| 82 |
+
|
| 83 |
+
suite = get_kernel("SZLHOLDINGS/szl-kernels", revision="main", trust_remote_code=True)
|
| 84 |
+
|
| 85 |
+
chain = suite.UnifiedReceiptChain()
|
| 86 |
+
x = torch.randn(4, 64)
|
| 87 |
+
suite.governed_rms_norm(chain, x, eps=1e-6) # op 1: governed_norm
|
| 88 |
+
suite.governed_lambda_gate(chain, torch.tensor([0.9, 0.8, 0.95])) # op 2: lambda_gate (ADVISORY)
|
| 89 |
+
suite.governed_measure_energy(chain) # op 3: energy_core (MEASURED-only)
|
| 90 |
+
|
| 91 |
+
ok, depth, first_break = chain.verify()
|
| 92 |
+
print(ok, depth, chain.kernels_touched())
|
| 93 |
+
# expected shape (not executed here):
|
| 94 |
+
# True 3 ['governed_norm', 'lambda_gate', 'energy_core']
|
| 95 |
+
# -> one hash-chain, three ops, verifies as ONE ordered sequence.
|
| 96 |
+
# The Λ gate receipt is ADVISORY (Conjecture 1, OPEN): recorded, never proven trust.
|
| 97 |
+
# energy_core reports joules=None + UNAVAILABLE_NO_NVML on CPU — never a fabricated joule.
|
| 98 |
+
```
|
| 99 |
+
|
| 100 |
+
### 2 — honest-BLOCKED, not fake-green (szl-blocked)
|
| 101 |
+
|
| 102 |
+
```python
|
| 103 |
+
from kernels import get_kernel
|
| 104 |
+
|
| 105 |
+
blk = get_kernel("SZLHOLDINGS/szl-blocked", revision="main", trust_remote_code=True)
|
| 106 |
+
|
| 107 |
+
chain = blk.UnifiedReceiptChain()
|
| 108 |
+
policy = blk.deny_if_action_in({"exfiltrate", "delete_all"})
|
| 109 |
+
work = lambda v: v * 2
|
| 110 |
+
|
| 111 |
+
allowed = blk.governed_call(work, policy, chain, request={"action": "summarize"}, args=(21,))
|
| 112 |
+
blocked = blk.governed_call(work, policy, chain, request={"action": "exfiltrate"}, args=(21,))
|
| 113 |
+
|
| 114 |
+
print(allowed.blocked, allowed.output)
|
| 115 |
+
print(blocked.blocked, blocked.output)
|
| 116 |
+
# expected shape (not executed here):
|
| 117 |
+
# False 42 -> ALLOWED path ran work(21); an ALLOW receipt is on the chain.
|
| 118 |
+
# True None -> BLOCKED path: work was NEVER called, output is None,
|
| 119 |
+
# a BLOCK receipt is recorded. Honest-BLOCKED, never faked green.
|
| 120 |
+
```
|
| 121 |
+
|
| 122 |
+
### 3 — Sign then verify a governance verdict (szl-govsign / DSSE)
|
| 123 |
+
|
| 124 |
+
```python
|
| 125 |
+
from kernels import get_kernel
|
| 126 |
+
|
| 127 |
+
gs = get_kernel("SZLHOLDINGS/szl-govsign", revision="main", trust_remote_code=True)
|
| 128 |
+
|
| 129 |
+
priv = gs.generate_ephemeral_keypair() # production: Sigstore keyless / cosign key, out-of-band
|
| 130 |
+
pred = gs.build_governance_predicate(
|
| 131 |
+
lambda_verdict = gs.LambdaVerdict(score=0.92, notes="advisory only — Conjecture 1 (OPEN)"),
|
| 132 |
+
energy = gs.EnergyLabel(value=12.5, unit="joules"), # MEASURED-only
|
| 133 |
+
decision = gs.GovernanceDecision(status="ALLOWED", reason="passed gates"),
|
| 134 |
+
honest_blocked = False,
|
| 135 |
+
)
|
| 136 |
+
subjects = [gs.Subject(name="szl_kernels/UnifiedReceiptChain", digest={"sha256": "<chain-head>"})]
|
| 137 |
+
envelope = gs.attest(subjects, pred, priv)
|
| 138 |
+
|
| 139 |
+
print(gs.verify(envelope, priv.public_key()))
|
| 140 |
+
# expected shape (not executed here):
|
| 141 |
+
# True -> DSSE envelope (ECDSA P-256) verifies: authorship + integrity of the verdict.
|
| 142 |
+
# Any tamper -> verify() returns False (fails closed).
|
| 143 |
+
# The signature does NOT upgrade Λ to proven trust: proven_trust is locked False.
|
| 144 |
+
```
|
| 145 |
+
|
| 146 |
+
> These recipes chain across three separately published, `get_kernel`-discoverable kernels.
|
| 147 |
+
> See [`szl-provctl`](https://huggingface.co/SZLHOLDINGS/szl-provctl) to turn any of these
|
| 148 |
+
> chains into a spec-exact in-toto v1 / SLSA v1 statement the wider supply-chain world verifies.
|
| 149 |
+
|
| 150 |
+
## The governed-kernel series
|
| 151 |
+
|
| 152 |
+
Independently published, `get_kernel`-discoverable kernels that share one `UnifiedReceiptChain`. The first three are the **numeric core**; govsign + blocked + provctl are the **governance / interop layer**.
|
| 153 |
+
|
| 154 |
+
| Kernel | Lane | Live hologram |
|
| 155 |
+
|---|---|---|
|
| 156 |
+
| [`szl-governed-norm`](https://huggingface.co/SZLHOLDINGS/szl-governed-norm) | RMSNorm/LayerNorm + SHA3-256 receipts | [`governed-norm-holo`](https://szlholdings-governed-norm-holo.static.hf.space) ✅ **live** |
|
| 157 |
+
| [`szl-lambda-gate`](https://huggingface.co/SZLHOLDINGS/szl-lambda-gate) | advisory Λ gate (Conjecture 1, OPEN) | [`lambda-gate-holo`](https://szlholdings-lambda-gate-holo.static.hf.space) ✅ **live** |
|
| 158 |
+
| [`governed-inference-meter`](https://huggingface.co/SZLHOLDINGS/governed-inference-meter) | MEASURED-joule energy accounting | [`energy-attest-holo`](https://szlholdings-energy-attest-holo.static.hf.space) ✅ **live** |
|
| 159 |
+
| [`szl-govsign`](https://huggingface.co/SZLHOLDINGS/szl-govsign) | signed governance attestation (DSSE / in-toto, ECDSA P-256) | [`szl-govsign-live`](https://szlholdings-szl-govsign-live.static.hf.space) ✅ **live** |
|
| 160 |
+
| [`szl-blocked`](https://huggingface.co/SZLHOLDINGS/szl-blocked) | honest-BLOCKED first-class state + EU AI Act Annex IV DRAFT | [`szl-blocked-live`](https://szlholdings-szl-blocked-live.static.hf.space) ✅ **live** |
|
| 161 |
+
| [`szl-provctl`](https://huggingface.co/SZLHOLDINGS/szl-provctl) | provenance-DAG verify + in-toto v1 / SLSA v1 interop + per-kernel MEASURED energy | [`szl-provctl-live`](https://szlholdings-szl-provctl-live.static.hf.space) ✅ **live** |
|
| 162 |
+
| **`szl-kernels`** (this repo) | **unified suite — cross-kernel `UnifiedReceiptChain`** | [`szl-kernels-live`](https://szlholdings-szl-kernels-live.static.hf.space) ✅ **live** |
|
| 163 |
+
|
| 164 |
+
`suite.list_kernels()` returns the numeric core; `suite.list_series()` returns the govsign + blocked + provctl governance/interop layer.
|
| 165 |
+
|
| 166 |
+
### The honest-model trio (offline replays of the live Alloy surface)
|
| 167 |
+
|
| 168 |
+
Published as HF **model** repos (NOT trained models, NO weights — pure-Python, stdlib-only offline replays). Each ships a `library_name: kernels` card and MEASURED local test counts:
|
| 169 |
+
|
| 170 |
+
| Model | Lane | Tests (MEASURED) |
|
| 171 |
+
|---|---|---|
|
| 172 |
+
| [`szl-invariants`](https://huggingface.co/SZLHOLDINGS/szl-invariants) | 8 falsifiable receipt/ledger invariants, offline | 14/14 |
|
| 173 |
+
| [`szl-ouroboros`](https://huggingface.co/SZLHOLDINGS/szl-ouroboros) | bounded-loop trace + MEASURED/DERIVED loop-tax accounting | 13/13 |
|
| 174 |
+
| [`szl-formulas`](https://huggingface.co/SZLHOLDINGS/szl-formulas) | the 21 canonical formulas + governed-loop composer, PROOF-STATUS mirrored verbatim (locked-proven = exactly 8) | 17/17 |
|
| 175 |
+
|
| 176 |
+
## The gap this closes
|
| 177 |
+
|
| 178 |
+
Today even SZL's own governance is fragmented: `szl-governed-norm` keeps its own receipt chain, the energy meter keeps its own ledger, and `szl-lambda-gate` keeps none. So a single forward pass yields three logs no third party can re-walk as one ordered, tamper-evident sequence. `UnifiedReceiptChain` is that missing artifact — op-agnostic SHA3-256 receipts that hash-chain norm, Λ, and energy calls into **one** verifiable stream, in call order. `szl-govsign` then makes that chain head third-party-verifiable; `szl-blocked` makes a refusal a recorded, first-class state and derives the compliance paperwork from it; `szl-provctl` verifies the whole multi-run provenance DAG and bridges it to the in-toto/SLSA formats the rest of the supply-chain world reads.
|
| 179 |
+
|
| 180 |
+
## API
|
| 181 |
+
|
| 182 |
+
| Symbol | What it does |
|
| 183 |
+
|---|---|
|
| 184 |
+
| `UnifiedReceiptChain` | Op-agnostic SHA3-256 hash chain. `emit`, `verify() -> (ok, depth, first_break)`, `kernels_touched()`, `to_json()`, `verify_json()` (offline). |
|
| 185 |
+
| `governed_rms_norm(chain, x, weight=None, eps=1e-6)` | RMSNorm + a receipt into the shared chain. Numerics match `szl-governed-norm`. |
|
| 186 |
+
| `governed_layer_norm(chain, x, ...)` | LayerNorm + receipt. |
|
| 187 |
+
| `governed_lambda_gate(chain, axes, weights=None, threshold=0.5)` | **Advisory** Λ gate; records an advisory receipt (`advisory=True`, never proven trust). |
|
| 188 |
+
| `governed_measure_energy(chain, measurement=None)` | Records an energy reading **verbatim** — `joules=None` + `UNAVAILABLE_NO_NVML` when no GPU. Never fabricated. |
|
| 189 |
+
| `GovernedBlock` | Pre-norm sub-block composing all three + a binding receipt into one auditable pass. |
|
| 190 |
+
| `list_kernels()`, `list_series()`, `get_member()`, `selfcheck()` | Numeric registry + governance-layer series + one-shot CPU health check. |
|
| 191 |
+
|
| 192 |
+
## Honesty (SZL doctrine)
|
| 193 |
+
|
| 194 |
+
- **Λ is advisory.** Its uniqueness is **Conjecture 1 — OPEN**. A recorded gate "pass" is a non-compensatory advisory signal, **never proven trust**.
|
| 195 |
+
- **Energy is MEASURED-only.** Real NVML cumulative-energy delta when a GPU is present; otherwise `joules=None`, labeled `UNAVAILABLE_NO_NVML`. **No joule is ever fabricated.**
|
| 196 |
+
- **The digest is an integrity fingerprint, not a signature.** SHA3-256 over a canonical receipt body proves tamper-evidence + ordering — not authorship. Signing is a separate, out-of-band layer — see [`szl-govsign`](https://huggingface.co/SZLHOLDINGS/szl-govsign) for DSSE / in-toto attestation.
|
| 197 |
+
- **Honest BLOCKED beats fake green.** A failed verification stays failed — see [`szl-blocked`](https://huggingface.co/SZLHOLDINGS/szl-blocked) for refusal as a first-class, provenanced state.
|
| 198 |
+
- **Universal (pure-Python) suite — a correctness + provenance reference, not a CUDA speed record. No fabricated benchmarks.** Suite tests: 7/7 passing.
|
| 199 |
+
|
| 200 |
+
## Provenance
|
| 201 |
+
|
| 202 |
+
Backed by the Lean 4 formalization [szl-holdings/lutar-lean](https://github.com/szl-holdings/lutar-lean) (749 declarations / 14 axioms / 163 tracked sorries), DOI [10.5281/zenodo.20434308](https://doi.org/10.5281/zenodo.20434308). Λ uniqueness = Conjecture 1 (open).
|
| 203 |
+
|
| 204 |
+
## See it live
|
| 205 |
+
|
| 206 |
+
- ✅ **Live now:** [a11oy](https://huggingface.co/spaces/SZLHOLDINGS/a11oy) (live governed inference) · [hatun-mcp](https://huggingface.co/spaces/SZLHOLDINGS/hatun-mcp). **All eight demo Spaces below are live** (static, in-browser).
|
| 207 |
+
- 📚 **Collection:** [Governed Kernels — verifiable AI building blocks](https://huggingface.co/collections/SZLHOLDINGS/governed-kernels-verifiable-ai-building-blocks-6a41d3936cfce4fba83ce378) — the whole family in one page. **Live console:** [a11oy](https://szlholdings-a11oy.hf.space) · [a-11-oy.com](https://a-11-oy.com) · [llm-router](https://szlholdings-llm-router-live.hf.space) · [receipt verifier](https://szlholdings-governed-receipt-verifier.static.hf.space) · [receipt spec (hub)](https://github.com/szl-holdings/governed-receipt-spec).
|
| 208 |
+
- ✅ Suite: [`szl-kernels-live`](https://szlholdings-szl-kernels-live.static.hf.space) ✅ **live** — holographic cross-kernel provenance graph with in-browser SHA3-256 + tamper / honest-BLOCKED demo.
|
| 209 |
+
- ✅ Members: [`governed-norm-holo`](https://szlholdings-governed-norm-holo.static.hf.space) ✅ **live** · [`lambda-gate-holo`](https://szlholdings-lambda-gate-holo.static.hf.space) ✅ **live** · [`energy-attest-holo`](https://szlholdings-energy-attest-holo.static.hf.space) ✅ **live** · [`receipt-chain-live`](https://szlholdings-receipt-chain-live.static.hf.space) ✅ **live**
|
| 210 |
+
- ✅ Governance layer: [`szl-govsign-live`](https://szlholdings-szl-govsign-live.static.hf.space) ✅ **live** · [`szl-blocked-live`](https://szlholdings-szl-blocked-live.static.hf.space) ✅ **live** · [`szl-provctl-live`](https://szlholdings-szl-provctl-live.static.hf.space) ✅ **live**
|
| 211 |
+
- 🔮 `szl-substrate` *(ROADMAP — not yet live)* — the hub tying the whole governed-compute substrate together.
|
| 212 |
+
|
| 213 |
+
## Compatibility
|
| 214 |
+
|
| 215 |
+
Python 3.9+, `torch>=2.5`, standard library + torch only. Runs on CPU and CUDA.
|
| 216 |
+
|
| 217 |
+
## License
|
| 218 |
+
|
| 219 |
+
Apache-2.0. Copyright 2026 SZL Holdings.
|
| 220 |
+
|
| 221 |
+
---
|
| 222 |
+
|
| 223 |
+
<sub><b>SZL Holdings</b> · unified governed-kernel suite · cross-kernel provenance · Λ advisory (Conjecture 1) · energy MEASURED-only · <a href="https://a-11-oy.com">a-11-oy.com</a> · <a href="https://github.com/szl-holdings">github.com/szl-holdings</a> · <a href="https://huggingface.co/SZLHOLDINGS">huggingface.co/SZLHOLDINGS</a></sub>
|
| 224 |
+
|
| 225 |
+
---
|
| 226 |
+
|
| 227 |
+
[](https://doi.org/10.5281/zenodo.19944926)
|
| 228 |
+
|
| 229 |
+
## Citation
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
**Cite this.** Part of the SZL Holdings *Ouroboros Thesis* (Governed Post-Determinism).
|
| 233 |
+
Concept DOI (always-latest): [10.5281/zenodo.19944926](https://doi.org/10.5281/zenodo.19944926).
|
| 234 |
+
Author: Stephen P. Lutar Jr. · [ORCID 0009-0001-0110-4173](https://orcid.org/0009-0001-0110-4173) · License CC-BY-4.0.
|
| 235 |
+
Full DOI-pinned lineage (v1→v26) + the 8 papers: [szl-papers PAPERS_INDEX](https://github.com/szl-holdings/szl-papers/blob/main/PAPERS_INDEX.md).
|
| 236 |
+
No artifact-specific DOI is minted for this model; the concept DOI above covers the program.
|
| 237 |
+
|
| 238 |
+
Honesty (Doctrine v11): Λ unconditional uniqueness is **Conjecture 1** (machine-checked FALSE as stated) — never a theorem; conditional uniqueness is **Theorem U** (axiom-free). Locked-proven formulas = **exactly 8** {F1,F4,F7,F11,F12,F18,F19,F22}; ~185 experimental theorems are a separate CI-green tier; Khipu BFT safety = Conjecture 2. Trust never 100%.
|
| 239 |
+
|
| 240 |
+
```bibtex
|
| 241 |
+
@misc{lutar_szl_ouroboros,
|
| 242 |
+
author = {Lutar, Stephen P., Jr.},
|
| 243 |
+
title = {SZL Holdings --- The Ouroboros Thesis (Governed Post-Determinism)},
|
| 244 |
+
year = {2026},
|
| 245 |
+
publisher = {Zenodo},
|
| 246 |
+
doi = {10.5281/zenodo.19944926},
|
| 247 |
+
url = {https://doi.org/10.5281/zenodo.19944926},
|
| 248 |
+
note = {Concept DOI --- always resolves to the latest version. ORCID 0009-0001-0110-4173. CC-BY-4.0.}
|
| 249 |
+
}
|
| 250 |
+
```
|
| 251 |
+
|
| 252 |
+
*Signed-off-by: Stephen Lutar <stephenlutar2@gmail.com>*
|
| 253 |
+
|
| 254 |
+
## Files in this repo
|
| 255 |
+
|
| 256 |
+
| Path | What it is |
|
| 257 |
+
|---|---|
|
| 258 |
+
| `build/torch-universal/szl_kernels/__init__.py` | public API — suite entry points + `selfcheck()` |
|
| 259 |
+
| `build/torch-universal/szl_kernels/_chain.py` | cross-kernel `UnifiedReceiptChain` (SHA3-256) |
|
| 260 |
+
| `build/torch-universal/szl_kernels/_ops.py` | the governed op set |
|
| 261 |
+
| `tests/test_suite.py` | suite test |
|
| 262 |
+
| `build.toml` · `metadata.json` | Kernel Hub build/metadata manifests |
|
| 263 |
+
| `LICENSE` · `SECURITY.md` | Apache-2.0 · security policy |
|
| 264 |
+
|
| 265 |
+
---
|
| 266 |
+
|
| 267 |
+
<p align="center">
|
| 268 |
+
<a href="https://huggingface.co/SZLHOLDINGS">SZL Holdings</a> ·
|
| 269 |
+
<a href="https://a-11-oy.com">a-11-oy.com</a> ·
|
| 270 |
+
<a href="https://huggingface.co/SZLHOLDINGS/a11oy-v19-substrate">a11oy-v19-substrate</a>
|
| 271 |
+
</p>
|
| 272 |
+
|
| 273 |
+
<p align="center"><sub>SLSA: L1 honest · L2 attested · L3 roadmap. Λ = Conjecture 1. Trust ceiling 0.97.</sub></p>
|
build/torch-cpu/metadata.json
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"name": "szl-kernels",
|
| 3 |
+
"id": "_szl_kernels_cpu_0d1a832737",
|
| 4 |
+
"version": 1,
|
| 5 |
+
"license": "Apache-2.0",
|
| 6 |
+
"python-depends": [],
|
| 7 |
+
"backend": {
|
| 8 |
+
"type": "cpu"
|
| 9 |
+
}
|
| 10 |
+
}
|
build/torch-cpu/szl_kernels/__init__.py
ADDED
|
@@ -0,0 +1,257 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 2 |
+
# © 2026 SZL Holdings · Stephen P. Lutar · ORCID 0009-0001-0110-4173
|
| 3 |
+
"""szl_kernels — SZL Holdings' unified governed-kernel SUITE.
|
| 4 |
+
|
| 5 |
+
ONE get_kernel-discoverable package that ties the three governed kernels plus
|
| 6 |
+
the energy meter into a single suite with a SHARED, op-agnostic
|
| 7 |
+
``UnifiedReceiptChain`` — cross-kernel provenance in one auditable forward pass.
|
| 8 |
+
This is the gap the Kernel Hub leaders leave open: they optimize FLOPs per op;
|
| 9 |
+
SZL governs provenance ACROSS ops.
|
| 10 |
+
|
| 11 |
+
Suite members (each independently published as its own Hub kernel):
|
| 12 |
+
* governed_norm -> SZLHOLDINGS/szl-governed-norm (RMSNorm/LayerNorm + receipts)
|
| 13 |
+
* lambda_gate -> SZLHOLDINGS/szl-lambda-gate (advisory Λ gate; Conjecture 1)
|
| 14 |
+
* energy_core -> szl_energy_core / governed-inference-meter (MEASURED joules)
|
| 15 |
+
* govsign -> SZLHOLDINGS/szl-govsign (signed governance attestation; DSSE / in-toto)
|
| 16 |
+
* blocked -> SZLHOLDINGS/szl-blocked (honest-BLOCKED first-class state + EU AI Act Annex IV)
|
| 17 |
+
* provctl -> SZLHOLDINGS/szl-provctl (provenance-DAG verify + in-toto v1 / SLSA v1 interop + per-kernel MEASURED energy)
|
| 18 |
+
|
| 19 |
+
The first three are the NUMERIC core exercised by the shared forward pass.
|
| 20 |
+
govsign + blocked are GOVERNANCE-LAYER series companions: govsign makes a
|
| 21 |
+
verdict third-party-verifiable (sign/verify offline), and blocked makes a
|
| 22 |
+
refusal a first-class, provenanced state (the op never runs — no fake-green)
|
| 23 |
+
and derives an EU AI Act Annex IV DRAFT skeleton from the same chain.
|
| 24 |
+
|
| 25 |
+
Discover + use the suite:
|
| 26 |
+
|
| 27 |
+
from kernels import get_kernel
|
| 28 |
+
suite = get_kernel("SZLHOLDINGS/szl-kernels", revision="main", trust_remote_code=True)
|
| 29 |
+
print(suite.list_kernels()) # {'governed_norm':..., 'lambda_gate':..., 'energy_core':...}
|
| 30 |
+
print(suite.list_series()) # {'govsign':..., 'blocked':..., 'provctl':...}
|
| 31 |
+
print(suite.selfcheck()) # one-shot suite health (CPU only)
|
| 32 |
+
|
| 33 |
+
# ONE shared chain spanning multiple ops:
|
| 34 |
+
chain = suite.UnifiedReceiptChain()
|
| 35 |
+
import torch
|
| 36 |
+
x = torch.randn(4, 64)
|
| 37 |
+
y = suite.governed_rms_norm(chain, x, eps=1e-6)
|
| 38 |
+
gate = suite.governed_lambda_gate(chain, torch.tensor([0.9, 0.8, 0.95]), threshold=0.5)
|
| 39 |
+
e = suite.governed_measure_energy(chain) # None joules when no NVML — never faked
|
| 40 |
+
ok, depth, brk = chain.verify() # the WHOLE pass verifies as one chain
|
| 41 |
+
print(chain.kernels_touched()) # ['governed_norm','lambda_gate','energy_core']
|
| 42 |
+
|
| 43 |
+
# Flagship composition — a governed transformer sub-block:
|
| 44 |
+
blk = suite.GovernedBlock()
|
| 45 |
+
res = blk.forward(x, gov_axes=torch.tensor([0.95, 0.9, 0.92]))
|
| 46 |
+
print(res["chain_ok"], res["chain_depth"], res["kernels_touched"])
|
| 47 |
+
|
| 48 |
+
HONESTY (SZL doctrine v11):
|
| 49 |
+
* Λ is the weighted-geometric-mean ADVISORY aggregator; its uniqueness is
|
| 50 |
+
Conjecture 1 (OPEN). A recorded gate "pass" is advisory, NEVER proven trust.
|
| 51 |
+
* Energy joules are MEASURED-only (real NVML delta). No GPU/NVML => None /
|
| 52 |
+
UNAVAILABLE_NO_NVML, NEVER a fabricated joule.
|
| 53 |
+
* Receipt digests are SHA3-256 integrity fingerprints — tamper-evidence +
|
| 54 |
+
ordering, NOT signatures and NOT proof of authorship.
|
| 55 |
+
* This is a UNIVERSAL (pure-Python) suite: a correctness + provenance
|
| 56 |
+
reference, not a hand-tuned CUDA speed record. No fabricated benchmarks.
|
| 57 |
+
"""
|
| 58 |
+
from typing import Any, Dict
|
| 59 |
+
|
| 60 |
+
import torch
|
| 61 |
+
|
| 62 |
+
from ._chain import GENESIS, UnifiedReceiptChain, tensor_digest
|
| 63 |
+
from ._ops import (
|
| 64 |
+
GovernedBlock,
|
| 65 |
+
governed_layer_norm,
|
| 66 |
+
governed_lambda_gate,
|
| 67 |
+
governed_measure_energy,
|
| 68 |
+
governed_rms_norm,
|
| 69 |
+
)
|
| 70 |
+
|
| 71 |
+
__all__ = [
|
| 72 |
+
"UnifiedReceiptChain",
|
| 73 |
+
"tensor_digest",
|
| 74 |
+
"GENESIS",
|
| 75 |
+
"governed_rms_norm",
|
| 76 |
+
"governed_layer_norm",
|
| 77 |
+
"governed_lambda_gate",
|
| 78 |
+
"governed_measure_energy",
|
| 79 |
+
"GovernedBlock",
|
| 80 |
+
"list_kernels",
|
| 81 |
+
"list_series",
|
| 82 |
+
"get_member",
|
| 83 |
+
"selfcheck",
|
| 84 |
+
"DOCTRINE_FOOTER",
|
| 85 |
+
"PROVENANCE",
|
| 86 |
+
"__version__",
|
| 87 |
+
]
|
| 88 |
+
|
| 89 |
+
__version__ = "0.1.0"
|
| 90 |
+
|
| 91 |
+
DOCTRINE_FOOTER = (
|
| 92 |
+
"SZL Holdings · unified governed-kernel suite · cross-kernel provenance · "
|
| 93 |
+
"Λ = Conjecture 1 (advisory) · energy MEASURED-only · honesty over checklist"
|
| 94 |
+
)
|
| 95 |
+
|
| 96 |
+
# Suite registry: maps a suite-member key to its Hub coordinates + role. In
|
| 97 |
+
# production, get_member() would resolve these via kernels.get_kernel(); the
|
| 98 |
+
# reference package ships byte-faithful numerics so it runs standalone.
|
| 99 |
+
_REGISTRY: Dict[str, Dict[str, str]] = {
|
| 100 |
+
"governed_norm": {
|
| 101 |
+
"hub_id": "SZLHOLDINGS/szl-governed-norm",
|
| 102 |
+
"role": "RMSNorm/LayerNorm + SHA3-256 hash-chained receipts",
|
| 103 |
+
"honesty": "integrity fingerprint, not a signature",
|
| 104 |
+
},
|
| 105 |
+
"lambda_gate": {
|
| 106 |
+
"hub_id": "SZLHOLDINGS/szl-lambda-gate",
|
| 107 |
+
"role": "advisory Λ weighted-geometric-mean gate",
|
| 108 |
+
"honesty": "Λ uniqueness = Conjecture 1 (open); advisory, NOT proven trust",
|
| 109 |
+
},
|
| 110 |
+
"energy_core": {
|
| 111 |
+
"hub_id": "SZLHOLDINGS/governed-inference-meter",
|
| 112 |
+
"role": "MEASURED-joule energy accounting (real NVML delta)",
|
| 113 |
+
"honesty": "no GPU/NVML => UNAVAILABLE_NO_NVML, joules None — never fabricated",
|
| 114 |
+
},
|
| 115 |
+
}
|
| 116 |
+
|
| 117 |
+
# Governance-layer series companions (not part of the numeric forward pass).
|
| 118 |
+
# Each is independently published and operates on the SAME UnifiedReceiptChain
|
| 119 |
+
# provenance, extending the suite from "govern provenance ACROSS ops" to
|
| 120 |
+
# "sign that provenance" and "refuse-and-record honestly."
|
| 121 |
+
_SERIES: Dict[str, Dict[str, str]] = {
|
| 122 |
+
"govsign": {
|
| 123 |
+
"hub_id": "SZLHOLDINGS/szl-govsign",
|
| 124 |
+
"role": "signed governance attestation (DSSE / in-toto, ECDSA P-256)",
|
| 125 |
+
"honesty": "signature proves authorship+integrity, NOT Λ uniqueness; proven_trust locked False; a BLOCKED verdict is signed as BLOCKED",
|
| 126 |
+
},
|
| 127 |
+
"blocked": {
|
| 128 |
+
"hub_id": "SZLHOLDINGS/szl-blocked",
|
| 129 |
+
"role": "honest-BLOCKED first-class state + EU AI Act Annex IV DRAFT derivation",
|
| 130 |
+
"honesty": "a BLOCKED op never executes (no fake-green); Annex IV output is a DRAFT skeleton, NOT legal advice",
|
| 131 |
+
},
|
| 132 |
+
"provctl": {
|
| 133 |
+
"hub_id": "SZLHOLDINGS/szl-provctl",
|
| 134 |
+
"role": "provenance-DAG verify + in-toto v1 / SLSA v1 interop + per-kernel MEASURED energy",
|
| 135 |
+
"honesty": "in-toto/SLSA field names spec-exact; proven_trust locked False; energy MEASURED-only (never fabricated); honest-BLOCKED DAG nodes surfaced, never dropped",
|
| 136 |
+
},
|
| 137 |
+
}
|
| 138 |
+
|
| 139 |
+
PROVENANCE = {
|
| 140 |
+
"suite": "szl_kernels",
|
| 141 |
+
"members": _REGISTRY,
|
| 142 |
+
"series_companions": _SERIES,
|
| 143 |
+
"lean_repo": "szl-holdings/lutar-lean",
|
| 144 |
+
"doi_lutar_lean": "10.5281/zenodo.20434308",
|
| 145 |
+
"lambda_status": "Conjecture 1 (open) — uniqueness unproven; advisory only",
|
| 146 |
+
"shared_chain": "UnifiedReceiptChain — op-agnostic SHA3-256 cross-kernel provenance",
|
| 147 |
+
}
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def list_kernels() -> Dict[str, Dict[str, str]]:
|
| 151 |
+
"""Return the suite registry: member key -> {hub_id, role, honesty}."""
|
| 152 |
+
return {k: dict(v) for k, v in _REGISTRY.items()}
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def list_series() -> Dict[str, Dict[str, str]]:
|
| 156 |
+
"""Return the governance-layer series companions (govsign, blocked, provctl).
|
| 157 |
+
|
| 158 |
+
These extend the numeric suite with signed attestation (govsign),
|
| 159 |
+
honest-BLOCKED + EU AI Act Annex IV derivation (blocked), and provenance-DAG
|
| 160 |
+
verification + in-toto/SLSA interop + per-kernel MEASURED energy (provctl).
|
| 161 |
+
They operate on the same UnifiedReceiptChain but are not part of the numeric
|
| 162 |
+
forward pass.
|
| 163 |
+
"""
|
| 164 |
+
return {k: dict(v) for k, v in _SERIES.items()}
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
def get_member(key: str) -> Dict[str, str]:
|
| 168 |
+
"""Resolve one suite member's Hub coordinates + honest role string."""
|
| 169 |
+
if key not in _REGISTRY:
|
| 170 |
+
raise KeyError(f"unknown suite member {key!r}; have {list(_REGISTRY)}")
|
| 171 |
+
return dict(_REGISTRY[key])
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def selfcheck() -> Dict[str, Any]:
|
| 175 |
+
"""One-shot CPU-only suite health check; never raises.
|
| 176 |
+
|
| 177 |
+
Proves the suite's CENTRAL claim end-to-end: a single shared chain spans
|
| 178 |
+
governed_norm + lambda_gate + energy_core in ONE forward pass, verifies as
|
| 179 |
+
one tamper-evident sequence, AND a deliberately mutated copy fails
|
| 180 |
+
verification (so the tamper-evidence is real, not decorative).
|
| 181 |
+
|
| 182 |
+
Returns {ok, version, checks:{...}, chain_head, kernels_touched,
|
| 183 |
+
tamper_detected, error}.
|
| 184 |
+
"""
|
| 185 |
+
checks: Dict[str, bool] = {}
|
| 186 |
+
error = None
|
| 187 |
+
chain_head = GENESIS
|
| 188 |
+
kernels_touched = []
|
| 189 |
+
tamper_detected = False
|
| 190 |
+
try:
|
| 191 |
+
torch.manual_seed(0)
|
| 192 |
+
x = torch.randn(4, 64, dtype=torch.float32)
|
| 193 |
+
w = torch.randn(64, dtype=torch.float32)
|
| 194 |
+
|
| 195 |
+
chain = UnifiedReceiptChain()
|
| 196 |
+
|
| 197 |
+
# norm matches a fp32 RMSNorm reference
|
| 198 |
+
y = governed_rms_norm(chain, x, weight=w, eps=1e-6)
|
| 199 |
+
ref = (x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + 1e-6)) * w
|
| 200 |
+
checks["norm_correct"] = bool(torch.allclose(y, ref, rtol=1e-5, atol=1e-5))
|
| 201 |
+
|
| 202 |
+
# advisory Λ gate runs and is recorded as advisory
|
| 203 |
+
gate = governed_lambda_gate(
|
| 204 |
+
chain, torch.tensor([0.9, 0.8, 0.95]), threshold=0.5
|
| 205 |
+
)
|
| 206 |
+
checks["lambda_advisory"] = bool(gate["advisory"] is True)
|
| 207 |
+
|
| 208 |
+
# energy is MEASURED-only: no NVML here => joules None, honest label
|
| 209 |
+
e = governed_measure_energy(chain)
|
| 210 |
+
checks["energy_honest"] = bool(
|
| 211 |
+
e["joules"] is None and e["label"] == "UNAVAILABLE_NO_NVML"
|
| 212 |
+
)
|
| 213 |
+
|
| 214 |
+
# the WHOLE multi-op pass verifies as ONE chain
|
| 215 |
+
ok, depth, brk = chain.verify()
|
| 216 |
+
checks["cross_kernel_verify"] = bool(ok and depth == 3 and brk == -1)
|
| 217 |
+
chain_head = chain.head()
|
| 218 |
+
kernels_touched = chain.kernels_touched()
|
| 219 |
+
checks["spans_three_kernels"] = bool(
|
| 220 |
+
kernels_touched == ["governed_norm", "lambda_gate", "energy_core"]
|
| 221 |
+
)
|
| 222 |
+
|
| 223 |
+
# offline re-verification of the exported chain
|
| 224 |
+
ok2, _, _ = UnifiedReceiptChain.verify_json(chain.to_json())
|
| 225 |
+
checks["offline_reverify"] = bool(ok2)
|
| 226 |
+
|
| 227 |
+
# tamper-evidence is REAL: mutate one recorded attr and confirm break
|
| 228 |
+
blob = chain.to_json()
|
| 229 |
+
import json as _json
|
| 230 |
+
recs = _json.loads(blob)
|
| 231 |
+
recs[0]["attrs"]["eps"] = 9.99e-3 # flip a recorded value
|
| 232 |
+
ok3, _, brk3 = UnifiedReceiptChain.verify_json(_json.dumps(recs))
|
| 233 |
+
tamper_detected = bool((not ok3) and brk3 == 0)
|
| 234 |
+
checks["tamper_detected"] = tamper_detected
|
| 235 |
+
|
| 236 |
+
# GovernedBlock composition runs and self-verifies
|
| 237 |
+
blk = GovernedBlock()
|
| 238 |
+
res = blk.forward(x, weight=w, gov_axes=torch.tensor([0.95, 0.9, 0.92]))
|
| 239 |
+
checks["block_forward"] = bool(
|
| 240 |
+
res["chain_ok"]
|
| 241 |
+
and res["chain_depth"] == 4
|
| 242 |
+
and res["kernels_touched"]
|
| 243 |
+
== ["governed_norm", "lambda_gate", "energy_core", "governed_block"]
|
| 244 |
+
)
|
| 245 |
+
except Exception as exc: # never raise from a health probe
|
| 246 |
+
error = f"{type(exc).__name__}: {exc}"
|
| 247 |
+
|
| 248 |
+
ok = bool(checks) and all(checks.values()) and error is None
|
| 249 |
+
return {
|
| 250 |
+
"ok": ok,
|
| 251 |
+
"version": __version__,
|
| 252 |
+
"checks": checks,
|
| 253 |
+
"chain_head": chain_head,
|
| 254 |
+
"kernels_touched": kernels_touched,
|
| 255 |
+
"tamper_detected": tamper_detected,
|
| 256 |
+
"error": error,
|
| 257 |
+
}
|
build/torch-cpu/szl_kernels/_chain.py
ADDED
|
@@ -0,0 +1,265 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 2 |
+
# © 2026 SZL Holdings · Stephen P. Lutar · ORCID 0009-0001-0110-4173
|
| 3 |
+
"""Unified, op-agnostic, SHA3-256 hash-chained provenance for the SZL kernel suite.
|
| 4 |
+
|
| 5 |
+
THE FRONTIER GAP THIS CLOSES
|
| 6 |
+
----------------------------
|
| 7 |
+
Every governed SZL kernel today owns its OWN receipt log:
|
| 8 |
+
* szl_governed_norm -> ReceiptChain over normalization calls
|
| 9 |
+
* szl_energy_core -> CheapestWattLedger over placement decisions
|
| 10 |
+
* szl_lambda_gate -> (no chain; advisory self-checks only)
|
| 11 |
+
So a real forward pass that touches norm AND an advisory Λ gate AND the energy
|
| 12 |
+
meter produces THREE disconnected logs. There is no single artifact a third
|
| 13 |
+
party can re-walk to prove "these ops happened, in this order, on these
|
| 14 |
+
tensors, and nothing was inserted or reordered between them". That cross-op
|
| 15 |
+
provenance is the genuine gap the Kernel Hub leaders leave open: they optimize
|
| 16 |
+
FLOPs per op, not auditable provenance ACROSS ops.
|
| 17 |
+
|
| 18 |
+
``UnifiedReceiptChain`` is that missing artifact: one append-only,
|
| 19 |
+
SHA3-256 hash-chained log whose entries are op-agnostic. A norm call, an
|
| 20 |
+
advisory Λ-gate call, and an energy reading all hash-chain into the SAME chain,
|
| 21 |
+
in call order, so the whole forward pass verifies as one tamper-evident
|
| 22 |
+
sequence.
|
| 23 |
+
|
| 24 |
+
HONESTY (SZL doctrine v11)
|
| 25 |
+
--------------------------
|
| 26 |
+
* The digest is a real SHA3-256 over a canonical JSON body. It is an INTEGRITY
|
| 27 |
+
fingerprint (tamper-evidence + ordering), NOT a cryptographic signature and
|
| 28 |
+
NOT a proof of authorship. DSSE / sigstore signing is a separate, out-of-band
|
| 29 |
+
concern and is explicitly NOT claimed here.
|
| 30 |
+
* Tensor fingerprints round to a fixed decimal precision so they reproduce
|
| 31 |
+
across devices/dtypes for the same logical values. This is the same scheme
|
| 32 |
+
szl_governed_norm already ships — we reuse it verbatim so a unified-chain
|
| 33 |
+
tensor digest equals the per-kernel chain's digest for the same tensor.
|
| 34 |
+
* Any Λ entry is recorded as ADVISORY metadata only. A recorded "passed=True"
|
| 35 |
+
is a non-compensatory advisory signal, NEVER "proven trust" (Λ uniqueness =
|
| 36 |
+
Conjecture 1, OPEN).
|
| 37 |
+
* Any energy entry carries the kernel's honest label verbatim (MEASURED /
|
| 38 |
+
SAMPLE / UNAVAILABLE_NO_NVML / ESTIMATE / UNKNOWN). The chain NEVER upgrades
|
| 39 |
+
an UNAVAILABLE reading to a number — if joules is None it stays None.
|
| 40 |
+
* Stdlib + torch only (Kernel Hub universal-kernel requirement). Nothing is
|
| 41 |
+
written to disk or the network from inside the chain.
|
| 42 |
+
"""
|
| 43 |
+
from __future__ import annotations
|
| 44 |
+
|
| 45 |
+
import hashlib
|
| 46 |
+
import json
|
| 47 |
+
import threading
|
| 48 |
+
import time
|
| 49 |
+
from typing import Any, Dict, List, Optional
|
| 50 |
+
|
| 51 |
+
try: # torch is optional at import time so the chain stays inspectable headless
|
| 52 |
+
import torch # noqa: F401
|
| 53 |
+
_HAS_TORCH = True
|
| 54 |
+
except Exception: # pragma: no cover - exercised only in torch-less envs
|
| 55 |
+
_HAS_TORCH = False
|
| 56 |
+
|
| 57 |
+
# Genesis link: 64 hex zeros, identical to szl_governed_norm and szl_energy_core
|
| 58 |
+
# so the unified chain's genesis is byte-compatible with the per-kernel chains.
|
| 59 |
+
GENESIS = "0" * 64
|
| 60 |
+
|
| 61 |
+
# Default rounding precision for tensor fingerprints. MUST match
|
| 62 |
+
# szl_governed_norm._receipt._tensor_digest so a unified-chain norm receipt's
|
| 63 |
+
# out_digest is bit-identical to the standalone kernel's.
|
| 64 |
+
_DECIMALS = 6
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def tensor_digest(t: "Any", decimals: int = _DECIMALS) -> str:
|
| 68 |
+
"""Deterministic SHA3-256 over a tensor's rounded float32 contents.
|
| 69 |
+
|
| 70 |
+
Identical scheme to szl_governed_norm._receipt._tensor_digest: round to a
|
| 71 |
+
fixed number of decimals, integerize, hash the raw little-endian bytes. This
|
| 72 |
+
makes the digest stable across devices/dtypes for the same logical values
|
| 73 |
+
(tiny FP noise won't change it). Integrity fingerprint, NOT a signature.
|
| 74 |
+
|
| 75 |
+
Falls back to hashing the repr only if torch is unavailable (headless
|
| 76 |
+
inspection); in a real kernel run torch is always present.
|
| 77 |
+
"""
|
| 78 |
+
if _HAS_TORCH and hasattr(t, "detach"):
|
| 79 |
+
flat = t.detach().to(torch.float32).reshape(-1)
|
| 80 |
+
scaled = (
|
| 81 |
+
torch.round(flat * (10 ** decimals)).to(torch.int64).cpu().numpy().tobytes()
|
| 82 |
+
)
|
| 83 |
+
return hashlib.sha3_256(scaled).hexdigest()
|
| 84 |
+
return hashlib.sha3_256(repr(t).encode("utf-8")).hexdigest()
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
class UnifiedReceiptChain:
|
| 88 |
+
"""Append-only, SHA3-256 hash-chained log spanning MANY kernel ops.
|
| 89 |
+
|
| 90 |
+
Each receipt body is canonical JSON with a fixed, sorted schema:
|
| 91 |
+
{seq, kernel, op, attrs, prev}
|
| 92 |
+
where:
|
| 93 |
+
seq -- 0-based position in the chain
|
| 94 |
+
kernel -- which suite member emitted it ('governed_norm', 'lambda_gate',
|
| 95 |
+
'energy_core', or a composed block name)
|
| 96 |
+
op -- the operation ('rms_norm', 'lambda_gate', 'measure_energy', ...)
|
| 97 |
+
attrs -- an op-agnostic, JSON-able dict of honest, reproducible
|
| 98 |
+
attributes (shapes, eps, out_digest, advisory Λ fields,
|
| 99 |
+
energy label/joules, ...). NEVER fabricated.
|
| 100 |
+
prev -- digest of the previous receipt (GENESIS for seq 0)
|
| 101 |
+
|
| 102 |
+
digest = SHA3-256 over the canonical JSON of {seq,kernel,op,attrs,prev}
|
| 103 |
+
(ts is excluded so the digest is reproducible offline).
|
| 104 |
+
|
| 105 |
+
verify() re-walks the chain and returns (ok, depth, first_break_seq):
|
| 106 |
+
it recomputes every digest and checks every prev-link, so ANY insertion,
|
| 107 |
+
deletion, reordering, or mutation of a recorded attribute is detected.
|
| 108 |
+
"""
|
| 109 |
+
|
| 110 |
+
def __init__(self) -> None:
|
| 111 |
+
self._lock = threading.RLock()
|
| 112 |
+
self._records: List[Dict[str, Any]] = []
|
| 113 |
+
|
| 114 |
+
# -- canonical hashing (sorted keys, tight separators, strict no-NaN) --
|
| 115 |
+
@staticmethod
|
| 116 |
+
def _digest_body(body: Dict[str, Any]) -> str:
|
| 117 |
+
raw = json.dumps(
|
| 118 |
+
body, sort_keys=True, separators=(",", ":"), allow_nan=False
|
| 119 |
+
).encode("utf-8")
|
| 120 |
+
return hashlib.sha3_256(raw).hexdigest()
|
| 121 |
+
|
| 122 |
+
def emit(self, kernel: str, op: str, attrs: Dict[str, Any]) -> Dict[str, Any]:
|
| 123 |
+
"""Append one op-agnostic receipt and return it (with digest + ts).
|
| 124 |
+
|
| 125 |
+
``attrs`` must be JSON-able and finite (no NaN/Inf) — a non-finite value
|
| 126 |
+
would make the receipt un-attestable by a strict third-party verifier,
|
| 127 |
+
so it is rejected at hash time by allow_nan=False. Callers screen
|
| 128 |
+
non-finite numbers to None/UNKNOWN upstream (the energy kernel already
|
| 129 |
+
does this).
|
| 130 |
+
"""
|
| 131 |
+
with self._lock:
|
| 132 |
+
prev = self._records[-1]["digest"] if self._records else GENESIS
|
| 133 |
+
seq = len(self._records)
|
| 134 |
+
body = {
|
| 135 |
+
"seq": seq,
|
| 136 |
+
"kernel": str(kernel),
|
| 137 |
+
"op": str(op),
|
| 138 |
+
"attrs": attrs,
|
| 139 |
+
"prev": prev,
|
| 140 |
+
}
|
| 141 |
+
digest = self._digest_body(body)
|
| 142 |
+
rec = dict(body, digest=digest, ts=time.time())
|
| 143 |
+
self._records.append(rec)
|
| 144 |
+
return rec
|
| 145 |
+
|
| 146 |
+
# -- convenience emitters that enforce the honesty schema per kernel ----
|
| 147 |
+
def emit_norm(self, op: str, x: "Any", out: "Any", eps: float) -> Dict[str, Any]:
|
| 148 |
+
"""Record a governed-norm op. out_digest matches szl_governed_norm."""
|
| 149 |
+
return self.emit(
|
| 150 |
+
"governed_norm",
|
| 151 |
+
op,
|
| 152 |
+
{
|
| 153 |
+
"in_shape": list(getattr(x, "shape", [])),
|
| 154 |
+
"in_dtype": str(getattr(x, "dtype", "")).replace("torch.", ""),
|
| 155 |
+
"eps": float(eps),
|
| 156 |
+
"out_digest": tensor_digest(out),
|
| 157 |
+
},
|
| 158 |
+
)
|
| 159 |
+
|
| 160 |
+
def emit_lambda(
|
| 161 |
+
self,
|
| 162 |
+
score: float,
|
| 163 |
+
threshold: float,
|
| 164 |
+
passed: bool,
|
| 165 |
+
k: int,
|
| 166 |
+
) -> Dict[str, Any]:
|
| 167 |
+
"""Record an ADVISORY Λ-gate evaluation.
|
| 168 |
+
|
| 169 |
+
``advisory`` is hard-coded True and ``lambda_status`` is stamped on every
|
| 170 |
+
entry so the chain itself is self-documenting: a recorded pass is NEVER
|
| 171 |
+
proven trust (Λ uniqueness = Conjecture 1, open).
|
| 172 |
+
"""
|
| 173 |
+
return self.emit(
|
| 174 |
+
"lambda_gate",
|
| 175 |
+
"lambda_gate",
|
| 176 |
+
{
|
| 177 |
+
"score": float(score),
|
| 178 |
+
"threshold": float(threshold),
|
| 179 |
+
"passed": bool(passed),
|
| 180 |
+
"k": int(k),
|
| 181 |
+
"advisory": True,
|
| 182 |
+
"lambda_status": "Conjecture 1 (open) — advisory only, NOT proven trust",
|
| 183 |
+
},
|
| 184 |
+
)
|
| 185 |
+
|
| 186 |
+
def emit_energy(self, measurement: Dict[str, Any]) -> Dict[str, Any]:
|
| 187 |
+
"""Record an energy reading VERBATIM (label + joules as-given).
|
| 188 |
+
|
| 189 |
+
``joules`` may be None (UNAVAILABLE/UNKNOWN) — it is recorded as None,
|
| 190 |
+
never upgraded to a fabricated number. ``label`` is the kernel's honest
|
| 191 |
+
MEASURED/SAMPLE/UNAVAILABLE_NO_NVML/ESTIMATE/UNKNOWN string.
|
| 192 |
+
"""
|
| 193 |
+
joules = measurement.get("joules", None)
|
| 194 |
+
return self.emit(
|
| 195 |
+
"energy_core",
|
| 196 |
+
"measure_energy",
|
| 197 |
+
{
|
| 198 |
+
"label": str(measurement.get("label", "UNKNOWN")),
|
| 199 |
+
"joules": (None if joules is None else float(joules)),
|
| 200 |
+
"source": str(measurement.get("source", "")),
|
| 201 |
+
},
|
| 202 |
+
)
|
| 203 |
+
|
| 204 |
+
# -- read surface --------------------------------------------------------
|
| 205 |
+
def head(self) -> str:
|
| 206 |
+
with self._lock:
|
| 207 |
+
return self._records[-1]["digest"] if self._records else GENESIS
|
| 208 |
+
|
| 209 |
+
def count(self) -> int:
|
| 210 |
+
with self._lock:
|
| 211 |
+
return len(self._records)
|
| 212 |
+
|
| 213 |
+
def tail(self, n: int = 10) -> List[Dict[str, Any]]:
|
| 214 |
+
with self._lock:
|
| 215 |
+
return list(self._records[-n:])
|
| 216 |
+
|
| 217 |
+
def kernels_touched(self) -> List[str]:
|
| 218 |
+
"""Distinct kernels that appear in the chain, in first-seen order.
|
| 219 |
+
|
| 220 |
+
The cross-kernel provenance summary: proof that a single auditable chain
|
| 221 |
+
actually spanned multiple suite members in one run.
|
| 222 |
+
"""
|
| 223 |
+
with self._lock:
|
| 224 |
+
seen: List[str] = []
|
| 225 |
+
for r in self._records:
|
| 226 |
+
if r["kernel"] not in seen:
|
| 227 |
+
seen.append(r["kernel"])
|
| 228 |
+
return seen
|
| 229 |
+
|
| 230 |
+
def verify(self):
|
| 231 |
+
"""Re-walk the chain. Returns (ok: bool, depth: int, first_break: int).
|
| 232 |
+
|
| 233 |
+
Recomputes every digest from {seq,kernel,op,attrs,prev} and checks each
|
| 234 |
+
prev-link. Detects insertion, deletion, reorder, or any attribute
|
| 235 |
+
mutation. first_break is the seq of the first bad record, or -1 if clean.
|
| 236 |
+
"""
|
| 237 |
+
with self._lock:
|
| 238 |
+
prev = GENESIS
|
| 239 |
+
for i, rec in enumerate(self._records):
|
| 240 |
+
body = {k: rec[k] for k in ("seq", "kernel", "op", "attrs", "prev")}
|
| 241 |
+
if rec["prev"] != prev or rec["digest"] != self._digest_body(body):
|
| 242 |
+
return (False, len(self._records), i)
|
| 243 |
+
prev = rec["digest"]
|
| 244 |
+
return (True, len(self._records), -1)
|
| 245 |
+
|
| 246 |
+
def to_json(self) -> str:
|
| 247 |
+
"""Export the full chain as canonical JSON for OFFLINE re-verification.
|
| 248 |
+
|
| 249 |
+
A third party can load this, recompute each digest, and confirm the
|
| 250 |
+
chain independently — no trust in the emitting process required.
|
| 251 |
+
"""
|
| 252 |
+
with self._lock:
|
| 253 |
+
return json.dumps(self._records, sort_keys=True, separators=(",", ":"))
|
| 254 |
+
|
| 255 |
+
@staticmethod
|
| 256 |
+
def verify_json(blob: str):
|
| 257 |
+
"""Verify an exported chain offline. Returns (ok, depth, first_break)."""
|
| 258 |
+
records = json.loads(blob)
|
| 259 |
+
prev = GENESIS
|
| 260 |
+
for i, rec in enumerate(records):
|
| 261 |
+
body = {k: rec[k] for k in ("seq", "kernel", "op", "attrs", "prev")}
|
| 262 |
+
if rec["prev"] != prev or rec["digest"] != UnifiedReceiptChain._digest_body(body):
|
| 263 |
+
return (False, len(records), i)
|
| 264 |
+
prev = rec["digest"]
|
| 265 |
+
return (True, len(records), -1)
|
build/torch-cpu/szl_kernels/_ops.py
ADDED
|
@@ -0,0 +1,220 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 2 |
+
# © 2026 SZL Holdings · Stephen P. Lutar · ORCID 0009-0001-0110-4173
|
| 3 |
+
"""Governed ops + a composed GovernedBlock, all writing ONE unified chain.
|
| 4 |
+
|
| 5 |
+
This module is the thin "suite" layer. It does NOT reimplement the kernels'
|
| 6 |
+
numerics — the canonical math lives in szl_governed_norm / szl_lambda_gate /
|
| 7 |
+
szl_energy_core. Here we provide:
|
| 8 |
+
|
| 9 |
+
* self-contained REFERENCE numerics (rms_norm, layer_norm, Λ aggregate) that
|
| 10 |
+
are byte-faithful ports of the published kernels, so this reference package
|
| 11 |
+
RUNS standalone with only torch installed (no Hub fetch needed for the
|
| 12 |
+
self-test). In production the suite delegates to the installed kernels via
|
| 13 |
+
get_kernel(); see NEXT_ARTIFACT_SPEC.md "Delegation".
|
| 14 |
+
* governed wrappers that emit op-agnostic receipts into a shared
|
| 15 |
+
UnifiedReceiptChain (cross-kernel provenance).
|
| 16 |
+
* GovernedBlock: a pre-norm transformer sub-block that composes governed-norm
|
| 17 |
+
+ an ADVISORY Λ gate + an energy measurement into ONE auditable forward
|
| 18 |
+
pass with an end-to-end receipt.
|
| 19 |
+
|
| 20 |
+
HONESTY: Λ stays advisory (Conjecture 1, open). Energy stays MEASURED-only
|
| 21 |
+
(None when no NVML — never fabricated). No benchmarks are claimed.
|
| 22 |
+
"""
|
| 23 |
+
from __future__ import annotations
|
| 24 |
+
|
| 25 |
+
import time
|
| 26 |
+
from typing import Any, Dict, Optional, Tuple
|
| 27 |
+
|
| 28 |
+
import torch
|
| 29 |
+
|
| 30 |
+
from ._chain import UnifiedReceiptChain
|
| 31 |
+
|
| 32 |
+
# ---------------------------------------------------------------------------
|
| 33 |
+
# Reference numerics — faithful ports of the published kernel math.
|
| 34 |
+
# (rms_norm / layer_norm mirror szl_governed_norm._norm; lambda_aggregate
|
| 35 |
+
# mirrors szl_lambda_gate._lambda. Kept minimal but numerically identical.)
|
| 36 |
+
# ---------------------------------------------------------------------------
|
| 37 |
+
def _rms_norm(x: torch.Tensor, weight: Optional[torch.Tensor], eps: float) -> torch.Tensor:
|
| 38 |
+
xf = x.to(torch.float32)
|
| 39 |
+
out = xf * torch.rsqrt(xf.pow(2).mean(-1, keepdim=True) + eps)
|
| 40 |
+
if weight is not None:
|
| 41 |
+
out = out * weight.to(torch.float32)
|
| 42 |
+
return out.to(x.dtype)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def _layer_norm(
|
| 46 |
+
x: torch.Tensor,
|
| 47 |
+
weight: Optional[torch.Tensor],
|
| 48 |
+
bias: Optional[torch.Tensor],
|
| 49 |
+
eps: float,
|
| 50 |
+
) -> torch.Tensor:
|
| 51 |
+
return torch.nn.functional.layer_norm(
|
| 52 |
+
x, (x.shape[-1],), weight=weight, bias=bias, eps=eps
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def _lambda_aggregate(axes: torch.Tensor, weights: Optional[torch.Tensor]) -> torch.Tensor:
|
| 57 |
+
"""Weighted geometric mean Λ(x)=∏ xᵢ^{wᵢ} with non-compensatory zero-routing.
|
| 58 |
+
|
| 59 |
+
Faithful to szl_lambda_gate: any zero or non-finite axis drives Λ to 0.
|
| 60 |
+
"""
|
| 61 |
+
cdt = torch.float32 if axes.dtype in (torch.float16, torch.bfloat16) else axes.dtype
|
| 62 |
+
xf = axes.to(cdt)
|
| 63 |
+
k = xf.shape[-1]
|
| 64 |
+
if weights is None:
|
| 65 |
+
w = torch.full((k,), 1.0 / k, dtype=cdt, device=xf.device)
|
| 66 |
+
else:
|
| 67 |
+
w = weights.to(cdt)
|
| 68 |
+
w = w / w.sum()
|
| 69 |
+
finite = torch.isfinite(xf)
|
| 70 |
+
xc = xf.clamp(0.0, 1.0)
|
| 71 |
+
bad = (~finite) | (xc <= 0.0)
|
| 72 |
+
any_bad = torch.any(bad, dim=-1)
|
| 73 |
+
safe = torch.where(bad, torch.ones_like(xc), xc)
|
| 74 |
+
val = torch.exp((torch.log(safe) * w).sum(dim=-1))
|
| 75 |
+
out = torch.where(any_bad, torch.zeros_like(val), val).clamp(0.0, 1.0)
|
| 76 |
+
return out.to(axes.dtype)
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
# ---------------------------------------------------------------------------
|
| 80 |
+
# Governed wrappers — numerics + a receipt into the SHARED unified chain.
|
| 81 |
+
# ---------------------------------------------------------------------------
|
| 82 |
+
def governed_rms_norm(
|
| 83 |
+
chain: UnifiedReceiptChain,
|
| 84 |
+
x: torch.Tensor,
|
| 85 |
+
weight: Optional[torch.Tensor] = None,
|
| 86 |
+
eps: float = 1e-6,
|
| 87 |
+
) -> torch.Tensor:
|
| 88 |
+
out = _rms_norm(x, weight, eps)
|
| 89 |
+
chain.emit_norm("rms_norm", x, out, eps)
|
| 90 |
+
return out
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def governed_layer_norm(
|
| 94 |
+
chain: UnifiedReceiptChain,
|
| 95 |
+
x: torch.Tensor,
|
| 96 |
+
weight: Optional[torch.Tensor] = None,
|
| 97 |
+
bias: Optional[torch.Tensor] = None,
|
| 98 |
+
eps: float = 1e-5,
|
| 99 |
+
) -> torch.Tensor:
|
| 100 |
+
out = _layer_norm(x, weight, bias, eps)
|
| 101 |
+
chain.emit_norm("layer_norm", x, out, eps)
|
| 102 |
+
return out
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def governed_lambda_gate(
|
| 106 |
+
chain: UnifiedReceiptChain,
|
| 107 |
+
axes: torch.Tensor,
|
| 108 |
+
weights: Optional[torch.Tensor] = None,
|
| 109 |
+
threshold: float = 0.5,
|
| 110 |
+
) -> Dict[str, Any]:
|
| 111 |
+
"""ADVISORY Λ gate that records an advisory receipt. NOT proven trust.
|
| 112 |
+
|
| 113 |
+
Returns a dict {score, passed, threshold, advisory=True}. ``passed`` is an
|
| 114 |
+
advisory, non-compensatory signal only (Λ uniqueness = Conjecture 1, open).
|
| 115 |
+
"""
|
| 116 |
+
score = _lambda_aggregate(axes, weights)
|
| 117 |
+
s = float(score.reshape(-1)[0]) if score.dim() else float(score)
|
| 118 |
+
passed = s >= float(threshold)
|
| 119 |
+
chain.emit_lambda(s, float(threshold), passed, int(axes.shape[-1]))
|
| 120 |
+
return {"score": s, "passed": passed, "threshold": float(threshold), "advisory": True}
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def governed_measure_energy(
|
| 124 |
+
chain: UnifiedReceiptChain,
|
| 125 |
+
measurement: Optional[Dict[str, Any]] = None,
|
| 126 |
+
) -> Dict[str, Any]:
|
| 127 |
+
"""Record an energy reading. MEASURED-only honesty.
|
| 128 |
+
|
| 129 |
+
If ``measurement`` is None we DO NOT fabricate joules: we record the honest
|
| 130 |
+
UNAVAILABLE_NO_NVML label with joules=None. (In production this delegates to
|
| 131 |
+
szl_energy_core.measure_energy(), which reads a real NVML cumulative-energy
|
| 132 |
+
delta when a GPU is present.)
|
| 133 |
+
"""
|
| 134 |
+
if measurement is None:
|
| 135 |
+
measurement = {
|
| 136 |
+
"joules": None,
|
| 137 |
+
"label": "UNAVAILABLE_NO_NVML",
|
| 138 |
+
"source": "no GPU/NVML in this reference run — joules NOT fabricated",
|
| 139 |
+
}
|
| 140 |
+
chain.emit_energy(measurement)
|
| 141 |
+
return measurement
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
# ---------------------------------------------------------------------------
|
| 145 |
+
# GovernedBlock — the flagship composition (candidate (c)) on the meta-package.
|
| 146 |
+
# ---------------------------------------------------------------------------
|
| 147 |
+
class GovernedBlock:
|
| 148 |
+
"""A pre-norm transformer sub-block with end-to-end cross-kernel provenance.
|
| 149 |
+
|
| 150 |
+
Forward pass, all into ONE shared chain, in order:
|
| 151 |
+
1. governed RMSNorm of the hidden state (governed_norm)
|
| 152 |
+
2. an ADVISORY Λ gate over caller-supplied governance axis scores
|
| 153 |
+
(lambda_gate) — recorded as advisory, never gating the math
|
| 154 |
+
3. an energy measurement of the step (energy_core)
|
| 155 |
+
4. a final 'block_forward' receipt binding the block's input/output digests
|
| 156 |
+
|
| 157 |
+
The result is a single hash-chained sequence a third party can re-walk to
|
| 158 |
+
confirm: norm ran, an advisory gate was evaluated, energy was accounted
|
| 159 |
+
(honestly labeled), and the block output is the one that was produced — with
|
| 160 |
+
nothing inserted or reordered between steps.
|
| 161 |
+
|
| 162 |
+
HONESTY: the Λ gate is ADVISORY; ``forward`` does NOT block, mask, or alter
|
| 163 |
+
the numerics based on the gate. The gate result is recorded for audit only.
|
| 164 |
+
Energy is MEASURED-only. No speed claims.
|
| 165 |
+
"""
|
| 166 |
+
|
| 167 |
+
def __init__(self, chain: Optional[UnifiedReceiptChain] = None) -> None:
|
| 168 |
+
self.chain = chain if chain is not None else UnifiedReceiptChain()
|
| 169 |
+
|
| 170 |
+
def forward(
|
| 171 |
+
self,
|
| 172 |
+
hidden: torch.Tensor,
|
| 173 |
+
weight: Optional[torch.Tensor] = None,
|
| 174 |
+
eps: float = 1e-6,
|
| 175 |
+
gov_axes: Optional[torch.Tensor] = None,
|
| 176 |
+
gov_weights: Optional[torch.Tensor] = None,
|
| 177 |
+
threshold: float = 0.5,
|
| 178 |
+
energy_measurement: Optional[Dict[str, Any]] = None,
|
| 179 |
+
) -> Dict[str, Any]:
|
| 180 |
+
c = self.chain
|
| 181 |
+
in_digest = __import__("hashlib").sha3_256(
|
| 182 |
+
__import__("json").dumps(list(hidden.shape)).encode()
|
| 183 |
+
).hexdigest()
|
| 184 |
+
|
| 185 |
+
# 1. governed normalization (numerics + receipt)
|
| 186 |
+
normed = governed_rms_norm(c, hidden, weight=weight, eps=eps)
|
| 187 |
+
|
| 188 |
+
# 2. ADVISORY Λ gate (recorded, does NOT alter numerics)
|
| 189 |
+
if gov_axes is None:
|
| 190 |
+
# default: neutral advisory axes; still recorded honestly as advisory
|
| 191 |
+
gov_axes = torch.tensor([0.9, 0.9, 0.9], dtype=torch.float32)
|
| 192 |
+
gate = governed_lambda_gate(c, gov_axes, weights=gov_weights, threshold=threshold)
|
| 193 |
+
|
| 194 |
+
# 3. energy measurement (MEASURED-only; None when no NVML)
|
| 195 |
+
energy = governed_measure_energy(c, energy_measurement)
|
| 196 |
+
|
| 197 |
+
# 4. bind the block I/O into a final receipt
|
| 198 |
+
from ._chain import tensor_digest
|
| 199 |
+
c.emit(
|
| 200 |
+
"governed_block",
|
| 201 |
+
"block_forward",
|
| 202 |
+
{
|
| 203 |
+
"in_shape_digest": in_digest,
|
| 204 |
+
"out_digest": tensor_digest(normed),
|
| 205 |
+
"gate_passed_advisory": bool(gate["passed"]),
|
| 206 |
+
"energy_label": str(energy.get("label", "UNKNOWN")),
|
| 207 |
+
},
|
| 208 |
+
)
|
| 209 |
+
|
| 210 |
+
ok, depth, brk = c.verify()
|
| 211 |
+
return {
|
| 212 |
+
"output": normed,
|
| 213 |
+
"gate": gate, # advisory only
|
| 214 |
+
"energy": energy, # MEASURED-only label/joules
|
| 215 |
+
"chain_head": c.head(),
|
| 216 |
+
"chain_depth": depth,
|
| 217 |
+
"chain_ok": ok,
|
| 218 |
+
"chain_first_break": brk,
|
| 219 |
+
"kernels_touched": c.kernels_touched(),
|
| 220 |
+
}
|