spatial-computing 0.9.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.
Files changed (86) hide show
  1. {spatial_computing-0.9.0/spatial_computing.egg-info → spatial_computing-0.10.0}/PKG-INFO +4 -3
  2. {spatial_computing-0.9.0 → spatial_computing-0.10.0}/README.md +3 -2
  3. {spatial_computing-0.9.0 → spatial_computing-0.10.0}/pyproject.toml +1 -1
  4. {spatial_computing-0.9.0 → spatial_computing-0.10.0}/spatial/__init__.py +1 -1
  5. {spatial_computing-0.9.0 → spatial_computing-0.10.0}/spatial/cli.py +54 -0
  6. {spatial_computing-0.9.0 → spatial_computing-0.10.0}/spatial/compute/workloads.py +58 -0
  7. {spatial_computing-0.9.0 → spatial_computing-0.10.0}/spatial/core/registry.py +3 -0
  8. spatial_computing-0.10.0/spatial/unified/__init__.py +11 -0
  9. spatial_computing-0.10.0/spatial/unified/model.py +160 -0
  10. spatial_computing-0.10.0/spatial/unified/planner.py +99 -0
  11. spatial_computing-0.10.0/spatial/unified/providers.py +397 -0
  12. {spatial_computing-0.9.0 → spatial_computing-0.10.0/spatial_computing.egg-info}/PKG-INFO +4 -3
  13. {spatial_computing-0.9.0 → spatial_computing-0.10.0}/spatial_computing.egg-info/SOURCES.txt +5 -0
  14. spatial_computing-0.10.0/tests/test_unified.py +162 -0
  15. {spatial_computing-0.9.0 → spatial_computing-0.10.0}/LICENSE +0 -0
  16. {spatial_computing-0.9.0 → spatial_computing-0.10.0}/setup.cfg +0 -0
  17. {spatial_computing-0.9.0 → spatial_computing-0.10.0}/spatial/ai/__init__.py +0 -0
  18. {spatial_computing-0.9.0 → spatial_computing-0.10.0}/spatial/ai/kvcache.py +0 -0
  19. {spatial_computing-0.9.0 → spatial_computing-0.10.0}/spatial/compute/__init__.py +0 -0
  20. {spatial_computing-0.9.0 → spatial_computing-0.10.0}/spatial/compute/cost.py +0 -0
  21. {spatial_computing-0.9.0 → spatial_computing-0.10.0}/spatial/compute/detect.py +0 -0
  22. {spatial_computing-0.9.0 → spatial_computing-0.10.0}/spatial/compute/monitor.py +0 -0
  23. {spatial_computing-0.9.0 → spatial_computing-0.10.0}/spatial/compute/scheduler.py +0 -0
  24. {spatial_computing-0.9.0 → spatial_computing-0.10.0}/spatial/compute/taskqueue.py +0 -0
  25. {spatial_computing-0.9.0 → spatial_computing-0.10.0}/spatial/compute/worker.py +0 -0
  26. {spatial_computing-0.9.0 → spatial_computing-0.10.0}/spatial/core/__init__.py +0 -0
  27. {spatial_computing-0.9.0 → spatial_computing-0.10.0}/spatial/core/auth.py +0 -0
  28. {spatial_computing-0.9.0 → spatial_computing-0.10.0}/spatial/core/energy.py +0 -0
  29. {spatial_computing-0.9.0 → spatial_computing-0.10.0}/spatial/core/ledger.py +0 -0
  30. {spatial_computing-0.9.0 → spatial_computing-0.10.0}/spatial/core/model.py +0 -0
  31. {spatial_computing-0.9.0 → spatial_computing-0.10.0}/spatial/core/protocol.py +0 -0
  32. {spatial_computing-0.9.0 → spatial_computing-0.10.0}/spatial/fleet/__init__.py +0 -0
  33. {spatial_computing-0.9.0 → spatial_computing-0.10.0}/spatial/fleet/agent.py +0 -0
  34. {spatial_computing-0.9.0 → spatial_computing-0.10.0}/spatial/fleet/hub.py +0 -0
  35. {spatial_computing-0.9.0 → spatial_computing-0.10.0}/spatial/holographic/__init__.py +0 -0
  36. {spatial_computing-0.9.0 → spatial_computing-0.10.0}/spatial/holographic/cgh.py +0 -0
  37. {spatial_computing-0.9.0 → spatial_computing-0.10.0}/spatial/holographic/model.py +0 -0
  38. {spatial_computing-0.9.0 → spatial_computing-0.10.0}/spatial/intelligence/__init__.py +0 -0
  39. {spatial_computing-0.9.0 → spatial_computing-0.10.0}/spatial/intelligence/predictor.py +0 -0
  40. {spatial_computing-0.9.0 → spatial_computing-0.10.0}/spatial/memory/__init__.py +0 -0
  41. {spatial_computing-0.9.0 → spatial_computing-0.10.0}/spatial/memory/fararray.py +0 -0
  42. {spatial_computing-0.9.0 → spatial_computing-0.10.0}/spatial/memory/pageserver.py +0 -0
  43. {spatial_computing-0.9.0 → spatial_computing-0.10.0}/spatial/memory/secure.py +0 -0
  44. {spatial_computing-0.9.0 → spatial_computing-0.10.0}/spatial/memory/shared.py +0 -0
  45. {spatial_computing-0.9.0 → spatial_computing-0.10.0}/spatial/memory/tiered.py +0 -0
  46. {spatial_computing-0.9.0 → spatial_computing-0.10.0}/spatial/q/__init__.py +0 -0
  47. {spatial_computing-0.9.0 → spatial_computing-0.10.0}/spatial/q/__main__.py +0 -0
  48. {spatial_computing-0.9.0 → spatial_computing-0.10.0}/spatial/q/backends/__init__.py +0 -0
  49. {spatial_computing-0.9.0 → spatial_computing-0.10.0}/spatial/q/codegen.py +0 -0
  50. {spatial_computing-0.9.0 → spatial_computing-0.10.0}/spatial/q/compiler.py +0 -0
  51. {spatial_computing-0.9.0 → spatial_computing-0.10.0}/spatial/q/ir.py +0 -0
  52. {spatial_computing-0.9.0 → spatial_computing-0.10.0}/spatial/q/lexer.py +0 -0
  53. {spatial_computing-0.9.0 → spatial_computing-0.10.0}/spatial/q/parser.py +0 -0
  54. {spatial_computing-0.9.0 → spatial_computing-0.10.0}/spatial/q/qir.py +0 -0
  55. {spatial_computing-0.9.0 → spatial_computing-0.10.0}/spatial/q/runtime.py +0 -0
  56. {spatial_computing-0.9.0 → spatial_computing-0.10.0}/spatial/q/sim.py +0 -0
  57. {spatial_computing-0.9.0 → spatial_computing-0.10.0}/spatial/runtime/__init__.py +0 -0
  58. {spatial_computing-0.9.0 → spatial_computing-0.10.0}/spatial/runtime/envs.py +0 -0
  59. {spatial_computing-0.9.0 → spatial_computing-0.10.0}/spatial/runtime/inspect.py +0 -0
  60. {spatial_computing-0.9.0 → spatial_computing-0.10.0}/spatial/runtime/microvm.py +0 -0
  61. {spatial_computing-0.9.0 → spatial_computing-0.10.0}/spatial/runtime/planner.py +0 -0
  62. {spatial_computing-0.9.0 → spatial_computing-0.10.0}/spatial/runtime/runner.py +0 -0
  63. {spatial_computing-0.9.0 → spatial_computing-0.10.0}/spatial/runtime/toolchain.py +0 -0
  64. {spatial_computing-0.9.0 → spatial_computing-0.10.0}/spatial/scientific/__init__.py +0 -0
  65. {spatial_computing-0.9.0 → spatial_computing-0.10.0}/spatial/scientific/jobs.py +0 -0
  66. {spatial_computing-0.9.0 → spatial_computing-0.10.0}/spatial/simulation/__init__.py +0 -0
  67. {spatial_computing-0.9.0 → spatial_computing-0.10.0}/spatial/simulation/heat.py +0 -0
  68. {spatial_computing-0.9.0 → spatial_computing-0.10.0}/spatial/simulation/nbody.py +0 -0
  69. {spatial_computing-0.9.0 → spatial_computing-0.10.0}/spatial_computing.egg-info/dependency_links.txt +0 -0
  70. {spatial_computing-0.9.0 → spatial_computing-0.10.0}/spatial_computing.egg-info/entry_points.txt +0 -0
  71. {spatial_computing-0.9.0 → spatial_computing-0.10.0}/spatial_computing.egg-info/requires.txt +0 -0
  72. {spatial_computing-0.9.0 → spatial_computing-0.10.0}/spatial_computing.egg-info/top_level.txt +0 -0
  73. {spatial_computing-0.9.0 → spatial_computing-0.10.0}/tests/test_auth.py +0 -0
  74. {spatial_computing-0.9.0 → spatial_computing-0.10.0}/tests/test_compute.py +0 -0
  75. {spatial_computing-0.9.0 → spatial_computing-0.10.0}/tests/test_core.py +0 -0
  76. {spatial_computing-0.9.0 → spatial_computing-0.10.0}/tests/test_domains.py +0 -0
  77. {spatial_computing-0.9.0 → spatial_computing-0.10.0}/tests/test_engines.py +0 -0
  78. {spatial_computing-0.9.0 → spatial_computing-0.10.0}/tests/test_fleet.py +0 -0
  79. {spatial_computing-0.9.0 → spatial_computing-0.10.0}/tests/test_memory.py +0 -0
  80. {spatial_computing-0.9.0 → spatial_computing-0.10.0}/tests/test_optimizer.py +0 -0
  81. {spatial_computing-0.9.0 → spatial_computing-0.10.0}/tests/test_q.py +0 -0
  82. {spatial_computing-0.9.0 → spatial_computing-0.10.0}/tests/test_runtime.py +0 -0
  83. {spatial_computing-0.9.0 → spatial_computing-0.10.0}/tests/test_v02.py +0 -0
  84. {spatial_computing-0.9.0 → spatial_computing-0.10.0}/tests/test_v03.py +0 -0
  85. {spatial_computing-0.9.0 → spatial_computing-0.10.0}/tests/test_v05.py +0 -0
  86. {spatial_computing-0.9.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.9.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 chooses where and how a workload should run from measurements, and claims a gain 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.
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.9.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.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,7 @@ 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` |
96
97
  | Fleet (agent on every machine + hub: measure, place, recommend, audit) | operational prototype | `tests/test_fleet.py`, `benchmarks/bench_fleet.py` |
97
98
  | Compute Engine (detect, monitor, compare strategies, offload, cost) | operational prototype | `tests/test_compute.py`, `benchmarks/bench_cpu.py` |
98
99
  | Tiered memory (hot / compressed / far) | operational prototype | `tests/test_memory.py`, `benchmarks/bench_memory.py` |
@@ -2,9 +2,9 @@
2
2
 
3
3
  **Measure. Decide. Prove.**
4
4
 
5
- Spatial Computing chooses where and how a workload should run from measurements, and claims a gain 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.
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.9.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.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,7 @@ 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` |
63
64
  | Fleet (agent on every machine + hub: measure, place, recommend, audit) | operational prototype | `tests/test_fleet.py`, `benchmarks/bench_fleet.py` |
64
65
  | Compute Engine (detect, monitor, compare strategies, offload, cost) | operational prototype | `tests/test_compute.py`, `benchmarks/bench_cpu.py` |
65
66
  | Tiered memory (hot / compressed / far) | operational prototype | `tests/test_memory.py`, `benchmarks/bench_memory.py` |
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "spatial-computing"
7
- version = "0.9.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"
@@ -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.9.0"
6
+ __version__ = "0.10.0"
@@ -137,6 +137,40 @@ def cmd_fleet(a):
137
137
  return 0
138
138
 
139
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
+
140
174
  def cmd_token(a):
141
175
  from .core import auth
142
176
  if a.action == "init":
@@ -194,6 +228,26 @@ def main(argv=None):
194
228
  p.add_argument("--port", type=int, default=0)
195
229
  p.add_argument("--allow-remote", action="store_true", help="explicit consent to accept LAN connections")
196
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)
197
251
  p = sub.add_parser("agent", help="run a fleet agent: measure this machine, report to a hub, run allow-listed tasks")
