Kernels
kernel
betterwithage commited on
Commit
bd94dc1
·
verified ·
1 Parent(s): 9cf4c8b

lambda-gate core: Λ aggregator + advisory gate + axioms (v0.2.0)

Browse files
build/torch-universal/szl_lambda_gate/_lambda.py ADDED
@@ -0,0 +1,313 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # © 2026 SZL Holdings · Stephen P. Lutar · ORCID 0009-0001-0110-4173
3
+ """Pure-PyTorch Lambda-Spine aggregator (Λ) for the szl-lambda-gate kernel.
4
+
5
+ Λ(x) = ∏ xᵢ^{wᵢ}, Σwᵢ = 1, wᵢ > 0, xᵢ ∈ [0,1] (weighted geometric mean)
6
+
7
+ This is a TORCH port of the canonical pure-Python reference. It is a
8
+ correctness reference, computed via logs in float32 for stability,
9
+ differentiable (autograd works), and torch.compile-friendly. Depends ONLY on
10
+ torch + the Python standard library (a Kernel Hub requirement for universal
11
+ kernels).
12
+
13
+ WHAT Λ IS / IS NOT (HONESTY — SZL Holdings doctrine v11):
14
+ Λ is the *weighted-geometric-mean aggregator*: a non-compensatory way to
15
+ combine axis scores in [0,1] into one number. It is an ADVISORY governance
16
+ signal — a conservative roll-up where any single zeroed axis drives the
17
+ aggregate to 0. It is NOT "proven trust" and NOT a closed theorem. Its
18
+ *uniqueness* remains Conjecture 1 — OPEN (an unresolved CAUCHY_ND step plus a
19
+ missing symmetry axiom in the Lean development). Do not describe Λ as proven
20
+ trust anywhere.
21
+
22
+ PRIOR ART (honest attribution): the weighted geometric mean as a less-
23
+ compensatory composite-indicator aggregator is established practice — the UN
24
+ HDI (arithmetic→geometric switch, 2010) and the OECD Handbook on Constructing
25
+ Composite Indicators (2008) both use it to limit the compensation effect. The
26
+ veto / cut-off idea (a single failing criterion blocks a pass) is the ELECTRE
27
+ veto threshold. The 13-axis conjunctive form (yuyay_weights) is SZL's own
28
+ yuyay_v3 gate. None of this makes Λ "proven trust"; the gate is ADVISORY.
29
+
30
+ PROVENANCE: backed by the Lean 4 formalization szl-holdings/lutar-lean
31
+ (749 declarations / 14 axioms / 163 tracked sorries),
32
+ DOI 10.5281/zenodo.20434308 (lutar-lean). Λ uniqueness = Conjecture 1 (open).
33
+
34
+ Axioms carried (Lutar/Axioms.lean), available below as runtime self-checks:
35
+ A1 IsMonotone — Λ is non-decreasing in each axis
36
+ A2 IsHomogeneous — Λ(t·x) = t·Λ(x) (degree 1)
37
+ A3 IsEgyptianExact — Λ(c,…,c) = c (the uniform-diagonal fixpoint)
38
+ A4 IsBounded(by max) — Λ(x) ≤ maxᵢ xᵢ
39
+ """
40
+ from typing import Optional
41
+
42
+ import torch
43
+
44
+ _SUPPORTED_DTYPES = (torch.float16, torch.bfloat16, torch.float32, torch.float64)
45
+
46
+
47
+ def _compute_dtype(in_dtype: torch.dtype) -> torch.dtype:
48
+ return torch.float32 if in_dtype in (torch.float16, torch.bfloat16) else in_dtype
49
+
50
+
51
+ def _check_axes(axes: torch.Tensor) -> None:
52
+ """Cheap, allocation-free metadata guards on the axis-score tensor."""
53
+ if not isinstance(axes, torch.Tensor):
54
+ raise TypeError(f"axes must be a torch.Tensor, got {type(axes).__name__}")
55
+ if axes.dtype not in _SUPPORTED_DTYPES:
56
+ raise TypeError(
57
+ f"axes has unsupported dtype {axes.dtype}; "
58
+ f"expected one of {tuple(str(d) for d in _SUPPORTED_DTYPES)}"
59
+ )
60
+ if axes.dim() < 1:
61
+ raise ValueError(
62
+ "axes must have at least 1 dimension (the k axis scores live on "
63
+ f"the last dim); got a {axes.dim()}-d tensor"
64
+ )
65
+ if axes.shape[-1] < 1:
66
+ raise ValueError("axes last dimension (k = number of axes) must be >= 1")
67
+
68
+
69
+ def _resolve_weights(
70
+ axes: torch.Tensor,
71
+ weights: Optional[torch.Tensor],
72
+ cdt: torch.dtype,
73
+ ) -> torch.Tensor:
74
+ """Return a normalized (Σw = 1) weight vector of shape (k,) in compute dtype."""
75
+ k = axes.shape[-1]
76
+ if weights is None:
77
+ return torch.full((k,), 1.0 / k, dtype=cdt, device=axes.device)
78
+ if not isinstance(weights, torch.Tensor):
79
+ raise TypeError(f"weights must be a torch.Tensor or None, got {type(weights).__name__}")
80
+ if weights.device != axes.device:
81
+ raise ValueError(
82
+ f"weights is on device {weights.device} but axes is on {axes.device}; "
83
+ "move them to the same device"
84
+ )
85
+ if weights.dim() != 1 or weights.shape[0] != k:
86
+ raise ValueError(
87
+ f"weights must be 1-D with shape ({k},) to match the last dim of axes; "
88
+ f"got shape {tuple(weights.shape)}"
89
+ )
90
+ wf = weights.to(cdt)
91
+ if not bool(torch.all(torch.isfinite(wf))):
92
+ raise ValueError("weights must all be finite (no NaN/Inf)")
93
+ if bool(torch.any(wf <= 0.0)):
94
+ raise ValueError("weights must be strictly positive (wᵢ > 0)")
95
+ sw = wf.sum()
96
+ if not bool(sw > 0.0):
97
+ raise ValueError("weights must sum to a positive value")
98
+ return wf / sw
99
+
100
+
101
+ def lambda_aggregate(
102
+ axes: torch.Tensor,
103
+ weights: Optional[torch.Tensor] = None,
104
+ ) -> torch.Tensor:
105
+ """Weighted geometric mean Λ(x) = ∏ xᵢ^{wᵢ} over the last dim of ``axes``.
106
+
107
+ Axis scores expected in [0,1] and clamped into [0,1]; uniform weights (1/k)
108
+ when ``weights`` is None. Computed via logs for stability:
109
+
110
+ Λ(x) = exp( Σᵢ wᵢ · log(clamp(xᵢ, 0, 1)) )
111
+
112
+ Non-compensatory zero-routing (A4-consistent): any axis that is zero, OR
113
+ that is NON-FINITE (NaN / ±Inf), is treated as a FAILING axis and drives
114
+ the whole aggregate to exactly 0. A garbage/invalid axis must never silently
115
+ pass as a perfect (clamped-to-1) axis; output and gradient stay finite and
116
+ in [0,1] for every input.
117
+
118
+ Returns a tensor of shape (...) — Λ(x) ∈ [0,1] per batch row, differentiable
119
+ w.r.t. ``axes``.
120
+
121
+ HONESTY: a non-compensatory governance roll-up, NOT proven trust.
122
+ Λ-uniqueness is Conjecture 1 (open).
123
+ """
124
+ _check_axes(axes)
125
+ in_dtype = axes.dtype
126
+ cdt = _compute_dtype(in_dtype)
127
+ xf = axes.to(cdt)
128
+ w = _resolve_weights(axes, weights, cdt) # (k,), Σw=1
129
+
130
+ finite_mask = torch.isfinite(xf)
131
+ xc = xf.clamp(0.0, 1.0)
132
+ bad_mask = (~finite_mask) | (xc <= 0.0)
133
+ any_bad = torch.any(bad_mask, dim=-1) # (...)
134
+
135
+ safe = torch.where(bad_mask, torch.ones_like(xc), xc)
136
+ logx = torch.log(safe) # (..., k)
137
+ acc = (logx * w).sum(dim=-1) # (...)
138
+ val = torch.exp(acc) # (...)
139
+
140
+ out = torch.where(any_bad, torch.zeros_like(val), val)
141
+ out = out.clamp(0.0, 1.0)
142
+ return out.to(in_dtype)
143
+
144
+
145
+ def lambda_gate(
146
+ axes: torch.Tensor,
147
+ weights: Optional[torch.Tensor] = None,
148
+ threshold: float = 0.5,
149
+ ):
150
+ """ADVISORY governance gate over Λ(x): score plus a pass/fail vs threshold.
151
+
152
+ Returns a :class:`LambdaGateResult` namedtuple (score, passed, threshold,
153
+ advisory). ``passed`` := Λ(x) >= threshold; ``advisory`` is always True.
154
+
155
+ HONESTY: a "pass" is an ADVISORY signal only. Λ is the weighted-geometric-
156
+ mean aggregator; its uniqueness is Conjecture 1 (open). Do not treat a pass
157
+ as proven trust or a closed theorem.
158
+ """
159
+ t = float(threshold)
160
+ if t != t or t == float("inf") or t == float("-inf"):
161
+ raise ValueError(f"threshold must be a finite float, got {threshold!r}")
162
+ score = lambda_aggregate(axes, weights)
163
+ passed = score >= t
164
+ return LambdaGateResult(score=score, passed=passed, threshold=t, advisory=True)
165
+
166
+
167
+ def lambda_gate_batch(
168
+ candidates: torch.Tensor,
169
+ weights: Optional[torch.Tensor] = None,
170
+ threshold: float = 0.5,
171
+ ):
172
+ """ADVISORY batch gate: score MANY candidate action-vectors in one call.
173
+
174
+ ``candidates`` is shape (..., N, k): last dim ``k`` is per-axis scores of one
175
+ candidate, the dim before it enumerates the N candidates. Returns a
176
+ :class:`LambdaGateResult` with score/passed of shape (..., N).
177
+
178
+ HONESTY: the pass mask is ADVISORY, non-compensatory. NOT proven trust;
179
+ Λ-uniqueness is Conjecture 1 (open).
180
+ """
181
+ _check_axes(candidates)
182
+ if candidates.dim() < 2:
183
+ raise ValueError(
184
+ "candidates must be at least 2-D, shape (..., N, k); "
185
+ f"got a {candidates.dim()}-d tensor"
186
+ )
187
+ return lambda_gate(candidates, weights=weights, threshold=threshold)
188
+
189
+
190
+ # ---- A1..A4 axiom RUNTIME self-checks (real, verifiable) ------------------- #
191
+ def is_egyptian_exact(c, k: int = 3, weights=None, tol: float = 1e-5) -> bool:
192
+ """A3 IsEgyptianExact: Λ(c, …, c) = c for a constant axis vector of length k."""
193
+ if k < 1:
194
+ raise ValueError("k must be >= 1")
195
+ cc = min(max(float(c), 0.0), 1.0)
196
+ axes = torch.full((k,), cc, dtype=torch.float64)
197
+ val = lambda_aggregate(axes, weights)
198
+ return bool(torch.abs(val - cc) <= tol)
199
+
200
+
201
+ def is_bounded_by_max(axes: torch.Tensor, weights=None, tol: float = 1e-6) -> bool:
202
+ """A4 IsBounded: Λ(x) ≤ maxᵢ xᵢ (over the last dim), within ``tol``."""
203
+ _check_axes(axes)
204
+ val = lambda_aggregate(axes, weights)
205
+ xf = axes.to(_compute_dtype(axes.dtype))
206
+ xf = torch.where(torch.isfinite(xf), xf, torch.zeros_like(xf))
207
+ mx = xf.clamp(0.0, 1.0).amax(dim=-1)
208
+ return bool(torch.all(val.to(mx.dtype) <= mx + tol))
209
+
210
+
211
+ def is_homogeneous(axes: torch.Tensor, t, weights=None, tol: float = 1e-5) -> bool:
212
+ """A2 IsHomogeneous (degree 1): Λ(t·x) = t·Λ(x) for scalar t in [0,1]."""
213
+ _check_axes(axes)
214
+ tt = min(max(float(t), 0.0), 1.0)
215
+ x = axes.to(torch.float64).clamp(0.0, 1.0)
216
+ lhs = lambda_aggregate(x * tt, weights)
217
+ rhs = tt * lambda_aggregate(x, weights)
218
+ return bool(torch.all(torch.abs(lhs - rhs) <= tol))
219
+
220
+
221
+ def is_monotone(axes: torch.Tensor, weights=None, delta: float = 0.05, tol: float = 1e-7) -> bool:
222
+ """A1 IsMonotone: Λ is non-decreasing in each axis."""
223
+ _check_axes(axes)
224
+ x = axes.to(torch.float64).clamp(0.0, 1.0)
225
+ base = lambda_aggregate(x, weights)
226
+ k = x.shape[-1]
227
+ ok = True
228
+ for j in range(k):
229
+ bumped = x.clone()
230
+ bumped[..., j] = (bumped[..., j] + float(delta)).clamp(0.0, 1.0)
231
+ bumped_val = lambda_aggregate(bumped, weights)
232
+ ok = ok and bool(torch.all(bumped_val - base >= -tol))
233
+ return ok
234
+
235
+
236
+ def find_axiom_violation(k: int = 5, trials: int = 200, weights=None, seed=0, tol: float = 1e-6):
237
+ """Random-search for ANY A1–A4 violation. Returns the first violating triple
238
+ ``(axiom, axes, weights)`` or ``None``. An honest FALSIFICATION attempt —
239
+ finding nothing is empirical evidence, NOT a proof (Λ-uniqueness = Conjecture 1).
240
+ """
241
+ gen = torch.Generator()
242
+ if seed is not None:
243
+ gen.manual_seed(int(seed))
244
+ for _ in range(int(trials)):
245
+ x = torch.rand(k, generator=gen, dtype=torch.float64)
246
+ w = weights
247
+ if w is None:
248
+ w = torch.rand(k, generator=gen, dtype=torch.float64) + 1e-3
249
+ c = float(torch.rand(1, generator=gen).item())
250
+ if not is_egyptian_exact(c, k=k, weights=w, tol=max(tol, 1e-5)):
251
+ return ("A3_IsEgyptianExact", torch.full((k,), c, dtype=torch.float64), w)
252
+ if not is_bounded_by_max(x, w, tol=max(tol, 1e-6)):
253
+ return ("A4_IsBounded", x, w)
254
+ t = float(torch.rand(1, generator=gen).item())
255
+ if not is_homogeneous(x, t, weights=w, tol=max(tol, 1e-5)):
256
+ return ("A2_IsHomogeneous", x, w)
257
+ if not is_monotone(x * 0.9, w, tol=max(tol, 1e-7)):
258
+ return ("A1_IsMonotone", x * 0.9, w)
259
+ return None
260
+
261
+
262
+ # ---- Canonical 13-axis Yuyay preset (ADVISORY ONLY) ------------------------ #
263
+ YUYAY_AXES = (
264
+ "moralGrounding", "measurabilityHonesty", "empiricalGrounding",
265
+ "logicalConsistency", "sourceTransparency", "reproducibility",
266
+ "licenseHygiene", "scopeDiscipline", "claimCalibration", "evalAwareness",
267
+ "deceptionKeywords", "conflictingDirectives", "reversalDirective",
268
+ )
269
+ YUYAY_FLOORS = (
270
+ 0.95, 0.95,
271
+ 0.90, 0.90, 0.90, 0.90, 0.90, 0.90, 0.90,
272
+ 0.90, 0.90, 0.90, 0.90,
273
+ )
274
+
275
+
276
+ def yuyay_weights(dtype: torch.dtype = torch.float64, device=None) -> torch.Tensor:
277
+ """Canonical 13-axis Yuyay Λ weight vector (uniform 1/13), ADVISORY only."""
278
+ k = len(YUYAY_AXES)
279
+ return torch.full((k,), 1.0 / k, dtype=dtype, device=device)
280
+
281
+
282
+ def selfcheck(k: int = 5, trials: int = 64, seed=0) -> dict:
283
+ """Run the A1–A4 empirical self-checks and report a verdict + version.
284
+
285
+ HONESTY: EMPIRICAL checks on sampled inputs, NOT a proof of Λ-uniqueness
286
+ (Conjecture 1, open). A clean run is evidence, not proof.
287
+ """
288
+ x = torch.rand(k, dtype=torch.float64) * 0.9
289
+ w = torch.rand(k, dtype=torch.float64) + 1e-3
290
+ axioms = {
291
+ "A1_IsMonotone": is_monotone(x, w),
292
+ "A2_IsHomogeneous": is_homogeneous(x, float(torch.rand(1).item()), weights=w),
293
+ "A3_IsEgyptianExact": is_egyptian_exact(float(torch.rand(1).item()), k=k, weights=w),
294
+ "A4_IsBounded": is_bounded_by_max(x, w),
295
+ }
296
+ violation = find_axiom_violation(k=k, trials=trials, seed=seed)
297
+ return {
298
+ "version": __version__,
299
+ "axioms": axioms,
300
+ "all_axioms_hold": all(axioms.values()) and violation is None,
301
+ "adversarial": {"trials": int(trials), "violation": violation},
302
+ "advisory": True,
303
+ "lambda_status": "Conjecture 1 (open) — uniqueness unproven; advisory only",
304
+ }
305
+
306
+
307
+ __version__ = "0.2.0"
308
+
309
+ from collections import namedtuple # noqa: E402
310
+
311
+ LambdaGateResult = namedtuple(
312
+ "LambdaGateResult", ["score", "passed", "threshold", "advisory"]
313
+ )