spatial-computing 0.10.0__tar.gz → 0.11.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.
Files changed (92) hide show
  1. {spatial_computing-0.10.0/spatial_computing.egg-info → spatial_computing-0.11.0}/PKG-INFO +3 -2
  2. {spatial_computing-0.10.0 → spatial_computing-0.11.0}/README.md +2 -1
  3. {spatial_computing-0.10.0 → spatial_computing-0.11.0}/pyproject.toml +4 -1
  4. {spatial_computing-0.10.0 → spatial_computing-0.11.0}/spatial/__init__.py +1 -1
  5. {spatial_computing-0.10.0 → spatial_computing-0.11.0}/spatial/cli.py +8 -0
  6. {spatial_computing-0.10.0 → spatial_computing-0.11.0}/spatial/compute/workloads.py +43 -0
  7. {spatial_computing-0.10.0 → spatial_computing-0.11.0}/spatial/core/registry.py +3 -0
  8. spatial_computing-0.11.0/spatial/fabric/__init__.py +8 -0
  9. spatial_computing-0.11.0/spatial/fabric/cuda.py +40 -0
  10. spatial_computing-0.11.0/spatial/fabric/devices.py +35 -0
  11. spatial_computing-0.11.0/spatial/fabric/metal.py +46 -0
  12. spatial_computing-0.11.0/spatial/fabric/metal_mandel.swift +82 -0
  13. {spatial_computing-0.10.0 → spatial_computing-0.11.0}/spatial/unified/model.py +1 -0
  14. {spatial_computing-0.10.0 → spatial_computing-0.11.0}/spatial/unified/providers.py +23 -4
  15. {spatial_computing-0.10.0 → spatial_computing-0.11.0/spatial_computing.egg-info}/PKG-INFO +3 -2
  16. {spatial_computing-0.10.0 → spatial_computing-0.11.0}/spatial_computing.egg-info/SOURCES.txt +6 -0
  17. spatial_computing-0.11.0/tests/test_fabric.py +54 -0
  18. {spatial_computing-0.10.0 → spatial_computing-0.11.0}/LICENSE +0 -0
  19. {spatial_computing-0.10.0 → spatial_computing-0.11.0}/setup.cfg +0 -0
  20. {spatial_computing-0.10.0 → spatial_computing-0.11.0}/spatial/ai/__init__.py +0 -0
  21. {spatial_computing-0.10.0 → spatial_computing-0.11.0}/spatial/ai/kvcache.py +0 -0
  22. {spatial_computing-0.10.0 → spatial_computing-0.11.0}/spatial/compute/__init__.py +0 -0
  23. {spatial_computing-0.10.0 → spatial_computing-0.11.0}/spatial/compute/cost.py +0 -0
  24. {spatial_computing-0.10.0 → spatial_computing-0.11.0}/spatial/compute/detect.py +0 -0
  25. {spatial_computing-0.10.0 → spatial_computing-0.11.0}/spatial/compute/monitor.py +0 -0
  26. {spatial_computing-0.10.0 → spatial_computing-0.11.0}/spatial/compute/scheduler.py +0 -0
  27. {spatial_computing-0.10.0 → spatial_computing-0.11.0}/spatial/compute/taskqueue.py +0 -0
  28. {spatial_computing-0.10.0 → spatial_computing-0.11.0}/spatial/compute/worker.py +0 -0
  29. {spatial_computing-0.10.0 → spatial_computing-0.11.0}/spatial/core/__init__.py +0 -0
  30. {spatial_computing-0.10.0 → spatial_computing-0.11.0}/spatial/core/auth.py +0 -0
  31. {spatial_computing-0.10.0 → spatial_computing-0.11.0}/spatial/core/energy.py +0 -0
  32. {spatial_computing-0.10.0 → spatial_computing-0.11.0}/spatial/core/ledger.py +0 -0
  33. {spatial_computing-0.10.0 → spatial_computing-0.11.0}/spatial/core/model.py +0 -0
  34. {spatial_computing-0.10.0 → spatial_computing-0.11.0}/spatial/core/protocol.py +0 -0
  35. {spatial_computing-0.10.0 → spatial_computing-0.11.0}/spatial/fleet/__init__.py +0 -0
  36. {spatial_computing-0.10.0 → spatial_computing-0.11.0}/spatial/fleet/agent.py +0 -0
  37. {spatial_computing-0.10.0 → spatial_computing-0.11.0}/spatial/fleet/hub.py +0 -0
  38. {spatial_computing-0.10.0 → spatial_computing-0.11.0}/spatial/holographic/__init__.py +0 -0
  39. {spatial_computing-0.10.0 → spatial_computing-0.11.0}/spatial/holographic/cgh.py +0 -0
  40. {spatial_computing-0.10.0 → spatial_computing-0.11.0}/spatial/holographic/model.py +0 -0
  41. {spatial_computing-0.10.0 → spatial_computing-0.11.0}/spatial/intelligence/__init__.py +0 -0
  42. {spatial_computing-0.10.0 → spatial_computing-0.11.0}/spatial/intelligence/predictor.py +0 -0
  43. {spatial_computing-0.10.0 → spatial_computing-0.11.0}/spatial/memory/__init__.py +0 -0
  44. {spatial_computing-0.10.0 → spatial_computing-0.11.0}/spatial/memory/fararray.py +0 -0
  45. {spatial_computing-0.10.0 → spatial_computing-0.11.0}/spatial/memory/pageserver.py +0 -0
  46. {spatial_computing-0.10.0 → spatial_computing-0.11.0}/spatial/memory/secure.py +0 -0
  47. {spatial_computing-0.10.0 → spatial_computing-0.11.0}/spatial/memory/shared.py +0 -0
  48. {spatial_computing-0.10.0 → spatial_computing-0.11.0}/spatial/memory/tiered.py +0 -0
  49. {spatial_computing-0.10.0 → spatial_computing-0.11.0}/spatial/q/__init__.py +0 -0
  50. {spatial_computing-0.10.0 → spatial_computing-0.11.0}/spatial/q/__main__.py +0 -0
  51. {spatial_computing-0.10.0 → spatial_computing-0.11.0}/spatial/q/backends/__init__.py +0 -0
  52. {spatial_computing-0.10.0 → spatial_computing-0.11.0}/spatial/q/codegen.py +0 -0
  53. {spatial_computing-0.10.0 → spatial_computing-0.11.0}/spatial/q/compiler.py +0 -0
  54. {spatial_computing-0.10.0 → spatial_computing-0.11.0}/spatial/q/ir.py +0 -0
  55. {spatial_computing-0.10.0 → spatial_computing-0.11.0}/spatial/q/lexer.py +0 -0
  56. {spatial_computing-0.10.0 → spatial_computing-0.11.0}/spatial/q/parser.py +0 -0
  57. {spatial_computing-0.10.0 → spatial_computing-0.11.0}/spatial/q/qir.py +0 -0
  58. {spatial_computing-0.10.0 → spatial_computing-0.11.0}/spatial/q/runtime.py +0 -0
  59. {spatial_computing-0.10.0 → spatial_computing-0.11.0}/spatial/q/sim.py +0 -0
  60. {spatial_computing-0.10.0 → spatial_computing-0.11.0}/spatial/runtime/__init__.py +0 -0
  61. {spatial_computing-0.10.0 → spatial_computing-0.11.0}/spatial/runtime/envs.py +0 -0
  62. {spatial_computing-0.10.0 → spatial_computing-0.11.0}/spatial/runtime/inspect.py +0 -0
  63. {spatial_computing-0.10.0 → spatial_computing-0.11.0}/spatial/runtime/microvm.py +0 -0
  64. {spatial_computing-0.10.0 → spatial_computing-0.11.0}/spatial/runtime/planner.py +0 -0
  65. {spatial_computing-0.10.0 → spatial_computing-0.11.0}/spatial/runtime/runner.py +0 -0
  66. {spatial_computing-0.10.0 → spatial_computing-0.11.0}/spatial/runtime/toolchain.py +0 -0
  67. {spatial_computing-0.10.0 → spatial_computing-0.11.0}/spatial/scientific/__init__.py +0 -0
  68. {spatial_computing-0.10.0 → spatial_computing-0.11.0}/spatial/scientific/jobs.py +0 -0
  69. {spatial_computing-0.10.0 → spatial_computing-0.11.0}/spatial/simulation/__init__.py +0 -0
  70. {spatial_computing-0.10.0 → spatial_computing-0.11.0}/spatial/simulation/heat.py +0 -0
  71. {spatial_computing-0.10.0 → spatial_computing-0.11.0}/spatial/simulation/nbody.py +0 -0
  72. {spatial_computing-0.10.0 → spatial_computing-0.11.0}/spatial/unified/__init__.py +0 -0
  73. {spatial_computing-0.10.0 → spatial_computing-0.11.0}/spatial/unified/planner.py +0 -0
  74. {spatial_computing-0.10.0 → spatial_computing-0.11.0}/spatial_computing.egg-info/dependency_links.txt +0 -0
  75. {spatial_computing-0.10.0 → spatial_computing-0.11.0}/spatial_computing.egg-info/entry_points.txt +0 -0
  76. {spatial_computing-0.10.0 → spatial_computing-0.11.0}/spatial_computing.egg-info/requires.txt +0 -0
  77. {spatial_computing-0.10.0 → spatial_computing-0.11.0}/spatial_computing.egg-info/top_level.txt +0 -0
  78. {spatial_computing-0.10.0 → spatial_computing-0.11.0}/tests/test_auth.py +0 -0
  79. {spatial_computing-0.10.0 → spatial_computing-0.11.0}/tests/test_compute.py +0 -0
  80. {spatial_computing-0.10.0 → spatial_computing-0.11.0}/tests/test_core.py +0 -0
  81. {spatial_computing-0.10.0 → spatial_computing-0.11.0}/tests/test_domains.py +0 -0
  82. {spatial_computing-0.10.0 → spatial_computing-0.11.0}/tests/test_engines.py +0 -0
  83. {spatial_computing-0.10.0 → spatial_computing-0.11.0}/tests/test_fleet.py +0 -0
  84. {spatial_computing-0.10.0 → spatial_computing-0.11.0}/tests/test_memory.py +0 -0
  85. {spatial_computing-0.10.0 → spatial_computing-0.11.0}/tests/test_optimizer.py +0 -0
  86. {spatial_computing-0.10.0 → spatial_computing-0.11.0}/tests/test_q.py +0 -0
  87. {spatial_computing-0.10.0 → spatial_computing-0.11.0}/tests/test_runtime.py +0 -0
  88. {spatial_computing-0.10.0 → spatial_computing-0.11.0}/tests/test_unified.py +0 -0
  89. {spatial_computing-0.10.0 → spatial_computing-0.11.0}/tests/test_v02.py +0 -0
  90. {spatial_computing-0.10.0 → spatial_computing-0.11.0}/tests/test_v03.py +0 -0
  91. {spatial_computing-0.10.0 → spatial_computing-0.11.0}/tests/test_v05.py +0 -0
  92. {spatial_computing-0.10.0 → spatial_computing-0.11.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.10.0
3
+ Version: 0.11.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
@@ -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.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).
40
+ > **Status: v0.11.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,7 @@ st.put(0, b"..." * 1000); st.get(0); print(st.stats())
93
93
 
