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/api.py ADDED
@@ -0,0 +1,682 @@
1
+ import atexit
2
+ import json
3
+ import math
4
+ import os
5
+ import threading
6
+ import time
7
+ import webbrowser
8
+
9
+ import numpy as np
10
+
11
+ from . import __version__, selfcheck, trainers
12
+ from .blocks import BETAS, EPS, load_ends
13
+ from .control import ControlServer, RemoteError, RemotePool, find_local
14
+ from .driver import Ends, PoolChain
15
+ from .export import BLOCKS_FILE, ENDS_FILE, add_saved_modules, write_ends
16
+ from .job import build_job
17
+ from .pool import OPTIMIZER_FILE, Pool, PoolError, scheduled_lr
18
+ from .worker import Worker, cuda_problem, device_identity, native_bf16, stored_identity
19
+
20
+ STATE_DIR = os.path.join(os.path.expanduser("~"), ".layerpool")
21
+
22
+
23
+ def _rows(input_ids) -> list[list[int]]:
24
+ if hasattr(input_ids, "tolist"):
25
+ input_ids = input_ids.tolist()
26
+ if input_ids and isinstance(input_ids[0], int):
27
+ input_ids = [input_ids]
28
+ return [list(map(int, r)) for r in input_ids]
29
+
30
+
31
+ def pad_rows(rows: list[list[int]], fill: int, length: int | None = None) -> np.ndarray:
32
+ length = length or max(len(r) for r in rows)
33
+ out = np.full((len(rows), length), fill, dtype=np.int64)
34
+ for i, r in enumerate(rows):
35
+ out[i, :len(r)] = r[:length]
36
+ return out
37
+
38
+
39
+ LOCAL_FILE = "layerpool_local.safetensors"
40
+ LOCAL_OPTIMIZER_FILE = "layerpool_local_optimizer.pt"
41
+
42
+
43
+ class Result(dict):
44
+ __getattr__ = dict.get
45
+
46
+
47
+ class Run:
48
+ """One training run on the pool. `run.model` is the transformers model on this machine; its repeated blocks live on the
49
+ devices. Your loop calls forward_backward / optim_step (or use the model with any transformers trainer)."""
50
+
51
+ def __init__(self, pool, run_id: str, job: dict, tokenizer=None, ends=None):
52
+ self.pool, self.id, self.job, self.tokenizer, self.ends = pool, run_id, job, tokenizer, ends
53
+ self.model = ends.model if ends is not None else None
54
+ self._ended = False
55
+ atexit.register(self._end_at_exit)
56
+ self.step = 0
57
+ self.metrics: list[dict] = []
58
+ self._loss_accum = None
59
+ self._loss_parts: list[tuple[float, int | None]] = []
60
+ self._local_opt = None
61
+
62
+ def _add_loss(self, value: float, tokens: int | None = None):
63
+ """One forward pass's loss. A loss averaged over its own tokens (tokens given) counts by its tokens, so the step shows the
64
+ average over the accumulated batches; a loss already divided by the whole step's count (tokens None) adds up."""
65
+ self._loss_parts.append((value, tokens))
66
+ if all(t is not None for _, t in self._loss_parts):
67
+ self._loss_accum = sum(v * t for v, t in self._loss_parts) / max(1, sum(t for _, t in self._loss_parts))
68
+ else:
69
+ self._loss_accum = sum(v for v, _ in self._loss_parts)
70
+
71
+ def _prepare(self, input_ids, labels=None, weights=None):
72
+ pad = self.job.get("pad_id", 0)
73
+ if isinstance(input_ids, np.ndarray) and input_ids.ndim == 2:
74
+ ids = input_ids.astype(np.int64)
75
+ elif hasattr(input_ids, "detach") and input_ids.dim() == 2:
76
+ ids = input_ids.detach().cpu().numpy().astype(np.int64)
77
+ else:
78
+ rows = _rows(input_ids)
79
+ ids = pad_rows(rows, pad)
80
+ if labels is None:
81
+ labels = pad_rows(rows, -100)
82
+ for i, r in enumerate(rows):
83
+ labels[i, :len(r)] = r
84
+ if hasattr(labels, "detach"):
85
+ labels = labels.detach().cpu().numpy()
86
+ targets = ids.copy() if labels is None else (labels.astype(np.int64) if isinstance(labels, np.ndarray) else pad_rows(_rows(labels), -100, ids.shape[1]))
87
+ if weights is None:
88
+ w = (targets[:, 1:] != -100).astype(np.float32)
89
+ else:
90
+ w = np.asarray(weights, np.float32)
91
+ w = w[:, 1:] if w.shape[1] == ids.shape[1] else w
92
+ return ids, targets, w
93
+
94
+ def _logits(self, ids: np.ndarray, micro_rows: int | None, **inputs):
95
+ import torch
96
+ old = self.job.get("micro_batch_size")
97
+ if micro_rows:
98
+ self.job["micro_batch_size"] = micro_rows
99
+ try:
100
+ device = self.model.device
101
+ inputs = {k: v.to(device) if torch.is_tensor(v) else v for k, v in inputs.items()}
102
+ out = self.model(input_ids=torch.tensor(ids, device=device), **inputs)
103
+ finally:
104
+ self.job["micro_batch_size"] = old
105
+ return out.logits
106
+
107
+ @staticmethod
108
+ def _token_logprobs(logits, targets):
109
+ import torch
110
+ from .losses import token_logprobs
111
+ t = torch.tensor(targets[:, 1:], device=logits.device).clamp(min=0)
112
+ return token_logprobs(logits[:, :-1], t)
113
+
114
+ def forward_backward(self, input_ids, labels=None, weights=None, loss="ce", normalize="mean", micro_rows: int | None = None, data=None,
115
+ **inputs) -> Result:
116
+ """Add this batch's gradients. `labels` use -100 for tokens that should not be learned. `loss` is "ce" (cross-entropy on the
117
+ labelled tokens) or a function loss(logprobs, mask, data) -> scalar torch tensor computed from the per-token log-probabilities.
118
+ `normalize` is "mean" (over the batch's labelled tokens), "sum", or a number to divide by. Extra keyword arguments go to the
119
+ model (pixel_values for an image model, for example)."""
120
+ import torch
121
+ t0 = time.time()
122
+ ids, targets, w = self._prepare(input_ids, labels, weights)
123
+ tokens = int((w > 0).sum())
124
+ self.model.train()
125
+ logits = self._logits(ids, micro_rows, **inputs)
126
+ lp = self._token_logprobs(logits, targets).cpu()
127
+ mask = torch.tensor(w)
128
+ if callable(loss):
129
+ value = loss(lp, mask, data)
130
+ elif loss == "ce":
131
+ divisor = float(w.sum()) if normalize == "mean" else 1.0 if normalize == "sum" else float(normalize)
132
+ value = -(lp * mask).sum() / max(divisor, 1e-9)
133
+ else:
134
+ raise ValueError(f"unknown loss {loss!r}; pass 'ce' or a function of (logprobs, mask, data)")
135
+ value.backward()
136
+ number = float(value.detach())
137
+ self._add_loss(number, tokens if loss == "ce" and normalize == "mean" else None)
138
+ self.pool.add_loss(number)
139
+ return Result(loss=number, tokens=tokens, seconds=round(time.time() - t0, 3))
140
+
141
+ def forward(self, input_ids, labels=None, adapter: bool = True, micro_rows: int | None = None, metrics: bool = False, **inputs):
142
+ """Per-token log-probabilities of the next tokens, shape (rows, tokens - 1). adapter=False gives the base model (LoRA runs).
143
+ metrics=True also returns the entropy of each next-token distribution and whether the target was the most likely token."""
144
+ import torch
145
+ ids, targets, _ = self._prepare(input_ids, labels)
146
+ self.ends.adapter = adapter
147
+ try:
148
+ with torch.no_grad():
149
+ logits = self._logits(ids, micro_rows, **inputs)
150
+ finally:
151
+ self.ends.adapter = True
152
+ if not metrics:
153
+ return self._token_logprobs(logits, targets).cpu().numpy()
154
+ from .losses import token_stats
155
+ lp, entropy, top1 = token_stats(logits[:, :-1], torch.tensor(targets[:, 1:], device=logits.device).clamp(min=0))
156
+ return Result(logprobs=lp.cpu().numpy(), entropy=entropy.cpu().numpy(), top1=top1.cpu().numpy())
157
+
158
+ def _new_local_opt(self, lr: float):
159
+ """AdamW for the trained parts on this machine: matrices decay, norms and biases do not (as in the Trainer)."""
160
+ import torch
161
+ params = self._local_params()
162
+ groups = [{"params": [p for p in params if p.dim() > 1], "weight_decay": self.job.get("weight_decay", 0.0)},
163
+ {"params": [p for p in params if p.dim() <= 1], "weight_decay": 0.0}]
164
+ return torch.optim.AdamW([g for g in groups if g["params"]], lr=lr, betas=BETAS, eps=EPS)
165
+
166
+ def _local_params(self):
167
+ return [p for n, p in self.model.named_parameters() if p.requires_grad and n != "layerpool_anchor"] if self.model is not None else []
168
+
169
+ def optim_step(self, lr: float | None = None, max_grad_norm: float | None = 1.0, loss: float | None = None) -> Result:
170
+ """One optimizer step on every device (and on this machine's part of the model in full fine-tuning), with the gradient
171
+ norm clipped across all of them."""
172
+ lr = self.job["lr"] if lr is None else lr
173
+ self.ends.chain.drop_pending()
174
+ local = [p for p in self._local_params() if p.grad is not None]
175
+ local_sq = float(sum(p.grad.float().pow(2).sum() for p in local)) if local else 0.0
176
+ remote = float(self.ends.remote_norm) ** 2
177
+ total = math.sqrt(local_sq + remote)
178
+ clip = min(1.0, max_grad_norm / (total + 1e-6)) if max_grad_norm else 1.0
179
+ if not math.isfinite(total):
180
+ clip = float("nan")
181
+ record = self.pool.optim_step(lr, None, self._loss_accum if loss is None else loss, clip=clip,
182
+ weight_decay=self.job.get("weight_decay"))
183
+ if local:
184
+ if record.get("skipped"):
185
+ for p in local:
186
+ p.grad = None
187
+ else:
188
+ if self._local_opt is None:
189
+ self._local_opt = self._new_local_opt(lr)
190
+ for group in self._local_opt.param_groups:
191
+ group["lr"] = lr
192
+ for p in local:
193
+ p.grad.mul_(clip)
194
+ self._local_opt.step()
195
+ self._local_opt.zero_grad(set_to_none=True)
196
+ self.ends.anchor.grad = None
197
+ self.ends.remote_norm = 0.0
198
+ self._loss_accum = None
199
+ self._loss_parts = []
200
+ self.step = record["step"] + 1
201
+ return Result(record)
202
+
203
+ def log(self, **metrics):
204
+ self.metrics.append({"step": self.step, "time": time.time(), **metrics})
205
+ self.pool.emit("metric", self.metrics[-1])
206
+
207
+ def save(self, path: str, dtype: str = "bfloat16", optimizer: bool = False) -> str:
208
+ """Write the result: a PEFT adapter folder for LoRA runs, a full Hugging Face model folder for full fine-tuning.
209
+ optimizer=True also keeps what resuming needs exactly: the devices' AdamW state and this machine's trained weights in
210
+ float32 (load() reads them back)."""
211
+ self.ends.chain.drop_pending()
212
+ path = os.path.abspath(path)
213
+ self.pool.export(path, dtype, self.metrics, optimizer=optimizer)
214
+ if self.job.get("mode") == "full":
215
+ write_ends(self.model, path, self.job, dtype)
216
+ elif self.job.get("modules_to_save"):
217
+ add_saved_modules(self.model, path, self.job["modules_to_save"])
218
+ if optimizer:
219
+ from safetensors.torch import save_file
220
+ mine = {n: p.detach().float().cpu().contiguous() for n, p in self.model.named_parameters()
221
+ if p.requires_grad and n != "layerpool_anchor"}
222
+ save_file(mine, os.path.join(path, LOCAL_FILE))
223
+ if self._local_opt is not None:
224
+ import torch
225
+ torch.save(self._local_opt.state_dict(), os.path.join(path, LOCAL_OPTIMIZER_FILE))
226
+ return path
227
+
228
+ def load(self, path: str):
229
+ """Continue from a folder this library saved (save(), save_pretrained or a Trainer checkpoint): a PEFT adapter for LoRA
230
+ runs, a model folder for full fine-tuning. Before the first step it is where training starts; later it replaces what the devices
231
+ have trained so far (as the Trainer does for load_best_model_at_end)."""
232
+ import torch
233
+ from safetensors.numpy import load_file
234
+ from safetensors.torch import load_file as load_torch
235
+ self.ends.chain.drop_pending()
236
+ stack = self.job["layout"]["stack"] + "."
237
+ where = lambda name: os.path.join(path, name)
238
+ remote = load_file(where(OPTIMIZER_FILE)) if os.path.exists(where(OPTIMIZER_FILE)) else None
239
+ local = {}
240
+ if self.job.get("mode") == "full":
241
+ if remote is None:
242
+ remote = {k[len(stack):]: v.float().numpy() for k, v in load_torch(where(BLOCKS_FILE)).items()}
243
+ local = load_torch(where(ENDS_FILE))
244
+ else:
245
+ if not os.path.exists(where("adapter_model.safetensors")):
246
+ raise FileNotFoundError(f"{path} has no adapter_model.safetensors: it is not a LoRA adapter saved by layerpool or PEFT")
247
+ self._check_adapter(path)
248
+ prefix = "base_model.model."
249
+ found = {}
250
+ for key, value in load_file(where("adapter_model.safetensors")).items():
251
+ name = key[len(prefix):] if key.startswith(prefix) else key
252
+ if name.startswith(stack) and ".lora_" in name:
253
+ module, which = name[len(stack):].split(".lora_")
254
+ found[f"{module}.{which.split('.')[0]}"] = value
255
+ else:
256
+ local[name] = torch.from_numpy(value)
257
+ remote = remote if remote is not None else found
258
+ if os.path.exists(where(LOCAL_FILE)):
259
+ local = {**local, **load_torch(where(LOCAL_FILE))}
260
+ if local:
261
+ names = self.model.state_dict(keep_vars=True)
262
+ unknown = [k for k in local if k not in names]
263
+ if unknown:
264
+ raise ValueError(f"{path} has weights this model does not: {unknown[:5]}")
265
+ with torch.no_grad():
266
+ for k, v in local.items():
267
+ names[k].copy_(v.to(names[k].dtype))
268
+ if os.path.exists(where(LOCAL_OPTIMIZER_FILE)) and self._local_params():
269
+ self._local_opt = self._new_local_opt(self.job["lr"])
270
+ self._local_opt.load_state_dict(torch.load(where(LOCAL_OPTIMIZER_FILE), weights_only=True))
271
+ self.pool.load_weights(remote)
272
+
273
+ def _check_adapter(self, path: str):
274
+ """The adapter must have this run's rank and scale, or its updates would come out at the wrong size."""
275
+ config_path = os.path.join(path, "adapter_config.json")
276
+ if not os.path.exists(config_path):
277
+ return
278
+ with open(config_path, encoding="utf-8") as f:
279
+ config = json.load(f)
280
+ rank, alpha = config.get("r"), config.get("lora_alpha")
281
+ if rank is not None and rank != self.job["rank"]:
282
+ raise ValueError(f"{path} is a rank-{rank} adapter and this run has rank {self.job['rank']}: start the run with lora_r={rank}")
283
+ if rank and alpha is not None:
284
+ scale = alpha / (math.sqrt(rank) if config.get("use_rslora") else rank)
285
+ if abs(scale - self.job["scale"]) > 1e-6 * max(1.0, scale):
286
+ raise ValueError(f"{path} was trained with lora_alpha={alpha} (scale {scale:g}) and this run has scale "
287
+ f"{self.job['scale']:g}: start the run with lora_alpha={alpha / rank * self.job['rank']:g}")
288
+
289
+ def end(self, state: str = "finished"):
290
+ if self._ended:
291
+ return
292
+ self._ended = True
293
+ atexit.unregister(self._end_at_exit)
294
+ if self.ends is not None:
295
+ self.ends.chain.drop_pending()
296
+ self.pool.end_run(state, self.id)
297
+
298
+ def _end_at_exit(self):
299
+ try:
300
+ self.end("finished" if getattr(self, "trained", False) else "stopped")
301
+ except Exception:
302
+ pass
303
+
304
+ def __enter__(self):
305
+ return self
306
+
307
+ def __exit__(self, kind, value, tb):
308
+ self.end("failed" if kind else "finished")
309
+
310
+ def schedule(self, step: int, total: int) -> float:
311
+ return scheduled_lr(self.job["lr"], step, total, self.job.get("warmup", 0), self.job.get("schedule", "constant"), self.job.get("min_lr_ratio", 0.1))
312
+
313
+ def train(self, data, method: str = "sft", steps: int | None = None, epochs: float = 1.0, batch_size: int = 8, seq: int | None = None,
314
+ max_grad_norm: float | None = 1.0, beta: float | None = None, on_step=None, seed: int = 0, **kw) -> list[dict]:
315
+ """Built-in loops. method: "sft" (chat or text rows, learns assistant replies), "cpt" (raw text, every token),
316
+ "dpo" / "ipo" / "simpo" / "orpo" (rows with prompt, chosen, rejected)."""
317
+ return trainers.train(self, data, method=method, steps=steps, epochs=epochs, batch_size=batch_size, seq=seq, max_grad_norm=max_grad_norm,
318
+ beta=beta, on_step=on_step, seed=seed, **kw)
319
+
320
+
321
+ def _choose_attention(model, wanted: str | None):
322
+ """The attention code of the part on this machine: the one asked for, or, on an Apple GPU, the plain one when the model has
323
+ attention dropout (PyTorch's fused attention on Apple GPUs cannot apply dropout in training)."""
324
+ import torch
325
+ if wanted is None:
326
+ text = model.config.get_text_config()
327
+ dropout = max(float(getattr(c, name, 0.0) or 0.0) for c in (model.config, text)
328
+ for name in ("attention_dropout", "attention_probs_dropout_prob", "dropout_rate", "attn_pdrop"))
329
+ if not (dropout > 0 and torch.backends.mps.is_available()):
330
+ return
331
+ wanted = "eager"
332
+ if hasattr(model, "set_attn_implementation"):
333
+ model.set_attn_implementation(wanted)
334
+ else:
335
+ model.config._attn_implementation = wanted
336
+ if wanted == "eager":
337
+ for mod in model.modules():
338
+ config = getattr(mod, "config", None)
339
+ if getattr(config, "_attn_implementation", None) == "sdpa":
340
+ config._attn_implementation = "eager"
341
+
342
+
343
+ def _this_machine() -> list[str]:
344
+ """The ids this machine's own devices joined with (layerpool up, or layerpool join), without making new ones."""
345
+ found = (stored_identity(os.path.join(STATE_DIR, name)) for name in ("local_device_id", "device_id"))
346
+ return [value for value in found if value]
347
+
348
+
349
+ def _inputs_as(say, convert: bool):
350
+ """A pre-hook that gives the model its floating inputs (audio features, pixels) in the model's own dtype, so code written for
351
+ a float32 model keeps working when this machine holds the model in half precision. A half-precision model that is still on
352
+ the CPU when it first runs (a hand-written loop that did not move it to a GPU) goes to float32 first: a CPU is hundreds of
353
+ times slower in bfloat16."""
354
+ import torch
355
+
356
+ def hook(module, args, kwargs):
357
+ if kwargs.get("output_hidden_states") or kwargs.get("output_attentions"):
358
+ from .blocks import NO_INNER_OUTPUTS
359
+ raise ValueError(NO_INNER_OUTPUTS)
360
+ p = next((p for n, p in module.named_parameters() if p.is_floating_point() and n != "layerpool_anchor"), None)
361
+ if p is None:
362
+ return None
363
+ if convert and p.device.type == "cpu" and p.dtype in (torch.bfloat16, torch.float16):
364
+ module.float()
365
+ say("this machine's part of the model runs on the CPU, so in float32; move the model to the GPU (model.to(\"cuda\") "
366
+ "or \"mps\") to run it there in bfloat16")
367
+ p = next(q for n, q in module.named_parameters() if q.is_floating_point() and n != "layerpool_anchor")
368
+ if p.dtype == torch.float32:
369
+ return None
370
+
371
+ def cast(v):
372
+ return v.to(p.dtype) if torch.is_tensor(v) and v.dtype == torch.float32 else v
373
+ return tuple(cast(a) for a in args), {k: cast(v) for k, v in kwargs.items()}
374
+ return hook
375
+
376
+
377
+ def best_device() -> str:
378
+ """Where this machine runs the parts around the blocks: its NVIDIA/AMD GPU if PyTorch can train on it, else the Apple GPU,
379
+ else the CPU."""
380
+ import torch
381
+ if torch.cuda.is_available() and cuda_problem() is None:
382
+ return "cuda"
383
+ if torch.backends.mps.is_available():
384
+ return "mps"
385
+ return "cpu"
386
+
387
+
388
+ def _ends_gb(repo: str, lay: dict, dtype) -> float:
389
+ """Memory the parts around the blocks take on this machine, from the checkpoint's tensor sizes, so the split can count it
390
+ before they are loaded (they load while the devices load their blocks)."""
391
+ import torch
392
+ from .blocks import block_keys
393
+ from .job import tensor_bytes
394
+ try:
395
+ sizes = tensor_bytes(repo)
396
+ inside = block_keys(sizes, lay["stack"], lay["n"])
397
+ held = sum(v for k, v in sizes.items() if k not in inside)
398
+ except Exception:
399
+ return 0.5
400
+ wide = torch.tensor([], dtype=dtype).element_size() if isinstance(dtype, torch.dtype) else 2
401
+ return round(held * max(1.0, wide / 2) / 1e9 + 0.5, 2)
402
+
403
+
404
+ def _local_dtype(choice, mode: str, codec: str, device: str | None = None):
405
+ """With "auto", bfloat16 only where this machine's part will run on a GPU that is fast at it: a CPU is far slower in bfloat16
406
+ than in float32."""
407
+ import torch
408
+ if isinstance(choice, torch.dtype):
409
+ return choice
410
+ if choice in ("float32", "bfloat16", "float16"):
411
+ return getattr(torch, choice)
412
+ if choice != "auto":
413
+ raise ValueError(f"dtype must be \"auto\", \"float32\", \"bfloat16\" or \"float16\", not {choice!r}")
414
+ if mode == "full" or codec == "fp32" or device == "cpu":
415
+ return torch.float32
416
+ if device == "mps":
417
+ return torch.bfloat16
418
+ if torch.cuda.is_available() and cuda_problem() is None:
419
+ return torch.bfloat16 if native_bf16() else torch.float32
420
+ if torch.backends.mps.is_available():
421
+ return torch.bfloat16
422
+ return torch.float32
423
+
424
+
425
+ class Client:
426
+ """A handle on a pool: the in-process one started by start(), or one already running from `layerpool up`."""
427
+
428
+ def __init__(self, pool: Pool | None = None, remote=None, local_worker=None):
429
+ self.pool = pool
430
+ self.remote = remote
431
+ self.local_worker = local_worker
432
+
433
+ @property
434
+ def _p(self):
435
+ return self.pool or self.remote
436
+
437
+ def devices(self) -> list[dict]:
438
+ return self._p.devices()
439
+
440
+ def status(self) -> dict:
441
+ return self._p.status()
442
+
443
+ def invite(self, reusable: bool = False, hours: float = 24) -> dict:
444
+ """A join command for a new device; reusable lets several devices join with it."""
445
+ return self._p.invite(reusable=reusable, ttl=hours * 3600)
446
+
447
+ def _device_id(self, device: str) -> str:
448
+ found = [d["id"] for d in self.devices() if device in (d["id"], d["name"]) and d["status"] != "removed"]
449
+ if not found:
450
+ raise ValueError(f"no device {device!r} in this pool")
451
+ return found[0]
452
+
453
+ def set_device(self, device: str, **settings) -> dict:
454
+ """Change a device's settings, by its id or name: name, cap_gb, enabled, layers (8, "30%", "4-10"), gpus ([0, 2]),
455
+ gpu_caps ({0: 6, 1: 10} in GB), order (its place in the chain) and ram_cap (GB of RAM a machine with GPUs may also use for
456
+ layers its CPU runs); None or "auto" clears one."""
457
+ if "gpu_caps" in settings and isinstance(settings["gpu_caps"], dict):
458
+ settings["gpu_caps"] = {str(k): v for k, v in settings["gpu_caps"].items()}
459
+ return self._p.set_device(self._device_id(device), **settings)
460
+
461
+ def pause(self, device: str):
462
+ """Stop using a device; its layers go to the others."""
463
+ self._p.drain(self._device_id(device))
464
+
465
+ def resume(self, device: str):
466
+ self._p.set_device(self._device_id(device), enabled=True)
467
+
468
+ def remove(self, device: str):
469
+ """Take a device out of the pool; it needs a new invite to come back."""
470
+ self._p.remove(self._device_id(device))
471
+
472
+ def waiting(self) -> list[dict]:
473
+ """Devices that asked to join without a code, each with the code it shows."""
474
+ return self._p.waiting()
475
+
476
+ def approve(self, code: str, yes: bool = True) -> str:
477
+ """Let a waiting device in (yes=False turns it away)."""
478
+ return self._p.answer(code, yes)
479
+
480
+ def end_run(self):
481
+ """End the current run at once, from anywhere (its script gets an error at its next call)."""
482
+ run = self.status().get("run")
483
+ if run:
484
+ self._p.end_run("stopped", run)
485
+
486
+ def plan(self, model: str, mlx_model: str | None = None, mode: str = "lora", rank: int = 16, seq: int = 512, micro: int = 8,
487
+ micro_batch_size: int | None = None, auto: str = "AutoModelForCausalLM", **settings) -> dict:
488
+ """Whether a run of this model fits the devices here now and how it would be split, before starting it: {"plan": [{"name",
489
+ "range", "gb"}, ...] or None, "why": the reason when it does not fit, "layers", "layer_gb"}. The modules around the
490
+ blocks (embeddings, output head) stay on the machine that runs the training code and are not counted here."""
491
+ job = build_job(model, mlx_model=mlx_model, mode=mode, rank=rank, seq=seq, micro=micro, micro_batch_size=micro_batch_size,
492
+ auto=auto, **settings)
493
+ return self._p.plan_for(job)
494
+
495
+ def set_run(self, rebalance: bool | None = None, resplit: bool = False, expected_steps: int | None = None) -> dict:
496
+ """Change the running run: rebalance=False keeps the current split, resplit=True splits the layers again now,
497
+ expected_steps tells rebalancing how long the run is."""
498
+ return self._p.set_run(rebalance=rebalance, resplit=resplit, expected_steps=expected_steps)
499
+
500
+ def wait_for_devices(self, count: int = 1, timeout: float = 600) -> list[dict]:
501
+ deadline, live = time.time() + timeout, []
502
+ while True:
503
+ live = [d for d in self.devices() if d["status"] in ("idle", "training")]
504
+ if len(live) >= count:
505
+ return live
506
+ if time.time() >= deadline:
507
+ break
508
+ time.sleep(0.5)
509
+ raise TimeoutError(f"only {len(live)} of {count} devices joined")
510
+
511
+ def run(self, model: str, mlx_model: str | None = None, mode: str = "lora", rank: int = 16, alpha: float | None = None, lr: float = 1e-4,
512
+ schedule: str = "cosine", warmup: int = 0, min_lr_ratio: float = 0.1, weight_decay: float = 0.0, micro: int = 8,
513
+ micro_batch_size: int | None = None, codec: str = "fp16", ckpt_every: int = 4, random_init: bool = False, expected_steps: int | None = None,
514
+ seq: int = 512, name: str | None = None, timeout: float = 1800, modules_to_save: list[str] | None = None,
515
+ config: dict | None = None, dtype: str = "auto", check: bool = True, attn_implementation: str | None = None,
516
+ device: str | None = "auto", **extra) -> Run:
517
+ """Start a run. mode: "lora" (also QLoRA on a 4-bit model), "full" (every weight), random_init=True trains from scratch.
518
+ modules_to_save: modules around the blocks that a LoRA run trains in full, as in PEFT (a head the checkpoint lacks, such as
519
+ a new classifier, is always trained). config: settings for the model's config, such as {"num_labels": 3}.
520
+ dtype: how this machine holds the parts around the blocks (embeddings, output head, encoders): "float32", "bfloat16",
521
+ "float16", or "auto" (bfloat16 when nothing here is trained and a GPU or Apple GPU is present, which halves this machine's
522
+ memory; float32 otherwise, and always with codec="fp32").
523
+ check: first split a small copy of the model's architecture and compare it with the whole copy (once per architecture),
524
+ so a model layerpool cannot split correctly stops here instead of training wrong.
525
+ device: where this machine runs its part ("auto": its GPU, the Apple GPU, or the CPU; "cuda", "mps", "cpu"); None leaves
526
+ the model on the CPU for you or a Trainer to move."""
527
+ import torch
528
+ place = best_device() if device == "auto" else device
529
+ local = _local_dtype(dtype, mode, codec, place)
530
+ status = self._p.status()
531
+ going = status.get("run")
532
+ quiet = status.get("script_quiet_s")
533
+ if going and not (quiet is not None and quiet > status.get("abandon_after_s", 20)):
534
+ raise PoolError(f"run {going} is still going on this pool: wait for it, or end it with `layerpool end` (or in the dashboard)")
535
+ job = build_job(model, mlx_model=mlx_model, mode=mode, rank=rank, alpha=alpha, lr=lr, schedule=schedule, warmup=warmup, min_lr_ratio=min_lr_ratio,
536
+ weight_decay=weight_decay, micro=micro, micro_batch_size=micro_batch_size, codec=codec, ckpt_every=ckpt_every,
537
+ random_init=random_init, expected_steps=expected_steps, seq=seq, **extra)
538
+ say = getattr(self._p, "event", None) or (lambda text: print(f"[layerpool] {text}", flush=True))
539
+ if job.get("mlx_guessed"):
540
+ say(f"Macs train this 4-bit model with {job['mlx_guessed']} (found on the Hub by its name); pass mlx_model= to choose another")
541
+ if check:
542
+ notes = selfcheck.check(model, job["auto"], log=say)
543
+ if "place" in notes and job["kind"] == "q4":
544
+ raise ValueError(f"{model} cannot be trained in 4-bit by layerpool yet: its blocks compute constants from where they "
545
+ "sit in the model, and the 4-bit path cannot rebuild them in place. Train the 16-bit model instead")
546
+ if "whole_batches" in notes:
547
+ job["micro"], job["micro_batch_size"] = 1, None
548
+ if modules_to_save and dtype == "auto":
549
+ local = torch.float32
550
+ job["driver"] = {"identities": _this_machine(), "gb": _ends_gb(model, job["layout"], local)}
551
+ job["config"] = dict(config or {})
552
+ run_id = self._p.start_run(job, name)
553
+ try:
554
+ here, local = self._load_ends(model, job, local, mode, modules_to_save, dtype, random_init, config, attn_implementation, say)
555
+ self._wait_ready(timeout, say)
556
+ except BaseException:
557
+ self._p.end_run("failed", run_id)
558
+ raise
559
+ tokenizer = None
560
+ try:
561
+ from transformers import AutoTokenizer
562
+ tokenizer = AutoTokenizer.from_pretrained(model)
563
+ except Exception:
564
+ pass
565
+ ends = Ends(here, job["layout"], PoolChain(self._p, job))
566
+ if place:
567
+ here.to(place)
568
+ return Run(self._p, run_id, job, tokenizer, ends)
569
+
570
+ def _load_ends(self, model, job, local, mode, modules_to_save, dtype, random_init, config, attn_implementation, say):
571
+ """This machine's part of the model (embeddings, output head, encoders), loaded while the devices load theirs."""
572
+ import torch
573
+ here = load_ends(model, job["layout"], local, random_init=random_init, log=say, overrides=config)
574
+ here.config._name_or_path = model
575
+ here.name_or_path = model
576
+ _choose_attention(here, attn_implementation)
577
+ stack = job["layout"]["stack"]
578
+ saved = {n.rsplit(".", 1)[0] for n in here.__dict__.get("_layerpool_new", [])}
579
+ names = [n for n, _ in here.named_modules() if n]
580
+ for wanted in modules_to_save or []:
581
+ found = [n for n in names if n == wanted or n.endswith("." + wanted)]
582
+ if not found:
583
+ raise ValueError(f"modules_to_save: this model has no module named {wanted!r}")
584
+ inside = [n for n in found if n == stack or n.startswith(stack + ".")]
585
+ if inside:
586
+ raise ValueError(f"modules_to_save: {inside[0]} is part of the blocks; it is for the modules around them")
587
+ saved.update(found)
588
+ saved = sorted(saved)
589
+ if saved and dtype == "auto" and local != torch.float32:
590
+ here, local = here.float(), torch.float32
591
+ for n, p in here.named_parameters():
592
+ p.requires_grad_(mode == "full" or any(n.startswith(m + ".") for m in saved))
593
+ job["modules_to_save"] = saved if mode != "full" else []
594
+ job["local_dtype"] = str(local).replace("torch.", "")
595
+ here.register_forward_pre_hook(_inputs_as(say, dtype == "auto"), with_kwargs=True)
596
+ return here, local
597
+
598
+ def _wait_ready(self, timeout: float, say):
599
+ """Wait for the devices to load their layers, saying here what the pool does meanwhile (devices downloading, joining) and
600
+ when no device has joined yet, instead of waiting in silence."""
601
+ deadline, told_empty = time.time() + timeout, 0.0
602
+ shown = {tuple(e) for e in (self._p.status().get("events") or [])} if self.remote else set()
603
+ while True:
604
+ left = deadline - time.time()
605
+ if left <= 0:
606
+ raise TimeoutError("the devices did not get ready in time; check the dashboard or `layerpool devices`")
607
+ try:
608
+ self._p.wait_ready(min(15.0, left))
609
+ return
610
+ except (TimeoutError, RemoteError) as e:
611
+ if isinstance(e, RemoteError) and "did not get ready in time" not in str(e):
612
+ raise
613
+ status = self._p.status()
614
+ if self.remote:
615
+ for event in status.get("events") or []:
616
+ if tuple(event) not in shown:
617
+ shown.add(tuple(event))
618
+ print(f"[layerpool] {event[1]}", flush=True)
619
+ if not status.get("devices") and time.time() - told_empty > 60:
620
+ told_empty = time.time()
621
+ say("waiting for devices: none has joined this pool yet. Add one from the dashboard or with `layerpool invite`")
622
+
623
+ def close(self):
624
+ if getattr(self, "_closed", False):
625
+ return
626
+ self._closed = True
627
+ if self.local_worker is not None:
628
+ self.local_worker.alive = False
629
+ if getattr(self, "control", None) is not None:
630
+ self.control.close()
631
+ if self.pool is not None:
632
+ self.pool.close()
633
+
634
+
635
+ def start(port: int = 0, tunnel: bool = False, work: bool = True, cap_gb: float | None = None, name: str | None = None, backend: str = "auto",
636
+ cpu: bool = False, heartbeat_timeout: float = 120.0, log=None, control: bool = True, open_browser: bool = False,
637
+ layers=None, gpus=None, gpu_caps=None, order: int | None = None, ram_cap: float | None = None) -> Client:
638
+ """Start a pool inside this Python process. This machine trains too unless work=False; the device settings (cap_gb,
639
+ layers, gpus, gpu_caps, order, ram_cap) are those of `layerpool join`."""
640
+ pool = Pool(port=port, tunnel=tunnel, heartbeat_timeout=heartbeat_timeout, log=log)
641
+ local = None
642
+ if work:
643
+ local = Worker(f"http://127.0.0.1:{pool.server.port}", pool.token, name, cap_gb, tunnel=tunnel, backend=backend, cpu=cpu,
644
+ identity=device_identity(os.path.join(os.path.expanduser("~"), ".layerpool", "local_device_id")),
645
+ log=(lambda *a: None) if log is not None else None, layers=layers, gpus=gpus, gpu_caps=gpu_caps, order=order, ram_cap=ram_cap)
646
+ threading.Thread(target=local.run, daemon=True).start()
647
+ client = Client(pool=pool, local_worker=local)
648
+ if control:
649
+ client.control = ControlServer(pool)
650
+ client.control.publish()
651
+ if open_browser:
652
+ webbrowser.open(client.control.login_url())
653
+ atexit.register(client.close)
654
+ return client
655
+
656
+
657
+ def connect(url: str | None = None, token: str | None = None, start_if_missing: bool = True, **start_kwargs) -> Client:
658
+ """Attach to a running pool (from `layerpool up`) or start one here. Looks at LAYERPOOL_URL / LAYERPOOL_TOKEN, then ~/.layerpool/pool.json."""
659
+ url = url or os.environ.get("LAYERPOOL_URL")
660
+ token = token or os.environ.get("LAYERPOOL_TOKEN")
661
+ if not url:
662
+ found = find_local()
663
+ if found:
664
+ url, token = found["url"], found["token"]
665
+ if url:
666
+ remote = RemotePool(url, token)
667
+ try:
668
+ theirs = str(remote.status().get("version", ""))
669
+ except RemoteError as e:
670
+ raise PoolError(f"the pool at {url} refused this script ({e}): check LAYERPOOL_TOKEN, or unset LAYERPOOL_URL to use "
671
+ "the pool `layerpool up` started on this computer") from None
672
+ except OSError:
673
+ raise PoolError(f"cannot reach a pool at {url}: is `layerpool up` running there?") from None
674
+ if theirs and theirs.split(".")[:2] != __version__.split(".")[:2]:
675
+ raise RuntimeError(f"the pool runs layerpool {theirs} and this script {__version__}: install the same version in both "
676
+ f"(pip install layerpool=={theirs})")
677
+ return Client(remote=remote)
678
+ if not start_if_missing:
679
+ raise PoolError("no running pool found; start one with `layerpool up`")
680
+ print("[layerpool] no pool is running on this computer, so this script starts its own and trains here alone. To add other "
681
+ "devices, run `layerpool up` in a terminal first.", flush=True)
682
+ return start(**start_kwargs)