spatial-computing 0.8.0__tar.gz → 0.10.0__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.8.0/spatial_computing.egg-info → spatial_computing-0.10.0}/PKG-INFO +5 -3
- {spatial_computing-0.8.0 → spatial_computing-0.10.0}/README.md +4 -2
- {spatial_computing-0.8.0 → spatial_computing-0.10.0}/pyproject.toml +1 -1
- {spatial_computing-0.8.0 → spatial_computing-0.10.0}/spatial/__init__.py +1 -1
- spatial_computing-0.10.0/spatial/cli.py +290 -0
- {spatial_computing-0.8.0 → spatial_computing-0.10.0}/spatial/compute/workloads.py +58 -0
- {spatial_computing-0.8.0 → spatial_computing-0.10.0}/spatial/core/ledger.py +9 -4
- {spatial_computing-0.8.0 → spatial_computing-0.10.0}/spatial/core/registry.py +6 -0
- spatial_computing-0.10.0/spatial/fleet/__init__.py +18 -0
- spatial_computing-0.10.0/spatial/fleet/agent.py +137 -0
- spatial_computing-0.10.0/spatial/fleet/hub.py +279 -0
- spatial_computing-0.10.0/spatial/unified/__init__.py +11 -0
- spatial_computing-0.10.0/spatial/unified/model.py +160 -0
- spatial_computing-0.10.0/spatial/unified/planner.py +99 -0
- spatial_computing-0.10.0/spatial/unified/providers.py +397 -0
- {spatial_computing-0.8.0 → spatial_computing-0.10.0/spatial_computing.egg-info}/PKG-INFO +5 -3
- {spatial_computing-0.8.0 → spatial_computing-0.10.0}/spatial_computing.egg-info/SOURCES.txt +9 -0
- spatial_computing-0.10.0/tests/test_fleet.py +163 -0
- spatial_computing-0.10.0/tests/test_unified.py +162 -0
- {spatial_computing-0.8.0 → spatial_computing-0.10.0}/tests/test_v02.py +14 -0
- spatial_computing-0.8.0/spatial/cli.py +0 -165
- {spatial_computing-0.8.0 → spatial_computing-0.10.0}/LICENSE +0 -0
- {spatial_computing-0.8.0 → spatial_computing-0.10.0}/setup.cfg +0 -0
- {spatial_computing-0.8.0 → spatial_computing-0.10.0}/spatial/ai/__init__.py +0 -0
- {spatial_computing-0.8.0 → spatial_computing-0.10.0}/spatial/ai/kvcache.py +0 -0
- {spatial_computing-0.8.0 → spatial_computing-0.10.0}/spatial/compute/__init__.py +0 -0
- {spatial_computing-0.8.0 → spatial_computing-0.10.0}/spatial/compute/cost.py +0 -0
- {spatial_computing-0.8.0 → spatial_computing-0.10.0}/spatial/compute/detect.py +0 -0
- {spatial_computing-0.8.0 → spatial_computing-0.10.0}/spatial/compute/monitor.py +0 -0
- {spatial_computing-0.8.0 → spatial_computing-0.10.0}/spatial/compute/scheduler.py +0 -0
- {spatial_computing-0.8.0 → spatial_computing-0.10.0}/spatial/compute/taskqueue.py +0 -0
- {spatial_computing-0.8.0 → spatial_computing-0.10.0}/spatial/compute/worker.py +0 -0
- {spatial_computing-0.8.0 → spatial_computing-0.10.0}/spatial/core/__init__.py +0 -0
- {spatial_computing-0.8.0 → spatial_computing-0.10.0}/spatial/core/auth.py +0 -0
- {spatial_computing-0.8.0 → spatial_computing-0.10.0}/spatial/core/energy.py +0 -0
- {spatial_computing-0.8.0 → spatial_computing-0.10.0}/spatial/core/model.py +0 -0
- {spatial_computing-0.8.0 → spatial_computing-0.10.0}/spatial/core/protocol.py +0 -0
- {spatial_computing-0.8.0 → spatial_computing-0.10.0}/spatial/holographic/__init__.py +0 -0
- {spatial_computing-0.8.0 → spatial_computing-0.10.0}/spatial/holographic/cgh.py +0 -0
- {spatial_computing-0.8.0 → spatial_computing-0.10.0}/spatial/holographic/model.py +0 -0
- {spatial_computing-0.8.0 → spatial_computing-0.10.0}/spatial/intelligence/__init__.py +0 -0
- {spatial_computing-0.8.0 → spatial_computing-0.10.0}/spatial/intelligence/predictor.py +0 -0
- {spatial_computing-0.8.0 → spatial_computing-0.10.0}/spatial/memory/__init__.py +0 -0
- {spatial_computing-0.8.0 → spatial_computing-0.10.0}/spatial/memory/fararray.py +0 -0
- {spatial_computing-0.8.0 → spatial_computing-0.10.0}/spatial/memory/pageserver.py +0 -0
- {spatial_computing-0.8.0 → spatial_computing-0.10.0}/spatial/memory/secure.py +0 -0
- {spatial_computing-0.8.0 → spatial_computing-0.10.0}/spatial/memory/shared.py +0 -0
- {spatial_computing-0.8.0 → spatial_computing-0.10.0}/spatial/memory/tiered.py +0 -0
- {spatial_computing-0.8.0 → spatial_computing-0.10.0}/spatial/q/__init__.py +0 -0
- {spatial_computing-0.8.0 → spatial_computing-0.10.0}/spatial/q/__main__.py +0 -0
- {spatial_computing-0.8.0 → spatial_computing-0.10.0}/spatial/q/backends/__init__.py +0 -0
- {spatial_computing-0.8.0 → spatial_computing-0.10.0}/spatial/q/codegen.py +0 -0
- {spatial_computing-0.8.0 → spatial_computing-0.10.0}/spatial/q/compiler.py +0 -0
- {spatial_computing-0.8.0 → spatial_computing-0.10.0}/spatial/q/ir.py +0 -0
- {spatial_computing-0.8.0 → spatial_computing-0.10.0}/spatial/q/lexer.py +0 -0
- {spatial_computing-0.8.0 → spatial_computing-0.10.0}/spatial/q/parser.py +0 -0
- {spatial_computing-0.8.0 → spatial_computing-0.10.0}/spatial/q/qir.py +0 -0
- {spatial_computing-0.8.0 → spatial_computing-0.10.0}/spatial/q/runtime.py +0 -0
- {spatial_computing-0.8.0 → spatial_computing-0.10.0}/spatial/q/sim.py +0 -0
- {spatial_computing-0.8.0 → spatial_computing-0.10.0}/spatial/runtime/__init__.py +0 -0
- {spatial_computing-0.8.0 → spatial_computing-0.10.0}/spatial/runtime/envs.py +0 -0
- {spatial_computing-0.8.0 → spatial_computing-0.10.0}/spatial/runtime/inspect.py +0 -0
- {spatial_computing-0.8.0 → spatial_computing-0.10.0}/spatial/runtime/microvm.py +0 -0
- {spatial_computing-0.8.0 → spatial_computing-0.10.0}/spatial/runtime/planner.py +0 -0
- {spatial_computing-0.8.0 → spatial_computing-0.10.0}/spatial/runtime/runner.py +0 -0
- {spatial_computing-0.8.0 → spatial_computing-0.10.0}/spatial/runtime/toolchain.py +0 -0
- {spatial_computing-0.8.0 → spatial_computing-0.10.0}/spatial/scientific/__init__.py +0 -0
- {spatial_computing-0.8.0 → spatial_computing-0.10.0}/spatial/scientific/jobs.py +0 -0
- {spatial_computing-0.8.0 → spatial_computing-0.10.0}/spatial/simulation/__init__.py +0 -0
- {spatial_computing-0.8.0 → spatial_computing-0.10.0}/spatial/simulation/heat.py +0 -0
- {spatial_computing-0.8.0 → spatial_computing-0.10.0}/spatial/simulation/nbody.py +0 -0
- {spatial_computing-0.8.0 → spatial_computing-0.10.0}/spatial_computing.egg-info/dependency_links.txt +0 -0
- {spatial_computing-0.8.0 → spatial_computing-0.10.0}/spatial_computing.egg-info/entry_points.txt +0 -0
- {spatial_computing-0.8.0 → spatial_computing-0.10.0}/spatial_computing.egg-info/requires.txt +0 -0
- {spatial_computing-0.8.0 → spatial_computing-0.10.0}/spatial_computing.egg-info/top_level.txt +0 -0
- {spatial_computing-0.8.0 → spatial_computing-0.10.0}/tests/test_auth.py +0 -0
- {spatial_computing-0.8.0 → spatial_computing-0.10.0}/tests/test_compute.py +0 -0
- {spatial_computing-0.8.0 → spatial_computing-0.10.0}/tests/test_core.py +0 -0
- {spatial_computing-0.8.0 → spatial_computing-0.10.0}/tests/test_domains.py +0 -0
- {spatial_computing-0.8.0 → spatial_computing-0.10.0}/tests/test_engines.py +0 -0
- {spatial_computing-0.8.0 → spatial_computing-0.10.0}/tests/test_memory.py +0 -0
- {spatial_computing-0.8.0 → spatial_computing-0.10.0}/tests/test_optimizer.py +0 -0
- {spatial_computing-0.8.0 → spatial_computing-0.10.0}/tests/test_q.py +0 -0
- {spatial_computing-0.8.0 → spatial_computing-0.10.0}/tests/test_runtime.py +0 -0
- {spatial_computing-0.8.0 → spatial_computing-0.10.0}/tests/test_v03.py +0 -0
- {spatial_computing-0.8.0 → spatial_computing-0.10.0}/tests/test_v05.py +0 -0
- {spatial_computing-0.8.0 → spatial_computing-0.10.0}/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.10.0
|
|
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
|
|
@@ -35,9 +35,9 @@ Dynamic: license-file
|
|
|
35
35
|
|
|
36
36
|
**Measure. Decide. Prove.**
|
|
37
37
|
|
|
38
|
-
Spatial Computing
|
|
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.10.0, 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
|
|
|
@@ -93,6 +93,8 @@ st.put(0, b"..." * 1000); st.get(0); print(st.stats())
|
|
|
93
93
|
|
|
94
94
|
| Engine | Level | Evidence |
|
|
95
95
|
|---|---|---|
|
|
96
|
+
| Planner (the one objective: price every option across all engines, choose, run, check) | operational prototype | `tests/test_unified.py`, `benchmarks/bench_unified.py` |
|
|
97
|
+
| Fleet (agent on every machine + hub: measure, place, recommend, audit) | operational prototype | `tests/test_fleet.py`, `benchmarks/bench_fleet.py` |
|
|
96
98
|
| Compute Engine (detect, monitor, compare strategies, offload, cost) | operational prototype | `tests/test_compute.py`, `benchmarks/bench_cpu.py` |
|
|
97
99
|
| Tiered memory (hot / compressed / far) | operational prototype | `tests/test_memory.py`, `benchmarks/bench_memory.py` |
|
|
98
100
|
| Runtime Engine (inspect binaries, route, micro-VM, WASI) | operational prototype | `tests/test_runtime.py`, `benchmarks/bench_runtime.py` |
|
|
@@ -2,9 +2,9 @@
|
|
|
2
2
|
|
|
3
3
|
**Measure. Decide. Prove.**
|
|
4
4
|
|
|
5
|
-
Spatial Computing
|
|
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.10.0, 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
|
|
|
@@ -60,6 +60,8 @@ st.put(0, b"..." * 1000); st.get(0); print(st.stats())
|
|
|
60
60
|
|
|
61
61
|
| Engine | Level | Evidence |
|
|
62
62
|
|---|---|---|
|
|
63
|
+
| Planner (the one objective: price every option across all engines, choose, run, check) | operational prototype | `tests/test_unified.py`, `benchmarks/bench_unified.py` |
|
|
64
|
+
| Fleet (agent on every machine + hub: measure, place, recommend, audit) | operational prototype | `tests/test_fleet.py`, `benchmarks/bench_fleet.py` |
|
|
63
65
|
| Compute Engine (detect, monitor, compare strategies, offload, cost) | operational prototype | `tests/test_compute.py`, `benchmarks/bench_cpu.py` |
|
|
64
66
|
| Tiered memory (hot / compressed / far) | operational prototype | `tests/test_memory.py`, `benchmarks/bench_memory.py` |
|
|
65
67
|
| Runtime Engine (inspect binaries, route, micro-VM, WASI) | operational prototype | `tests/test_runtime.py`, `benchmarks/bench_runtime.py` |
|
|
@@ -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.10.0"
|
|
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"
|
|
@@ -0,0 +1,290 @@
|
|
|
1
|
+
"""`spatial` command line: one entry point for the three operational engines."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import argparse
|
|
5
|
+
import json
|
|
6
|
+
import subprocess
|
|
7
|
+
import sys
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
ROOT = Path(__file__).resolve().parents[1]
|
|
11
|
+
BENCHES = {"cpu": "bench_cpu", "memory": "bench_memory", "gpu": "bench_gpu",
|
|
12
|
+
"runtime": "bench_runtime", "q": "bench_q"}
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def cmd_audit(a):
|
|
16
|
+
from .compute import detect_node, limitations, snapshot
|
|
17
|
+
from .compute.monitor import underused
|
|
18
|
+
node, snap = detect_node(), snapshot()
|
|
19
|
+
if a.json:
|
|
20
|
+
print(json.dumps({"node": node.to_dict(), "snapshot": snap, "limitations": limitations(node)},
|
|
21
|
+
indent=1, default=str))
|
|
22
|
+
return 0
|
|
23
|
+
print(f"{node.attrs.get('model')} | {node.attrs.get('cpu_brand')} | {node.os} | {node.arch}")
|
|
24
|
+
for r in node.resources:
|
|
25
|
+
cap = f"{r.capacity / 2**30:.1f} GiB" if r.unit == "bytes" else f"{r.capacity:g} {r.unit}"
|
|
26
|
+
if "utilization_percent" in r.attrs:
|
|
27
|
+
cap += f" ({r.attrs['utilization_percent']:.0f}% busy)"
|
|
28
|
+
print(f" {r.kind.value:<11} {r.name:<42} {cap}")
|
|
29
|
+
print(f"memory pressure: {snap.get('memory_pressure')} | compressor ratio: {snap.get('compressor_ratio')} "
|
|
30
|
+
f"| swap used: {snap['swap_used'] / 2**30:.2f} GiB")
|
|
31
|
+
for u in underused(snap):
|
|
32
|
+
print(" idle:", u)
|
|
33
|
+
print("limitations:")
|
|
34
|
+
for x in limitations(node):
|
|
35
|
+
print(" -", x)
|
|
36
|
+
return 0
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def cmd_status(a):
|
|
40
|
+
from .core.registry import ENGINES
|
|
41
|
+
for e in ENGINES:
|
|
42
|
+
print(f"{e.name:<42} {e.status.value:<24} not done: {e.not_done}")
|
|
43
|
+
return 0
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def cmd_plan(a):
|
|
47
|
+
from .runtime import inspect, plan
|
|
48
|
+
art = inspect(a.file)
|
|
49
|
+
print(f"{a.file}: {art.format} / {art.os} / {','.join(art.arch)} {art.detail}")
|
|
50
|
+
for r in plan(art):
|
|
51
|
+
print(f" [{'x' if r.feasible else ' '}] {r.name:<16} {r.reason}")
|
|
52
|
+
return 0
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def cmd_run(a):
|
|
56
|
+
from .runtime import execute
|
|
57
|
+
e = execute(a.file, a.args, route=a.route, timeout_s=a.timeout)
|
|
58
|
+
if e.stdout:
|
|
59
|
+
print(e.stdout)
|
|
60
|
+
print(f"[spatial] route={e.route} ok={e.ok} wall={e.wall_s:.2f}s "
|
|
61
|
+
+ (f"reason: {e.extra.get('not_runnable')}" if not e.ok and e.extra.get("not_runnable") else ""),
|
|
62
|
+
file=sys.stderr)
|
|
63
|
+
return 0 if e.ok else 1
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def cmd_q(a):
|
|
67
|
+
from .q import runtime
|
|
68
|
+
sys.argv = ["spatialq", *a.rest]
|
|
69
|
+
runtime.main()
|
|
70
|
+
return 0
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def cmd_bench(a):
|
|
74
|
+
names = list(BENCHES) if a.name == "all" else [a.name]
|
|
75
|
+
bdir = ROOT / "benchmarks"
|
|
76
|
+
if not bdir.exists():
|
|
77
|
+
print("benchmarks/ not found: run from a source checkout", file=sys.stderr)
|
|
78
|
+
return 2
|
|
79
|
+
rc = 0
|
|
80
|
+
for n in names:
|
|
81
|
+
rc |= subprocess.run([sys.executable, f"{BENCHES[n]}.py"], cwd=bdir).returncode
|
|
82
|
+
rc |= subprocess.run([sys.executable, "report.py"], cwd=bdir).returncode
|
|
83
|
+
return rc
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _read_token(path: str) -> bytes:
|
|
87
|
+
raw = Path(path).read_bytes()
|
|
88
|
+
return raw.strip() if raw.startswith(b"spc1.") else raw # scoped tokens are text, shared secrets are raw bytes
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _hub_client(a):
|
|
92
|
+
from .core.protocol import RpcClient
|
|
93
|
+
host, _, port = a.hub.rpartition(":")
|
|
94
|
+
return RpcClient(host or "127.0.0.1", int(port), _read_token(a.token_file), timeout=30)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def cmd_agent(a):
|
|
98
|
+
from .fleet import Agent
|
|
99
|
+
host, _, port = a.hub.rpartition(":")
|
|
100
|
+
ag = Agent(host or "127.0.0.1", int(port), _read_token(a.token_file), name=a.name, interval_s=a.interval,
|
|
101
|
+
usd_per_hour=a.usd_per_hour, labels=[x for x in a.labels.split(",") if x], run_tasks=not a.no_tasks)
|
|
102
|
+
print(f"agent '{ag.name}' reporting to {a.hub} every {a.interval:g} s" + ("" if a.no_tasks else "; accepts allow-listed tasks"))
|
|
103
|
+
ag.run_forever()
|
|
104
|
+
return 0
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def cmd_fleet(a):
|
|
108
|
+
cli = _hub_client(a)
|
|
109
|
+
if a.action == "status":
|
|
110
|
+
rh, _ = cli.call({"op": "nodes", "window_s": a.window})
|
|
111
|
+
print(f"{'node':<22}{'up':<4}{'cores':>6}{'cpu%':>7}{'ram free%':>10}{'gpus':>5}{'gpu%':>6}{'$/h':>7} samples")
|
|
112
|
+
f = lambda v, n=0: "-" if v is None else f"{v:.{n}f}"
|
|
113
|
+
for r in rh["nodes"]:
|
|
114
|
+
print(f"{r['node']:<22}{'yes' if r['alive'] else 'NO':<4}{f(r['cores']):>6}{f(r['cpu_avg']):>7}{f(r['ram_avail_pct']):>10}"
|
|
115
|
+
f"{r['gpu_count']:>5}{f(r['gpu_util_avg']):>6}{f(r['usd_per_hour'], 2):>7} {r['samples']}")
|
|
116
|
+
u = rh["utilization"]
|
|
117
|
+
print(f"fleet: {u['nodes']} node(s), {u['cores']} cores, CPU utilization "
|
|
118
|
+
f"{'-' if u['cpu_utilization_pct'] is None else format(u['cpu_utilization_pct'], '.1f') + '%'} (last {a.window:g} s)")
|
|
119
|
+
elif a.action == "advise":
|
|
120
|
+
rh, _ = cli.call({"op": "advise", "window_s": a.window})
|
|
121
|
+
if not rh["recommendations"]:
|
|
122
|
+
print("no recommendation: nothing in the measurements justifies a change")
|
|
123
|
+
for r in rh["recommendations"]:
|
|
124
|
+
extra = f" [estimated saving {r['est_saving_usd_per_hour']:.2f} $/h, {r['est_saving_usd_per_month']:.0f} $/month]" if "est_saving_usd_per_hour" in r else ""
|
|
125
|
+
print(f"[{r['severity']}] {r['kind']}: {r['text']}{extra}")
|
|
126
|
+
print(f" evidence: {r['evidence']}")
|
|
127
|
+
elif a.action == "submit":
|
|
128
|
+
import json as _json
|
|
129
|
+
rh, _ = cli.call({"op": "submit", "workload": a.workload, "params": _json.loads(a.params),
|
|
130
|
+
"needs": _json.loads(a.needs)})
|
|
131
|
+
print(rh["task_id"])
|
|
132
|
+
else:
|
|
133
|
+
rh, _ = cli.call({"op": "task", "task_id": a.task_id})
|
|
134
|
+
t = rh["task"]
|
|
135
|
+
print({k: t.get(k) for k in ("id", "state", "node", "result", "error", "wall_s")})
|
|
136
|
+
cli.close()
|
|
137
|
+
return 0
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def cmd_optimize(a):
|
|
141
|
+
import json as _json
|
|
142
|
+
from .unified import Job, Objective, Planner, PlanError, Prices
|
|
143
|
+
prices = Prices(local_usd_per_hour=a.local_usd_per_hour, qpu_usd_per_shot=a.qpu_usd_per_shot, qpu_usd_per_task=a.qpu_usd_per_task,
|
|
144
|
+
ram_usd_gb_hour=a.ram_usd_gb_hour, storage_usd_gb_hour=a.storage_usd_gb_hour)
|
|
145
|
+
obj = Objective(minimize=a.objective, deadline_s=a.deadline, max_ram_bytes=int(a.max_ram_gib * 2**30) if a.max_ram_gib else None,
|
|
146
|
+
require_isolation=a.isolated, allow_qpu=a.allow_qpu, require_hardware=a.require_hardware)
|
|
147
|
+
hub = _hub_client(a) if a.hub else None
|
|
148
|
+
if a.job == "compute":
|
|
149
|
+
job = Job.compute(a.family, **_json.loads(a.params))
|
|
150
|
+
elif a.job == "binary":
|
|
151
|
+
job = Job.binary(a.file, a.args, a.est_native_s)
|
|
152
|
+
elif a.job == "quantum":
|
|
153
|
+
job = Job.quantum(Path(a.file).read_text(), a.kernel, _json.loads(a.kargs), a.shots)
|
|
154
|
+
elif a.job == "dataset":
|
|
155
|
+
job = Job.dataset(int(a.gib * 2**30), a.accesses, a.locality, a.hot_fraction)
|
|
156
|
+
else:
|
|
157
|
+
job = Job.kv_cache(a.prefix_tokens, a.reuse, a.horizon_h)
|
|
158
|
+
planner = Planner(prices=prices, hub=hub)
|
|
159
|
+
try:
|
|
160
|
+
plan = planner.plan(job, obj)
|
|
161
|
+
except PlanError as e:
|
|
162
|
+
print(e)
|
|
163
|
+
return 1
|
|
164
|
+
print(plan.explain())
|
|
165
|
+
if a.execute:
|
|
166
|
+
ex = planner.execute(plan)
|
|
167
|
+
err = "n/a" if ex.time_error_pct is None else f"{ex.time_error_pct:+.0f}%"
|
|
168
|
+
print(f"\nexecuted {ex.option}: {ex.wall_s:.4g} s (estimated {ex.est_time_s if ex.est_time_s is None else format(ex.est_time_s, '.4g')} s, error {err}); "
|
|
169
|
+
f"cost {ex.actual_cost_usd:.3g} $ (estimated {ex.est_cost_usd if ex.est_cost_usd is None else format(ex.est_cost_usd, '.3g')} $)")
|
|
170
|
+
print("result:", str(ex.result)[:300])
|
|
171
|
+
return 0
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def cmd_token(a):
|
|
175
|
+
from .core import auth
|
|
176
|
+
if a.action == "init":
|
|
177
|
+
auth.init_master_key(a.master_key_file)
|
|
178
|
+
print(f"master key written to {a.master_key_file} (mode 600). Keep it private; it can issue any credential.")
|
|
179
|
+
return 0
|
|
180
|
+
az = auth.authorizer_from_file(a.master_key_file)
|
|
181
|
+
print(az.issue(a.name, [s for s in a.scopes.split(",") if s], ttl_s=a.ttl, max_ops=a.max_ops, max_bytes=a.max_bytes))
|
|
182
|
+
return 0
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def cmd_worker(a):
|
|
186
|
+
mod = {"compute": "spatial.compute.worker", "memory": "spatial.memory.pageserver",
|
|
187
|
+
"runtime": "spatial.runtime.runner", "hub": "spatial.fleet.hub"}[a.kind]
|
|
188
|
+
cmd = [sys.executable, "-m", mod, "--host", a.host, "--port", str(a.port)]
|
|
189
|
+
if a.token_file:
|
|
190
|
+
cmd += ["--token-file", a.token_file]
|
|
191
|
+
if a.master_key_file:
|
|
192
|
+
cmd += ["--master-key-file", a.master_key_file]
|
|
193
|
+
if a.audit_log:
|
|
194
|
+
cmd += ["--audit-log", a.audit_log]
|
|
195
|
+
if a.allow_remote:
|
|
196
|
+
cmd.append("--allow-remote")
|
|
197
|
+
return subprocess.run(cmd).returncode
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def main(argv=None):
|
|
201
|
+
ap = argparse.ArgumentParser(prog="spatial", description="SPATIAL COMPUTING — measure, decide, prove")
|
|
202
|
+
sub = ap.add_subparsers(dest="cmd", required=True)
|
|
203
|
+
p = sub.add_parser("audit", help="detect hardware, usage and limits of this machine")
|
|
204
|
+
p.add_argument("--json", action="store_true")
|
|
205
|
+
p.set_defaults(fn=cmd_audit)
|
|
206
|
+
sub.add_parser("status", help="honest status of every engine").set_defaults(fn=cmd_status)
|
|
207
|
+
p = sub.add_parser("plan", help="inspect a binary and list execution routes")
|
|
208
|
+
p.add_argument("file")
|
|
209
|
+
p.set_defaults(fn=cmd_plan)
|
|
210
|
+
p = sub.add_parser("run", help="run a binary through the best feasible route")
|
|
211
|
+
p.add_argument("file")
|
|
212
|
+
p.add_argument("args", nargs="*")
|
|
213
|
+
p.add_argument("--route")
|
|
214
|
+
p.add_argument("--timeout", type=float, default=300)
|
|
215
|
+
p.set_defaults(fn=cmd_run)
|
|
216
|
+
p = sub.add_parser("q", help="SPATIAL Q: run|check|qasm|ir <file.sq>")
|
|
217
|
+
p.add_argument("rest", nargs=argparse.REMAINDER)
|
|
218
|
+
p.set_defaults(fn=cmd_q)
|
|
219
|
+
p = sub.add_parser("bench", help="run benchmarks and regenerate docs/RESULTATS.md")
|
|
220
|
+
p.add_argument("name", choices=[*BENCHES, "all"])
|
|
221
|
+
p.set_defaults(fn=cmd_bench)
|
|
222
|
+
p = sub.add_parser("serve", help="start a compute worker, a page server or a sandboxed binary runner (loopback by default)")
|
|
223
|
+
p.add_argument("kind", choices=["compute", "memory", "runtime", "hub"])
|
|
224
|
+
p.add_argument("--token-file", help="shared secret: every client may do everything")
|
|
225
|
+
p.add_argument("--master-key-file", help="scoped credentials with quotas and an audit log (see `spatial token`)")
|
|
226
|
+
p.add_argument("--audit-log")
|
|
227
|
+
p.add_argument("--host", default="127.0.0.1")
|
|
228
|
+
p.add_argument("--port", type=int, default=0)
|
|
229
|
+
p.add_argument("--allow-remote", action="store_true", help="explicit consent to accept LAN connections")
|
|
230
|
+
p.set_defaults(fn=cmd_worker)
|
|
231
|
+
p = sub.add_parser("optimize", help="ONE objective for every engine: price each way to do a job, pick the cheapest, optionally run and check")
|
|
232
|
+
p.add_argument("job", choices=["compute", "binary", "quantum", "dataset", "kv"])
|
|
233
|
+
p.add_argument("--family", default="mandel", help="compute: mandel|heat|nbody|hologram|option|ode")
|
|
234
|
+
p.add_argument("--params", default="{}", help="compute: JSON parameters, e.g. '{\"n\":800,\"iters\":300}'")
|
|
235
|
+
p.add_argument("--file", help="binary: path; quantum: .sq file")
|
|
236
|
+
p.add_argument("args", nargs="*", help="binary: arguments")
|
|
237
|
+
p.add_argument("--est-native-s", type=float, default=1.0, help="binary: expected run time when native")
|
|
238
|
+
p.add_argument("--kernel", help="quantum: kernel name"); p.add_argument("--kargs", default="[]"); p.add_argument("--shots", type=int, default=1000)
|
|
239
|
+
p.add_argument("--gib", type=float, default=1.0, help="dataset: size in GiB"); p.add_argument("--accesses", type=int, default=100000)
|
|
240
|
+
p.add_argument("--locality", type=float, default=0.8); p.add_argument("--hot-fraction", type=float, default=0.2)
|
|
241
|
+
p.add_argument("--prefix-tokens", type=int, default=1000); p.add_argument("--reuse", type=float, default=0.5); p.add_argument("--horizon-h", type=float, default=1.0)
|
|
242
|
+
p.add_argument("--objective", choices=["cost", "time"], default="cost")
|
|
243
|
+
p.add_argument("--deadline", type=float); p.add_argument("--max-ram-gib", type=float)
|
|
244
|
+
p.add_argument("--isolated", action="store_true"); p.add_argument("--allow-qpu", action="store_true"); p.add_argument("--require-hardware", action="store_true")
|
|
245
|
+
p.add_argument("--local-usd-per-hour", type=float, default=0.134, help="price of this machine (default is an assumption)")
|
|
246
|
+
p.add_argument("--ram-usd-gb-hour", type=float, default=0.0); p.add_argument("--storage-usd-gb-hour", type=float, default=0.0)
|
|
247
|
+
p.add_argument("--qpu-usd-per-shot", type=float, default=0.0); p.add_argument("--qpu-usd-per-task", type=float, default=0.0)
|
|
248
|
+
p.add_argument("--hub", help="host:port of a fleet hub: nodes become options"); p.add_argument("--token-file")
|
|
249
|
+
p.add_argument("--execute", action="store_true", help="run the chosen option and compare with the estimate")
|
|
250
|
+
p.set_defaults(fn=cmd_optimize)
|
|
251
|
+
p = sub.add_parser("agent", help="run a fleet agent: measure this machine, report to a hub, run allow-listed tasks")
|
|
252
|
+
p.add_argument("--hub", required=True, help="host:port of the hub")
|
|
253
|
+
p.add_argument("--token-file", required=True, help="shared secret file, or a scoped token with fleet:report,fleet:work")
|
|
254
|
+
p.add_argument("--name")
|
|
255
|
+
p.add_argument("--interval", type=float, default=5.0)
|
|
256
|
+
p.add_argument("--usd-per-hour", type=float, help="what this machine costs per hour (for estimates only)")
|
|
257
|
+
p.add_argument("--labels", default="")
|
|
258
|
+
p.add_argument("--no-tasks", action="store_true", help="measure only; never run tasks")
|
|
259
|
+
p.set_defaults(fn=cmd_agent)
|
|
260
|
+
p = sub.add_parser("fleet", help="see and use the fleet through a hub")
|
|
261
|
+
p.add_argument("action", choices=["status", "advise", "submit", "result"])
|
|
262
|
+
p.add_argument("--hub", required=True)
|
|
263
|
+
p.add_argument("--token-file", required=True, help="scoped token with fleet:read (status/advise) or fleet:submit")
|
|
264
|
+
p.add_argument("--window", type=float, default=60.0)
|
|
265
|
+
p.add_argument("--workload"); p.add_argument("--params", default="{}"); p.add_argument("--needs", default="{}")
|
|
266
|
+
p.add_argument("--task-id", type=int)
|
|
267
|
+
p.set_defaults(fn=cmd_fleet)
|
|
268
|
+
p = sub.add_parser("token", help="scoped credentials: `init` a master key, `issue` a tenant token")
|
|
269
|
+
p.add_argument("action", choices=["init", "issue"])
|
|
270
|
+
p.add_argument("--master-key-file", required=True)
|
|
271
|
+
p.add_argument("--name", default="tenant")
|
|
272
|
+
p.add_argument("--scopes", default="", help="comma list, e.g. run:mandel_numba,mem:read,exec:elf (trailing * = prefix)")
|
|
273
|
+
p.add_argument("--ttl", type=float, default=3600, help="seconds")
|
|
274
|
+
p.add_argument("--max-ops", type=int)
|
|
275
|
+
p.add_argument("--max-bytes", type=int)
|
|
276
|
+
p.set_defaults(fn=cmd_token)
|
|
277
|
+
a = ap.parse_args(argv)
|
|
278
|
+
if getattr(a, "cmd", None) == "serve" and bool(a.token_file) == bool(a.master_key_file):
|
|
279
|
+
ap.error("serve needs exactly one of --token-file or --master-key-file")
|
|
280
|
+
try:
|
|
281
|
+
return a.fn(a)
|
|
282
|
+
except (Exception, SystemExit) as e: # user-facing tool: one clean line, no traceback
|
|
283
|
+
if isinstance(e, SystemExit) and not isinstance(e.code, str):
|
|
284
|
+
raise
|
|
285
|
+
print(f"spatial: {type(e).__name__}: {e}", file=sys.stderr)
|
|
286
|
+
return 1
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
if __name__ == "__main__":
|
|
290
|
+
sys.exit(main())
|
|
@@ -130,12 +130,70 @@ def matmul(n: int, seed: int = 0) -> float:
|
|
|
130
130
|
return float((a @ b).trace())
|
|
131
131
|
|
|
132
132
|
|
|
133
|
+
def heat_numpy(n: int, steps: int, c: float = 0.2) -> float:
|
|
134
|
+
"""Simulation engine: 2-D heat diffusion from a hot square; returns the peak temperature."""
|
|
135
|
+
import numpy as np
|
|
136
|
+
from ..simulation.heat import simulate
|
|
137
|
+
u0 = np.zeros((n, n))
|
|
138
|
+
u0[n // 2 - n // 10: n // 2 + n // 10 + 1, n // 2 - n // 10: n // 2 + n // 10 + 1] = 100.0
|
|
139
|
+
return float(simulate(u0, c, steps, "numpy").max())
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def heat_numba(n: int, steps: int, c: float = 0.2) -> float:
|
|
143
|
+
import numpy as np
|
|
144
|
+
from ..simulation.heat import simulate
|
|
145
|
+
u0 = np.zeros((n, n))
|
|
146
|
+
u0[n // 2 - n // 10: n // 2 + n // 10 + 1, n // 2 - n // 10: n // 2 + n // 10 + 1] = 100.0
|
|
147
|
+
return float(simulate(u0, c, steps, "numba").max())
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def nbody(bodies: int, steps: int, seed: int = 1) -> float:
|
|
151
|
+
"""Simulation engine: relative energy drift of a leapfrog N-body run (should be tiny)."""
|
|
152
|
+
import numpy as np
|
|
153
|
+
from ..simulation import nbody as nb
|
|
154
|
+
rng = np.random.default_rng(seed)
|
|
155
|
+
pos, vel, mass = rng.normal(size=(bodies, 3)), rng.normal(size=(bodies, 3)) * 0.1, rng.uniform(0.5, 1.5, bodies)
|
|
156
|
+
e0 = nb.energy(pos, vel, mass, 0.05)
|
|
157
|
+
p, v = nb.leapfrog(pos, vel, mass, dt=1e-3, steps=steps, soft=0.05)
|
|
158
|
+
return float(abs(nb.energy(p, v, mass, 0.05) - e0) / abs(e0))
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def hologram_peak(n: int, seed: int = 1) -> int:
|
|
162
|
+
"""Holographic engine: synthesise a 1-point hologram, reconstruct it, return the focus position
|
|
163
|
+
(row * n + column) of the brightest pixel (it must be the emitter's pixel)."""
|
|
164
|
+
import numpy as np
|
|
165
|
+
from ..holographic import hologram, reconstruct
|
|
166
|
+
wl, pitch = 633e-9, 8e-6
|
|
167
|
+
k = int(np.random.default_rng(seed).integers(-n // 8, n // 8 + 1))
|
|
168
|
+
H = hologram(np.array([[k * pitch, 0.0, 0.05]]), np.array([1.0]), n, pitch, wl)
|
|
169
|
+
img = reconstruct(H, 0.05, pitch, wl)
|
|
170
|
+
return int(np.argmax(img))
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def option_mc(paths: int, seed: int = 0) -> float:
|
|
174
|
+
"""Scientific engine: Monte-Carlo European call price (Black-Scholes reference exists in tests)."""
|
|
175
|
+
from ..scientific import european_call_mc
|
|
176
|
+
return float(european_call_mc(100.0, 105.0, 0.03, 0.2, 1.0, paths, seed)[0])
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def harmonic_rk4_x(omega: float, t_end: float, steps: int) -> float:
|
|
180
|
+
"""Scientific engine: RK4 solution of x'' = -omega^2 x at t_end (exact: cos(omega * t_end))."""
|
|
181
|
+
from ..scientific import harmonic_rk4
|
|
182
|
+
return float(harmonic_rk4(omega, t_end, steps)[0])
|
|
183
|
+
|
|
184
|
+
|
|
133
185
|
REGISTRY = {
|
|
134
186
|
"mandel_python": mandel_python,
|
|
135
187
|
"mandel_numpy": mandel_numpy,
|
|
136
188
|
"montecarlo_pi": montecarlo_pi,
|
|
137
189
|
"sha256_chain": sha256_chain,
|
|
138
190
|
"matmul": matmul,
|
|
191
|
+
"heat_numpy": heat_numpy,
|
|
192
|
+
"heat_numba": heat_numba,
|
|
193
|
+
"nbody": nbody,
|
|
194
|
+
"hologram_peak": hologram_peak,
|
|
195
|
+
"option_mc": option_mc,
|
|
196
|
+
"harmonic_rk4": harmonic_rk4_x,
|
|
139
197
|
}
|
|
140
198
|
if HAVE_NUMBA:
|
|
141
199
|
REGISTRY["mandel_numba"] = mandel_numba
|
|
@@ -3,12 +3,15 @@
|
|
|
3
3
|
Every row carries `prev` (hash of the previous row) and `hash` = SHA-256(prev | canonical
|
|
4
4
|
JSON of the row). `verify()` detects an edited, removed or reordered row. This is tamper
|
|
5
5
|
EVIDENCE, not a signature: someone who can rewrite the whole file can rebuild the chain.
|
|
6
|
+
Thread-safe within one process. Two PROCESSES writing the same file would fork the chain: give each
|
|
7
|
+
process its own ledger file.
|
|
6
8
|
"""
|
|
7
9
|
from __future__ import annotations
|
|
8
10
|
|
|
9
11
|
import hashlib
|
|
10
12
|
import json
|
|
11
13
|
import os
|
|
14
|
+
import threading
|
|
12
15
|
import time
|
|
13
16
|
from pathlib import Path
|
|
14
17
|
|
|
@@ -29,6 +32,7 @@ class Ledger:
|
|
|
29
32
|
self.path = Path(path) if path else RESULTS / "ledger.jsonl"
|
|
30
33
|
self.path.parent.mkdir(parents=True, exist_ok=True)
|
|
31
34
|
self._last = self._tail_hash()
|
|
35
|
+
self._lock = threading.Lock() # services write from one thread per connection
|
|
32
36
|
|
|
33
37
|
def _tail_hash(self) -> str:
|
|
34
38
|
last = GENESIS
|
|
@@ -40,10 +44,11 @@ class Ledger:
|
|
|
40
44
|
|
|
41
45
|
def _append(self, row: dict) -> None:
|
|
42
46
|
row = json.loads(json.dumps(row, default=str)) # normalise before hashing
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
+
with self._lock: # read-last / hash / write must be one step
|
|
48
|
+
h = _digest(self._last, row)
|
|
49
|
+
with open(self.path, "a") as f:
|
|
50
|
+
f.write(json.dumps({**row, "prev": self._last, "hash": h}) + "\n")
|
|
51
|
+
self._last = h
|
|
47
52
|
|
|
48
53
|
def record(self, m: Measurement) -> Measurement:
|
|
49
54
|
self._append({"type": "measurement", **m.to_dict()})
|
|
@@ -29,6 +29,12 @@ ENGINES: list[Engine] = [
|
|
|
29
29
|
Status.OPERATIONAL_PROTOTYPE,
|
|
30
30
|
"tests/test_memory.py, benchmarks/bench_memory.py",
|
|
31
31
|
"user-space object store only; not kernel paging; single writer; no RDMA/CXL hardware"),
|
|
32
|
+
Engine("planner", "Spatial Planner (the one objective)", "spatial.unified", Status.OPERATIONAL_PROTOTYPE,
|
|
33
|
+
"tests/test_unified.py",
|
|
34
|
+
"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"),
|
|
35
|
+
Engine("fleet", "Spatial Fleet (agent + hub)", "spatial.fleet", Status.OPERATIONAL_PROTOTYPE,
|
|
36
|
+
"tests/test_fleet.py, benchmarks/bench_fleet.py",
|
|
37
|
+
"validated on one machine (agents on loopback); no dashboard UI; recommendations are estimates; never applies changes by itself"),
|
|
32
38
|
Engine("runtime", "Spatial Runtime Engine", "spatial.runtime", Status.OPERATIONAL_PROTOTYPE,
|
|
33
39
|
"tests/test_runtime.py, benchmarks/bench_runtime.py",
|
|
34
40
|
"Windows apps not demonstrated (no Wine / Windows image); no containers; no GUI streaming"),
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
"""Spatial Fleet: an agent on every machine, a hub that sees the whole fleet.
|
|
2
|
+
|
|
3
|
+
agent.py measures its machine continuously, reports to the hub, and runs allow-listed workloads
|
|
4
|
+
the hub hands out (pull model: the agent asks for work, nothing is pushed to it).
|
|
5
|
+
hub.py stores the fleet's measurements, places tasks, and turns the measurements into
|
|
6
|
+
recommendations whose evidence is shown. It never changes a machine by itself.
|
|
7
|
+
|
|
8
|
+
Everything travels over SWP/2 (encrypted, forward-secret, scoped credentials, audit log).
|
|
9
|
+
Savings are only ever ESTIMATES until a recommendation is applied and the fleet is measured again.
|
|
10
|
+
"""
|
|
11
|
+
def __getattr__(name): # lazy: `python -m spatial.fleet.hub` must not import itself twice
|
|
12
|
+
if name == "Agent":
|
|
13
|
+
from .agent import Agent
|
|
14
|
+
return Agent
|
|
15
|
+
if name in ("Hub", "serve_hub"):
|
|
16
|
+
from . import hub
|
|
17
|
+
return getattr(hub, name)
|
|
18
|
+
raise AttributeError(name)
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
"""Fleet agent: measure this machine continuously, report to the hub, run the hub's tasks.
|
|
2
|
+
|
|
3
|
+
Design points:
|
|
4
|
+
* outbound connections only (the agent never listens);
|
|
5
|
+
* a ring buffer keeps measurements while the hub is unreachable and delivers them, in order,
|
|
6
|
+
on reconnection (each keeps its own timestamp);
|
|
7
|
+
* the agent only runs workloads from the allow-list in compute/workloads.py: it never executes
|
|
8
|
+
code that came from the network.
|
|
9
|
+
"""
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import socket
|
|
13
|
+
import threading
|
|
14
|
+
import time
|
|
15
|
+
from collections import deque
|
|
16
|
+
|
|
17
|
+
from ..compute import workloads
|
|
18
|
+
from ..compute.detect import _nvidia_gpus, detect_node
|
|
19
|
+
from ..compute.monitor import snapshot
|
|
20
|
+
from ..core.protocol import RpcClient
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class Agent:
|
|
24
|
+
def __init__(self, host: str, port: int, token: bytes, name: str | None = None, interval_s: float = 5.0,
|
|
25
|
+
usd_per_hour: float | None = None, labels: list | None = None, run_tasks: bool = True,
|
|
26
|
+
poll_s: float = 1.0, buffer: int = 720):
|
|
27
|
+
self.host, self.port, self.token = host, port, token
|
|
28
|
+
self.name = name or socket.gethostname()
|
|
29
|
+
self.interval_s, self.poll_s = interval_s, poll_s
|
|
30
|
+
self.usd_per_hour, self.labels, self.run_tasks = usd_per_hour, labels or [], run_tasks
|
|
31
|
+
self._buf: deque = deque(maxlen=buffer)
|
|
32
|
+
self._stop = threading.Event()
|
|
33
|
+
self._threads: list[threading.Thread] = []
|
|
34
|
+
self.sent = self.reconnects = self.tasks_done = 0
|
|
35
|
+
self.last_error: str | None = None
|
|
36
|
+
self._inventory = None
|
|
37
|
+
|
|
38
|
+
# ---------------------------------------------------------------- measurement
|
|
39
|
+
def collect(self) -> dict:
|
|
40
|
+
s = snapshot()
|
|
41
|
+
return {"ts": s["ts"], "cpu_percent": s["cpu_percent"], "cpu_count": _cores(), "load1": s["load1"],
|
|
42
|
+
"ram_total": s["ram_total"], "ram_available": s["ram_available"], "swap_used": s["swap_used"],
|
|
43
|
+
"memory_pressure": s.get("memory_pressure"),
|
|
44
|
+
"gpus": [{"name": g["name"], "util": g["utilization_percent"], "vram_total": g["vram_bytes"],
|
|
45
|
+
"vram_used": g["vram_used_bytes"]} for g in _nvidia_gpus()]}
|
|
46
|
+
|
|
47
|
+
# ---------------------------------------------------------------- loops
|
|
48
|
+
def _connect(self) -> RpcClient:
|
|
49
|
+
return RpcClient(self.host, self.port, self.token, timeout=30)
|
|
50
|
+
|
|
51
|
+
def _report_loop(self):
|
|
52
|
+
cli = None
|
|
53
|
+
while not self._stop.is_set():
|
|
54
|
+
self._buf.append(self.collect())
|
|
55
|
+
try:
|
|
56
|
+
if cli is None:
|
|
57
|
+
cli = self._connect()
|
|
58
|
+
self.reconnects += 1
|
|
59
|
+
while self._buf:
|
|
60
|
+
m = self._buf[0]
|
|
61
|
+
extra = {}
|
|
62
|
+
if self._inventory is None:
|
|
63
|
+
self._inventory = detect_node().to_dict()
|
|
64
|
+
if self.sent == 0 or self.reconnects_changed:
|
|
65
|
+
extra["inventory"] = self._inventory
|
|
66
|
+
cli.call({"op": "report", "node": self.name, "metrics": m, "usd_per_hour": self.usd_per_hour,
|
|
67
|
+
"labels": self.labels, **extra})
|
|
68
|
+
self._buf.popleft()
|
|
69
|
+
self.sent += 1
|
|
70
|
+
self.reconnects_changed = False
|
|
71
|
+
self.last_error = None
|
|
72
|
+
except (OSError, ConnectionError, RuntimeError) as e:
|
|
73
|
+
self.last_error = f"{type(e).__name__}: {e}"
|
|
74
|
+
if cli is not None:
|
|
75
|
+
cli.close()
|
|
76
|
+
cli = None
|
|
77
|
+
self.reconnects_changed = True
|
|
78
|
+
self._stop.wait(self.interval_s)
|
|
79
|
+
if cli is not None:
|
|
80
|
+
cli.close()
|
|
81
|
+
|
|
82
|
+
reconnects_changed = True
|
|
83
|
+
|
|
84
|
+
def _work_loop(self):
|
|
85
|
+
cli = None
|
|
86
|
+
while not self._stop.is_set():
|
|
87
|
+
try:
|
|
88
|
+
if cli is None:
|
|
89
|
+
cli = self._connect()
|
|
90
|
+
task = cli.call({"op": "poll", "node": self.name})[0].get("task")
|
|
91
|
+
except (OSError, ConnectionError, RuntimeError):
|
|
92
|
+
if cli is not None:
|
|
93
|
+
cli.close()
|
|
94
|
+
cli = None
|
|
95
|
+
self._stop.wait(self.poll_s * 2)
|
|
96
|
+
continue
|
|
97
|
+
if not task:
|
|
98
|
+
self._stop.wait(self.poll_s)
|
|
99
|
+
continue
|
|
100
|
+
t0 = time.perf_counter()
|
|
101
|
+
try:
|
|
102
|
+
value = workloads.run(task["workload"], **task["params"])
|
|
103
|
+
msg = {"ok": True, "value": value}
|
|
104
|
+
except Exception as e:
|
|
105
|
+
msg = {"ok": False, "error": f"{type(e).__name__}: {e}"}
|
|
106
|
+
try:
|
|
107
|
+
cli.call({"op": "result", "node": self.name, "task_id": task["id"], "wall_s": time.perf_counter() - t0, **msg})
|
|
108
|
+
self.tasks_done += 1
|
|
109
|
+
except (OSError, ConnectionError, RuntimeError):
|
|
110
|
+
cli = None
|
|
111
|
+
|
|
112
|
+
# ---------------------------------------------------------------- lifecycle
|
|
113
|
+
def start(self) -> "Agent":
|
|
114
|
+
self._threads = [threading.Thread(target=self._report_loop, daemon=True)]
|
|
115
|
+
if self.run_tasks:
|
|
116
|
+
self._threads.append(threading.Thread(target=self._work_loop, daemon=True))
|
|
117
|
+
for t in self._threads:
|
|
118
|
+
t.start()
|
|
119
|
+
return self
|
|
120
|
+
|
|
121
|
+
def stop(self):
|
|
122
|
+
self._stop.set()
|
|
123
|
+
for t in self._threads:
|
|
124
|
+
t.join(timeout=10)
|
|
125
|
+
|
|
126
|
+
def run_forever(self):
|
|
127
|
+
self.start()
|
|
128
|
+
try:
|
|
129
|
+
while True:
|
|
130
|
+
time.sleep(3600)
|
|
131
|
+
except KeyboardInterrupt:
|
|
132
|
+
self.stop()
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def _cores() -> int:
|
|
136
|
+
import psutil
|
|
137
|
+
return psutil.cpu_count(logical=True) or 1
|