94
94
  | Engine | Level | Evidence |
95
95
  |---|---|---|
96
+ | Virtual accelerator fabric (one job, several devices: CPU, Metal GPU, NVIDIA when present) | first components | `tests/test_fabric.py`, `benchmarks/bench_unified.py` |
96
97
  | Planner (the one objective: price every option across all engines, choose, run, check) | operational prototype | `tests/test_unified.py`, `benchmarks/bench_unified.py` |
97
98
  | Fleet (agent on every machine + hub: measure, place, recommend, audit) | operational prototype | `tests/test_fleet.py`, `benchmarks/bench_fleet.py` |
98
99
  | Compute Engine (detect, monitor, compare strategies, offload, cost) | operational prototype | `tests/test_compute.py`, `benchmarks/bench_cpu.py` |
@@ -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.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).
7
+ > **Status: v0.11.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,7 @@ st.put(0, b"..." * 1000); st.get(0); print(st.stats())
60
60
 
61
61
  | Engine | Level | Evidence |
62
62
  |---|---|---|
63
+ | Virtual accelerator fabric (one job, several devices: CPU, Metal GPU, NVIDIA when present) | first components | `tests/test_fabric.py`, `benchmarks/bench_unified.py` |
63
64
  | Planner (the one objective: price every option across all engines, choose, run, check) | operational prototype | `tests/test_unified.py`, `benchmarks/bench_unified.py` |
