Add torch-universal variant for kernels 0.16 get_kernel (build.toml universal=true; no model conversion)
Browse filesFiles changed (9)
- build/torch-universal/metadata.jsonAdded+36
- build/torch-universal/szl_lambda_gate/__init__.pyAdded+198
- build/torch-universal/szl_lambda_gate/_lambda.pyAdded+504
- build/torch-universal/szl_lambda_gate/_ops.pyAdded+10
- build/torch-universal/szl_lambda_gate/governed_norm/__init__.pyAdded+279
- build/torch-universal/szl_lambda_gate/governed_norm/_norm.pyAdded+246
- build/torch-universal/szl_lambda_gate/governed_norm/_receipt.pyAdded+253
- build/torch-universal/szl_lambda_gate/governed_norm/layers.pyAdded+60
- build/torch-universal/szl_lambda_gate/layers.pyAdded+51
123456789101112131415161718192021222324252627282930313233343536{
"name": "szl-lambda-gate",
"version": 1,
"license": "Apache-2.0",
"universal": true,
"python-depends": [],
"id": "_szl_lambda_gate_universal_cto1",
"backend": {
"type": "cpu"
},
"lambda": "Conjecture 1 (advisory, never a theorem)",
"locked_8": [
"F1",
"F4",
"F7",
"F11",
"F12",
"F18",
"F19",
"F22"
],
"github_recipe": "build.toml [torch] universal=true; kernels 0.16 loads repo_type=kernel",
"digest": {
"algorithm": "sha256",
"files": {
"szl_lambda_gate/layers.py": "cde2de167d89002ad0cc63a4de205848f14eae0c649c19e2a8a96665a63806f2",
"szl_lambda_gate/_lambda.py": "7c8a04eeaa1d7851b99b498c6b85d3556da6cab1b0adc274e42ff2a3814353ee",
"szl_lambda_gate/_ops.py": "6adf1dc42e7a9e6da914e304da9720438e59c234104e11f3e5ccaa45ecee23b6",
"szl_lambda_gate/__init__.py": "3d65508cdf9b9dc2d525cdd2063e432752d42894cd96f84efa5f27866dfaf126",
"szl_lambda_gate/governed_norm/layers.py": "d79c83355cb2332b9d0e9d98584b86434e486532e27d30652df10158b30fc37b",
"szl_lambda_gate/governed_norm/_norm.py": "cf72ace281ec86c504426f75e23eebdb661a1e3a12e4dfcc6c8b9fa634b03942",
"szl_lambda_gate/governed_norm/_receipt.py": "db1244bd184affdca929bd38ac728b2696f82ad565aaf82d14ca3845d4d748a9",
"szl_lambda_gate/governed_norm/__init__.py": "50fe4fb09a165d0ae9a781f0ef3515388c752a14cde95f73687854f59a7dfadc"
}
}
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198# SPDX-License-Identifier: Apache-2.0# © 2026 SZL Holdings · Stephen P. Lutar · ORCID 0009-0001-0110-4173"""szl_lambda_gate — the Lambda-Spine aggregator (Λ) as a universal kernel.
A pure-PyTorch (universal) kernel from SZL Holdings for the Hugging FaceKernel Hub. It ports the canonical Λ aggregator into a differentiable,torch.compile-friendly torch op:
Λ(x) = ∏ xᵢ^{wᵢ}, Σwᵢ = 1, wᵢ > 0, xᵢ ∈ [0,1] (weighted geometric mean)
plus an ADVISORY governance gate (Λ vs threshold), the four carried axioms asreal runtime self-checks, and pure nn.Module layers.
Load from the Hub:
import torch from kernels import get_kernel
lg = get_kernel("SZLHOLDINGS/szl-lambda-gate") axes = torch.tensor([0.9, 0.8, 0.95]) # axis scores in [0,1] score = lg.lambda_aggregate(axes) # Λ(x) ∈ [0,1] res = lg.lambda_gate(axes, threshold=0.5) # ADVISORY pass/fail print(res.score, res.passed, res.advisory)
WHAT Λ IS / IS NOT (HONESTY — SZL Holdings doctrine v11): Λ is the weighted-geometric-mean aggregator — a non-compensatory, ADVISORY way to roll axis scores in [0,1] into one number (any zeroed axis zeroes the aggregate). It is NOT "proven trust" and NOT a closed theorem: Λ-uniqueness remains Conjecture 1 (OPEN — an unresolved CAUCHY_ND step plus a missing symmetry axiom). Label it honestly everywhere; a gate "pass" is advisory.
PROVENANCE: backed by the Lean 4 formalization szl-holdings/lutar-lean (749 declarations / 14 axioms / 163 tracked sorries), DOI 10.5281/zenodo.20434308 (lutar-lean). Λ uniqueness = Conjecture 1 (open)."""from typing import Optional
import torch
from . import layers # noqa: F401 (must be importable for Hub layer mapping)# CONSOLIDATION (Wave D): the governed-norm universal kernel is folded in here# as a subpackage so szl-lambda-gate is the ONE canonical kernels package. The# source repo szl-holdings/szl-governed-norm is DEPRECATED and points here;# nothing was deleted (additive, reversible copy). Λ stays Conjecture 1.from . import governed_norm # noqa: F401 (folded-in governed normalization kernels)from ._lambda import YUYAY_AXES, YUYAY_FLOORS, LambdaGateResultfrom ._lambda import find_axiom_violation as _find_axiom_violationfrom ._lambda import is_bounded_by_max as _is_bounded_by_maxfrom ._lambda import is_egyptian_exact as _is_egyptian_exactfrom ._lambda import is_homogeneous as _is_homogeneousfrom ._lambda import is_monotone as _is_monotonefrom ._lambda import lambda_aggregate as _lambda_aggregatefrom ._lambda import lambda_gate as _lambda_gatefrom ._lambda import lambda_gate_batch as _lambda_gate_batchfrom ._lambda import selfcheck as _selfcheckfrom ._lambda import yuyay_weights as _yuyay_weights
__all__ = [ "lambda_aggregate", "lambda_gate", "lambda_gate_batch", "LambdaGateResult", "is_monotone", "is_egyptian_exact", "is_bounded_by_max", "is_homogeneous", "find_axiom_violation", "selfcheck", "yuyay_weights", "YUYAY_AXES", "YUYAY_FLOORS", "layers", "DOCTRINE_FOOTER", "PROVENANCE", "__version__", # ---- folded-in governed-norm kernels (Wave D consolidation) ---- "governed_norm", "rms_norm", "layer_norm", "fused_add_rms_norm",]
# ---- folded-in governed-norm surface (Wave D consolidation) ---------------- ## Convenience top-level re-exports of the governed normalization kernels that# were absorbed from szl-governed-norm. The full surface (ReceiptChain,# emit_receipt, receipt_* helpers, selfcheck, layers) lives under# ``szl_lambda_gate.governed_norm``. These are a DIFFERENT kernel family from Λ# (normalization, not the Λ aggregator); Λ itself remains Conjecture 1# (advisory, uniqueness OPEN) and is never described as proven trust.rms_norm = governed_norm.rms_normlayer_norm = governed_norm.layer_normfused_add_rms_norm = governed_norm.fused_add_rms_norm
__version__ = "0.2.0"DOCTRINE_FOOTER = ( "SZL Holdings · Λ = Conjecture 1 (ADVISORY, weighted geometric mean) · " "uniqueness OPEN · NOT proven trust · honesty over checklist")PROVENANCE = { "lean_repo": "szl-holdings/lutar-lean", "lean_declarations": 749, "lean_axioms": 14, "lean_tracked_sorries": 163, "doi_lutar_lean": "10.5281/zenodo.20434308", "lambda_status": "Conjecture 1 (open) — uniqueness unproven; advisory only",}
def lambda_aggregate( axes: torch.Tensor, weights: Optional[torch.Tensor] = None,) -> torch.Tensor: """Λ(x) = ∏ xᵢ^{wᵢ}, the weighted geometric mean over the last dim of axes.
See ``szl_lambda_gate._lambda.lambda_aggregate``. Axis scores in [0,1], uniform weights when ``weights`` is None. Differentiable, batched, and torch.compile-friendly. ADVISORY — NOT proven trust. """ return _lambda_aggregate(axes, weights=weights)
def lambda_gate( axes: torch.Tensor, weights: Optional[torch.Tensor] = None, threshold: float = 0.5,) -> LambdaGateResult: """ADVISORY Λ governance gate: returns LambdaGateResult(score, passed, threshold, advisory). ``passed`` = Λ(axes) >= threshold. ``threshold`` must lie within Λ's range [0,1] (a value outside it is a misconfiguration — a negative threshold would advisory-pass a fully-failing Λ=0 candidate — and is rejected). A pass is an advisory, non-compensatory signal — NOT proven trust (Λ = Conjecture 1). """ return _lambda_gate(axes, weights=weights, threshold=threshold)
def lambda_gate_batch( candidates: torch.Tensor, weights: Optional[torch.Tensor] = None, threshold: float = 0.5,) -> LambdaGateResult: """ADVISORY batch gate over many candidate action-vectors (shape (..., N, k)).
The realistic per-inference-step call: score all N candidates at once and return the advisory pass mask. Returns LambdaGateResult(score, passed, threshold, advisory) with score/passed of shape (..., N). ``threshold`` must lie within Λ's range [0,1] (same domain guard as ``lambda_gate``). NOT proven trust. """ return _lambda_gate_batch(candidates, weights=weights, threshold=threshold)
def yuyay_weights(dtype: torch.dtype = torch.float64, device=None) -> torch.Tensor: """Canonical 13-axis Yuyay Λ weight vector (uniform 1/13), ADVISORY only.
Use as ``weights`` over the 13 ``YUYAY_AXES``. The yuyay_v3 gate is a conjunctive AND with per-axis floors (``YUYAY_FLOORS``); this Λ roll-up is the weighted geometric mean and is ADVISORY — NOT proven trust. """ return _yuyay_weights(dtype=dtype, device=device)
def find_axiom_violation(k=5, trials=200, weights=None, seed=0, tol=1e-6): """Random-search for any A1–A4 violation; returns (axiom, axes, weights) or None. An honest falsification attempt — finding nothing is evidence, not a proof (Λ-uniqueness is Conjecture 1, open). """ return _find_axiom_violation(k=k, trials=trials, weights=weights, seed=seed, tol=tol)
def selfcheck(k=5, trials=64, seed=0) -> dict: """Expose the A1–A4 empirical self-checks + version as a single verdict dict.
Callable as get_kernel(...).selfcheck(). EMPIRICAL checks on sampled inputs, NOT a proof of Λ-uniqueness (Conjecture 1, open). Advisory only. """ return _selfcheck(k=k, trials=trials, seed=seed)
# ---- axiom runtime self-checks (real, verifiable; NOT a uniqueness proof) -- #def is_monotone(axes, weights=None, delta=0.05, tol=1e-7) -> bool: """A1 IsMonotone self-check: Λ is non-decreasing in each axis (on this data).""" return _is_monotone(axes, weights=weights, delta=delta, tol=tol)
def is_egyptian_exact(c, k=3, weights=None, tol=1e-5) -> bool: """A3 IsEgyptianExact self-check: Λ(c, …, c) = c.""" return _is_egyptian_exact(c, k=k, weights=weights, tol=tol)
def is_bounded_by_max(axes, weights=None, tol=1e-6) -> bool: """A4 IsBounded self-check: Λ(x) ≤ maxᵢ xᵢ.""" return _is_bounded_by_max(axes, weights=weights, tol=tol)
def is_homogeneous(axes, t, weights=None, tol=1e-5) -> bool: """A2 IsHomogeneous(degree 1) self-check: Λ(t·x) = t·Λ(x).""" return _is_homogeneous(axes, t, weights=weights, tol=tol)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504# SPDX-License-Identifier: Apache-2.0# © 2026 SZL Holdings · Stephen P. Lutar · ORCID 0009-0001-0110-4173"""Pure-PyTorch Lambda-Spine aggregator (Λ) for the szl-lambda-gate kernel.
Λ(x) = ∏ xᵢ^{wᵢ}, Σwᵢ = 1, wᵢ > 0, xᵢ ∈ [0,1] (weighted geometric mean)
This is a TORCH port of the canonical pure-Python reference(packages/puriq-os/puriq_os/lambda_aggregator.py — saved alongside this kernelas lambda_aggregator_source.py). It is a correctness reference, computed vialogs in float32 for stability, differentiable (autograd works), andtorch.compile-friendly. Depends ONLY on torch + the Python standard library(a Kernel Hub requirement for universal kernels).
WHAT Λ IS / IS NOT (HONESTY — SZL Holdings doctrine v11): Λ is the *weighted-geometric-mean aggregator*: a non-compensatory way to combine axis scores in [0,1] into one number. It is ADVISORY governance signal — a conservative roll-up where any single zeroed axis drives the aggregate to 0. It is NOT "proven trust" and NOT a closed theorem. Its *uniqueness* (that the weighted geometric mean is the only aggregator satisfying the carried axioms) remains Conjecture 1 — OPEN (an unresolved CAUCHY_ND step plus a missing symmetry axiom in the Lean development). Do not describe Λ as proven trust anywhere.
PRIOR ART (honest attribution): the weighted geometric mean as a *less- compensatory* composite-indicator aggregator is established practice — the UN HDI (arithmetic→geometric switch, 2010), the OECD Handbook on Constructing Composite Indicators (2008), and the UNECE well-being guidelines all use it "to limit the compensation effect". The veto / cut-off idea (a single failing criterion blocks a pass regardless of the others) is the ELECTRE veto threshold / "satisficing" minimum-threshold screen. The 13-axis conjunctive form exposed by :func:`yuyay_weights` is SZL's own yuyay_v3 "Heart" gate. None of this makes Λ "proven trust"; the gate is ADVISORY (a11oy: "the advisory Λ trust score is a research conjecture, not a pass/fail oracle").
PROVENANCE: backed by the Lean 4 formalization szl-holdings/lutar-lean (749 declarations / 14 axioms / 163 tracked sorries), DOI 10.5281/zenodo.20434308 (lutar-lean). Λ uniqueness = Conjecture 1 (open).
Axioms carried (Lutar/Axioms.lean), available below as runtime self-checks: A1 IsMonotone — Λ is non-decreasing in each axis A2 IsHomogeneous — Λ(t·x) = t·Λ(x) (degree 1) A3 IsEgyptianExact — Λ(c,…,c) = c (the uniform-diagonal fixpoint) A4 IsBounded(by max) — Λ(x) ≤ maxᵢ xᵢ"""from typing import Optional
import torch
# Compute reductions/log-sum in float32 for stability when inputs are low# precision; keep float64 inputs in float64 (downcasting would break gradcheck# and silently lose precision)._SUPPORTED_DTYPES = (torch.float16, torch.bfloat16, torch.float32, torch.float64)
def _compute_dtype(in_dtype: torch.dtype) -> torch.dtype: return torch.float32 if in_dtype in (torch.float16, torch.bfloat16) else in_dtype
def _check_axes(axes: torch.Tensor) -> None: """Cheap, allocation-free metadata guards on the axis-score tensor.
Inspects only type / dtype / rank / last-dim, so it constant-folds under torch.compile and adds no tensor work on the happy path. """ if not isinstance(axes, torch.Tensor): raise TypeError(f"axes must be a torch.Tensor, got {type(axes).__name__}") if axes.dtype not in _SUPPORTED_DTYPES: raise TypeError( f"axes has unsupported dtype {axes.dtype}; " f"expected one of {tuple(str(d) for d in _SUPPORTED_DTYPES)}" ) if axes.dim() < 1: raise ValueError( "axes must have at least 1 dimension (the k axis scores live on " f"the last dim); got a {axes.dim()}-d tensor" ) if axes.shape[-1] < 1: raise ValueError("axes last dimension (k = number of axes) must be >= 1")
def _resolve_weights( axes: torch.Tensor, weights: Optional[torch.Tensor], cdt: torch.dtype,) -> torch.Tensor: """Return a normalized (Σw = 1) weight vector of shape (k,) in compute dtype.
``weights=None`` -> uniform 1/k (the Egyptian-exact diagonal). Otherwise the weights must be 1-D of length k, strictly positive, with a positive sum; they are normalized so Σwᵢ = 1. """ k = axes.shape[-1] if weights is None: return torch.full((k,), 1.0 / k, dtype=cdt, device=axes.device) if not isinstance(weights, torch.Tensor): raise TypeError(f"weights must be a torch.Tensor or None, got {type(weights).__name__}") if weights.device != axes.device: raise ValueError( f"weights is on device {weights.device} but axes is on {axes.device}; " "move them to the same device" ) if weights.dim() != 1 or weights.shape[0] != k: raise ValueError( f"weights must be 1-D with shape ({k},) to match the last dim of axes; " f"got shape {tuple(weights.shape)}" ) wf = weights.to(cdt) # Reject non-finite weights up front: a NaN/Inf weight is meaningless for a # governance roll-up and would silently poison the normalization. if not bool(torch.all(torch.isfinite(wf))): raise ValueError("weights must all be finite (no NaN/Inf)") # Positivity / sum guards mirror the pure-Python reference (wᵢ>0, Σw>0). if bool(torch.any(wf <= 0.0)): raise ValueError("weights must be strictly positive (wᵢ > 0)") sw = wf.sum() if not bool(sw > 0.0): raise ValueError("weights must sum to a positive value") return wf / sw
def lambda_aggregate( axes: torch.Tensor, weights: Optional[torch.Tensor] = None,) -> torch.Tensor: """Weighted geometric mean Λ(x) = ∏ xᵢ^{wᵢ} over the last dim of ``axes``.
Λ is the (ADVISORY) Lambda-Spine aggregator. Axis scores are expected in [0,1] and are clamped into [0,1]; uniform weights (1/k) are used when ``weights`` is None — the Egyptian-exact diagonal. Computed via logs in float32 (or float64 for float64 inputs) for numerical stability:
Λ(x) = exp( Σᵢ wᵢ · log(clamp(xᵢ, 0, 1)) )
Non-compensatory zero-routing (A4-consistent): any axis that is zero, OR that is NON-FINITE (NaN / ±Inf), is treated as a FAILING axis and drives the whole aggregate to exactly 0. This is the conservative governance choice — a garbage/invalid axis must never silently pass as a "perfect" (clamped-to-1) axis, and the output (and its gradient) stay finite and in [0,1] for every input. Zeros/non-finite axes are routed explicitly so log(0) = -inf and log(NaN) = NaN never produce a NaN value or gradient.
Args: axes: tensor of shape (..., k) of axis scores in [0,1]. Batched: the reduction is over the last dim, leading dims are batch. weights: optional 1-D tensor of shape (k,); None -> uniform. Normalized internally so Σwᵢ = 1.
Returns: tensor of shape (...) — Λ(x) ∈ [0,1] per batch row. Differentiable w.r.t. ``axes`` (and ``weights``).
HONESTY: this is a non-compensatory governance roll-up, NOT proven trust. Λ-uniqueness is Conjecture 1 (open). """ _check_axes(axes) in_dtype = axes.dtype cdt = _compute_dtype(in_dtype) xf = axes.to(cdt) w = _resolve_weights(axes, weights, cdt) # (k,), Σw=1
# A "bad" axis is one that fails non-compensatorily: a non-positive score # OR a non-finite value (NaN / ±Inf). clamp(+inf)=1 would otherwise count a # garbage axis as perfect, and clamp(NaN)=NaN would poison the product — we # treat BOTH as failing (zeroing) axes. Detect non-finite on the RAW input. finite_mask = torch.isfinite(xf) xc = xf.clamp(0.0, 1.0) bad_mask = (~finite_mask) | (xc <= 0.0) any_bad = torch.any(bad_mask, dim=-1) # (...)
# Replace bad axes with 1.0 before the log purely to keep log finite and the # gradient well-defined; the bad-axis contribution is reinstated via any_bad. safe = torch.where(bad_mask, torch.ones_like(xc), xc) logx = torch.log(safe) # (..., k) acc = (logx * w).sum(dim=-1) # (...) weighted log-sum val = torch.exp(acc) # (...) Λ before zero-routing
out = torch.where(any_bad, torch.zeros_like(val), val) out = out.clamp(0.0, 1.0) return out.to(in_dtype)
def lambda_gate( axes: torch.Tensor, weights: Optional[torch.Tensor] = None, threshold: float = 0.5,): """ADVISORY governance gate over Λ(x): score plus a pass/fail vs threshold.
Computes Λ(x) (see :func:`lambda_aggregate`) and compares it to ``threshold``: pass := Λ(x) >= threshold.
``threshold`` must be a finite float within Λ's range ``[0, 1]`` (Λ is the weighted geometric mean over [0,1]). This bound is enforced: a threshold below 0 or above 1 is meaningless for the advisory gate and is rejected — see the non-compensatory rationale below. The domain edges are valid: ``0.0`` admits every candidate (a permissive "no-gate" boundary) and ``1.0`` admits only a Λ == 1 candidate.
Returns a :class:`LambdaGateResult` namedtuple with fields: score — Λ(x) tensor of shape (...), in [0,1] passed — boolean tensor of shape (...), Λ(x) >= threshold threshold — the float threshold used advisory — always True; a STANDING reminder that this is a non-compensatory governance signal, NOT proven trust.
Non-compensatory threshold hardening: because a failing/garbage candidate (a zero, NaN, or ±Inf axis) is routed to Λ = 0, a NEGATIVE threshold would advisory-"pass" exactly those fully-failing candidates (0 >= t for t < 0) — the opposite of a conservative admission gate. A threshold above 1 can never pass. Both are misconfigurations, so the [0,1] domain is enforced up front rather than silently producing a wrong pass mask.
HONESTY: a "pass" is an ADVISORY signal only. Λ is the weighted-geometric- mean aggregator; its uniqueness is Conjecture 1 (open). Do not treat a pass as proven trust or a closed theorem. """ t = float(threshold) if t != t or t == float("inf") or t == float("-inf"): raise ValueError(f"threshold must be a finite float, got {threshold!r}") if t < 0.0 or t > 1.0: raise ValueError( "threshold must be within Λ's range [0, 1] (Λ is the weighted " f"geometric mean over [0,1]); got {t!r}. A threshold below 0 would " "advisory-pass a fully-failing (Λ=0) candidate and one above 1 can " "never pass — both signal a misconfigured gate." ) score = lambda_aggregate(axes, weights) passed = score >= t return LambdaGateResult(score=score, passed=passed, threshold=t, advisory=True)
def lambda_gate_batch( candidates: torch.Tensor, weights: Optional[torch.Tensor] = None, threshold: float = 0.5,): """ADVISORY batch gate: score MANY candidate action-vectors in one call.
This is the realistic way a model/agent uses the gate — one call per inference step that scores every proposed action-vector at once and returns the advisory pass mask (which candidates clear the threshold).
``candidates`` is a tensor of shape (..., N, k): the last dim ``k`` holds the per-axis scores of a single candidate, and the second-to-last dim ``N`` enumerates the candidates (any leading dims are extra batch). Equivalent to calling :func:`lambda_gate` on the whole tensor — the reduction is over the last dim — but named to make the agent-loop intent explicit. ``threshold`` inherits the same [0,1] domain guard as :func:`lambda_gate` (a threshold outside Λ's range is a misconfiguration and is rejected).
Returns a :class:`LambdaGateResult` with: score — Λ tensor of shape (..., N), one score per candidate passed — boolean mask of shape (..., N): score >= threshold threshold — the float threshold used advisory — always True (NOT proven trust)
HONESTY: the pass mask is an ADVISORY, non-compensatory signal. A "pass" is not proven trust; Λ-uniqueness is Conjecture 1 (open). """ _check_axes(candidates) if candidates.dim() < 2: raise ValueError( "candidates must be at least 2-D, shape (..., N, k): the last dim is " f"the k axis scores and the one before it enumerates the N candidates; " f"got a {candidates.dim()}-d tensor" ) # Reuse the single-call gate — its reduction over the last dim already gives # one score per candidate, so the (..., N) layout falls out for free. return lambda_gate(candidates, weights=weights, threshold=threshold)
# ---- A1..A4 axiom RUNTIME self-checks (real, verifiable) ------------------- ## These are honest empirical checks callers can run on concrete inputs. They# verify the carried axioms hold for THIS implementation on the given data —# they are NOT a proof of Λ-uniqueness (that is Conjecture 1, open).
def is_egyptian_exact( c: float, k: int = 3, weights: Optional[torch.Tensor] = None, tol: float = 1e-5,) -> bool: """A3 IsEgyptianExact: Λ(c, …, c) = c for a constant axis vector of length k.
Builds the uniform vector (c repeated k times) and checks Λ equals c within ``tol``. ``c`` is clamped into [0,1] to match the aggregator's domain. """ if k < 1: raise ValueError("k must be >= 1") cc = min(max(float(c), 0.0), 1.0) axes = torch.full((k,), cc, dtype=torch.float64) val = lambda_aggregate(axes, weights) return bool(torch.abs(val - cc) <= tol)
def is_bounded_by_max( axes: torch.Tensor, weights: Optional[torch.Tensor] = None, tol: float = 1e-6,) -> bool: """A4 IsBounded: Λ(x) ≤ maxᵢ xᵢ (over the last dim), within ``tol``.
Returns True iff the bound holds for every batch row. Non-finite axis values are clamped/zero-routed the same way the aggregator treats them, so the bound is checked on the conservative (finite) domain. """ _check_axes(axes) val = lambda_aggregate(axes, weights) # (...) xf = axes.to(_compute_dtype(axes.dtype)) # Mirror the aggregator: non-finite axes are failing (treated as 0) for the # purposes of the max bound, so the check matches the routed semantics. xf = torch.where(torch.isfinite(xf), xf, torch.zeros_like(xf)) mx = xf.clamp(0.0, 1.0).amax(dim=-1) # (...) return bool(torch.all(val.to(mx.dtype) <= mx + tol))
def is_homogeneous( axes: torch.Tensor, t: float, weights: Optional[torch.Tensor] = None, tol: float = 1e-5,) -> bool: """A2 IsHomogeneous (degree 1): Λ(t·x) = t·Λ(x) for scalar t in [0,1].
Verified on the clamped domain: both ``axes`` and ``t*axes`` must remain in [0,1] for the identity to be meaningful, so ``axes`` is clamped to [0,1] and ``t`` to [0,1] before the comparison. """ _check_axes(axes) tt = min(max(float(t), 0.0), 1.0) x = axes.to(torch.float64).clamp(0.0, 1.0) lhs = lambda_aggregate(x * tt, weights) rhs = tt * lambda_aggregate(x, weights) return bool(torch.all(torch.abs(lhs - rhs) <= tol))
def is_monotone( axes: torch.Tensor, weights: Optional[torch.Tensor] = None, delta: float = 0.05, tol: float = 1e-7,) -> bool: """A1 IsMonotone: Λ is non-decreasing in each axis.
For each axis j, nudges that axis UP by ``delta`` (clamped to stay ≤ 1) on every batch row and checks Λ does not decrease (within ``tol``). Rows that cannot move (already at 1) are skipped for that axis. A real check on the given data — not a symbolic proof. """ _check_axes(axes) x = axes.to(torch.float64).clamp(0.0, 1.0) base = lambda_aggregate(x, weights) k = x.shape[-1] ok = True for j in range(k): bumped = x.clone() bumped[..., j] = (bumped[..., j] + float(delta)).clamp(0.0, 1.0) bumped_val = lambda_aggregate(bumped, weights) # Λ must not go DOWN when an axis goes UP. ok = ok and bool(torch.all(bumped_val - base >= -tol)) return ok
# ---- Adversarial axiom search (honest: a falsification attempt) ------------ #def find_axiom_violation( k: int = 5, trials: int = 200, weights: Optional[torch.Tensor] = None, seed: Optional[int] = 0, tol: float = 1e-6,): """Random-search for ANY A1–A4 violation on random axis/weight draws.
Returns the first ``(axiom, axes, weights)`` triple that violates a carried axiom within ``tol``, or ``None`` if none is found in ``trials`` draws. This is an honest FALSIFICATION attempt on this implementation — finding nothing is empirical evidence, NOT a proof (Λ-uniqueness is Conjecture 1, open). """ gen = torch.Generator() if seed is not None: gen.manual_seed(int(seed)) for _ in range(int(trials)): x = torch.rand(k, generator=gen, dtype=torch.float64) w = weights if w is None: w = torch.rand(k, generator=gen, dtype=torch.float64) + 1e-3 # A3 on a constant draw c = float(torch.rand(1, generator=gen).item()) if not is_egyptian_exact(c, k=k, weights=w, tol=max(tol, 1e-5)): return ("A3_IsEgyptianExact", torch.full((k,), c, dtype=torch.float64), w) # A4 bounded-by-max if not is_bounded_by_max(x, w, tol=max(tol, 1e-6)): return ("A4_IsBounded", x, w) # A2 homogeneous at a random t t = float(torch.rand(1, generator=gen).item()) if not is_homogeneous(x, t, weights=w, tol=max(tol, 1e-5)): return ("A2_IsHomogeneous", x, w) # A1 monotone (leave headroom so an up-bump stays in range) if not is_monotone(x * 0.9, w, tol=max(tol, 1e-7)): return ("A1_IsMonotone", x * 0.9, w) return None
# ---- Canonical 13-axis Yuyay preset (ADVISORY ONLY) ------------------------ ## SZL's own yuyay_v3 "Heart" gate is a 13-axis CONJUNCTIVE-AND screen (each axis# independently clears its floor — no compensation). We expose its published# axis NAMES and per-axis FLOORS as advisory metadata, and a uniform Λ weight# vector over the 13 axes. This is ADVISORY: Λ here is still the weighted# geometric mean, and a "pass" is a research-conjecture signal, NOT proven# trust. Source: yuyay_v3 spec (Lutar, 2026).YUYAY_AXES = ( "moralGrounding", "measurabilityHonesty", "empiricalGrounding", "logicalConsistency", "sourceTransparency", "reproducibility", "licenseHygiene", "scopeDiscipline", "claimCalibration", "evalAwareness", "deceptionKeywords", "conflictingDirectives", "reversalDirective",)# Published per-axis advisory floors for the CONJUNCTIVE screen: two "sacred"# axes at 0.95, seven "structural" at 0.90, four "introspection" at 0.90.YUYAY_FLOORS = ( 0.95, 0.95, # sacred 0.90, 0.90, 0.90, 0.90, 0.90, 0.90, 0.90, # structural (7) 0.90, 0.90, 0.90, 0.90, # introspection (4))
def yuyay_weights( dtype: torch.dtype = torch.float64, device: Optional[torch.device] = None,) -> torch.Tensor: """Canonical 13-axis Yuyay Λ weight vector (uniform 1/13), ADVISORY only.
Returns a length-13 weight tensor for use as the ``weights`` argument to :func:`lambda_aggregate` / :func:`lambda_gate` over the 13 :data:`YUYAY_AXES`. Uniform by default (the Egyptian-exact diagonal). The published yuyay_v3 gate is a conjunctive AND with per-axis floors (:data:`YUYAY_FLOORS`); the Λ roll-up here is the weighted geometric mean and is ADVISORY — NOT proven trust (Λ-uniqueness is Conjecture 1, open). """ k = len(YUYAY_AXES) return torch.full((k,), 1.0 / k, dtype=dtype, device=device)
# ---- Kernel self-check surface --------------------------------------------- #def selfcheck( k: int = 5, trials: int = 64, seed: Optional[int] = 0,) -> dict: """Run the A1–A4 empirical self-checks and report a verdict + version.
Returns a dict: version — kernel version string axioms — {A1..A4: bool} empirical pass on sampled inputs all_axioms_hold — bool, every sampled axiom check passed adversarial — {trials, violation} from a random falsification search (violation is None when no violation was found) advisory — always True lambda_status — Conjecture 1 (open) honesty string
HONESTY: these are EMPIRICAL checks on sampled inputs, NOT a proof of Λ-uniqueness (Conjecture 1, open). A clean run is evidence, not proof. """ x = torch.rand(k, dtype=torch.float64) * 0.9 # headroom for the A1 up-bump w = torch.rand(k, dtype=torch.float64) + 1e-3 axioms = { "A1_IsMonotone": is_monotone(x, w), "A2_IsHomogeneous": is_homogeneous(x, float(torch.rand(1).item()), weights=w), "A3_IsEgyptianExact": is_egyptian_exact(float(torch.rand(1).item()), k=k, weights=w), "A4_IsBounded": is_bounded_by_max(x, w), } violation = find_axiom_violation(k=k, trials=trials, seed=seed) return { "version": __version__, "axioms": axioms, "all_axioms_hold": all(axioms.values()) and violation is None, "adversarial": {"trials": int(trials), "violation": violation}, "advisory": True, "lambda_status": "Conjecture 1 (open) — uniqueness unproven; advisory only", }
# Kept in sync with the package __version__ (single source of truth lives in# __init__; duplicated here so _lambda is importable/selfcheck-able standalone).__version__ = "0.2.0"
# Namedtuple result type for the gate. Defined after functions so docstrings# above can reference it; imported by __init__ and layers.from collections import namedtuple # noqa: E402
LambdaGateResult = namedtuple( "LambdaGateResult", ["score", "passed", "threshold", "advisory"])12345678910# SPDX-License-Identifier: Apache-2.0# Auto-style ops namespace shim for the universal kernel. Unique suffix lets# multiple versions load in the same process (Kernel Hub requirement).import torch
ops = torch.ops._szl_lambda_gate_20260623081355
def add_op_namespace_prefix(op_name: str) -> str: return f"_szl_lambda_gate_20260623081355::{op_name}"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279# SPDX-License-Identifier: Apache-2.0# © 2026 SZL Holdings · Stephen P. Lutar · ORCID 0009-0001-0110-4173"""szl_lambda_gate.governed_norm — governed normalization kernels (folded in).
CONSOLIDATION (Wave D): this subpackage is the ``szl-governed-norm`` universalkernel folded into the canonical ``szl-lambda-gate`` kernels package so the twoduplicate micro-repos become ONE canonical home. The source repo``szl-holdings/szl-governed-norm`` is DEPRECATED (see its DEPRECATED.md) andpoints here; nothing was deleted — this is the additive, reversible copy.
It provides correctness-verified RMSNorm and LayerNorm that run on CPU and CUDAand are torch.compile-friendly, plus an optional *governed* path that emitscontent-addressed, SHA3-256 hash-chained receipts of each call — provenance atthe kernel layer, in the spirit of the a11oy governed-AI platform(https://a-11-oy.com).
Usage (as a subpackage of the canonical kernel)::
import torch from szl_lambda_gate import governed_norm as gn
print(gn.selfcheck()) # one-shot correctness + receipt check x = torch.randn(4, 1024, dtype=torch.float16) y = gn.rms_norm(x, eps=1e-6) # plain path y2 = gn.rms_norm(x, eps=1e-6, governed=True) # records to the default chain chain = gn.ReceiptChain() y3 = gn.rms_norm(x, eps=1e-6, chain=chain) # records into YOUR chain only print(chain.verify()) # (ok, depth, first_break_seq)
Honesty: this is a universal (pure-Python) kernel — a correctness reference,not a hand-tuned CUDA speed record. No fabricated benchmarks. Itsdifferentiator is verifiable governance, not raw FLOPs. Λ = Conjecture 1(advisory, uniqueness OPEN) — never described as proven trust anywhere.
Note on torch.compile: every op is torch.compile(fullgraph=True)-compatible.Receipt emission is an eager-only side effect (it hashes materialized tensorbytes), so when a *governed* call is captured into a compiled graph thenumerics are unchanged but NO receipt is recorded — govern at the eager auditboundary. This is documented honestly and covered by tests."""from typing import Any, Dict, List, Optional, Tuple
import torch
from . import layers # noqa: F401 (must be importable for Hub layer mapping)from ._norm import fused_add_rms_norm as _fused_add_rms_normfrom ._norm import layer_norm as _layer_normfrom ._norm import rms_norm as _rms_normfrom ._receipt import _GENESIS as _GENESIS_HEADfrom ._receipt import ReceiptChain, default_chain, emit_receipt
__all__ = [ "rms_norm", "layer_norm", "fused_add_rms_norm", "layers", "ReceiptChain", "emit_receipt", "receipt_head", "receipt_count", "receipt_tail", "receipt_verify", "selfcheck", "DOCTRINE_FOOTER", "__version__",]
__version__ = "0.2.0"DOCTRINE_FOOTER = ( "SZL Holdings · governed normalization · provenance at the kernel layer · " "Lambda = Conjecture 1 (advisory) · honesty over checklist")
def _is_tracing() -> bool: """True while torch.compile / Dynamo is tracing this code.
Receipt emission reads materialized tensor bytes (hashing on CPU), which is an inherently eager, side-effecting host operation that cannot live inside a traced FX graph — so under torch.compile we skip the emit. This keeps EVERY op torch.compile(fullgraph=True)-compatible while remaining honest: when a governed call is captured into a compiled graph, NO receipt is recorded (the numerics are unchanged and identical to the eager path). Governance is intended for the eager audit boundary; record receipts there. """ is_compiling = getattr(torch.compiler, "is_compiling", None) return bool(is_compiling()) if is_compiling is not None else False
def _emit( chain: Optional[ReceiptChain], op: str, x: torch.Tensor, out: torch.Tensor, eps: float, sign_key: Optional[Any] = None, organ: str = "szl-governed-norm",) -> None: """Append a receipt to ``chain`` (or the process default chain if None).
No-op while torch.compile is tracing (see ``_is_tracing``). When ``sign_key`` (a PEM ECDSA-P256 private key) is supplied and szl-receipt is installed, the receipt carries an additive DSSE ``signature`` envelope; keyless is UNSIGNED-honest. """ if _is_tracing(): return target = chain if chain is not None else default_chain() target.emit(op, x, out, eps, sign_key=sign_key, organ=organ)
def rms_norm( x: torch.Tensor, weight: Optional[torch.Tensor] = None, eps: float = 1e-6, governed: bool = False, chain: Optional[ReceiptChain] = None, sign_key: Optional[Any] = None, organ: str = "szl-governed-norm",) -> torch.Tensor: """RMSNorm over the last dim.
If ``governed=True``, append an audit receipt. By default the receipt goes to the process-wide default chain (convenient). Pass your own ``chain`` (a ``ReceiptChain`` instance) to record into a caller-owned chain instead — this avoids global-state contention when many threads/requests govern independently. Passing ``chain`` implies governance even if ``governed=False`` is left at its default. Pass ``sign_key`` (PEM ECDSA-P256) to additively sign the receipt via szl-receipt. """ out = _rms_norm(x, weight=weight, eps=eps) if governed or chain is not None: _emit(chain, "rms_norm", x, out, eps, sign_key=sign_key, organ=organ) return out
def layer_norm( x: torch.Tensor, weight: Optional[torch.Tensor] = None, bias: Optional[torch.Tensor] = None, eps: float = 1e-5, governed: bool = False, chain: Optional[ReceiptChain] = None, sign_key: Optional[Any] = None, organ: str = "szl-governed-norm",) -> torch.Tensor: """LayerNorm over the last dim.
If ``governed=True`` (or a ``chain`` is supplied), append an audit receipt to ``chain`` when given, otherwise to the process default chain. See ``rms_norm`` for the per-call ``chain`` rationale and ``sign_key``. """ out = _layer_norm(x, weight=weight, bias=bias, eps=eps) if governed or chain is not None: _emit(chain, "layer_norm", x, out, eps, sign_key=sign_key, organ=organ) return out
def fused_add_rms_norm( x: torch.Tensor, residual: torch.Tensor, weight: Optional[torch.Tensor] = None, eps: float = 1e-6, governed: bool = False, chain: Optional[ReceiptChain] = None, sign_key: Optional[Any] = None, organ: str = "szl-governed-norm",) -> Tuple[torch.Tensor, torch.Tensor]: """Residual-add + RMSNorm (transformer block pattern).
Returns ``(y, new_residual)`` where ``new_residual = x + residual`` and ``y = rms_norm(new_residual, weight, eps)``. If ``governed=True`` (or a ``chain`` is supplied), append an audit receipt over the normalized output to ``chain`` when given, otherwise to the process default chain. Pass ``sign_key`` to additively sign the receipt via szl-receipt. """ out, new_residual = _fused_add_rms_norm(x, residual, weight=weight, eps=eps) if governed or chain is not None: _emit(chain, "fused_add_rms_norm", x, out, eps, sign_key=sign_key, organ=organ) return out, new_residual
# ---- governance receipt surface (operates on the default in-process chain) --def receipt_head() -> str: """SHA3-256 head of the governed-call receipt chain ('0'*64 if empty).""" return default_chain().head()
def receipt_count() -> int: """Number of governed calls recorded.""" return default_chain().count()
def receipt_tail(n: int = 10) -> List[Dict[str, Any]]: """Last n receipts.""" return default_chain().tail(n)
def receipt_verify() -> Dict[str, Any]: """Re-walk the receipt chain. Returns {ok, depth, first_break_seq}.""" ok, depth, brk = default_chain().verify() return {"ok": ok, "depth": depth, "first_break_seq": brk, "head": default_chain().head()}
# ---- one-shot self-verification --------------------------------------------def selfcheck() -> Dict[str, Any]: """Verify correctness + governance in a single call; never raises.
Runs a tiny, self-contained, CPU-only smoke test against PyTorch references so downstream code (and SZL's own a11oy / hatun-mcp) can confirm the loaded kernel is the real, working article before trusting it.
Checks (all on a *private, throwaway* ReceiptChain so the process default chain is never touched): * ``rms_norm`` matches a Llama-style float32 reference, * ``layer_norm`` matches ``torch.nn.functional.layer_norm``, * ``fused_add_rms_norm`` matches the unfused add-then-norm path, * a governed call emits exactly one receipt and the chain verifies.
Returns a JSON-able dict: ``{ok, version, checks: {name: bool}, receipt_ok, receipt_head, error}`` ``ok`` is True iff every check passed. On unexpected failure ``ok`` is False and ``error`` carries the message — this function is designed to be safe to call in a health probe and will not raise. """ checks: Dict[str, bool] = {} receipt_ok = False receipt_head = _GENESIS_HEAD error = None try: torch.manual_seed(0) x = torch.randn(4, 64, dtype=torch.float32) w = torch.randn(64, dtype=torch.float32) b = torch.randn(64, dtype=torch.float32) res = torch.randn(4, 64, dtype=torch.float32) eps_r, eps_l = 1e-6, 1e-5
# rms_norm vs Llama-style fp32 reference xf = x.to(torch.float32) ref_rms = (xf * torch.rsqrt(xf.pow(2).mean(-1, keepdim=True) + eps_r)) * w checks["rms_norm"] = bool( torch.allclose(rms_norm(x, weight=w, eps=eps_r), ref_rms, rtol=1e-5, atol=1e-5) )
# layer_norm vs torch reference ref_ln = torch.nn.functional.layer_norm(x, (64,), weight=w, bias=b, eps=eps_l) checks["layer_norm"] = bool( torch.allclose(layer_norm(x, weight=w, bias=b, eps=eps_l), ref_ln, rtol=1e-5, atol=1e-5) )
# fused_add_rms_norm vs unfused path y_f, new_res = fused_add_rms_norm(x, res, weight=w, eps=eps_r) h = x.to(torch.float32) + res.to(torch.float32) ref_y = rms_norm(h.to(x.dtype), weight=w, eps=eps_r) checks["fused_add_rms_norm"] = bool( torch.allclose(y_f, ref_y, rtol=1e-5, atol=1e-5) and torch.allclose(new_res, h.to(x.dtype), rtol=1e-6, atol=1e-6) )
# governance on a private chain: one emit, chain verifies probe_chain = ReceiptChain() rms_norm(x, weight=w, eps=eps_r, chain=probe_chain) ok, depth, brk = probe_chain.verify() receipt_ok = bool(ok and depth == 1 and brk == -1) receipt_head = probe_chain.head() checks["governance"] = receipt_ok except Exception as exc: # never raise from a health probe error = f"{type(exc).__name__}: {exc}"
ok = bool(checks) and all(checks.values()) and error is None return { "ok": ok, "version": __version__, "checks": checks, "receipt_ok": receipt_ok, "receipt_head": receipt_head, "error": error, }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246# SPDX-License-Identifier: Apache-2.0# © 2026 SZL Holdings · Stephen P. Lutar · ORCID 0009-0001-0110-4173"""Pure-PyTorch normalization primitives for the SZL governed-norm kernel.
These are correctness-verified reference implementations (RMSNorm, LayerNorm,and the residual-fused RMSNorm pattern used by transformer blocks) written inpure PyTorch. They run on CPU and CUDA, are torch.compile-friendly, and dependONLY on torch + the Python standard library (a Kernel Hub requirement foruniversal kernels).
HONESTY: this is a *universal* (pure-Python) kernel. It does NOT ship ahand-tuned CUDA/Triton binary, so it is a correctness reference, not aspeed record. We make no fabricated benchmark claims. Where it adds valueis the optional *governed* path (see _receipt.py): every normalization callcan emit a content-addressed, hash-chained receipt of its inputs/outputs sothe operation is auditable — SZL Holdings' provenance doctrine applied atthe kernel layer.
Numerical convention (all ops): reductions and the normalization math arecomputed in float32 for stability, then the result is cast back to the inputdtype. This is the standard Llama-style convention and is what makesfloat16 / bfloat16 inputs numerically well-behaved.
Validation convention: guards below are cheap, branch-only checks on metadata(dtype / ndim / shape / device) — they allocate nothing on the happy path andconstant-fold away under torch.compile, so they do not perturb traced graphs.They exist to turn silent broadcasting / device-mismatch bugs into clear,early errors. A zero-size normalized last dimension is rejected (normalizingover zero elements is undefined); a single-element last dimension is allowed(RMSNorm yields sign(x); LayerNorm yields 0, matching F.layer_norm).
Non-finite convention (NaN / Inf inputs): these ops do NOT sanitize theirinput. A NaN or Inf in the input propagates through the reduction and appearsin the output, exactly as it would in torch.nn.functional.layer_norm / ahand-written kernel. We deliberately do NOT silently replace non-finite values(that would hide upstream numerical bugs); detecting/handling them is thecaller's responsibility. This propagation behavior is covered by regressiontests so it cannot change unnoticed."""from typing import Optional
import torch
# Floating dtypes this kernel supports. Integer / complex inputs are rejected# early with a clear message rather than silently producing garbage._SUPPORTED_DTYPES = (torch.float16, torch.bfloat16, torch.float32, torch.float64)
def _compute_dtype(in_dtype: torch.dtype) -> torch.dtype: """Reduction/normalization compute dtype.
Low-precision inputs (fp16/bf16) are upcast to float32 for stability — the standard Llama-style convention. float64 inputs are NOT downcast: doing so would silently lose precision (and break gradcheck), so we keep float64. """ return torch.float32 if in_dtype in (torch.float16, torch.bfloat16) else in_dtype
def _check_input(x: torch.Tensor, name: str = "x") -> None: """Cheap, allocation-free guards on the primary input tensor.
Only inspects metadata (type / dtype / ndim), so it is constant-folded by torch.compile and adds no runtime tensor work on the happy path. """ if not isinstance(x, torch.Tensor): raise TypeError(f"{name} must be a torch.Tensor, got {type(x).__name__}") if x.dtype not in _SUPPORTED_DTYPES: raise TypeError( f"{name} has unsupported dtype {x.dtype}; " f"expected one of {tuple(str(d) for d in _SUPPORTED_DTYPES)}" ) if x.dim() < 1: raise ValueError( f"{name} must have at least 1 dimension (the normalized dim); " f"got a {x.dim()}-d tensor" ) # A zero-size normalized (last) dimension is mathematically undefined: # mean/RMS over zero elements is NaN, so normalization has no meaning. # Reject it early with a clear message instead of silently returning an # empty/NaN tensor (the classic shape-bug-masquerading-as-success case). if x.shape[-1] == 0: raise ValueError( f"{name} has a zero-size normalized last dimension {tuple(x.shape)}; " f"normalization over zero elements is undefined" )
def _check_affine( x: torch.Tensor, param: Optional[torch.Tensor], name: str,) -> None: """Validate an optional affine parameter (weight/bias/residual peer).
Enforces that the parameter is 1-D and matches the normalized (last) dimension, and lives on the same device as ``x``. This catches the classic silent-broadcast bug where a mis-shaped weight would broadcast instead of erroring. Metadata-only: no allocations. """ if param is None: return if not isinstance(param, torch.Tensor): raise TypeError(f"{name} must be a torch.Tensor or None, got {type(param).__name__}") if param.device != x.device: raise ValueError( f"{name} is on device {param.device} but x is on {x.device}; " f"move them to the same device" ) last = x.shape[-1] if param.dim() != 1 or param.shape[0] != last: raise ValueError( f"{name} must be 1-D with shape ({last},) to match the normalized " f"last dimension of x; got shape {tuple(param.shape)}" )
def _check_eps(eps: float) -> None: """eps must be a positive, finite scalar (rsqrt(var+eps) must be safe).""" e = float(eps) if not (e > 0.0) or e != e or e == float("inf"): raise ValueError(f"eps must be a positive finite float, got {eps!r}")
def rms_norm( x: torch.Tensor, weight: Optional[torch.Tensor] = None, eps: float = 1e-6,) -> torch.Tensor: """Root-mean-square layer normalization over the last dimension.
y = x / sqrt(mean(x^2, dim=-1) + eps) * weight
Computed in float32 for numerical stability, then cast back to the input dtype (the standard, correctness-preserving convention used by Llama-style RMSNorm). `weight` is optional; when omitted, no affine scale is applied.
Raises clear TypeError/ValueError on bad dtype, rank, eps, or a weight whose shape/device does not match x's normalized dimension. """ _check_input(x) _check_eps(eps) _check_affine(x, weight, "weight")
in_dtype = x.dtype xf = x.to(_compute_dtype(in_dtype)) variance = xf.pow(2).mean(dim=-1, keepdim=True) xf = xf * torch.rsqrt(variance + eps) out = xf.to(in_dtype) if weight is not None: out = out * weight return out
def layer_norm( x: torch.Tensor, weight: Optional[torch.Tensor] = None, bias: Optional[torch.Tensor] = None, eps: float = 1e-5,) -> torch.Tensor: """Standard layer normalization over the last dimension.
Mean/variance computed in float32 for stability, then cast back. Matches torch.nn.functional.layer_norm semantics for the normalized-shape = last dim case; verified against it in the test suite.
Raises clear TypeError/ValueError on bad dtype, rank, eps, or a weight/bias whose shape/device does not match x's normalized dimension. """ _check_input(x) _check_eps(eps) _check_affine(x, weight, "weight") _check_affine(x, bias, "bias")
in_dtype = x.dtype xf = x.to(_compute_dtype(in_dtype)) mean = xf.mean(dim=-1, keepdim=True) # Biased (population) variance = mean of squared deviations. We compute it # directly rather than via Tensor.var(unbiased=False): torch's .var emits a # "degrees of freedom <= 0" UserWarning when the normalized dim has a single # element, even though unbiased=False is well-defined there (variance 0). # Computing it ourselves matches F.layer_norm exactly and stays silent and # torch.compile(fullgraph=True)-clean for the single-element edge case. centered = xf - mean var = centered.pow(2).mean(dim=-1, keepdim=True) xf = centered * torch.rsqrt(var + eps) out = xf.to(in_dtype) if weight is not None: out = out * weight if bias is not None: out = out + bias return out
def fused_add_rms_norm( x: torch.Tensor, residual: torch.Tensor, weight: Optional[torch.Tensor] = None, eps: float = 1e-6,): """Residual-add followed by RMSNorm — the canonical transformer block pattern.
h = x + residual # updated residual stream y = rms_norm(h, weight, eps) return y, h
This mirrors the `fused_add_rms_norm` used in real LLM inference stacks (e.g. the pre-norm transformer block: the normalized output `y` feeds the sublayer, while the un-normalized sum `h` is carried forward as the next residual). We return BOTH so callers can thread the residual stream, which is exactly why the fused form exists.
HONESTY: "fused" here means *logically* fused (one Python op, one float32 cast path, the add done in float32 alongside the norm) — it is a correct, allocation-conscious pure-PyTorch reference, not a hand-written fused CUDA kernel. No speed claims are made.
The add is performed in float32 so that, for float16/bfloat16 inputs, the residual accumulation does not lose precision before normalization — this matches high-quality reference implementations. """ _check_input(x, "x") _check_input(residual, "residual") _check_eps(eps) if residual.shape != x.shape: raise ValueError( f"residual shape {tuple(residual.shape)} must equal x shape " f"{tuple(x.shape)} for the residual add" ) if residual.device != x.device: raise ValueError( f"residual is on device {residual.device} but x is on {x.device}; " f"move them to the same device" ) _check_affine(x, weight, "weight")
in_dtype = x.dtype cdt = _compute_dtype(in_dtype) # Add in compute dtype, keep both the normalized output and the residual. hf = x.to(cdt) + residual.to(cdt) new_residual = hf.to(in_dtype) variance = hf.pow(2).mean(dim=-1, keepdim=True) yf = hf * torch.rsqrt(variance + eps) out = yf.to(in_dtype) if weight is not None: out = out * weight return out, new_residual123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253# SPDX-License-Identifier: Apache-2.0# © 2026 SZL Holdings · Stephen P. Lutar · ORCID 0009-0001-0110-4173"""Content-addressed governance receipts for normalization calls.
SZL Holdings' provenance doctrine applied at the kernel layer: when anormalization runs in *governed* mode, it emits a small, deterministicreceipt describing the call — input shape/dtype, eps, and a SHA3-256 digestof the (quantized) output tensor — and hash-chains it to the previousreceipt. This makes a sequence of kernel calls independently auditablewithout trusting the caller.
HONESTY:- The digest is a real SHA3-256 over the output bytes (rounded to a fixed decimal precision so it is reproducible across runs/devices). It is an integrity fingerprint, NOT a cryptographic signature — we never claim it proves authorship. DSSE signing is a separate, out-of-band concern.- Receipts are kept in an in-process, append-only chain. Nothing is written to disk or the network from inside the kernel.- Stdlib + torch (+ numpy for the output digest) only — Kernel Hub universal-kernel requirement.- The canonical szl-receipt v0.2.0 evidence binding (``emit_receipt``) is ADDITIVE and IMPORT-GUARDED: with szl-receipt absent it returns ``None`` and the kernel runs unchanged. It binds subject / input-digest / output-digest / policy-id / energy; energy is the literal string "UNAVAILABLE" because this kernel measures NO joules — a value is never fabricated. Like the SHA3-256 chain, it is an EVIDENCE trail, NOT a proof of correctness."""import hashlibimport jsonimport threadingimport timefrom typing import Any, Dict, List, Optional, Union
import torch
_GENESIS = "0" * 64
# Logical signing-authority label stamped onto signature envelopes._ORGAN = "szl-governed-norm"
# Governing policy id bound into every canonical szl-receipt evidence binding._POLICY_ID = "szl-governed-norm/provenance@v1"
# This universal kernel measures NO joules. The honesty doctrine forbids# fabricating an energy value, so the canonical binding records the literal# string "UNAVAILABLE" rather than a placeholder number._ENERGY_UNAVAILABLE = "UNAVAILABLE"
def _maybe_sign( body: Dict[str, Any], sign_key: Optional[Union[str, bytes]], organ: str,) -> Optional[Dict[str, Any]]: """ADDITIVE szl-receipt signature layer over the receipt *body*.
Returns a DSSE envelope (from ``szl_receipt.sign_receipt``) covering the exact canonical body, or ``None`` when szl-receipt is not installed (the kernel then behaves exactly as before). Doctrine: with no *sign_key* the envelope is UNSIGNED-honest (``signed=False``); a signature is NEVER fabricated. This is distinct from and additive to the SHA3-256 chain integrity hash (``digest``) — szl-receipt's envelope carries its own SHA-256 ``digest``/``algo`` so the two integrity hashes are explicit. """ try: from szl_receipt import Receipt, sign_receipt except Exception: # noqa: BLE001 - signing is optional; absence is honest return None env = sign_receipt(Receipt(kind="governed-norm", body=body), sign_key, organ=organ) return env
def _tensor_digest(t: torch.Tensor, decimals: int = 6) -> str: """Deterministic SHA3-256 over a tensor's rounded float32 contents.
Rounding to a fixed number of decimals makes the digest stable across devices/dtypes for the same logical values (tiny FP noise won't change it). This is an integrity fingerprint, not a signature. """ flat = t.detach().to(torch.float32).reshape(-1) # Round to `decimals` places, integerize, hash the raw bytes. CPU move is # required to read bytes; kept O(n) and allocation-light. scaled = torch.round(flat * (10 ** decimals)).to(torch.int64).cpu().numpy().tobytes() h = hashlib.sha3_256() h.update(scaled) return h.hexdigest()
def _input_digest(x: torch.Tensor, eps: float) -> str: """SHA3-256 over the canonical JSON of a call's input spec.
Binds {input shape, dtype, eps} — the *shape* of the call, not the input bytes — so the receipt is a compact fingerprint of what produced the output. Deterministic and stdlib-only (json + hashlib). """ spec = { "in_shape": list(x.shape), "in_dtype": str(x.dtype).replace("torch.", ""), "eps": float(eps), } raw = json.dumps(spec, sort_keys=True, separators=(",", ":")).encode("utf-8") return hashlib.sha3_256(raw).hexdigest()
def emit_receipt( op: str, x: torch.Tensor, out: torch.Tensor, eps: float, subject: Optional[str] = None, policy_id: str = _POLICY_ID, sign_key: Optional[Union[str, bytes]] = None, organ: str = _ORGAN,) -> Optional[Dict[str, Any]]: """Canonical szl-receipt v0.2.0 evidence binding for a governed-norm call.
ADDITIVE and IMPORT-GUARDED: returns ``None`` when szl-receipt is not installed, so this universal Kernel-Hub kernel still imports and runs on stdlib + torch + numpy alone. When szl-receipt is present it binds an EVIDENCE trail and wraps it in a DSSE envelope via ``sign_receipt``:
subject organ / norm-call id (who/what emitted this) input_digest SHA3-256 over canonical {input shape, dtype, eps} output_digest the EXISTING SHA3-256 rounded-tensor digest of ``out`` policy_id the governing policy id energy the literal string "UNAVAILABLE"
Doctrine (non-negotiable): * A receipt is an integrity/EVIDENCE trail, NOT a proof of correctness. * ``energy == "UNAVAILABLE"`` — this kernel measures NO joules; a joule is NEVER fabricated. * Keyless => UNSIGNED-honest (``signature["signed"] is False``); a signature is NEVER fabricated. A real ``sign_key`` yields a real DSSE signature over the exact canonical binding.
Returns the binding dict (subject/input_digest/output_digest/policy_id/ energy) with the DSSE envelope under ``signature``, or ``None`` when szl-receipt is absent. """ try: from szl_receipt import Receipt, sign_receipt except Exception: # noqa: BLE001 - canonical binding is optional; absence is honest return None body = { "subject": subject if subject is not None else f"{organ}/{op}", "input_digest": _input_digest(x, eps), "output_digest": _tensor_digest(out), "policy_id": policy_id, "energy": _ENERGY_UNAVAILABLE, } env = sign_receipt(Receipt(kind="governed-norm", body=body), sign_key, organ=organ) return dict(body, signature=env)
class ReceiptChain: """Append-only, SHA3-256 hash-chained log of normalization receipts.
Each receipt: {seq, op, in_shape, in_dtype, eps, out_digest, prev, digest, ts} digest = SHA3-256 over the canonical JSON body (excluding digest/ts). verify() re-walks the chain and returns (ok, depth, first_break_seq). """
def __init__(self) -> None: self._lock = threading.RLock() self._records: List[Dict[str, Any]] = []
@staticmethod def _digest_body(body: Dict[str, Any]) -> str: raw = json.dumps(body, sort_keys=True, separators=(",", ":")).encode("utf-8") return hashlib.sha3_256(raw).hexdigest()
def emit( self, op: str, x: torch.Tensor, out: torch.Tensor, eps: float, sign_key: Optional[Union[str, bytes]] = None, organ: str = _ORGAN, policy_id: str = _POLICY_ID, ) -> Dict[str, Any]: with self._lock: prev = self._records[-1]["digest"] if self._records else _GENESIS seq = len(self._records) body = { "seq": seq, "op": op, "in_shape": list(x.shape), "in_dtype": str(x.dtype).replace("torch.", ""), "eps": float(eps), "out_digest": _tensor_digest(out), "prev": prev, } digest = self._digest_body(body) rec = dict(body, digest=digest, ts=time.time()) sig = _maybe_sign(body, sign_key, organ) if sig is not None: rec["signature"] = sig # ADDITIVE canonical szl-receipt v0.2.0 evidence binding. Import- # guarded: None when szl-receipt is absent, so the universal kernel # keeps working on stdlib + torch + numpy only. Binds subject / # input-digest / output-digest / policy-id / energy; energy is # "UNAVAILABLE" (no joules measured here). It does NOT enter the # SHA3-256 chain body, so verify() is unaffected. binding = emit_receipt( op, x, out, eps, subject=f"{organ}/{op}#{seq}", policy_id=policy_id, sign_key=sign_key, organ=organ, ) if binding is not None: rec["receipt"] = binding self._records.append(rec) return rec
def head(self) -> str: with self._lock: return self._records[-1]["digest"] if self._records else _GENESIS
def count(self) -> int: with self._lock: return len(self._records)
def tail(self, n: int = 10) -> List[Dict[str, Any]]: with self._lock: return list(self._records[-n:])
def verify(self): """Re-walk the chain. Returns (ok: bool, depth: int, first_break: int).""" with self._lock: prev = _GENESIS for i, rec in enumerate(self._records): body = {k: rec[k] for k in ("seq", "op", "in_shape", "in_dtype", "eps", "out_digest", "prev")} if rec["prev"] != prev or rec["digest"] != self._digest_body(body): return (False, len(self._records), i) prev = rec["digest"] return (True, len(self._records), -1)
# Module-level default chain (opt-in: only written when governed=True is used)._DEFAULT_CHAIN: Optional[ReceiptChain] = None_chain_lock = threading.Lock()
def default_chain() -> ReceiptChain: global _DEFAULT_CHAIN with _chain_lock: if _DEFAULT_CHAIN is None: _DEFAULT_CHAIN = ReceiptChain() return _DEFAULT_CHAIN123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960# SPDX-License-Identifier: Apache-2.0# © 2026 SZL Holdings · Stephen P. Lutar · ORCID 0009-0001-0110-4173"""Hub-compliant kernel layers.
Per the Kernel Hub `kernel-requirements`, layers exposed for extension mustbe PURE torch.nn.Module subclasses: - no custom __init__, - no class variables, - only a `forward` method, - forward signature compatible with the module it extends.
These layers therefore read their parameters (weight/bias/eps) off themodule instance they are bound to (set by the host model), and only define`forward`. They are drop-in replacements for an existing RMSNorm/LayerNormmodule via the `kernels` layer-mapping mechanism."""import torchfrom torch import nn
from ._norm import fused_add_rms_norm, layer_norm, rms_norm
class RMSNorm(nn.Module): """Pure RMSNorm layer. Expects the host module to provide `self.weight` (optional) and `self.variance_epsilon` or `self.eps`."""
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: weight = getattr(self, "weight", None) eps = getattr(self, "variance_epsilon", None) if eps is None: eps = getattr(self, "eps", 1e-6) return rms_norm(hidden_states, weight=weight, eps=float(eps))
class LayerNorm(nn.Module): """Pure LayerNorm layer. Expects the host module to provide `self.weight` (optional), `self.bias` (optional), and `self.eps`."""
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: weight = getattr(self, "weight", None) bias = getattr(self, "bias", None) eps = getattr(self, "eps", 1e-5) return layer_norm(hidden_states, weight=weight, bias=bias, eps=float(eps))
class FusedAddRMSNorm(nn.Module): """Pure residual-add + RMSNorm layer for pre-norm transformer blocks.
Expects the host module to provide `self.weight` (optional) and `self.variance_epsilon` or `self.eps`. Returns `(normalized, new_residual)` where `new_residual = hidden_states + residual` is carried forward as the next block's residual stream. """
def forward(self, hidden_states: torch.Tensor, residual: torch.Tensor): weight = getattr(self, "weight", None) eps = getattr(self, "variance_epsilon", None) if eps is None: eps = getattr(self, "eps", 1e-6) return fused_add_rms_norm(hidden_states, residual, weight=weight, eps=float(eps))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051# SPDX-License-Identifier: Apache-2.0# © 2026 SZL Holdings · Stephen P. Lutar · ORCID 0009-0001-0110-4173"""Hub-compliant kernel layer for the szl-lambda-gate kernel.
Per the Kernel Hub `kernel-requirements`, layers exposed for extension must bePURE torch.nn.Module subclasses: - no custom __init__, - no class variables, - only a `forward` method.
The layer therefore reads its parameters (weights / threshold) off the moduleinstance it is bound to (set by the host model) and only defines `forward`.
HONESTY: `LambdaGate` emits an ADVISORY governance signal (the weightedgeometric mean Λ plus a pass/fail vs threshold). Λ is NOT proven trust; itsuniqueness is Conjecture 1 (open)."""import torchfrom torch import nn
from ._lambda import lambda_aggregate, lambda_gate
class LambdaGate(nn.Module): """Pure Λ-gate layer.
Reads optional ``self.weights`` (1-D, length k) and ``self.threshold`` (float, default 0.5) off the bound module instance.
forward(axes) -> LambdaGateResult(score, passed, threshold, advisory) where ``score`` = Λ(axes) over the last dim and ``passed`` = score >= threshold. Differentiable in ``score`` w.r.t. ``axes``. """
def forward(self, axes: torch.Tensor): weights = getattr(self, "weights", None) threshold = getattr(self, "threshold", 0.5) return lambda_gate(axes, weights=weights, threshold=float(threshold))
class LambdaAggregate(nn.Module): """Pure Λ-aggregator layer: forward(axes) -> Λ(axes) tensor in [0,1].
Reads optional ``self.weights`` (1-D, length k) off the bound module instance; uniform weights when absent. Returns just the score (no gate), fully differentiable w.r.t. ``axes``. """
def forward(self, axes: torch.Tensor) -> torch.Tensor: weights = getattr(self, "weights", None) return lambda_aggregate(axes, weights=weights)build/torch-universal/metadata.jsonAdded+36
build/torch-universal/szl_lambda_gate/__init__.pyAdded+198
build/torch-universal/szl_lambda_gate/_lambda.pyAdded+504
build/torch-universal/szl_lambda_gate/_ops.pyAdded+10
build/torch-universal/szl_lambda_gate/governed_norm/__init__.pyAdded+279
build/torch-universal/szl_lambda_gate/governed_norm/_norm.pyAdded+246
build/torch-universal/szl_lambda_gate/governed_norm/_receipt.pyAdded+253
build/torch-universal/szl_lambda_gate/governed_norm/layers.pyAdded+60
build/torch-universal/szl_lambda_gate/layers.pyAdded+51