spatial-computing 0.11.0__tar.gz → 0.12.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.11.0/spatial_computing.egg-info → spatial_computing-0.12.0}/PKG-INFO +2 -2
- {spatial_computing-0.11.0 → spatial_computing-0.12.0}/README.md +1 -1
- {spatial_computing-0.11.0 → spatial_computing-0.12.0}/pyproject.toml +1 -1
- {spatial_computing-0.11.0 → spatial_computing-0.12.0}/spatial/__init__.py +1 -1
- {spatial_computing-0.11.0 → spatial_computing-0.12.0}/spatial/compute/workloads.py +26 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.0}/spatial/core/registry.py +6 -0
- spatial_computing-0.12.0/spatial/fabric/metal.py +85 -0
- spatial_computing-0.12.0/spatial/fabric/metal_run.swift +52 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.0}/spatial/fleet/hub.py +126 -14
- spatial_computing-0.12.0/spatial/interconnect/__init__.py +10 -0
- spatial_computing-0.12.0/spatial/interconnect/collectives.py +102 -0
- spatial_computing-0.12.0/spatial/interconnect/comm.py +114 -0
- spatial_computing-0.12.0/spatial/interconnect/model.py +77 -0
- spatial_computing-0.12.0/spatial/interconnect/tasks.py +72 -0
- spatial_computing-0.12.0/spatial/kernel/__init__.py +3 -0
- spatial_computing-0.12.0/spatial/kernel/dsl.py +389 -0
- spatial_computing-0.12.0/spatial/kernel/library.py +46 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.0}/spatial/unified/providers.py +5 -1
- {spatial_computing-0.11.0 → spatial_computing-0.12.0/spatial_computing.egg-info}/PKG-INFO +2 -2
- {spatial_computing-0.11.0 → spatial_computing-0.12.0}/spatial_computing.egg-info/SOURCES.txt +11 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.0}/tests/test_fabric.py +22 -12
- {spatial_computing-0.11.0 → spatial_computing-0.12.0}/tests/test_fleet.py +64 -0
- spatial_computing-0.12.0/tests/test_interconnect.py +50 -0
- spatial_computing-0.12.0/tests/test_kernel.py +96 -0
- spatial_computing-0.11.0/spatial/fabric/metal.py +0 -46
- {spatial_computing-0.11.0 → spatial_computing-0.12.0}/LICENSE +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.0}/setup.cfg +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.0}/spatial/ai/__init__.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.0}/spatial/ai/kvcache.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.0}/spatial/cli.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.0}/spatial/compute/__init__.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.0}/spatial/compute/cost.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.0}/spatial/compute/detect.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.0}/spatial/compute/monitor.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.0}/spatial/compute/scheduler.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.0}/spatial/compute/taskqueue.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.0}/spatial/compute/worker.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.0}/spatial/core/__init__.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.0}/spatial/core/auth.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.0}/spatial/core/energy.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.0}/spatial/core/ledger.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.0}/spatial/core/model.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.0}/spatial/core/protocol.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.0}/spatial/fabric/__init__.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.0}/spatial/fabric/cuda.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.0}/spatial/fabric/devices.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.0}/spatial/fabric/metal_mandel.swift +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.0}/spatial/fleet/__init__.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.0}/spatial/fleet/agent.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.0}/spatial/holographic/__init__.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.0}/spatial/holographic/cgh.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.0}/spatial/holographic/model.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.0}/spatial/intelligence/__init__.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.0}/spatial/intelligence/predictor.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.0}/spatial/memory/__init__.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.0}/spatial/memory/fararray.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.0}/spatial/memory/pageserver.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.0}/spatial/memory/secure.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.0}/spatial/memory/shared.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.0}/spatial/memory/tiered.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.0}/spatial/q/__init__.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.0}/spatial/q/__main__.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.0}/spatial/q/backends/__init__.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.0}/spatial/q/codegen.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.0}/spatial/q/compiler.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.0}/spatial/q/ir.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.0}/spatial/q/lexer.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.0}/spatial/q/parser.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.0}/spatial/q/qir.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.0}/spatial/q/runtime.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.0}/spatial/q/sim.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.0}/spatial/runtime/__init__.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.0}/spatial/runtime/envs.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.0}/spatial/runtime/inspect.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.0}/spatial/runtime/microvm.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.0}/spatial/runtime/planner.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.0}/spatial/runtime/runner.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.0}/spatial/runtime/toolchain.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.0}/spatial/scientific/__init__.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.0}/spatial/scientific/jobs.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.0}/spatial/simulation/__init__.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.0}/spatial/simulation/heat.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.0}/spatial/simulation/nbody.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.0}/spatial/unified/__init__.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.0}/spatial/unified/model.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.0}/spatial/unified/planner.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.0}/spatial_computing.egg-info/dependency_links.txt +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.0}/spatial_computing.egg-info/entry_points.txt +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.0}/spatial_computing.egg-info/requires.txt +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.0}/spatial_computing.egg-info/top_level.txt +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.0}/tests/test_auth.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.0}/tests/test_compute.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.0}/tests/test_core.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.0}/tests/test_domains.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.0}/tests/test_engines.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.0}/tests/test_memory.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.0}/tests/test_optimizer.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.0}/tests/test_q.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.0}/tests/test_runtime.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.0}/tests/test_unified.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.0}/tests/test_v02.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.0}/tests/test_v03.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.0}/tests/test_v05.py +0 -0
- {spatial_computing-0.11.0 → spatial_computing-0.12.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.12.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.
|
|
40
|
+
> **Status: v0.12.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
|
|
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
|
|
5
5
|
One objective for the whole infrastructure: get every job done correctly at the lowest cost, and prove it. Spatial Computing prices every way to run a job across compute, memory, runtime, quantum, AI, science and a fleet of machines, picks the cheapest, and records the estimate next to what really happened. A gain is claimed only when it is measured. It does not add RAM, cores or GPUs: it compares execution strategies on the hardware you have, trades one resource for another in numbers, and says plainly what it cannot do.
|
|
6
6
|
|
|
7
|
-
> **Status: v0.
|
|
7
|
+
> **Status: v0.12.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
|
|
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "spatial-computing"
|
|
7
|
-
version = "0.
|
|
7
|
+
version = "0.12.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"
|
|
@@ -142,6 +142,28 @@ def mandel_f32_cuda(n: int, iters: int) -> int:
|
|
|
142
142
|
return cuda.mandel(n, iters)
|
|
143
143
|
|
|
144
144
|
|
|
145
|
+
def _pk(name: str, device: str, n: int, **params) -> int:
|
|
146
|
+
from ..kernel.library import LIBRARY
|
|
147
|
+
return int(LIBRARY[name].run(device, n, **params).astype("uint64").sum())
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def pk_mandel_cpu(n: int, iters: int) -> int:
|
|
151
|
+
"""Portable kernel (spatial.kernel) on the CPU: the SAME source as the Metal variant."""
|
|
152
|
+
return _pk("mandelbrot", "cpu", n, iters=iters)
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def pk_mandel_metal(n: int, iters: int) -> int:
|
|
156
|
+
return _pk("mandelbrot", "metal", n, iters=iters)
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def pk_collatz_cpu(n: int, limit: int) -> int:
|
|
160
|
+
return _pk("collatz", "cpu", n, limit=limit)
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def pk_collatz_metal(n: int, limit: int) -> int:
|
|
164
|
+
return _pk("collatz", "metal", n, limit=limit)
|
|
165
|
+
|
|
166
|
+
|
|
145
167
|
def montecarlo_pi(samples: int, seed: int = 0) -> float:
|
|
146
168
|
rng = np.random.default_rng(seed)
|
|
147
169
|
inside = 0
|
|
@@ -231,6 +253,10 @@ REGISTRY = {
|
|
|
231
253
|
"mandel_f32_cpu": mandel_f32_cpu,
|
|
232
254
|
"mandel_f32_metal": mandel_f32_metal,
|
|
233
255
|
"mandel_f32_cuda": mandel_f32_cuda,
|
|
256
|
+
"pk_mandel_cpu": pk_mandel_cpu,
|
|
257
|
+
"pk_mandel_metal": pk_mandel_metal,
|
|
258
|
+
"pk_collatz_cpu": pk_collatz_cpu,
|
|
259
|
+
"pk_collatz_metal": pk_collatz_metal,
|
|
234
260
|
"heat_numpy": heat_numpy,
|
|
235
261
|
"heat_numba": heat_numba,
|
|
236
262
|
"nbody": nbody,
|
|
@@ -32,6 +32,12 @@ ENGINES: list[Engine] = [
|
|
|
32
32
|
Engine("fabric", "Virtual accelerator fabric", "spatial.fabric", Status.FIRST_COMPONENTS,
|
|
33
33
|
"tests/test_fabric.py, benchmarks/bench_unified.py (FABRIC=1: 7 of 7 device choices correct)",
|
|
34
34
|
"CPU and Metal GPU tested; the NVIDIA (numba.cuda) path is written and never run on real NVIDIA hardware; one job family; no host-device transfer model"),
|
|
35
|
+
Engine("interconnect", "Virtual interconnect (collectives)", "spatial.interconnect", Status.FIRST_COMPONENTS,
|
|
36
|
+
"tests/test_interconnect.py, benchmarks/bench_interconnect.py (uncalibrated model right 1 of 6; calibrated per algorithm 4 of 6)",
|
|
37
|
+
"N = 4 and 8 processes on one machine over loopback; no real network, RDMA or GPU memory; about 3,000x slower than NVLink 5 (vendor figure); no fault tolerance"),
|
|
38
|
+
Engine("kernel", "Portable kernels", "spatial.kernel", Status.FIRST_COMPONENTS,
|
|
39
|
+
"tests/test_kernel.py, benchmarks/bench_kernel.py (planner right 4 of 6; integer kernel bit-identical CPU vs Metal)",
|
|
40
|
+
"CUDA C generated, never compiled or run; one kernel shape (2-D per-element, no shared memory or reductions)"),
|
|
35
41
|
Engine("planner", "Spatial Planner (the one objective)", "spatial.unified", Status.OPERATIONAL_PROTOTYPE,
|
|
36
42
|
"tests/test_unified.py",
|
|
37
43
|
"estimates come from probes and measured constants on one machine; calibration is a median of past ratios; no learned model; fleet and QPU pricing need the caller's prices"),
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
"""Metal compute backend (macOS): compiles the bundled Swift program once, then runs it per job."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
import platform
|
|
6
|
+
import shutil
|
|
7
|
+
import subprocess
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
SRC = Path(__file__).with_name("metal_mandel.swift")
|
|
11
|
+
CACHE = Path.home() / ".cache" / "spatial"
|
|
12
|
+
BIN = CACHE / "metal_mandel"
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def available() -> bool:
|
|
16
|
+
return platform.system() == "Darwin" and (BIN.exists() or shutil.which("swiftc") is not None)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def ensure_binary() -> Path:
|
|
20
|
+
if BIN.exists() and BIN.stat().st_mtime >= SRC.stat().st_mtime:
|
|
21
|
+
return BIN
|
|
22
|
+
if platform.system() != "Darwin" or not shutil.which("swiftc"):
|
|
23
|
+
raise RuntimeError("Metal backend needs macOS and swiftc")
|
|
24
|
+
CACHE.mkdir(parents=True, exist_ok=True)
|
|
25
|
+
r = subprocess.run(["swiftc", "-O", str(SRC), "-o", str(BIN)], capture_output=True, text=True, timeout=600)
|
|
26
|
+
if r.returncode != 0:
|
|
27
|
+
raise RuntimeError("swiftc failed: " + r.stderr[-300:])
|
|
28
|
+
return BIN
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def mandel(n: int, iters: int, reps: int = 1) -> dict:
|
|
32
|
+
out = subprocess.run([str(ensure_binary()), str(n), str(iters), str(reps)], capture_output=True, text=True, timeout=600)
|
|
33
|
+
try:
|
|
34
|
+
d = json.loads(out.stdout.strip().splitlines()[-1])
|
|
35
|
+
except Exception:
|
|
36
|
+
raise RuntimeError("Metal program failed: " + (out.stdout + out.stderr)[-300:])
|
|
37
|
+
if not d.get("ok"):
|
|
38
|
+
raise RuntimeError(d.get("error", "Metal error"))
|
|
39
|
+
return d
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def device_name() -> str | None:
|
|
43
|
+
try:
|
|
44
|
+
return mandel(8, 8, 1)["device"]
|
|
45
|
+
except Exception:
|
|
46
|
+
return None
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
RUN_SRC = Path(__file__).with_name("metal_run.swift")
|
|
50
|
+
RUN_BIN = CACHE / "metal_run"
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _ensure_run_binary() -> Path:
|
|
54
|
+
if RUN_BIN.exists() and RUN_BIN.stat().st_mtime >= RUN_SRC.stat().st_mtime:
|
|
55
|
+
return RUN_BIN
|
|
56
|
+
if platform.system() != "Darwin" or not shutil.which("swiftc"):
|
|
57
|
+
raise RuntimeError("Metal backend needs macOS and swiftc")
|
|
58
|
+
CACHE.mkdir(parents=True, exist_ok=True)
|
|
59
|
+
r = subprocess.run(["swiftc", "-O", str(RUN_SRC), "-o", str(RUN_BIN)], capture_output=True, text=True, timeout=600)
|
|
60
|
+
if r.returncode != 0:
|
|
61
|
+
raise RuntimeError("swiftc failed: " + r.stderr[-300:])
|
|
62
|
+
return RUN_BIN
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def run_kernel(k, n: int, params: dict, reps: int = 1, timing: dict | None = None):
|
|
66
|
+
"""Run a portable Kernel (spatial.kernel) on the Metal GPU; returns the (n, n) uint32 output.
|
|
67
|
+
`timing`, if given, receives the GPU-side median seconds."""
|
|
68
|
+
import numpy as np
|
|
69
|
+
import tempfile
|
|
70
|
+
binary = _ensure_run_binary()
|
|
71
|
+
with tempfile.TemporaryDirectory() as d:
|
|
72
|
+
msl, out = Path(d) / "k.metal", Path(d) / "out.bin"
|
|
73
|
+
msl.write_text(k.to_metal())
|
|
74
|
+
args = [str(binary), str(msl), k.name, str(n), str(reps), str(out)]
|
|
75
|
+
args += [f"{t}:{float(params[p]) if t == 'float' else int(params[p])}" for p, t in k.params]
|
|
76
|
+
r = subprocess.run(args, capture_output=True, text=True, timeout=600)
|
|
77
|
+
try:
|
|
78
|
+
info = json.loads(r.stdout.strip().splitlines()[-1])
|
|
79
|
+
except Exception:
|
|
80
|
+
raise RuntimeError("Metal program failed: " + (r.stdout + r.stderr)[-300:])
|
|
81
|
+
if not info.get("ok"):
|
|
82
|
+
raise RuntimeError(info.get("error", "Metal error"))
|
|
83
|
+
if timing is not None:
|
|
84
|
+
timing.update(info)
|
|
85
|
+
return np.fromfile(out, dtype=np.uint32).reshape(n, n)
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
// Generic Metal host for portable kernels generated by spatial.kernel.
|
|
2
|
+
// usage: metal_run <msl_file> <kernel_name> <n> <reps> <out_file> [int:<v> | float:<v> ...]
|
|
3
|
+
// Buffers: 0 = output uint[n*n], 1 = n (int), 2.. = parameters in order. Writes raw uint32 to <out_file>.
|
|
4
|
+
import Foundation
|
|
5
|
+
import Metal
|
|
6
|
+
|
|
7
|
+
func now() -> Double { return Double(DispatchTime.now().uptimeNanoseconds) / 1e9 }
|
|
8
|
+
func fail(_ m: String) -> Never { print("{\"ok\": false, \"error\": \"\(m)\"}"); exit(1) }
|
|
9
|
+
|
|
10
|
+
let a = CommandLine.arguments
|
|
11
|
+
if a.count < 6 { fail("usage") }
|
|
12
|
+
guard let src = try? String(contentsOfFile: a[1], encoding: .utf8) else { fail("cannot read msl") }
|
|
13
|
+
let name = a[2], n = Int(a[3])!, reps = max(1, Int(a[4])!), outPath = a[5]
|
|
14
|
+
guard let dev = MTLCreateSystemDefaultDevice() ?? MTLCopyAllDevices().first else { fail("no Metal device") }
|
|
15
|
+
let t0 = now()
|
|
16
|
+
let lib: MTLLibrary
|
|
17
|
+
do { lib = try dev.makeLibrary(source: src, options: nil) } catch {
|
|
18
|
+
let msg = "\(error)".replacingOccurrences(of: "\"", with: "'").replacingOccurrences(of: "\n", with: " ")
|
|
19
|
+
fail("shader compile failed: " + String(msg.prefix(300)))
|
|
20
|
+
}
|
|
21
|
+
guard let fn = lib.makeFunction(name: name) else { fail("kernel not found") }
|
|
22
|
+
let pipe = try! dev.makeComputePipelineState(function: fn)
|
|
23
|
+
let setupS = now() - t0
|
|
24
|
+
let out = dev.makeBuffer(length: n * n * 4, options: .storageModeShared)!
|
|
25
|
+
let queue = dev.makeCommandQueue()!
|
|
26
|
+
var nn = Int32(n)
|
|
27
|
+
|
|
28
|
+
func run() -> Double {
|
|
29
|
+
let t = now()
|
|
30
|
+
let cb = queue.makeCommandBuffer()!
|
|
31
|
+
let enc = cb.makeComputeCommandEncoder()!
|
|
32
|
+
enc.setComputePipelineState(pipe)
|
|
33
|
+
enc.setBuffer(out, offset: 0, index: 0)
|
|
34
|
+
enc.setBytes(&nn, length: 4, index: 1)
|
|
35
|
+
for (k, spec) in a[6...].enumerated() {
|
|
36
|
+
let parts = spec.split(separator: ":", maxSplits: 1).map(String.init)
|
|
37
|
+
if parts[0] == "int" { var v = Int32(parts[1])!; enc.setBytes(&v, length: 4, index: 2 + k) }
|
|
38
|
+
else { var v = Float(parts[1])!; enc.setBytes(&v, length: 4, index: 2 + k) }
|
|
39
|
+
}
|
|
40
|
+
let w = pipe.threadExecutionWidth
|
|
41
|
+
let h = pipe.maxTotalThreadsPerThreadgroup / w
|
|
42
|
+
enc.dispatchThreadgroups(MTLSize(width: (n + w - 1) / w, height: (n + h - 1) / h, depth: 1),
|
|
43
|
+
threadsPerThreadgroup: MTLSize(width: w, height: h, depth: 1))
|
|
44
|
+
enc.endEncoding(); cb.commit(); cb.waitUntilCompleted()
|
|
45
|
+
return now() - t
|
|
46
|
+
}
|
|
47
|
+
var times: [Double] = []
|
|
48
|
+
for _ in 0..<reps { times.append(run()) }
|
|
49
|
+
let data = Data(bytes: out.contents(), count: n * n * 4)
|
|
50
|
+
do { try data.write(to: URL(fileURLWithPath: outPath)) } catch { fail("cannot write output") }
|
|
51
|
+
times.sort()
|
|
52
|
+
print("{\"ok\": true, \"device\": \"\(dev.name)\", \"gpu_s_median\": \(times[times.count / 2]), \"setup_s\": \(setupS)}")
|
|
@@ -29,7 +29,7 @@ HISTORY = 2000 # samples kept per node
|
|
|
29
29
|
|
|
30
30
|
class Hub:
|
|
31
31
|
def __init__(self, ledger: Ledger | None = None, stale_after_s: float = 30.0, clock=time.time,
|
|
32
|
-
busy_cpu_pct: float = 90.0):
|
|
32
|
+
busy_cpu_pct: float = 90.0, gang_hold_s: float = 30.0, affinity_wait_s: float = 5.0):
|
|
33
33
|
self.nodes: dict[str, dict] = {}
|
|
34
34
|
self.series: dict[str, deque] = {}
|
|
35
35
|
self.tasks: dict[int, dict] = {}
|
|
@@ -40,6 +40,12 @@ class Hub:
|
|
|
40
40
|
self.busy_cpu_pct = busy_cpu_pct
|
|
41
41
|
self._ids = itertools.count(1)
|
|
42
42
|
self._lock = threading.RLock()
|
|
43
|
+
self.gang_hold_s = gang_hold_s # how long idle nodes are held for a gang that has started
|
|
44
|
+
self.affinity_wait_s = affinity_wait_s # how long a task waits for the node that holds its cache
|
|
45
|
+
self.weights: dict[str, float] = {} # tenant -> share weight (default 1)
|
|
46
|
+
self.usage: dict[str, float] = {} # tenant -> finished compute-seconds
|
|
47
|
+
self.gangs: dict[int, dict] = {}
|
|
48
|
+
self.affinity: dict[str, str] = {} # cache key -> node that last ran it
|
|
43
49
|
|
|
44
50
|
# ------------------------------------------------------------------ identity
|
|
45
51
|
@staticmethod
|
|
@@ -69,16 +75,51 @@ class Hub:
|
|
|
69
75
|
n["latest"] = {**m, "ts": ts}
|
|
70
76
|
self.series.setdefault(node, deque(maxlen=HISTORY)).append((ts, m))
|
|
71
77
|
|
|
72
|
-
def submit(self, workload: str, params: dict, needs: dict | None = None, priority: int = 10
|
|
78
|
+
def submit(self, workload: str, params: dict, needs: dict | None = None, priority: int = 10,
|
|
79
|
+
tenant: str = "default", _gang: int | None = None) -> int:
|
|
73
80
|
if workload not in workloads.REGISTRY:
|
|
74
81
|
raise KeyError(f"workload '{workload}' is not allow-listed")
|
|
75
82
|
with self._lock:
|
|
76
83
|
tid = next(self._ids)
|
|
77
84
|
self.tasks[tid] = {"id": tid, "workload": workload, "params": params, "needs": needs or {},
|
|
78
|
-
"priority": int(priority), "state": "queued", "submitted": self.clock()
|
|
85
|
+
"priority": int(priority), "state": "queued", "submitted": self.clock(),
|
|
86
|
+
"tenant": str(tenant), "gang": _gang}
|
|
79
87
|
self.queue.append(tid)
|
|
80
88
|
return tid
|
|
81
89
|
|
|
90
|
+
def submit_gang(self, workload: str, params_list: list[dict], needs: dict | None = None, priority: int = 10,
|
|
91
|
+
tenant: str = "default") -> dict:
|
|
92
|
+
"""All-or-nothing group: the members start only when enough eligible idle nodes exist for ALL of
|
|
93
|
+
them; the first start holds the other nodes for `gang_hold_s`. Admission and reservation, not
|
|
94
|
+
preemption: a member that already runs is never stopped."""
|
|
95
|
+
if not params_list:
|
|
96
|
+
raise ValueError("a gang needs at least one member")
|
|
97
|
+
with self._lock:
|
|
98
|
+
gid = next(self._ids)
|
|
99
|
+
tids = [self.submit(workload, p, {**(needs or {}), "distinct_nodes": True}, priority, tenant, _gang=gid) for p in params_list]
|
|
100
|
+
self.gangs[gid] = {"id": gid, "size": len(tids), "tasks": tids, "reserved": {}, "started": [], "tenant": str(tenant)}
|
|
101
|
+
return {"gang": gid, "tasks": tids}
|
|
102
|
+
|
|
103
|
+
def set_weight(self, tenant: str, weight: float) -> None:
|
|
104
|
+
if not weight > 0:
|
|
105
|
+
raise ValueError("weight must be positive")
|
|
106
|
+
with self._lock:
|
|
107
|
+
self.weights[str(tenant)] = float(weight)
|
|
108
|
+
|
|
109
|
+
def _tenant_load(self, tenant: str, now: float) -> float:
|
|
110
|
+
"""Weighted compute-seconds consumed so far (finished plus running): lowest goes first."""
|
|
111
|
+
running = sum(now - t.get("started", now) for t in self.tasks.values() if t["state"] == "running" and t["tenant"] == tenant)
|
|
112
|
+
return (self.usage.get(tenant, 0.0) + running) / self.weights.get(tenant, 1.0)
|
|
113
|
+
|
|
114
|
+
def tenants(self) -> list[dict]:
|
|
115
|
+
with self._lock:
|
|
116
|
+
now = self.clock()
|
|
117
|
+
names = sorted({t["tenant"] for t in self.tasks.values()} | set(self.weights))
|
|
118
|
+
return [{"tenant": n, "weight": self.weights.get(n, 1.0), "finished_s": self.usage.get(n, 0.0),
|
|
119
|
+
"weighted_load": self._tenant_load(n, now),
|
|
120
|
+
"queued": sum(1 for t in self.tasks.values() if t["tenant"] == n and t["state"] == "queued"),
|
|
121
|
+
"running": sum(1 for t in self.tasks.values() if t["tenant"] == n and t["state"] == "running")} for n in names]
|
|
122
|
+
|
|
82
123
|
def _eligible(self, node: str, needs: dict) -> bool:
|
|
83
124
|
n = self.nodes.get(node)
|
|
84
125
|
if not n or "latest" not in n:
|
|
@@ -94,28 +135,83 @@ class Hub:
|
|
|
94
135
|
return False
|
|
95
136
|
return True
|
|
96
137
|
|
|
138
|
+
def _ready(self, node: str, now: float) -> bool:
|
|
139
|
+
"""Fresh, not saturated, not running a task."""
|
|
140
|
+
n = self.nodes.get(node)
|
|
141
|
+
if not n or "latest" not in n or now - n.get("last_seen", 0) > self.stale_after_s:
|
|
142
|
+
return False
|
|
143
|
+
if (n["latest"].get("cpu_percent") or 0) >= self.busy_cpu_pct:
|
|
144
|
+
return False
|
|
145
|
+
return not any(t["state"] == "running" and t.get("node") == node for t in self.tasks.values())
|
|
146
|
+
|
|
147
|
+
def _gang_nodes(self, g: dict, needs: dict, now: float, exclude: str) -> list[str]:
|
|
148
|
+
"""Other ready, eligible nodes not held by a different gang."""
|
|
149
|
+
held = {nd for og in self.gangs.values() if og["id"] != g["id"] for nd, exp in og["reserved"].items() if exp > now}
|
|
150
|
+
return sorted(nd for nd in self.nodes if nd != exclude and nd not in held and nd not in g["started"]
|
|
151
|
+
and self._ready(nd, now) and self._eligible(nd, needs))
|
|
152
|
+
|
|
97
153
|
def poll(self, node: str) -> dict | None:
|
|
98
|
-
"""Hand the best eligible queued task to an agent that asks for work. Backpressure: a node
|
|
99
|
-
|
|
154
|
+
"""Hand the best eligible queued task to an agent that asks for work. Backpressure: a node that
|
|
155
|
+
reports itself saturated gets nothing. Order: tenant with the lowest weighted usage first (fair
|
|
156
|
+
share), then priority, then submission order. Gang members start only when the whole gang can;
|
|
157
|
+
a task with a cache-affinity key waits `affinity_wait_s` for the node that holds that cache."""
|
|
100
158
|
with self._lock:
|
|
101
159
|
n = self.nodes.get(node)
|
|
102
160
|
if not n or "latest" not in n:
|
|
103
161
|
return None
|
|
104
162
|
if (n["latest"].get("cpu_percent") or 0) >= self.busy_cpu_pct:
|
|
105
163
|
return None
|
|
164
|
+
now = self.clock()
|
|
165
|
+
for g in self.gangs.values():
|
|
166
|
+
g["reserved"] = {nd: exp for nd, exp in g["reserved"].items() if exp > now}
|
|
167
|
+
for g in self.gangs.values(): # a node held for a gang serves only that gang
|
|
168
|
+
if node in g["reserved"]:
|
|
169
|
+
mine = [self.tasks[t] for t in g["tasks"] if self.tasks[t]["state"] == "queued" and self._eligible(node, self.tasks[t]["needs"])]
|
|
170
|
+
if not mine:
|
|
171
|
+
return None
|
|
172
|
+
return self._assign(min(mine, key=lambda t: t["id"]), node, now, g, "held for its gang")
|
|
173
|
+
held_elsewhere = {nd for g in self.gangs.values() for nd, exp in g["reserved"].items() if exp > now}
|
|
174
|
+
if node in held_elsewhere:
|
|
175
|
+
return None
|
|
176
|
+
load = {}
|
|
106
177
|
best = None
|
|
107
178
|
for tid in self.queue:
|
|
108
179
|
t = self.tasks[tid]
|
|
109
|
-
if self._eligible(node, t["needs"])
|
|
110
|
-
|
|
180
|
+
if not self._eligible(node, t["needs"]):
|
|
181
|
+
continue
|
|
182
|
+
key = t["needs"].get("affinity")
|
|
183
|
+
owner = self.affinity.get(key) if key else None
|
|
184
|
+
if owner and owner != node and now - t["submitted"] < self.affinity_wait_s and self._ready(owner, now):
|
|
185
|
+
continue # the node holding its cache is free: wait for it
|
|
186
|
+
g = self.gangs.get(t["gang"]) if t["gang"] else None
|
|
187
|
+
if g is not None:
|
|
188
|
+
missing = sum(1 for x in g["tasks"] if self.tasks[x]["state"] == "queued")
|
|
189
|
+
if len(self._gang_nodes(g, t["needs"], now, node)) + 1 < missing:
|
|
190
|
+
continue # not enough idle nodes for the whole gang yet
|
|
191
|
+
tn = t["tenant"]
|
|
192
|
+
if tn not in load:
|
|
193
|
+
load[tn] = self._tenant_load(tn, now)
|
|
194
|
+
rank = (load[tn], 0 if owner == node else 1, t["priority"], tid)
|
|
195
|
+
if best is None or rank < best[0]:
|
|
196
|
+
best = (rank, t, g)
|
|
111
197
|
if best is None:
|
|
112
198
|
return None
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
199
|
+
_, t, g = best
|
|
200
|
+
if g is not None and not g["started"]:
|
|
201
|
+
for nd in self._gang_nodes(g, t["needs"], now, node)[: g["size"] - 1]:
|
|
202
|
+
g["reserved"][nd] = now + self.gang_hold_s
|
|
203
|
+
return self._assign(t, node, now, g, "agent asked for work and is eligible")
|
|
204
|
+
|
|
205
|
+
def _assign(self, t: dict, node: str, now: float, g: dict | None, why: str) -> dict:
|
|
206
|
+
self.queue.remove(t["id"])
|
|
207
|
+
t.update(state="running", node=node, started=now)
|
|
208
|
+
if g is not None:
|
|
209
|
+
g["started"].append(node)
|
|
210
|
+
g["reserved"].pop(node, None)
|
|
211
|
+
if self.ledger:
|
|
212
|
+
self.ledger.decide("fleet", f"task {t['id']} -> {node}", why, workload=t["workload"], tenant=t["tenant"],
|
|
213
|
+
gang=t["gang"], node_cpu=(self.nodes[node]["latest"] or {}).get("cpu_percent"))
|
|
214
|
+
return {"id": t["id"], "workload": t["workload"], "params": t["params"]}
|
|
119
215
|
|
|
120
216
|
def result(self, node: str, task_id: int, ok: bool, value=None, error: str | None = None, wall_s: float | None = None):
|
|
121
217
|
with self._lock:
|
|
@@ -123,6 +219,9 @@ class Hub:
|
|
|
123
219
|
if t is None or t.get("node") != node:
|
|
124
220
|
raise PermissionError("task is not assigned to this node")
|
|
125
221
|
t.update(state="done" if ok else "failed", finished=self.clock(), result=value, error=error, wall_s=wall_s)
|
|
222
|
+
self.usage[t["tenant"]] = self.usage.get(t["tenant"], 0.0) + (wall_s if wall_s is not None else self.clock() - t.get("started", self.clock()))
|
|
223
|
+
if ok and t["needs"].get("affinity"):
|
|
224
|
+
self.affinity[t["needs"]["affinity"]] = node
|
|
126
225
|
|
|
127
226
|
def task(self, task_id: int) -> dict:
|
|
128
227
|
with self._lock:
|
|
@@ -218,6 +317,13 @@ def _avg(xs):
|
|
|
218
317
|
|
|
219
318
|
|
|
220
319
|
# ---------------------------------------------------------------------- service
|
|
320
|
+
def _tenant(h: dict) -> str:
|
|
321
|
+
"""With scoped credentials the tenant is the credential name (it cannot be spoofed); otherwise the declared one."""
|
|
322
|
+
p = auth.current()
|
|
323
|
+
t = p.name if p is not None else h.get("tenant", "default")
|
|
324
|
+
return str(t)[:128]
|
|
325
|
+
|
|
326
|
+
|
|
221
327
|
def make_handler(hub: Hub):
|
|
222
328
|
def handle(h: dict, blob: bytes):
|
|
223
329
|
op = h.get("op")
|
|
@@ -236,7 +342,13 @@ def make_handler(hub: Hub):
|
|
|
236
342
|
return {}, b""
|
|
237
343
|
if op == "submit":
|
|
238
344
|
require("fleet:submit")
|
|
239
|
-
return {"task_id": hub.submit(h["workload"], h.get("params", {}), h.get("needs"), h.get("priority", 10))}, b""
|
|
345
|
+
return {"task_id": hub.submit(h["workload"], h.get("params", {}), h.get("needs"), h.get("priority", 10), _tenant(h))}, b""
|
|
346
|
+
if op == "submit_gang":
|
|
347
|
+
require("fleet:submit")
|
|
348
|
+
return hub.submit_gang(h["workload"], h["params_list"], h.get("needs"), h.get("priority", 10), _tenant(h)), b""
|
|
349
|
+
if op == "tenants":
|
|
350
|
+
require("fleet:read")
|
|
351
|
+
return {"tenants": hub.tenants()}, b""
|
|
240
352
|
if op == "task":
|
|
241
353
|
require("fleet:submit")
|
|
242
354
|
return {"task": hub.task(int(h["task_id"]))}, b""
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
"""Virtual interconnect: collective communication between ranks (devices, processes, machines)
|
|
2
|
+
over the encrypted SWP/2 transport, with an alpha-beta cost model that picks the algorithm.
|
|
3
|
+
|
|
4
|
+
This is NOT NVLink: it is a software layer over commodity links (loopback, Ethernet), thousands of
|
|
5
|
+
times slower in bandwidth. Its value is abstraction (the same collective over any set of devices,
|
|
6
|
+
across vendors and machines) and the measured choice of algorithm. See docs/INTERCONNECT.md.
|
|
7
|
+
"""
|
|
8
|
+
from .comm import Comm, launch # noqa: F401
|
|
9
|
+
from .collectives import allreduce, broadcast, ALGOS # noqa: F401
|
|
10
|
+
from .model import choose, fit_link, predict # noqa: F401
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
"""Collectives built on Comm.send/recv: all-reduce (sum) three ways, and broadcast."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import math
|
|
5
|
+
|
|
6
|
+
import numpy as np
|
|
7
|
+
|
|
8
|
+
from .model import choose, is_pow2
|
|
9
|
+
|
|
10
|
+
ALGOS = ("ring", "halving_doubling", "tree")
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _bounds(total: int, parts: int) -> list[tuple[int, int]]:
|
|
14
|
+
edges = np.linspace(0, total, parts + 1).astype(int)
|
|
15
|
+
return [(int(edges[i]), int(edges[i + 1])) for i in range(parts)]
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def ring_allreduce(comm, x: np.ndarray, tag) -> np.ndarray:
|
|
19
|
+
n, r = comm.size, comm.rank
|
|
20
|
+
buf = x.astype(np.float32, copy=True)
|
|
21
|
+
ch = _bounds(len(buf), n)
|
|
22
|
+
nxt, prv = (r + 1) % n, (r - 1) % n
|
|
23
|
+
for s in range(n - 1): # reduce-scatter
|
|
24
|
+
a, b = ch[(r - s) % n]
|
|
25
|
+
comm.send(nxt, (tag, "rs", s), buf[a:b])
|
|
26
|
+
a, b = ch[(r - s - 1) % n]
|
|
27
|
+
buf[a:b] += comm.recv(prv, (tag, "rs", s))
|
|
28
|
+
for s in range(n - 1): # all-gather
|
|
29
|
+
a, b = ch[(r + 1 - s) % n]
|
|
30
|
+
comm.send(nxt, (tag, "ag", s), buf[a:b])
|
|
31
|
+
a, b = ch[(r - s) % n]
|
|
32
|
+
buf[a:b] = comm.recv(prv, (tag, "ag", s))
|
|
33
|
+
return buf
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def halving_doubling_allreduce(comm, x: np.ndarray, tag) -> np.ndarray:
|
|
37
|
+
n, r = comm.size, comm.rank
|
|
38
|
+
if not is_pow2(n):
|
|
39
|
+
raise ValueError("halving_doubling needs a power-of-two number of ranks")
|
|
40
|
+
buf = x.astype(np.float32, copy=True)
|
|
41
|
+
lo, hi = 0, len(buf)
|
|
42
|
+
steps = [] # (keep, send) bounds per halving step
|
|
43
|
+
d = n // 2
|
|
44
|
+
while d >= 1: # recursive halving (reduce-scatter)
|
|
45
|
+
mid = lo + (hi - lo) // 2
|
|
46
|
+
keep, send = ((lo, mid), (mid, hi)) if r & d == 0 else ((mid, hi), (lo, mid))
|
|
47
|
+
partner = r ^ d
|
|
48
|
+
comm.send(partner, (tag, "h", d), buf[send[0]:send[1]])
|
|
49
|
+
buf[keep[0]:keep[1]] += comm.recv(partner, (tag, "h", d))
|
|
50
|
+
steps.append((keep, send, d))
|
|
51
|
+
lo, hi = keep
|
|
52
|
+
d //= 2
|
|
53
|
+
for keep, send, d in reversed(steps): # recursive doubling (all-gather)
|
|
54
|
+
partner = r ^ d
|
|
55
|
+
comm.send(partner, (tag, "g", d), buf[keep[0]:keep[1]])
|
|
56
|
+
buf[send[0]:send[1]] = comm.recv(partner, (tag, "g", d))
|
|
57
|
+
return buf
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def tree_allreduce(comm, x: np.ndarray, tag) -> np.ndarray:
|
|
61
|
+
n, r = comm.size, comm.rank
|
|
62
|
+
buf = x.astype(np.float32, copy=True)
|
|
63
|
+
d = 1
|
|
64
|
+
while d < n: # binomial reduce to rank 0
|
|
65
|
+
if r % (2 * d) == 0:
|
|
66
|
+
if r + d < n:
|
|
67
|
+
buf += comm.recv(r + d, (tag, "r", d))
|
|
68
|
+
elif r % (2 * d) == d:
|
|
69
|
+
comm.send(r - d, (tag, "r", d), buf)
|
|
70
|
+
break
|
|
71
|
+
d *= 2
|
|
72
|
+
return broadcast(comm, buf, 0, (tag, "b"))
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def broadcast(comm, x: np.ndarray, root: int, tag) -> np.ndarray:
|
|
76
|
+
"""Binomial-tree broadcast from `root`."""
|
|
77
|
+
n = comm.size
|
|
78
|
+
rel = (comm.rank - root) % n
|
|
79
|
+
buf = x.astype(np.float32, copy=True)
|
|
80
|
+
top = 1 << (math.ceil(math.log2(n)) - 1) if n > 1 else 0
|
|
81
|
+
d = top
|
|
82
|
+
have = rel == 0
|
|
83
|
+
while d >= 1:
|
|
84
|
+
if have and rel % (2 * d) == 0 and rel + d < n:
|
|
85
|
+
comm.send((rel + d + root) % n, (tag, d), buf)
|
|
86
|
+
elif not have and rel % (2 * d) == d:
|
|
87
|
+
buf = comm.recv((rel - d + root) % n, (tag, d))
|
|
88
|
+
have = True
|
|
89
|
+
d //= 2
|
|
90
|
+
return buf
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def allreduce(comm, x: np.ndarray, algo: str = "auto", tag="ar", alpha: float | None = None, beta: float | None = None) -> np.ndarray:
|
|
94
|
+
"""Sum of x over all ranks, on every rank. algo = ring | halving_doubling | tree | auto
|
|
95
|
+
(auto uses the alpha-beta model; pass measured alpha/beta, e.g. from tasks.measure_link)."""
|
|
96
|
+
if comm.size == 1:
|
|
97
|
+
return x.astype(np.float32, copy=True)
|
|
98
|
+
if algo == "auto":
|
|
99
|
+
if alpha is None or beta is None:
|
|
100
|
+
raise ValueError("auto needs alpha and beta (measure them with tasks.measure_link)")
|
|
101
|
+
algo, _ = choose(comm.size, x.nbytes, alpha, beta)
|
|
102
|
+
return {"ring": ring_allreduce, "halving_doubling": halving_doubling_allreduce, "tree": tree_allreduce}[algo](comm, x, tag)
|