198
252
  p.add_argument("--hub", required=True, help="host:port of the hub")
199
253
  p.add_argument("--token-file", required=True, help="shared secret file, or a scoped token with fleet:report,fleet:work")
@@ -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
@@ -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("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"),
32
35
  Engine("fleet", "Spatial Fleet (agent + hub)", "spatial.fleet", Status.OPERATIONAL_PROTOTYPE,
33
36
  "tests/test_fleet.py, benchmarks/bench_fleet.py",
34
37
  "validated on one machine (agents on loopback); no dashboard UI; recommendations are estimates; never applies changes by itself"),
@@ -0,0 +1,11 @@
1
+ """The unified planner: ONE objective for the whole infrastructure.
2
+
3
+ get the job done correctly at the lowest cost in dollars, within the stated constraints,
4
+ and prove it (estimate recorded next to reality; future estimates corrected by that history).
5
+
6
+ Every engine plugs in through a provider that turns a job into priced options:
7
+ compute / simulation / scientific / holographic (numerical families), fleet (nodes), tiered memory
8
+ (datasets), runtime (binaries), SPATIAL Q (circuits) and the AI cache (KV prefixes).
9
+ """
10
+ from .model import Execution, Job, Objective, Option, Plan, PlanError, Prices, Validated # noqa: F401
11
+ from .planner import Planner # noqa: F401
@@ -0,0 +1,160 @@
1
+ """The single objective and the shared vocabulary of the planner.
2
+
3
+ OBJECTIVE (the same for every engine): get the job done correctly at the lowest cost in dollars,
4
+ within the constraints the caller states (deadline, RAM, isolation, hardware), and PROVE it:
5
+ every executed plan records the estimate next to what really happened, and the estimates of the
6
+ next plans are corrected by that history.
7
+
8
+ Costs are computed from prices the caller gives (or the defaults below, which are assumptions).
9
+ Nothing here invents a price for a service the caller has not priced.
10
+ """
11
+ from __future__ import annotations
12
+
13
+ from dataclasses import dataclass, field
14
+ from typing import Any, Callable
15
+
16
+
17
+ class PlanError(Exception):
18
+ """No option satisfies the objective; the message lists why each one was rejected."""
19
+
20
+
21
+ @dataclass
22
+ class Prices:
23
+ # Default = a 2017 laptop amortised over 4 years at 8 h/day plus 32.5 W of electricity at 0.17 $/kWh.
24
+ # It is an ASSUMPTION: set the real figure for your machines.
25
+ local_usd_per_hour: float = 0.134
26
+ ram_usd_gb_hour: float = 0.0 # cost of holding a GB in RAM for an hour (0 = not charged)
27
+ storage_usd_gb_hour: float = 0.0 # same for SSD/object storage
28
+ qpu_usd_per_shot: float = 0.0 # provider tariff, supplied by the caller
29
+ qpu_usd_per_task: float = 0.0
30
+ qpu_seconds_per_shot: float = 0.0
31
+ qpu_usd_per_second: float = 0.0
32
+
33
+ def qpu_priced(self) -> bool:
34
+ return bool(self.qpu_usd_per_shot or self.qpu_usd_per_task or self.qpu_usd_per_second)
35
+
36
+
37
+ @dataclass
38
+ class Objective:
39
+ minimize: str = "cost" # "cost" (default, the one objective) or "time" (tie-break reversed)
40
+ deadline_s: float | None = None
41
+ max_ram_bytes: int | None = None
42
+ require_isolation: bool = False # binaries: only routes that isolate the program from the host
43
+ allow_qpu: bool = False # real quantum hardware is never used unless asked for
44
+ require_hardware: bool = False # quantum: refuse simulators
45
+ allow_remote: bool = True # fleet nodes
46
+
47
+ def __post_init__(self):
48
+ if self.minimize not in ("cost", "time"):
49
+ raise ValueError("minimize must be 'cost' or 'time'")
50
+
51
+
52
+ @dataclass
53
+ class Job:
54
+ kind: str # compute | binary | quantum | dataset | kv
55
+ spec: dict[str, Any] = field(default_factory=dict)
56
+
57
+ @classmethod
58
+ def compute(cls, family: str, **params) -> "Job":
59
+ """A numerical job from a registered family (mandel, heat, nbody, hologram, option, ode)."""
60
+ return cls("compute", {"family": family, "params": params})
61
+
62
+ @classmethod
63
+ def binary(cls, path: str, args: list[str] | None = None, est_native_s: float = 1.0) -> "Job":
64
+ return cls("binary", {"path": path, "args": args or [], "est_native_s": est_native_s})
65
+
66
+ @classmethod
67
+ def quantum(cls, source: str, kernel: str, args: list | None = None, shots: int = 1000) -> "Job":
68
+ return cls("quantum", {"source": source, "kernel": kernel, "args": args or [], "shots": shots})
69
+
70
+ @classmethod
71
+ def dataset(cls, total_bytes: int, accesses: int, locality: float = 0.8, hot_fraction: float = 0.2,
72
+ page_bytes: int = 65536) -> "Job":
73
+ """Keep `total_bytes` addressable and touch it `accesses` times; `locality` of the accesses
74
+ go to the hottest `hot_fraction` of the data."""
75
+ return cls("dataset", {"total_bytes": int(total_bytes), "accesses": int(accesses), "locality": locality,
76
+ "hot_fraction": hot_fraction, "page_bytes": page_bytes})
77
+
78
+ @classmethod
79
+ def kv_cache(cls, prefix_tokens: int, reuse_prob: float, horizon_h: float = 1.0) -> "Job":
80
+ """A cached inference prefix: keep it for later reuse or recompute it when needed (toy model)."""
81
+ return cls("kv", {"prefix_tokens": int(prefix_tokens), "reuse_prob": float(reuse_prob), "horizon_h": horizon_h})
82
+
83
+ def label(self) -> str:
84
+ s = {k: v for k, v in self.spec.items() if k != "source"}
85
+ return f"{self.kind} {s}"
86
+
87
+
88
+ @dataclass
89
+ class Validated:
90
+ """Returned by options that can only be run at reduced scale (datasets, KV cache): the result plus
91
+ the measured wall time and the time the estimate predicted for that same reduced run."""
92
+ result: Any
93
+ wall_s: float
94
+ est_time_s: float
95
+
96
+
97
+ @dataclass
98
+ class Option:
99
+ engine: str
100
+ name: str
101
+ feasible: bool
102
+ reason: str = ""
103
+ est_time_s: float | None = None
104
+ rate_usd_h: float = 0.0 # what the resource costs per hour while this option runs
105
+ fixed_usd: float = 0.0 # costs that do not depend on time (a QPU task fee, shot fees)
106
+ est_ram_bytes: int | None = None
107
+ isolated: bool | None = None
108
+ basis: str = "" # where the time estimate comes from: probe, measured constants, assumption
109
+ run: Callable[[], Any] | None = None
110
+ meta: dict = field(default_factory=dict)
111
+
112
+ @property
113
+ def key(self) -> str:
114
+ return f"{self.engine}/{self.name}"
115
+
116
+ @property
117
+ def est_cost_usd(self) -> float | None:
118
+ if self.est_time_s is None and not self.fixed_usd:
119
+ return None
120
+ return (self.est_time_s or 0.0) / 3600 * self.rate_usd_h + self.fixed_usd
121
+
122
+ def reject(self, why: str) -> None:
123
+ self.feasible, self.reason = False, why
124
+
125
+
126
+ @dataclass
127
+ class Plan:
128
+ job: Job
129
+ objective: Objective
130
+ prices: Prices
131
+ options: list[Option] # ranked: feasible first, by the objective
132
+ chosen: Option | None
133
+
134
+ def explain(self) -> str:
135
+ f = lambda v, fmt: "-" if v is None else format(v, fmt)
136
+ rows = [f"job: {self.job.label()}",
137
+ f"objective: minimize {self.objective.minimize}"
138
+ + (f", deadline {self.objective.deadline_s:g} s" if self.objective.deadline_s else "")
139
+ + (f", RAM <= {self.objective.max_ram_bytes / 2**30:.1f} GiB" if self.objective.max_ram_bytes else "")
140
+ + (", isolated" if self.objective.require_isolation else "")
141
+ + f" (local price {self.prices.local_usd_per_hour:g} $/h)",
142
+ f"{'':3}{'option':<28}{'time_s':>10}{'cost_usd':>12}{'ram_MiB':>9} {'basis':<22}status"]
143
+ for o in self.options:
144
+ mark = ">>" if o is self.chosen else " "
145
+ status = "chosen" if o is self.chosen else ("ok" if o.feasible else f"rejected: {o.reason}")
146
+ rows.append(f"{mark} {o.key:<28}{f(o.est_time_s, '.4g'):>10}{f(o.est_cost_usd, '.3g'):>12}"
147
+ f"{f(None if o.est_ram_bytes is None else o.est_ram_bytes / 2**20, '.0f'):>9} {o.basis[:22]:<22}{status}")
148
+ return "\n".join(rows)
149
+
150
+
151
+ @dataclass
152
+ class Execution:
153
+ option: str
154
+ result: Any
155
+ wall_s: float
156
+ est_time_s: float | None
157
+ time_error_pct: float | None # (actual - estimate) / estimate
158
+ est_cost_usd: float | None
159
+ actual_cost_usd: float
160
+ calibration_samples: int
@@ -0,0 +1,99 @@
1
+ """The planner: every engine proposes options for a job; one function ranks them by the one
2
+ objective; executing a plan records estimate versus reality and corrects future estimates."""
3
+ from __future__ import annotations
4
+
5
+ import statistics
6
+ import time
7
+ from collections import defaultdict, deque
8
+
9
+ from ..core.ledger import Ledger
10
+ from ..core.model import Measurement
11
+ from .model import Execution, Job, Objective, Option, Plan, PlanError, Prices, Validated
12
+
13
+
14
+ class Planner:
15
+ def __init__(self, prices: Prices | None = None, ledger: Ledger | None = None, hub=None, providers=None):
16
+ """hub: an RpcClient to a fleet hub with fleet:read and fleet:submit (enables remote options)."""
17
+ from .providers import default_providers
18
+ self.prices = prices or Prices()
19
+ self.ledger = ledger or Ledger()
20
+ self.hub = hub
21
+ self.providers = providers if providers is not None else default_providers()
22
+ self._ratios: dict[tuple, deque] = defaultdict(lambda: deque(maxlen=8)) # actual / estimate, per option
23
+
24
+ # ---------------------------------------------------------------- calibration (the learning loop)
25
+ def calibrate(self, kind: str, opt: Option) -> Option:
26
+ """Scale the option's time estimate by the median error of its past executions (needs 2+)."""
27
+ r = self._ratios[(kind, opt.key)]
28
+ if opt.est_time_s is not None and len(r) >= 2:
29
+ opt.est_time_s *= statistics.median(r)
30
+ opt.basis += f"+calibrated({len(r)})"
31
+ return opt
32
+
33
+ # ---------------------------------------------------------------- planning
34
+ def plan(self, job: Job, objective: Objective | None = None) -> Plan:
35
+ obj = objective or Objective()
36
+ options: list[Option] = []
37
+ for p in self.providers:
38
+ if job.kind in p.kinds:
39
+ options += p.options(job, obj, self, options)
40
+ for o in options:
41
+ self._apply_constraints(o, obj)
42
+ key = (lambda o: (o.est_cost_usd if o.est_cost_usd is not None else float("inf"),
43
+ o.est_time_s if o.est_time_s is not None else float("inf"))) if obj.minimize == "cost" else \
44
+ (lambda o: (o.est_time_s if o.est_time_s is not None else float("inf"),
45
+ o.est_cost_usd if o.est_cost_usd is not None else float("inf")))
46
+ ok = sorted((o for o in options if o.feasible), key=key)
47
+ rest = [o for o in options if not o.feasible]
48
+ plan = Plan(job, obj, self.prices, ok + rest, ok[0] if ok else None)
49
+ if plan.chosen is None:
50
+ raise PlanError("no option satisfies the objective:\n" + plan.explain())
51
+ self.ledger.decide("planner", f"{job.kind}: choose {plan.chosen.key}", f"minimize {obj.minimize}",
52
+ candidates={o.key: (o.est_cost_usd, o.est_time_s) for o in ok},
53
+ rejected={o.key: o.reason for o in rest})
54
+ return plan
55
+
56
+ @staticmethod
57
+ def _apply_constraints(o: Option, obj: Objective) -> None:
58
+ if not o.feasible:
59
+ return
60
+ if obj.deadline_s is not None:
61
+ if o.est_time_s is None:
62
+ o.reject("duration unknown, cannot promise the deadline")
63
+ elif o.est_time_s > obj.deadline_s:
64
+ o.reject(f"estimated {o.est_time_s:.3g} s exceeds the {obj.deadline_s:g} s deadline")
65
+ if obj.max_ram_bytes is not None and o.est_ram_bytes is not None and o.est_ram_bytes > obj.max_ram_bytes:
66
+ o.reject(f"needs {o.est_ram_bytes / 2**20:.0f} MiB of RAM, limit {obj.max_ram_bytes / 2**20:.0f} MiB")
67
+ if obj.require_isolation and o.isolated is False:
68
+ o.reject("does not isolate the program from the host")
69
+
70
+ # ---------------------------------------------------------------- execution + proof
71
+ def execute(self, plan: Plan) -> Execution:
72
+ opt = plan.chosen
73
+ t0 = time.perf_counter()
74
+ ok, err = True, None
75
+ try:
76
+ res = opt.run()
77
+ except Exception as e:
78
+ ok, err, res = False, f"{type(e).__name__}: {e}", None
79
+ wall = time.perf_counter() - t0
80
+ est = opt.est_time_s
81
+ if isinstance(res, Validated): # reduced-scale validation: compare like with like
82
+ wall, est, res = res.wall_s, res.est_time_s, res.result
83
+ error = None if (est is None or est <= 0) else (wall - est) / est
84
+ if ok and est and est > 0:
85
+ self._ratios[(plan.job.kind, opt.key)].append(wall / est)
86
+ actual_cost = wall / 3600 * opt.rate_usd_h + opt.fixed_usd
87
+ self.ledger.record(Measurement(
88
+ "planner", plan.job.kind, opt.key, ok, wall, cost_usd=actual_cost,
89
+ metrics={"est_time_s": est, "est_cost_usd": opt.est_cost_usd, "time_error_pct": None if error is None else 100 * error,
90
+ "basis": opt.basis, "objective": plan.objective.minimize}, notes=err or ""))
91
+ if not ok:
92
+ raise RuntimeError(f"{opt.key} failed: {err}")
93
+ return Execution(opt.key, res, wall, est, None if error is None else 100 * error, opt.est_cost_usd, actual_cost,
94
+ len(self._ratios[(plan.job.kind, opt.key)]))
95
+
96
+ def run(self, job: Job, objective: Objective | None = None) -> tuple[Plan, Execution]:
97
+ """Plan, execute, record: the whole loop in one call."""
98
+ p = self.plan(job, objective)
99
+ return p, self.execute(p)