64
65
  | Fleet (agent on every machine + hub: measure, place, recommend, audit) | operational prototype | `tests/test_fleet.py`, `benchmarks/bench_fleet.py` |
65
66
  | Compute Engine (detect, monitor, compare strategies, offload, cost) | operational prototype | `tests/test_compute.py`, `benchmarks/bench_cpu.py` |
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "spatial-computing"
7
- version = "0.10.0"
7
+ version = "0.11.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"
@@ -31,5 +31,8 @@ spatialq = "spatial.q.runtime:main"
31
31
  [tool.setuptools.packages.find]
32
32
  include = ["spatial*"]
33
33
 
34
+ [tool.setuptools.package-data]
35
+ "spatial.fabric" = ["*.swift"]
36
+
34
37
  [tool.pytest.ini_options]
35
38
  testpaths = ["tests"]
@@ -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.10.0"
6
+ __version__ = "0.11.0"
@@ -171,6 +171,13 @@ def cmd_optimize(a):
171
171
  return 0
172
172
 
173
173
 
174
+ def cmd_devices(a):
175
+ from .fabric import discover
176
+ for d in discover():
177
+ print(f"{d.id:<8}{d.kind:<5}{d.vendor:<22}{d.name:<40}{'available' if d.available else 'UNAVAILABLE'}" + (f" ({d.note})" if d.note else ""))
178
+ return 0
179
+
180
+
174
181
  def cmd_token(a):
