spatial-computing 0.28.0__py3-none-any.whl → 0.30.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
spatial/__init__.py CHANGED
@@ -3,4 +3,4 @@
3
3
  Status of every engine is declared in spatial.core.registry and must be backed
4
4
  by a test or benchmark before being set to OPERATIONAL.
5
5
  """
6
- __version__ = "0.28.0"
6
+ __version__ = "0.30.0"
spatial/cli.py CHANGED
@@ -293,6 +293,57 @@ def cmd_automotive(a):
293
293
  return 0
294
294
 
295
295
 
296
+ def cmd_verify(a):
297
+ from .kernel.library import LIBRARY
298
+ from .verify import VerificationError, verify_kernel
299
+ kernel = LIBRARY[a.family]
300
+ params = json.loads(a.params)
301
+ devices = a.devices.split(",")
302
+ try:
303
+ c = verify_kernel(kernel, devices, a.n, tolerance=a.tolerance, exact=a.exact, **params)
304
+ except VerificationError as e:
305
+ print(f"spatial: {e}", file=sys.stderr)
306
+ return 1
307
+ print(f"{'AGREE' if c.agreed else 'DISAGREE'}: {c.n_results} results ({', '.join(devices)}), "
308
+ f"max abs diff {c.max_abs_diff:g} -- {c.reason}")
309
+ if not c.agreed:
310
+ print("spatial: redundant execution did not agree; do not trust this result", file=sys.stderr)
311
+ return 1
312
+ return 0
313
+
314
+
315
+ def cmd_screen(a):
316
+ from .fabric import metal
317
+ from .kernel.library import LIBRARY
318
+ from .verify import VerificationError, kernel_executors, screen
319
+ kernel = LIBRARY[a.family]
320
+ if a.devices == "auto":
321
+ devices = ["cpu", "cpu", "metal" if metal.available() else "cpu"]
322
+ else:
323
+ devices = a.devices.split(",")
324
+ ex = kernel_executors(kernel, devices, a.n, **json.loads(a.params))
325
+ if a.simulate_fault is not None:
326
+ name = list(ex)[a.simulate_fault]
327
+ real = ex[name]
328
+
329
+ def faulty(real=real):
330
+ out = real().copy()
331
+ out.flat[0] ^= 1 # one flipped bit
332
+ return out
333
+ faulty.kind = getattr(real, "kind", None)
334
+ ex[name] = faulty
335
+ print(f"SIMULATED fault injected into '{name}' (a flipped bit; not a real hardware fault)")
336
+ try:
337
+ r = screen(ex)
338
+ except VerificationError as e:
339
+ print(f"spatial: {e}", file=sys.stderr)
340
+ return 1
341
+ for x in r.results:
342
+ print(f"{x.name:10s} {x.status:13s} {x.seconds * 1000:8.1f} ms {x.digest[:12] or x.error}")
343
+ print(("HEALTHY: " if r.healthy else "UNHEALTHY: ") + r.reason)
344
+ return 0 if r.healthy else 1
345
+
346
+
296
347
  def cmd_token(a):
297
348
  from .core import auth
298
349
  if a.action == "init":
@@ -376,6 +427,21 @@ def main(argv=None):
376
427
  p = sub.add_parser("automotive", help="place a task graph on a declared in-vehicle chip catalogue (software only, no real automotive silicon here)")
377
428
  p.add_argument("--file", required=True, help="JSON: {\"chips\":[{\"name\",\"flops_per_s\",\"power_w\",\"supports_npu\"}], \"tasks\":[{\"name\",\"flops\",\"needs_npu\",\"after\"}]}")
378
429
  p.set_defaults(fn=cmd_automotive)
430
+ p = sub.add_parser("verify", help="redundant-execution check: run a kernel on 2+ devices and compare (not cryptographic proof, see docs/VERIFY.md)")
431
+ p.add_argument("--family", default="batch_score", choices=["mandelbrot", "collatz", "waves", "batch_score"])
432
+ p.add_argument("--n", type=int, default=64)
433
+ p.add_argument("--params", default="{}", help="JSON kernel parameters, e.g. '{\"signals\":16}'")
434
+ p.add_argument("--devices", default="cpu,metal", help="comma list, e.g. cpu,metal")
435
+ p.add_argument("--tolerance", type=float, default=0.0, help="max absolute difference allowed (ignored if --exact)")
436
+ p.add_argument("--exact", action="store_true", help="require a bit-exact match (integer kernels)")
437
+ p.set_defaults(fn=cmd_verify)
438
+ p = sub.add_parser("screen", help="fleet screening: same known-answer kernel on every executor, majority vote, flag the outlier and the straggler (see docs/VERIFY.md)")
439
+ p.add_argument("--family", default="collatz", choices=["mandelbrot", "collatz", "waves", "batch_score"], help="collatz is integer and bit-exact: the best known-answer test")
440
+ p.add_argument("--n", type=int, default=64)
441
+ p.add_argument("--params", default='{"limit":300}', help="JSON kernel parameters")
442
+ p.add_argument("--devices", default="auto", help="comma list (e.g. cpu,cpu,metal), or auto")
443
+ p.add_argument("--simulate-fault", type=int, default=None, metavar="INDEX", help="demo only: flip one bit in the output of the executor at INDEX")
444
+ p.set_defaults(fn=cmd_screen)
379
445
  p = sub.add_parser("agent", help="run a fleet agent: measure this machine, report to a hub, run allow-listed tasks")
380
446
  p.add_argument("--hub", required=True, help="host:port of the hub")
381
447
  p.add_argument("--token-file", required=True, help="shared secret file, or a scoped token with fleet:report,fleet:work")
@@ -0,0 +1,7 @@
1
+ """Redundant-execution verification and fleet screening. See spatial.verify.consensus and spatial.verify.screen."""
2
+
3
+ from .consensus import Consensus, VerificationError, consensus, verify_kernel
4
+ from .screen import ExecResult, ScreenReport, kernel_executors, screen, screen_kernel
5
+
6
+ __all__ = ["Consensus", "ExecResult", "ScreenReport", "VerificationError", "consensus", "kernel_executors",
7
+ "screen", "screen_kernel", "verify_kernel"]
@@ -0,0 +1,72 @@
1
+ """Redundant-execution verification: trust a result only if an independent second execution
2
+ agrees. The same comparison this project already made ad hoc between CPU and Metal kernel
3
+ output (tests/test_kernel.py), made into a reusable, documented primitive instead of a
4
+ one-off test.
5
+
6
+ Not cryptographic proof: no zkML, no TEE attestation. It is the cheap, economical check 2026
7
+ production systems actually use for decentralized/untrusted GPU markets -- redundant execution
8
+ or spot-check agreement, not a proof of correct floating-point GPU execution (see
9
+ docs/VERIFY.md for what this does and does not prove, and why).
10
+
11
+ No network calls here, no rented hardware, no money spent: this module only compares results
12
+ you already have. Actually renting two independent untrusted providers (e.g. two different
13
+ Vast.ai listings) and running a job on each is a separate, later, money-spending step that
14
+ needs explicit go-ahead each time -- same boundary as spatial.market's read-only pricing.
15
+ """
16
+
17
+ from dataclasses import dataclass
18
+
19
+ import numpy as np
20
+
21
+
22
+ class VerificationError(Exception):
23
+ pass
24
+
25
+
26
+ @dataclass(frozen=True)
27
+ class Consensus:
28
+ agreed: bool
29
+ max_abs_diff: float
30
+ n_results: int
31
+ reason: str
32
+
33
+
34
+ def consensus(results, *, tolerance: float = 0.0, exact: bool = False) -> Consensus:
35
+ """Compare 2+ independent results for the same job.
36
+
37
+ exact=True: every value must match bit-for-bit (integer/deterministic kernels); tolerance
38
+ is ignored. exact=False: the largest absolute difference across all pairs must be <=
39
+ tolerance (float kernels, which legitimately differ in the last bits between devices).
40
+
41
+ Raises VerificationError for fewer than 2 results or results of different shapes -- there
42
+ is nothing to verify by redundancy with only one result."""
43
+ if len(results) < 2:
44
+ raise VerificationError("need at least 2 independent results to verify by redundancy")
45
+ arrays = [np.asarray(r) for r in results]
46
+ shape = arrays[0].shape
47
+ for a in arrays[1:]:
48
+ if a.shape != shape:
49
+ raise VerificationError(f"shape mismatch: {shape} vs {a.shape}")
50
+ ref = arrays[0]
51
+ max_diff = 0.0
52
+ for a in arrays[1:]:
53
+ if exact:
54
+ if not np.array_equal(ref, a):
55
+ diff = np.abs(ref.astype(np.int64) - a.astype(np.int64))
56
+ return Consensus(False, float(diff.max()), len(results), "exact match required, results differ")
57
+ else:
58
+ diff = np.abs(ref.astype(np.float64) - a.astype(np.float64))
59
+ d = float(diff.max())
60
+ max_diff = max(max_diff, d)
61
+ if d > tolerance:
62
+ return Consensus(False, d, len(results), f"max absolute difference {d:g} exceeds tolerance {tolerance:g}")
63
+ return Consensus(True, max_diff, len(results), "bit-exact match" if exact else "agreement within tolerance")
64
+
65
+
66
+ def verify_kernel(kernel, devices, n: int, *, tolerance: float = 0.0, exact: bool = False, **params) -> Consensus:
67
+ """Run the same portable kernel on 2+ devices (e.g. ("cpu", "metal")) and check the results
68
+ agree. This is what redundant-execution verification looks like when the two independent
69
+ executions are two of this project's own devices rather than two rented, untrusted ones --
70
+ the only thing actually measurable here (no second machine to rent)."""
71
+ results = [kernel.run(d, n, **params) for d in devices]
72
+ return consensus(results, tolerance=tolerance, exact=exact)
@@ -0,0 +1,136 @@
1
+ """Fleet screening: run the same known-answer job on every executor, vote, quarantine the odd one out.
2
+
3
+ The mechanism large GPU fleets use against silent data corruption (periodic known-answer screening, outlier
4
+ against the fleet baseline) and against stragglers (a node much slower than its peers on an identical probe),
5
+ reduced to a small, testable, vendor-neutral core. An executor is any callable returning an array: a local
6
+ device, a remote node, a rented GPU.
7
+
8
+ What it does not do: no real GPU fault was ever observed here. The tests inject faults. Real corruption is
9
+ data-, voltage- and temperature-dependent (NVIDIA/OCP white paper) and a few known-answer kernels will not
10
+ cover that test space; this finds gross or systematic miscomputation and gross slowness, not rare faults.
11
+ """
12
+
13
+ import hashlib
14
+ import statistics
15
+ import time
16
+ from dataclasses import dataclass
17
+
18
+ import numpy as np
19
+
20
+ from .consensus import VerificationError
21
+
22
+
23
+ @dataclass(frozen=True)
24
+ class ExecResult:
25
+ name: str
26
+ status: str # "ok" | "outlier" | "undetermined" | "error"
27
+ seconds: float
28
+ digest: str
29
+ error: str = ""
30
+
31
+
32
+ @dataclass(frozen=True)
33
+ class ScreenReport:
34
+ results: tuple
35
+ majority: str | None
36
+ outliers: tuple
37
+ errors: tuple
38
+ stragglers: tuple
39
+ reason: str
40
+
41
+ @property
42
+ def healthy(self) -> bool:
43
+ return self.majority is not None and not (self.outliers or self.errors or self.stragglers)
44
+
45
+
46
+ def _digest(arr) -> str:
47
+ a = np.ascontiguousarray(arr)
48
+ h = hashlib.sha256()
49
+ h.update(str((a.shape, a.dtype.str)).encode())
50
+ h.update(a.tobytes())
51
+ return h.hexdigest()
52
+
53
+
54
+ def screen(executors: dict, *, clock=time.perf_counter, straggler_factor: float = 2.0,
55
+ straggler_min_gap_s: float = 0.05) -> ScreenReport:
56
+ """Run every executor once and compare. Needs 2+ executors; 3+ to say WHICH one is wrong (with two that
57
+ disagree, nobody can tell). A majority must hold strictly more than half of the executors that ran.
58
+ Stragglers are judged within a group of 3+ executors sharing the same `.kind` attribute on their callable
59
+ (unset = one shared group)."""
60
+ if len(executors) < 2:
61
+ raise VerificationError("need at least 2 executors to screen")
62
+ raw = []
63
+ for name, fn in executors.items():
64
+ t0 = clock()
65
+ try:
66
+ digest, err = _digest(np.asarray(fn())), ""
67
+ except Exception as e: # a broken executor is a finding, not a crash
68
+ digest, err = "", f"{type(e).__name__}: {e}"
69
+ raw.append((name, digest, clock() - t0, err))
70
+ oks = [r for r in raw if not r[3]]
71
+ counts: dict = {}
72
+ for _, d, _, _ in oks:
73
+ counts[d] = counts.get(d, 0) + 1
74
+ majority = None
75
+ if counts:
76
+ top, c = max(counts.items(), key=lambda kv: kv[1])
77
+ if c >= 2 and c > len(oks) / 2:
78
+ majority = top
79
+ results, outliers, errors = [], [], []
80
+ for name, d, s, err in raw:
81
+ if err:
82
+ status = "error"
83
+ errors.append(name)
84
+ elif majority is None:
85
+ status = "ok" if len(counts) == 1 else "undetermined"
86
+ elif d == majority:
87
+ status = "ok"
88
+ else:
89
+ status = "outlier"
90
+ outliers.append(name)
91
+ results.append(ExecResult(name, status, s, d, err))
92
+ stragglers = []
93
+ groups: dict = {}
94
+ for n, _, s, _ in oks:
95
+ groups.setdefault(getattr(executors[n], "kind", None), []).append((n, s))
96
+ for g in groups.values(): # a CPU is not a straggler against GPUs: judge within a kind
97
+ if len(g) >= 3:
98
+ med = statistics.median(s for _, s in g)
99
+ stragglers += [n for n, s in g if s > straggler_factor * med and s - med >= straggler_min_gap_s]
100
+ if not oks:
101
+ reason = "every executor failed"
102
+ elif majority is None and len(counts) > 1:
103
+ reason = ("results disagree and no majority exists: with only two executors nobody can tell which is wrong"
104
+ if len(oks) == 2 else "results disagree and no majority exists")
105
+ elif outliers:
106
+ reason = f"outlier(s) against a {counts[majority]}-of-{len(oks)} majority: {', '.join(outliers)}"
107
+ elif errors:
108
+ reason = f"executor(s) failed: {', '.join(errors)}"
109
+ elif stragglers:
110
+ reason = f"all agree, but slow against the median: {', '.join(stragglers)}"
111
+ else:
112
+ reason = f"all {len(oks)} executors agree"
113
+ return ScreenReport(tuple(results), majority, tuple(outliers), tuple(errors), tuple(stragglers), reason)
114
+
115
+
116
+ def kernel_executors(kernel, devices, n: int, **params) -> dict:
117
+ """One executor per entry of `devices`; repeated names get a #index suffix. Kernel runs are warmed up once
118
+ (JIT/compile) so the straggler check does not measure compilation."""
119
+ for d in dict.fromkeys(devices):
120
+ try:
121
+ kernel.run(d, 8, **params)
122
+ except Exception:
123
+ pass # surfaces as an error result in the real run
124
+ def make(d):
125
+ def run():
126
+ return kernel.run(d, n, **params)
127
+ run.kind = d # screen() judges stragglers only among the same kind
128
+ return run
129
+ out = {}
130
+ for i, d in enumerate(devices):
131
+ out[d if list(devices).count(d) == 1 else f"{d}#{i}"] = make(d)
132
+ return out
133
+
134
+
135
+ def screen_kernel(kernel, devices, n: int, **params) -> ScreenReport:
136
+ return screen(kernel_executors(kernel, devices, n, **params))
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: spatial-computing
3
- Version: 0.28.0
3
+ Version: 0.30.0
4
4
  Summary: Spatial Computing: open-source infrastructure efficiency toolkit. Measure, decide, prove (compute, tiered memory, runtime routing, fleet)
5
5
  Author: Spatial Computing contributors
6
6
  License-Expression: Apache-2.0
@@ -103,6 +103,7 @@ st.put(0, b"..." * 1000); st.get(0); print(st.stats())
103
103
  | Portable kernels (one source, CPU/Metal/CUDA/HIP/Triton; market-vertical presets) | first components | `tests/test_kernel.py`, `benchmarks/bench_kernel.py` |
104
104
  | Live GPU market prices (`spatial market`, read-only, no account) | first components | `tests/test_market.py`, [docs/MARKET.md](docs/MARKET.md) |
105
105
  | In-vehicle multi-chip placement (`spatial automotive`, declared chip specs, no real silicon) | first components | `tests/test_automotive.py`, [docs/AUTOMOTIVE.md](docs/AUTOMOTIVE.md) |
106
+ | Redundant-execution verification and fleet screening (`spatial verify`, `spatial screen`; faults injected in tests, not cryptographic, see limits) | first components | `tests/test_verify.py`, `tests/test_screen.py`, [docs/VERIFY.md](docs/VERIFY.md) |
106
107
  | AI, Intelligence | first components (toy model) | `tests/test_engines.py`, `tests/test_domains.py` |
107
108
 
108
109
  Measured on the reference machine (AC power): Numba JIT ×31.6 over pure Python with an identical result; 0.88 s to boot an isolated Linux micro-VM on macOS; −75 % local RAM for a skewed-access dataset at 107× the mean access latency. Full table and conditions: [docs/RESULTATS.fr.md](docs/RESULTATS.fr.md).
@@ -1,5 +1,5 @@
1
- spatial/__init__.py,sha256=5MiKi5WHuF0szxJzhJMtA02suPdCaOOLnKHmHo3tHSE,208
2
- spatial/cli.py,sha256=fHQCKRMnsm58Dcx8NDBrH6TQF2SNLHA-CPf01bYN2Hc,23627
1
+ spatial/__init__.py,sha256=ldJNFaB2fFoL3QyPLfdsmliJgA2wf6JuLDDXik__Cfk,208
2
+ spatial/cli.py,sha256=0EiMXF5WS_1PSF5FCI6IU_EUqmiQJWWSOScR3jfp4O4,27108
3
3
  spatial/ai/__init__.py,sha256=qrQZBRNCGwnMp_Rx7HNblvGfgmLApVrdIAPcYVmZdCg,926
4
4
  spatial/ai/kvcache.py,sha256=7xrNI3zBKSoLA9ZjI1U2TZQ7GdXMZDzZq50qBrbWAWY,4054
5
5
  spatial/ai/llm.py,sha256=-e_F4giPVlc_R9AiDX0LT4LFf-gmnAIhlfNZDW07Sig,2292
@@ -91,9 +91,12 @@ spatial/unified/__init__.py,sha256=-pRHK15GyeXStIKLHLxDQMN72pelTaBHJMaPpT-MODI,6
91
91
  spatial/unified/model.py,sha256=Glban2XOL48_262IKtBR2ESMrFrvImHDHbDo2B8GK8I,6336
92
92
  spatial/unified/planner.py,sha256=kdpzCpZJ-RdjCj8MNaES4TPdSug0skSQ53pKUi2Q-Bo,5429
93
93
  spatial/unified/providers.py,sha256=36GMPSdyu8xuNtzlkWJ2XNOj8fZntJJlrO63gcWjXHA,21010
94
- spatial_computing-0.28.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
95
- spatial_computing-0.28.0.dist-info/METADATA,sha256=91DD4Y80yfiaR96FxK3hcIFQw53CpmmuAA2t9KCrjS8,6967
96
- spatial_computing-0.28.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
97
- spatial_computing-0.28.0.dist-info/entry_points.txt,sha256=2o6Kjkd0lkEd-qQgFuW-ptYOh4RmnHFPyvwzP2KiMS0,45
98
- spatial_computing-0.28.0.dist-info/top_level.txt,sha256=ZHke8hWgy4qIqEGq7omus3O-T7AhmPoc-cqr7JdGGxQ,8
99
- spatial_computing-0.28.0.dist-info/RECORD,,
94
+ spatial/verify/__init__.py,sha256=eBditY6H6tTdL112GXb5OBuvfn1ILWjUseXO9SJ1TQM,445
95
+ spatial/verify/consensus.py,sha256=IVTSeuHAZOLVrSJ5y26kspXaM70z6JasYQYOPLe3g60,3450
96
+ spatial/verify/screen.py,sha256=9iDaifkznjjHeDpj-IZLTOz_t4ry7AUjCqCrD6zdPM0,5523
97
+ spatial_computing-0.30.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
98
+ spatial_computing-0.30.0.dist-info/METADATA,sha256=MXNn-p2bo2CaXdNx6xQf7cs8ekkqt-Amfiwb6NF5jkg,7220
99
+ spatial_computing-0.30.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
100
+ spatial_computing-0.30.0.dist-info/entry_points.txt,sha256=2o6Kjkd0lkEd-qQgFuW-ptYOh4RmnHFPyvwzP2KiMS0,45
101
+ spatial_computing-0.30.0.dist-info/top_level.txt,sha256=ZHke8hWgy4qIqEGq7omus3O-T7AhmPoc-cqr7JdGGxQ,8
102
+ spatial_computing-0.30.0.dist-info/RECORD,,