Instructions to use SZLHOLDINGS/szl-lambda-gate with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Kernels
How to use SZLHOLDINGS/szl-lambda-gate with Kernels:
# !pip install kernels from kernels import get_kernel kernel = get_kernel("SZLHOLDINGS/szl-lambda-gate") - Notebooks
- Google Colab
- Kaggle
File size: 13,068 Bytes
bd94dc1 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 | # 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. It is a
correctness reference, computed via logs in float32 for stability,
differentiable (autograd works), and torch.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 an 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* 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) and the OECD Handbook on Constructing
Composite Indicators (2008) both use it to limit the compensation effect. The
veto / cut-off idea (a single failing criterion blocks a pass) is the ELECTRE
veto threshold. The 13-axis conjunctive form (yuyay_weights) is SZL's own
yuyay_v3 gate. None of this makes Λ "proven trust"; the gate 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).
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
_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."""
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."""
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)
if not bool(torch.all(torch.isfinite(wf))):
raise ValueError("weights must all be finite (no NaN/Inf)")
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``.
Axis scores expected in [0,1] and clamped into [0,1]; uniform weights (1/k)
when ``weights`` is None. Computed via logs for 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. A garbage/invalid axis must never silently
pass as a perfect (clamped-to-1) axis; output and gradient stay finite and
in [0,1] for every input.
Returns a tensor of shape (...) — Λ(x) ∈ [0,1] per batch row, differentiable
w.r.t. ``axes``.
HONESTY: 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
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) # (...)
safe = torch.where(bad_mask, torch.ones_like(xc), xc)
logx = torch.log(safe) # (..., k)
acc = (logx * w).sum(dim=-1) # (...)
val = torch.exp(acc) # (...)
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.
Returns a :class:`LambdaGateResult` namedtuple (score, passed, threshold,
advisory). ``passed`` := Λ(x) >= threshold; ``advisory`` is always True.
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}")
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.
``candidates`` is shape (..., N, k): last dim ``k`` is per-axis scores of one
candidate, the dim before it enumerates the N candidates. Returns a
:class:`LambdaGateResult` with score/passed of shape (..., N).
HONESTY: the pass mask is ADVISORY, non-compensatory. 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); "
f"got a {candidates.dim()}-d tensor"
)
return lambda_gate(candidates, weights=weights, threshold=threshold)
# ---- A1..A4 axiom RUNTIME self-checks (real, verifiable) ------------------- #
def is_egyptian_exact(c, k: int = 3, weights=None, tol: float = 1e-5) -> bool:
"""A3 IsEgyptianExact: Λ(c, …, c) = c for a constant axis vector of length k."""
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=None, tol: float = 1e-6) -> bool:
"""A4 IsBounded: Λ(x) ≤ maxᵢ xᵢ (over the last dim), within ``tol``."""
_check_axes(axes)
val = lambda_aggregate(axes, weights)
xf = axes.to(_compute_dtype(axes.dtype))
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, weights=None, tol: float = 1e-5) -> bool:
"""A2 IsHomogeneous (degree 1): Λ(t·x) = t·Λ(x) for scalar t in [0,1]."""
_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=None, delta: float = 0.05, tol: float = 1e-7) -> bool:
"""A1 IsMonotone: Λ is non-decreasing in each axis."""
_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)
ok = ok and bool(torch.all(bumped_val - base >= -tol))
return ok
def find_axiom_violation(k: int = 5, trials: int = 200, weights=None, seed=0, tol: float = 1e-6):
"""Random-search for ANY A1–A4 violation. Returns the first violating triple
``(axiom, axes, weights)`` or ``None``. An honest FALSIFICATION attempt —
finding nothing is empirical evidence, NOT a proof (Λ-uniqueness = Conjecture 1).
"""
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
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)
if not is_bounded_by_max(x, w, tol=max(tol, 1e-6)):
return ("A4_IsBounded", x, w)
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)
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) ------------------------ #
YUYAY_AXES = (
"moralGrounding", "measurabilityHonesty", "empiricalGrounding",
"logicalConsistency", "sourceTransparency", "reproducibility",
"licenseHygiene", "scopeDiscipline", "claimCalibration", "evalAwareness",
"deceptionKeywords", "conflictingDirectives", "reversalDirective",
)
YUYAY_FLOORS = (
0.95, 0.95,
0.90, 0.90, 0.90, 0.90, 0.90, 0.90, 0.90,
0.90, 0.90, 0.90, 0.90,
)
def yuyay_weights(dtype: torch.dtype = torch.float64, device=None) -> torch.Tensor:
"""Canonical 13-axis Yuyay Λ weight vector (uniform 1/13), ADVISORY only."""
k = len(YUYAY_AXES)
return torch.full((k,), 1.0 / k, dtype=dtype, device=device)
def selfcheck(k: int = 5, trials: int = 64, seed=0) -> dict:
"""Run the A1–A4 empirical self-checks and report a verdict + version.
HONESTY: 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
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",
}
__version__ = "0.2.0"
from collections import namedtuple # noqa: E402
LambdaGateResult = namedtuple(
"LambdaGateResult", ["score", "passed", "threshold", "advisory"]
)
|