175
182
  from .core import auth
176
183
  if a.action == "init":
@@ -248,6 +255,7 @@ def main(argv=None):
248
255
  p.add_argument("--hub", help="host:port of a fleet hub: nodes become options"); p.add_argument("--token-file")
249
256
  p.add_argument("--execute", action="store_true", help="run the chosen option and compare with the estimate")
250
257
  p.set_defaults(fn=cmd_optimize)
258
+ sub.add_parser("devices", help="compute devices the planner can use on this machine (CPU, Metal GPU, NVIDIA GPU)").set_defaults(fn=cmd_devices)
251
259
  p = sub.add_parser("agent", help="run a fleet agent: measure this machine, report to a hub, run allow-listed tasks")
252
260
  p.add_argument("--hub", required=True, help="host:port of the hub")
253
261
  p.add_argument("--token-file", required=True, help="shared secret file, or a scoped token with fleet:report,fleet:work")
@@ -73,6 +73,27 @@ if HAVE_NUMBA:
73
73
  total += k
74
74
  return total
75
75
 
76
+ @njit(cache=True, parallel=True)
77
+ def _mandel_f32_cpu(n, iters):
78
+ total = 0
79
+ fn = np.float32(n)
80
+ for i in prange(n):
81
+ ci = np.float32(-1.3) + np.float32(2.6) * np.float32(i) / fn
82
+ row = 0
83
+ for j in range(n):
84
+ cr = np.float32(-2.0) + np.float32(2.6) * np.float32(j) / fn
85
+ zr = np.float32(0.0)
86
+ zi = np.float32(0.0)
87
+ k = 0
88
+ while k < iters and zr * zr + zi * zi <= np.float32(4.0):
89
+ t = zr * zr - zi * zi + cr
90
+ zi = np.float32(2.0) * zr * zi + ci
91
+ zr = t
92
+ k += 1
93
+ row += k
94
+ total += row
95
+ return total
96
+
76
97
  @njit(cache=True, parallel=True, fastmath=False)
77
98
  def _mandel_nb_par(n, iters, r0, r1):
78
99
  total = 0
