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/worker.py
ADDED
|
@@ -0,0 +1,1277 @@
|
|
|
1
|
+
import argparse
|
|
2
|
+
import faulthandler
|
|
3
|
+
import gc
|
|
4
|
+
import hashlib
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
import platform
|
|
8
|
+
import queue
|
|
9
|
+
import re
|
|
10
|
+
import secrets
|
|
11
|
+
import shutil
|
|
12
|
+
import signal
|
|
13
|
+
import socket
|
|
14
|
+
import subprocess
|
|
15
|
+
import sys
|
|
16
|
+
import threading
|
|
17
|
+
import time
|
|
18
|
+
import uuid
|
|
19
|
+
import traceback
|
|
20
|
+
import urllib.error
|
|
21
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
22
|
+
|
|
23
|
+
import numpy as np
|
|
24
|
+
|
|
25
|
+
from . import __version__
|
|
26
|
+
from .blocks import BlockCore, load_blocks, mlx_masks, unpack_args, unwrap_lora
|
|
27
|
+
from .codec import DiskStore, decode, encode, pack, split_prefix, to_half, unpack, with_prefix
|
|
28
|
+
from .net import Cancelled, HTTPError, Peer, PeerServer, Sender
|
|
29
|
+
from .telemetry import sample
|
|
30
|
+
from .tunnel import Tunnel, child_options
|
|
31
|
+
|
|
32
|
+
ROCM_BF16 = ("gfx90a", "gfx94", "gfx95", "gfx11", "gfx12")
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def native_bf16() -> bool:
|
|
36
|
+
"""bfloat16 in hardware: NVIDIA Ampere (compute capability 8) and newer, AMD MI200/MI300 and RDNA3 and newer.
|
|
37
|
+
torch.cuda.is_bf16_supported() also says yes on cards that only emulate it (a T4, older AMD cards), which is slow."""
|
|
38
|
+
import torch
|
|
39
|
+
if not torch.cuda.is_available():
|
|
40
|
+
return False
|
|
41
|
+
if getattr(torch.version, "hip", None):
|
|
42
|
+
return all(str(getattr(torch.cuda.get_device_properties(i), "gcnArchName", "")).startswith(ROCM_BF16)
|
|
43
|
+
for i in range(torch.cuda.device_count()))
|
|
44
|
+
return all(torch.cuda.get_device_capability(i)[0] >= 8 for i in range(torch.cuda.device_count()))
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def train_dtype(device: str):
|
|
48
|
+
"""The 16-bit type a device trains LoRA in: bfloat16 where it is native, float16 where float16 is fast (with loss scaling),
|
|
49
|
+
and float32 on GPUs where neither is (GTX 10xx and older) and on CPUs."""
|
|
50
|
+
import torch
|
|
51
|
+
if device == "mps":
|
|
52
|
+
newer = getattr(torch.backends.mps, "is_macos_or_newer", None)
|
|
53
|
+
return torch.bfloat16 if newer is None or newer(14, 0) else torch.float16
|
|
54
|
+
if device == "cpu":
|
|
55
|
+
return torch.float32
|
|
56
|
+
if native_bf16():
|
|
57
|
+
return torch.bfloat16
|
|
58
|
+
if not getattr(torch.version, "hip", None) and min(torch.cuda.get_device_capability(i) for i in range(torch.cuda.device_count())) < (7, 0) \
|
|
59
|
+
and min(torch.cuda.get_device_capability(i) for i in range(torch.cuda.device_count())) != (6, 0):
|
|
60
|
+
return torch.float32
|
|
61
|
+
return torch.float16
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _arch(name: str) -> tuple | None:
|
|
65
|
+
"""("sm_86" or "compute_90a") -> (8, 6) or (9, 0); GPUs run code built for an earlier minor version of their major version."""
|
|
66
|
+
digits = re.match(r"(?:sm|compute)_(\d+)(\d)", name)
|
|
67
|
+
return (int(digits.group(1)), int(digits.group(2))) if digits else None
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
_HIP_RUNS: dict = {}
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def cuda_problem() -> str | None:
|
|
74
|
+
"""Why this machine's NVIDIA/AMD GPU cannot train with the installed PyTorch, or None when it can (or there is none)."""
|
|
75
|
+
try:
|
|
76
|
+
import torch
|
|
77
|
+
except ImportError:
|
|
78
|
+
return None
|
|
79
|
+
if not torch.cuda.is_available():
|
|
80
|
+
if shutil.which("nvidia-smi") and platform.system() in ("Windows", "Linux"):
|
|
81
|
+
return ("this machine has an NVIDIA GPU, but the installed PyTorch has no CUDA support, so it trains on the CPU. Install "
|
|
82
|
+
"the CUDA build: https://pytorch.org/get-started/locally/")
|
|
83
|
+
if platform.system() == "Linux" and (os.path.exists("/dev/kfd") or shutil.which("rocminfo") or shutil.which("amd-smi")):
|
|
84
|
+
return ("this machine has an AMD GPU, but the installed PyTorch has no ROCm support, so it trains on the CPU. Install the "
|
|
85
|
+
"ROCm build (choose ROCm at https://pytorch.org/get-started/locally/), then layerpool")
|
|
86
|
+
return None
|
|
87
|
+
if getattr(torch.version, "hip", None):
|
|
88
|
+
for i in range(torch.cuda.device_count()):
|
|
89
|
+
if _HIP_RUNS.get(i) is True:
|
|
90
|
+
continue
|
|
91
|
+
try:
|
|
92
|
+
probe = torch.ones(8, device=f"cuda:{i}") * 2
|
|
93
|
+
torch.cuda.synchronize(i)
|
|
94
|
+
assert float(probe.sum().cpu()) == 16.0
|
|
95
|
+
_HIP_RUNS[i] = True
|
|
96
|
+
except Exception as e:
|
|
97
|
+
arch = str(getattr(torch.cuda.get_device_properties(i), "gcnArchName", "")).split(":")[0]
|
|
98
|
+
return (f"{torch.cuda.get_device_name(i)} ({arch}) does not run the installed PyTorch {torch.__version__} ({e.__class__.__name__}), "
|
|
99
|
+
"so this device trains on the CPU. Install a ROCm build of PyTorch made for it, or, for a card ROCm does not list, "
|
|
100
|
+
"set HSA_OVERRIDE_GFX_VERSION (for example 10.3.0 for an RX 6000 card) before starting layerpool")
|
|
101
|
+
return None
|
|
102
|
+
built = torch.cuda.get_arch_list()
|
|
103
|
+
for i in range(torch.cuda.device_count()):
|
|
104
|
+
major, minor = torch.cuda.get_device_capability(i)
|
|
105
|
+
native = any(_arch(a) and _arch(a)[0] == major and _arch(a)[1] <= minor for a in built if a.startswith("sm_"))
|
|
106
|
+
ptx = any(_arch(a) and _arch(a) <= (major, minor) for a in built if a.startswith("compute_"))
|
|
107
|
+
if not native and not ptx:
|
|
108
|
+
return (f"{torch.cuda.get_device_name(i)} (compute capability {major}.{minor}) is not supported by PyTorch {torch.__version__}, "
|
|
109
|
+
"so this device trains on the CPU. Install a PyTorch build for it, for example: "
|
|
110
|
+
"pip install \"torch<2.15\" --index-url https://download.pytorch.org/whl/cu126")
|
|
111
|
+
return None
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def out_of_memory(error: BaseException) -> bool:
|
|
115
|
+
"""Whether an error means the device ran out of memory (CUDA, Apple GPU with PyTorch or MLX, or the CPU)."""
|
|
116
|
+
if type(error).__name__ in ("OutOfMemoryError", "MemoryError"):
|
|
117
|
+
return True
|
|
118
|
+
text = str(error).lower()
|
|
119
|
+
return "out of memory" in text or "outofmemory" in text or "[metal::malloc]" in text or "insufficient memory" in text
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def library_versions() -> dict:
|
|
123
|
+
"""The versions that decide how a model is built and run here."""
|
|
124
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
125
|
+
out = {"python": platform.python_version()}
|
|
126
|
+
for name in ("torch", "transformers", "mlx", "mlx-lm", "bitsandbytes", "flash-linear-attention", "causal-conv1d"):
|
|
127
|
+
try:
|
|
128
|
+
out[name] = version(name)
|
|
129
|
+
except PackageNotFoundError:
|
|
130
|
+
pass
|
|
131
|
+
try:
|
|
132
|
+
from transformers.utils.import_utils import BITSANDBYTES_MIN_VERSION
|
|
133
|
+
out["bitsandbytes-needed"] = BITSANDBYTES_MIN_VERSION
|
|
134
|
+
except ImportError:
|
|
135
|
+
pass
|
|
136
|
+
return out
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
STORE_ROOT = os.path.join(os.path.expanduser("~"), ".cache", "layerpool", "store")
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _store_folder() -> str:
|
|
143
|
+
"""This device's own folder for the checkpoints it keeps; folders of devices that are no longer running are removed."""
|
|
144
|
+
import psutil
|
|
145
|
+
os.makedirs(STORE_ROOT, exist_ok=True)
|
|
146
|
+
for name in os.listdir(STORE_ROOT):
|
|
147
|
+
pid = name.split("_", 1)[0]
|
|
148
|
+
if pid.isdigit() and not psutil.pid_exists(int(pid)):
|
|
149
|
+
shutil.rmtree(os.path.join(STORE_ROOT, name), ignore_errors=True)
|
|
150
|
+
return os.path.join(STORE_ROOT, f"{os.getpid()}_{secrets.token_hex(4)}")
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def unit_of(key: str) -> int:
|
|
154
|
+
return int(key.split(".", 1)[0])
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
class Abort(Exception):
|
|
158
|
+
pass
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
class NeighbourDown(Exception):
|
|
162
|
+
def __init__(self, wid: str, error: Exception):
|
|
163
|
+
super().__init__(f"{wid} unreachable: {error!r}")
|
|
164
|
+
self.wid = wid
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def _has_mlx() -> bool:
|
|
168
|
+
try:
|
|
169
|
+
import mlx.core as mx
|
|
170
|
+
return mx.metal.is_available()
|
|
171
|
+
except ImportError:
|
|
172
|
+
return False
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def _has_cuda() -> bool:
|
|
176
|
+
try:
|
|
177
|
+
import torch
|
|
178
|
+
return torch.cuda.is_available() and cuda_problem() is None
|
|
179
|
+
except ImportError:
|
|
180
|
+
return False
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def _has_mps() -> bool:
|
|
184
|
+
try:
|
|
185
|
+
import torch
|
|
186
|
+
return torch.backends.mps.is_available()
|
|
187
|
+
except ImportError:
|
|
188
|
+
return False
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def pick_backend(backend: str = "auto", cpu: bool = False) -> str:
|
|
192
|
+
if backend != "auto":
|
|
193
|
+
return backend
|
|
194
|
+
if not cpu and _has_cuda():
|
|
195
|
+
return "torch"
|
|
196
|
+
return "mlx" if _has_mlx() else "torch"
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def total_ram_gb() -> float:
|
|
200
|
+
"""The machine's memory, or a container's limit when it runs in one (Docker, Kubernetes, some notebook services)."""
|
|
201
|
+
import psutil
|
|
202
|
+
total = psutil.virtual_memory().total
|
|
203
|
+
for path in ("/sys/fs/cgroup/memory.max", "/sys/fs/cgroup/memory/memory.limit_in_bytes"):
|
|
204
|
+
try:
|
|
205
|
+
with open(path, encoding="utf-8") as f:
|
|
206
|
+
value = f.read().strip()
|
|
207
|
+
except OSError:
|
|
208
|
+
continue
|
|
209
|
+
if value.isdigit() and 0 < int(value) < total:
|
|
210
|
+
total = int(value)
|
|
211
|
+
return round(total / 1e9, 1)
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def cpu_name() -> str:
|
|
215
|
+
try:
|
|
216
|
+
if platform.system() == "Darwin":
|
|
217
|
+
return subprocess.run(["sysctl", "-n", "machdep.cpu.brand_string"], capture_output=True, text=True).stdout.strip()
|
|
218
|
+
if platform.system() == "Windows":
|
|
219
|
+
import winreg
|
|
220
|
+
with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"HARDWARE\DESCRIPTION\System\CentralProcessor\0") as key:
|
|
221
|
+
return winreg.QueryValueEx(key, "ProcessorNameString")[0].strip()
|
|
222
|
+
with open("/proc/cpuinfo", encoding="utf-8") as f:
|
|
223
|
+
for line in f:
|
|
224
|
+
if line.lower().startswith("model name"):
|
|
225
|
+
return line.split(":", 1)[1].strip()
|
|
226
|
+
except Exception:
|
|
227
|
+
pass
|
|
228
|
+
return platform.processor() or platform.machine()
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def default_name() -> str:
|
|
232
|
+
"""The host name, or the notebook service a device runs in (their host names are random)."""
|
|
233
|
+
if os.environ.get("COLAB_RELEASE_TAG") or os.environ.get("COLAB_GPU") is not None:
|
|
234
|
+
return "colab"
|
|
235
|
+
if os.environ.get("KAGGLE_KERNEL_RUN_TYPE") or os.environ.get("KAGGLE_URL_BASE"):
|
|
236
|
+
return "kaggle"
|
|
237
|
+
return socket.gethostname()
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def keep_awake():
|
|
241
|
+
"""Keep this computer from sleeping while it lends itself to a pool (a sleeping device looks gone and costs a rollback).
|
|
242
|
+
Closing a laptop's lid still sleeps it. Returns the helper process to stop, if any."""
|
|
243
|
+
try:
|
|
244
|
+
if sys.platform == "darwin" and shutil.which("caffeinate"):
|
|
245
|
+
return subprocess.Popen(["caffeinate", "-i", "-w", str(os.getpid())], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
|
246
|
+
if sys.platform == "win32":
|
|
247
|
+
import ctypes
|
|
248
|
+
ctypes.windll.kernel32.SetThreadExecutionState(0x80000000 | 0x00000001)
|
|
249
|
+
elif shutil.which("systemd-inhibit") and os.environ.get("XDG_SESSION_ID"):
|
|
250
|
+
return subprocess.Popen(["systemd-inhibit", "--what=sleep", "--who=layerpool", "--why=training", "--mode=block",
|
|
251
|
+
"sleep", "infinity"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, **child_options())
|
|
252
|
+
except Exception:
|
|
253
|
+
pass
|
|
254
|
+
return None
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def amd_4bit_works(index: int) -> bool:
|
|
258
|
+
"""Whether bitsandbytes' 4-bit layers run on this AMD GPU (its recent versions support many of them)."""
|
|
259
|
+
try:
|
|
260
|
+
import torch
|
|
261
|
+
import bitsandbytes.functional as bnb
|
|
262
|
+
packed, state = bnb.quantize_4bit(torch.randn(64, 64, device=f"cuda:{index}", dtype=torch.float16), quant_type="nf4")
|
|
263
|
+
back = bnb.dequantize_4bit(packed, state)
|
|
264
|
+
torch.cuda.synchronize(index)
|
|
265
|
+
return bool(torch.isfinite(back).all())
|
|
266
|
+
except Exception:
|
|
267
|
+
return False
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def describe_devices(backend: str, cpu: bool = False) -> list[dict]:
|
|
271
|
+
ram = total_ram_gb()
|
|
272
|
+
if backend == "torch" and not cpu and _has_cuda():
|
|
273
|
+
import torch
|
|
274
|
+
amd = bool(getattr(torch.version, "hip", None))
|
|
275
|
+
out = []
|
|
276
|
+
for i in range(torch.cuda.device_count()):
|
|
277
|
+
total = torch.cuda.get_device_properties(i).total_memory
|
|
278
|
+
out.append({"kind": "cuda", "name": torch.cuda.get_device_name(i), "gb": round(total / 1e9, 1), "amd": amd,
|
|
279
|
+
**({"q4": amd_4bit_works(i)} if amd else {})})
|
|
280
|
+
return out
|
|
281
|
+
if backend == "mlx" and not cpu:
|
|
282
|
+
return [{"kind": "mlx", "name": cpu_name() or platform.machine(), "gb": ram}]
|
|
283
|
+
if backend == "torch" and not cpu and _has_mps():
|
|
284
|
+
return [{"kind": "mps", "name": cpu_name() or platform.machine(), "gb": ram}]
|
|
285
|
+
return [{"kind": "cpu", "name": cpu_name(), "gb": ram}]
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
def model_key(job: dict, first: int, last: int) -> tuple:
|
|
289
|
+
return (job["repo"], job.get("mlx_repo"), job.get("auto"), job["kind"], job.get("mode", "lora"), job.get("random_init", False), first, last)
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
class Worker:
|
|
293
|
+
def __init__(self, coordinator: str, token: str, name: str | None = None, cap_gb: float | None = None, tunnel: bool | None = False,
|
|
294
|
+
port: int = 0, backend: str = "auto", cpu: bool = False, identity: str | None = None, log=None, advertise: list | None = None,
|
|
295
|
+
layers: str | None = None, gpus: str | None = None, gpu_caps: str | None = None, order: int | None = None,
|
|
296
|
+
allow_sleep: bool = False, ram_cap: float | None = None):
|
|
297
|
+
self.server = PeerServer(port=port)
|
|
298
|
+
self.coord = Peer([coordinator], token)
|
|
299
|
+
self.name = name or default_name()
|
|
300
|
+
self.cap_gb = cap_gb
|
|
301
|
+
self.allow_sleep = allow_sleep
|
|
302
|
+
self.asked = {k: v for k, v in (("layers", layers), ("gpus", gpus), ("gpu_caps", gpu_caps), ("order", order), ("ram_cap", ram_cap))
|
|
303
|
+
if v is not None}
|
|
304
|
+
self.backend, self.cpu = pick_backend(backend, cpu), cpu
|
|
305
|
+
self.devices = describe_devices(self.backend, cpu)
|
|
306
|
+
self.identity = identity
|
|
307
|
+
problem = None if cpu else cuda_problem()
|
|
308
|
+
if problem:
|
|
309
|
+
(log or (lambda *a: print("[layerpool]", *a, flush=True)))(problem)
|
|
310
|
+
self.addrs = [self.server.url_at(a) for a in advertise] if advertise else [self.server.lan_url()]
|
|
311
|
+
self.tunnel = None
|
|
312
|
+
self.tunnel_wanted = tunnel
|
|
313
|
+
self.tunnel_log = log or (lambda *a: print("[layerpool]", *a, flush=True))
|
|
314
|
+
if tunnel:
|
|
315
|
+
self._open_tunnel()
|
|
316
|
+
self.alive = True
|
|
317
|
+
self.chain = None
|
|
318
|
+
self.loaded = None
|
|
319
|
+
self.key = None
|
|
320
|
+
self.run_id = None
|
|
321
|
+
self.state_step = None
|
|
322
|
+
self.base_seen = None
|
|
323
|
+
self.synced_epoch = None
|
|
324
|
+
self.store = DiskStore(_store_folder())
|
|
325
|
+
self.store_lock = threading.Lock()
|
|
326
|
+
self.keep_from = -1
|
|
327
|
+
self.replica = None
|
|
328
|
+
self.settings: dict = {}
|
|
329
|
+
self.server.routes.update({("GET", "/ckpt"): self._serve_ckpt, ("POST", "/replica"): self._take_replica})
|
|
330
|
+
self.log = log or (lambda *a: print("[layerpool]", *a, flush=True))
|
|
331
|
+
|
|
332
|
+
def _ask_pool(self, path: str, patience: float | None = None) -> dict:
|
|
333
|
+
"""Ask the pool, riding out short outages of the network or of a tunnel instead of leaving at once."""
|
|
334
|
+
patience = patience or float(os.environ.get("LAYERPOOL_PATIENCE_S", "1800"))
|
|
335
|
+
start, warned = time.time(), False
|
|
336
|
+
while True:
|
|
337
|
+
try:
|
|
338
|
+
out = self.coord.json(path)
|
|
339
|
+
if warned:
|
|
340
|
+
self.log("the pool answers again")
|
|
341
|
+
return out
|
|
342
|
+
except ConnectionError:
|
|
343
|
+
if time.time() - start > patience:
|
|
344
|
+
raise
|
|
345
|
+
if not warned:
|
|
346
|
+
self.log(f"the pool does not answer; trying again for up to {patience / 60:.0f} minutes")
|
|
347
|
+
warned = True
|
|
348
|
+
time.sleep(5)
|
|
349
|
+
|
|
350
|
+
def _open_tunnel(self):
|
|
351
|
+
self.tunnel = Tunnel(self.server.port, log=self.tunnel_log)
|
|
352
|
+
self.addrs.append(self.tunnel.url)
|
|
353
|
+
|
|
354
|
+
def join(self):
|
|
355
|
+
if self.tunnel_wanted is None and self.tunnel is None:
|
|
356
|
+
try:
|
|
357
|
+
if self.coord.json("/info").get("tunnel"):
|
|
358
|
+
self.tunnel_log("the pool also has devices on the internet, so this device opens a tunnel too")
|
|
359
|
+
self._open_tunnel()
|
|
360
|
+
except HTTPError:
|
|
361
|
+
pass
|
|
362
|
+
if not self.coord.token:
|
|
363
|
+
self._ask_to_join()
|
|
364
|
+
me = self.coord.json("/join", {"name": self.name, "addrs": self.addrs, "token": self.server.token, "devices": self.devices, "cap_gb": self.cap_gb,
|
|
365
|
+
"near": self.coord.urls[0].startswith("http://"), "backend": self.backend,
|
|
366
|
+
"version": __version__, "identity": self.identity,
|
|
367
|
+
"libraries": library_versions(), **self.asked})
|
|
368
|
+
self.wid = me["wid"]
|
|
369
|
+
if isinstance(me.get("settings"), dict):
|
|
370
|
+
self._apply({"settings": me["settings"]})
|
|
371
|
+
if me.get("token"):
|
|
372
|
+
self.coord.token = me["token"]
|
|
373
|
+
self.heartbeat_every = me.get("heartbeat", 5.0)
|
|
374
|
+
self.log(f"joined as {self.wid} ({self.name}, {[d['name'] for d in self.devices]})")
|
|
375
|
+
if not getattr(self, "_beating", False):
|
|
376
|
+
self._beating = True
|
|
377
|
+
threading.Thread(target=self._heartbeat, daemon=True).start()
|
|
378
|
+
|
|
379
|
+
def _ask_to_join(self):
|
|
380
|
+
"""No join code: ask the pool, and wait until someone there approves this device."""
|
|
381
|
+
req = self.coord.json("/request", {"name": self.name, "devices": [d["name"] for d in self.devices]})
|
|
382
|
+
self.log(f"asked to join. Approve this device on the pool's computer: in the dashboard, or with\n\n layerpool approve {req['code']}\n")
|
|
383
|
+
deadline = time.time() + req.get("expires_in_s", 900)
|
|
384
|
+
while time.time() < deadline:
|
|
385
|
+
got = self.coord.json(f"/request?ticket={req['ticket']}")
|
|
386
|
+
if got["status"] == "approved":
|
|
387
|
+
self.coord.token = got["invite"]
|
|
388
|
+
return
|
|
389
|
+
if got["status"] == "denied":
|
|
390
|
+
raise HTTPError(self.coord.urls[0], 403, "the pool denied this device")
|
|
391
|
+
time.sleep(2)
|
|
392
|
+
raise HTTPError(self.coord.urls[0], 403, "nobody approved this device in time")
|
|
393
|
+
|
|
394
|
+
def _telemetry(self) -> dict:
|
|
395
|
+
return sample(self.backend, self.cpu or self.devices[0]["kind"] == "cpu")
|
|
396
|
+
|
|
397
|
+
def _heartbeat(self):
|
|
398
|
+
while self.alive:
|
|
399
|
+
try:
|
|
400
|
+
body = json.dumps({"telemetry": self._telemetry(), "applied": self.settings.get("version", 0)}).encode()
|
|
401
|
+
reply = self.coord.request(f"/hb?w={self.wid}", body, timeout=20, retries=1)
|
|
402
|
+
if reply:
|
|
403
|
+
self._apply(json.loads(reply))
|
|
404
|
+
except Exception:
|
|
405
|
+
pass
|
|
406
|
+
time.sleep(self.heartbeat_every)
|
|
407
|
+
|
|
408
|
+
def _apply(self, reply: dict):
|
|
409
|
+
wanted = reply.get("settings")
|
|
410
|
+
if not wanted or wanted.get("version", 0) == self.settings.get("version", 0):
|
|
411
|
+
return
|
|
412
|
+
self.settings = wanted
|
|
413
|
+
if wanted.get("name"):
|
|
414
|
+
self.name = wanted["name"]
|
|
415
|
+
if "cap_gb" in wanted:
|
|
416
|
+
self.cap_gb = wanted["cap_gb"]
|
|
417
|
+
self._limit_memory()
|
|
418
|
+
|
|
419
|
+
def _gpus(self) -> list[int]:
|
|
420
|
+
"""The GPUs this device trains on: the ones chosen in its settings, or all of them."""
|
|
421
|
+
import torch
|
|
422
|
+
count = torch.cuda.device_count()
|
|
423
|
+
chosen = [i for i in (self.settings.get("gpus") or []) if 0 <= i < count]
|
|
424
|
+
return chosen or list(range(count))
|
|
425
|
+
|
|
426
|
+
def _limit_cuda(self):
|
|
427
|
+
"""Each GPU's share of the device's cap (or its own cap); GPUs left out and GPUs without a cap are not limited."""
|
|
428
|
+
import torch
|
|
429
|
+
used = self._gpus()
|
|
430
|
+
caps = self.settings.get("gpu_caps") or {}
|
|
431
|
+
totals = {i: torch.cuda.get_device_properties(i).total_memory for i in range(torch.cuda.device_count())}
|
|
432
|
+
for i, total in totals.items():
|
|
433
|
+
gb = caps.get(str(i))
|
|
434
|
+
if gb is None and self.cap_gb and i in used:
|
|
435
|
+
gb = self.cap_gb / len(used)
|
|
436
|
+
torch.cuda.set_per_process_memory_fraction(min(1.0, gb * 1e9 / total) if gb else 1.0, i)
|
|
437
|
+
|
|
438
|
+
def _limit_memory(self):
|
|
439
|
+
"""The memory cap, on whatever this device trains with right now: MLX, or PyTorch on CUDA or on the Mac GPU. Without a
|
|
440
|
+
cap, a limit set earlier in this process (such limits are process-wide) is lifted."""
|
|
441
|
+
if not self.cap_gb and not (self.settings.get("gpu_caps") and _has_cuda() and not self.cpu):
|
|
442
|
+
try:
|
|
443
|
+
if getattr(self, "engine", None) == "mlx":
|
|
444
|
+
import mlx.core as mx
|
|
445
|
+
info = mx.device_info() if hasattr(mx, "device_info") else mx.metal.device_info()
|
|
446
|
+
if info.get("max_recommended_working_set_size"):
|
|
447
|
+
mx.set_memory_limit(int(1.5 * info["max_recommended_working_set_size"]))
|
|
448
|
+
elif getattr(self, "engine", None) == "torch" and _has_cuda() and not self.cpu:
|
|
449
|
+
self._limit_cuda()
|
|
450
|
+
elif getattr(self, "engine", None) == "torch" and not self.cpu and _has_mps():
|
|
451
|
+
import torch
|
|
452
|
+
torch.mps.set_per_process_memory_fraction(0.0)
|
|
453
|
+
except Exception as e:
|
|
454
|
+
self.log(f"could not lift the memory cap: {e!r}")
|
|
455
|
+
return
|
|
456
|
+
try:
|
|
457
|
+
if getattr(self, "engine", None) == "mlx":
|
|
458
|
+
import mlx.core as mx
|
|
459
|
+
mx.set_memory_limit(int(self.cap_gb * 1e9))
|
|
460
|
+
elif _has_cuda() and not self.cpu:
|
|
461
|
+
self._limit_cuda()
|
|
462
|
+
elif not self.cpu and getattr(self, "engine", None) == "torch":
|
|
463
|
+
import torch
|
|
464
|
+
if torch.backends.mps.is_available() and hasattr(torch.mps, "recommended_max_memory"):
|
|
465
|
+
torch.mps.set_per_process_memory_fraction(min(2.0, self.cap_gb * 1e9 / torch.mps.recommended_max_memory()))
|
|
466
|
+
except Exception as e:
|
|
467
|
+
self.log(f"could not apply the memory cap: {e!r}")
|
|
468
|
+
|
|
469
|
+
def _release(self, keep: set | None = None):
|
|
470
|
+
if self.chain is not None:
|
|
471
|
+
if self.state_step is not None and self.state_step >= 0:
|
|
472
|
+
packed = self._pack(self._snapshot())
|
|
473
|
+
self._keep(self.state_step, packed)
|
|
474
|
+
leaving = [u for u in packed if keep is None or u not in keep]
|
|
475
|
+
if leaving:
|
|
476
|
+
try:
|
|
477
|
+
self.coord.request(f"/have?w={self.wid}&run={self.run_id}",
|
|
478
|
+
json.dumps({"step": self.state_step, "layers": leaving, "holders": [self.wid]}).encode())
|
|
479
|
+
except Exception as e:
|
|
480
|
+
self.log(f"could not register the checkpoint of step {self.state_step}: {e!r}")
|
|
481
|
+
self.chain = None
|
|
482
|
+
self.loaded = None
|
|
483
|
+
self.key = None
|
|
484
|
+
self.state_step = None
|
|
485
|
+
self.synced_epoch = None
|
|
486
|
+
self._free_caches()
|
|
487
|
+
|
|
488
|
+
def _free_caches(self):
|
|
489
|
+
gc.collect()
|
|
490
|
+
if "torch" in sys.modules:
|
|
491
|
+
import torch
|
|
492
|
+
if torch.cuda.is_available():
|
|
493
|
+
torch.cuda.empty_cache()
|
|
494
|
+
elif torch.backends.mps.is_available():
|
|
495
|
+
torch.mps.empty_cache()
|
|
496
|
+
if "mlx.core" in sys.modules:
|
|
497
|
+
import mlx.core as mx
|
|
498
|
+
mx.clear_cache()
|
|
499
|
+
|
|
500
|
+
def _peak_gb(self) -> float:
|
|
501
|
+
"""The most memory training used here since the last check, then the count starts again."""
|
|
502
|
+
peak = 0.0
|
|
503
|
+
try:
|
|
504
|
+
if self.cpu or self.devices[0]["kind"] == "cpu":
|
|
505
|
+
import psutil
|
|
506
|
+
return psutil.Process().memory_info().rss / 1e9
|
|
507
|
+
if "torch" in sys.modules:
|
|
508
|
+
import torch
|
|
509
|
+
if torch.cuda.is_available():
|
|
510
|
+
for i in self._gpus():
|
|
511
|
+
peak += torch.cuda.max_memory_allocated(i) / 1e9
|
|
512
|
+
torch.cuda.reset_peak_memory_stats(i)
|
|
513
|
+
elif torch.backends.mps.is_available():
|
|
514
|
+
peak = max(peak, torch.mps.driver_allocated_memory() / 1e9)
|
|
515
|
+
if "mlx.core" in sys.modules:
|
|
516
|
+
import mlx.core as mx
|
|
517
|
+
peak = max(peak, mx.get_peak_memory() / 1e9)
|
|
518
|
+
mx.reset_peak_memory()
|
|
519
|
+
except Exception:
|
|
520
|
+
pass
|
|
521
|
+
return peak
|
|
522
|
+
|
|
523
|
+
def _units(self, first: int, last: int) -> set:
|
|
524
|
+
return set(range(first, last))
|
|
525
|
+
|
|
526
|
+
def _mlx(self, job: dict) -> bool:
|
|
527
|
+
"""MLX for text models whose blocks mlx-lm computes as transformers does (checked once per architecture on a small
|
|
528
|
+
copy); PyTorch on the Mac GPU for the rest. A 4-bit run has no PyTorch way on a Mac, so then this Mac sits it out."""
|
|
529
|
+
if self.backend != "mlx" or not job.get("mlx_ok"):
|
|
530
|
+
return False
|
|
531
|
+
key = (job["repo"], job.get("auto"), job.get("mode", "lora"))
|
|
532
|
+
verdicts = self.__dict__.setdefault("_mlx_verdicts", {})
|
|
533
|
+
if key not in verdicts:
|
|
534
|
+
from .backends.mlx_backend import verify
|
|
535
|
+
verdicts[key] = verify(job["repo"], job.get("auto", "AutoModelForCausalLM"), job.get("mode", "lora"), log=self.log)
|
|
536
|
+
if verdicts[key]:
|
|
537
|
+
self.log(f"MLX does not compute this model's blocks as transformers does ({verdicts[key]}), so this Mac trains them "
|
|
538
|
+
"with PyTorch")
|
|
539
|
+
if verdicts[key] and job.get("kind") == "q4":
|
|
540
|
+
raise RuntimeError(f"this Mac cannot train this 4-bit model: MLX does not compute its blocks as transformers does "
|
|
541
|
+
f"({verdicts[key]}), and PyTorch on a Mac has no 4-bit layers")
|
|
542
|
+
return not verdicts[key]
|
|
543
|
+
|
|
544
|
+
def _build_mlx(self, job: dict, first: int, last: int) -> list:
|
|
545
|
+
import mlx.core as mx
|
|
546
|
+
from .backends.mlx_backend import StageCore, load_range
|
|
547
|
+
self.engine = "mlx"
|
|
548
|
+
self._limit_memory()
|
|
549
|
+
full = job.get("mode") == "full"
|
|
550
|
+
loader = lambda: load_range(job.get("mlx_repo") or job["repo"], first, last, job["layout"]["n"], job["layout"]["stack"],
|
|
551
|
+
mx.float32 if full else None,
|
|
552
|
+
random_init=job.get("random_init", False), log=self.log)
|
|
553
|
+
return [StageCore(loader, first, job["rank"], job["scale"], job["lr"], loss_scale=job.get("loss_scale", 1024.0),
|
|
554
|
+
checkpointing=job.get("checkpointing", True), device=mx.cpu if self.cpu else mx.gpu, mode=job.get("mode", "lora"),
|
|
555
|
+
weight_decay=job.get("weight_decay", 0.0), targets=job.get("target_modules"))]
|
|
556
|
+
|
|
557
|
+
def _build_torch(self, job: dict, first: int, last: int, on_gpu: int | None = None) -> tuple[list, list]:
|
|
558
|
+
import torch
|
|
559
|
+
self.engine = "torch"
|
|
560
|
+
self._limit_memory()
|
|
561
|
+
mode = job.get("mode", "lora")
|
|
562
|
+
loss_scale = job.get("loss_scale", 1024.0)
|
|
563
|
+
if torch.cuda.is_available() and not self.cpu:
|
|
564
|
+
devices = [f"cuda:{i}" for i in self._gpus()]
|
|
565
|
+
elif not self.cpu and getattr(torch.backends, "mps", None) is not None and torch.backends.mps.is_available():
|
|
566
|
+
devices = ["mps"]
|
|
567
|
+
else:
|
|
568
|
+
devices = ["cpu"]
|
|
569
|
+
spill_from = last if on_gpu is None or not devices[0].startswith("cuda") else first + on_gpu
|
|
570
|
+
n = spill_from - first
|
|
571
|
+
caps = self.settings.get("gpu_caps") or {}
|
|
572
|
+
index = lambda d: int(d.split(":")[1])
|
|
573
|
+
share = self.cap_gb * 1e9 / len(devices) if self.cap_gb else float("inf")
|
|
574
|
+
room = [min(torch.cuda.mem_get_info(index(d))[0], caps[str(index(d))] * 1e9 if str(index(d)) in caps else share)
|
|
575
|
+
for d in devices] if devices[0].startswith("cuda") else [1.0] * len(devices)
|
|
576
|
+
share = [sum(room[:i]) / sum(room) for i in range(len(devices) + 1)]
|
|
577
|
+
parts = [(first + round(share[i] * n), first + round(share[i + 1] * n), d) for i, d in enumerate(devices)]
|
|
578
|
+
parts = [(a, b, d) for a, b, d in parts if b > a]
|
|
579
|
+
if spill_from < last:
|
|
580
|
+
parts.append((spill_from, last, "cpu"))
|
|
581
|
+
cores = []
|
|
582
|
+
kwargs = dict(loss_scale=loss_scale, checkpointing=job.get("checkpointing", True), mode=mode, weight_decay=job.get("weight_decay", 0.0),
|
|
583
|
+
targets=job.get("target_modules"))
|
|
584
|
+
quantized = job["kind"] == "q4"
|
|
585
|
+
half = train_dtype(devices[0].split(":")[0])
|
|
586
|
+
dtype = torch.float32 if mode == "full" else half
|
|
587
|
+
for a_, b_, d in parts:
|
|
588
|
+
here = torch.float32 if d == "cpu" else (half if half != torch.float32 else torch.float16) if quantized else dtype
|
|
589
|
+
blocks = load_blocks(job["repo"], job["layout"], a_, b_, d, here, quantized=quantized, random_init=job.get("random_init", False),
|
|
590
|
+
log=self.log)
|
|
591
|
+
cores.append(BlockCore(blocks, a_, job["rank"], job["scale"], job["lr"], **kwargs))
|
|
592
|
+
cores[-1].spill = d == "cpu" and devices[0] != "cpu"
|
|
593
|
+
return cores, [d for _, _, d in parts]
|
|
594
|
+
|
|
595
|
+
def _build(self, a: dict):
|
|
596
|
+
job, (first, last) = a["job"], a["range"]
|
|
597
|
+
self._release(self._units(first, last))
|
|
598
|
+
t = time.time()
|
|
599
|
+
if self._mlx(job):
|
|
600
|
+
cores, devices = self._build_mlx(job, first, last), ["mlx"]
|
|
601
|
+
else:
|
|
602
|
+
cores, devices = self._build_torch(job, first, last, a.get("on_gpu"))
|
|
603
|
+
self.chain = cores
|
|
604
|
+
self.loaded = (first, last, a.get("on_gpu"))
|
|
605
|
+
self.key = model_key(job, first, last)
|
|
606
|
+
self.built_gpus = (self.settings.get("gpus"), self.settings.get("gpu_caps"))
|
|
607
|
+
self.state_step, self.base_seen = -1, None
|
|
608
|
+
self.log(f"loaded layers {first}-{last} on {devices[:len(cores)]} in {time.time() - t:.0f}s")
|
|
609
|
+
|
|
610
|
+
def _rewrap(self, job: dict):
|
|
611
|
+
cores = []
|
|
612
|
+
kwargs = dict(loss_scale=job.get("loss_scale", 1024.0), checkpointing=job.get("checkpointing", True), mode="lora", weight_decay=job.get("weight_decay", 0.0),
|
|
613
|
+
targets=job.get("target_modules"))
|
|
614
|
+
for core in self.chain:
|
|
615
|
+
if self._mlx(job):
|
|
616
|
+
from .backends.mlx_backend import StageCore
|
|
617
|
+
import mlx.core as mx
|
|
618
|
+
held = (core.model, core.layers)
|
|
619
|
+
cores.append(StageCore(lambda held=held: held, core.first, job["rank"], job["scale"], job["lr"],
|
|
620
|
+
device=mx.cpu if self.cpu else mx.gpu, **kwargs))
|
|
621
|
+
else:
|
|
622
|
+
cores.append(BlockCore(unwrap_lora(core.layers), core.first, job["rank"], job["scale"], job["lr"], **kwargs))
|
|
623
|
+
cores[-1].spill = getattr(core, "spill", False)
|
|
624
|
+
self.chain = cores
|
|
625
|
+
self.state_step, self.base_seen = -1, None
|
|
626
|
+
self.log("kept the loaded model for the new run")
|
|
627
|
+
|
|
628
|
+
def _serve_ckpt(self, query, body):
|
|
629
|
+
with self.store_lock:
|
|
630
|
+
data = self.store.get((int(query["layer"]), int(query["step"])))
|
|
631
|
+
return (200, data) if data is not None else (404, b"")
|
|
632
|
+
|
|
633
|
+
def _take_replica(self, query, body):
|
|
634
|
+
if query.get("run") != self.run_id:
|
|
635
|
+
return 409, {"error": "a checkpoint copy of another run"}
|
|
636
|
+
with self.store_lock:
|
|
637
|
+
self.store[(int(query["layer"]), int(query["step"]))] = body
|
|
638
|
+
return 200, b""
|
|
639
|
+
|
|
640
|
+
def _pack(self, flat: dict) -> dict[int, bytes]:
|
|
641
|
+
return {u: pack(None, **{k: v for k, v in flat.items() if unit_of(k) == u}) for u in sorted({unit_of(k) for k in flat})}
|
|
642
|
+
|
|
643
|
+
def _keep(self, step: int, packed: dict[int, bytes]):
|
|
644
|
+
with self.store_lock:
|
|
645
|
+
for u, data in packed.items():
|
|
646
|
+
self.store[(u, step)] = data
|
|
647
|
+
|
|
648
|
+
def _prune(self, keep_from: int):
|
|
649
|
+
self.keep_from = max(self.keep_from, keep_from)
|
|
650
|
+
with self.store_lock:
|
|
651
|
+
own = sorted({st for _, st in self.store})[-2:]
|
|
652
|
+
for key in [k for k in self.store if k[1] < self.keep_from and k[1] not in own]:
|
|
653
|
+
del self.store[key]
|
|
654
|
+
|
|
655
|
+
def _fetch(self, unit: int, step: int, epoch: int, patience: float = 900.0) -> bytes:
|
|
656
|
+
with self.store_lock:
|
|
657
|
+
if (unit, step) in self.store:
|
|
658
|
+
return self.store[(unit, step)]
|
|
659
|
+
deadline = time.time() + patience
|
|
660
|
+
while True:
|
|
661
|
+
try:
|
|
662
|
+
where = self.coord.json(f"/where?w={self.wid}&layer={unit}&step={step}&epoch={epoch}&wait=60")
|
|
663
|
+
except urllib.error.HTTPError as e:
|
|
664
|
+
if e.code != 404 or time.time() > deadline:
|
|
665
|
+
raise
|
|
666
|
+
continue
|
|
667
|
+
for holder in where["holders"]:
|
|
668
|
+
try:
|
|
669
|
+
if holder["w"] == "coord":
|
|
670
|
+
return self.coord.get_blob(f"/ckpt?layer={unit}&step={step}")
|
|
671
|
+
if holder["w"] != self.wid:
|
|
672
|
+
return Peer(holder["addrs"], holder["token"]).get_blob(f"/ckpt?layer={unit}&step={step}")
|
|
673
|
+
except Exception as e:
|
|
674
|
+
self.log(f"could not fetch layer {unit} from {holder['w']}: {e!r}")
|
|
675
|
+
if time.time() > deadline:
|
|
676
|
+
raise ConnectionError(f"no holder of layer {unit} at step {step} could be reached")
|
|
677
|
+
time.sleep(2)
|
|
678
|
+
|
|
679
|
+
def _restore(self, step: int, epoch: int, units: set, base=None):
|
|
680
|
+
t = time.time()
|
|
681
|
+
state, fetched = {}, 0
|
|
682
|
+
if step == -1 and not base:
|
|
683
|
+
for core in self.chain:
|
|
684
|
+
state.update(core.initial())
|
|
685
|
+
else:
|
|
686
|
+
for u in sorted(units):
|
|
687
|
+
with self.store_lock:
|
|
688
|
+
local = None if step == -1 else self.store.get((u, step))
|
|
689
|
+
if local is None:
|
|
690
|
+
local, fetched = self._fetch(u, step, epoch), fetched + 1
|
|
691
|
+
self._keep(step, {u: local})
|
|
692
|
+
state.update(unpack(local)[1])
|
|
693
|
+
for core in self.chain:
|
|
694
|
+
core.zero_grad()
|
|
695
|
+
restored = core.load_state(state)
|
|
696
|
+
expected = len(core.params) if hasattr(core, "params") else restored
|
|
697
|
+
if step >= 0 and restored < expected:
|
|
698
|
+
raise RuntimeError(f"the checkpoint of layers {core.first}-{core.first + len(core.layers) - 1} has {restored} of the {expected} weights this "
|
|
699
|
+
"device trains; the devices of this pool build the model differently (use the same transformers version)")
|
|
700
|
+
self.state_step = step
|
|
701
|
+
self.base_seen = base
|
|
702
|
+
source = "the initial values" if step == -1 and not base else f"{len(units) - fetched} parts held here, {fetched} fetched"
|
|
703
|
+
self.log(f"restored the state after step {step} ({source}) in {time.time() - t:.1f}s")
|
|
704
|
+
|
|
705
|
+
def _zero_grad(self):
|
|
706
|
+
for stage in self.chain or []:
|
|
707
|
+
stage.zero_grad()
|
|
708
|
+
|
|
709
|
+
def _snapshot(self) -> dict:
|
|
710
|
+
flat = {}
|
|
711
|
+
for core in self.chain or []:
|
|
712
|
+
flat.update(core.state())
|
|
713
|
+
return flat
|
|
714
|
+
|
|
715
|
+
def _checkpoint(self, step: int, packed: dict[int, bytes], target: str, run_id: str | None = None):
|
|
716
|
+
"""Send a checkpoint to the pool or to the neighbour that keeps a copy, under the run it was taken in."""
|
|
717
|
+
run_id = run_id or self.run_id
|
|
718
|
+
holders = [self.wid]
|
|
719
|
+
replica = None if target == "coord" else self.replica
|
|
720
|
+
try:
|
|
721
|
+
if replica is None:
|
|
722
|
+
for u, data in packed.items():
|
|
723
|
+
self.coord.post_blob(f"/ckpt?w={self.wid}&run={run_id}&layer={u}&step={step}", data)
|
|
724
|
+
else:
|
|
725
|
+
peer = Peer(replica["addrs"], replica["token"])
|
|
726
|
+
for u, data in packed.items():
|
|
727
|
+
peer.post_blob(f"/replica?run={run_id}&layer={u}&step={step}", data, retries=3)
|
|
728
|
+
holders.append(replica["w"])
|
|
729
|
+
except Exception as e:
|
|
730
|
+
self.log(f"checkpoint copy of step {step} failed: {e!r}")
|
|
731
|
+
try:
|
|
732
|
+
self.coord.request(f"/have?w={self.wid}&run={run_id}", json.dumps({"step": step, "layers": list(packed), "holders": holders}).encode())
|
|
733
|
+
except Exception as e:
|
|
734
|
+
self.log(f"could not register checkpoint of step {step}: {e!r}")
|
|
735
|
+
|
|
736
|
+
def run(self):
|
|
737
|
+
self.join()
|
|
738
|
+
awake = None if self.allow_sleep else keep_awake()
|
|
739
|
+
told = None
|
|
740
|
+
try:
|
|
741
|
+
while self.alive:
|
|
742
|
+
if self.tunnel is not None and not self.tunnel.alive():
|
|
743
|
+
self.log("this device's tunnel stopped; opening a new one and joining the pool again")
|
|
744
|
+
self.addrs = [u for u in self.addrs if u != self.tunnel.url]
|
|
745
|
+
self._release()
|
|
746
|
+
try:
|
|
747
|
+
self._open_tunnel()
|
|
748
|
+
except Exception as e:
|
|
749
|
+
self.log(f"could not open a new tunnel ({str(e).splitlines()[0]}); trying again in a minute")
|
|
750
|
+
time.sleep(60)
|
|
751
|
+
continue
|
|
752
|
+
self.join()
|
|
753
|
+
continue
|
|
754
|
+
try:
|
|
755
|
+
a = self._ask_pool(f"/assignment?w={self.wid}")
|
|
756
|
+
except HTTPError as e:
|
|
757
|
+
if e.code != 409:
|
|
758
|
+
raise
|
|
759
|
+
self.log("the pool restarted; joining it again")
|
|
760
|
+
self._release()
|
|
761
|
+
self.join()
|
|
762
|
+
continue
|
|
763
|
+
if a.get("left_out") and a["left_out"] != told:
|
|
764
|
+
told = a["left_out"]
|
|
765
|
+
self.log(f"left out of this run after repeated errors ({told}); it will be used again in the next run")
|
|
766
|
+
if a.get("done"):
|
|
767
|
+
break
|
|
768
|
+
if a.get("wait"):
|
|
769
|
+
if self.chain is not None and a.get("run") is not None and a.get("run") == self.run_id:
|
|
770
|
+
try:
|
|
771
|
+
self._release()
|
|
772
|
+
self.log("left out of the current split; handed this device's layers to the others")
|
|
773
|
+
except Exception as e:
|
|
774
|
+
self.log("could not hand over the layers:", repr(e))
|
|
775
|
+
self.chain = None
|
|
776
|
+
time.sleep(0.5)
|
|
777
|
+
continue
|
|
778
|
+
self._apply(a)
|
|
779
|
+
self.replica = a.get("replica")
|
|
780
|
+
self._prune(a.get("keep_from", -1))
|
|
781
|
+
job, (first, last) = a["job"], a["range"]
|
|
782
|
+
try:
|
|
783
|
+
if a["run"] != self.run_id:
|
|
784
|
+
with self.store_lock:
|
|
785
|
+
self.store.clear()
|
|
786
|
+
self.keep_from = -1
|
|
787
|
+
self.state_step = None
|
|
788
|
+
if self.chain is not None and self.key == model_key(job, first, last) and job.get("mode", "lora") == "lora":
|
|
789
|
+
self._rewrap(job)
|
|
790
|
+
else:
|
|
791
|
+
self._release()
|
|
792
|
+
self.run_id = a["run"]
|
|
793
|
+
self.synced_epoch = None
|
|
794
|
+
if self.loaded != (first, last, a.get("on_gpu")) or (self.chain is not None and getattr(self, "built_gpus", None) is not None
|
|
795
|
+
and self.built_gpus != (self.settings.get("gpus"), self.settings.get("gpu_caps"))):
|
|
796
|
+
self._build(a)
|
|
797
|
+
if self.synced_epoch != a["epoch"]:
|
|
798
|
+
if self.state_step != a["restore"] or (a["restore"] == -1 and self.base_seen != job.get("base")):
|
|
799
|
+
self._restore(a["restore"], a["epoch"], self._units(first, last), job.get("base"))
|
|
800
|
+
self.synced_epoch = a["epoch"]
|
|
801
|
+
self.coord.request(f"/ready?w={self.wid}&epoch={a['epoch']}", b"")
|
|
802
|
+
self._failures = 0
|
|
803
|
+
self._serve(a)
|
|
804
|
+
except Abort:
|
|
805
|
+
self._zero_grad()
|
|
806
|
+
except Exception as e:
|
|
807
|
+
self._zero_grad()
|
|
808
|
+
try:
|
|
809
|
+
now = self.coord.json(f"/epoch?w={self.wid}")
|
|
810
|
+
except Exception:
|
|
811
|
+
raise e
|
|
812
|
+
if now["epoch"] != a["epoch"] or now["finished"]:
|
|
813
|
+
self.log(f"plan {a['epoch']} ended while working ({e!r})")
|
|
814
|
+
continue
|
|
815
|
+
oom = out_of_memory(e)
|
|
816
|
+
peak = self._peak_gb() if oom else None
|
|
817
|
+
self._free_caches()
|
|
818
|
+
if oom:
|
|
819
|
+
self.log(f"ran out of memory (about {peak:.1f} GB in use): asking for fewer layers")
|
|
820
|
+
else:
|
|
821
|
+
self.log("error:", repr(e))
|
|
822
|
+
traceback.print_exc()
|
|
823
|
+
blame = f"&blame={e.wid}" if isinstance(e, NeighbourDown) else ""
|
|
824
|
+
extra = f"&oom={peak:.2f}" if oom else ""
|
|
825
|
+
if not oom and not blame and getattr(self, "engine", None) == "mlx" and job.get("kind") != "q4":
|
|
826
|
+
self.__dict__.setdefault("_mlx_verdicts", {})[(job["repo"], job.get("auto"), job.get("mode", "lora"))] = repr(e)
|
|
827
|
+
self.log(f"MLX failed on this model ({e!r}); this Mac goes on with PyTorch")
|
|
828
|
+
self._release()
|
|
829
|
+
extra = "&switched=1"
|
|
830
|
+
self.coord.request(f"/fail?w={self.wid}{blame}{extra}", repr(e).encode())
|
|
831
|
+
self._failures = getattr(self, "_failures", 0) + 1
|
|
832
|
+
time.sleep(min(30, 3 * self._failures))
|
|
833
|
+
finally:
|
|
834
|
+
self.alive = False
|
|
835
|
+
if awake is not None:
|
|
836
|
+
awake.terminate()
|
|
837
|
+
if self.tunnel:
|
|
838
|
+
self.tunnel.close()
|
|
839
|
+
self.server.close()
|
|
840
|
+
self.store.close()
|
|
841
|
+
self.log("worker stopped")
|
|
842
|
+
|
|
843
|
+
def _serve(self, a: dict):
|
|
844
|
+
job, epoch = a["job"], a["epoch"]
|
|
845
|
+
self._neighbours = {side: a[side]["w"] for side in ("prev", "next") if a.get(side)}
|
|
846
|
+
stop = threading.Event()
|
|
847
|
+
streams = job.get("streams", 3)
|
|
848
|
+
senders = {side: Sender(Peer(a[side]["addrs"], a[side]["token"]), streams, cancel=stop.is_set) for side in ("prev", "next") if a.get(side)}
|
|
849
|
+
|
|
850
|
+
def watch():
|
|
851
|
+
misses = 0
|
|
852
|
+
while not stop.is_set():
|
|
853
|
+
time.sleep(1)
|
|
854
|
+
try:
|
|
855
|
+
now = self.coord.json(f"/epoch?w={self.wid}")
|
|
856
|
+
misses = 0
|
|
857
|
+
self._prune(now.get("keep_from", -1))
|
|
858
|
+
if now["epoch"] != epoch or now["finished"]:
|
|
859
|
+
stop.set()
|
|
860
|
+
except Exception:
|
|
861
|
+
misses += 1
|
|
862
|
+
if misses >= 30:
|
|
863
|
+
self.log("the pool has not answered for 30 s")
|
|
864
|
+
stop.set()
|
|
865
|
+
threading.Thread(target=watch, daemon=True).start()
|
|
866
|
+
inbox = self.server.inbox
|
|
867
|
+
inbox.drop(lambda k: k[1] == str(epoch))
|
|
868
|
+
seq = a["seq"]
|
|
869
|
+
try:
|
|
870
|
+
while True:
|
|
871
|
+
data = inbox.get(("op", str(epoch), str(seq)), cancel=stop.is_set)
|
|
872
|
+
if data is None:
|
|
873
|
+
raise Abort()
|
|
874
|
+
op = json.loads(data)
|
|
875
|
+
if op["type"] in ("fb", "fwd"):
|
|
876
|
+
report = self._pipeline(op, job, epoch, seq, stop, senders)
|
|
877
|
+
elif op["type"] == "commit":
|
|
878
|
+
report = self._commit(op, job)
|
|
879
|
+
elif op["type"] == "save":
|
|
880
|
+
report = self._save(op)
|
|
881
|
+
else:
|
|
882
|
+
raise ValueError(f"unknown operation {op['type']}")
|
|
883
|
+
self.coord.request(f"/done?w={self.wid}&epoch={epoch}&seq={seq}", json.dumps(report).encode())
|
|
884
|
+
seq += 1
|
|
885
|
+
finally:
|
|
886
|
+
stop.set()
|
|
887
|
+
for sender in senders.values():
|
|
888
|
+
sender.close()
|
|
889
|
+
|
|
890
|
+
def _commit(self, op: dict, job: dict) -> dict:
|
|
891
|
+
for core in self.chain:
|
|
892
|
+
if op.get("weight_decay") is not None:
|
|
893
|
+
core.set_weight_decay(op["weight_decay"])
|
|
894
|
+
core.step(lr=op.get("lr"), clip=op.get("clip", 1.0), skip=op.get("skip", False))
|
|
895
|
+
if op.get("lower_scale"):
|
|
896
|
+
core.loss_scale = min(core.loss_scale, op["lower_scale"])
|
|
897
|
+
step = op["step"]
|
|
898
|
+
self.state_step = step
|
|
899
|
+
if (step + 1) % job.get("ckpt_every", 4) == 0 or op.get("checkpoint"):
|
|
900
|
+
packed = self._pack(self._snapshot())
|
|
901
|
+
self._keep(step, packed)
|
|
902
|
+
self._upload_later(step, packed)
|
|
903
|
+
return {"step": step}
|
|
904
|
+
|
|
905
|
+
def _upload_later(self, step: int, packed: dict):
|
|
906
|
+
"""Copies of checkpoints go out one at a time; while one uploads, a newer one replaces the one waiting, so a slow uplink
|
|
907
|
+
sends fewer checkpoints instead of piling them up in memory."""
|
|
908
|
+
with self.store_lock:
|
|
909
|
+
self._next_upload = (self.run_id, step, packed)
|
|
910
|
+
if getattr(self, "_uploading", False):
|
|
911
|
+
return
|
|
912
|
+
self._uploading = True
|
|
913
|
+
|
|
914
|
+
def loop():
|
|
915
|
+
while True:
|
|
916
|
+
with self.store_lock:
|
|
917
|
+
item, self._next_upload = self._next_upload, None
|
|
918
|
+
if item is None:
|
|
919
|
+
self._uploading = False
|
|
920
|
+
return
|
|
921
|
+
if item[0] == self.run_id:
|
|
922
|
+
self._checkpoint(item[1], item[2], "replica", item[0])
|
|
923
|
+
threading.Thread(target=loop, daemon=True).start()
|
|
924
|
+
|
|
925
|
+
def _save(self, op: dict) -> dict:
|
|
926
|
+
if op.get("weights_only"):
|
|
927
|
+
weights = {k: v for k, v in self._snapshot().items() if op.get("moments") or not k.endswith((".m", ".v", ".t"))}
|
|
928
|
+
half = op.get("dtype") in ("bfloat16", "float16")
|
|
929
|
+
by_unit = {}
|
|
930
|
+
for k, v in weights.items():
|
|
931
|
+
by_unit.setdefault(unit_of(k), {})[k] = v
|
|
932
|
+
step = self.state_step
|
|
933
|
+
|
|
934
|
+
def send(item):
|
|
935
|
+
u, flat = item
|
|
936
|
+
meta, arrays = (to_half(flat, op["dtype"]) if half else (None, flat))
|
|
937
|
+
self.coord.post_blob(f"/export?w={self.wid}&run={self.run_id}&layer={u}&step={step}", pack(meta, **arrays))
|
|
938
|
+
with ThreadPoolExecutor(4) as ex:
|
|
939
|
+
list(ex.map(send, sorted(by_unit.items())))
|
|
940
|
+
return {"step": step}
|
|
941
|
+
packed = self._pack(self._snapshot())
|
|
942
|
+
self._keep(self.state_step, packed)
|
|
943
|
+
self._checkpoint(self.state_step, packed, op.get("target", "coord"))
|
|
944
|
+
return {"step": self.state_step}
|
|
945
|
+
|
|
946
|
+
def _pipeline(self, op: dict, job: dict, epoch: int, seq: int, stop: threading.Event, senders: dict) -> dict:
|
|
947
|
+
n_micro = op["n"]
|
|
948
|
+
backward = op["type"] == "fb"
|
|
949
|
+
inbox = self.server.inbox
|
|
950
|
+
n = len(self.chain)
|
|
951
|
+
clock = {"compute": 0.0, "wait": 0.0}
|
|
952
|
+
per_core = [0.0] * n
|
|
953
|
+
lock = threading.Lock()
|
|
954
|
+
errors = []
|
|
955
|
+
fq = [queue.Queue() for _ in range(n + 1)]
|
|
956
|
+
bq = [queue.Queue() for _ in range(n + 1)]
|
|
957
|
+
for sender in senders.values():
|
|
958
|
+
sender.busy = 0.0
|
|
959
|
+
if not op.get("adapter", True):
|
|
960
|
+
for core in self.chain:
|
|
961
|
+
core.set_adapter(False)
|
|
962
|
+
|
|
963
|
+
def timed(kind, fn, *args, ci=None, **kwargs):
|
|
964
|
+
t0 = time.time()
|
|
965
|
+
try:
|
|
966
|
+
return fn(*args, **kwargs)
|
|
967
|
+
finally:
|
|
968
|
+
with lock:
|
|
969
|
+
clock[kind] += time.time() - t0
|
|
970
|
+
if ci is not None:
|
|
971
|
+
per_core[ci] += time.time() - t0
|
|
972
|
+
|
|
973
|
+
def blame(side, call):
|
|
974
|
+
try:
|
|
975
|
+
return call()
|
|
976
|
+
except Cancelled:
|
|
977
|
+
raise Abort()
|
|
978
|
+
except ConnectionError as e:
|
|
979
|
+
raise NeighbourDown(a_side(side), e)
|
|
980
|
+
|
|
981
|
+
def a_side(side):
|
|
982
|
+
return self._neighbours.get(side)
|
|
983
|
+
|
|
984
|
+
def push(side, key, data):
|
|
985
|
+
blame(side, lambda: senders[side].put(key, data))
|
|
986
|
+
|
|
987
|
+
def recv(kind, m):
|
|
988
|
+
data = timed("wait", inbox.get, (kind, str(epoch), str(seq), str(m)), cancel=lambda: stop.is_set() or bool(errors))
|
|
989
|
+
if data is None:
|
|
990
|
+
raise Abort()
|
|
991
|
+
return unpack(data)
|
|
992
|
+
|
|
993
|
+
def recv_any(kind, pending):
|
|
994
|
+
t0 = time.time()
|
|
995
|
+
try:
|
|
996
|
+
while True:
|
|
997
|
+
for m in sorted(pending):
|
|
998
|
+
data = inbox.get((kind, str(epoch), str(seq), str(m)), timeout=0.05)
|
|
999
|
+
if data is not None:
|
|
1000
|
+
return m, unpack(data)[1]
|
|
1001
|
+
if stop.is_set() or errors:
|
|
1002
|
+
raise Abort()
|
|
1003
|
+
finally:
|
|
1004
|
+
with lock:
|
|
1005
|
+
clock["wait"] += time.time() - t0
|
|
1006
|
+
|
|
1007
|
+
def get(q):
|
|
1008
|
+
t0 = time.time()
|
|
1009
|
+
try:
|
|
1010
|
+
while True:
|
|
1011
|
+
if stop.is_set() or errors:
|
|
1012
|
+
raise Abort()
|
|
1013
|
+
try:
|
|
1014
|
+
return q.get(timeout=0.2)
|
|
1015
|
+
except queue.Empty:
|
|
1016
|
+
pass
|
|
1017
|
+
finally:
|
|
1018
|
+
with lock:
|
|
1019
|
+
clock["wait"] += time.time() - t0
|
|
1020
|
+
|
|
1021
|
+
first_stage, last_stage = "prev" not in senders, "next" not in senders
|
|
1022
|
+
out_codec = "fp32" if job["codec"] == "fp32" else "fp16"
|
|
1023
|
+
grads_back = op.get("grads", False)
|
|
1024
|
+
args_of = {}
|
|
1025
|
+
|
|
1026
|
+
def core_args(core, m):
|
|
1027
|
+
meta, arrays = args_of[m]
|
|
1028
|
+
if not hasattr(core, "device"):
|
|
1029
|
+
return mlx_masks(meta, arrays, range(core.first, core.first + len(core.layers))), {}
|
|
1030
|
+
return unpack_args(meta, arrays, core.device, core.dtype, range(core.first, core.first + len(core.layers)))
|
|
1031
|
+
|
|
1032
|
+
def grads_message(g, sides, carried=None, core=None):
|
|
1033
|
+
parts = with_prefix(encode(g, job["codec"], 0), "g_")
|
|
1034
|
+
for k, v in sides.items():
|
|
1035
|
+
parts.update(with_prefix(encode(v, "fp32"), f"s{k}_"))
|
|
1036
|
+
parts.update(carried_parts(carried or {}, "q", core))
|
|
1037
|
+
return pack(None, **parts)
|
|
1038
|
+
|
|
1039
|
+
def carried_parts(carried, letter, core):
|
|
1040
|
+
"""Block outputs that later blocks take (T5's position bias), or their gradients, in full precision: they can hold
|
|
1041
|
+
mask values a 16-bit code cannot."""
|
|
1042
|
+
parts = {}
|
|
1043
|
+
for (i, k), v in carried.items():
|
|
1044
|
+
parts.update(with_prefix(encode(core.numpy(v), "fp32"), f"{letter}{i}_{k}_"))
|
|
1045
|
+
return parts
|
|
1046
|
+
|
|
1047
|
+
def carried_from(arrays, letter, core):
|
|
1048
|
+
keys = {(int(m.group(1)), int(m.group(2))) for m in (re.match(rf"^{letter}(\d+)_(\d+)_", a) for a in arrays) if m}
|
|
1049
|
+
return {key: core.tensor(decode(split_prefix(arrays, f"{letter}{key[0]}_{key[1]}_"))) for key in keys}
|
|
1050
|
+
|
|
1051
|
+
def plan_of(m):
|
|
1052
|
+
meta = args_of[m][0] or {}
|
|
1053
|
+
return meta.get("carry")
|
|
1054
|
+
|
|
1055
|
+
def add_sides(total, sides, core):
|
|
1056
|
+
for k, v in sides.items():
|
|
1057
|
+
if v is not None:
|
|
1058
|
+
v = core.numpy(v) if not isinstance(v, np.ndarray) else v
|
|
1059
|
+
total[k] = total[k] + v if k in total else v
|
|
1060
|
+
|
|
1061
|
+
def core_loop(ci):
|
|
1062
|
+
core = self.chain[ci]
|
|
1063
|
+
head, tail = ci == 0, ci == n - 1
|
|
1064
|
+
saved = {}
|
|
1065
|
+
for index in range(n_micro):
|
|
1066
|
+
if head:
|
|
1067
|
+
m = index
|
|
1068
|
+
meta, arrays = recv("d" if first_stage else "f", m)
|
|
1069
|
+
args_of[m] = ((meta or {}).get("args"), split_prefix(arrays, "a_"))
|
|
1070
|
+
x = core.tensor(decode(split_prefix(arrays, "h_")))
|
|
1071
|
+
carry = carried_from(arrays, "c", core)
|
|
1072
|
+
else:
|
|
1073
|
+
m, x, carry = get(fq[ci])
|
|
1074
|
+
args, leaves = core_args(core, m)
|
|
1075
|
+
plan = plan_of(m)
|
|
1076
|
+
kept = {"key": (seq, m), "leaves": leaves} if backward else {}
|
|
1077
|
+
if plan:
|
|
1078
|
+
out, onward = timed("compute", core.forward, x, args, carry, plan, ci=ci, **kept)
|
|
1079
|
+
else:
|
|
1080
|
+
out, onward = timed("compute", core.forward, x, args, ci=ci, **kept), {}
|
|
1081
|
+
if backward:
|
|
1082
|
+
saved[m] = (x, carry)
|
|
1083
|
+
if not tail:
|
|
1084
|
+
fq[ci + 1].put((m, out, onward))
|
|
1085
|
+
elif last_stage:
|
|
1086
|
+
if op.get("outputs", True):
|
|
1087
|
+
self.coord.send(("o", epoch, seq, m), pack(None, **with_prefix(encode(core.numpy(out), out_codec), "h_")), cancel=stop.is_set)
|
|
1088
|
+
else:
|
|
1089
|
+
meta, arrays = args_of[m]
|
|
1090
|
+
push("next", ("f", epoch, seq, m), pack({"args": meta}, **with_prefix(encode(core.numpy(out), job["codec"]), "h_"),
|
|
1091
|
+
**with_prefix(arrays, "a_"), **carried_parts(onward, "c", core)))
|
|
1092
|
+
if not backward:
|
|
1093
|
+
return
|
|
1094
|
+
pending = set(saved)
|
|
1095
|
+
while pending:
|
|
1096
|
+
if tail:
|
|
1097
|
+
m, arrays = recv_any("cg" if last_stage else "b", pending)
|
|
1098
|
+
g = core.tensor(decode(split_prefix(arrays, "g_")))
|
|
1099
|
+
sides = {int(k[1:].split("_", 1)[0]): None for k in arrays if k.startswith("s")}
|
|
1100
|
+
upstream = {k: decode(split_prefix(arrays, f"s{k}_")) for k in sides}
|
|
1101
|
+
carry_grads = carried_from(arrays, "q", core)
|
|
1102
|
+
else:
|
|
1103
|
+
m, g, upstream, carry_grads = get(bq[ci + 1])
|
|
1104
|
+
pending.discard(m)
|
|
1105
|
+
x, carry = saved.pop(m)
|
|
1106
|
+
plan = plan_of(m)
|
|
1107
|
+
if plan:
|
|
1108
|
+
g_in, sides, back = timed("compute", core.backward, x, None, {}, g, carry, carry_grads, plan, ci=ci, key=(seq, m))
|
|
1109
|
+
else:
|
|
1110
|
+
(g_in, sides), back = timed("compute", core.backward, x, None, {}, g, ci=ci, key=(seq, m)), {}
|
|
1111
|
+
total = dict(upstream)
|
|
1112
|
+
add_sides(total, sides, core)
|
|
1113
|
+
if head:
|
|
1114
|
+
if not first_stage:
|
|
1115
|
+
push("prev", ("b", epoch, seq, m), grads_message(core.numpy(g_in), total, back, core))
|
|
1116
|
+
elif grads_back:
|
|
1117
|
+
self.coord.send(("g0", epoch, seq, m), grads_message(core.numpy(g_in), total), cancel=stop.is_set)
|
|
1118
|
+
else:
|
|
1119
|
+
bq[ci].put((m, g_in, total, back))
|
|
1120
|
+
|
|
1121
|
+
def guarded(ci):
|
|
1122
|
+
try:
|
|
1123
|
+
core_loop(ci)
|
|
1124
|
+
except Abort:
|
|
1125
|
+
errors.append(Abort())
|
|
1126
|
+
except Exception as e:
|
|
1127
|
+
errors.append(e)
|
|
1128
|
+
|
|
1129
|
+
try:
|
|
1130
|
+
threads = [threading.Thread(target=guarded, args=(ci,)) for ci in range(n)]
|
|
1131
|
+
[th.start() for th in threads]
|
|
1132
|
+
[th.join() for th in threads]
|
|
1133
|
+
real = [e for e in errors if not isinstance(e, Abort)]
|
|
1134
|
+
if real:
|
|
1135
|
+
raise real[0]
|
|
1136
|
+
if errors or stop.is_set():
|
|
1137
|
+
raise Abort()
|
|
1138
|
+
for side, sender in senders.items():
|
|
1139
|
+
blame(side, sender.flush)
|
|
1140
|
+
finally:
|
|
1141
|
+
if not op.get("adapter", True):
|
|
1142
|
+
for core in self.chain:
|
|
1143
|
+
core.set_adapter(True)
|
|
1144
|
+
return {"cores": [[len(c.layers), round(per_core[i], 3), "spill" if getattr(c, "spill", False) else "fast"] for i, c in enumerate(self.chain)], "compute": round(clock["compute"], 3),
|
|
1145
|
+
"engine": getattr(self, "engine", None), "wait": round(clock["wait"], 3), "send": round(sum(sd.busy for sd in senders.values()), 3),
|
|
1146
|
+
"grad_sq": sum(c.grad_sq() for c in self.chain) if backward else 0.0,
|
|
1147
|
+
"loss_scale": min((c.loss_scale for c in self.chain if c.max_loss_scale > 1), default=None)}
|
|
1148
|
+
|
|
1149
|
+
|
|
1150
|
+
def add_worker_args(p: argparse.ArgumentParser):
|
|
1151
|
+
p.add_argument("--name", help="how this device shows up in the dashboard (default: host name)")
|
|
1152
|
+
p.add_argument("--cap-gb", type=float, help="the most memory layerpool may use on this device, in GB: GPU memory on a machine with NVIDIA or AMD GPUs (all the GPUs it trains on together, shared equally unless --gpu-cap sets each), the shared memory on a Mac, RAM on a computer that trains on its CPU. Default: what it can spare (about 92%% of each GPU, 60%% of a Mac's memory, 50%% of RAM)")
|
|
1153
|
+
p.add_argument("--backend", choices=["auto", "torch", "mlx"], default="auto")
|
|
1154
|
+
p.add_argument("--cpu", action="store_true", help="train on the CPU even if a GPU is present")
|
|
1155
|
+
p.add_argument("--layers", help="how many of the model's layers this device takes: a count (8), a share (30%%) or a range (4-10); "
|
|
1156
|
+
"default: as many as suit its memory and its measured speed")
|
|
1157
|
+
p.add_argument("--gpus", help="on a machine with several GPUs, the ones to train on, such as 0,2 (default: all)")
|
|
1158
|
+
p.add_argument("--gpu-cap", help="the most GPU memory each GPU may use, in GB, such as 0=6,1=10 (GPU numbers as `layerpool devices` "
|
|
1159
|
+
"lists them); it takes the place of that GPU's share of --cap-gb")
|
|
1160
|
+
p.add_argument("--order", type=int, help="this device's place in the chain of devices (lower comes first)")
|
|
1161
|
+
p.add_argument("--ram-cap", type=float, help="on a machine with GPUs, the RAM in GB it may also use for layers that do not fit its GPUs; its CPU runs those, more slowly, and layerpool gives it only as many as pay off (default: none)")
|
|
1162
|
+
p.add_argument("--allow-sleep", action="store_true", help="let this computer sleep while it is in the pool (by default it stays "
|
|
1163
|
+
"awake, since a sleeping device looks gone; closing a laptop's lid still sleeps it)")
|
|
1164
|
+
|
|
1165
|
+
|
|
1166
|
+
def main(argv=None):
|
|
1167
|
+
if hasattr(signal, "SIGUSR1"):
|
|
1168
|
+
faulthandler.register(signal.SIGUSR1, all_threads=True)
|
|
1169
|
+
p = argparse.ArgumentParser(prog="layerpool join", description="Lend this device to a layerpool pool.")
|
|
1170
|
+
p.add_argument("coordinator", help="address printed by `layerpool up` or shown by Add device")
|
|
1171
|
+
p.add_argument("--token", help="join code from the dashboard or `layerpool invite`; without one, the device asks and waits for approval")
|
|
1172
|
+
p.add_argument("--tunnel", choices=["auto", "on", "off"], default="auto",
|
|
1173
|
+
help="open a cloudflared tunnel so other devices can reach this one (auto: when the pool is reached over https or has a tunnel itself)")
|
|
1174
|
+
p.add_argument("--identity", help="file that keeps this device's id across restarts (default: ~/.layerpool/device_id)")
|
|
1175
|
+
p.add_argument("--port", type=int, default=0, help="port other devices reach this one on (default: any free port)")
|
|
1176
|
+
p.add_argument("--advertise", help="address other devices use for this one, such as http://192.168.1.20:7400 (inside Docker, WSL "
|
|
1177
|
+
"or behind a VPN the address found by itself may be wrong); several are separated by commas")
|
|
1178
|
+
add_worker_args(p)
|
|
1179
|
+
args = p.parse_args(argv)
|
|
1180
|
+
if not args.coordinator.startswith(("http://", "https://")):
|
|
1181
|
+
args.coordinator = "http://" + args.coordinator
|
|
1182
|
+
tunnel = True if args.tunnel == "on" or args.coordinator.startswith("https://") and args.tunnel == "auto" else (False if args.tunnel == "off" else None)
|
|
1183
|
+
worker = None
|
|
1184
|
+
try:
|
|
1185
|
+
worker = Worker(args.coordinator, args.token, args.name, args.cap_gb, tunnel, port=args.port, backend=args.backend, cpu=args.cpu,
|
|
1186
|
+
identity=device_identity(args.identity), advertise=[a.strip() for a in (args.advertise or "").split(",") if a.strip()],
|
|
1187
|
+
layers=args.layers, gpus=args.gpus, gpu_caps=args.gpu_cap, order=args.order, allow_sleep=args.allow_sleep,
|
|
1188
|
+
ram_cap=args.ram_cap)
|
|
1189
|
+
worker.run()
|
|
1190
|
+
except KeyboardInterrupt:
|
|
1191
|
+
pass
|
|
1192
|
+
except ConnectionError:
|
|
1193
|
+
if worker is None or getattr(worker, "wid", None) is None:
|
|
1194
|
+
sys.exit(f"layerpool: could not reach a pool at {args.coordinator}: check the address that `layerpool up` printed, and "
|
|
1195
|
+
"that both computers are on the same network (or start the pool with --tunnel)")
|
|
1196
|
+
sys.exit(f"layerpool: the pool at {args.coordinator} stopped answering, so this device left it")
|
|
1197
|
+
except HTTPError as e:
|
|
1198
|
+
if e.code != 403:
|
|
1199
|
+
sys.exit(f"layerpool: the pool answered {e}")
|
|
1200
|
+
if getattr(e, "detail", "").startswith(("the pool denied", "nobody approved")):
|
|
1201
|
+
sys.exit(f"layerpool: {e.detail}")
|
|
1202
|
+
sys.exit("layerpool: the pool refused this device. The join code may be used up or expired, the pool may have restarted, "
|
|
1203
|
+
"or the device was removed. Get a new join command from the dashboard or `layerpool invite`.")
|
|
1204
|
+
|
|
1205
|
+
|
|
1206
|
+
def machine_key() -> str:
|
|
1207
|
+
"""What tells this machine apart from others that share its home folder, and stays the same when the host name changes (macOS
|
|
1208
|
+
renames it between networks): a hash of the system's machine id, else of the network hardware address, else the host name."""
|
|
1209
|
+
found = None
|
|
1210
|
+
try:
|
|
1211
|
+
if sys.platform == "darwin":
|
|
1212
|
+
out = subprocess.run(["ioreg", "-rd1", "-c", "IOPlatformExpertDevice"], capture_output=True, text=True, timeout=5).stdout
|
|
1213
|
+
hit = re.search(r'"IOPlatformUUID"\s*=\s*"([^"]+)"', out)
|
|
1214
|
+
found = hit.group(1) if hit else None
|
|
1215
|
+
elif sys.platform == "win32":
|
|
1216
|
+
import winreg
|
|
1217
|
+
with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\Microsoft\Cryptography") as key:
|
|
1218
|
+
found = winreg.QueryValueEx(key, "MachineGuid")[0]
|
|
1219
|
+
else:
|
|
1220
|
+
for path in ("/etc/machine-id", "/var/lib/dbus/machine-id"):
|
|
1221
|
+
if os.path.exists(path):
|
|
1222
|
+
with open(path, encoding="utf-8") as f:
|
|
1223
|
+
found = f.read().strip() or None
|
|
1224
|
+
break
|
|
1225
|
+
except Exception:
|
|
1226
|
+
found = None
|
|
1227
|
+
if not found:
|
|
1228
|
+
node = uuid.getnode()
|
|
1229
|
+
found = f"{node:012x}" if not (node >> 40) & 1 else None
|
|
1230
|
+
return hashlib.sha256(found.encode()).hexdigest()[:16] if found else socket.gethostname()
|
|
1231
|
+
|
|
1232
|
+
|
|
1233
|
+
def _read_identities(path: str) -> tuple[dict, bool]:
|
|
1234
|
+
"""The ids kept in that file by machine, and whether it needs writing again: an id from before machines were told apart
|
|
1235
|
+
(a bare id, or one under this machine's host name) becomes this machine's."""
|
|
1236
|
+
try:
|
|
1237
|
+
with open(path, encoding="utf-8") as f:
|
|
1238
|
+
text = f.read().strip()
|
|
1239
|
+
except OSError:
|
|
1240
|
+
return {}, False
|
|
1241
|
+
try:
|
|
1242
|
+
stored = json.loads(text) if text.startswith("{") else {machine_key(): text} if text else {}
|
|
1243
|
+
except ValueError:
|
|
1244
|
+
return {}, False
|
|
1245
|
+
if not isinstance(stored, dict):
|
|
1246
|
+
return {}, False
|
|
1247
|
+
old = stored.pop(socket.gethostname(), None)
|
|
1248
|
+
moved = not text.startswith("{") or (old is not None and machine_key() not in stored)
|
|
1249
|
+
if old is not None:
|
|
1250
|
+
stored.setdefault(machine_key(), old)
|
|
1251
|
+
return stored, moved
|
|
1252
|
+
|
|
1253
|
+
|
|
1254
|
+
def stored_identity(path: str) -> str | None:
|
|
1255
|
+
"""The id device_identity keeps for this machine in that file, or None, without making one."""
|
|
1256
|
+
return _read_identities(path)[0].get(machine_key()) or None
|
|
1257
|
+
|
|
1258
|
+
|
|
1259
|
+
def device_identity(path: str | None = None) -> str:
|
|
1260
|
+
"""This machine's lasting id, kept in the home folder. It is kept per machine, so machines that share a home folder (a
|
|
1261
|
+
network drive, a copied disk image) do not take each other's place in the pool."""
|
|
1262
|
+
path = path or os.path.join(os.path.expanduser("~"), ".layerpool", "device_id")
|
|
1263
|
+
stored, moved = _read_identities(path)
|
|
1264
|
+
key = machine_key()
|
|
1265
|
+
if stored.get(key) and not moved:
|
|
1266
|
+
return stored[key]
|
|
1267
|
+
stored[key] = stored.get(key) or secrets.token_hex(8)
|
|
1268
|
+
try:
|
|
1269
|
+
os.makedirs(os.path.dirname(path), exist_ok=True)
|
|
1270
|
+
with open(path, "w", encoding="utf-8") as f:
|
|
1271
|
+
json.dump(stored, f)
|
|
1272
|
+
except OSError:
|
|
1273
|
+
pass
|
|
1274
|
+
return stored[key]
|
|
1275
|
+
|
|
1276
|
+
if __name__ == "__main__":
|
|
1277
|
+
main()
|