spatial-computing 0.11.0__tar.gz → 0.12.1__tar.gz
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_computing-0.11.0 → spatial_computing-0.12.1}/PKG-INFO +2 -2
- {spatial_computing-0.11.0 → spatial_computing-0.12.1}/README.md +1 -1
- {spatial_computing-0.11.0 → spatial_computing-0.12.1}/pyproject.toml +1 -1
- {spatial_computing-0.11.0 → spatial_computing-0.12.1}/spatial/__init__.py +1 -1
- {spatial_computing-0.11.0 → spatial_computing-0.12.1}/spatial/compute/workloads.py +26 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.1}/spatial/core/protocol.py +17 -2
- {spatial_computing-0.11.0 → spatial_computing-0.12.1}/spatial/core/registry.py +6 -0
- spatial_computing-0.12.1/spatial/fabric/metal.py +85 -0
- spatial_computing-0.12.1/spatial/fabric/metal_run.swift +52 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.1}/spatial/fleet/hub.py +199 -19
- spatial_computing-0.12.1/spatial/interconnect/__init__.py +10 -0
- spatial_computing-0.12.1/spatial/interconnect/collectives.py +102 -0
- spatial_computing-0.12.1/spatial/interconnect/comm.py +114 -0
- spatial_computing-0.12.1/spatial/interconnect/model.py +77 -0
- spatial_computing-0.12.1/spatial/interconnect/tasks.py +72 -0
- spatial_computing-0.12.1/spatial/kernel/__init__.py +3 -0
- spatial_computing-0.12.1/spatial/kernel/dsl.py +389 -0
- spatial_computing-0.12.1/spatial/kernel/library.py +46 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.1}/spatial/unified/providers.py +5 -1
- {spatial_computing-0.11.0 → spatial_computing-0.12.1}/spatial_computing.egg-info/PKG-INFO +2 -2
- {spatial_computing-0.11.0 → spatial_computing-0.12.1}/spatial_computing.egg-info/SOURCES.txt +12 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.1}/tests/test_fabric.py +25 -12
- {spatial_computing-0.11.0 → spatial_computing-0.12.1}/tests/test_fleet.py +110 -0
- spatial_computing-0.12.1/tests/test_hardening.py +172 -0
- spatial_computing-0.12.1/tests/test_interconnect.py +50 -0
- spatial_computing-0.12.1/tests/test_kernel.py +96 -0
- spatial_computing-0.11.0/spatial/fabric/metal.py +0 -46
- {spatial_computing-0.11.0 → spatial_computing-0.12.1}/LICENSE +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.1}/setup.cfg +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.1}/spatial/ai/__init__.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.1}/spatial/ai/kvcache.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.1}/spatial/cli.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.1}/spatial/compute/__init__.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.1}/spatial/compute/cost.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.1}/spatial/compute/detect.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.1}/spatial/compute/monitor.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.1}/spatial/compute/scheduler.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.1}/spatial/compute/taskqueue.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.1}/spatial/compute/worker.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.1}/spatial/core/__init__.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.1}/spatial/core/auth.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.1}/spatial/core/energy.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.1}/spatial/core/ledger.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.1}/spatial/core/model.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.1}/spatial/fabric/__init__.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.1}/spatial/fabric/cuda.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.1}/spatial/fabric/devices.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.1}/spatial/fabric/metal_mandel.swift +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.1}/spatial/fleet/__init__.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.1}/spatial/fleet/agent.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.1}/spatial/holographic/__init__.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.1}/spatial/holographic/cgh.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.1}/spatial/holographic/model.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.1}/spatial/intelligence/__init__.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.1}/spatial/intelligence/predictor.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.1}/spatial/memory/__init__.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.1}/spatial/memory/fararray.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.1}/spatial/memory/pageserver.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.1}/spatial/memory/secure.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.1}/spatial/memory/shared.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.1}/spatial/memory/tiered.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.1}/spatial/q/__init__.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.1}/spatial/q/__main__.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.1}/spatial/q/backends/__init__.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.1}/spatial/q/codegen.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.1}/spatial/q/compiler.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.1}/spatial/q/ir.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.1}/spatial/q/lexer.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.1}/spatial/q/parser.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.1}/spatial/q/qir.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.1}/spatial/q/runtime.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.1}/spatial/q/sim.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.1}/spatial/runtime/__init__.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.1}/spatial/runtime/envs.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.1}/spatial/runtime/inspect.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.1}/spatial/runtime/microvm.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.1}/spatial/runtime/planner.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.1}/spatial/runtime/runner.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.1}/spatial/runtime/toolchain.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.1}/spatial/scientific/__init__.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.1}/spatial/scientific/jobs.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.1}/spatial/simulation/__init__.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.1}/spatial/simulation/heat.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.1}/spatial/simulation/nbody.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.1}/spatial/unified/__init__.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.1}/spatial/unified/model.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.1}/spatial/unified/planner.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.1}/spatial_computing.egg-info/dependency_links.txt +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.1}/spatial_computing.egg-info/entry_points.txt +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.1}/spatial_computing.egg-info/requires.txt +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.1}/spatial_computing.egg-info/top_level.txt +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.1}/tests/test_auth.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.1}/tests/test_compute.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.1}/tests/test_core.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.1}/tests/test_domains.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.1}/tests/test_engines.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.1}/tests/test_memory.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.1}/tests/test_optimizer.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.1}/tests/test_q.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.1}/tests/test_runtime.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.1}/tests/test_unified.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.1}/tests/test_v02.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.1}/tests/test_v03.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.1}/tests/test_v05.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.1}/tests/test_v07.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: spatial-computing
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.12.1
|
|
4
4
|
Summary: Spatial Computing: open-source infrastructure efficiency toolkit. Measure, decide, prove (compute, tiered memory, runtime routing, hybrid quantum language)
|
|
5
5
|
Author: Spatial Computing contributors
|
|
6
6
|
License-Expression: Apache-2.0
|
|
@@ -37,7 +37,7 @@ Dynamic: license-file
|
|
|
37
37
|
|
|
38
38
|
One objective for the whole infrastructure: get every job done correctly at the lowest cost, and prove it. Spatial Computing prices every way to run a job across compute, memory, runtime, quantum, AI, science and a fleet of machines, picks the cheapest, and records the estimate next to what really happened. A gain is claimed only when it is measured. It does not add RAM, cores or GPUs: it compares execution strategies on the hardware you have, trades one resource for another in numbers, and says plainly what it cannot do.
|
|
39
39
|
|
|
40
|
-
> **Status: v0.
|
|
40
|
+
> **Status: v0.12.1, early-stage open-source toolkit.** Everything here was built and measured on a single 2017 MacBook Pro (Intel i7-7660U, 2 cores, 16 GB). Nothing has been proven on a second machine, a data-center GPU or a real quantum computer. See [Limitations](docs/LIMITATIONS.md) and the [site](https://spatial-computing-ecru.vercel.app).
|
|
41
41
|
|
|
42
42
|
[Français](README.fr.md)
|
|
43
43
|
|
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
|
|
5
5
|
One objective for the whole infrastructure: get every job done correctly at the lowest cost, and prove it. Spatial Computing prices every way to run a job across compute, memory, runtime, quantum, AI, science and a fleet of machines, picks the cheapest, and records the estimate next to what really happened. A gain is claimed only when it is measured. It does not add RAM, cores or GPUs: it compares execution strategies on the hardware you have, trades one resource for another in numbers, and says plainly what it cannot do.
|
|
6
6
|
|
|
7
|
-
> **Status: v0.
|
|
7
|
+
> **Status: v0.12.1, early-stage open-source toolkit.** Everything here was built and measured on a single 2017 MacBook Pro (Intel i7-7660U, 2 cores, 16 GB). Nothing has been proven on a second machine, a data-center GPU or a real quantum computer. See [Limitations](docs/LIMITATIONS.md) and the [site](https://spatial-computing-ecru.vercel.app).
|
|
8
8
|
|
|
9
9
|
[Français](README.fr.md)
|
|
10
10
|
|
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "spatial-computing"
|
|
7
|
-
version = "0.
|
|
7
|
+
version = "0.12.1"
|
|
8
8
|
description = "Spatial Computing: open-source infrastructure efficiency toolkit. Measure, decide, prove (compute, tiered memory, runtime routing, hybrid quantum language)"
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
license = "Apache-2.0"
|
|
@@ -142,6 +142,28 @@ def mandel_f32_cuda(n: int, iters: int) -> int:
|
|
|
142
142
|
return cuda.mandel(n, iters)
|
|
143
143
|
|
|
144
144
|
|
|
145
|
+
def _pk(name: str, device: str, n: int, **params) -> int:
|
|
146
|
+
from ..kernel.library import LIBRARY
|
|
147
|
+
return int(LIBRARY[name].run(device, n, **params).astype("uint64").sum())
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def pk_mandel_cpu(n: int, iters: int) -> int:
|
|
151
|
+
"""Portable kernel (spatial.kernel) on the CPU: the SAME source as the Metal variant."""
|
|
152
|
+
return _pk("mandelbrot", "cpu", n, iters=iters)
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def pk_mandel_metal(n: int, iters: int) -> int:
|
|
156
|
+
return _pk("mandelbrot", "metal", n, iters=iters)
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def pk_collatz_cpu(n: int, limit: int) -> int:
|
|
160
|
+
return _pk("collatz", "cpu", n, limit=limit)
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def pk_collatz_metal(n: int, limit: int) -> int:
|
|
164
|
+
return _pk("collatz", "metal", n, limit=limit)
|
|
165
|
+
|
|
166
|
+
|
|
145
167
|
def montecarlo_pi(samples: int, seed: int = 0) -> float:
|
|
146
168
|
rng = np.random.default_rng(seed)
|
|
147
169
|
inside = 0
|
|
@@ -231,6 +253,10 @@ REGISTRY = {
|
|
|
231
253
|
"mandel_f32_cpu": mandel_f32_cpu,
|
|
232
254
|
"mandel_f32_metal": mandel_f32_metal,
|
|
233
255
|
"mandel_f32_cuda": mandel_f32_cuda,
|
|
256
|
+
"pk_mandel_cpu": pk_mandel_cpu,
|
|
257
|
+
"pk_mandel_metal": pk_mandel_metal,
|
|
258
|
+
"pk_collatz_cpu": pk_collatz_cpu,
|
|
259
|
+
"pk_collatz_metal": pk_collatz_metal,
|
|
234
260
|
"heat_numpy": heat_numpy,
|
|
235
261
|
"heat_numba": heat_numba,
|
|
236
262
|
"nbody": nbody,
|
|
@@ -86,6 +86,8 @@ class SecureChannel:
|
|
|
86
86
|
if _HDR.size + hl + bl != len(plain):
|
|
87
87
|
raise ValueError("malformed record")
|
|
88
88
|
header = json.loads(plain[_HDR.size:_HDR.size + hl]) if hl else {}
|
|
89
|
+
if not isinstance(header, dict):
|
|
90
|
+
raise ValueError("header must be a JSON object")
|
|
89
91
|
return header, plain[_HDR.size + hl:]
|
|
90
92
|
|
|
91
93
|
|
|
@@ -104,7 +106,8 @@ class RpcServer:
|
|
|
104
106
|
"""
|
|
105
107
|
|
|
106
108
|
def __init__(self, handler: Handler, token: bytes | None = None, host: str = "127.0.0.1",
|
|
107
|
-
port: int = 0, allow_remote: bool = False, authorizer: "auth.Authorizer | None" = None
|
|
109
|
+
port: int = 0, allow_remote: bool = False, authorizer: "auth.Authorizer | None" = None,
|
|
110
|
+
handshake_timeout_s: float = 10.0, max_connections: int = 512):
|
|
108
111
|
if host not in ("127.0.0.1", "localhost", "::1") and not allow_remote:
|
|
109
112
|
raise PermissionError(
|
|
110
113
|
"refusing to bind a non-loopback address without allow_remote=True "
|
|
@@ -112,11 +115,21 @@ class RpcServer:
|
|
|
112
115
|
if token is None and authorizer is None:
|
|
113
116
|
raise ValueError("RpcServer needs a token or an authorizer")
|
|
114
117
|
outer = self
|
|
118
|
+
slots = threading.BoundedSemaphore(max_connections) # one thread per connection: cap them
|
|
115
119
|
|
|
116
120
|
class _H(socketserver.BaseRequestHandler):
|
|
117
121
|
def handle(self):
|
|
122
|
+
if not slots.acquire(blocking=False):
|
|
123
|
+
return # over the cap: drop before any work
|
|
124
|
+
try:
|
|
125
|
+
self._serve()
|
|
126
|
+
finally:
|
|
127
|
+
slots.release()
|
|
128
|
+
|
|
129
|
+
def _serve(self):
|
|
118
130
|
s = self.request
|
|
119
131
|
s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
|
|
132
|
+
s.settimeout(handshake_timeout_s) # a silent peer must not hold a thread forever
|
|
120
133
|
eph = X25519PrivateKey.generate()
|
|
121
134
|
pub_s = eph.public_key().public_bytes(**_RAW)
|
|
122
135
|
nonce_s = os.urandom(16)
|
|
@@ -142,10 +155,11 @@ class RpcServer:
|
|
|
142
155
|
return # silent drop on bad auth
|
|
143
156
|
shared = eph.exchange(X25519PublicKey.from_public_bytes(pub_c))
|
|
144
157
|
ch = SecureChannel(s, shared + secret, nonce_s, nonce_c, is_server=True)
|
|
158
|
+
s.settimeout(None) # authenticated peers may stay idle (agents poll)
|
|
145
159
|
while True:
|
|
146
160
|
try:
|
|
147
161
|
header, blob = ch.recv()
|
|
148
|
-
except (ConnectionError, OSError, ValueError):
|
|
162
|
+
except (ConnectionError, OSError, ValueError, struct.error):
|
|
149
163
|
return
|
|
150
164
|
op = str(header.get("op"))
|
|
151
165
|
try:
|
|
@@ -167,6 +181,7 @@ class RpcServer:
|
|
|
167
181
|
class _S(socketserver.ThreadingTCPServer):
|
|
168
182
|
allow_reuse_address = True
|
|
169
183
|
daemon_threads = True
|
|
184
|
+
request_queue_size = 1024 # the default backlog of 5 refused simultaneous reconnects (found by the scale test)
|
|
170
185
|
|
|
171
186
|
self.handler = handler
|
|
172
187
|
self._srv = _S((host, port), _H)
|
|
@@ -32,6 +32,12 @@ ENGINES: list[Engine] = [
|
|
|
32
32
|
Engine("fabric", "Virtual accelerator fabric", "spatial.fabric", Status.FIRST_COMPONENTS,
|
|
33
33
|
"tests/test_fabric.py, benchmarks/bench_unified.py (FABRIC=1: 7 of 7 device choices correct)",
|
|
34
34
|
"CPU and Metal GPU tested; the NVIDIA (numba.cuda) path is written and never run on real NVIDIA hardware; one job family; no host-device transfer model"),
|
|
35
|
+
Engine("interconnect", "Virtual interconnect (collectives)", "spatial.interconnect", Status.FIRST_COMPONENTS,
|
|
36
|
+
"tests/test_interconnect.py, benchmarks/bench_interconnect.py (uncalibrated model right 1 of 6; calibrated per algorithm 4 of 6)",
|
|
37
|
+
"N = 4 and 8 processes on one machine over loopback; no real network, RDMA or GPU memory; about 3,000x slower than NVLink 5 (vendor figure); no fault tolerance"),
|
|
38
|
+
Engine("kernel", "Portable kernels", "spatial.kernel", Status.FIRST_COMPONENTS,
|
|
39
|
+
"tests/test_kernel.py, benchmarks/bench_kernel.py (planner right 4 of 6; integer kernel bit-identical CPU vs Metal)",
|
|
40
|
+
"CUDA C generated, never compiled or run; one kernel shape (2-D per-element, no shared memory or reductions)"),
|
|
35
41
|
Engine("planner", "Spatial Planner (the one objective)", "spatial.unified", Status.OPERATIONAL_PROTOTYPE,
|
|
36
42
|
"tests/test_unified.py",
|
|
37
43
|
"estimates come from probes and measured constants on one machine; calibration is a median of past ratios; no learned model; fleet and QPU pricing need the caller's prices"),
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
"""Metal compute backend (macOS): compiles the bundled Swift program once, then runs it per job."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
import platform
|
|
6
|
+
import shutil
|
|
7
|
+
import subprocess
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
SRC = Path(__file__).with_name("metal_mandel.swift")
|
|
11
|
+
CACHE = Path.home() / ".cache" / "spatial"
|
|
12
|
+
BIN = CACHE / "metal_mandel"
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def available() -> bool:
|
|
16
|
+
return platform.system() == "Darwin" and (BIN.exists() or shutil.which("swiftc") is not None)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def ensure_binary() -> Path:
|
|
20
|
+
if BIN.exists() and BIN.stat().st_mtime >= SRC.stat().st_mtime:
|
|
21
|
+
return BIN
|
|
22
|
+
if platform.system() != "Darwin" or not shutil.which("swiftc"):
|
|
23
|
+
raise RuntimeError("Metal backend needs macOS and swiftc")
|
|
24
|
+
CACHE.mkdir(parents=True, exist_ok=True)
|
|
25
|
+
r = subprocess.run(["swiftc", "-O", str(SRC), "-o", str(BIN)], capture_output=True, text=True, timeout=600)
|
|
26
|
+
if r.returncode != 0:
|
|
27
|
+
raise RuntimeError("swiftc failed: " + r.stderr[-300:])
|
|
28
|
+
return BIN
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def mandel(n: int, iters: int, reps: int = 1) -> dict:
|
|
32
|
+
out = subprocess.run([str(ensure_binary()), str(n), str(iters), str(reps)], capture_output=True, text=True, timeout=600)
|
|
33
|
+
try:
|
|
34
|
+
d = json.loads(out.stdout.strip().splitlines()[-1])
|
|
35
|
+
except Exception:
|
|
36
|
+
raise RuntimeError("Metal program failed: " + (out.stdout + out.stderr)[-300:])
|
|
37
|
+
if not d.get("ok"):
|
|
38
|
+
raise RuntimeError(d.get("error", "Metal error"))
|
|
39
|
+
return d
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def device_name() -> str | None:
|
|
43
|
+
try:
|
|
44
|
+
return mandel(8, 8, 1)["device"]
|
|
45
|
+
except Exception:
|
|
46
|
+
return None
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
RUN_SRC = Path(__file__).with_name("metal_run.swift")
|
|
50
|
+
RUN_BIN = CACHE / "metal_run"
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _ensure_run_binary() -> Path:
|
|
54
|
+
if RUN_BIN.exists() and RUN_BIN.stat().st_mtime >= RUN_SRC.stat().st_mtime:
|
|
55
|
+
return RUN_BIN
|
|
56
|
+
if platform.system() != "Darwin" or not shutil.which("swiftc"):
|
|
57
|
+
raise RuntimeError("Metal backend needs macOS and swiftc")
|
|
58
|
+
CACHE.mkdir(parents=True, exist_ok=True)
|
|
59
|
+
r = subprocess.run(["swiftc", "-O", str(RUN_SRC), "-o", str(RUN_BIN)], capture_output=True, text=True, timeout=600)
|
|
60
|
+
if r.returncode != 0:
|
|
61
|
+
raise RuntimeError("swiftc failed: " + r.stderr[-300:])
|
|
62
|
+
return RUN_BIN
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def run_kernel(k, n: int, params: dict, reps: int = 1, timing: dict | None = None):
|
|
66
|
+
"""Run a portable Kernel (spatial.kernel) on the Metal GPU; returns the (n, n) uint32 output.
|
|
67
|
+
`timing`, if given, receives the GPU-side median seconds."""
|
|
68
|
+
import numpy as np
|
|
69
|
+
import tempfile
|
|
70
|
+
binary = _ensure_run_binary()
|
|
71
|
+
with tempfile.TemporaryDirectory() as d:
|
|
72
|
+
msl, out = Path(d) / "k.metal", Path(d) / "out.bin"
|
|
73
|
+
msl.write_text(k.to_metal())
|
|
74
|
+
args = [str(binary), str(msl), k.name, str(n), str(reps), str(out)]
|
|
75
|
+
args += [f"{t}:{float(params[p]) if t == 'float' else int(params[p])}" for p, t in k.params]
|
|
76
|
+
r = subprocess.run(args, capture_output=True, text=True, timeout=600)
|
|
77
|
+
try:
|
|
78
|
+
info = json.loads(r.stdout.strip().splitlines()[-1])
|
|
79
|
+
except Exception:
|
|
80
|
+
raise RuntimeError("Metal program failed: " + (r.stdout + r.stderr)[-300:])
|
|
81
|
+
if not info.get("ok"):
|
|
82
|
+
raise RuntimeError(info.get("error", "Metal error"))
|
|
83
|
+
if timing is not None:
|
|
84
|
+
timing.update(info)
|
|
85
|
+
return np.fromfile(out, dtype=np.uint32).reshape(n, n)
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
// Generic Metal host for portable kernels generated by spatial.kernel.
|
|
2
|
+
// usage: metal_run <msl_file> <kernel_name> <n> <reps> <out_file> [int:<v> | float:<v> ...]
|
|
3
|
+
// Buffers: 0 = output uint[n*n], 1 = n (int), 2.. = parameters in order. Writes raw uint32 to <out_file>.
|
|
4
|
+
import Foundation
|
|
5
|
+
import Metal
|
|
6
|
+
|
|
7
|
+
func now() -> Double { return Double(DispatchTime.now().uptimeNanoseconds) / 1e9 }
|
|
8
|
+
func fail(_ m: String) -> Never { print("{\"ok\": false, \"error\": \"\(m)\"}"); exit(1) }
|
|
9
|
+
|
|
10
|
+
let a = CommandLine.arguments
|
|
11
|
+
if a.count < 6 { fail("usage") }
|
|
12
|
+
guard let src = try? String(contentsOfFile: a[1], encoding: .utf8) else { fail("cannot read msl") }
|
|
13
|
+
let name = a[2], n = Int(a[3])!, reps = max(1, Int(a[4])!), outPath = a[5]
|
|
14
|
+
guard let dev = MTLCreateSystemDefaultDevice() ?? MTLCopyAllDevices().first else { fail("no Metal device") }
|
|
15
|
+
let t0 = now()
|
|
16
|
+
let lib: MTLLibrary
|
|
17
|
+
do { lib = try dev.makeLibrary(source: src, options: nil) } catch {
|
|
18
|
+
let msg = "\(error)".replacingOccurrences(of: "\"", with: "'").replacingOccurrences(of: "\n", with: " ")
|
|
19
|
+
fail("shader compile failed: " + String(msg.prefix(300)))
|
|
20
|
+
}
|
|
21
|
+
guard let fn = lib.makeFunction(name: name) else { fail("kernel not found") }
|
|
22
|
+
let pipe = try! dev.makeComputePipelineState(function: fn)
|
|
23
|
+
let setupS = now() - t0
|
|
24
|
+
let out = dev.makeBuffer(length: n * n * 4, options: .storageModeShared)!
|
|
25
|
+
let queue = dev.makeCommandQueue()!
|
|
26
|
+
var nn = Int32(n)
|
|
27
|
+
|
|
28
|
+
func run() -> Double {
|
|
29
|
+
let t = now()
|
|
30
|
+
let cb = queue.makeCommandBuffer()!
|
|
31
|
+
let enc = cb.makeComputeCommandEncoder()!
|
|
32
|
+
enc.setComputePipelineState(pipe)
|
|
33
|
+
enc.setBuffer(out, offset: 0, index: 0)
|
|
34
|
+
enc.setBytes(&nn, length: 4, index: 1)
|
|
35
|
+
for (k, spec) in a[6...].enumerated() {
|
|
36
|
+
let parts = spec.split(separator: ":", maxSplits: 1).map(String.init)
|
|
37
|
+
if parts[0] == "int" { var v = Int32(parts[1])!; enc.setBytes(&v, length: 4, index: 2 + k) }
|
|
38
|
+
else { var v = Float(parts[1])!; enc.setBytes(&v, length: 4, index: 2 + k) }
|
|
39
|
+
}
|
|
40
|
+
let w = pipe.threadExecutionWidth
|
|
41
|
+
let h = pipe.maxTotalThreadsPerThreadgroup / w
|
|
42
|
+
enc.dispatchThreadgroups(MTLSize(width: (n + w - 1) / w, height: (n + h - 1) / h, depth: 1),
|
|
43
|
+
threadsPerThreadgroup: MTLSize(width: w, height: h, depth: 1))
|
|
44
|
+
enc.endEncoding(); cb.commit(); cb.waitUntilCompleted()
|
|
45
|
+
return now() - t
|
|
46
|
+
}
|
|
47
|
+
var times: [Double] = []
|
|
48
|
+
for _ in 0..<reps { times.append(run()) }
|
|
49
|
+
let data = Data(bytes: out.contents(), count: n * n * 4)
|
|
50
|
+
do { try data.write(to: URL(fileURLWithPath: outPath)) } catch { fail("cannot write output") }
|
|
51
|
+
times.sort()
|
|
52
|
+
print("{\"ok\": true, \"device\": \"\(dev.name)\", \"gpu_s_median\": \(times[times.count / 2]), \"setup_s\": \(setupS)}")
|
|
@@ -12,6 +12,8 @@ from __future__ import annotations
|
|
|
12
12
|
|
|
13
13
|
import argparse
|
|
14
14
|
import itertools
|
|
15
|
+
import json
|
|
16
|
+
import os
|
|
15
17
|
import math
|
|
16
18
|
import threading
|
|
17
19
|
import time
|
|
@@ -29,7 +31,7 @@ HISTORY = 2000 # samples kept per node
|
|
|
29
31
|
|
|
30
32
|
class Hub:
|
|
31
33
|
def __init__(self, ledger: Ledger | None = None, stale_after_s: float = 30.0, clock=time.time,
|
|
32
|
-
busy_cpu_pct: float = 90.0):
|
|
34
|
+
busy_cpu_pct: float = 90.0, gang_hold_s: float = 30.0, affinity_wait_s: float = 5.0):
|
|
33
35
|
self.nodes: dict[str, dict] = {}
|
|
34
36
|
self.series: dict[str, deque] = {}
|
|
35
37
|
self.tasks: dict[int, dict] = {}
|
|
@@ -40,6 +42,12 @@ class Hub:
|
|
|
40
42
|
self.busy_cpu_pct = busy_cpu_pct
|
|
41
43
|
self._ids = itertools.count(1)
|
|
42
44
|
self._lock = threading.RLock()
|
|
45
|
+
self.gang_hold_s = gang_hold_s # how long idle nodes are held for a gang that has started
|
|
46
|
+
self.affinity_wait_s = affinity_wait_s # how long a task waits for the node that holds its cache
|
|
47
|
+
self.weights: dict[str, float] = {} # tenant -> share weight (default 1)
|
|
48
|
+
self.usage: dict[str, float] = {} # tenant -> finished compute-seconds
|
|
49
|
+
self.gangs: dict[int, dict] = {}
|
|
50
|
+
self.affinity: dict[str, str] = {} # cache key -> node that last ran it
|
|
43
51
|
|
|
44
52
|
# ------------------------------------------------------------------ identity
|
|
45
53
|
@staticmethod
|
|
@@ -69,16 +77,51 @@ class Hub:
|
|
|
69
77
|
n["latest"] = {**m, "ts": ts}
|
|
70
78
|
self.series.setdefault(node, deque(maxlen=HISTORY)).append((ts, m))
|
|
71
79
|
|
|
72
|
-
def submit(self, workload: str, params: dict, needs: dict | None = None, priority: int = 10
|
|
80
|
+
def submit(self, workload: str, params: dict, needs: dict | None = None, priority: int = 10,
|
|
81
|
+
tenant: str = "default", _gang: int | None = None) -> int:
|
|
73
82
|
if workload not in workloads.REGISTRY:
|
|
74
83
|
raise KeyError(f"workload '{workload}' is not allow-listed")
|
|
75
84
|
with self._lock:
|
|
76
85
|
tid = next(self._ids)
|
|
77
86
|
self.tasks[tid] = {"id": tid, "workload": workload, "params": params, "needs": needs or {},
|
|
78
|
-
"priority": int(priority), "state": "queued", "submitted": self.clock()
|
|
87
|
+
"priority": int(priority), "state": "queued", "submitted": self.clock(),
|
|
88
|
+
"tenant": str(tenant), "gang": _gang}
|
|
79
89
|
self.queue.append(tid)
|
|
80
90
|
return tid
|
|
81
91
|
|
|
92
|
+
def submit_gang(self, workload: str, params_list: list[dict], needs: dict | None = None, priority: int = 10,
|
|
93
|
+
tenant: str = "default") -> dict:
|
|
94
|
+
"""All-or-nothing group: the members start only when enough eligible idle nodes exist for ALL of
|
|
95
|
+
them; the first start holds the other nodes for `gang_hold_s`. Admission and reservation, not
|
|
96
|
+
preemption: a member that already runs is never stopped."""
|
|
97
|
+
if not params_list:
|
|
98
|
+
raise ValueError("a gang needs at least one member")
|
|
99
|
+
with self._lock:
|
|
100
|
+
gid = next(self._ids)
|
|
101
|
+
tids = [self.submit(workload, p, {**(needs or {}), "distinct_nodes": True}, priority, tenant, _gang=gid) for p in params_list]
|
|
102
|
+
self.gangs[gid] = {"id": gid, "size": len(tids), "tasks": tids, "reserved": {}, "started": [], "tenant": str(tenant)}
|
|
103
|
+
return {"gang": gid, "tasks": tids}
|
|
104
|
+
|
|
105
|
+
def set_weight(self, tenant: str, weight: float) -> None:
|
|
106
|
+
if not weight > 0:
|
|
107
|
+
raise ValueError("weight must be positive")
|
|
108
|
+
with self._lock:
|
|
109
|
+
self.weights[str(tenant)] = float(weight)
|
|
110
|
+
|
|
111
|
+
def _tenant_load(self, tenant: str, now: float) -> float:
|
|
112
|
+
"""Weighted compute-seconds consumed so far (finished plus running): lowest goes first."""
|
|
113
|
+
running = sum(now - t.get("started", now) for t in self.tasks.values() if t["state"] == "running" and t["tenant"] == tenant)
|
|
114
|
+
return (self.usage.get(tenant, 0.0) + running) / self.weights.get(tenant, 1.0)
|
|
115
|
+
|
|
116
|
+
def tenants(self) -> list[dict]:
|
|
117
|
+
with self._lock:
|
|
118
|
+
now = self.clock()
|
|
119
|
+
names = sorted({t["tenant"] for t in self.tasks.values()} | set(self.weights))
|
|
120
|
+
return [{"tenant": n, "weight": self.weights.get(n, 1.0), "finished_s": self.usage.get(n, 0.0),
|
|
121
|
+
"weighted_load": self._tenant_load(n, now),
|
|
122
|
+
"queued": sum(1 for t in self.tasks.values() if t["tenant"] == n and t["state"] == "queued"),
|
|
123
|
+
"running": sum(1 for t in self.tasks.values() if t["tenant"] == n and t["state"] == "running")} for n in names]
|
|
124
|
+
|
|
82
125
|
def _eligible(self, node: str, needs: dict) -> bool:
|
|
83
126
|
n = self.nodes.get(node)
|
|
84
127
|
if not n or "latest" not in n:
|
|
@@ -94,35 +137,95 @@ class Hub:
|
|
|
94
137
|
return False
|
|
95
138
|
return True
|
|
96
139
|
|
|
140
|
+
def _ready(self, node: str, now: float) -> bool:
|
|
141
|
+
"""Fresh, not saturated, not running a task."""
|
|
142
|
+
n = self.nodes.get(node)
|
|
143
|
+
if not n or "latest" not in n or now - n.get("last_seen", 0) > self.stale_after_s:
|
|
144
|
+
return False
|
|
145
|
+
if (n["latest"].get("cpu_percent") or 0) >= self.busy_cpu_pct:
|
|
146
|
+
return False
|
|
147
|
+
return not any(t["state"] == "running" and t.get("node") == node for t in self.tasks.values())
|
|
148
|
+
|
|
149
|
+
def _gang_nodes(self, g: dict, needs: dict, now: float, exclude: str) -> list[str]:
|
|
150
|
+
"""Other ready, eligible nodes not held by a different gang."""
|
|
151
|
+
held = {nd for og in self.gangs.values() if og["id"] != g["id"] for nd, exp in og["reserved"].items() if exp > now}
|
|
152
|
+
return sorted(nd for nd in self.nodes if nd != exclude and nd not in held and nd not in g["started"]
|
|
153
|
+
and self._ready(nd, now) and self._eligible(nd, needs))
|
|
154
|
+
|
|
97
155
|
def poll(self, node: str) -> dict | None:
|
|
98
|
-
"""Hand the best eligible queued task to an agent that asks for work. Backpressure: a node
|
|
99
|
-
|
|
156
|
+
"""Hand the best eligible queued task to an agent that asks for work. Backpressure: a node that
|
|
157
|
+
reports itself saturated gets nothing. Order: tenant with the lowest weighted usage first (fair
|
|
158
|
+
share), then priority, then submission order. Gang members start only when the whole gang can;
|
|
159
|
+
a task with a cache-affinity key waits `affinity_wait_s` for the node that holds that cache."""
|
|
100
160
|
with self._lock:
|
|
101
161
|
n = self.nodes.get(node)
|
|
102
162
|
if not n or "latest" not in n:
|
|
103
163
|
return None
|
|
104
164
|
if (n["latest"].get("cpu_percent") or 0) >= self.busy_cpu_pct:
|
|
105
165
|
return None
|
|
166
|
+
now = self.clock()
|
|
167
|
+
for g in self.gangs.values():
|
|
168
|
+
g["reserved"] = {nd: exp for nd, exp in g["reserved"].items() if exp > now}
|
|
169
|
+
for g in self.gangs.values(): # a node held for a gang serves only that gang
|
|
170
|
+
if node in g["reserved"]:
|
|
171
|
+
mine = [self.tasks[t] for t in g["tasks"] if self.tasks[t]["state"] == "queued" and self._eligible(node, self.tasks[t]["needs"])]
|
|
172
|
+
if not mine:
|
|
173
|
+
return None
|
|
174
|
+
return self._assign(min(mine, key=lambda t: t["id"]), node, now, g, "held for its gang")
|
|
175
|
+
held_elsewhere = {nd for g in self.gangs.values() for nd, exp in g["reserved"].items() if exp > now}
|
|
176
|
+
if node in held_elsewhere:
|
|
177
|
+
return None
|
|
178
|
+
load = {}
|
|
106
179
|
best = None
|
|
107
180
|
for tid in self.queue:
|
|
108
181
|
t = self.tasks[tid]
|
|
109
|
-
if self._eligible(node, t["needs"])
|
|
110
|
-
|
|
182
|
+
if not self._eligible(node, t["needs"]):
|
|
183
|
+
continue
|
|
184
|
+
key = t["needs"].get("affinity")
|
|
185
|
+
owner = self.affinity.get(key) if key else None
|
|
186
|
+
if owner and owner != node and now - t["submitted"] < self.affinity_wait_s and self._ready(owner, now):
|
|
187
|
+
continue # the node holding its cache is free: wait for it
|
|
188
|
+
g = self.gangs.get(t["gang"]) if t["gang"] else None
|
|
189
|
+
if g is not None:
|
|
190
|
+
missing = sum(1 for x in g["tasks"] if self.tasks[x]["state"] == "queued")
|
|
191
|
+
if len(self._gang_nodes(g, t["needs"], now, node)) + 1 < missing:
|
|
192
|
+
continue # not enough idle nodes for the whole gang yet
|
|
193
|
+
tn = t["tenant"]
|
|
194
|
+
if tn not in load:
|
|
195
|
+
load[tn] = self._tenant_load(tn, now)
|
|
196
|
+
rank = (load[tn], 0 if owner == node else 1, t["priority"], tid)
|
|
197
|
+
if best is None or rank < best[0]:
|
|
198
|
+
best = (rank, t, g)
|
|
111
199
|
if best is None:
|
|
112
200
|
return None
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
201
|
+
_, t, g = best
|
|
202
|
+
if g is not None and not g["started"]:
|
|
203
|
+
for nd in self._gang_nodes(g, t["needs"], now, node)[: g["size"] - 1]:
|
|
204
|
+
g["reserved"][nd] = now + self.gang_hold_s
|
|
205
|
+
return self._assign(t, node, now, g, "agent asked for work and is eligible")
|
|
206
|
+
|
|
207
|
+
def _assign(self, t: dict, node: str, now: float, g: dict | None, why: str) -> dict:
|
|
208
|
+
self.queue.remove(t["id"])
|
|
209
|
+
t.update(state="running", node=node, started=now)
|
|
210
|
+
if g is not None:
|
|
211
|
+
g["started"].append(node)
|
|
212
|
+
g["reserved"].pop(node, None)
|
|
213
|
+
if self.ledger:
|
|
214
|
+
self.ledger.decide("fleet", f"task {t['id']} -> {node}", why, workload=t["workload"], tenant=t["tenant"],
|
|
215
|
+
gang=t["gang"], node_cpu=(self.nodes[node]["latest"] or {}).get("cpu_percent"))
|
|
216
|
+
return {"id": t["id"], "workload": t["workload"], "params": t["params"]}
|
|
119
217
|
|
|
120
218
|
def result(self, node: str, task_id: int, ok: bool, value=None, error: str | None = None, wall_s: float | None = None):
|
|
121
219
|
with self._lock:
|
|
122
220
|
t = self.tasks.get(task_id)
|
|
123
221
|
if t is None or t.get("node") != node:
|
|
124
222
|
raise PermissionError("task is not assigned to this node")
|
|
223
|
+
if t["state"] == "queued": # requeued after a hub restart, but its agent finished it anyway
|
|
224
|
+
self.queue.remove(task_id)
|
|
125
225
|
t.update(state="done" if ok else "failed", finished=self.clock(), result=value, error=error, wall_s=wall_s)
|
|
226
|
+
self.usage[t["tenant"]] = self.usage.get(t["tenant"], 0.0) + (wall_s if wall_s is not None else self.clock() - t.get("started", self.clock()))
|
|
227
|
+
if ok and t["needs"].get("affinity"):
|
|
228
|
+
self.affinity[t["needs"]["affinity"]] = node
|
|
126
229
|
|
|
127
230
|
def task(self, task_id: int) -> dict:
|
|
128
231
|
with self._lock:
|
|
@@ -131,6 +234,66 @@ class Hub:
|
|
|
131
234
|
raise KeyError(f"unknown task {task_id}")
|
|
132
235
|
return {k: v for k, v in t.items()}
|
|
133
236
|
|
|
237
|
+
|
|
238
|
+
# ------------------------------------------------------------------ persistence
|
|
239
|
+
def snapshot(self) -> dict:
|
|
240
|
+
"""Durable state: tasks, queue order, tenant usage and weights, gangs, cache owners. Node
|
|
241
|
+
measurements are not saved: agents rebuild them within one report interval."""
|
|
242
|
+
with self._lock:
|
|
243
|
+
return {"version": 1, "next_id": next(self._ids), "tasks": list(self.tasks.values()), "queue": list(self.queue),
|
|
244
|
+
"usage": self.usage, "weights": self.weights, "affinity": self.affinity,
|
|
245
|
+
"gangs": [{**g, "reserved": {}} for g in self.gangs.values()]}
|
|
246
|
+
|
|
247
|
+
def restore(self, snap: dict) -> dict:
|
|
248
|
+
"""Load a snapshot. A task that was running is put back in the queue (at-least-once: the
|
|
249
|
+
allow-listed workloads are pure functions); if its agent still finishes it, that result is accepted."""
|
|
250
|
+
with self._lock:
|
|
251
|
+
self.tasks = {int(t["id"]): t for t in snap["tasks"]}
|
|
252
|
+
self.queue = deque(int(i) for i in snap["queue"])
|
|
253
|
+
requeued = 0
|
|
254
|
+
for t in self.tasks.values():
|
|
255
|
+
if t["state"] == "running":
|
|
256
|
+
t["state"] = "queued"
|
|
257
|
+
t["requeued_after_restart"] = True
|
|
258
|
+
self.queue.append(t["id"])
|
|
259
|
+
requeued += 1
|
|
260
|
+
self.usage, self.weights, self.affinity = dict(snap["usage"]), dict(snap["weights"]), dict(snap["affinity"])
|
|
261
|
+
self.gangs = {int(g["id"]): {**g, "started": [], "reserved": {}} for g in snap["gangs"]}
|
|
262
|
+
self._ids = itertools.count(int(snap["next_id"]))
|
|
263
|
+
return {"tasks": len(self.tasks), "queued": len(self.queue), "requeued_running": requeued}
|
|
264
|
+
|
|
265
|
+
def save(self, path: str | Path) -> None:
|
|
266
|
+
tmp = f"{path}.tmp"
|
|
267
|
+
with open(tmp, "w") as f:
|
|
268
|
+
json.dump(self.snapshot(), f)
|
|
269
|
+
f.flush()
|
|
270
|
+
os.fsync(f.fileno())
|
|
271
|
+
os.replace(tmp, path) # atomic: a crash leaves the old or the new file, never half
|
|
272
|
+
|
|
273
|
+
def load(self, path: str | Path) -> dict | None:
|
|
274
|
+
try:
|
|
275
|
+
snap = json.loads(Path(path).read_text())
|
|
276
|
+
except FileNotFoundError:
|
|
277
|
+
return None
|
|
278
|
+
return self.restore(snap)
|
|
279
|
+
|
|
280
|
+
def autosave(self, path: str | Path, every_s: float = 5.0) -> threading.Event:
|
|
281
|
+
"""Save every `every_s` seconds in a daemon thread; set the returned event to stop (one last save is made)."""
|
|
282
|
+
stop = threading.Event()
|
|
283
|
+
|
|
284
|
+
def loop():
|
|
285
|
+
while not stop.wait(every_s):
|
|
286
|
+
try:
|
|
287
|
+
self.save(path)
|
|
288
|
+
except OSError:
|
|
289
|
+
pass
|
|
290
|
+
try:
|
|
291
|
+
self.save(path)
|
|
292
|
+
except OSError:
|
|
293
|
+
pass
|
|
294
|
+
threading.Thread(target=loop, daemon=True).start()
|
|
295
|
+
return stop
|
|
296
|
+
|
|
134
297
|
# ------------------------------------------------------------------ views
|
|
135
298
|
def _window(self, node: str, window_s: float, now: float) -> list:
|
|
136
299
|
return [m for ts, m in self.series.get(node, ()) if now - window_s <= ts <= now]
|
|
@@ -218,6 +381,13 @@ def _avg(xs):
|
|
|
218
381
|
|
|
219
382
|
|
|
220
383
|
# ---------------------------------------------------------------------- service
|
|
384
|
+
def _tenant(h: dict) -> str:
|
|
385
|
+
"""With scoped credentials the tenant is the credential name (it cannot be spoofed); otherwise the declared one."""
|
|
386
|
+
p = auth.current()
|
|
387
|
+
t = p.name if p is not None else h.get("tenant", "default")
|
|
388
|
+
return str(t)[:128]
|
|
389
|
+
|
|
390
|
+
|
|
221
391
|
def make_handler(hub: Hub):
|
|
222
392
|
def handle(h: dict, blob: bytes):
|
|
223
393
|
op = h.get("op")
|
|
@@ -236,7 +406,13 @@ def make_handler(hub: Hub):
|
|
|
236
406
|
return {}, b""
|
|
237
407
|
if op == "submit":
|
|
238
408
|
require("fleet:submit")
|
|
239
|
-
return {"task_id": hub.submit(h["workload"], h.get("params", {}), h.get("needs"), h.get("priority", 10))}, b""
|
|
409
|
+
return {"task_id": hub.submit(h["workload"], h.get("params", {}), h.get("needs"), h.get("priority", 10), _tenant(h))}, b""
|
|
410
|
+
if op == "submit_gang":
|
|
411
|
+
require("fleet:submit")
|
|
412
|
+
return hub.submit_gang(h["workload"], h["params_list"], h.get("needs"), h.get("priority", 10), _tenant(h)), b""
|
|
413
|
+
if op == "tenants":
|
|
414
|
+
require("fleet:read")
|
|
415
|
+
return {"tenants": hub.tenants()}, b""
|
|
240
416
|
if op == "task":
|
|
241
417
|
require("fleet:submit")
|
|
242
418
|
return {"task": hub.task(int(h["task_id"]))}, b""
|
|
@@ -251,9 +427,9 @@ def make_handler(hub: Hub):
|
|
|
251
427
|
|
|
252
428
|
|
|
253
429
|
def serve_hub(token: bytes | None = None, host: str = "127.0.0.1", port: int = 0, allow_remote: bool = False,
|
|
254
|
-
authorizer=None, hub: Hub | None = None, ledger: Ledger | None = None) -> tuple[RpcServer, Hub]:
|
|
430
|
+
authorizer=None, hub: Hub | None = None, ledger: Ledger | None = None, **server_kw) -> tuple[RpcServer, Hub]:
|
|
255
431
|
hub = hub or Hub(ledger=ledger)
|
|
256
|
-
return RpcServer(make_handler(hub), token, host=host, port=port, allow_remote=allow_remote, authorizer=authorizer), hub
|
|
432
|
+
return RpcServer(make_handler(hub), token, host=host, port=port, allow_remote=allow_remote, authorizer=authorizer, **server_kw), hub
|
|
257
433
|
|
|
258
434
|
|
|
259
435
|
def main():
|
|
@@ -265,12 +441,16 @@ def main():
|
|
|
265
441
|
ap.add_argument("--port", type=int, default=0)
|
|
266
442
|
ap.add_argument("--allow-remote", action="store_true")
|
|
267
443
|
ap.add_argument("--decision-log", default=str(Path.home() / ".spatial" / "fleet-decisions.jsonl"))
|
|
444
|
+
ap.add_argument("--state-file", help="save tasks, queue, tenant usage here every 5 s and reload it at start")
|
|
268
445
|
a = ap.parse_args()
|
|
269
446
|
if bool(a.token_file) == bool(a.master_key_file):
|
|
270
447
|
raise SystemExit("give exactly one of --token-file or --master-key-file")
|
|
271
|
-
srv,
|
|
272
|
-
|
|
273
|
-
|
|
448
|
+
srv, hub = serve_hub(Path(a.token_file).read_bytes() if a.token_file else None, a.host, a.port, a.allow_remote,
|
|
449
|
+
authorizer_from_file(a.master_key_file, a.audit_log) if a.master_key_file else None,
|
|
450
|
+
ledger=Ledger(a.decision_log))
|
|
451
|
+
if a.state_file:
|
|
452
|
+
print("restored", hub.load(a.state_file), flush=True)
|
|
453
|
+
hub.autosave(a.state_file)
|
|
274
454
|
print(f"PORT {srv.port}", flush=True)
|
|
275
455
|
srv.serve_forever()
|
|
276
456
|
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
"""Virtual interconnect: collective communication between ranks (devices, processes, machines)
|
|
2
|
+
over the encrypted SWP/2 transport, with an alpha-beta cost model that picks the algorithm.
|
|
3
|
+
|
|
4
|
+
This is NOT NVLink: it is a software layer over commodity links (loopback, Ethernet), thousands of
|
|
5
|
+
times slower in bandwidth. Its value is abstraction (the same collective over any set of devices,
|
|
6
|
+
across vendors and machines) and the measured choice of algorithm. See docs/INTERCONNECT.md.
|
|
7
|
+
"""
|
|
8
|
+
from .comm import Comm, launch # noqa: F401
|
|
9
|
+
from .collectives import allreduce, broadcast, ALGOS # noqa: F401
|
|
10
|
+
from .model import choose, fit_link, predict # noqa: F401
|