@@ -102,6 +123,25 @@ def mandel_numba_parallel(n: int, iters: int, r0: int = 0, r1: int | None = None
102
123
  return int(_mandel_nb_par(n, iters, r0, n if r1 is None else r1))
103
124
 
104
125
 
126
+ def mandel_f32_cpu(n: int, iters: int) -> int:
127
+ """Fabric: float32 Mandelbrot on the CPU (Numba, all cores). Same job as the GPU variants."""
128
+ return int(_mandel_f32_cpu(n, iters))
129
+
130
+
131
+ def mandel_f32_metal(n: int, iters: int) -> int:
132
+ """Fabric: the same job on a Metal GPU (macOS)."""
133
+ from ..fabric import metal
134
+ return int(metal.mandel(n, iters, 1)["checksum"])
135
+
136
+
137
+ def mandel_f32_cuda(n: int, iters: int) -> int:
138
+ """Fabric: the same job on an NVIDIA GPU. Never run on real NVIDIA hardware."""
139
+ from ..fabric import cuda
140
+ if not cuda.available():
141
+ raise RuntimeError("no CUDA device visible to numba")
142
+ return cuda.mandel(n, iters)
143
+
144
+
105
145
  def montecarlo_pi(samples: int, seed: int = 0) -> float:
106
146
  rng = np.random.default_rng(seed)
107
147
  inside = 0
@@ -188,6 +228,9 @@ REGISTRY = {
188
228
  "montecarlo_pi": montecarlo_pi,
189
229
  "sha256_chain": sha256_chain,
190
230
  "matmul": matmul,
231
+ "mandel_f32_cpu": mandel_f32_cpu,
232
+ "mandel_f32_metal": mandel_f32_metal,
233
+ "mandel_f32_cuda": mandel_f32_cuda,
191
234
  "heat_numpy": heat_numpy,
192
235
  "heat_numba": heat_numba,
193
236
  "nbody": nbody,
@@ -29,6 +29,9 @@ 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("fabric", "Virtual accelerator fabric", "spatial.fabric", Status.FIRST_COMPONENTS,
33
+ "tests/test_fabric.py, benchmarks/bench_unified.py (FABRIC=1: 7 of 7 device choices correct)",
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"),
32
35
  Engine("planner", "Spatial Planner (the one objective)", "spatial.unified", Status.OPERATIONAL_PROTOTYPE,
33
36
  "tests/test_unified.py",
34
37
  "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,8 @@
1
+ """Virtual accelerator fabric: describe a job once, run it on whichever device is cheapest.
2
+
3
+ Devices today: the CPU (Numba), a Metal GPU (macOS, compiled on first use), an NVIDIA GPU through
4
+ numba.cuda (code present, NEVER RUN on real NVIDIA hardware). This is not CUDA emulation and not
5
+ a translation layer: each device runs its own native implementation of the same job, and the
6
+ planner chooses by measured cost. See docs/FABRIC.md.
7
+ """
8
+ from .devices import Device, discover # noqa: F401
@@ -0,0 +1,40 @@
1
+ """NVIDIA backend through numba.cuda. WRITTEN BUT NEVER RUN ON REAL NVIDIA HARDWARE: this machine
2
+ has none. The planner treats this variant as unavailable unless numba reports a CUDA device, and the
3
+ first real run is test A2 in docs/TESTS_NOT_DONE.md."""
4
+ from __future__ import annotations
5
+
6
+
7
+ def available() -> bool:
8
+ try:
9
+ from numba import cuda
10
+ return bool(cuda.is_available())
11
+ except Exception:
12
+ return False
13
+
14
+
15
+ def mandel(n: int, iters: int) -> int:
16
+ import numpy as np
17
+ from numba import cuda
18
+
19
+ @cuda.jit
20
+ def kern(out, n, iters):
21
+ j, i = cuda.grid(2)
22
+ if i >= n or j >= n:
23
+ return
24
+ ci = np.float32(-1.3) + np.float32(2.6) * np.float32(i) / np.float32(n)
25
+ cr = np.float32(-2.0) + np.float32(2.6) * np.float32(j) / np.float32(n)
26
+ zr = np.float32(0.0)
27
+ zi = np.float32(0.0)
28
+ k = 0
29
+ while k < iters and zr * zr + zi * zi <= np.float32(4.0):
30
+ t = zr * zr - zi * zi + cr
31
+ zi = np.float32(2.0) * zr * zi + ci
32
+ zr = t
33
+ k += 1
34
+ out[i, j] = k
35
+
36
+ d = cuda.device_array((n, n), dtype=np.uint32)
37
+ tpb = (16, 16)
38
+ kern[((n + 15) // 16, (n + 15) // 16), tpb](d, n, iters)
39
+ cuda.synchronize()
40
+ return int(d.copy_to_host().astype(np.uint64).sum())
@@ -0,0 +1,35 @@
1
+ """Discover the compute devices this machine can offer to the planner."""
2
+ from __future__ import annotations
3
+
4
+ import platform
5
+ from dataclasses import dataclass
6
+
7
+ import psutil
8
+
9
+ from . import cuda, metal
10
+
11
+
12
+ @dataclass
13
+ class Device:
14
+ id: str
15
+ kind: str # cpu | gpu
16
+ vendor: str
17
+ name: str
18
+ backend: str # numba | metal | cuda
19
+ available: bool
20
+ note: str = ""
21
+
22
+
23
+ def discover() -> list[Device]:
24
+ from ..compute.detect import _nvidia_gpus
25
+ out = [Device("cpu", "cpu", platform.processor() or platform.machine(), f"{psutil.cpu_count(logical=False)} cores", "numba", True)]
26
+ if platform.system() == "Darwin":
27
+ ok = metal.available()
28
+ out.append(Device("metal", "gpu", "Apple/Intel (Metal)", (metal.device_name() or "Metal GPU") if ok else "Metal GPU", "metal", ok,
29
+ "" if ok else "needs swiftc"))
30
+ for i, g in enumerate(_nvidia_gpus()):
31
+ out.append(Device(f"cuda:{i}", "gpu", "NVIDIA", g["name"], "cuda", cuda.available(),
32
+ "" if cuda.available() else "nvidia-smi sees it but numba.cuda does not: install numba CUDA support"))
33
+ if not any(d.vendor == "NVIDIA" for d in out):
34
+ out.append(Device("cuda", "gpu", "NVIDIA", "no NVIDIA GPU detected", "cuda", False, "no nvidia-smi"))
35
+ return out
@@ -0,0 +1,46 @@
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
@@ -0,0 +1,82 @@
1
+ // GPU reference workload: Mandelbrot iteration counts on the Metal GPU (float32).
2
+ // usage: metal_mandel <n> <iters> [reps=3]
3
+ // prints one JSON line. The shader is compiled at run time (no Xcode toolchain needed).
4
+ import Foundation
5
+ import CoreGraphics
6
+ import Metal
7
+
8
+ let shader = """
9
+ #include <metal_stdlib>
10
+ using namespace metal;
11
+ struct P { uint n; uint iters; };
12
+ kernel void mandel(device uint *out [[buffer(0)]], constant P &p [[buffer(1)]],
13
+ uint2 gid [[thread_position_in_grid]]) {
14
+ if (gid.x >= p.n || gid.y >= p.n) return;
15
+ float ci = -1.3f + 2.6f * float(gid.y) / float(p.n);
16
+ float cr = -2.0f + 2.6f * float(gid.x) / float(p.n);
17
+ float zr = 0.0f, zi = 0.0f;
18
+ uint k = 0;
19
+ while (k < p.iters && zr * zr + zi * zi <= 4.0f) {
20
+ float t = zr * zr - zi * zi + cr;
21
+ zi = 2.0f * zr * zi + ci;
22
+ zr = t;
23
+ k++;
24
+ }
25
+ out[gid.y * p.n + gid.x] = k;
26
+ }
27
+ """
28
+
29
+ struct P { var n: UInt32; var iters: UInt32 }
30
+
31
+ func now() -> Double { return Double(DispatchTime.now().uptimeNanoseconds) / 1e9 }
32
+
33
+ let args = CommandLine.arguments
34
+ let n = args.count > 1 ? Int(args[1])! : 1024
35
+ let iters = args.count > 2 ? Int(args[2])! : 300
36
+ let reps = max(1, args.count > 3 ? Int(args[3])! : 3)
37
+
38
+ // In a command-line tool the default device can be nil; enumerate explicitly as a fallback.
39
+ guard let dev = MTLCreateSystemDefaultDevice() ?? MTLCopyAllDevices().first else {
40
+ print("{\"ok\": false, \"error\": \"no Metal device\"}")
41
+ exit(1)
42
+ }
43
+ let t0 = now()
44
+ let lib: MTLLibrary
45
+ do { lib = try dev.makeLibrary(source: shader, options: nil) } catch {
46
+ print("{\"ok\": false, \"error\": \"shader compile failed\"}")
47
+ exit(1)
48
+ }
49
+ let fn = lib.makeFunction(name: "mandel")!
50
+ let pipe = try! dev.makeComputePipelineState(function: fn)
51
+ let setupS = now() - t0
52
+
53
+ let out = dev.makeBuffer(length: n * n * 4, options: .storageModeShared)!
54
+ var p = P(n: UInt32(n), iters: UInt32(iters))
55
+ let queue = dev.makeCommandQueue()!
56
+
57
+ func run() -> Double {
58
+ let t = now()
59
+ let cb = queue.makeCommandBuffer()!
60
+ let enc = cb.makeComputeCommandEncoder()!
61
+ enc.setComputePipelineState(pipe)
62
+ enc.setBuffer(out, offset: 0, index: 0)
63
+ enc.setBytes(&p, length: MemoryLayout<P>.size, index: 1)
64
+ let w = pipe.threadExecutionWidth
65
+ let h = pipe.maxTotalThreadsPerThreadgroup / w
66
+ enc.dispatchThreadgroups(MTLSize(width: (n + w - 1) / w, height: (n + h - 1) / h, depth: 1),
67
+ threadsPerThreadgroup: MTLSize(width: w, height: h, depth: 1))
68
+ enc.endEncoding()
69
+ cb.commit()
70
+ cb.waitUntilCompleted()
71
+ return now() - t
72
+ }
73
+
74
+ var times: [Double] = []
75
+ for _ in 0..<reps { times.append(run()) }
76
+ let ptr = out.contents().bindMemory(to: UInt32.self, capacity: n * n)
77
+ var total: UInt64 = 0
78
+ for i in 0..<(n * n) { total += UInt64(ptr[i]) }
79
+ times.sort()
80
+ print("{\"ok\": true, \"device\": \"\(dev.name)\", \"n\": \(n), \"iters\": \(iters), \"checksum\": \(total), " +
81
+ "\"gpu_s_median\": \(times[times.count / 2]), \"gpu_s_all\": \(times), \"setup_s\": \(setupS), " +
82
+ "\"low_power\": \(dev.isLowPower), \"max_buffer_MB\": \(dev.maxBufferLength / 1_000_000)}")
@@ -25,6 +25,7 @@ class Prices:
25
25
  local_usd_per_hour: float = 0.134
26
26
  ram_usd_gb_hour: float = 0.0 # cost of holding a GB in RAM for an hour (0 = not charged)
27
27
  storage_usd_gb_hour: float = 0.0 # same for SSD/object storage
28
+ device_usd_h: dict = field(default_factory=dict) # price per hour of a specific device/variant, e.g. {"gpu_cuda": 1.2}
28
29
  qpu_usd_per_shot: float = 0.0 # provider tariff, supplied by the caller
29
30
  qpu_usd_per_task: float = 0.0
30
31
  qpu_seconds_per_shot: float = 0.0
@@ -29,6 +29,9 @@ ROOT = Path(__file__).resolve().parents[2]
29
29
  FAMILIES = {
30
30
  "mandel": dict(variants={"python": "mandel_python", "numpy": "mandel_numpy", "numba_jit": "mandel_numba",
31
31
  "numba_threads": "mandel_numba_parallel"}, scale="n", exp=2.0, min=8, exact=True),
32
+ # one job, three devices: the planner picks by measured cost (CPU for small sizes, the GPU once its fixed cost is amortised)
33
+ "mandel_f32": dict(variants={"cpu": "mandel_f32_cpu", "gpu_metal": "mandel_f32_metal", "gpu_cuda": "mandel_f32_cuda"},
34
+ scale="n", exp=2.0, min=8, exact=False, tol=1e-3),
32
35
  "heat": dict(variants={"numpy": "heat_numpy", "numba": "heat_numba"}, scale="steps", exp=1.0, min=2, exact=False),
33
36
  "nbody": dict(variants={"cpu": "nbody"}, scale="steps", exp=1.0, min=2, exact=False),
34
37
  "hologram": dict(variants={"cpu": "hologram_peak"}, scale="n", exp=2.0, min=32, exact=True),
@@ -37,8 +40,19 @@ FAMILIES = {
37
40
  }
38
41
 
39
42
 
40
- def _same(a, b, exact: bool) -> bool:
41
- return a == b if exact else math.isclose(a, b, rel_tol=1e-6, abs_tol=1e-12)
43
+ def _same(a, b, exact: bool, tol: float = 1e-6) -> bool:
44
+ return a == b if exact else math.isclose(a, b, rel_tol=tol, abs_tol=1e-12)
45
+
46
+
47
+ def _variant_available(workload: str) -> str | None:
48
+ """None if the variant can run here, else why not."""
49
+ if workload == "mandel_f32_metal":
50
+ from ..fabric import metal
51
+ return None if metal.available() else "no Metal GPU (macOS with swiftc is required)"
52
+ if workload == "mandel_f32_cuda":
53
+ from ..fabric import cuda
54
+ return None if cuda.available() else "no NVIDIA GPU usable by numba.cuda on this machine"
55
+ return None
42
56
 
43
57
 
44
58
  def _best_of(fn, min_total_s: float = 0.01, max_reps: int = 25):
@@ -74,6 +88,10 @@ class ComputeProvider(Provider):
74
88
  s1, s2 = (s, s) if small else (max(fam["min"], s // 8), max(fam["min"] * 2, s // 4))
75
89
  out, ref = [], None
76
90
  for vname, wname in fam["variants"].items():
91
+ why = _variant_available(wname)
92
+ if why:
93
+ out.append(Option("compute", vname, False, why, isolated=None, basis="device not available"))
94
+ continue
77
95
  workloads.run(wname, **{**params, scale: fam["min"]}) # warm-up (JIT), not timed
78
96
  t1, r1 = _best_of(lambda: workloads.run(wname, **{**params, scale: s1}))
79
97
  if small:
@@ -87,11 +105,12 @@ class ComputeProvider(Provider):
87
105
  est, basis = a_ + b_ * wf, f"probe 1/8+1/4, affine fit"
88
106
  else: # noisy probes: fall back to proportional scaling from the larger one
89
107
  est, basis = t2 * wf / w2, "probe 1/4, proportional"
90
- o = Option("compute", vname, True, est_time_s=est, rate_usd_h=planner.prices.local_usd_per_hour, isolated=None, basis=basis,
108
+ o = Option("compute", vname, True, est_time_s=est, rate_usd_h=planner.prices.device_usd_h.get(vname, planner.prices.local_usd_per_hour),
109
+ isolated=None, basis=basis,
91
110
  run=(lambda wn=wname: workloads.run(wn, **params)), meta={"workload": wname, "params": params})
92
111
  if ref is None:
93
112
  ref = r
94
- elif not _same(r, ref, fam["exact"]):
113
+ elif not _same(r, ref, fam["exact"], fam.get("tol", 1e-6)):
95
114
  o.reject("result differs from the other variants on the probe")
96
115
  out.append(planner.calibrate("compute", o))
97
116
  return out
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: spatial-computing
3
- Version: 0.10.0
3
+ Version: 0.11.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
@@ -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.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).
40
+ > **Status: v0.11.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,7 @@ st.put(0, b"..." * 1000); st.get(0); print(st.stats())
93
93
 
94
94
  | Engine | Level | Evidence |
95
95
  |---|---|---|
96
+ | Virtual accelerator fabric (one job, several devices: CPU, Metal GPU, NVIDIA when present) | first components | `tests/test_fabric.py`, `benchmarks/bench_unified.py` |
96
97
  | Planner (the one objective: price every option across all engines, choose, run, check) | operational prototype | `tests/test_unified.py`, `benchmarks/bench_unified.py` |
97
98
  | Fleet (agent on every machine + hub: measure, place, recommend, audit) | operational prototype | `tests/test_fleet.py`, `benchmarks/bench_fleet.py` |
98
99
  | Compute Engine (detect, monitor, compare strategies, offload, cost) | operational prototype | `tests/test_compute.py`, `benchmarks/bench_cpu.py` |
@@ -20,6 +20,11 @@ spatial/core/ledger.py
20
20
  spatial/core/model.py
21
21
  spatial/core/protocol.py
22
22
  spatial/core/registry.py
23
+ spatial/fabric/__init__.py
24
+ spatial/fabric/cuda.py
25
+ spatial/fabric/devices.py
26
+ spatial/fabric/metal.py
27
+ spatial/fabric/metal_mandel.swift
23
28
  spatial/fleet/__init__.py
24
29
  spatial/fleet/agent.py
25
30
  spatial/fleet/hub.py
@@ -72,6 +77,7 @@ tests/test_compute.py
72
77
  tests/test_core.py
73
78
  tests/test_domains.py
74
79
  tests/test_engines.py
80
+ tests/test_fabric.py
75
81
  tests/test_fleet.py
76
82
  tests/test_memory.py
77
83
  tests/test_optimizer.py
@@ -0,0 +1,54 @@
1
+ """Virtual accelerator fabric: one job, several devices, chosen by measured cost."""
2
+ import pytest
3
+
4
+ from spatial.compute import workloads
5
+ from spatial.core.ledger import Ledger
6
+ from spatial.fabric import discover, metal
7
+ from spatial.unified import Job, Objective, Planner, Prices
8
+
9
+ needs_metal = pytest.mark.skipif(not metal.available(), reason="no Metal GPU (macOS with swiftc)")
10
+
11
+
12
+ @pytest.fixture
13
+ def planner(tmp_path):
14
+ return Planner(ledger=Ledger(tmp_path / "plan.jsonl"))
15
+
16
+
17
+ def test_discovery_always_reports_the_cpu_and_never_pretends_about_nvidia():
18
+ ds = {d.id: d for d in discover()}
19
+ assert ds["cpu"].available and ds["cpu"].backend == "numba"
20
+ nv = [d for d in ds.values() if d.vendor == "NVIDIA"]
21
+ assert nv and all((not d.available) or d.backend == "cuda" for d in nv)
22
+
23
+
24
+ def test_cuda_variant_is_rejected_with_the_reason_when_there_is_no_nvidia_gpu(planner):
25
+ from spatial.fabric import cuda
26
+ if cuda.available():
27
+ pytest.skip("a real CUDA device is present: covered by the hardware test A2")
28
+ plan = planner.plan(Job.compute("mandel_f32", n=64, iters=50))
29
+ gpu = next(o for o in plan.options if o.name == "gpu_cuda")
30
+ assert not gpu.feasible and "NVIDIA" in gpu.reason and plan.chosen.name != "gpu_cuda"
31
+ with pytest.raises(RuntimeError, match="no CUDA device"):
32
+ workloads.mandel_f32_cuda(64, 50)
33
+
34
+
35
+ @needs_metal
36
+ def test_same_job_on_cpu_and_gpu_agrees_and_the_planner_picks_the_device_by_size(planner):
37
+ assert abs(workloads.mandel_f32_cpu(256, 120) - workloads.mandel_f32_metal(256, 120)) / workloads.mandel_f32_cpu(256, 120) < 1e-3
38
+ small = planner.plan(Job.compute("mandel_f32", n=32, iters=100))
39
+ big = planner.plan(Job.compute("mandel_f32", n=2048, iters=200))
40
+ assert small.chosen.name == "cpu" # a GPU launch has a fixed cost that a tiny job cannot amortise
41
+ assert big.chosen.name == "gpu_metal" # ... that a big job easily does
42
+ gpu_big = next(o for o in big.options if o.name == "gpu_metal")
43
+ cpu_big = next(o for o in big.options if o.name == "cpu")
44
+ assert gpu_big.est_time_s < cpu_big.est_time_s
45
+ ex = planner.execute(big)
46
+ assert abs(ex.result - workloads.mandel_f32_cpu(2048, 200)) / ex.result < 1e-3
47
+ assert abs(ex.time_error_pct) < 400 # one run: the GPU process start-up adds jitter; accuracy is measured in bench_unified.py
48
+
49
+
50
+ @needs_metal
51
+ def test_device_prices_change_the_choice(planner):
52
+ pricey = Planner(prices=Prices(device_usd_h={"gpu_metal": 1e6}), ledger=planner.ledger)
53
+ assert pricey.plan(Job.compute("mandel_f32", n=2048, iters=200)).chosen.name == "cpu" # GPU too dear to rent
54
+ assert pricey.plan(Job.compute("mandel_f32", n=2048, iters=200), Objective(minimize="time")).chosen.name == "gpu_metal"