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/__init__.py +11 -0
- layerpool/__main__.py +3 -0
- layerpool/api.py +682 -0
- layerpool/backends/__init__.py +0 -0
- layerpool/backends/common.py +21 -0
- layerpool/backends/mlx_backend.py +622 -0
- layerpool/blocks.py +1061 -0
- layerpool/cli.py +567 -0
- layerpool/codec.py +195 -0
- layerpool/control.py +447 -0
- layerpool/driver.py +427 -0
- layerpool/export.py +157 -0
- layerpool/fetch.py +324 -0
- layerpool/hf.py +303 -0
- layerpool/job.py +242 -0
- layerpool/losses.py +108 -0
- layerpool/net.py +529 -0
- layerpool/planner.py +104 -0
- layerpool/pool.py +1670 -0
- layerpool/selfcheck.py +348 -0
- layerpool/telemetry.py +195 -0
- layerpool/trainers.py +168 -0
- layerpool/tunnel.py +165 -0
- layerpool/ui/app.js +479 -0
- layerpool/ui/index.html +82 -0
- layerpool/ui/style.css +148 -0
- layerpool/worker.py +1277 -0
- layerpool-0.1.0.dist-info/METADATA +407 -0
- layerpool-0.1.0.dist-info/RECORD +32 -0
- layerpool-0.1.0.dist-info/WHEEL +4 -0
- layerpool-0.1.0.dist-info/entry_points.txt +2 -0
- layerpool-0.1.0.dist-info/licenses/LICENSE +21 -0
layerpool/pool.py
ADDED
|
@@ -0,0 +1,1670 @@
|
|
|
1
|
+
import hmac
|
|
2
|
+
import json
|
|
3
|
+
import math
|
|
4
|
+
import os
|
|
5
|
+
import queue
|
|
6
|
+
import re
|
|
7
|
+
import secrets
|
|
8
|
+
import shutil
|
|
9
|
+
import tempfile
|
|
10
|
+
import threading
|
|
11
|
+
import time
|
|
12
|
+
|
|
13
|
+
import numpy as np
|
|
14
|
+
|
|
15
|
+
from . import __version__
|
|
16
|
+
from .codec import Spilled, from_half, pack, replace_file, unpack
|
|
17
|
+
from .export import export_blocks, export_peft
|
|
18
|
+
from .net import Cancelled, Peer, PeerServer, ping
|
|
19
|
+
from .planner import Node, Stage, layer_bounds, plan
|
|
20
|
+
from .tunnel import Tunnel
|
|
21
|
+
|
|
22
|
+
DEFAULT_SPEED = {"cuda": 1.0, "mlx": 0.6, "mps": 1.5, "cpu": 8.0}
|
|
23
|
+
OPLOG_LIMIT_GB = float(os.environ.get("LAYERPOOL_REPLAY_GB", "4"))
|
|
24
|
+
CKPT_ROOT = os.path.join(os.path.expanduser("~"), ".cache", "layerpool", "checkpoints")
|
|
25
|
+
SHARED_MEMORY = {"cpu": 0.5, "mlx": 0.6, "mps": 0.6}
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
OPTIMIZER_FILE = "layerpool_optimizer.safetensors"
|
|
29
|
+
|
|
30
|
+
def _number(value) -> float | None:
|
|
31
|
+
try:
|
|
32
|
+
return float(value)
|
|
33
|
+
except (TypeError, ValueError):
|
|
34
|
+
return None
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _version_tuple(text: str) -> tuple:
|
|
38
|
+
return tuple(int(part) for part in re.findall(r"\d+", str(text).split("+")[0])[:3])
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _transformers_version() -> str:
|
|
42
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
43
|
+
try:
|
|
44
|
+
return version("transformers")
|
|
45
|
+
except PackageNotFoundError:
|
|
46
|
+
return ""
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class Unreachable(ConnectionError):
|
|
50
|
+
def __init__(self, wid: str, error: Exception):
|
|
51
|
+
super().__init__(f"{wid}: {error!r}")
|
|
52
|
+
self.wid = wid
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class Interrupted(Exception):
|
|
56
|
+
pass
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _clean_telemetry(data) -> dict:
|
|
60
|
+
"""Keep only numbers (and lists of GPU records with numbers) from a device's report, plus a short heat note, so a bad device
|
|
61
|
+
cannot break the dashboard."""
|
|
62
|
+
|
|
63
|
+
def number(v):
|
|
64
|
+
return v if isinstance(v, (int, float)) and not isinstance(v, bool) and math.isfinite(v) else None
|
|
65
|
+
out = {}
|
|
66
|
+
for key, value in (data or {}).items() if isinstance(data, dict) else []:
|
|
67
|
+
key = str(key)[:32]
|
|
68
|
+
if key == "gpus" and isinstance(value, list):
|
|
69
|
+
out[key] = [{str(k)[:32]: number(v) for k, v in g.items()} for g in value[:16] if isinstance(g, dict)]
|
|
70
|
+
elif number(value) is not None:
|
|
71
|
+
out[key] = number(value)
|
|
72
|
+
elif key == "heat" and isinstance(value, str):
|
|
73
|
+
out[key] = "".join(c for c in value[:60] if c.isprintable())
|
|
74
|
+
return out
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
class PoolError(RuntimeError):
|
|
78
|
+
pass
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
DEVICE_SETTINGS = ("name", "cap_gb", "enabled", "layers", "gpus", "gpu_caps", "order", "ram_cap")
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def clean_settings(changes: dict, gpu_count: int) -> dict:
|
|
85
|
+
"""A device's settings checked and in one form, or PoolError saying what is wrong. None (or "auto") clears a setting.
|
|
86
|
+
layers: a count ("8"), a share of the model ("30%") or a range ("4-10"); gpus: the GPUs to use on a machine with several
|
|
87
|
+
([0, 2]); gpu_caps: the most memory each GPU may use ({"0": 6, "1": 10}); order: the device's place in the chain (lower first);
|
|
88
|
+
ram_cap: on a machine with GPUs, the RAM it may also use for layers that do not fit them, which its CPU then runs."""
|
|
89
|
+
bad = set(changes) - set(DEVICE_SETTINGS)
|
|
90
|
+
if bad:
|
|
91
|
+
raise PoolError(f"unknown device settings: {sorted(bad)}")
|
|
92
|
+
out = {}
|
|
93
|
+
for key, value in changes.items():
|
|
94
|
+
if value == "auto":
|
|
95
|
+
value = None
|
|
96
|
+
if key == "ram_cap" and value is not None and not gpu_count:
|
|
97
|
+
raise PoolError("ram_cap lets a machine with GPUs keep more layers in its RAM; on this device the memory cap already is its RAM")
|
|
98
|
+
if key in ("cap_gb", "ram_cap") and value is not None:
|
|
99
|
+
if isinstance(value, bool) or not (isinstance(value, (int, float)) and math.isfinite(value) and value > 0):
|
|
100
|
+
raise PoolError(f"{key} must be a positive number")
|
|
101
|
+
elif key == "name":
|
|
102
|
+
value = str(value or "").strip()[:64]
|
|
103
|
+
if not value:
|
|
104
|
+
raise PoolError("a device name cannot be empty")
|
|
105
|
+
elif key == "enabled":
|
|
106
|
+
value = bool(value)
|
|
107
|
+
elif key == "layers" and value is not None:
|
|
108
|
+
value = str(value).replace(" ", "")
|
|
109
|
+
if not re.fullmatch(r"[1-9]\d{0,3}|[1-9]\d{0,3}-[1-9]\d{0,3}|(100|[1-9]\d?(\.\d+)?)%", value):
|
|
110
|
+
raise PoolError("layers takes a count (8), a share of the model (30%), a range (4-10) or auto")
|
|
111
|
+
low, high = layer_bounds(value, 100)
|
|
112
|
+
if high is not None and low > high:
|
|
113
|
+
raise PoolError(f"layers {value}: the range goes the wrong way")
|
|
114
|
+
elif key == "gpus" and value is not None:
|
|
115
|
+
if isinstance(value, str):
|
|
116
|
+
value = [x for x in value.replace(" ", "").split(",") if x]
|
|
117
|
+
try:
|
|
118
|
+
value = sorted({int(x) for x in value})
|
|
119
|
+
except (TypeError, ValueError):
|
|
120
|
+
raise PoolError("gpus takes GPU numbers such as 0,2") from None
|
|
121
|
+
if not value or any(i < 0 or i >= gpu_count for i in value):
|
|
122
|
+
raise PoolError(f"gpus: this device has {gpu_count} GPU{'s' if gpu_count != 1 else ''}, numbered 0 to {max(0, gpu_count - 1)}")
|
|
123
|
+
elif key == "gpu_caps" and value is not None:
|
|
124
|
+
if isinstance(value, str):
|
|
125
|
+
try:
|
|
126
|
+
value = dict(part.split("=", 1) for part in value.replace(" ", "").split(",") if part)
|
|
127
|
+
except ValueError:
|
|
128
|
+
raise PoolError("gpu_caps takes GPU=GB pairs such as 0=6,1=10") from None
|
|
129
|
+
try:
|
|
130
|
+
value = {str(int(k)): float(v) for k, v in dict(value).items()}
|
|
131
|
+
except (TypeError, ValueError):
|
|
132
|
+
raise PoolError("gpu_caps takes GPU=GB pairs such as 0=6,1=10") from None
|
|
133
|
+
if any(int(k) < 0 or int(k) >= gpu_count for k in value) or any(not (math.isfinite(v) and v > 0) for v in value.values()):
|
|
134
|
+
raise PoolError(f"gpu_caps: GPU numbers go from 0 to {max(0, gpu_count - 1)} on this device and each cap is a positive "
|
|
135
|
+
"number of GB")
|
|
136
|
+
value = value or None
|
|
137
|
+
elif key == "order" and value is not None:
|
|
138
|
+
try:
|
|
139
|
+
value = int(value)
|
|
140
|
+
except (TypeError, ValueError):
|
|
141
|
+
raise PoolError("order takes a whole number (lower comes first in the chain)") from None
|
|
142
|
+
out[key] = value
|
|
143
|
+
return out
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def scheduled_lr(base: float, step: int, total: int, warmup: int = 0, schedule: str = "constant", min_ratio: float = 0.1) -> float:
|
|
147
|
+
if step < warmup:
|
|
148
|
+
return base * (step + 1) / warmup
|
|
149
|
+
if schedule == "cosine":
|
|
150
|
+
progress = min(1.0, (step - warmup) / max(1, total - warmup))
|
|
151
|
+
return base * (min_ratio + (1 - min_ratio) * 0.5 * (1 + math.cos(math.pi * progress)))
|
|
152
|
+
if schedule == "linear":
|
|
153
|
+
progress = min(1.0, (step - warmup) / max(1, total - warmup))
|
|
154
|
+
return base * (1 - (1 - min_ratio) * progress)
|
|
155
|
+
return base
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _thin(rows: list, most: int) -> list:
|
|
159
|
+
"""At most `most` rows spread over the whole list, the last one always kept, for charts of long runs."""
|
|
160
|
+
if len(rows) <= most:
|
|
161
|
+
return list(rows)
|
|
162
|
+
step = len(rows) / (most - 1)
|
|
163
|
+
return [rows[int(i * step)] for i in range(most - 1)] + [rows[-1]]
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
class Pool:
|
|
167
|
+
"""Devices join once and stay; runs come and go. Every surface (library, CLI, dashboard) drives runs through these methods."""
|
|
168
|
+
|
|
169
|
+
def __init__(self, port: int = 0, heartbeat_timeout: float = 120.0, tunnel: bool = False, log=None, ckpt_dir: str | None = None,
|
|
170
|
+
max_failures: int = 3, token: str | None = None, settings_file: str | None = None,
|
|
171
|
+
state_file: str | None = None, advertise: str | None = None):
|
|
172
|
+
self.heartbeat_timeout = heartbeat_timeout
|
|
173
|
+
self.state_file = state_file
|
|
174
|
+
kept = {}
|
|
175
|
+
if state_file and os.path.exists(state_file):
|
|
176
|
+
try:
|
|
177
|
+
with open(state_file, encoding="utf-8") as f:
|
|
178
|
+
kept = json.load(f)
|
|
179
|
+
except ValueError:
|
|
180
|
+
kept = {}
|
|
181
|
+
token = token or kept.get("token")
|
|
182
|
+
self.settings_file = settings_file
|
|
183
|
+
self.saved_settings: dict[str, dict] = {}
|
|
184
|
+
if settings_file and os.path.exists(settings_file):
|
|
185
|
+
try:
|
|
186
|
+
with open(settings_file, encoding="utf-8") as f:
|
|
187
|
+
self.saved_settings = json.load(f)
|
|
188
|
+
except ValueError:
|
|
189
|
+
pass
|
|
190
|
+
self.cond = threading.Condition()
|
|
191
|
+
self.op_lock = threading.Lock()
|
|
192
|
+
self.workers: dict[str, dict] = {}
|
|
193
|
+
self.identities: dict[str, str] = dict(kept.get("identities", {}))
|
|
194
|
+
self.plan: list[dict] | None = None
|
|
195
|
+
self.epoch = 0
|
|
196
|
+
self.step = 0
|
|
197
|
+
self.seq = 0
|
|
198
|
+
self.seq_base = 0
|
|
199
|
+
self.ready: set = set()
|
|
200
|
+
self.reports: dict[tuple, dict] = {}
|
|
201
|
+
self.measured: dict[str, float] = {}
|
|
202
|
+
self.measured_link: dict[str, float] = {}
|
|
203
|
+
self.measured_spill: dict[str, float] = {}
|
|
204
|
+
self.told_bnb: set = set()
|
|
205
|
+
self.steps_in_plan = 0
|
|
206
|
+
self.pending = False
|
|
207
|
+
self.closed = False
|
|
208
|
+
self.job: dict | None = None
|
|
209
|
+
self._planning = threading.local()
|
|
210
|
+
self.run_id: str | None = None
|
|
211
|
+
self.runs: list[dict] = []
|
|
212
|
+
self.oplog: list[dict] = []
|
|
213
|
+
self.oplog_after = -1
|
|
214
|
+
self._replayed_epoch = -1
|
|
215
|
+
self._good_steps = 0
|
|
216
|
+
self.accum = {"loss": None, "tokens": 0, "started": None}
|
|
217
|
+
self._own_ckpt = ckpt_dir is None
|
|
218
|
+
if ckpt_dir is None:
|
|
219
|
+
os.makedirs(CKPT_ROOT, exist_ok=True)
|
|
220
|
+
ckpt_dir = tempfile.mkdtemp(prefix="pool_", dir=CKPT_ROOT)
|
|
221
|
+
self.ckpt_dir = ckpt_dir
|
|
222
|
+
os.makedirs(self.ckpt_dir, exist_ok=True)
|
|
223
|
+
self.ckpt: dict[int, dict[int, set[str]]] = {}
|
|
224
|
+
self.restore = -1
|
|
225
|
+
self.protect: int | None = None
|
|
226
|
+
self.max_failures = max_failures
|
|
227
|
+
self.history: list[dict] = []
|
|
228
|
+
self.events: list[tuple[float, str]] = []
|
|
229
|
+
self.listeners: list = []
|
|
230
|
+
self.t0 = time.time()
|
|
231
|
+
self.log_fn = log or (lambda text: print(f"[layerpool {time.time() - self.t0:7.1f}s] {text}", flush=True))
|
|
232
|
+
routes = {
|
|
233
|
+
("POST", "/join"): self._join, ("POST", "/hb"): self._hb, ("GET", "/assignment"): self._assignment, ("GET", "/epoch"): self._epoch,
|
|
234
|
+
("POST", "/ready"): self._ready, ("POST", "/done"): self._done, ("POST", "/ckpt"): self._ckpt_put, ("GET", "/ckpt"): self._ckpt_get,
|
|
235
|
+
("GET", "/info"): lambda q, b: (200, {"tunnel": self.tunnel is not None, "version": __version__}), ("POST", "/export"): self._export_put,
|
|
236
|
+
("POST", "/fail"): self._fail, ("POST", "/have"): self._have, ("GET", "/where"): self._where,
|
|
237
|
+
("POST", "/request"): self._request_join, ("GET", "/request"): self._request_status,
|
|
238
|
+
}
|
|
239
|
+
self.requests: dict[str, dict] = {}
|
|
240
|
+
self.invites: dict[str, dict] = {}
|
|
241
|
+
self.device_tokens: dict[str, str] = dict(kept.get("device_tokens", {}))
|
|
242
|
+
self.server = PeerServer(port=port, token=token, routes=routes, check=self._check,
|
|
243
|
+
limits={"/request": 8192, "/join": 1 << 16, "/hb": 1 << 20, "/info": 1024})
|
|
244
|
+
self.token = self.server.token
|
|
245
|
+
self.urls = [self.server.url_at(advertise) if advertise else self.server.lan_url()]
|
|
246
|
+
self.tunnel = None
|
|
247
|
+
if tunnel:
|
|
248
|
+
opened = queue.Queue()
|
|
249
|
+
threading.Thread(target=self._keep_tunnel, args=(opened,), daemon=True).start()
|
|
250
|
+
got = opened.get()
|
|
251
|
+
if isinstance(got, BaseException):
|
|
252
|
+
self.server.close()
|
|
253
|
+
raise got
|
|
254
|
+
self.tunnel = got
|
|
255
|
+
self.urls.append(self.tunnel.url)
|
|
256
|
+
threading.Thread(target=self._monitor, daemon=True).start()
|
|
257
|
+
|
|
258
|
+
def _keep_tunnel(self, opened):
|
|
259
|
+
"""Opens the tunnel, watches it for as long as the pool runs, and opens new ones from here: on Linux a helper process ends
|
|
260
|
+
with the thread that started it, so this thread must outlive every tunnel it opens."""
|
|
261
|
+
try:
|
|
262
|
+
opened.put(Tunnel(self.server.port, log=self.event))
|
|
263
|
+
except BaseException as e:
|
|
264
|
+
opened.put(e)
|
|
265
|
+
return
|
|
266
|
+
while not self.closed:
|
|
267
|
+
time.sleep(1)
|
|
268
|
+
if self.tunnel is not None and not self.tunnel.alive() and not self.closed:
|
|
269
|
+
self._reopen_tunnel()
|
|
270
|
+
|
|
271
|
+
def _reopen_tunnel(self):
|
|
272
|
+
"""cloudflared stopped: open a new tunnel. It has a new address, so devices on the internet must join again with a new
|
|
273
|
+
join command; the ones on this network go on."""
|
|
274
|
+
old = self.tunnel.url
|
|
275
|
+
self.event("the tunnel stopped; opening a new one")
|
|
276
|
+
try:
|
|
277
|
+
self.tunnel = Tunnel(self.server.port, log=self.event)
|
|
278
|
+
except Exception as e:
|
|
279
|
+
self.event(f"could not open a new tunnel ({str(e).splitlines()[0]}); trying again in a minute")
|
|
280
|
+
time.sleep(60)
|
|
281
|
+
return
|
|
282
|
+
self.urls = [u for u in self.urls if u != old] + [self.tunnel.url]
|
|
283
|
+
self.event(f"new tunnel at {self.tunnel.url}: devices on the internet need a new join command (dashboard or `layerpool invite`)")
|
|
284
|
+
|
|
285
|
+
def event(self, text: str):
|
|
286
|
+
if getattr(self._planning, "previewing", False):
|
|
287
|
+
return
|
|
288
|
+
item = (round(time.time() - self.t0, 1), text)
|
|
289
|
+
self.events.append(item)
|
|
290
|
+
self.events[:] = self.events[-500:]
|
|
291
|
+
self.log_fn(text)
|
|
292
|
+
for listener in list(self.listeners):
|
|
293
|
+
listener("event", {"t": item[0], "text": text})
|
|
294
|
+
|
|
295
|
+
def emit(self, kind: str, data: dict):
|
|
296
|
+
for listener in list(self.listeners):
|
|
297
|
+
listener(kind, data)
|
|
298
|
+
|
|
299
|
+
def _seen(self, query):
|
|
300
|
+
w = query.get("w")
|
|
301
|
+
if w in self.workers:
|
|
302
|
+
info = self.workers[w]
|
|
303
|
+
info["seen"] = time.time()
|
|
304
|
+
if not info["alive"] and not info.get("banned") and not info.get("removed"):
|
|
305
|
+
info["alive"] = True
|
|
306
|
+
self.pending = True
|
|
307
|
+
self.event(f"{info['name']} is back")
|
|
308
|
+
|
|
309
|
+
@staticmethod
|
|
310
|
+
def _clean_join(info: dict) -> dict:
|
|
311
|
+
"""Everything a device says about itself ends up in the dashboard and the plan, so keep only well-formed values."""
|
|
312
|
+
def number(v):
|
|
313
|
+
try:
|
|
314
|
+
v = float(v)
|
|
315
|
+
except (TypeError, ValueError):
|
|
316
|
+
return None
|
|
317
|
+
return v if 0 < v < 1e6 else None
|
|
318
|
+
text = lambda v, n=80: "".join(c for c in str(v)[:n] if c.isprintable()) if v is not None else ""
|
|
319
|
+
devices = [{"kind": text(d.get("kind"), 16), "name": text(d.get("name")), "gb": number(d.get("gb")) or 0.0, "amd": bool(d.get("amd")),
|
|
320
|
+
"q4": bool(d.get("q4", not d.get("amd")))}
|
|
321
|
+
for d in (info.get("devices") or [])[:16] if isinstance(d, dict)] or [{"kind": "cpu", "name": "unknown", "gb": 0.0}]
|
|
322
|
+
addrs = [a for a in (info.get("addrs") or [])[:4] if isinstance(a, str) and a.startswith(("http://", "https://")) and len(a) < 200]
|
|
323
|
+
libraries = {text(k, 24): text(v, 40) for k, v in list((info.get("libraries") or {}).items())[:12]} if isinstance(info.get("libraries"), dict) else {}
|
|
324
|
+
return {**info, "libraries": libraries, "name": text(info.get("name"), 40) or "device", "cap_gb": number(info.get("cap_gb")),
|
|
325
|
+
"devices": devices, "addrs": addrs, "backend": text(info.get("backend"), 16), "token": text(info.get("token"), 128),
|
|
326
|
+
"identity": text(info.get("identity"), 64) or None, "version": text(info.get("version"), 32)}
|
|
327
|
+
|
|
328
|
+
def _join(self, query, body):
|
|
329
|
+
info = self._clean_join(json.loads(body))
|
|
330
|
+
gpu_count = sum(1 for d in info["devices"] if d["kind"] == "cuda")
|
|
331
|
+
asked = {k: info.pop(k) for k in ("layers", "gpus", "gpu_caps", "order", "ram_cap") if info.get(k) is not None}
|
|
332
|
+
if info.get("cap_gb") is not None:
|
|
333
|
+
asked["cap_gb"] = info["cap_gb"]
|
|
334
|
+
try:
|
|
335
|
+
info["asked"] = clean_settings(asked, gpu_count)
|
|
336
|
+
except PoolError as e:
|
|
337
|
+
return 400, {"error": str(e)}
|
|
338
|
+
with self.cond:
|
|
339
|
+
if info.get("version") and info["version"].split(".")[:2] != __version__.split(".")[:2]:
|
|
340
|
+
return 409, {"error": f"this pool runs layerpool {__version__}, the device has {info['version']}: run pip install -U layerpool=={__version__}"}
|
|
341
|
+
theirs = str((info.get("libraries") or {}).get("transformers") or "")
|
|
342
|
+
ours = _transformers_version()
|
|
343
|
+
if theirs and ours and theirs.split(".")[0] != ours.split(".")[0]:
|
|
344
|
+
return 409, {"error": f"this pool runs transformers {ours} and the device has {theirs}: install the same major version on both, "
|
|
345
|
+
f"for example pip install \"transformers=={ours}\""}
|
|
346
|
+
if theirs and ours and theirs.split(".")[:2] != ours.split(".")[:2]:
|
|
347
|
+
self.event(f"note: {info['name']} has transformers {theirs} and this pool {ours}; the same version everywhere is safest")
|
|
348
|
+
identity = info.get("identity")
|
|
349
|
+
wid = self.identities.get(identity) if identity else None
|
|
350
|
+
if wid is None or wid not in self.workers or self.workers[wid].get("removed"):
|
|
351
|
+
if wid is None or self.workers.get(wid, {}).get("removed"):
|
|
352
|
+
used = set(self.workers) | set(self.identities.values())
|
|
353
|
+
wid = next(f"w{k}" for k in range(len(used) + 1) if f"w{k}" not in used)
|
|
354
|
+
if identity:
|
|
355
|
+
self.identities[identity] = wid
|
|
356
|
+
settings = {"version": 1, "name": info["name"], "cap_gb": None, "enabled": True}
|
|
357
|
+
for key, value in (self.saved_settings.get(identity) or {}).items() if identity else ():
|
|
358
|
+
try:
|
|
359
|
+
settings.update(clean_settings({key: value}, gpu_count))
|
|
360
|
+
except PoolError as e:
|
|
361
|
+
self.event(f"{info['name']}: a saved setting no longer fits this device and is dropped ({e})")
|
|
362
|
+
settings.update(info.pop("asked", {}))
|
|
363
|
+
settings["version"] = 2
|
|
364
|
+
else:
|
|
365
|
+
settings = self.workers[wid]["settings"]
|
|
366
|
+
if info.get("asked"):
|
|
367
|
+
settings.update(info["asked"])
|
|
368
|
+
settings["version"] = settings.get("version", 0) + 1
|
|
369
|
+
info.pop("asked", None)
|
|
370
|
+
for steps in self.ckpt.values():
|
|
371
|
+
for holders in steps.values():
|
|
372
|
+
holders.discard(wid)
|
|
373
|
+
self.workers[wid] = {**info, "name": settings.get("name") or info["name"], "cap_gb": settings.get("cap_gb"), "alive": True,
|
|
374
|
+
"seen": time.time(), "fails": 0, "peer": Peer(info["addrs"], info["token"]), "settings": settings, "telemetry": {},
|
|
375
|
+
"joined": time.time()}
|
|
376
|
+
self._remember(self.workers[wid])
|
|
377
|
+
self.event(f"{self.workers[wid]['name']} joined as {wid} with {[d['name'] for d in info['devices']]}")
|
|
378
|
+
threading.Thread(target=self._check_reachable, args=(wid, list(info["addrs"])), daemon=True).start()
|
|
379
|
+
if self.job is not None:
|
|
380
|
+
if self.plan is None:
|
|
381
|
+
self._replan(f"{info['name']} joined", lost=False)
|
|
382
|
+
elif any(p["w"] == wid for p in self.plan):
|
|
383
|
+
self._replan(f"{info['name']} restarted and lost its layers", lost=True)
|
|
384
|
+
else:
|
|
385
|
+
self.pending = True
|
|
386
|
+
self.cond.notify_all()
|
|
387
|
+
device_token = secrets.token_hex(16)
|
|
388
|
+
with self.cond:
|
|
389
|
+
for t, w in [(t, w) for t, w in self.device_tokens.items() if w == wid]:
|
|
390
|
+
del self.device_tokens[t]
|
|
391
|
+
self.device_tokens[device_token] = wid
|
|
392
|
+
used = query.get("_invite")
|
|
393
|
+
if used in self.invites and not self.invites[used]["reusable"]:
|
|
394
|
+
del self.invites[used]
|
|
395
|
+
self._save_state()
|
|
396
|
+
return 200, {"wid": wid, "token": device_token, "heartbeat": max(0.5, min(5.0, self.heartbeat_timeout / 4)), "settings": self.workers[wid]["settings"]}
|
|
397
|
+
|
|
398
|
+
REQUEST_TTL = 900
|
|
399
|
+
|
|
400
|
+
def _request_join(self, query, body):
|
|
401
|
+
"""A device without a join code asks to join. It waits until someone at the pool approves its code."""
|
|
402
|
+
if len(body) > 8192:
|
|
403
|
+
return 413, {"error": "request too large"}
|
|
404
|
+
try:
|
|
405
|
+
info = json.loads(body)
|
|
406
|
+
except ValueError:
|
|
407
|
+
return 400, {"error": "bad request"}
|
|
408
|
+
text = lambda v, n: "".join(c for c in str(v or "")[:n] if c.isprintable())
|
|
409
|
+
with self.cond:
|
|
410
|
+
now = time.time()
|
|
411
|
+
for t in [t for t, r in self.requests.items() if now - r["time"] > self.REQUEST_TTL]:
|
|
412
|
+
del self.requests[t]
|
|
413
|
+
if sum(r["status"] == "waiting" for r in self.requests.values()) >= 20:
|
|
414
|
+
return 429, {"error": "too many devices are waiting for approval; approve or deny them first"}
|
|
415
|
+
alphabet = "ABCDEFGHJKMNPQRSTUVWXYZ23456789"
|
|
416
|
+
code = "".join(secrets.choice(alphabet) for _ in range(6))
|
|
417
|
+
ticket = secrets.token_urlsafe(24)
|
|
418
|
+
self.requests[ticket] = {"code": code, "name": text(info.get("name"), 40) or "device", "ip": str(query.get("_ip", ""))[:64],
|
|
419
|
+
"hardware": [text(d, 80) for d in (info.get("devices") or [])[:8]], "time": now, "status": "waiting"}
|
|
420
|
+
self.event(f"{self.requests[ticket]['name']} asks to join (code {code}): approve it in the dashboard or with `layerpool approve {code}`")
|
|
421
|
+
return 200, {"code": code, "ticket": ticket, "expires_in_s": self.REQUEST_TTL}
|
|
422
|
+
|
|
423
|
+
def _request_status(self, query, body):
|
|
424
|
+
with self.cond:
|
|
425
|
+
req = self.requests.get(str(query.get("ticket", "")))
|
|
426
|
+
if req is None:
|
|
427
|
+
return 404, {"error": "this request is unknown or expired; ask again"}
|
|
428
|
+
if req["status"] == "approved":
|
|
429
|
+
if "invite" not in req:
|
|
430
|
+
req["invite"] = self.invite(ttl=self.REQUEST_TTL)["code"]
|
|
431
|
+
return 200, {"status": "approved", "invite": req["invite"]}
|
|
432
|
+
return 200, {"status": req["status"]}
|
|
433
|
+
|
|
434
|
+
def waiting(self) -> list[dict]:
|
|
435
|
+
"""Devices waiting for approval."""
|
|
436
|
+
with self.cond:
|
|
437
|
+
now = time.time()
|
|
438
|
+
return [{"code": r["code"], "name": r["name"], "hardware": r["hardware"], "from": r.get("ip", ""), "waiting_s": round(now - r["time"])}
|
|
439
|
+
for r in self.requests.values() if r["status"] == "waiting" and now - r["time"] <= self.REQUEST_TTL]
|
|
440
|
+
|
|
441
|
+
def answer(self, code: str, approve: bool = True) -> str:
|
|
442
|
+
"""Approve or deny a device that asked to join; returns its name."""
|
|
443
|
+
code = str(code).strip().upper().replace("-", "")
|
|
444
|
+
with self.cond:
|
|
445
|
+
for r in self.requests.values():
|
|
446
|
+
if r["code"] == code and r["status"] == "waiting":
|
|
447
|
+
r["status"] = "approved" if approve else "denied"
|
|
448
|
+
name = r["name"]
|
|
449
|
+
break
|
|
450
|
+
else:
|
|
451
|
+
raise KeyError(f"no device is waiting with code {code}")
|
|
452
|
+
self.event(f"{name} was {'approved' if approve else 'denied'}")
|
|
453
|
+
return name
|
|
454
|
+
|
|
455
|
+
def _save_state(self):
|
|
456
|
+
if not self.state_file:
|
|
457
|
+
return
|
|
458
|
+
try:
|
|
459
|
+
os.makedirs(os.path.dirname(self.state_file), exist_ok=True)
|
|
460
|
+
fd = os.open(self.state_file + ".tmp", os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
|
461
|
+
with os.fdopen(fd, "w", encoding="utf-8") as f:
|
|
462
|
+
json.dump({"token": self.token, "device_tokens": self.device_tokens, "identities": self.identities}, f)
|
|
463
|
+
replace_file(self.state_file + ".tmp", self.state_file)
|
|
464
|
+
except OSError:
|
|
465
|
+
pass
|
|
466
|
+
|
|
467
|
+
def _check_reachable(self, wid: str, addrs: list[str]):
|
|
468
|
+
"""Devices send their work straight to each other: say so plainly when the pool cannot reach a device that joined."""
|
|
469
|
+
for attempt in range(7):
|
|
470
|
+
if not addrs or any(ping(a) for a in addrs) or self.closed or wid not in self.workers:
|
|
471
|
+
return
|
|
472
|
+
time.sleep(10)
|
|
473
|
+
name = self.workers.get(wid, {}).get("name", wid)
|
|
474
|
+
self.event(f"{name} joined, but this pool cannot reach it at {', '.join(addrs)}: other devices may not reach it either. "
|
|
475
|
+
"Allow layerpool through its firewall, give it an address with --advertise, or join with --tunnel on")
|
|
476
|
+
|
|
477
|
+
def _hb(self, query, body):
|
|
478
|
+
with self.cond:
|
|
479
|
+
self._seen(query)
|
|
480
|
+
info = self.workers.get(query.get("w"))
|
|
481
|
+
if info is None:
|
|
482
|
+
return 404, b""
|
|
483
|
+
if body:
|
|
484
|
+
data = json.loads(body)
|
|
485
|
+
info["telemetry"] = _clean_telemetry(data.get("telemetry"))
|
|
486
|
+
applied = data.get("applied", 0)
|
|
487
|
+
info["applied"] = applied if isinstance(applied, int) else 0
|
|
488
|
+
return 200, {"settings": info["settings"]}
|
|
489
|
+
|
|
490
|
+
def _assignment(self, query, body):
|
|
491
|
+
with self.cond:
|
|
492
|
+
self._seen(query)
|
|
493
|
+
if self.closed:
|
|
494
|
+
if query.get("w") in self.workers:
|
|
495
|
+
self.workers[query["w"]]["bye"] = True
|
|
496
|
+
self.cond.notify_all()
|
|
497
|
+
return 200, {"done": True}
|
|
498
|
+
stages = self.plan or []
|
|
499
|
+
if self.job is not None:
|
|
500
|
+
for i, stage in enumerate(stages):
|
|
501
|
+
if stage["w"] == query["w"]:
|
|
502
|
+
neighbour = lambda j: None if j < 0 or j >= len(stages) else {
|
|
503
|
+
"w": stages[j]["w"], "addrs": self.workers[stages[j]["w"]]["addrs"], "token": self.workers[stages[j]["w"]]["token"]}
|
|
504
|
+
return 200, {"run": self.run_id, "epoch": self.epoch, "seq": self.seq_base, "range": stage["range"], "on_gpu": stage.get("on_gpu"), "step": self.step,
|
|
505
|
+
"restore": self.restore, "prev": neighbour(i - 1), "next": neighbour(i + 1), "replica": self._replica_target(query["w"]),
|
|
506
|
+
"keep_from": self.keep_from(), "job": self.job, "settings": self.workers[query["w"]]["settings"]}
|
|
507
|
+
info = self.workers.get(query.get("w"), {})
|
|
508
|
+
return 200, {"wait": True, "run": self.run_id if self.job is not None else None, "left_out": info.get("why_left_out") if info.get("banned") else None}
|
|
509
|
+
|
|
510
|
+
def _epoch(self, query, body):
|
|
511
|
+
with self.cond:
|
|
512
|
+
self._seen(query)
|
|
513
|
+
return 200, {"epoch": self.epoch, "finished": self.closed, "keep_from": self.keep_from()}
|
|
514
|
+
|
|
515
|
+
def _ready(self, query, body):
|
|
516
|
+
with self.cond:
|
|
517
|
+
self._seen(query)
|
|
518
|
+
self.ready.add((query["w"], int(query["epoch"])))
|
|
519
|
+
self.cond.notify_all()
|
|
520
|
+
return 200, b""
|
|
521
|
+
|
|
522
|
+
def _done(self, query, body):
|
|
523
|
+
with self.cond:
|
|
524
|
+
self._seen(query)
|
|
525
|
+
self.reports[(query["w"], int(query["epoch"]), int(query["seq"]))] = json.loads(body) if body else {}
|
|
526
|
+
self.cond.notify_all()
|
|
527
|
+
return 200, b""
|
|
528
|
+
|
|
529
|
+
def _answers(self, wid: str) -> bool:
|
|
530
|
+
return any(ping(url, 10) for url in self.workers[wid]["addrs"])
|
|
531
|
+
|
|
532
|
+
def _lose(self, wid: str, why: str):
|
|
533
|
+
info = self.workers[wid]
|
|
534
|
+
if info["alive"]:
|
|
535
|
+
info["alive"] = False
|
|
536
|
+
self.event(f"{info['name']} {why}")
|
|
537
|
+
if self.job is not None and any(p["w"] == wid for p in self.plan or []):
|
|
538
|
+
self._replan(f"{info['name']} dropped out")
|
|
539
|
+
|
|
540
|
+
def _fail(self, query, body):
|
|
541
|
+
blame = query.get("blame")
|
|
542
|
+
if blame in self.workers and not self._answers(blame):
|
|
543
|
+
with self.cond:
|
|
544
|
+
self._seen(query)
|
|
545
|
+
self._lose(blame, f"does not answer ({self.workers[query['w']]['name']} could not reach it)")
|
|
546
|
+
return 200, b""
|
|
547
|
+
with self.cond:
|
|
548
|
+
self._seen(query)
|
|
549
|
+
info = self.workers[query["w"]]
|
|
550
|
+
if query.get("switched") and self.job is not None:
|
|
551
|
+
info["no_mlx"] = self.job["repo"]
|
|
552
|
+
self._replan(f"{info['name']} trains this model with PyTorch instead of MLX, which failed on it: {body.decode()[:200]}")
|
|
553
|
+
return 200, b""
|
|
554
|
+
oom = _number(query.get("oom"))
|
|
555
|
+
room = info.get("cap_gb") or sum(d["gb"] for d in info["devices"])
|
|
556
|
+
if oom is not None and room > 1.0:
|
|
557
|
+
cap = round(max(0.5, 0.85 * min(room, oom or room)), 1)
|
|
558
|
+
info["cap_gb"], info["oom_capped"] = cap, True
|
|
559
|
+
why = f"{info['name']} ran out of memory; it now gets layers for at most {cap} GB (set its cap in the dashboard to change this)"
|
|
560
|
+
if self.job is not None:
|
|
561
|
+
self._replan(why)
|
|
562
|
+
else:
|
|
563
|
+
self.event(why)
|
|
564
|
+
return 200, b""
|
|
565
|
+
info["fails"] += 1
|
|
566
|
+
why = f"{info['name']} reported an error: {body.decode()[:300]}"
|
|
567
|
+
if info["fails"] >= self.max_failures:
|
|
568
|
+
info["alive"], info["banned"] = False, True
|
|
569
|
+
info["why_left_out"] = body.decode()[:300]
|
|
570
|
+
why += f" ({info['fails']} times in a row, it is left out)"
|
|
571
|
+
if self.job is not None:
|
|
572
|
+
self._replan(why)
|
|
573
|
+
else:
|
|
574
|
+
self.event(why)
|
|
575
|
+
return 200, b""
|
|
576
|
+
|
|
577
|
+
def _units(self) -> list[int]:
|
|
578
|
+
return list(range(self.job["layers"]))
|
|
579
|
+
|
|
580
|
+
def _path(self, unit: int, step: int) -> str:
|
|
581
|
+
return os.path.join(self.ckpt_dir, f"{self.run_id}_{unit}_{step}.npz")
|
|
582
|
+
|
|
583
|
+
def _available(self, unit: int, step: int) -> bool:
|
|
584
|
+
holders = self.ckpt.get(unit, {}).get(step, set())
|
|
585
|
+
return any(h == "coord" or (h in self.workers and self.workers[h]["alive"]) for h in holders)
|
|
586
|
+
|
|
587
|
+
def complete_step(self) -> int:
|
|
588
|
+
if self.job is None:
|
|
589
|
+
return -1
|
|
590
|
+
steps = None
|
|
591
|
+
for unit in self._units():
|
|
592
|
+
got = {st for st in self.ckpt.get(unit, {}) if self._available(unit, st)}
|
|
593
|
+
steps = got if steps is None else steps & got
|
|
594
|
+
return max(steps) if steps else -1
|
|
595
|
+
|
|
596
|
+
def keep_from(self) -> int:
|
|
597
|
+
done = self.complete_step()
|
|
598
|
+
return done if self.protect is None else min(done, self.protect)
|
|
599
|
+
|
|
600
|
+
def _replica_target(self, wid: str) -> dict | None:
|
|
601
|
+
mode = self.job.get("peer_replicas", "auto")
|
|
602
|
+
if mode == "never" or not self.plan:
|
|
603
|
+
return None
|
|
604
|
+
ring = [p["w"] for p in self.plan if mode == "always" or not self.workers[p["w"]].get("near")]
|
|
605
|
+
if wid not in ring or len(ring) < 2:
|
|
606
|
+
return None
|
|
607
|
+
target = ring[(ring.index(wid) + 1) % len(ring)]
|
|
608
|
+
return {"w": target, "addrs": self.workers[target]["addrs"], "token": self.workers[target]["token"]}
|
|
609
|
+
|
|
610
|
+
def _prune(self):
|
|
611
|
+
low = self.keep_from()
|
|
612
|
+
for unit, steps in self.ckpt.items():
|
|
613
|
+
for old in [st for st in steps if st < low]:
|
|
614
|
+
if "coord" in steps.pop(old):
|
|
615
|
+
try:
|
|
616
|
+
os.remove(self._path(unit, old))
|
|
617
|
+
except FileNotFoundError:
|
|
618
|
+
pass
|
|
619
|
+
floor = self.keep_from()
|
|
620
|
+
if floor > self.oplog_after:
|
|
621
|
+
self._set_oplog([op for op in self.oplog if op["step"] > floor])
|
|
622
|
+
self.oplog_after = floor
|
|
623
|
+
|
|
624
|
+
def _add(self, unit: int, step: int, holder: str):
|
|
625
|
+
self.ckpt.setdefault(unit, {}).setdefault(step, set()).add(holder)
|
|
626
|
+
|
|
627
|
+
def _ckpt_put(self, query, body):
|
|
628
|
+
if query.get("run") and query["run"] != self.run_id:
|
|
629
|
+
return 409, {"error": "this checkpoint belongs to a run that has ended"}
|
|
630
|
+
unit, step = int(query["layer"]), int(query["step"])
|
|
631
|
+
path = self._path(unit, step)
|
|
632
|
+
with open(path + ".part", "wb") as f:
|
|
633
|
+
f.write(body)
|
|
634
|
+
replace_file(path + ".part", path)
|
|
635
|
+
with self.cond:
|
|
636
|
+
self._add(unit, step, "coord")
|
|
637
|
+
self._prune()
|
|
638
|
+
self.cond.notify_all()
|
|
639
|
+
return 200, b""
|
|
640
|
+
|
|
641
|
+
def _export_put(self, query, body):
|
|
642
|
+
if query.get("run") and query["run"] != self.run_id:
|
|
643
|
+
return 409, {"error": "this export belongs to a run that has ended"}
|
|
644
|
+
path = self._path(int(query["layer"]), int(query["step"])) + ".weights"
|
|
645
|
+
with open(path + ".part", "wb") as f:
|
|
646
|
+
f.write(body)
|
|
647
|
+
replace_file(path + ".part", path)
|
|
648
|
+
return 200, b""
|
|
649
|
+
|
|
650
|
+
def _have(self, query, body):
|
|
651
|
+
info = json.loads(body)
|
|
652
|
+
if query.get("run") and query["run"] != self.run_id:
|
|
653
|
+
return 409, {"error": "this checkpoint belongs to a run that has ended"}
|
|
654
|
+
with self.cond:
|
|
655
|
+
self._seen(query)
|
|
656
|
+
for unit in info["layers"]:
|
|
657
|
+
for holder in info["holders"]:
|
|
658
|
+
if holder in self.workers:
|
|
659
|
+
self._add(int(unit), int(info["step"]), holder)
|
|
660
|
+
self._prune()
|
|
661
|
+
self.cond.notify_all()
|
|
662
|
+
return 200, b""
|
|
663
|
+
|
|
664
|
+
def _where(self, query, body):
|
|
665
|
+
unit, step, epoch = int(query["layer"]), int(query["step"]), int(query.get("epoch", -1))
|
|
666
|
+
with self.cond:
|
|
667
|
+
self.cond.wait_for(lambda: self._available(unit, step) or (epoch >= 0 and self.epoch != epoch), timeout=float(query.get("wait", 60)))
|
|
668
|
+
if epoch >= 0 and self.epoch != epoch:
|
|
669
|
+
return 409, b""
|
|
670
|
+
holders = self.ckpt.get(unit, {}).get(step, set())
|
|
671
|
+
out = [{"w": "coord"}] if "coord" in holders else []
|
|
672
|
+
out += [{"w": h, "addrs": self.workers[h]["addrs"], "token": self.workers[h]["token"]} for h in sorted(holders)
|
|
673
|
+
if h in self.workers and self.workers[h]["alive"] and h != query.get("w")]
|
|
674
|
+
if query.get("w") in holders:
|
|
675
|
+
out.insert(0, {"w": query["w"]})
|
|
676
|
+
return (200, {"holders": out}) if out else (404, b"")
|
|
677
|
+
|
|
678
|
+
def _ckpt_get(self, query, body):
|
|
679
|
+
unit, step = int(query["layer"]), int(query["step"])
|
|
680
|
+
with self.cond:
|
|
681
|
+
if "coord" not in self.ckpt.get(unit, {}).get(step, set()):
|
|
682
|
+
return 404, b""
|
|
683
|
+
with open(self._path(unit, step), "rb") as f:
|
|
684
|
+
return 200, f.read()
|
|
685
|
+
|
|
686
|
+
def _job(self) -> dict | None:
|
|
687
|
+
"""The job the split is worked out for: a run that plan_for asks about, on its own thread only, or the running one."""
|
|
688
|
+
return getattr(self._planning, "job", None) or self.job
|
|
689
|
+
|
|
690
|
+
def _nodes(self, alive: list[str]) -> list[Node]:
|
|
691
|
+
job, nodes = self._job(), []
|
|
692
|
+
usable = self._usable(alive)
|
|
693
|
+
left_out = [w for w in alive if w not in usable]
|
|
694
|
+
told = self.__dict__.setdefault("_told_q4", set())
|
|
695
|
+
fresh = [w for w in left_out if (self.run_id, w) not in told and (self.run_id, w) not in self.told_bnb]
|
|
696
|
+
if fresh and not getattr(self._planning, "previewing", False):
|
|
697
|
+
told.update((self.run_id, w) for w in fresh)
|
|
698
|
+
names = ", ".join(self.workers[w]["name"] for w in fresh)
|
|
699
|
+
self.event(f"{names} sit{'s' if len(fresh) == 1 else ''} this run out: a bitsandbytes 4-bit model needs a GPU bitsandbytes "
|
|
700
|
+
f"runs on (NVIDIA, or a recent AMD one), or an MLX 4-bit version (mlx_model=) on Apple Silicon")
|
|
701
|
+
for w in usable:
|
|
702
|
+
alive = usable
|
|
703
|
+
info = self.workers[w]
|
|
704
|
+
settings = info["settings"]
|
|
705
|
+
kind = info["devices"][0]["kind"]
|
|
706
|
+
devices = [(i, d) for i, d in enumerate(info["devices"]) if kind != "cuda" or not settings.get("gpus") or i in settings["gpus"]]
|
|
707
|
+
cap_gb, gpu_caps = info.get("cap_gb"), settings.get("gpu_caps") or {}
|
|
708
|
+
share = cap_gb / len(devices) if cap_gb else 1e9
|
|
709
|
+
cap = sum(max(0.0, min(d["gb"] * 0.92 - 0.6, gpu_caps.get(str(i), share))) for i, d in devices)
|
|
710
|
+
if cap_gb:
|
|
711
|
+
cap = min(cap, cap_gb)
|
|
712
|
+
if kind in SHARED_MEMORY:
|
|
713
|
+
cap = min(cap, cap_gb or info["devices"][0]["gb"] * SHARED_MEMORY[kind])
|
|
714
|
+
guess = self._guess(w)
|
|
715
|
+
speed = self.measured.get(w) or guess * self._calibration(alive)
|
|
716
|
+
engine = self._engine(info)
|
|
717
|
+
sizes = {**job, **job.get("sizes", {}).get("mlx" if engine == "mlx" else "torch", {})}
|
|
718
|
+
fixed = sizes.get("overhead_gb", 0.5)
|
|
719
|
+
driver = job.get("driver") or {}
|
|
720
|
+
if info.get("identity") and info["identity"] in driver.get("identities", []):
|
|
721
|
+
fixed += driver.get("gb", 0.0)
|
|
722
|
+
per_layer = sizes.get("layer_gb", 0.0) * (2.0 if engine == "cpu" and job.get("mode", "lora") != "full" else 1.0)
|
|
723
|
+
spill = {}
|
|
724
|
+
if engine == "cuda" and settings.get("ram_cap") and job.get("kind") != "q4":
|
|
725
|
+
cpu_speed = self.measured_spill.get(w) or DEFAULT_SPEED["cpu"] * self._calibration(alive)
|
|
726
|
+
cpu_layer = sizes.get("layer_gb", 0.0) * (1.0 if job.get("mode", "lora") == "full" else 2.0)
|
|
727
|
+
spill = {"spill_gb": settings["ram_cap"], "spill_layer_gb": cpu_layer, "spill_sec_per_layer": cpu_speed}
|
|
728
|
+
low, high = layer_bounds(settings.get("layers"), job["layers"])
|
|
729
|
+
if low and info.get("oom_capped") and fixed + low * per_layer > cap:
|
|
730
|
+
fits = max(0, int((cap - fixed) / per_layer)) if per_layer else low
|
|
731
|
+
if not getattr(self._planning, "previewing", False) and info.get("told_oom_layers") != (self.run_id, fits):
|
|
732
|
+
info["told_oom_layers"] = (self.run_id, fits)
|
|
733
|
+
self.event(f"{info['name']} ran out of memory with {low} layers, so it takes {fits} until its memory cap is set again")
|
|
734
|
+
low, high = min(low, fits), min(high or fits, fits)
|
|
735
|
+
nodes.append(Node(w, cap, fixed, speed, layer_gb=per_layer, link_sec=self.measured_link.get(w, 0.0), min_layers=low, max_layers=high,
|
|
736
|
+
**spill))
|
|
737
|
+
return nodes if usable else []
|
|
738
|
+
|
|
739
|
+
def _usable(self, alive: list[str]) -> list[str]:
|
|
740
|
+
job = self._job()
|
|
741
|
+
kind = lambda w: self.workers[w]["devices"][0]["kind"]
|
|
742
|
+
if job["kind"] != "q4":
|
|
743
|
+
return list(alive)
|
|
744
|
+
return [w for w in alive if (kind(w) == "cuda" and self.workers[w]["devices"][0].get("q4", True) and self._has_bnb(w))
|
|
745
|
+
or (kind(w) == "mlx" and job.get("mlx_repo"))]
|
|
746
|
+
|
|
747
|
+
def _tell_slow_kernels(self, workers: list[str]):
|
|
748
|
+
"""A model with linear-attention blocks (Qwen3.5, Qwen3-Next) runs them far faster on NVIDIA GPUs with
|
|
749
|
+
flash-linear-attention and causal-conv1d; devices without them work, slowly, so the events say which."""
|
|
750
|
+
if not (self.job or {}).get("linear_attention"):
|
|
751
|
+
return
|
|
752
|
+
told = self.__dict__.setdefault("_told_kernels", set())
|
|
753
|
+
slow = []
|
|
754
|
+
for w in workers:
|
|
755
|
+
info = self.workers.get(w) or {}
|
|
756
|
+
libraries = info.get("libraries") or {}
|
|
757
|
+
if info.get("devices", [{}])[0].get("kind") == "cuda" and not info["devices"][0].get("amd") and "transformers" in libraries \
|
|
758
|
+
and not ("flash-linear-attention" in libraries and "causal-conv1d" in libraries) and (self.run_id, w) not in told:
|
|
759
|
+
told.add((self.run_id, w))
|
|
760
|
+
slow.append(info.get("name", w))
|
|
761
|
+
if slow:
|
|
762
|
+
self.event(f"{', '.join(slow)} run{'s' if len(slow) == 1 else ''} this model's linear-attention blocks without their fast "
|
|
763
|
+
"kernels, which is much slower: run pip install flash-linear-attention causal-conv1d there and join again")
|
|
764
|
+
|
|
765
|
+
def _has_bnb(self, w: str) -> bool:
|
|
766
|
+
"""Whether a CUDA device has the bitsandbytes its transformers needs for 4-bit layers; if not, it sits out 4-bit runs and
|
|
767
|
+
the events say what to install."""
|
|
768
|
+
libraries = self.workers[w].get("libraries") or {}
|
|
769
|
+
if "transformers" not in libraries:
|
|
770
|
+
return True
|
|
771
|
+
have, need = libraries.get("bitsandbytes"), libraries.get("bitsandbytes-needed")
|
|
772
|
+
if have and (not need or _version_tuple(have) >= _version_tuple(need)):
|
|
773
|
+
return True
|
|
774
|
+
key = (self.run_id, w)
|
|
775
|
+
if key not in self.told_bnb and not getattr(self._planning, "previewing", False):
|
|
776
|
+
self.told_bnb.add(key)
|
|
777
|
+
want = f"bitsandbytes>={need}" if need else "bitsandbytes"
|
|
778
|
+
self.event(f"{self.workers[w]['name']} sits out this 4-bit run: it needs {want} (it has {have or 'none'}); "
|
|
779
|
+
f"run pip install -U \"{want}\" on it and join again")
|
|
780
|
+
return False
|
|
781
|
+
|
|
782
|
+
def _cost(self, stages) -> float:
|
|
783
|
+
"""Seconds a step takes with this split: the pieces of a batch follow each other through the devices, so the first one
|
|
784
|
+
goes through every stage and each further one adds the slowest stage. With many pieces that is the slowest stage; with
|
|
785
|
+
one, the sum of all of them."""
|
|
786
|
+
secs = [st.sec for st in stages]
|
|
787
|
+
pieces = self._job().get("pieces") or self._job().get("micro", 8)
|
|
788
|
+
return sum(secs) + (max(1, pieces) - 1) * max(secs)
|
|
789
|
+
|
|
790
|
+
def _stages(self, order: list[str]):
|
|
791
|
+
return plan(self._nodes(order), self._job()["layers"], self._job().get("layer_gb", 0.0)) if order else None
|
|
792
|
+
|
|
793
|
+
def _best_stages(self, alive: list[str]):
|
|
794
|
+
"""The fastest split, and it leaves out devices that only slow the run down when the others can hold the model without
|
|
795
|
+
them. The model's ends run on the training machine, so devices differ only by speed and memory: the order tried is the
|
|
796
|
+
joining order (devices on one network stay neighbours) and the roomiest-first one."""
|
|
797
|
+
placed = lambda w: self.workers[w]["settings"].get("order")
|
|
798
|
+
pinned = lambda w: layer_bounds(self.workers[w]["settings"].get("layers"), self._job()["layers"])[0] > 0 and not self.workers[w].get("oom_capped")
|
|
799
|
+
|
|
800
|
+
def best_for(group):
|
|
801
|
+
found = None
|
|
802
|
+
nodes = {n.name: n for n in self._nodes(group)}
|
|
803
|
+
spare = lambda w: nodes[w].cap_gb - nodes[w].fixed_gb if w in nodes else -1e9
|
|
804
|
+
if any(placed(w) is not None for w in group):
|
|
805
|
+
orders = [sorted(group, key=lambda w: (placed(w) is None, placed(w) or 0, group.index(w)))]
|
|
806
|
+
else:
|
|
807
|
+
orders = [list(group)]
|
|
808
|
+
roomy = sorted(group, key=spare, reverse=True)
|
|
809
|
+
if roomy != orders[0]:
|
|
810
|
+
orders.append(roomy)
|
|
811
|
+
for order in orders:
|
|
812
|
+
stages = self._stages(order)
|
|
813
|
+
if stages:
|
|
814
|
+
cost = self._cost(stages)
|
|
815
|
+
if found is None or cost < found[0] - 1e-9:
|
|
816
|
+
found = (cost, stages)
|
|
817
|
+
return found
|
|
818
|
+
group = list(alive)
|
|
819
|
+
best = best_for(group)
|
|
820
|
+
while best is None and len(group) > 1:
|
|
821
|
+
trials = [(best_for([w for w in group if w != out]), out) for out in group if not pinned(out)]
|
|
822
|
+
feasible = [(t, out) for t, out in trials if t]
|
|
823
|
+
if feasible:
|
|
824
|
+
best, out = min(feasible, key=lambda x: x[0][0])
|
|
825
|
+
group.remove(out)
|
|
826
|
+
break
|
|
827
|
+
nodes = {n.name: n for n in self._nodes(group)}
|
|
828
|
+
loose = [w for w in group if not pinned(w)]
|
|
829
|
+
if not loose:
|
|
830
|
+
break
|
|
831
|
+
group.remove(min(loose, key=lambda w: nodes[w].cap_gb - nodes[w].fixed_gb if w in nodes else -1e9))
|
|
832
|
+
best = best_for(group)
|
|
833
|
+
while best and len(group) > 1:
|
|
834
|
+
trials = [(best_for([w for w in group if w != out]), out) for out in group if not pinned(out)]
|
|
835
|
+
trials = [(t, out) for t, out in trials if t]
|
|
836
|
+
if not trials:
|
|
837
|
+
break
|
|
838
|
+
(cost, stages), out = min(trials, key=lambda x: x[0][0])
|
|
839
|
+
if cost >= 0.9 * best[0]:
|
|
840
|
+
break
|
|
841
|
+
group.remove(out)
|
|
842
|
+
best = (cost, stages)
|
|
843
|
+
return best[1] if best else None
|
|
844
|
+
|
|
845
|
+
def _engine(self, info: dict) -> str:
|
|
846
|
+
"""What the device trains this run with: "mlx", "mps" (a Mac with PyTorch, for models MLX does not run), "cuda" or "cpu"."""
|
|
847
|
+
kind = info["devices"][0]["kind"]
|
|
848
|
+
if kind == "mlx" and not (self._job() and self._job().get("mlx_ok") and info.get("backend") == "mlx"
|
|
849
|
+
and info.get("no_mlx") != self._job().get("repo")):
|
|
850
|
+
return "mps"
|
|
851
|
+
return kind
|
|
852
|
+
|
|
853
|
+
def _guess(self, w: str) -> float:
|
|
854
|
+
info = self.workers[w]
|
|
855
|
+
chosen = info["settings"].get("gpus") if info["devices"][0]["kind"] == "cuda" else None
|
|
856
|
+
return DEFAULT_SPEED.get(self._engine(info), 4.0) / len(chosen or info["devices"])
|
|
857
|
+
|
|
858
|
+
def _calibration(self, alive: list[str]) -> float:
|
|
859
|
+
ratios = sorted(self.measured[w] / self._guess(w) for w in alive if w in self.measured)
|
|
860
|
+
return ratios[len(ratios) // 2] if ratios else 1.0
|
|
861
|
+
|
|
862
|
+
def _measure(self, reports: dict[str, dict]):
|
|
863
|
+
for w, r in reports.items():
|
|
864
|
+
cores = r.get("cores")
|
|
865
|
+
if not cores or not sum(c[0] for c in cores):
|
|
866
|
+
continue
|
|
867
|
+
fast = [c for c in cores if len(c) < 3 or c[2] != "spill"]
|
|
868
|
+
spill = [c for c in cores if len(c) > 2 and c[2] == "spill"]
|
|
869
|
+
for found, store in ((fast, self.measured), (spill, self.measured_spill)):
|
|
870
|
+
if found and sum(c[0] for c in found):
|
|
871
|
+
per_layer = max(c[1] for c in found) / sum(c[0] for c in found)
|
|
872
|
+
store[w] = per_layer if w not in store else 0.5 * store[w] + 0.5 * per_layer
|
|
873
|
+
send = float(r.get("send") or 0.0)
|
|
874
|
+
self.measured_link[w] = send if w not in self.measured_link else 0.5 * self.measured_link[w] + 0.5 * send
|
|
875
|
+
|
|
876
|
+
def preview(self, overrides: dict[str, dict] | None = None) -> list[dict] | None:
|
|
877
|
+
"""The split the devices would get with these settings changed ({device id: {setting: value}}), or None if none fits."""
|
|
878
|
+
stages, _ = self._try(overrides)
|
|
879
|
+
return [{"w": st.name, "name": self.workers[st.name]["name"], "range": [st.first, st.last], "gb": st.gb, "sec": st.sec,
|
|
880
|
+
"on_gpu": st.on_gpu} for st in stages] if stages else None
|
|
881
|
+
|
|
882
|
+
def plan_for(self, job: dict) -> dict:
|
|
883
|
+
"""How a run of this job would be split over the devices here now, or why it would not fit; changes nothing. While a run
|
|
884
|
+
is going, it answers for the devices as they are, the running one included."""
|
|
885
|
+
with self.cond:
|
|
886
|
+
pending, self._planning.previewing, self._planning.job = self.pending, True, job
|
|
887
|
+
try:
|
|
888
|
+
alive = [w for w, v in self.workers.items() if v["alive"] and v["settings"].get("enabled", True)]
|
|
889
|
+
stages = self._best_stages(alive) if alive else None
|
|
890
|
+
self.pending = False
|
|
891
|
+
why = None if stages else (self._why_no_plan() or "no device has joined yet")
|
|
892
|
+
finally:
|
|
893
|
+
self.pending, self._planning.previewing, self._planning.job = pending, False, None
|
|
894
|
+
return {"layers": job["layers"], "layer_gb": job.get("layer_gb"), "why": why,
|
|
895
|
+
"plan": [{"w": st.name, "name": self.workers[st.name]["name"], "range": [st.first, st.last], "gb": st.gb, "sec": st.sec,
|
|
896
|
+
"on_gpu": st.on_gpu}
|
|
897
|
+
for st in stages] if stages else None}
|
|
898
|
+
|
|
899
|
+
def _try(self, overrides: dict[str, dict] | None):
|
|
900
|
+
"""The split with some devices' settings changed, and why there is none, without changing anything or telling anyone."""
|
|
901
|
+
with self.cond:
|
|
902
|
+
if self.job is None:
|
|
903
|
+
return None, None
|
|
904
|
+
saved = {w: dict(self.workers[w]) for w in (overrides or {})}
|
|
905
|
+
measured, links, spills, self._planning.previewing = dict(self.measured), dict(self.measured_link), dict(self.measured_spill), True
|
|
906
|
+
try:
|
|
907
|
+
for w, change in (overrides or {}).items():
|
|
908
|
+
info = self.workers[w]
|
|
909
|
+
change = clean_settings(change, sum(1 for d in info["devices"] if d["kind"] == "cuda"))
|
|
910
|
+
info["settings"] = {**info["settings"], **change}
|
|
911
|
+
if "cap_gb" in change:
|
|
912
|
+
info["cap_gb"] = change["cap_gb"]
|
|
913
|
+
if "cap_gb" in change:
|
|
914
|
+
info.pop("oom_capped", None)
|
|
915
|
+
if "gpus" in change:
|
|
916
|
+
self.measured.pop(w, None)
|
|
917
|
+
self.measured_link.pop(w, None)
|
|
918
|
+
alive = [w for w, v in self.workers.items() if v["alive"] and v["settings"].get("enabled", True)]
|
|
919
|
+
stages = self._best_stages(alive) if alive else None
|
|
920
|
+
pending, self.pending = self.pending, False
|
|
921
|
+
why = None if stages else self._why_no_plan()
|
|
922
|
+
self.pending = pending
|
|
923
|
+
finally:
|
|
924
|
+
for w, before in saved.items():
|
|
925
|
+
self.workers[w].clear()
|
|
926
|
+
self.workers[w].update(before)
|
|
927
|
+
self.measured.clear()
|
|
928
|
+
self.measured.update(measured)
|
|
929
|
+
self.measured_link.clear()
|
|
930
|
+
self.measured_link.update(links)
|
|
931
|
+
self.measured_spill.clear()
|
|
932
|
+
self.measured_spill.update(spills)
|
|
933
|
+
self._planning.previewing = False
|
|
934
|
+
return stages, why
|
|
935
|
+
|
|
936
|
+
def _maybe_rebalance(self):
|
|
937
|
+
if not self.job.get("rebalance", True) or self.steps_in_plan < 3 or not self.plan:
|
|
938
|
+
return
|
|
939
|
+
if self.steps_in_plan > 3 and (self.steps_in_plan - 3) % (5 if len(self.workers) <= 8 else 20):
|
|
940
|
+
return
|
|
941
|
+
alive = [p["w"] for p in self.plan]
|
|
942
|
+
if any(w not in self.measured for w in alive):
|
|
943
|
+
return
|
|
944
|
+
now = self._cost([Stage(p["w"], 0, 0, 0.0, self.measured[p["w"]] * (p["range"][1] - p["range"][0]) + self.measured_link.get(p["w"], 0.0))
|
|
945
|
+
for p in self.plan])
|
|
946
|
+
everyone = [w for w, v in self.workers.items() if v["alive"] and v["settings"].get("enabled", True)]
|
|
947
|
+
stages = self._best_stages(everyone)
|
|
948
|
+
if not stages:
|
|
949
|
+
return
|
|
950
|
+
better = self._cost(stages)
|
|
951
|
+
moved = [(st.name, st.first, st.last) for st in stages] != [(p["w"], *p["range"]) for p in self.plan]
|
|
952
|
+
left = max(1, (self.job.get("expected_steps") or self.step + 100) - self.step)
|
|
953
|
+
if moved and better < 0.87 * now and (now - better) * left > self.job.get("rebalance_cost_s", 60):
|
|
954
|
+
self._replan(f"rebalancing on measured speed, compute per step {now:.1f}s -> {better:.1f}s", lost=False)
|
|
955
|
+
|
|
956
|
+
def _replan(self, why: str, lost: bool = True):
|
|
957
|
+
self.steps_in_plan = 0
|
|
958
|
+
alive = [w for w, v in self.workers.items() if v["alive"] and v["settings"].get("enabled", True)]
|
|
959
|
+
stages = self._best_stages(alive) if alive and self.job else None
|
|
960
|
+
self.epoch += 1
|
|
961
|
+
self.pending = False
|
|
962
|
+
if lost or self.plan is None:
|
|
963
|
+
self.restore = self.complete_step()
|
|
964
|
+
else:
|
|
965
|
+
self.restore = self.step - 1
|
|
966
|
+
self.protect = self.restore
|
|
967
|
+
if self.step > self.restore + 1:
|
|
968
|
+
self.event(f"rolling back to the state after step {self.restore}; steps {self.restore + 1}-{self.step - 1} will be replayed")
|
|
969
|
+
self.step = self.restore + 1
|
|
970
|
+
self.seq_base = self.seq
|
|
971
|
+
self.plan = [{"w": s.name, "range": [s.first, s.last], **({"on_gpu": s.on_gpu} if s.on_gpu is not None else {})} for s in stages] \
|
|
972
|
+
if stages else None
|
|
973
|
+
self.server.inbox.drop(lambda k: False)
|
|
974
|
+
text = ", ".join(f"{self.workers[p['w']]['name']} {p['range']}" for p in self.plan) if self.plan else "no split fits the devices"
|
|
975
|
+
idle = [self.workers[w]["name"] for w in (self._usable(alive) if self.job else []) if self.plan and w not in {p["w"] for p in self.plan}]
|
|
976
|
+
if idle:
|
|
977
|
+
text += f"; {', '.join(idle)} sit{'s' if len(idle) == 1 else ''} this run out because the others are faster without {'it' if len(idle) == 1 else 'them'}"
|
|
978
|
+
self.event(f"plan {self.epoch} ({why}): {text}")
|
|
979
|
+
self.emit("plan", {"epoch": self.epoch, "plan": self.plan})
|
|
980
|
+
self.cond.notify_all()
|
|
981
|
+
|
|
982
|
+
def _monitor(self):
|
|
983
|
+
while not self.closed:
|
|
984
|
+
time.sleep(1)
|
|
985
|
+
with self.cond:
|
|
986
|
+
for w, info in self.workers.items():
|
|
987
|
+
if info["alive"] and time.time() - info["seen"] > self.heartbeat_timeout:
|
|
988
|
+
self._lose(w, f"lost (silent for {time.time() - info['seen']:.0f}s)")
|
|
989
|
+
break
|
|
990
|
+
|
|
991
|
+
def set_device(self, wid: str, **changes) -> dict:
|
|
992
|
+
with self.cond:
|
|
993
|
+
info = self.workers[wid]
|
|
994
|
+
gpu_count = sum(1 for d in info["devices"] if d["kind"] == "cuda")
|
|
995
|
+
changes = clean_settings(changes, gpu_count)
|
|
996
|
+
shaping = any(k in changes for k in ("cap_gb", "enabled", "layers", "gpus", "gpu_caps", "order", "ram_cap"))
|
|
997
|
+
if self.job is not None and shaping and info["alive"] and changes.get("enabled", True):
|
|
998
|
+
stages, why = self._try({wid: changes})
|
|
999
|
+
if not stages and why:
|
|
1000
|
+
raise PoolError(f"not changed, since the run could not go on: {why}")
|
|
1001
|
+
moved = {k: v for k, v in changes.items() if info["settings"].get(k) != v}
|
|
1002
|
+
settings = {**info["settings"], **changes, "version": info["settings"].get("version", 0) + 1}
|
|
1003
|
+
if "cap_gb" in changes:
|
|
1004
|
+
info.pop("oom_capped", None)
|
|
1005
|
+
info["settings"] = settings
|
|
1006
|
+
for key in ("name", "cap_gb"):
|
|
1007
|
+
if key in changes:
|
|
1008
|
+
info[key] = changes[key]
|
|
1009
|
+
replan = self.job is not None and shaping
|
|
1010
|
+
if "gpus" in changes:
|
|
1011
|
+
self.measured.pop(wid, None)
|
|
1012
|
+
self.measured_spill.pop(wid, None)
|
|
1013
|
+
self.measured_link.pop(wid, None)
|
|
1014
|
+
if moved:
|
|
1015
|
+
self.event(f"{info['name']} settings changed: " + ", ".join(f"{k} {'auto' if v is None else v}" for k, v in moved.items()))
|
|
1016
|
+
self._remember(info)
|
|
1017
|
+
if replan:
|
|
1018
|
+
self.pending = True
|
|
1019
|
+
self.cond.notify_all()
|
|
1020
|
+
return settings
|
|
1021
|
+
|
|
1022
|
+
def _remember(self, info: dict):
|
|
1023
|
+
if not self.settings_file or not info.get("identity"):
|
|
1024
|
+
return
|
|
1025
|
+
self.saved_settings[info["identity"]] = {k: info["settings"].get(k) for k in DEVICE_SETTINGS if k in info["settings"]}
|
|
1026
|
+
try:
|
|
1027
|
+
os.makedirs(os.path.dirname(self.settings_file), exist_ok=True)
|
|
1028
|
+
with open(self.settings_file + ".tmp", "w", encoding="utf-8") as f:
|
|
1029
|
+
json.dump(self.saved_settings, f, indent=1)
|
|
1030
|
+
replace_file(self.settings_file + ".tmp", self.settings_file)
|
|
1031
|
+
except OSError:
|
|
1032
|
+
pass
|
|
1033
|
+
|
|
1034
|
+
def drain(self, wid: str):
|
|
1035
|
+
self.set_device(wid, enabled=False)
|
|
1036
|
+
|
|
1037
|
+
def remove(self, wid: str):
|
|
1038
|
+
with self.cond:
|
|
1039
|
+
info = self.workers[wid]
|
|
1040
|
+
info["removed"] = True
|
|
1041
|
+
info["settings"]["enabled"] = False
|
|
1042
|
+
self._lose(wid, "was removed")
|
|
1043
|
+
if info.get("identity"):
|
|
1044
|
+
self.identities.pop(info["identity"], None)
|
|
1045
|
+
for t in [t for t, w in self.device_tokens.items() if w == wid]:
|
|
1046
|
+
del self.device_tokens[t]
|
|
1047
|
+
self._save_state()
|
|
1048
|
+
|
|
1049
|
+
def devices(self) -> list[dict]:
|
|
1050
|
+
with self.cond:
|
|
1051
|
+
out = []
|
|
1052
|
+
for w, info in self.workers.items():
|
|
1053
|
+
stage = next((p for p in self.plan or [] if p["w"] == w), None)
|
|
1054
|
+
status = "removed" if info.get("removed") else "banned" if info.get("banned") else "offline" if not info["alive"] else \
|
|
1055
|
+
"disabled" if not info["settings"].get("enabled", True) else "training" if stage and self.job else "idle"
|
|
1056
|
+
out.append({"id": w, "name": info["name"], "status": status, "backend": info.get("backend"), "devices": info["devices"],
|
|
1057
|
+
"cap_gb": info.get("cap_gb"), "measured_s_per_layer": self.measured.get(w), "link_s": self.measured_link.get(w),
|
|
1058
|
+
"layers": stage["range"] if stage else None, "on_gpu": stage.get("on_gpu") if stage else None, "last_seen_s": round(time.time() - info["seen"], 1),
|
|
1059
|
+
"telemetry": info.get("telemetry", {}), "settings": info["settings"], "applied": info.get("applied", 0),
|
|
1060
|
+
"near": info.get("near"), "version": info.get("version"),
|
|
1061
|
+
"libraries": info.get("libraries", {}), "why_left_out": info.get("why_left_out") if info.get("banned") else None})
|
|
1062
|
+
return out
|
|
1063
|
+
|
|
1064
|
+
def status(self) -> dict:
|
|
1065
|
+
with self.cond:
|
|
1066
|
+
return {"version": __version__, "run": self.run_id if self.job else None, "last_run": self.run_id, "job": self.job, "step": self.step, "epoch": self.epoch,
|
|
1067
|
+
"plan": [{**p, "name": self.workers[p["w"]]["name"]} for p in self.plan or []] if self.job else None,
|
|
1068
|
+
"devices": len([w for w in self.workers.values() if w["alive"]]), "history": _thin(self.history, 400), "steps_done": len(self.history),
|
|
1069
|
+
"trained_s": round(sum(h.get("seconds") or 0.0 for h in self.history), 1),
|
|
1070
|
+
"events": self.events[-50:], "runs": self.runs[-20:], "waiting": self.waiting()}
|
|
1071
|
+
|
|
1072
|
+
def set_run(self, rebalance=None, resplit: bool = False, expected_steps: int | None = None) -> dict:
|
|
1073
|
+
"""Change the running run: rebalance turns moving layers to faster devices on or off; resplit splits the layers again now
|
|
1074
|
+
(after changing devices' settings, or to undo moves); expected_steps is how long the run is, which rebalancing weighs
|
|
1075
|
+
moves against (the Trainer and the built-in loops tell it themselves)."""
|
|
1076
|
+
with self.cond:
|
|
1077
|
+
if self.job is None:
|
|
1078
|
+
raise PoolError("no run is going on; to start one without rebalancing, pass rebalance=False to it")
|
|
1079
|
+
if expected_steps:
|
|
1080
|
+
self.job["expected_steps"] = int(expected_steps)
|
|
1081
|
+
if rebalance is not None:
|
|
1082
|
+
self.job["rebalance"] = bool(rebalance)
|
|
1083
|
+
self.event(f"rebalancing turned {'on' if rebalance else 'off'}")
|
|
1084
|
+
if resplit:
|
|
1085
|
+
self.pending = True
|
|
1086
|
+
self.event("splitting the layers again, as asked")
|
|
1087
|
+
self.cond.notify_all()
|
|
1088
|
+
return {"rebalance": self.job.get("rebalance", True), "expected_steps": self.job.get("expected_steps")}
|
|
1089
|
+
|
|
1090
|
+
def start_run(self, job: dict, run_id: str | None = None) -> str:
|
|
1091
|
+
with self.op_lock, self.cond:
|
|
1092
|
+
if self.job is not None:
|
|
1093
|
+
raise PoolError(f"run {self.run_id} is still active; end it first")
|
|
1094
|
+
if job.get("mode", "lora") == "full" and job.get("kind") == "q4":
|
|
1095
|
+
raise PoolError("full fine-tuning needs a model in 16/32-bit; a 4-bit model can only be trained with LoRA")
|
|
1096
|
+
if run_id is not None and not re.fullmatch(r"[A-Za-z0-9._-]{1,64}", run_id) or run_id in (".", ".."):
|
|
1097
|
+
raise PoolError(f"run name {run_id!r}: use up to 64 letters, digits, '.', '_' or '-'")
|
|
1098
|
+
self.job = dict(job)
|
|
1099
|
+
self.run_id = run_id or time.strftime("run-%Y%m%d-%H%M%S-") + secrets.token_hex(2)
|
|
1100
|
+
os.makedirs(self.ckpt_dir, exist_ok=True)
|
|
1101
|
+
self.step, self.restore, self.protect = 0, -1, None
|
|
1102
|
+
self.ckpt = {}
|
|
1103
|
+
for name in os.listdir(self.ckpt_dir):
|
|
1104
|
+
if name.endswith((".npz", ".weights", ".part")):
|
|
1105
|
+
try:
|
|
1106
|
+
os.remove(os.path.join(self.ckpt_dir, name))
|
|
1107
|
+
except OSError:
|
|
1108
|
+
pass
|
|
1109
|
+
self._set_oplog([])
|
|
1110
|
+
shutil.rmtree(os.path.join(self.ckpt_dir, "replay"), ignore_errors=True)
|
|
1111
|
+
self.oplog_after = -1
|
|
1112
|
+
self._good_steps = 0
|
|
1113
|
+
self._scales = {}
|
|
1114
|
+
self._grad_sq = 0.0
|
|
1115
|
+
self.history = []
|
|
1116
|
+
self.measured = {}
|
|
1117
|
+
self.measured_spill = {}
|
|
1118
|
+
self.measured_link = {}
|
|
1119
|
+
self.accum = {"loss": None, "tokens": 0, "started": None}
|
|
1120
|
+
self.runs.append({"id": self.run_id, "started": time.time(), "job": self.job, "state": "running"})
|
|
1121
|
+
for info in self.workers.values():
|
|
1122
|
+
if info.get("banned") and not info.get("removed"):
|
|
1123
|
+
info["banned"], info["fails"], info["alive"] = False, 0, time.time() - info["seen"] < self.heartbeat_timeout
|
|
1124
|
+
self.plan = None
|
|
1125
|
+
self._replan(f"run {self.run_id} started", lost=False)
|
|
1126
|
+
self._tell_slow_kernels([w for w, v in self.workers.items() if v["alive"]])
|
|
1127
|
+
return self.run_id
|
|
1128
|
+
|
|
1129
|
+
def end_run(self, state: str = "finished", run_id: str | None = None):
|
|
1130
|
+
with self.cond:
|
|
1131
|
+
if self.job is None or (run_id is not None and run_id != self.run_id):
|
|
1132
|
+
return
|
|
1133
|
+
for r in self.runs:
|
|
1134
|
+
if r["id"] == self.run_id:
|
|
1135
|
+
r["state"], r["ended"], r["steps"] = state, time.time(), self.step
|
|
1136
|
+
self.event(f"run {self.run_id} {state} after {self.step} steps")
|
|
1137
|
+
self.job = None
|
|
1138
|
+
self.plan = None
|
|
1139
|
+
self.epoch += 1
|
|
1140
|
+
self.cond.notify_all()
|
|
1141
|
+
|
|
1142
|
+
def wait_ready(self, timeout: float | None = None):
|
|
1143
|
+
deadline = None if timeout is None else time.time() + timeout
|
|
1144
|
+
with self.cond:
|
|
1145
|
+
while True:
|
|
1146
|
+
if self.job is None:
|
|
1147
|
+
raise PoolError("no active run")
|
|
1148
|
+
if self.pending:
|
|
1149
|
+
self._replan("a device joined, came back or changed", lost=False)
|
|
1150
|
+
if self.plan and all((p["w"], self.epoch) in self.ready for p in self.plan):
|
|
1151
|
+
self.protect = None
|
|
1152
|
+
return
|
|
1153
|
+
if not self.plan:
|
|
1154
|
+
why = self._why_no_plan()
|
|
1155
|
+
if why:
|
|
1156
|
+
raise PoolError(why)
|
|
1157
|
+
left = None if deadline is None else deadline - time.time()
|
|
1158
|
+
if left is not None and left <= 0:
|
|
1159
|
+
raise TimeoutError("the devices did not get ready in time; check the dashboard or `layerpool devices`")
|
|
1160
|
+
self.cond.wait(timeout=1 if left is None else min(1, left))
|
|
1161
|
+
|
|
1162
|
+
def _set_oplog(self, kept: list[dict]):
|
|
1163
|
+
"""The replay log becomes `kept`; the files of the operations it drops go."""
|
|
1164
|
+
ids = {id(op) for op in kept}
|
|
1165
|
+
for op in self.oplog:
|
|
1166
|
+
if id(op) not in ids:
|
|
1167
|
+
for key in ("inputs", "cot"):
|
|
1168
|
+
if isinstance(op.get(key), Spilled):
|
|
1169
|
+
op[key].drop()
|
|
1170
|
+
self.oplog = kept
|
|
1171
|
+
|
|
1172
|
+
def _spilled(self, op: dict, seq: int) -> dict:
|
|
1173
|
+
"""An operation the devices did, as the replay log keeps it: its inputs and loss gradients in files."""
|
|
1174
|
+
logged = {k: v for k, v in op.items() if k != "provider"}
|
|
1175
|
+
for key in ("inputs", "cot"):
|
|
1176
|
+
if logged.get(key) is not None and not isinstance(logged[key], Spilled):
|
|
1177
|
+
folder = os.path.join(self.ckpt_dir, "replay")
|
|
1178
|
+
os.makedirs(folder, exist_ok=True)
|
|
1179
|
+
logged[key] = Spilled(os.path.join(folder, f"{self.run_id}_op{seq}_{key}.log"), logged[key])
|
|
1180
|
+
return logged
|
|
1181
|
+
|
|
1182
|
+
def _oplog_gb(self) -> float:
|
|
1183
|
+
total = 0
|
|
1184
|
+
for op in self.oplog:
|
|
1185
|
+
for key in ("inputs", "cot"):
|
|
1186
|
+
blobs = op.get(key) or []
|
|
1187
|
+
total += blobs.nbytes if isinstance(blobs, Spilled) else sum(len(b) for b in blobs if isinstance(b, (bytes, bytearray)))
|
|
1188
|
+
return total / 1e9
|
|
1189
|
+
|
|
1190
|
+
def _need_run(self):
|
|
1191
|
+
if self.job is None:
|
|
1192
|
+
raise PoolError("this run has ended (from the dashboard, or because its script stopped answering); start a new run")
|
|
1193
|
+
|
|
1194
|
+
def _why_no_plan(self) -> str | None:
|
|
1195
|
+
"""Why no split exists when waiting cannot change it, in words the user can act on; None while devices may still come."""
|
|
1196
|
+
known = [w for w, v in self.workers.items() if not v.get("removed")]
|
|
1197
|
+
alive = [w for w in known if self.workers[w]["alive"]]
|
|
1198
|
+
errors = [self.workers[w].get("why_left_out") for w in known if self.workers[w].get("banned")]
|
|
1199
|
+
if errors and not alive:
|
|
1200
|
+
return f"every device left the run after errors; the last one: {errors[-1]}"
|
|
1201
|
+
enabled = [w for w in alive if self.workers[w]["settings"].get("enabled", True)]
|
|
1202
|
+
if alive and not enabled:
|
|
1203
|
+
return "every device is paused: resume one in the dashboard or with `layerpool resume DEVICE`"
|
|
1204
|
+
usable = self._usable(enabled)
|
|
1205
|
+
if enabled and not usable:
|
|
1206
|
+
return ("no device here can run this 4-bit model: it needs a GPU bitsandbytes runs on (NVIDIA, or a recent AMD one), "
|
|
1207
|
+
"or an Apple Silicon Mac with an MLX 4-bit version of the model (mlx_model=)")
|
|
1208
|
+
if usable and not self.pending:
|
|
1209
|
+
nodes = self._nodes(usable)
|
|
1210
|
+
n = self._job()["layers"]
|
|
1211
|
+
name = lambda node: self.workers[node.name]["name"]
|
|
1212
|
+
fixed = [node for node in nodes if node.min_layers]
|
|
1213
|
+
if sum(node.min_layers for node in fixed) > n:
|
|
1214
|
+
return (f"the layer settings ask for {sum(node.min_layers for node in fixed)} layers ("
|
|
1215
|
+
+ ", ".join(f"{name(node)} {node.min_layers}" for node in fixed) + f") but the model has {n}: lower them or "
|
|
1216
|
+
"set some to auto")
|
|
1217
|
+
if all(node.max_layers is not None for node in nodes) and sum(node.max_layers for node in nodes) < n:
|
|
1218
|
+
return (f"the layer settings allow at most {sum(node.max_layers for node in nodes)} layers in all and the model has {n}: "
|
|
1219
|
+
"raise them, set one to auto, or add a device")
|
|
1220
|
+
for node in fixed:
|
|
1221
|
+
need = node.fixed_gb + node.min_layers * (node.layer_gb or self._job().get("layer_gb", 0.0))
|
|
1222
|
+
if need > node.cap_gb:
|
|
1223
|
+
return (f"{name(node)} is set to at least {node.min_layers} layers, which need about {need:.1f} GB, and it may use "
|
|
1224
|
+
f"{node.cap_gb:.1f} GB: lower its layers or raise its memory cap")
|
|
1225
|
+
per_layer = max(((n.layer_gb or self._job().get("layer_gb", 0.0)) for n in nodes), default=0.0)
|
|
1226
|
+
need = per_layer * self._job()["layers"]
|
|
1227
|
+
room = ", ".join(f"{self.workers[n.name]['name']} {max(0.0, n.cap_gb - n.fixed_gb):.1f} GB (of {n.cap_gb:.1f} GB it may use, "
|
|
1228
|
+
f"{n.fixed_gb:.1f} GB go to activations and other parts)" for n in nodes)
|
|
1229
|
+
return (f"the model does not fit the devices: its {self._job()['layers']} blocks need about {need:.1f} GB "
|
|
1230
|
+
f"({per_layer:.2f} GB each) and the devices have room for {room}. Add devices, raise their memory caps, use "
|
|
1231
|
+
"LoRA instead of full fine-tuning, a 4-bit model, or a shorter seq")
|
|
1232
|
+
return None
|
|
1233
|
+
|
|
1234
|
+
def _broadcast(self, epoch: int, seq: int, stages: list[dict], header: dict):
|
|
1235
|
+
"""Sends the operation to every device at once and returns a function that waits for that and raises what failed, so
|
|
1236
|
+
the first device's inputs go out at the same time instead of a round trip later."""
|
|
1237
|
+
data = json.dumps(header).encode()
|
|
1238
|
+
errors = []
|
|
1239
|
+
|
|
1240
|
+
def one(w):
|
|
1241
|
+
try:
|
|
1242
|
+
self.workers[w]["peer"].send(("op", epoch, seq), data, cancel=lambda: self.epoch != epoch, retries=2)
|
|
1243
|
+
except Cancelled:
|
|
1244
|
+
pass
|
|
1245
|
+
except ConnectionError as e:
|
|
1246
|
+
errors.append(Unreachable(w, e))
|
|
1247
|
+
threads = [threading.Thread(target=one, args=(p["w"],), daemon=True) for p in stages]
|
|
1248
|
+
[t.start() for t in threads]
|
|
1249
|
+
|
|
1250
|
+
def wait():
|
|
1251
|
+
[t.join() for t in threads]
|
|
1252
|
+
if errors:
|
|
1253
|
+
raise errors[0]
|
|
1254
|
+
return wait
|
|
1255
|
+
|
|
1256
|
+
def _send(self, wid: str, key: tuple, data: bytes, epoch: int):
|
|
1257
|
+
try:
|
|
1258
|
+
self.workers[wid]["peer"].send(key, data, cancel=lambda: self.epoch != epoch, retries=2)
|
|
1259
|
+
except Cancelled:
|
|
1260
|
+
raise Interrupted()
|
|
1261
|
+
except ConnectionError as e:
|
|
1262
|
+
raise Unreachable(wid, e)
|
|
1263
|
+
|
|
1264
|
+
def _recv(self, key: tuple, epoch: int) -> bytes:
|
|
1265
|
+
while True:
|
|
1266
|
+
data = self.server.inbox.get(tuple(str(x) for x in key), timeout=0.2)
|
|
1267
|
+
if data is not None:
|
|
1268
|
+
return data
|
|
1269
|
+
if self.epoch != epoch:
|
|
1270
|
+
raise Interrupted()
|
|
1271
|
+
|
|
1272
|
+
def _wait_reports(self, epoch: int, seq: int, stages: list[dict]) -> dict[str, dict]:
|
|
1273
|
+
started, told = time.time(), 0.0
|
|
1274
|
+
with self.cond:
|
|
1275
|
+
while self.epoch == epoch and not all((p["w"], epoch, seq) in self.reports for p in stages):
|
|
1276
|
+
self.cond.wait(timeout=1)
|
|
1277
|
+
waited = time.time() - started
|
|
1278
|
+
usual = max([1.0] + [h.get("seconds") or 0.0 for h in self.history[-5:]])
|
|
1279
|
+
if waited > max(30.0, 4 * usual) and waited - told > 30.0:
|
|
1280
|
+
told = waited
|
|
1281
|
+
slow = [self.workers[p["w"]]["name"] for p in stages if (p["w"], epoch, seq) not in self.reports]
|
|
1282
|
+
self.event(f"waiting {waited:.0f}s for {', '.join(slow)} (a step usually takes {usual:.0f}s); a device that stays "
|
|
1283
|
+
f"silent for {self.heartbeat_timeout:.0f}s is dropped and its layers move")
|
|
1284
|
+
if self.epoch != epoch:
|
|
1285
|
+
raise Interrupted()
|
|
1286
|
+
return {p["w"]: self.reports.pop((p["w"], epoch, seq)) for p in stages}
|
|
1287
|
+
|
|
1288
|
+
def _run_op(self, op: dict, epoch: int, seq: int, stages: list[dict]) -> dict:
|
|
1289
|
+
header = {k: v for k, v in op.items() if k not in ("inputs", "cot", "provider")}
|
|
1290
|
+
first, last = stages[0]["w"], stages[-1]["w"]
|
|
1291
|
+
outputs, grads = None, None
|
|
1292
|
+
if op["type"] in ("fb", "fwd"):
|
|
1293
|
+
n = len(op["inputs"])
|
|
1294
|
+
header["n"] = n
|
|
1295
|
+
header["outputs"] = op["type"] == "fwd" or op.get("cot") is None
|
|
1296
|
+
header["grads"] = op["type"] == "fb" and bool(op.get("grads"))
|
|
1297
|
+
sent = self._broadcast(epoch, seq, stages, header)
|
|
1298
|
+
if op["type"] in ("fb", "fwd"):
|
|
1299
|
+
for m, blob in enumerate(op["inputs"]):
|
|
1300
|
+
self._send(first, ("d", epoch, seq, m), blob, epoch)
|
|
1301
|
+
sent()
|
|
1302
|
+
if op["type"] in ("fb", "fwd"):
|
|
1303
|
+
if header["outputs"]:
|
|
1304
|
+
outputs = [self._recv(("o", epoch, seq, m), epoch) for m in range(n)]
|
|
1305
|
+
if op["type"] == "fb":
|
|
1306
|
+
if op.get("cot") is None:
|
|
1307
|
+
op["cot"] = list(op["provider"](outputs))
|
|
1308
|
+
for m, blob in enumerate(op["cot"]):
|
|
1309
|
+
self._send(last, ("cg", epoch, seq, m), blob, epoch)
|
|
1310
|
+
if header["grads"]:
|
|
1311
|
+
grads = [self._recv(("g0", epoch, seq, m), epoch) for m in range(n)]
|
|
1312
|
+
reports = self._wait_reports(epoch, seq, stages)
|
|
1313
|
+
return {"reports": reports, "outputs": outputs, "grads": grads, "last": last}
|
|
1314
|
+
|
|
1315
|
+
def _recover(self):
|
|
1316
|
+
while True:
|
|
1317
|
+
self.wait_ready()
|
|
1318
|
+
with self.cond:
|
|
1319
|
+
epoch, stages = self.epoch, [dict(p) for p in self.plan]
|
|
1320
|
+
if self.restore < self.oplog_after:
|
|
1321
|
+
lost = f"the saved state of step {self.oplog_after} was lost together with the device that held it"
|
|
1322
|
+
self.event(f"run {self.run_id} cannot continue exactly: {lost}. Start the run again from your last save.")
|
|
1323
|
+
raise PoolError(f"cannot recover the run exactly: {lost}; start again from your last save")
|
|
1324
|
+
replay = [{**op, "grads": False} for op in self.oplog if op["step"] > self.restore]
|
|
1325
|
+
try:
|
|
1326
|
+
for op in replay:
|
|
1327
|
+
seq = self._next_seq()
|
|
1328
|
+
self._run_op(op, epoch, seq, stages)
|
|
1329
|
+
if op["type"] == "commit":
|
|
1330
|
+
with self.cond:
|
|
1331
|
+
self.step = op["step"] + 1
|
|
1332
|
+
with self.cond:
|
|
1333
|
+
if self.epoch != epoch:
|
|
1334
|
+
continue
|
|
1335
|
+
self._replayed_epoch = epoch
|
|
1336
|
+
if replay:
|
|
1337
|
+
self.event(f"replayed {len(replay)} operations, the run continues exactly where it was")
|
|
1338
|
+
return
|
|
1339
|
+
except (Interrupted, Unreachable) as e:
|
|
1340
|
+
self._handle(e, epoch)
|
|
1341
|
+
|
|
1342
|
+
def _next_seq(self) -> int:
|
|
1343
|
+
with self.cond:
|
|
1344
|
+
seq = self.seq
|
|
1345
|
+
self.seq += 1
|
|
1346
|
+
return seq
|
|
1347
|
+
|
|
1348
|
+
def _handle(self, error: Exception, epoch: int):
|
|
1349
|
+
if isinstance(error, Unreachable) and not self._answers(error.wid):
|
|
1350
|
+
with self.cond:
|
|
1351
|
+
if self.epoch == epoch:
|
|
1352
|
+
self._lose(error.wid, "does not answer (the pool could not reach it)")
|
|
1353
|
+
with self.cond:
|
|
1354
|
+
if self.epoch == epoch:
|
|
1355
|
+
self._replan(f"an operation could not finish: {error!r}")
|
|
1356
|
+
|
|
1357
|
+
def execute(self, op: dict, log: bool = True) -> dict:
|
|
1358
|
+
with self.op_lock:
|
|
1359
|
+
while True:
|
|
1360
|
+
if self.job is None:
|
|
1361
|
+
raise PoolError("no active run")
|
|
1362
|
+
self.wait_ready()
|
|
1363
|
+
if self._replayed_epoch != self.epoch:
|
|
1364
|
+
self._recover()
|
|
1365
|
+
continue
|
|
1366
|
+
with self.cond:
|
|
1367
|
+
epoch, stages = self.epoch, [dict(p) for p in self.plan]
|
|
1368
|
+
seq = self._next_seq()
|
|
1369
|
+
try:
|
|
1370
|
+
if op["type"] == "commit":
|
|
1371
|
+
op["step"] = self.step
|
|
1372
|
+
elif op["type"] == "fb":
|
|
1373
|
+
op["step"] = self.step
|
|
1374
|
+
result = self._run_op(op, epoch, seq, stages)
|
|
1375
|
+
except (Interrupted, Unreachable) as e:
|
|
1376
|
+
self._handle(e, epoch)
|
|
1377
|
+
continue
|
|
1378
|
+
except BaseException as e:
|
|
1379
|
+
with self.cond:
|
|
1380
|
+
if self.job is not None and self.epoch == epoch:
|
|
1381
|
+
self._replan(f"an operation was stopped ({type(e).__name__}); the devices drop it and keep the run as it was",
|
|
1382
|
+
lost=op["type"] == "commit")
|
|
1383
|
+
raise
|
|
1384
|
+
if log and op["type"] in ("fb", "commit"):
|
|
1385
|
+
logged = self._spilled(op, seq)
|
|
1386
|
+
with self.cond:
|
|
1387
|
+
self.oplog.append(logged)
|
|
1388
|
+
if op["type"] == "commit":
|
|
1389
|
+
with self.cond:
|
|
1390
|
+
self.step = op["step"] + 1
|
|
1391
|
+
for p in stages:
|
|
1392
|
+
self.workers[p["w"]]["fails"] = 0
|
|
1393
|
+
return result
|
|
1394
|
+
|
|
1395
|
+
def fit_batch(self, rows: int, seq: int, pieces: int | None = None):
|
|
1396
|
+
"""The training code's batches have pieces of `rows` rows of `seq` tokens. When that is more than the run assumed, the
|
|
1397
|
+
memory each device needs is worked out again, and the split changes if it no longer fits."""
|
|
1398
|
+
from .job import estimate, hf_config
|
|
1399
|
+
with self.cond:
|
|
1400
|
+
job = self.job
|
|
1401
|
+
if job is None:
|
|
1402
|
+
return {}
|
|
1403
|
+
have_rows, have_seq = job.get("piece_rows") or job.get("micro_batch_size") or 1, job.get("seq", 512)
|
|
1404
|
+
if pieces and int(pieces) != job.get("pieces"):
|
|
1405
|
+
job["pieces"] = max(1, int(pieces))
|
|
1406
|
+
if rows <= have_rows and seq <= have_seq:
|
|
1407
|
+
return {}
|
|
1408
|
+
rows, seq = max(int(rows), have_rows), max(int(seq), have_seq)
|
|
1409
|
+
run_id = self.run_id
|
|
1410
|
+
sizes = dict(job.get("sizes") or {})
|
|
1411
|
+
try:
|
|
1412
|
+
configs = self.__dict__.setdefault("_configs", {})
|
|
1413
|
+
config = configs.get(job["repo"]) or configs.setdefault(job["repo"], hf_config(job["repo"]))
|
|
1414
|
+
sizes["torch"] = estimate(job["repo"], job["layout"], job["rank"], seq, rows, job["micro"], job["mode"], config)
|
|
1415
|
+
except Exception as e:
|
|
1416
|
+
self.event(f"could not work out the memory of {rows}-row pieces of {seq} tokens: {e!r}")
|
|
1417
|
+
return {}
|
|
1418
|
+
if "mlx" in sizes and job.get("mlx_repo"):
|
|
1419
|
+
try:
|
|
1420
|
+
sizes["mlx"] = estimate(job["mlx_repo"], job["layout"], job["rank"], seq, rows, job["micro"], job["mode"], config, stack="model.layers")
|
|
1421
|
+
except Exception:
|
|
1422
|
+
pass
|
|
1423
|
+
with self.cond:
|
|
1424
|
+
if self.job is not job or self.run_id != run_id:
|
|
1425
|
+
return {}
|
|
1426
|
+
job.update(sizes["torch"])
|
|
1427
|
+
job["sizes"], job["seq"], job["piece_rows"] = sizes, seq, rows
|
|
1428
|
+
alive = [w for w, v in self.workers.items() if v["alive"] and v["settings"].get("enabled", True)]
|
|
1429
|
+
stages = self._best_stages(alive) if alive else None
|
|
1430
|
+
now = [(s.name, s.first, s.last) for s in stages] if stages else None
|
|
1431
|
+
if now != [(p["w"], *p["range"]) for p in self.plan or []]:
|
|
1432
|
+
self._replan(f"pieces of {rows} rows of {seq} tokens need more memory than the run assumed", lost=False)
|
|
1433
|
+
return {"rows": rows, "seq": seq}
|
|
1434
|
+
|
|
1435
|
+
def forward_backward(self, inputs: list[bytes], provider, tokens: int = 0, grads: bool = False) -> dict:
|
|
1436
|
+
"""One batch through the devices and back. `inputs` are the packed stack inputs of each micro-batch; `provider(outputs)` gets
|
|
1437
|
+
the packed stack outputs and returns the packed output gradients. Returns the gradients of the stack inputs when `grads`."""
|
|
1438
|
+
op = {"type": "fb", "inputs": inputs, "cot": None, "provider": provider, "grads": grads}
|
|
1439
|
+
t = time.time()
|
|
1440
|
+
if self.accum["started"] is None:
|
|
1441
|
+
self.accum["started"] = t
|
|
1442
|
+
result = self.execute(op)
|
|
1443
|
+
reports = result["reports"]
|
|
1444
|
+
with self.cond:
|
|
1445
|
+
if self.steps_in_plan > 0:
|
|
1446
|
+
self._measure(reports)
|
|
1447
|
+
self.accum["tokens"] += tokens
|
|
1448
|
+
self._last_reports = reports
|
|
1449
|
+
self._tell_scales(reports)
|
|
1450
|
+
self._grad_sq = sum(r.get("grad_sq", 0.0) for r in reports.values())
|
|
1451
|
+
return {"grads": result["grads"], "seconds": round(time.time() - t, 3), "grad_sq": self._grad_sq,
|
|
1452
|
+
"timing": {self.workers[w]["name"]: {"compute": max([c[1] for c in r.get("cores", [])] or [r.get("compute", 0)]), "wait": r.get("wait", 0),
|
|
1453
|
+
"send": r.get("send", 0)} for w, r in reports.items()}}
|
|
1454
|
+
|
|
1455
|
+
def _device_scales(self) -> list[float]:
|
|
1456
|
+
return [r["loss_scale"] for r in (getattr(self, "_last_reports", None) or {}).values() if isinstance(r.get("loss_scale"), (int, float))]
|
|
1457
|
+
|
|
1458
|
+
def _tell_scales(self, reports: dict):
|
|
1459
|
+
"""Devices lower their own loss scale when a 16-bit backward overflows and redo that piece; say so once per new low."""
|
|
1460
|
+
seen = self.__dict__.setdefault("_scales", {})
|
|
1461
|
+
for w, r in reports.items():
|
|
1462
|
+
scale = r.get("loss_scale")
|
|
1463
|
+
if isinstance(scale, (int, float)) and w in seen and scale < seen[w]:
|
|
1464
|
+
self.event(f"{self.workers[w]['name']} lowered its loss scale to {scale:g}: a float16 backward overflowed there, and "
|
|
1465
|
+
"it redid that piece instead of skipping the step")
|
|
1466
|
+
if isinstance(scale, (int, float)):
|
|
1467
|
+
seen[w] = scale
|
|
1468
|
+
|
|
1469
|
+
def add_loss(self, value: float):
|
|
1470
|
+
with self.cond:
|
|
1471
|
+
self.accum["loss"] = (self.accum["loss"] or 0.0) + float(value)
|
|
1472
|
+
|
|
1473
|
+
def forward(self, inputs: list[bytes], adapter: bool = True) -> list[bytes]:
|
|
1474
|
+
return self.execute({"type": "fwd", "inputs": inputs, "adapter": adapter}, log=False)["outputs"]
|
|
1475
|
+
|
|
1476
|
+
def optim_step(self, lr: float, max_grad_norm: float | None = None, loss: float | None = None, clip: float | None = None,
|
|
1477
|
+
weight_decay: float | None = None, skip: bool = False) -> dict:
|
|
1478
|
+
"""One optimizer step on every device. skip=True drops the gradients gathered since the last step instead, as the training
|
|
1479
|
+
code did (a GradScaler that found an overflow in its own part)."""
|
|
1480
|
+
self._need_run()
|
|
1481
|
+
norm = float(np.sqrt(getattr(self, "_grad_sq", 0.0)))
|
|
1482
|
+
overflow = not np.isfinite(norm) or (clip is not None and not np.isfinite(clip))
|
|
1483
|
+
if skip and not overflow:
|
|
1484
|
+
clip = 0.0
|
|
1485
|
+
self.event(f"step {self.step}: the training code dropped this step's gradients without a step, so the devices drop theirs too")
|
|
1486
|
+
skip = skip or overflow
|
|
1487
|
+
if overflow:
|
|
1488
|
+
clip = 0.0
|
|
1489
|
+
scale = max(1.0, min([self.job.get("loss_scale", 1.0)] + self._device_scales()) / 2)
|
|
1490
|
+
self.event(f"step {self.step} skipped: the gradients overflowed; loss scale lowered to {scale:g}")
|
|
1491
|
+
if self.job.get("loss_scale", 1.0) <= 1.0:
|
|
1492
|
+
halves = [self.workers[p["w"]]["name"] for p in self.plan or [] if self.workers[p["w"]]["devices"][0]["kind"] == "cuda"]
|
|
1493
|
+
self.event("the gradients overflow even without loss scaling: the values of this model do not fit in float16, which "
|
|
1494
|
+
f"older GPUs train in ({', '.join(halves) or 'some devices'}). Use GPUs with bfloat16 (NVIDIA RTX 30 / A100 "
|
|
1495
|
+
"and newer, AMD MI200 / RX 7000 and newer, Apple Silicon) or pause the float16 ones")
|
|
1496
|
+
self.job["loss_scale"], self._good_steps = scale, 0
|
|
1497
|
+
elif clip is None:
|
|
1498
|
+
clip = min(1.0, max_grad_norm / (norm + 1e-6)) if max_grad_norm else 1.0
|
|
1499
|
+
good = 0 if skip else self._good_steps + 1
|
|
1500
|
+
op = {"type": "commit", "lr": lr, "clip": clip, "skip": skip}
|
|
1501
|
+
if overflow:
|
|
1502
|
+
op["lower_scale"] = self.job["loss_scale"]
|
|
1503
|
+
if self._oplog_gb() > OPLOG_LIMIT_GB:
|
|
1504
|
+
op["checkpoint"] = True
|
|
1505
|
+
if weight_decay is not None:
|
|
1506
|
+
op["weight_decay"] = float(weight_decay)
|
|
1507
|
+
self.execute(op)
|
|
1508
|
+
self._good_steps = good
|
|
1509
|
+
with self.cond:
|
|
1510
|
+
self._grad_sq = 0.0
|
|
1511
|
+
took = time.time() - (self.accum["started"] or time.time())
|
|
1512
|
+
value = self.accum["loss"] if loss is None else loss
|
|
1513
|
+
record = {"step": self.step - 1, "loss": value, "lr": lr, "grad_norm": round(norm, 5) if np.isfinite(norm) else None, "clip": round(clip, 5),
|
|
1514
|
+
"skipped": skip, "seconds": round(took, 2),
|
|
1515
|
+
"tokens": self.accum["tokens"], "tokens_per_s": round(self.accum["tokens"] / took, 1) if took > 0 else None,
|
|
1516
|
+
"plan": [[self.workers[p["w"]]["name"], p["range"]] for p in self.plan or []], "time": time.time()}
|
|
1517
|
+
if getattr(self, "_last_reports", None):
|
|
1518
|
+
record["timing"] = {self.workers[w]["name"]: {"compute": max([c[1] for c in r.get("cores", [])] or [r.get("compute", 0)]),
|
|
1519
|
+
"wait": r.get("wait", 0), "send": r.get("send", 0)} for w, r in self._last_reports.items()}
|
|
1520
|
+
self.history.append(record)
|
|
1521
|
+
if len(self.history) > 20000:
|
|
1522
|
+
self.history = self.history[:-10000:2] + self.history[-10000:]
|
|
1523
|
+
self.accum = {"loss": None, "tokens": 0, "started": None}
|
|
1524
|
+
self.steps_in_plan += 1
|
|
1525
|
+
self._maybe_rebalance()
|
|
1526
|
+
said = "" if value is None else f" loss {value:.4f}"
|
|
1527
|
+
self.event(f"step {record['step']}{said} in {record['seconds']:.1f}s" + (f" ({record['tokens_per_s']} tok/s)" if record["tokens_per_s"] else ""))
|
|
1528
|
+
self.emit("step", record)
|
|
1529
|
+
return record
|
|
1530
|
+
|
|
1531
|
+
def gather(self, step: int | None = None, moments: bool = False) -> dict[str, np.ndarray]:
|
|
1532
|
+
with self.cond:
|
|
1533
|
+
step = self.step - 1 if step is None else step
|
|
1534
|
+
units = self._units()
|
|
1535
|
+
out = {}
|
|
1536
|
+
for unit in units:
|
|
1537
|
+
path = self._path(unit, step)
|
|
1538
|
+
path = path + ".weights" if os.path.exists(path + ".weights") else path
|
|
1539
|
+
with open(path, "rb") as f:
|
|
1540
|
+
meta, arrays = unpack(f.read())
|
|
1541
|
+
arrays = from_half(meta, arrays)
|
|
1542
|
+
out.update({k: v for k, v in arrays.items() if moments or not k.endswith((".m", ".v", ".t"))})
|
|
1543
|
+
return out
|
|
1544
|
+
|
|
1545
|
+
def load_weights(self, weights: dict[str, np.ndarray]):
|
|
1546
|
+
"""Put saved weights (an adapter or trained blocks, under the devices' names such as "3.mlp.up_proj.A") on the devices.
|
|
1547
|
+
Before the first step they take the place of the initial values. Later (the Trainer's load_best_model_at_end, or going back
|
|
1548
|
+
to a save) they become the state after the last step taken, under a step number no checkpoint has used, so no older state
|
|
1549
|
+
of the devices can be taken for them; the run goes on from there, and a device that joins later starts from them too."""
|
|
1550
|
+
with self.op_lock, self.cond:
|
|
1551
|
+
if self.job is None:
|
|
1552
|
+
raise PoolError("no run is going")
|
|
1553
|
+
by_unit: dict[int, dict] = {}
|
|
1554
|
+
for key, value in weights.items():
|
|
1555
|
+
by_unit.setdefault(int(key.split(".", 1)[0]), {})[key] = np.asarray(value)
|
|
1556
|
+
lacking = [u for u in self._units() if u not in by_unit]
|
|
1557
|
+
if lacking:
|
|
1558
|
+
raise PoolError(f"the saved weights have nothing for blocks {lacking[:8]}")
|
|
1559
|
+
midway = self.step > 0
|
|
1560
|
+
at = self.step if midway else -1
|
|
1561
|
+
for unit, state in by_unit.items():
|
|
1562
|
+
path = self._path(unit, at)
|
|
1563
|
+
with open(path + ".part", "wb") as f:
|
|
1564
|
+
f.write(pack(None, **state))
|
|
1565
|
+
replace_file(path + ".part", path)
|
|
1566
|
+
if midway:
|
|
1567
|
+
self.ckpt[unit] = {}
|
|
1568
|
+
self._add(unit, at, "coord")
|
|
1569
|
+
if midway:
|
|
1570
|
+
self._set_oplog([])
|
|
1571
|
+
self.oplog_after, self.protect = at, at
|
|
1572
|
+
self._replan("loaded saved weights", lost=True)
|
|
1573
|
+
else:
|
|
1574
|
+
self.job["base"] = self.job.get("base", 0) + 1
|
|
1575
|
+
self._replan("loaded saved weights", lost=False)
|
|
1576
|
+
self.cond.notify_all()
|
|
1577
|
+
self.event(f"run {self.run_id} goes on from saved weights ({len(weights)} tensors)")
|
|
1578
|
+
|
|
1579
|
+
def export(self, path: str, dtype: str = "bfloat16", metrics: list | None = None, optimizer: bool = False) -> str:
|
|
1580
|
+
"""The run's result in path. optimizer=True also keeps the devices' AdamW state (layerpool_optimizer.safetensors), so a
|
|
1581
|
+
training checkpoint resumes exactly."""
|
|
1582
|
+
self._need_run()
|
|
1583
|
+
if optimizer:
|
|
1584
|
+
from safetensors.numpy import save_file
|
|
1585
|
+
self.execute({"type": "save", "target": "coord", "weights_only": True, "moments": True}, log=False)
|
|
1586
|
+
os.makedirs(path, exist_ok=True)
|
|
1587
|
+
full = self.gather(moments=True)
|
|
1588
|
+
save_file({k: np.ascontiguousarray(v) for k, v in full.items()}, os.path.join(path, OPTIMIZER_FILE))
|
|
1589
|
+
weights = {k: v for k, v in full.items() if not k.endswith((".m", ".v", ".t"))}
|
|
1590
|
+
else:
|
|
1591
|
+
half = dtype if self.job.get("mode", "lora") == "full" else None
|
|
1592
|
+
self.execute({"type": "save", "target": "coord", "weights_only": True, "dtype": half}, log=False)
|
|
1593
|
+
weights = self.gather()
|
|
1594
|
+
for name in os.listdir(self.ckpt_dir):
|
|
1595
|
+
if name.startswith(f"{self.run_id}_") and name.endswith(".weights"):
|
|
1596
|
+
os.remove(os.path.join(self.ckpt_dir, name))
|
|
1597
|
+
job = self.job
|
|
1598
|
+
if job.get("mode", "lora") == "lora":
|
|
1599
|
+
export_peft({k: v for k, v in weights.items() if k.endswith((".A", ".B"))}, path, job)
|
|
1600
|
+
else:
|
|
1601
|
+
export_blocks(weights, path, job, dtype)
|
|
1602
|
+
with open(os.path.join(path, "layerpool_run.json"), "w", encoding="utf-8") as f:
|
|
1603
|
+
json.dump({"run": self.run_id, "job": job, "steps": self.step, "history": self.history, "metrics": metrics or []}, f, indent=1, default=str)
|
|
1604
|
+
self.event(f"saved run {self.run_id} at step {self.step - 1} to {path}")
|
|
1605
|
+
return path
|
|
1606
|
+
|
|
1607
|
+
def invite(self, ttl: float = 86400, reusable: bool = False) -> dict:
|
|
1608
|
+
ttl = float(ttl)
|
|
1609
|
+
if not 60 <= ttl <= 30 * 86400:
|
|
1610
|
+
raise ValueError("an invite lasts from a minute to 30 days")
|
|
1611
|
+
code = "inv_" + secrets.token_urlsafe(12)
|
|
1612
|
+
with self.cond:
|
|
1613
|
+
now = time.time()
|
|
1614
|
+
for old in [c for c, v in self.invites.items() if v["expires"] < now]:
|
|
1615
|
+
del self.invites[old]
|
|
1616
|
+
self.invites[code] = {"expires": time.time() + ttl, "reusable": reusable}
|
|
1617
|
+
url = self.urls[-1]
|
|
1618
|
+
join = f"layerpool join {url} --token {code}"
|
|
1619
|
+
return {"code": code, "url": url, "expires_in_s": ttl, "reusable": reusable, "tunnel": self.tunnel is not None,
|
|
1620
|
+
"command": f"pip install -U layerpool=={__version__}\n{join}",
|
|
1621
|
+
"notebook": f"!pip install -q -U layerpool=={__version__}\n!{join}"}
|
|
1622
|
+
|
|
1623
|
+
def _check(self, handler, method: str, path: str, query: dict):
|
|
1624
|
+
query.pop("_invite", None)
|
|
1625
|
+
query.pop("_ip", None)
|
|
1626
|
+
token = handler.headers.get("X-Token")
|
|
1627
|
+
if token and hmac.compare_digest(token.encode("utf-8", "surrogateescape"), self.token.encode()):
|
|
1628
|
+
return None
|
|
1629
|
+
if token in self.device_tokens:
|
|
1630
|
+
if "w" in query and query["w"] != self.device_tokens[token]:
|
|
1631
|
+
return 403, {"error": "this device token belongs to another device"}
|
|
1632
|
+
if path != "/join" and self.device_tokens[token] not in self.workers:
|
|
1633
|
+
return 409, {"error": "rejoin"}
|
|
1634
|
+
return None
|
|
1635
|
+
if path == "/request":
|
|
1636
|
+
ip = handler.client_address[0]
|
|
1637
|
+
if self.tunnel is not None and ip in ("127.0.0.1", "::1"):
|
|
1638
|
+
ip = "".join(c for c in str(handler.headers.get("CF-Connecting-IP") or ip)[:64] if c.isprintable())
|
|
1639
|
+
query["_ip"] = ip
|
|
1640
|
+
if method == "POST":
|
|
1641
|
+
with self.cond:
|
|
1642
|
+
now = time.time()
|
|
1643
|
+
mine = [r for r in self.requests.values() if r.get("ip") == ip and r["status"] == "waiting" and now - r["time"] < self.REQUEST_TTL]
|
|
1644
|
+
if len(mine) >= 3:
|
|
1645
|
+
return 429, {"error": "this address already has devices waiting for approval; approve or deny them first"}
|
|
1646
|
+
return None
|
|
1647
|
+
if path == "/info":
|
|
1648
|
+
return None
|
|
1649
|
+
if path in ("/join", "/info") and token in self.invites:
|
|
1650
|
+
invite = self.invites[token]
|
|
1651
|
+
if invite["expires"] < time.time():
|
|
1652
|
+
return 403, {"error": "this invite has expired; create a new one from the dashboard or `layerpool invite`"}
|
|
1653
|
+
query["_invite"] = token
|
|
1654
|
+
return None
|
|
1655
|
+
return 403, b""
|
|
1656
|
+
|
|
1657
|
+
def close(self, grace: float = 3.0):
|
|
1658
|
+
with self.cond:
|
|
1659
|
+
self.closed = True
|
|
1660
|
+
self.cond.notify_all()
|
|
1661
|
+
deadline = time.time() + grace
|
|
1662
|
+
with self.cond:
|
|
1663
|
+
while time.time() < deadline and not all(not w["alive"] or w.get("bye") for w in self.workers.values()):
|
|
1664
|
+
self.cond.wait(timeout=0.1)
|
|
1665
|
+
time.sleep(0.2)
|
|
1666
|
+
if self.tunnel:
|
|
1667
|
+
self.tunnel.close()
|
|
1668
|
+
self.server.close()
|
|
1669
|
+
if self._own_ckpt:
|
|
1670
|
+
shutil.rmtree(self.ckpt_dir, ignore_errors=True)
|