betterwithage commited on
Commit
8cb741b
·
verified ·
1 Parent(s): 958469d

Upload folder using huggingface_hub

Browse files
Files changed (3) hide show
  1. Dockerfile +2 -0
  2. energy.py +132 -0
  3. kernel.py +133 -0
Dockerfile CHANGED
@@ -6,3 +6,5 @@ COPY server.py ./server.py
6
  COPY index.html ./index.html
7
  EXPOSE 7860
8
  CMD ["python", "-u", "server.py"]
 
 
 
6
  COPY index.html ./index.html
7
  EXPOSE 7860
8
  CMD ["python", "-u", "server.py"]
9
+ COPY energy.py ./energy.py
10
+ COPY kernel.py ./kernel.py
energy.py ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ # Copyright 2026 SZL Holdings
4
+ # Signed-off-by: Lutar, Stephen P. <stephenlutar2@gmail.com>
5
+ """Energy probe. Channel is always LIVE. Joules MEASURED only from RAPL or NVML."""
6
+ from __future__ import annotations
7
+
8
+ import time
9
+ from pathlib import Path
10
+ from typing import Any
11
+
12
+ POWERCAP = Path("/sys/class/powercap")
13
+ RAPL = Path("/sys/class/powercap/intel-rapl:0/energy_uj")
14
+
15
+
16
+ def _rapl_uj() -> int | None:
17
+ candidates: list[Path] = [RAPL]
18
+ try:
19
+ if POWERCAP.is_dir():
20
+ candidates.extend(sorted(POWERCAP.glob("intel-rapl:*/energy_uj")))
21
+ candidates.extend(sorted(POWERCAP.glob("intel-rapl:*:*/energy_uj")))
22
+ except OSError:
23
+ pass
24
+ seen: set[Path] = set()
25
+ for path in candidates:
26
+ if path in seen:
27
+ continue
28
+ seen.add(path)
29
+ try:
30
+ if path.is_file():
31
+ return int(path.read_text().strip())
32
+ except (OSError, ValueError):
33
+ continue
34
+ return None
35
+
36
+
37
+ def _nvml_mj() -> float | None:
38
+ try:
39
+ import pynvml # type: ignore
40
+ except ImportError:
41
+ return None
42
+ try:
43
+ pynvml.nvmlInit()
44
+ handle = pynvml.nvmlDeviceGetHandleByIndex(0)
45
+ mj = float(pynvml.nvmlDeviceGetTotalEnergyConsumption(handle))
46
+ pynvml.nvmlShutdown()
47
+ return mj
48
+ except Exception:
49
+ try:
50
+ pynvml.nvmlShutdown()
51
+ except Exception:
52
+ pass
53
+ return None
54
+
55
+
56
+ def _unavailable(note: str) -> dict[str, Any]:
57
+ return {
58
+ "channel": "LIVE",
59
+ "honesty": "UNAVAILABLE",
60
+ "source": None,
61
+ "package_energy_j": None,
62
+ "sample_delta_j": None,
63
+ "inference_energy_j": None,
64
+ "energy_j": None,
65
+ "note": note,
66
+ }
67
+
68
+
69
+ def probe(*, sample_s: float = 0.05) -> dict[str, Any]:
70
+ """Return MEASURED package energy if hardware exists, else UNAVAILABLE.
71
+
72
+ The probe channel is always LIVE. A RAPL counter is package energy, not
73
+ tokens/joule. Inference joules are only MEASURED when a kernel run is
74
+ wrapped in a RAPL/NVML delta. Never a fabricated joule.
75
+ """
76
+ a = _rapl_uj()
77
+ if a is not None:
78
+ time.sleep(max(0.0, sample_s))
79
+ b = _rapl_uj()
80
+ if b is None:
81
+ b = a
82
+ delta_j = max(0.0, (b - a) / 1_000_000.0)
83
+ return {
84
+ "channel": "LIVE",
85
+ "honesty": "MEASURED",
86
+ "source": "intel-rapl",
87
+ "package_energy_j": b / 1_000_000.0,
88
+ "sample_delta_j": delta_j,
89
+ "inference_energy_j": None,
90
+ "energy_j": None,
91
+ "note": "RAPL package counter MEASURED. Inference joule still None until a kernel is wrapped.",
92
+ }
93
+ mj = _nvml_mj()
94
+ if mj is not None:
95
+ return {
96
+ "channel": "LIVE",
97
+ "honesty": "MEASURED",
98
+ "source": "nvml",
99
+ "package_energy_j": mj / 1000.0,
100
+ "sample_delta_j": None,
101
+ "inference_energy_j": None,
102
+ "energy_j": None,
103
+ "note": "NVML total energy MEASURED. Inference joule still None until a kernel is wrapped.",
104
+ }
105
+ return _unavailable("No RAPL, no NVML. Channel is live. Never a fabricated joule.")
106
+
107
+
108
+ def measure_run(fn):
109
+ """Wrap a kernel. If RAPL/NVML exists, inference_energy_j is MEASURED."""
110
+ a = _rapl_uj()
111
+ nv_a = _nvml_mj()
112
+ t0 = time.perf_counter()
113
+ result = fn()
114
+ dt = time.perf_counter() - t0
115
+ b = _rapl_uj()
116
+ nv_b = _nvml_mj()
117
+ energy = probe(sample_s=0.0)
118
+ energy["channel"] = "LIVE"
119
+ energy["duration_s"] = dt
120
+ if a is not None and b is not None:
121
+ energy["honesty"] = "MEASURED"
122
+ energy["source"] = "intel-rapl"
123
+ energy["inference_energy_j"] = max(0.0, (b - a) / 1_000_000.0)
124
+ energy["energy_j"] = energy["inference_energy_j"]
125
+ energy["note"] = f"RAPL delta around kernel · {dt:.4f}s"
126
+ elif nv_a is not None and nv_b is not None:
127
+ energy["honesty"] = "MEASURED"
128
+ energy["source"] = "nvml"
129
+ energy["inference_energy_j"] = max(0.0, (nv_b - nv_a) / 1000.0)
130
+ energy["energy_j"] = energy["inference_energy_j"]
131
+ energy["note"] = f"NVML delta around kernel · {dt:.4f}s"
132
+ return result, energy
kernel.py ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ # Copyright 2026 SZL Holdings
4
+ # Signed-off-by: Lutar, Stephen P. <stephenlutar2@gmail.com>
5
+ """Command-lab fail-closed integrity kernel.
6
+
7
+ Stdlib only. Real SHA-256. Advisory Λ. Energy UNAVAILABLE.
8
+ Locked-proven stays exactly 8. Λ uniqueness is Conjecture 1 OPEN.
9
+ proven_trust is False. Not a-11-oy.com. Not an ATO.
10
+ """
11
+ from __future__ import annotations
12
+
13
+ import hashlib
14
+ import json
15
+ import math
16
+ from datetime import datetime, timezone
17
+ from typing import Any, Sequence
18
+
19
+ LOCKED_EIGHT = ("F1", "F4", "F7", "F11", "F12", "F18", "F19", "F22")
20
+ YUYAY_FLOORS = (0.95, 0.95) + (0.90,) * 11
21
+ ZERO = "0" * 64
22
+ CHAIN_OPS = ("anatomy.brain", "anatomy.heart", "anatomy.skeleton")
23
+ proven_trust = False
24
+
25
+
26
+ def _sha256_hex(text: str) -> str:
27
+ return hashlib.sha256(text.encode("utf-8")).hexdigest()
28
+
29
+
30
+ def wgm(xs: Sequence[float], ws: Sequence[float]) -> float:
31
+ if len(xs) != len(ws) or not xs:
32
+ return 0.0
33
+ if any((not math.isfinite(x)) or x <= 0.0 for x in xs):
34
+ return 0.0
35
+ if any((not math.isfinite(w)) or w < 0.0 for w in ws):
36
+ return 0.0
37
+ if abs(sum(ws) - 1.0) >= 1e-9:
38
+ return 0.0
39
+ value = math.exp(sum(w * math.log(x) for x, w in zip(xs, ws)))
40
+ return value if math.isfinite(value) else 0.0
41
+
42
+
43
+ def evaluate_lambda(axes: Sequence[float]) -> dict[str, Any]:
44
+ n = len(axes)
45
+ weights = tuple(1.0 / n for _ in range(n)) if n else ()
46
+ value = wgm(axes, weights)
47
+ blocked = value == 0.0
48
+ return {
49
+ "value": float(value),
50
+ "blocked": bool(blocked),
51
+ "reason": "zero-routed" if blocked else "advisory pass — Conjecture 1 OPEN",
52
+ }
53
+
54
+
55
+ def yawar_chain(seed: int, tamper: bool) -> dict[str, Any]:
56
+ hops = []
57
+ prev = ZERO
58
+ for seq, op in enumerate(CHAIN_OPS):
59
+ material = f"{seq}|{op}|{prev}|{int(seed)}"
60
+ digest = _sha256_hex(material)
61
+ hops.append({"seq": seq, "op": op, "prev": prev, "digest": digest})
62
+ prev = digest
63
+ if tamper and len(hops) > 1:
64
+ hops[1] = dict(hops[1])
65
+ hops[1]["prev"] = "deadbeef" + hops[1]["prev"][8:]
66
+ walk = ZERO
67
+ ok = True
68
+ brk = None
69
+ for hop in hops:
70
+ expect = _sha256_hex(f"{hop['seq']}|{hop['op']}|{hop['prev']}|{int(seed)}")
71
+ if hop["prev"] != walk or expect != hop["digest"]:
72
+ ok = False
73
+ brk = int(hop["seq"])
74
+ break
75
+ walk = hop["digest"]
76
+ return {"hops": hops, "ok": ok, "head": hops[-1]["digest"] if hops else ZERO, "break_at": brk, "alg": "SHA-256"}
77
+
78
+
79
+ def evaluate_anatomy(*, zero_heart: bool = False, tamper_chain: bool = False, fabricate_joule: bool = False, seed: int = 11) -> dict[str, Any]:
80
+ if proven_trust is True:
81
+ raise RuntimeError("refusing proven_trust true")
82
+ axes = list(YUYAY_FLOORS)
83
+ if zero_heart:
84
+ axes[0] = 0.0
85
+ heart = evaluate_lambda(axes)
86
+ chain = yawar_chain(int(seed), bool(tamper_chain))
87
+ organs = [
88
+ {"name": "BRAIN", "status": "LIVE", "honesty": "LIVE"},
89
+ {"name": "HEART", "status": "DOWN" if heart["blocked"] else "LIVE", "honesty": "ADVISORY"},
90
+ {"name": "CIRCULATORY", "status": "DOWN" if not chain["ok"] else "LIVE", "honesty": "LIVE"},
91
+ {"name": "NERVOUS", "status": "DOWN" if fabricate_joule else "LIVE", "honesty": "UNAVAILABLE"},
92
+ {"name": "SKELETON", "status": "LIVE", "honesty": "ADVISORY"},
93
+ ]
94
+ live = sum(1 for o in organs if o["status"] == "LIVE")
95
+ blocked = any(o["status"] == "DOWN" for o in organs)
96
+ return {
97
+ "organs": organs,
98
+ "live_count": live,
99
+ "blocked": blocked,
100
+ "verdict": "BLOCKED" if blocked else "ADVISORY_BODY",
101
+ "energy": "UNAVAILABLE",
102
+ "energy_j": None,
103
+ "conjecture_1": "OPEN",
104
+ "locked_proven": 8,
105
+ "locked_ids": list(LOCKED_EIGHT),
106
+ "proven_trust": False,
107
+ "chain_head": chain["head"],
108
+ "reason": (
109
+ f"organ integrity {live}/5 LIVE · Λ advisory · energy UNAVAILABLE · Conjecture 1 OPEN"
110
+ if not blocked
111
+ else "organ integrity FAIL · fail closed"
112
+ ),
113
+ "checked_at": datetime.now(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z"),
114
+ }
115
+
116
+
117
+ def selftest() -> dict[str, Any]:
118
+ healthy = evaluate_anatomy(seed=11)
119
+ assert healthy["live_count"] == 5
120
+ assert healthy["blocked"] is False
121
+ assert healthy["energy"] == "UNAVAILABLE"
122
+ assert healthy["proven_trust"] is False
123
+ z = evaluate_anatomy(zero_heart=True)
124
+ assert z["blocked"] is True
125
+ t = evaluate_anatomy(tamper_chain=True)
126
+ assert t["blocked"] is True
127
+ j = evaluate_anatomy(fabricate_joule=True)
128
+ assert j["blocked"] is True
129
+ return {"ok": True, "cases": 4, "healthy_head": healthy["chain_head"]}
130
+
131
+
132
+ if __name__ == "__main__":
133
+ print(json.dumps(selftest(), indent=2))