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/cli.py ADDED
@@ -0,0 +1,567 @@
1
+ import argparse
2
+ import json
3
+ import os
4
+ import re
5
+ import shutil
6
+ import signal
7
+ import socket
8
+ import sys
9
+ import threading
10
+ import time
11
+ import urllib.request
12
+ import webbrowser
13
+
14
+ import numpy as np
15
+ import psutil
16
+
17
+ from . import __version__, worker as worker_module
18
+ from .api import connect, start
19
+ from .control import ControlServer, RemoteError, find_local
20
+ from .pool import Pool, PoolError
21
+
22
+ REFERENCE_FILE = "reference_logprobs.npy"
23
+ TRAIN_KEYS = ("model", "mlx_model", "data", "method", "mode", "rank", "alpha", "lr", "schedule", "warmup", "min_lr_ratio", "weight_decay", "steps",
24
+ "epochs", "batch_size", "seq", "micro", "micro_batch_size", "codec", "ckpt_every", "max_grad_norm", "beta", "out", "random_init", "train_on", "name",
25
+ "save_every", "resume", "target_modules")
26
+
27
+
28
+ def plain_error(e: BaseException) -> str:
29
+ """A sentence for the errors people meet most, instead of a traceback."""
30
+ name = type(e).__name__
31
+ if name in ("RepositoryNotFoundError", "GatedRepoError"):
32
+ return ("Hugging Face cannot find that model, or it needs you to log in and accept its terms: check the name, run "
33
+ "`hf auth login` (or set HF_TOKEN) here and on every device")
34
+ if name in ("URLError", "ConnectionRefusedError", "ConnectionResetError", "RemoteDisconnected"):
35
+ reason = getattr(e, "reason", None) or e
36
+ return f"cannot connect ({reason}): if this is the pool, is `layerpool up` still running? (LAYERPOOL_URL picks another pool)"
37
+ if isinstance(e, (FileNotFoundError, ValueError, TypeError, RuntimeError, OSError)):
38
+ return str(e) or name
39
+ raise e
40
+
41
+
42
+ def _client():
43
+ try:
44
+ return connect(start_if_missing=False)
45
+ except Exception as e:
46
+ sys.exit(f"layerpool: {e}")
47
+
48
+
49
+ def up(argv):
50
+ p = argparse.ArgumentParser(prog="layerpool up", description="Start a pool: devices join it once, runs come and go. Opens the dashboard.")
51
+ p.add_argument("--port", type=int, default=7340, help="dashboard and control API, on 127.0.0.1 only")
52
+ p.add_argument("--worker-port", type=int, default=7341, help="where devices connect")
53
+ p.add_argument("--tunnel", action="store_true", help="let devices outside this network join through a cloudflared tunnel")
54
+ p.add_argument("--no-work", action="store_true", help="this machine only coordinates and does not train")
55
+ p.add_argument("--no-browser", action="store_true")
56
+ p.add_argument("--heartbeat", type=float, default=120.0, help="seconds of silence before a device counts as gone")
57
+ p.add_argument("--advertise", help="this machine's address for other devices, such as 192.168.1.20, when the one it finds is "
58
+ "wrong (inside Docker, WSL or a VPN); the pool and this machine's own device use it with their ports")
59
+ worker_module.add_worker_args(p)
60
+ args = p.parse_args(argv)
61
+ found = find_local()
62
+ if found:
63
+ sys.exit(f"layerpool: a pool is already running here: {found['url']} (stop it first)")
64
+ pool = Pool(port=_free(args.worker_port), heartbeat_timeout=args.heartbeat, tunnel=args.tunnel, advertise=args.advertise,
65
+ settings_file=os.path.join(os.path.expanduser("~"), ".layerpool", "devices.json"),
66
+ state_file=os.path.join(os.path.expanduser("~"), ".layerpool", "pool_state.json"))
67
+ control = ControlServer(pool, port=_free(args.port, "127.0.0.1"))
68
+ control.publish()
69
+ awake = None if args.allow_sleep else worker_module.keep_awake()
70
+ if not args.no_work:
71
+ local = worker_module.Worker(f"http://127.0.0.1:{pool.server.port}", pool.token, args.name, args.cap_gb, tunnel=args.tunnel,
72
+ backend=args.backend, cpu=args.cpu,
73
+ identity=worker_module.device_identity(os.path.join(os.path.expanduser("~"), ".layerpool", "local_device_id")),
74
+ log=lambda *a: print("[this device]", *a, flush=True), layers=args.layers, gpus=args.gpus,
75
+ gpu_caps=args.gpu_cap, order=args.order, allow_sleep=args.allow_sleep, ram_cap=args.ram_cap,
76
+ advertise=[args.advertise] if args.advertise else None)
77
+ threading.Thread(target=local.run, daemon=True).start()
78
+ invite = pool.invite(reusable=True, ttl=7 * 86400)
79
+ print(f"layerpool {__version__}")
80
+ print(f" dashboard {control.dashboard_url()}")
81
+ print(f" devices {' or '.join(pool.urls)}")
82
+ print(" add one " + invite["command"].replace("\n", "\n "))
83
+ print(" your code import layerpool; pool = layerpool.connect()", flush=True)
84
+ threading.Thread(target=_tell_if_outdated, daemon=True).start()
85
+ if not args.no_browser:
86
+ webbrowser.open(control.login_url())
87
+
88
+ def interrupt(*_):
89
+ raise KeyboardInterrupt
90
+ for name in ("SIGTERM", "SIGHUP"):
91
+ if hasattr(signal, name):
92
+ signal.signal(getattr(signal, name), interrupt)
93
+ try:
94
+ while True:
95
+ time.sleep(3600)
96
+ except KeyboardInterrupt:
97
+ print("\nlayerpool: stopping")
98
+ finally:
99
+ if awake is not None:
100
+ awake.terminate()
101
+ control.close()
102
+ pool.close()
103
+
104
+
105
+ def _free(port: int, host: str = "0.0.0.0") -> int:
106
+ s = socket.socket()
107
+ try:
108
+ if os.name != "nt":
109
+ s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
110
+ s.bind((host, port))
111
+ return port
112
+ except OSError:
113
+ return 0
114
+ finally:
115
+ s.close()
116
+
117
+
118
+ def train(argv):
119
+ p = argparse.ArgumentParser(prog="layerpool train", description="Run a built-in training loop on the pool.")
120
+ p.add_argument("config", nargs="?", help="YAML or JSON file with any of the options below")
121
+ p.add_argument("--model")
122
+ p.add_argument("--mlx-model")
123
+ p.add_argument("--data", help=".jsonl/.json/.txt: chat rows ('messages'), text rows ('text'), or preference rows ('prompt', 'chosen', 'rejected')")
124
+ p.add_argument("--method", choices=["sft", "cpt", "dpo", "ipo", "simpo", "orpo"])
125
+ p.add_argument("--mode", choices=["lora", "full"])
126
+ p.add_argument("--random-init", action="store_true", default=None, help="train from scratch (with --mode full)")
127
+ p.add_argument("--rank", type=int)
128
+ p.add_argument("--alpha", type=float)
129
+ p.add_argument("--lr", type=float)
130
+ p.add_argument("--schedule", choices=["cosine", "linear", "constant"])
131
+ p.add_argument("--warmup", type=int)
132
+ p.add_argument("--min-lr-ratio", type=float)
133
+ p.add_argument("--weight-decay", type=float)
134
+ p.add_argument("--steps", type=int)
135
+ p.add_argument("--epochs", type=float)
136
+ p.add_argument("--batch-size", type=int)
137
+ p.add_argument("--seq", type=int)
138
+ p.add_argument("--micro", type=int, help="pieces each batch is cut into, so all devices work at once")
139
+ p.add_argument("--micro-batch-size", type=int, help="rows in each piece, instead of --micro")
140
+ p.add_argument("--target-modules", nargs="+", help="the linear layers LoRA goes on, such as q_proj v_proj (default: all of them)")
141
+ p.add_argument("--save-every", type=int, help="also save a checkpoint folder (out/step-N) every N steps")
142
+ p.add_argument("--resume", help="a checkpoint folder from --save-every: go on from there (same data and settings)")
143
+ p.add_argument("--codec", choices=["int8", "fp16", "fp32"])
144
+ p.add_argument("--ckpt-every", type=int)
145
+ p.add_argument("--max-grad-norm", type=float)
146
+ p.add_argument("--beta", type=float)
147
+ p.add_argument("--train-on", choices=["assistant", "all"])
148
+ p.add_argument("--out")
149
+ p.add_argument("--name")
150
+ p.add_argument("--local", action="store_true", help="no running pool needed: start one in this process (this machine trains)")
151
+ args = p.parse_args(argv)
152
+ cfg = {}
153
+ if args.config:
154
+ with open(args.config, encoding="utf-8") as f:
155
+ text = f.read()
156
+ try:
157
+ cfg = json.loads(text)
158
+ except ValueError:
159
+ import yaml
160
+ cfg = yaml.safe_load(text)
161
+ cfg = cfg or {}
162
+ if not isinstance(cfg, dict):
163
+ sys.exit(f"layerpool train: {args.config} must hold a mapping of options (model: ..., data: ...)")
164
+ cfg = {str(k).replace("-", "_"): v for k, v in cfg.items()}
165
+ unknown = sorted(set(cfg) - set(TRAIN_KEYS))
166
+ if unknown:
167
+ sys.exit(f"layerpool train: unknown options in {args.config}: {', '.join(unknown)}")
168
+ cfg.update({k: v for k, v in vars(args).items() if k in TRAIN_KEYS and v is not None})
169
+ if not cfg.get("model") or not cfg.get("data"):
170
+ sys.exit("layerpool train: --model and --data are required (or put them in the config file)")
171
+ if isinstance(cfg["data"], str) and not os.path.exists(cfg["data"]):
172
+ sys.exit(f"layerpool train: the data file {cfg['data']} does not exist")
173
+ run_training(cfg, local=args.local)
174
+
175
+
176
+ def run_training(cfg: dict, local: bool = False):
177
+ client = start(control=False) if local else _client()
178
+ method = cfg.get("method", "sft")
179
+ run_kwargs = {k: cfg[k] for k in ("mlx_model", "mode", "rank", "alpha", "lr", "schedule", "warmup", "min_lr_ratio", "weight_decay", "micro", "codec",
180
+ "micro_batch_size", "ckpt_every", "random_init", "seq", "target_modules") if cfg.get(k) is not None}
181
+ batch = cfg.get("batch_size", 8)
182
+ if "micro" not in run_kwargs:
183
+ run_kwargs["micro"] = min(8, batch * (2 if method in ("dpo", "ipo", "simpo", "orpo") else 1))
184
+ if local:
185
+ client.wait_for_devices(1, timeout=300)
186
+ run = client.run(cfg["model"], name=cfg.get("name"), **run_kwargs)
187
+ out = cfg.get("out") or f"layerpool-{run.id}"
188
+ print(f"layerpool: run {run.id} started on {len(run.pool.devices())} device(s)", flush=True)
189
+ start_step = 0
190
+ if cfg.get("resume"):
191
+ named = re.search(r"step-(\d+)$", os.path.basename(os.path.normpath(cfg["resume"])))
192
+ if named:
193
+ start_step = int(named.group(1))
194
+ else:
195
+ with open(os.path.join(cfg["resume"], "layerpool_run.json"), encoding="utf-8") as f:
196
+ start_step = json.load(f).get("steps", 0)
197
+ run.load(cfg["resume"])
198
+ print(f"layerpool: going on from step {start_step} ({cfg['resume']})", flush=True)
199
+ saved = os.path.join(cfg["resume"], REFERENCE_FILE)
200
+ reference = np.load(saved) if os.path.exists(saved) else None
201
+ else:
202
+ reference = None
203
+ state = "finished"
204
+ t0, every = time.time(), cfg.get("save_every")
205
+
206
+ def on_step(r):
207
+ done = r.get("at", r["step"]) + 1
208
+ total = r.get("total") or 0
209
+ rate = (time.time() - t0) / max(1, done - start_step)
210
+ left = f" {done}/{total}, about {(total - done) * rate / 60:.0f} min left" if total else ""
211
+ loss = "" if r.get("loss") is None else f" loss {r['loss']:.4f}"
212
+ print(f"step {done - 1}{loss} lr {r['lr']:.2e}" + (f" {r['tokens_per_s']:.0f} tok/s" if r.get("tokens_per_s") else "") + left, flush=True)
213
+ if every and done % every == 0:
214
+ path = run.save(os.path.join(out, f"step-{done}"), optimizer=True)
215
+ if getattr(run, "reference", None) is not None:
216
+ np.save(os.path.join(path, REFERENCE_FILE), run.reference)
217
+ print(f"layerpool: checkpoint {path} (resume with --resume {path})", flush=True)
218
+ try:
219
+ run.train(cfg["data"], method=method, steps=cfg.get("steps"), epochs=cfg.get("epochs", 1.0), batch_size=batch, seq=cfg.get("seq"),
220
+ max_grad_norm=cfg.get("max_grad_norm", 1.0), beta=cfg.get("beta"), assistant_only=cfg.get("train_on", "assistant") == "assistant",
221
+ on_step=on_step, start_step=start_step, reference=reference)
222
+ path = run.save(out)
223
+ print(f"layerpool: saved to {path}")
224
+ except BaseException:
225
+ state = "failed"
226
+ raise
227
+ finally:
228
+ run.end(state)
229
+ if local:
230
+ client.close()
231
+
232
+
233
+ def devices(argv):
234
+ p = argparse.ArgumentParser(prog="layerpool devices")
235
+ p.add_argument("--json", action="store_true", help="print every device with its settings and readings as JSON, for scripts")
236
+ args = p.parse_args(argv)
237
+ rows = _client().devices()
238
+ if args.json:
239
+ print(json.dumps(rows, default=str))
240
+ return
241
+ if not rows:
242
+ print("no devices yet: run `layerpool invite` and paste the command on a device")
243
+ return
244
+ print(f"{'id':5} {'name':18} {'status':9} {'layers':9} {'cap':>6} {'memory':>16} {'temp':>5} hardware")
245
+ for d in rows:
246
+ t = d.get("telemetry", {})
247
+ gpus = t.get("gpus") or []
248
+ mem = f"{sum(g.get('used_gb') or 0 for g in gpus):.1f}/{sum(g.get('total_gb') or 0 for g in gpus):.0f} GB" if gpus else \
249
+ (f"{t.get('ram_used_gb', 0):.1f}/{t.get('ram_total_gb', 0):.0f} GB" if t.get("ram_total_gb") else "n/a")
250
+ temp = t.get("temp_c") or max([g.get("temp_c") or 0 for g in gpus] or [0]) or None
251
+ layers = f"{d['layers'][0]}-{d['layers'][1] - 1}" if d.get("layers") else "-"
252
+ if d.get("layers") and d.get("on_gpu") is not None and d["on_gpu"] < d["layers"][1] - d["layers"][0]:
253
+ layers += "*"
254
+ cap = f"{d['cap_gb']:.1f}" if d.get("cap_gb") else "auto"
255
+ status = {"banned": "left out", "disabled": "paused"}.get(d["status"], d["status"])
256
+ heat = (str(round(temp)) + "C") if temp else ("hot" if str(t.get("heat", "")).startswith("hot") else "-")
257
+ hardware = [f"{i}: {x['name']}" if len(d["devices"]) > 1 else x["name"] for i, x in enumerate(d["devices"])]
258
+ print(f"{d['id']:5} {d['name'][:18]:18} {status:9} {layers:9} {cap:>6} {mem:>16} {heat:>5} {', '.join(hardware)}")
259
+ if any(d.get("layers") and d.get("on_gpu") is not None and d["on_gpu"] < d["layers"][1] - d["layers"][0] for d in rows):
260
+ print("* some of its layers are in RAM, run by its CPU (--ram-cap)")
261
+ chosen = [d for d in rows if any((d.get("settings") or {}).get(k) is not None for k in ("layers", "gpus", "gpu_caps", "order", "ram_cap"))]
262
+ if chosen:
263
+ print()
264
+ for d in chosen:
265
+ print(f"{d['id']:5} {d['name'][:18]:18} " + describe_settings(d["settings"]))
266
+
267
+
268
+ def set_device(argv):
269
+ p = argparse.ArgumentParser(prog="layerpool set", description="Change a device's settings; memory changes re-split the layers at the next step.")
270
+ p.add_argument("device", help="device id or name")
271
+ p.add_argument("--name")
272
+ p.add_argument("--cap-gb", 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); auto clears it")
273
+ p.add_argument("--layers", help="how many layers it takes: a count (8), a share of the model (30%%), a range (4-10) or auto")
274
+ p.add_argument("--gpus", help="the GPUs it trains on, such as 0,2, or auto for all")
275
+ 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` "
276
+ "lists them); it takes the place of that GPU's share of --cap-gb; auto clears it")
277
+ p.add_argument("--order", help="its place in the chain of devices (lower comes first), or auto")
278
+ p.add_argument("--ram-cap", 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); auto turns it off")
279
+ args = p.parse_args(argv)
280
+ client = _client()
281
+ wid = _resolve(client, args.device)
282
+ cap = None
283
+ if args.cap_gb is not None:
284
+ try:
285
+ cap = None if args.cap_gb.lower() == "auto" else float(args.cap_gb)
286
+ except ValueError:
287
+ sys.exit("layerpool set: --cap-gb takes a number of GB or 'auto'")
288
+ changes = {"name": args.name} if args.name is not None else {}
289
+ if args.cap_gb is not None:
290
+ changes["cap_gb"] = cap
291
+ if args.ram_cap is not None:
292
+ try:
293
+ changes["ram_cap"] = None if args.ram_cap.lower() == "auto" else float(args.ram_cap)
294
+ except ValueError:
295
+ sys.exit("layerpool set: --ram-cap takes a number of GB or 'auto'")
296
+ for key, value in (("layers", args.layers), ("gpus", args.gpus), ("gpu_caps", args.gpu_cap), ("order", args.order)):
297
+ if value is not None:
298
+ changes[key] = None if value.lower() == "auto" else value
299
+ if not changes:
300
+ sys.exit("layerpool set: nothing to change")
301
+ settings = client.set_device(wid, **changes)
302
+ print(f"layerpool: {settings.get('name') or args.device} now: " + describe_settings(settings))
303
+
304
+
305
+ def describe_settings(settings: dict) -> str:
306
+ caps = settings.get("gpu_caps")
307
+ parts = [f"memory cap {'auto' if settings.get('cap_gb') is None else format(settings['cap_gb'], 'g') + ' GB'}",
308
+ f"layers {settings.get('layers') or 'auto'}"]
309
+ if settings.get("gpus"):
310
+ parts.append("GPUs " + ",".join(str(i) for i in settings["gpus"]))
311
+ if caps:
312
+ parts.append("GPU caps " + ", ".join(f"{k}: {v:g} GB" for k, v in sorted(caps.items())))
313
+ if settings.get("order") is not None:
314
+ parts.append(f"order {settings['order']}")
315
+ if settings.get("ram_cap"):
316
+ parts.append(f"up to {settings['ram_cap']:g} GB of layers in RAM")
317
+ parts.append("in use" if settings.get("enabled", True) else "paused")
318
+ return ", ".join(parts)
319
+
320
+
321
+ def plan_cmd(argv):
322
+ p = argparse.ArgumentParser(prog="layerpool plan", description="Check, before training, whether a model fits the devices in the pool "
323
+ "now and how its layers would be split.")
324
+ p.add_argument("model", help="Hugging Face model name or local folder")
325
+ p.add_argument("--mlx-model", help="its MLX version, for Macs (a 4-bit one for a 4-bit model)")
326
+ p.add_argument("--full", action="store_true", help="full fine-tuning instead of LoRA")
327
+ p.add_argument("--rank", type=int, default=16)
328
+ p.add_argument("--seq", type=int, default=512, help="tokens per sequence")
329
+ p.add_argument("--micro", type=int, default=8, help="micro-batches per step")
330
+ p.add_argument("--micro-batch-size", type=int, help="sequences per micro-batch")
331
+ p.add_argument("--auto", default="AutoModelForCausalLM", help="the transformers AutoModel class (AutoModelForSeq2SeqLM, ...)")
332
+ p.add_argument("--json", action="store_true")
333
+ args = p.parse_args(argv)
334
+ out = _client().plan(args.model, mlx_model=args.mlx_model, mode="full" if args.full else "lora", rank=args.rank, seq=args.seq,
335
+ micro=args.micro, micro_batch_size=args.micro_batch_size, auto=args.auto)
336
+ if args.json:
337
+ print(json.dumps(out))
338
+ return
339
+ print(f"{args.model}: {out['layers']} layers of about {out['layer_gb'] or 0:.2f} GB each, with "
340
+ f"{'full fine-tuning' if args.full else f'LoRA rank {args.rank}'}, seq {args.seq}")
341
+ if not out["plan"]:
342
+ print(f"does not fit: {out['why']}")
343
+ sys.exit(1)
344
+ for st in out["plan"]:
345
+ print(f" {st['name'][:18]:18} layers {st['range'][0]}-{st['range'][1] - 1} ({st['range'][1] - st['range'][0]}), about {st['gb']:.1f} GB")
346
+ print("it fits; the embeddings and output head stay on the computer that runs your training code")
347
+
348
+
349
+ def rebalance(argv):
350
+ p = argparse.ArgumentParser(prog="layerpool rebalance", description="Control how the running run splits its layers.")
351
+ p.add_argument("what", choices=["on", "off", "now"], help="on/off: move layers to faster devices while training, or keep the "
352
+ "split; now: split the layers again at once")
353
+ args = p.parse_args(argv)
354
+ out = _client().set_run(**({"resplit": True} if args.what == "now" else {"rebalance": args.what == "on"}))
355
+ print(f"layerpool: rebalancing is {'on' if out.get('rebalance', True) else 'off'}" + ("; splitting again now" if args.what == "now" else ""))
356
+
357
+
358
+ def _resolve(client, ref: str) -> str:
359
+ devices = [d for d in client.devices() if d.get("status") != "removed"]
360
+ for d in devices:
361
+ if ref == d["id"]:
362
+ return d["id"]
363
+ named = [d["id"] for d in devices if ref == d["name"]]
364
+ if len(named) > 1:
365
+ sys.exit(f"layerpool: several devices are called {ref!r} ({', '.join(named)}); use the id instead")
366
+ if named:
367
+ return named[0]
368
+ sys.exit(f"layerpool: no device called {ref!r}; see `layerpool devices`")
369
+
370
+
371
+ def simple(name: str, argv):
372
+ p = argparse.ArgumentParser(prog=f"layerpool {name}")
373
+ p.add_argument("device")
374
+ args = p.parse_args(argv)
375
+ client = _client()
376
+ wid = _resolve(client, args.device)
377
+ getattr(client, name)(wid)
378
+ print(f"layerpool: {args.device} {dict(pause='paused', resume='back in use', remove='removed')[name]}")
379
+
380
+
381
+ def approve(argv, yes: bool = True):
382
+ name = "approve" if yes else "deny"
383
+ p = argparse.ArgumentParser(prog=f"layerpool {name}", description=f"{name.capitalize()} a device that asked to join (it shows a code).")
384
+ p.add_argument("code", nargs="?", help="the code the device shows; leave it out to list the devices waiting")
385
+ args = p.parse_args(argv)
386
+ pool = _client()._p
387
+ if not args.code:
388
+ rows = pool.waiting()
389
+ if not rows:
390
+ print("no device is waiting. On the device run: layerpool join URL (without --token)")
391
+ for r in rows:
392
+ print(f"{r['code']} {r['name']:18} {', '.join(r['hardware'])} from {r.get('from') or '?'}, asked {r['waiting_s']}s ago")
393
+ return
394
+ try:
395
+ who = pool.answer(args.code, approve=yes)
396
+ except Exception as e:
397
+ sys.exit(f"layerpool: {e}")
398
+ print(f"{who} {'approved: it joins in a few seconds' if yes else 'denied'}")
399
+
400
+
401
+ CACHE_ROOT = os.path.join(os.path.expanduser("~"), ".cache", "layerpool")
402
+
403
+
404
+ def _size(path: str) -> int:
405
+ total = 0
406
+ for root, _, files in os.walk(path):
407
+ for name in files:
408
+ try:
409
+ total += os.path.getsize(os.path.join(root, name))
410
+ except OSError:
411
+ pass
412
+ return total
413
+
414
+
415
+ def _tell_if_outdated():
416
+ """A line when PyPI has a newer layerpool (one anonymous request; LAYERPOOL_NO_UPDATE_CHECK=1 turns it off)."""
417
+ if os.environ.get("LAYERPOOL_NO_UPDATE_CHECK"):
418
+ return
419
+ try:
420
+ with urllib.request.urlopen("https://pypi.org/pypi/layerpool/json", timeout=5) as r:
421
+ latest = json.load(r)["info"]["version"]
422
+ except Exception:
423
+ return
424
+ number = lambda v: tuple(int(x) for x in v.split(".")[:3] if x.isdigit())
425
+ if number(latest) > number(__version__):
426
+ print(f" update layerpool {latest} is out (you have {__version__}): pip install -U layerpool, here and on every device",
427
+ flush=True)
428
+
429
+
430
+ def end_run(argv):
431
+ argparse.ArgumentParser(prog="layerpool end", description="End the current run, for example one whose script is stuck.").parse_args(argv)
432
+ client = _client()
433
+ run = client.status().get("run")
434
+ if not run:
435
+ print("no run is going")
436
+ return
437
+ client.end_run()
438
+ print(f"ended run {run}; the devices are free")
439
+
440
+
441
+ def cache(argv):
442
+ p = argparse.ArgumentParser(prog="layerpool cache", description="Show or clear what layerpool keeps on this computer's disk.")
443
+ p.add_argument("action", nargs="?", choices=["show", "clear"], default="show")
444
+ args = p.parse_args(argv)
445
+ parts = {"tensors": "weights downloaded from Hugging Face", "ranges": "the parts of models this device held",
446
+ "checkpoints": "checkpoints of pools that did not close cleanly", "store": "checkpoints devices keep while they train"}
447
+ tunnels = [os.path.join(CACHE_ROOT, f) for f in os.listdir(CACHE_ROOT) if f.startswith("cloudflared")] if os.path.isdir(CACHE_ROOT) else []
448
+ if args.action == "show":
449
+ for name, what in parts.items():
450
+ print(f"{_size(os.path.join(CACHE_ROOT, name)) / 1e9:8.2f} GB {name:12} {what}")
451
+ print(f"{sum(os.path.getsize(t) for t in tunnels) / 1e9:8.2f} GB {'cloudflared':12} the tunnel program (--tunnel)")
452
+ print(f"\nin {CACHE_ROOT}; `layerpool cache clear` frees it (downloads happen again when needed). Whole model files that "
453
+ "were cheaper to download than their parts are in the Hugging Face cache: `hf cache scan` shows them")
454
+ return
455
+ busy = [e for e in (os.listdir(os.path.join(CACHE_ROOT, "store")) if os.path.isdir(os.path.join(CACHE_ROOT, "store")) else [])
456
+ if e.split("_", 1)[0].isdigit() and psutil.pid_exists(int(e.split("_", 1)[0]))]
457
+ if busy:
458
+ print("a device on this computer is in a pool now, so the downloaded weights and model parts stay; stop it first to free "
459
+ "them too")
460
+ freed = 0
461
+ for path in tunnels:
462
+ try:
463
+ size = os.path.getsize(path)
464
+ os.remove(path)
465
+ freed += size
466
+ except OSError:
467
+ pass
468
+ for name in parts:
469
+ path = os.path.join(CACHE_ROOT, name)
470
+ if not os.path.isdir(path):
471
+ continue
472
+ for entry in os.listdir(path):
473
+ target = os.path.join(path, entry)
474
+ if name == "checkpoints" and time.time() - os.path.getmtime(target) < 3600:
475
+ continue
476
+ if busy and name in ("tensors", "ranges"):
477
+ continue
478
+ if name == "store" and entry.split("_", 1)[0].isdigit() and psutil.pid_exists(int(entry.split("_", 1)[0])):
479
+ continue
480
+ freed += _size(target) if os.path.isdir(target) else os.path.getsize(target)
481
+ shutil.rmtree(target, ignore_errors=True) if os.path.isdir(target) else os.remove(target)
482
+ print(f"freed {freed / 1e9:.2f} GB")
483
+
484
+
485
+ def invite(argv):
486
+ p = argparse.ArgumentParser(prog="layerpool invite", description="Print a join command for a new device.")
487
+ p.add_argument("--reusable", action="store_true", help="one code for several devices (they show up for you to see in the dashboard)")
488
+ p.add_argument("--hours", type=float, default=24)
489
+ args = p.parse_args(argv)
490
+ got = _client().invite(reusable=args.reusable, hours=args.hours)
491
+ print("On a computer:\n " + got["command"].replace("\n", "\n "))
492
+ print("\nIn a notebook cell:\n " + got["notebook"].replace("\n", "\n "))
493
+ if not got.get("tunnel"):
494
+ print("\nThis pool has no tunnel, so only devices on this network can join. For notebooks (Colab, Kaggle) or devices elsewhere,\n"
495
+ "start the pool with `layerpool up --tunnel`.")
496
+
497
+
498
+ def status(argv):
499
+ p = argparse.ArgumentParser(prog="layerpool status")
500
+ p.add_argument("-f", "--follow", action="store_true")
501
+ p.add_argument("--json", action="store_true", help="print the pool's state as JSON, for scripts")
502
+ args = p.parse_args(argv)
503
+ client = _client()
504
+ if args.json:
505
+ print(json.dumps(client.status(), default=str))
506
+ return
507
+ run, last = object(), None
508
+ while True:
509
+ s = client.status()
510
+ if s["run"] != run:
511
+ run, last = s["run"], None
512
+ print(f"layerpool {s['version']}: {s['devices']} device(s) online, run: {s['run'] or 'none'}")
513
+ for p_ in s.get("plan") or []:
514
+ print(f" {p_['name']}: layers {p_['range'][0]}-{p_['range'][1] - 1}")
515
+ rows = [h for h in s["history"] if last is None or h["step"] > last]
516
+ for h in rows if last is not None or args.follow else rows[-5:]:
517
+ loss = " skipped (overflow)" if h.get("skipped") else "" if h.get("loss") is None else f" loss {h['loss']:.4f}"
518
+ print(f"step {h['step']}{loss}" + (f" {h['tokens_per_s']:.0f} tok/s" if h.get("tokens_per_s") else ""))
519
+ if s["history"]:
520
+ last = max(last if last is not None else -1, s["history"][-1]["step"])
521
+ if not args.follow:
522
+ return
523
+ time.sleep(2)
524
+
525
+
526
+ COMMANDS = {"cache": cache, "up": up, "join": worker_module.main, "approve": approve, "deny": lambda argv: approve(argv, yes=False), "train": train, "devices": devices, "set": set_device, "invite": invite, "status": status,
527
+ "end": end_run, "rebalance": rebalance, "plan": plan_cmd, "pause": lambda a: simple("pause", a), "resume": lambda a: simple("resume", a), "remove": lambda a: simple("remove", a)}
528
+
529
+
530
+ def main(argv=None):
531
+ argv = sys.argv[1:] if argv is None else argv
532
+ if argv and argv[0] in ("-V", "--version", "version"):
533
+ print(f"layerpool {__version__}")
534
+ return
535
+ if not argv or argv[0] not in COMMANDS:
536
+ if argv and argv[0] not in ("-h", "--help", "help"):
537
+ print(f"layerpool: there is no command {argv[0]!r}\n", file=sys.stderr)
538
+ print(f"layerpool {__version__}: pool the memory of your devices to train one model\n\n"
539
+ " layerpool up start the pool and open the dashboard\n"
540
+ " layerpool invite print a join command for a new device\n"
541
+ " layerpool join URL [--token] lend this device to a pool (without a code it waits for approval)\n"
542
+ " layerpool approve [CODE] let a waiting device in (no code: list them); deny CODE refuses it\n"
543
+ " layerpool devices list devices, their layers, memory and temperature\n"
544
+ " layerpool plan MODEL check whether a model fits the devices, and how it would be split\n"
545
+ " layerpool set DEVICE ... change a device's layers, GPUs, memory caps, RAM offload, order or name\n"
546
+ " layerpool pause / resume stop using a device, or use it again\n"
547
+ " layerpool remove DEVICE take a device out of the pool\n"
548
+ " layerpool train ... run a built-in training loop (sft, cpt, dpo, ...)\n"
549
+ " layerpool status [-f] follow the current run\n"
550
+ " layerpool rebalance on|off move layers to faster devices while training, or keep the split (now: split again)\n"
551
+ " layerpool end end the current run (a stuck or abandoned one)\n"
552
+ " layerpool cache [clear] show or free the disk space layerpool uses\n\n"
553
+ "In Python: import layerpool; pool = layerpool.connect(); run = pool.run(\"Qwen/Qwen3-0.6B\")")
554
+ sys.exit(0 if not argv or argv[0] in ("-h", "--help", "help") else 2)
555
+ for stream in (sys.stdout, sys.stderr):
556
+ try:
557
+ stream.reconfigure(errors="replace")
558
+ except Exception:
559
+ pass
560
+ try:
561
+ COMMANDS[argv[0]](argv[1:])
562
+ except KeyboardInterrupt:
563
+ sys.exit(130)
564
+ except (RemoteError, PoolError) as e:
565
+ sys.exit(f"layerpool: {e}")
566
+ except Exception as e:
567
+ sys.exit(f"layerpool: {plain_error(e)}")