layerpool 0.1.0__py3-none-any.whl

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.
layerpool/codec.py ADDED
@@ -0,0 +1,195 @@
1
+ import io
2
+ import json
3
+ import os
4
+ import time
5
+
6
+ import numpy as np
7
+
8
+
9
+ def encode(x: np.ndarray, mode: str = "int8", outliers: int = 8) -> dict[str, np.ndarray]:
10
+ x = np.asarray(x, dtype=np.float32)
11
+ if mode == "fp32" or x.ndim == 0 or x.size == 0:
12
+ return {"x": x}
13
+ if mode == "fp16":
14
+ if not np.isfinite(x).all():
15
+ return {"x": x}
16
+ scale = np.abs(x).max(axis=-1, keepdims=True).astype(np.float32) + 1e-30
17
+ return {"h": (x / scale).astype(np.float16), "s": scale}
18
+ if mode != "int8":
19
+ raise ValueError(f"unknown mode {mode}")
20
+ out = {}
21
+ rest = x
22
+ if outliers > 0 and x.shape[-1] > outliers:
23
+ top = np.argsort(np.abs(x).reshape(-1, x.shape[-1]).max(axis=0))[-outliers:].astype(np.int32)
24
+ rest = x.copy()
25
+ rest[..., top] = 0
26
+ out["oi"] = top
27
+ out["ov"] = x[..., top]
28
+ scale = np.abs(rest).max(axis=-1, keepdims=True).astype(np.float32) + 1e-30
29
+ out["q"] = np.round(rest / scale * 127).astype(np.int8)
30
+ out["s"] = scale
31
+ return out
32
+
33
+
34
+ def decode(parts: dict[str, np.ndarray]) -> np.ndarray:
35
+ if "x" in parts:
36
+ return parts["x"].astype(np.float32)
37
+ if "h" in parts:
38
+ return parts["h"].astype(np.float32) * parts["s"]
39
+ x = parts["q"].astype(np.float32) * parts["s"] / 127.0
40
+ if "oi" in parts:
41
+ x[..., parts["oi"]] = parts["ov"].astype(np.float32)
42
+ return x
43
+
44
+
45
+ def pack(meta: dict | None = None, **tensors) -> bytes:
46
+ buf = io.BytesIO()
47
+ arrays = {k: np.asarray(v) for k, v in tensors.items()}
48
+ if meta:
49
+ arrays["__meta__"] = np.frombuffer(json.dumps(meta, default=float).encode(), dtype=np.uint8)
50
+ np.savez(buf, **arrays)
51
+ return buf.getvalue()
52
+
53
+
54
+ def unpack(data: bytes) -> tuple[dict, dict[str, np.ndarray]]:
55
+ with np.load(io.BytesIO(data), allow_pickle=False) as z:
56
+ items = {k: z[k] for k in z.files}
57
+ meta = json.loads(items.pop("__meta__").tobytes().decode()) if "__meta__" in items else {}
58
+ return meta, items
59
+
60
+
61
+ def split_prefix(arrays: dict[str, np.ndarray], prefix: str) -> dict[str, np.ndarray]:
62
+ return {k[len(prefix):]: v for k, v in arrays.items() if k.startswith(prefix)}
63
+
64
+
65
+ def with_prefix(arrays: dict[str, np.ndarray], prefix: str) -> dict[str, np.ndarray]:
66
+ return {prefix + k: v for k, v in arrays.items()}
67
+
68
+
69
+ def to_half(arrays: dict, dtype: str) -> tuple[dict, dict]:
70
+ """float32 arrays as 16-bit values for sending: float16, or bfloat16 kept as its bits in uint16 (rounded to nearest even)."""
71
+ out, kinds = {}, {}
72
+ for k, v in arrays.items():
73
+ v = np.asarray(v)
74
+ if v.dtype != np.float32:
75
+ out[k] = v
76
+ continue
77
+ if dtype == "float16":
78
+ out[k], kinds[k] = v.astype(np.float16), "f16"
79
+ else:
80
+ bits = np.ascontiguousarray(v).view(np.uint32).astype(np.uint64)
81
+ rounded = ((bits + 0x7FFF + ((bits >> 16) & 1)) >> 16).astype(np.uint16)
82
+ out[k], kinds[k] = np.where(np.isnan(v), np.uint16(0x7FC0), rounded), "bf16"
83
+ return {"half": kinds}, out
84
+
85
+
86
+ def from_half(meta: dict | None, arrays: dict) -> dict:
87
+ """The float32 arrays back from to_half."""
88
+ kinds = (meta or {}).get("half") or {}
89
+ out = dict(arrays)
90
+ for k, kind in kinds.items():
91
+ v = arrays[k]
92
+ out[k] = v.astype(np.float32) if kind == "f16" else (v.astype(np.uint32) << 16).view(np.float32)
93
+ return out
94
+
95
+
96
+ def replace_file(src: str, dst: str, tries: int = 20):
97
+ """os.replace, retried for a moment: on Windows an antivirus scan or another process reading the file can block it briefly."""
98
+ for attempt in range(tries):
99
+ try:
100
+ os.replace(src, dst)
101
+ return
102
+ except PermissionError:
103
+ if attempt == tries - 1:
104
+ raise
105
+ time.sleep(0.1 * (attempt + 1))
106
+
107
+
108
+ class DiskStore:
109
+ """A dict of byte blobs kept in files in its own folder instead of in memory: checkpoints of a device's layers (and of a
110
+ neighbour's) can be gigabytes in full fine-tuning."""
111
+
112
+ def __init__(self, folder: str):
113
+ os.makedirs(folder, exist_ok=True)
114
+ self.folder = folder
115
+ self.keys_: dict = {}
116
+
117
+ def _path(self, key) -> str:
118
+ return os.path.join(self.folder, "_".join(str(k) for k in key) + ".bin")
119
+
120
+ def __setitem__(self, key, data: bytes):
121
+ path = self._path(key)
122
+ with open(path + ".part", "wb") as f:
123
+ f.write(data)
124
+ replace_file(path + ".part", path)
125
+ self.keys_[key] = len(data)
126
+
127
+ def __getitem__(self, key) -> bytes:
128
+ if key not in self.keys_:
129
+ raise KeyError(key)
130
+ with open(self._path(key), "rb") as f:
131
+ return f.read()
132
+
133
+ def get(self, key, default=None):
134
+ return self[key] if key in self.keys_ else default
135
+
136
+ def __contains__(self, key) -> bool:
137
+ return key in self.keys_
138
+
139
+ def __delitem__(self, key):
140
+ self.keys_.pop(key)
141
+ try:
142
+ os.remove(self._path(key))
143
+ except FileNotFoundError:
144
+ pass
145
+
146
+ def __iter__(self):
147
+ return iter(list(self.keys_))
148
+
149
+ def __len__(self) -> int:
150
+ return len(self.keys_)
151
+
152
+ def clear(self):
153
+ for key in list(self.keys_):
154
+ del self[key]
155
+
156
+ def close(self):
157
+ import shutil
158
+ self.keys_.clear()
159
+ shutil.rmtree(self.folder, ignore_errors=True)
160
+
161
+
162
+ class Spilled:
163
+ """Byte blobs written once to a file and read back on demand (the inputs and loss gradients of a step the pool may have to
164
+ replay), so the replay log does not hold them in memory."""
165
+
166
+ def __init__(self, path: str, blobs):
167
+ self.path, self.sizes = path, []
168
+ with open(path, "wb") as f:
169
+ for blob in blobs:
170
+ f.write(blob)
171
+ self.sizes.append(len(blob))
172
+
173
+ def __len__(self) -> int:
174
+ return len(self.sizes)
175
+
176
+ def __getitem__(self, i: int) -> bytes:
177
+ i = range(len(self.sizes))[i]
178
+ with open(self.path, "rb") as f:
179
+ f.seek(sum(self.sizes[:i]))
180
+ return f.read(self.sizes[i])
181
+
182
+ def __iter__(self):
183
+ with open(self.path, "rb") as f:
184
+ for size in self.sizes:
185
+ yield f.read(size)
186
+
187
+ @property
188
+ def nbytes(self) -> int:
189
+ return sum(self.sizes)
190
+
191
+ def drop(self):
192
+ try:
193
+ os.remove(self.path)
194
+ except FileNotFoundError:
195
+ pass
layerpool/control.py ADDED
@@ -0,0 +1,447 @@
1
+ import hmac
2
+ import json
3
+ import os
4
+ import queue
5
+ import secrets
6
+ import threading
7
+ import time
8
+ import urllib.request
9
+
10
+ import numpy as np
11
+
12
+ from .codec import pack, replace_file, unpack
13
+ from .net import PeerServer
14
+ from .pool import PoolError
15
+
16
+ UI_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "ui")
17
+ STATE_FILE = os.path.join(os.path.expanduser("~"), ".layerpool", "pool.json")
18
+ TYPES = {".html": "text/html; charset=utf-8", ".js": "text/javascript; charset=utf-8", ".css": "text/css; charset=utf-8", ".svg": "image/svg+xml"}
19
+ PAGE_HEADERS = {"Content-Security-Policy": "default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; script-src 'self'; "
20
+ "connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'none'",
21
+ "X-Content-Type-Options": "nosniff", "Referrer-Policy": "no-referrer"}
22
+ LOGIN_TTL_S = 300
23
+
24
+
25
+ def _arrays(prefix: str, arrays: dict) -> list:
26
+ out, i = [], 0
27
+ while f"{prefix}{i}" in arrays:
28
+ out.append(arrays[f"{prefix}{i}"])
29
+ i += 1
30
+ return out
31
+
32
+
33
+ def _blobs(prefix: str, arrays: dict) -> list[bytes]:
34
+ return [a.tobytes() for a in _arrays(prefix, arrays)]
35
+
36
+
37
+ def _as_arrays(prefix: str, blobs) -> dict:
38
+ return {f"{prefix}{i}": np.frombuffer(b, np.uint8) for i, b in enumerate(blobs or [])}
39
+
40
+
41
+ class EventStream:
42
+ content_type = "text/event-stream"
43
+
44
+ def __init__(self, pool):
45
+ self.pool = pool
46
+ self.q: queue.Queue = queue.Queue(maxsize=1000)
47
+ self.listener = lambda kind, data: self._put(kind, data)
48
+ pool.listeners.append(self.listener)
49
+
50
+ def _put(self, kind, data):
51
+ try:
52
+ self.q.put_nowait((kind, data))
53
+ except queue.Full:
54
+ pass
55
+
56
+ def __iter__(self):
57
+ yield b"retry: 2000\n\n"
58
+ while not self.pool.closed:
59
+ try:
60
+ kind, data = self.q.get(timeout=10)
61
+ yield f"event: {kind}\ndata: {json.dumps(data, default=str)}\n\n".encode()
62
+ except queue.Empty:
63
+ yield b": keep-alive\n\n"
64
+
65
+ def close(self):
66
+ if self.listener in self.pool.listeners:
67
+ self.pool.listeners.remove(self.listener)
68
+
69
+
70
+ class ControlServer:
71
+ """Admin API and dashboard, on 127.0.0.1 only. Every dashboard button, CLI command and library call goes through these routes."""
72
+
73
+ def __init__(self, pool, port: int = 0, token: str | None = None):
74
+ self.pool = pool
75
+ self.token = token or secrets.token_urlsafe(18)
76
+ self.pending: dict[str, dict] = {}
77
+ self.client_seen: dict[str, float] = {}
78
+ self.logins: dict[str, float] = {}
79
+ routes = {
80
+ ("GET", "/"): self._index, ("GET", "/ui"): self._static, ("GET", "/api/status"): lambda q, b: (200, self._status()),
81
+ ("GET", "/api/devices"): lambda q, b: (200, self.pool.devices()), ("GET", "/api/events"): lambda q, b: (200, EventStream(self.pool)),
82
+ ("POST", "/api/device"): self._device, ("POST", "/api/device/drain"): lambda q, b: self._call(self.pool.drain, json.loads(b)["id"]),
83
+ ("POST", "/api/device/remove"): lambda q, b: self._call(self.pool.remove, json.loads(b)["id"]),
84
+ ("POST", "/api/invite"): lambda q, b: self._call(self.pool.invite, **(json.loads(b) if b else {})),
85
+ ("GET", "/api/waiting"): lambda q, b: (200, self.pool.waiting()),
86
+ ("POST", "/api/answer"): lambda q, b: self._call(self.pool.answer, **json.loads(b)),
87
+ ("POST", "/api/preview"): lambda q, b: self._call(lambda: {"plan": self.pool.preview(json.loads(b) if b else None)}),
88
+ ("POST", "/api/run/settings"): lambda q, b: self._call(self.pool.set_run, **json.loads(b)),
89
+ ("POST", "/api/plan"): lambda q, b: self._call(self.pool.plan_for, json.loads(b)["job"]),
90
+ ("POST", "/api/run/start"): self._start, ("POST", "/api/run/end"): self._end,
91
+ ("POST", "/api/run/alive"): self._alive, ("POST", "/api/login"): self._login,
92
+ ("POST", "/api/run/ready"): lambda q, b: self._call(self.pool.wait_ready, float(q.get("timeout", 1800))),
93
+ ("POST", "/api/run/fb"): self._fb, ("POST", "/api/run/cot"): self._cot, ("POST", "/api/run/forward"): self._forward, ("POST", "/api/run/load"): self._load,
94
+ ("POST", "/api/run/step"): lambda q, b: self._call(self.pool.optim_step, **json.loads(b)),
95
+ ("POST", "/api/run/fit"): lambda q, b: self._call(self.pool.fit_batch, **json.loads(b)),
96
+ ("POST", "/api/run/export"): lambda q, b: self._call(self.pool.export, **json.loads(b)),
97
+ ("POST", "/api/run/metric"): lambda q, b: (self.pool.emit("metric", json.loads(b)), (200, b""))[1],
98
+ }
99
+ self.server = PeerServer(port=port, token=self.token, routes=routes, host="127.0.0.1", check=self._check)
100
+ self.port = self.server.port
101
+ self.url = f"http://127.0.0.1:{self.port}"
102
+ threading.Thread(target=self._watch_clients, daemon=True).start()
103
+
104
+ def _status(self) -> dict:
105
+ out = self.pool.status()
106
+ seen = self.client_seen.get(out.get("run")) if out.get("run") else None
107
+ out["script_quiet_s"] = round(time.monotonic() - seen, 1) if seen else None
108
+ out["abandon_after_s"] = self.ABANDONED_AFTER_S
109
+ return out
110
+
111
+ def _watch_clients(self):
112
+ """A training script that died (killed, crashed, out of memory) stops saying it is alive: end its run so the devices are
113
+ free for the next one."""
114
+ last = time.monotonic()
115
+ while not self.pool.closed:
116
+ time.sleep(5)
117
+ now = time.monotonic()
118
+ if now - last > 15:
119
+ self.client_seen = {k: max(v, now - 5) for k, v in self.client_seen.items()}
120
+ last = now
121
+ try:
122
+ self._abandon_stale_run()
123
+ except Exception:
124
+ pass
125
+
126
+ def _check(self, handler, method: str, path: str, query: dict):
127
+ host = handler.headers.get("Host", "")
128
+ if host not in (f"127.0.0.1:{self.port}", f"localhost:{self.port}"):
129
+ return 403, {"error": "unexpected Host header"}
130
+ origin = handler.headers.get("Origin")
131
+ if origin and origin not in (f"http://127.0.0.1:{self.port}", f"http://localhost:{self.port}"):
132
+ return 403, {"error": "cross-site request refused"}
133
+ if path == "/" or path.startswith("/ui") or path == "/api/login":
134
+ return None
135
+ auth = handler.headers.get("Authorization", "")
136
+ given = auth[7:] if auth.startswith("Bearer ") else handler.headers.get("X-Token") or query.get("t")
137
+ if not hmac.compare_digest(str(given or "").encode("utf-8", "surrogateescape"), self.token.encode()):
138
+ return 401, {"error": "missing or wrong admin token"}
139
+ if path in ("/api/run/fb", "/api/run/cot", "/api/run/forward", "/api/run/step", "/api/run/export", "/api/run/ready", "/api/run/metric"):
140
+ self._touch()
141
+ return None
142
+
143
+ def _index(self, query, body):
144
+ with open(os.path.join(UI_DIR, "index.html"), "rb") as f:
145
+ return 200, f.read(), TYPES[".html"], PAGE_HEADERS
146
+
147
+ def _static(self, query, body):
148
+ name = os.path.basename(query.get("f", ""))
149
+ path = os.path.join(UI_DIR, name)
150
+ if not name or not os.path.isfile(path):
151
+ return 404, b""
152
+ with open(path, "rb") as f:
153
+ return 200, f.read(), TYPES.get(os.path.splitext(name)[1], "application/octet-stream"), PAGE_HEADERS
154
+
155
+ def _call(self, fn, *args, **kwargs):
156
+ try:
157
+ out = fn(*args, **kwargs)
158
+ except PoolError as e:
159
+ return 409, {"error": str(e)}
160
+ except (ValueError, KeyError, TimeoutError, TypeError) as e:
161
+ return 400, {"error": str(e.args[0]) if isinstance(e, KeyError) and e.args else str(e)}
162
+ return 200, out if isinstance(out, (dict, list)) else {"result": out}
163
+
164
+ def _device(self, query, body):
165
+ data = json.loads(body)
166
+ wid = data.pop("id")
167
+ return self._call(self.pool.set_device, wid, **data)
168
+
169
+ ABANDONED_AFTER_S = float(os.environ.get("LAYERPOOL_ABANDON_S", "120"))
170
+
171
+ def _alive(self, query, body):
172
+ run_id = json.loads(body).get("run") if body else None
173
+ if run_id:
174
+ self.client_seen[run_id] = time.monotonic()
175
+ active = self.pool.job is not None and self.pool.run_id == run_id
176
+ return 200, {"active": active}
177
+
178
+ def _fail_pending(self, why: str):
179
+ for slot in list(self.pending.values()):
180
+ slot["cot"].put(PoolError(why))
181
+
182
+ def _end(self, query, body):
183
+ data = json.loads(body) if body else {}
184
+ if self.pool.job is not None and data.get("run") in (None, self.pool.run_id):
185
+ self._fail_pending("the run was ended")
186
+ return self._call(self.pool.end_run, data.get("state", "finished"), data.get("run"))
187
+
188
+ def _abandon_stale_run(self):
189
+ run_id = self.pool.run_id if self.pool.job is not None else None
190
+ if run_id is None:
191
+ return
192
+ seen = self.client_seen.get(run_id)
193
+ if seen is None or time.monotonic() - seen < self.ABANDONED_AFTER_S:
194
+ return
195
+ self._fail_pending("the training script that owned this run stopped")
196
+ self.pool.event(f"run {run_id} has no live training script any more; ending it so a new run can start")
197
+ self.pool.end_run("abandoned", run_id)
198
+
199
+ def _start(self, query, body):
200
+ self._abandon_stale_run()
201
+ data = json.loads(body)
202
+ if not isinstance(data.get("job"), dict):
203
+ return 400, {"error": "start a run with a job (see layerpool.job.build_job)"}
204
+ return self._call(lambda: {"run": self.pool.start_run(data["job"], data.get("name"))})
205
+
206
+ def _touch(self):
207
+ if self.pool.job is not None:
208
+ self.client_seen[self.pool.run_id] = time.monotonic()
209
+
210
+ def _fb(self, query, body):
211
+ meta, arrays = unpack(body)
212
+ inputs = _blobs("in", arrays)
213
+ slot = {"news": queue.Queue(), "cot": queue.Queue()}
214
+ op_id = secrets.token_hex(8)
215
+ self.pending[op_id] = slot
216
+
217
+ def provider(outputs):
218
+ slot["news"].put(("outputs", outputs))
219
+ try:
220
+ got = slot["cot"].get(timeout=1800)
221
+ except queue.Empty:
222
+ raise PoolError("the training script did not send its loss gradient within 30 minutes") from None
223
+ if isinstance(got, Exception):
224
+ raise got
225
+ return got
226
+
227
+ def work():
228
+ try:
229
+ out = self.pool.forward_backward(inputs, provider, tokens=int(meta.get("tokens", 0)), grads=bool(meta.get("grads")))
230
+ slot["news"].put(("result", out))
231
+ except Exception as e:
232
+ slot["news"].put(("result", e))
233
+ threading.Thread(target=work, daemon=True).start()
234
+ return self._answer(op_id)
235
+
236
+ def _answer(self, op_id: str):
237
+ slot = self.pending[op_id]
238
+ kind, out = slot["news"].get()
239
+ if kind == "outputs":
240
+ return 200, pack({"done": False, "op": op_id, "n": len(out)}, **_as_arrays("out", out))
241
+ del self.pending[op_id]
242
+ if isinstance(out, Exception):
243
+ return (409 if isinstance(out, PoolError) else 500), {"error": str(out) if isinstance(out, PoolError) else repr(out)}
244
+ grads = out.pop("grads", None)
245
+ return 200, pack({"done": True, **out}, **_as_arrays("g", grads))
246
+
247
+ def _cot(self, query, body):
248
+ meta, arrays = unpack(body)
249
+ slot = self.pending.get(meta["op"])
250
+ if slot is None:
251
+ return 404, {"error": "unknown operation"}
252
+ slot["cot"].put(_blobs("cot", arrays))
253
+ return self._answer(meta["op"])
254
+
255
+ def _load(self, query, body):
256
+ meta, arrays = unpack(body)
257
+ return self._call(self.pool.load_weights, arrays)
258
+
259
+ def _forward(self, query, body):
260
+ meta, arrays = unpack(body)
261
+ try:
262
+ outputs = self.pool.forward(_blobs("in", arrays), adapter=bool(meta.get("adapter", True)))
263
+ except PoolError as e:
264
+ return 409, {"error": str(e)}
265
+ return 200, pack({"n": len(outputs)}, **_as_arrays("out", outputs))
266
+
267
+ def publish(self, path: str = STATE_FILE):
268
+ os.makedirs(os.path.dirname(path), mode=0o700, exist_ok=True)
269
+ tmp = path + ".tmp"
270
+ if os.path.exists(tmp):
271
+ os.remove(tmp)
272
+ with os.fdopen(os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600), "w", encoding="utf-8") as f:
273
+ json.dump({"url": self.url, "token": self.token, "pid": os.getpid(), "workers": self.pool.urls, "started": time.time()}, f)
274
+ replace_file(tmp, path)
275
+ self.state_file = path
276
+
277
+ def dashboard_url(self) -> str:
278
+ return f"{self.url}/#t={self.token}"
279
+
280
+ def login_url(self) -> str:
281
+ """The dashboard with a code that works once, for a few minutes, so the admin token itself is not on the command line
282
+ that opens the browser."""
283
+ code = secrets.token_urlsafe(16)
284
+ now = time.monotonic()
285
+ self.logins = {c: t for c, t in self.logins.items() if now - t < LOGIN_TTL_S}
286
+ self.logins[code] = now
287
+ return f"{self.url}/#o={code}"
288
+
289
+ def _login(self, query, body):
290
+ code = str((json.loads(body) if body else {}).get("code", ""))
291
+ made = self.logins.pop(code, None)
292
+ if made is None or time.monotonic() - made > LOGIN_TTL_S:
293
+ return 403, {"error": "this sign-in link was used already or is too old; open the dashboard link `layerpool up` printed"}
294
+ return 200, {"token": self.token}
295
+
296
+ def close(self):
297
+ if getattr(self, "state_file", None):
298
+ try:
299
+ with open(self.state_file, encoding="utf-8") as f:
300
+ if json.load(f).get("pid") == os.getpid():
301
+ os.remove(self.state_file)
302
+ except (OSError, ValueError):
303
+ pass
304
+ self.server.close()
305
+
306
+
307
+ _LOCAL = urllib.request.build_opener(urllib.request.ProxyHandler({}))
308
+
309
+
310
+ def find_local(path: str = STATE_FILE) -> dict | None:
311
+ try:
312
+ with open(path, encoding="utf-8") as f:
313
+ info = json.load(f)
314
+ import psutil
315
+ if not psutil.pid_exists(info["pid"]):
316
+ return None
317
+ _LOCAL.open(info["url"] + "/ping", timeout=2).read()
318
+ return info
319
+ except (OSError, ValueError, KeyError):
320
+ return None
321
+ except Exception:
322
+ return None
323
+
324
+
325
+ class RemoteError(RuntimeError):
326
+ pass
327
+
328
+
329
+ class RemotePool:
330
+ """The same methods as Pool, over the control API of a pool running in another process (`layerpool up`)."""
331
+
332
+ def __init__(self, url: str, token: str):
333
+ self.url, self.token = url.rstrip("/"), token
334
+ self.history: list = []
335
+
336
+ def _req(self, path: str, data: bytes | None = None, timeout: float = 3600) -> bytes:
337
+ req = urllib.request.Request(self.url + path, data=data, method="POST" if data is not None else "GET",
338
+ headers={"Authorization": f"Bearer {self.token}"})
339
+ try:
340
+ with _LOCAL.open(req, timeout=timeout) as r:
341
+ return r.read()
342
+ except urllib.error.HTTPError as e:
343
+ detail = e.read().decode(errors="replace")
344
+ try:
345
+ detail = json.loads(detail).get("error", detail)
346
+ except ValueError:
347
+ pass
348
+ if e.code == 409:
349
+ raise PoolError(detail) from None
350
+ raise RemoteError(f"{e.code}: {detail}") from None
351
+
352
+ def _json(self, path: str, payload=None):
353
+ out = self._req(path, None if payload is None else json.dumps(payload, default=str).encode())
354
+ return json.loads(out) if out else None
355
+
356
+ def status(self):
357
+ status = self._json("/api/status")
358
+ self.history = status.get("history", [])
359
+ return status
360
+
361
+ def devices(self):
362
+ return self._json("/api/devices")
363
+
364
+ def invite(self, **kw):
365
+ return self._json("/api/invite", kw)
366
+
367
+ def waiting(self):
368
+ return self._json("/api/waiting")
369
+
370
+ def answer(self, code: str, approve: bool = True) -> str:
371
+ return self._json("/api/answer", {"code": code, "approve": approve})["result"]
372
+
373
+ def set_device(self, wid: str, **changes):
374
+ return self._json("/api/device", {"id": wid, **changes})
375
+
376
+ def drain(self, wid: str):
377
+ return self._json("/api/device/drain", {"id": wid})
378
+
379
+ def set_run(self, **changes):
380
+ return self._json("/api/run/settings", changes)
381
+
382
+ def plan_for(self, job: dict) -> dict:
383
+ return self._json("/api/plan", {"job": job})
384
+
385
+ def remove(self, wid: str):
386
+ return self._json("/api/device/remove", {"id": wid})
387
+
388
+ def preview(self, overrides=None):
389
+ return self._json("/api/preview", overrides or {})["plan"]
390
+
391
+ def start_run(self, job: dict, name: str | None = None) -> str:
392
+ run_id = self._json("/api/run/start", {"job": job, "name": name})["run"]
393
+ threading.Thread(target=self._keep_alive, args=(run_id,), daemon=True).start()
394
+ return run_id
395
+
396
+ def _keep_alive(self, run_id: str):
397
+ while True:
398
+ try:
399
+ if not self._json("/api/run/alive", {"run": run_id}).get("active"):
400
+ return
401
+ except Exception:
402
+ pass
403
+ time.sleep(5)
404
+
405
+ def end_run(self, state: str = "finished", run_id: str | None = None):
406
+ return self._json("/api/run/end", {"state": state, "run": run_id})
407
+
408
+ def wait_ready(self, timeout: float | None = None):
409
+ return self._json(f"/api/run/ready?timeout={timeout or 1800}", {})
410
+
411
+ def forward_backward(self, inputs, provider, tokens: int = 0, grads: bool = False) -> dict:
412
+ meta, got = unpack(self._req("/api/run/fb", pack({"tokens": tokens, "grads": grads}, **_as_arrays("in", inputs))))
413
+ while not meta.get("done"):
414
+ cots = provider(_blobs("out", got))
415
+ meta, got = unpack(self._req("/api/run/cot", pack({"op": meta["op"]}, **_as_arrays("cot", cots))))
416
+ meta.pop("done", None)
417
+ meta["grads"] = _blobs("g", got) if grads else None
418
+ return meta
419
+
420
+ def add_loss(self, value: float):
421
+ pass
422
+
423
+ def fit_batch(self, rows: int, seq: int, pieces: int | None = None):
424
+ return self._json("/api/run/fit", {"rows": rows, "seq": seq, "pieces": pieces})
425
+
426
+ def forward(self, inputs, adapter: bool = True):
427
+ meta, got = unpack(self._req("/api/run/forward", pack({"adapter": adapter}, **_as_arrays("in", inputs))))
428
+ return _blobs("out", got)
429
+
430
+ def optim_step(self, lr: float, max_grad_norm=None, loss=None, clip=None, weight_decay=None, skip: bool = False) -> dict:
431
+ record = self._json("/api/run/step", {"lr": lr, "max_grad_norm": max_grad_norm, "loss": loss, "clip": clip, "weight_decay": weight_decay,
432
+ "skip": skip})
433
+ self.history.append(record)
434
+ return record
435
+
436
+ def export(self, path: str, dtype: str = "bfloat16", metrics=None, optimizer: bool = False) -> str:
437
+ return self._json("/api/run/export", {"path": path, "dtype": dtype, "metrics": metrics, "optimizer": optimizer})["result"]
438
+
439
+ def load_weights(self, weights: dict):
440
+ self._req("/api/run/load", pack(None, **weights))
441
+
442
+ def emit(self, kind: str, data: dict):
443
+ if kind == "metric":
444
+ try:
445
+ self._json("/api/run/metric", data)
446
+ except Exception:
447
+ pass