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/fetch.py ADDED
@@ -0,0 +1,324 @@
1
+ """Get only the tensors a device needs from a Hugging Face model.
2
+
3
+ A safetensors file starts with a JSON header that lists every tensor's byte range, so a device that holds 2 of 64 layers can
4
+ download the header and those byte ranges instead of the whole file. Files that are already on disk are read in place."""
5
+ import glob
6
+ import hashlib
7
+ import json
8
+ import os
9
+ import struct
10
+ import threading
11
+ import time
12
+ import urllib.parse
13
+ import urllib.request
14
+ from concurrent.futures import ThreadPoolExecutor
15
+
16
+ from .codec import replace_file
17
+
18
+ CACHE = os.path.join(os.path.expanduser("~"), ".cache", "layerpool", "tensors")
19
+ MERGE_GAP = 1 << 20
20
+ WHOLE_FILE_SHARE = 0.7
21
+
22
+
23
+ def _hub_file(repo: str, name: str) -> str:
24
+ from huggingface_hub import hf_hub_download
25
+ return hf_hub_download(repo, name)
26
+
27
+
28
+ def load_json(repo: str, name: str) -> dict:
29
+ path = os.path.join(repo, name) if os.path.isdir(repo) else _hub_file(repo, name)
30
+ with open(path, encoding="utf-8") as f:
31
+ return json.load(f)
32
+
33
+
34
+ def weight_map(repo: str) -> dict[str, str]:
35
+ """tensor name -> file name inside the repo."""
36
+ try:
37
+ return load_json(repo, "model.safetensors.index.json")["weight_map"]
38
+ except Exception:
39
+ pass
40
+ try:
41
+ return {key: "model.safetensors" for key in header(repo, "model.safetensors") if key != "__metadata__"}
42
+ except Exception:
43
+ if os.path.isdir(repo):
44
+ files = os.listdir(repo)
45
+ else:
46
+ from huggingface_hub import list_repo_files
47
+ files = list_repo_files(repo)
48
+ if not any(f.endswith(".safetensors") for f in files):
49
+ other = sorted({os.path.splitext(f)[1] for f in files if f.endswith((".bin", ".pt", ".pth", ".gguf", ".ckpt"))})
50
+ found = f" (only {', '.join(other)} files)" if other else ""
51
+ raise ValueError(f"{repo} has no .safetensors weights{found}; layerpool "
52
+ "reads safetensors only. Pick a repo that has them, or load it once with transformers and save_pretrained "
53
+ "it to a folder (that writes safetensors)") from None
54
+ raise
55
+
56
+
57
+ def _local(repo: str, name: str) -> str | None:
58
+ if os.path.isdir(repo):
59
+ return os.path.join(repo, name)
60
+ try:
61
+ from huggingface_hub import try_to_load_from_cache
62
+ found = try_to_load_from_cache(repo, name)
63
+ return found if isinstance(found, str) and os.path.exists(found) else None
64
+ except Exception:
65
+ return None
66
+
67
+
68
+ def _remote(repo: str, name: str) -> tuple[str, dict, str, int]:
69
+ from huggingface_hub import get_hf_file_metadata, hf_hub_url
70
+ from huggingface_hub.utils import build_hf_headers
71
+ meta = get_hf_file_metadata(hf_hub_url(repo, name))
72
+ url = meta.location or hf_hub_url(repo, name)
73
+ hub = urllib.parse.urlsplit(hf_hub_url(repo, name)).hostname
74
+ headers = build_hf_headers() if urllib.parse.urlsplit(url).hostname == hub else {}
75
+ return url, headers, meta.commit_hash or "main", int(meta.size or 0)
76
+
77
+
78
+ def revision(repo: str) -> str:
79
+ """The commit of a hub model (or the mtime of a local folder), to key caches by."""
80
+ if os.path.isdir(repo):
81
+ files = sorted(f for f in os.listdir(repo) if f.endswith((".safetensors", ".json")))
82
+ return hashlib.sha1("|".join(f"{f}:{os.path.getsize(os.path.join(repo, f))}:{os.path.getmtime(os.path.join(repo, f))}"
83
+ for f in files).encode()).hexdigest()[:12]
84
+ return _remote(repo, "config.json")[2]
85
+
86
+
87
+ def _cached_parts(repo: str, name: str) -> list[str]:
88
+ return sorted(glob.glob(os.path.join(CACHE, repo.replace("/", "--"), "*", f"{name.replace('/', '--')}.*.safetensors")),
89
+ key=os.path.getmtime, reverse=True)
90
+
91
+
92
+ def _get_range(url: str, headers: dict, start: int, end: int) -> bytes:
93
+ request = urllib.request.Request(url, headers={**headers, "Range": f"bytes={start}-{end - 1}"})
94
+ for attempt in range(5):
95
+ try:
96
+ with urllib.request.urlopen(request, timeout=120) as r:
97
+ data = r.read()
98
+ if r.status != 206 and start != 0:
99
+ raise IOError(f"server ignored the byte range (HTTP {r.status})")
100
+ data = data[:end - start]
101
+ if len(data) != end - start:
102
+ raise IOError(f"got {len(data)} bytes instead of {end - start}")
103
+ return data
104
+ except Exception:
105
+ if attempt == 4:
106
+ raise
107
+ raise IOError("unreachable")
108
+
109
+
110
+ def _read_header(read) -> tuple[dict, int]:
111
+ size = struct.unpack("<Q", read(0, 8))[0]
112
+ return json.loads(read(8, 8 + size)), 8 + size
113
+
114
+
115
+ def header(repo: str, name: str) -> dict:
116
+ local = _local(repo, name)
117
+ if local:
118
+ with open(local, "rb") as f:
119
+ size = struct.unpack("<Q", f.read(8))[0]
120
+ return json.loads(f.read(size))
121
+ try:
122
+ url, headers, _, _ = _remote(repo, name)
123
+ except Exception:
124
+ cached = _cached_parts(repo, name)
125
+ if not cached:
126
+ raise
127
+ with open(cached[0], "rb") as f:
128
+ size = struct.unpack("<Q", f.read(8))[0]
129
+ return json.loads(f.read(size))
130
+ return _read_header(lambda a, b: _get_range(url, headers, a, b))[0]
131
+
132
+
133
+ CHUNK = 1 << 20
134
+
135
+
136
+ def _stream_range(url: str, headers: dict, start: int, end: int, sink):
137
+ """Bytes start..end of a remote file, handed to sink(position, bytes) a megabyte at a time, so no whole range sits in memory.
138
+ A failed attempt starts the range again; sink writes to fixed places, so that is safe."""
139
+ request = urllib.request.Request(url, headers={**headers, "Range": f"bytes={start}-{end - 1}"})
140
+ for attempt in range(5):
141
+ try:
142
+ with urllib.request.urlopen(request, timeout=120) as r:
143
+ if r.status != 206 and start != 0:
144
+ raise IOError(f"server ignored the byte range (HTTP {r.status})")
145
+ pos = start
146
+ while pos < end:
147
+ chunk = r.read(min(CHUNK, end - pos))
148
+ if not chunk:
149
+ raise IOError(f"got {pos - start} bytes instead of {end - start}")
150
+ sink(pos, chunk)
151
+ pos += len(chunk)
152
+ return
153
+ except Exception:
154
+ if attempt == 4:
155
+ raise
156
+
157
+
158
+ def _layout(entries: list[tuple[str, dict, int]]) -> tuple[bytes, dict]:
159
+ """The header of a safetensors file holding these tensors in this order, and where each tensor's bytes start after it."""
160
+ out, offset, starts = {}, 0, {}
161
+ for key, info, size in entries:
162
+ out[key] = {"dtype": info["dtype"], "shape": info["shape"], "data_offsets": [offset, offset + size]}
163
+ starts[key] = offset
164
+ offset += size
165
+ head = json.dumps({"__metadata__": {"format": "pt"}, **out}, separators=(",", ":")).encode()
166
+ head += b" " * (-len(head) % 8)
167
+ return struct.pack("<Q", len(head)) + head, {k: len(head) + 8 + v for k, v in starts.items()}
168
+
169
+
170
+ def copy_tensors(files: dict[str, list[str]], rename, path: str):
171
+ """A safetensors file at `path` with the tensors `files` names ({source file: [keys]}), renamed, copied as raw bytes a
172
+ megabyte at a time instead of loaded."""
173
+ entries, sources = [], []
174
+ for source, keys in files.items():
175
+ with open(source, "rb") as f:
176
+ size = struct.unpack("<Q", f.read(8))[0]
177
+ head = json.loads(f.read(size))
178
+ for key in keys:
179
+ a, b = head[key]["data_offsets"]
180
+ entries.append((rename(key), head[key], b - a))
181
+ sources.append((source, 8 + size + a, b - a))
182
+ header, starts = _layout(entries)
183
+ tmp = f"{path}.{os.getpid()}.{threading.get_ident()}.part"
184
+ with open(tmp, "wb") as out:
185
+ out.write(header)
186
+ for (key, _, _), (source, at, size) in zip(entries, sources):
187
+ with open(source, "rb") as f:
188
+ f.seek(at)
189
+ left = size
190
+ while left:
191
+ chunk = f.read(min(CHUNK, left))
192
+ if not chunk:
193
+ raise IOError(f"{source} ends inside {key}")
194
+ out.write(chunk)
195
+ left -= len(chunk)
196
+ replace_file(tmp, path)
197
+
198
+
199
+ def fetch(repo: str, keys, log=None) -> dict[str, list[str]]:
200
+ """Make the tensors `keys` available on disk. Returns {safetensors path: [keys in that file]}."""
201
+ log = log or (lambda *a: None)
202
+ files = weight_map(repo)
203
+ by_file: dict[str, list[str]] = {}
204
+ for key in keys:
205
+ by_file.setdefault(files[key], []).append(key)
206
+ out = {}
207
+ for name, wanted in sorted(by_file.items()):
208
+ local = _local(repo, name)
209
+ if local:
210
+ out[local] = wanted
211
+ continue
212
+ try:
213
+ out[_fetch_part(repo, name, wanted, log)] = wanted
214
+ except Exception as e:
215
+ log(f"partial download of {name} failed ({e!r}); downloading the whole file")
216
+ out[_hub_file(repo, name)] = wanted
217
+ return out
218
+
219
+
220
+ def _already_here(folder: str, name: str, head: dict, wanted: list[str]) -> dict:
221
+ """Tensors of this file that an earlier download of other layers (before a rebalance) already put on this device:
222
+ {key: (file, offset, size)}, so only the rest is downloaded again."""
223
+ found = {}
224
+ for part in glob.glob(os.path.join(folder, f"{name.replace('/', '--')}.*.safetensors")):
225
+ try:
226
+ with open(part, "rb") as f:
227
+ size = struct.unpack("<Q", f.read(8))[0]
228
+ theirs = json.loads(f.read(size))
229
+ except (OSError, ValueError, struct.error):
230
+ continue
231
+ for key in wanted:
232
+ info = theirs.get(key)
233
+ if key in found or not isinstance(info, dict):
234
+ continue
235
+ if info.get("dtype") == head[key]["dtype"] and info.get("shape") == head[key]["shape"]:
236
+ a, b = info["data_offsets"]
237
+ found[key] = (part, 8 + size + a, b - a)
238
+ return found
239
+
240
+
241
+ def _fetch_part(repo: str, name: str, wanted: list[str], log) -> str:
242
+ key_hash = hashlib.sha1("\n".join(sorted(wanted)).encode()).hexdigest()[:16]
243
+ try:
244
+ url, headers, commit, size = _remote(repo, name)
245
+ except Exception:
246
+ for found in _cached_parts(repo, name):
247
+ if found.endswith(f".{key_hash}.safetensors"):
248
+ log(f"the hub cannot be reached; using the copy of {name} already on this device")
249
+ return found
250
+ raise
251
+ folder = os.path.join(CACHE, repo.replace("/", "--"), commit)
252
+ path = os.path.join(folder, f"{name.replace('/', '--')}.{key_hash}.safetensors")
253
+ if os.path.exists(path):
254
+ os.utime(path)
255
+ return path
256
+ head, base = _read_header(lambda a, b: _get_range(url, headers, a, b))
257
+ everything = sorted((base + head[k]["data_offsets"][0], base + head[k]["data_offsets"][1], k) for k in wanted)
258
+ here = _already_here(folder, name, head, wanted)
259
+ spans = [s for s in everything if s[2] not in here]
260
+ need = sum(b - a for a, b, _ in spans)
261
+ if size and need > WHOLE_FILE_SHARE * size:
262
+ return _hub_file(repo, name)
263
+ if spans:
264
+ kept = f", {len(here)} tensors already on this device" if here else ""
265
+ log(f"downloading {need / 1e6:.0f} MB of {name} ({size / 1e6:.0f} MB), only the layers this device holds{kept}")
266
+ groups, current = [], None
267
+ for a, b, k in spans:
268
+ if current and a - current[1] <= MERGE_GAP:
269
+ current[1] = max(current[1], b)
270
+ current[2].append((a, b, k))
271
+ else:
272
+ current = [a, b, [(a, b, k)]]
273
+ groups.append(current)
274
+ header, starts = _layout([(k, head[k], b - a) for a, b, k in everything])
275
+ os.makedirs(folder, exist_ok=True)
276
+ tmp = f"{path}.{os.getpid()}.{threading.get_ident()}.part"
277
+ with open(tmp, "wb") as f:
278
+ f.write(header)
279
+ f.truncate(len(header) + sum(b - a for a, b, _ in everything))
280
+ for key, (source, at, length) in here.items():
281
+ f.seek(starts[key])
282
+ with open(source, "rb") as src:
283
+ src.seek(at)
284
+ left = length
285
+ while left:
286
+ chunk = src.read(min(CHUNK, left))
287
+ if not chunk:
288
+ raise IOError(f"{source} ends inside {key}")
289
+ f.write(chunk)
290
+ left -= len(chunk)
291
+
292
+ def one(group):
293
+ _, _, members = group
294
+ with open(tmp, "r+b") as f:
295
+ def sink(pos, chunk):
296
+ for a, b, k in members:
297
+ lo, hi = max(a, pos), min(b, pos + len(chunk))
298
+ if lo < hi:
299
+ f.seek(starts[k] + lo - a)
300
+ f.write(chunk[lo - pos:hi - pos])
301
+ _stream_range(url, headers, group[0], group[1], sink)
302
+ try:
303
+ with ThreadPoolExecutor(max_workers=4) as pool:
304
+ list(pool.map(one, groups))
305
+ except BaseException:
306
+ os.remove(tmp)
307
+ raise
308
+ replace_file(tmp, path)
309
+ _prune_parts(folder, name, path)
310
+ return path
311
+
312
+
313
+ def _prune_parts(folder: str, name: str, keep: str):
314
+ """Partial downloads of one file pile up as a device's layers change. The newest two stay (the next change usually reuses
315
+ the previous range); older ones go once unused for ten minutes, since another device on this machine may be reading one."""
316
+ parts = [p for p in glob.glob(os.path.join(folder, f"{name.replace('/', '--')}.*.safetensors")) if p != keep]
317
+ parts.sort(key=os.path.getmtime, reverse=True)
318
+ now = time.time()
319
+ for part in parts[1:]:
320
+ if now - os.path.getmtime(part) > 600:
321
+ try:
322
+ os.remove(part)
323
+ except OSError:
324
+ pass
layerpool/hf.py ADDED
@@ -0,0 +1,303 @@
1
+ """Use a layerpool run as a Hugging Face model, so transformers.Trainer, TRL trainers and hand-written loops work unchanged.
2
+
3
+ model = layerpool.hf.AutoModelForCausalLM.from_pretrained("Qwen/Qwen3-0.6B", lora_r=16)
4
+ trainer = transformers.Trainer(model=model, args=TrainingArguments(...), train_dataset=ds, data_collator=...)
5
+ trainer.train()
6
+ model.save_pretrained("out")
7
+
8
+ The model you get is the real transformers model: its embeddings, output head and any image or audio encoder are on this machine,
9
+ and its repeated blocks run on the devices. Every AutoModel class works (layerpool.hf.AutoModelForImageTextToText, AutoModel, ...).
10
+ The model shows torch one stand-in parameter whose gradient equals the gradient norm on the devices, so clip_grad_norm_ works
11
+ unchanged, and every optimizer.step() is forwarded to the devices with the learning rate the scheduler set and the clipping factor
12
+ torch applied."""
13
+
14
+ import inspect
15
+ import os
16
+ import warnings
17
+
18
+ import torch
19
+ from torch.optim.optimizer import register_optimizer_step_pre_hook
20
+
21
+ from .api import connect
22
+ from .blocks import load_config
23
+
24
+ _runs: dict = {}
25
+
26
+
27
+ def _is_ours(model) -> bool:
28
+ return getattr(model, "layerpool_run", None) is not None
29
+
30
+
31
+ def _step_hook(optimizer, args, kwargs):
32
+ for group in optimizer.param_groups:
33
+ for p in group["params"]:
34
+ run = _runs.get(id(p))
35
+ if run is not None:
36
+ _optimizer_step(run, optimizer, group)
37
+
38
+
39
+ def _optimizer_step(run, optimizer, group):
40
+ ends = run.ends
41
+ ends.chain.drop_pending()
42
+ if not getattr(run, "_warned_optimizer", False) and not isinstance(optimizer, (torch.optim.AdamW, torch.optim.Adam)):
43
+ run._warned_optimizer = True
44
+ warnings.warn(f"layerpool trains the devices with AdamW; {type(optimizer).__name__} only sets the learning rate and weight decay")
45
+ norm = ends.remote_norm
46
+ current = float(ends.anchor.grad.item()) if ends.anchor.grad is not None else norm
47
+ clip = current / norm if norm > 0 else 1.0
48
+ run.pool.optim_step(float(group["lr"]), None, run._loss_accum, clip=min(1.0, clip), weight_decay=group.get("weight_decay"))
49
+ ends.remote_norm = 0.0
50
+ run._loss_accum = None
51
+ run._loss_parts = []
52
+
53
+
54
+ register_optimizer_step_pre_hook(_step_hook)
55
+
56
+
57
+ def _tell_length(run):
58
+ """A Trainer callback that tells the pool how many steps the Trainer will take, so rebalancing weighs a move against the
59
+ steps left."""
60
+ from transformers import TrainerCallback
61
+
62
+ class TellLength(TrainerCallback):
63
+ layerpool_run = run
64
+
65
+ def on_train_begin(self, args, state, control, **kwargs):
66
+ if state.max_steps and state.max_steps > 0:
67
+ run.pool.set_run(expected_steps=state.max_steps)
68
+ chain = run.ends.chain
69
+ if hasattr(chain, "expect"):
70
+ rows, pieces = chain.pieces(int(args.per_device_train_batch_size))
71
+ chain.expect(rows, run.job.get("seq", 512), pieces)
72
+ if args.gradient_accumulation_steps > 1 and args.per_device_train_batch_size < 2 * len(run.pool.status().get("plan") or [1]):
73
+ warnings.warn(f"layerpool: per_device_train_batch_size={args.per_device_train_batch_size} with gradient_accumulation_steps="
74
+ f"{args.gradient_accumulation_steps} sends small batches one after another, so the devices mostly wait for each "
75
+ "other; a bigger per_device_train_batch_size with fewer accumulation steps (the same rows per step) lets "
76
+ "them all work at once", stacklevel=2)
77
+ return TellLength()
78
+
79
+
80
+ def _needs(cls, names, package: str):
81
+ """layerpool hooks into these methods; a release that renamed one gets a clear message instead of an AttributeError."""
82
+ missing = [n for n in names if not callable(getattr(cls, n, None))]
83
+ if missing:
84
+ import importlib.metadata
85
+ try:
86
+ version = importlib.metadata.version(package)
87
+ except importlib.metadata.PackageNotFoundError:
88
+ version = "?"
89
+ raise RuntimeError(f"this {package} ({version}) has no {cls.__name__}.{', '.join(missing)}, which layerpool hooks into; "
90
+ f"install the {package} version layerpool was released with, or update layerpool")
91
+
92
+
93
+ def _teach_trainer():
94
+ """transformers.Trainer saves models it knows by their state_dict; a layerpool model saves its weights from the devices instead."""
95
+ try:
96
+ from transformers import Trainer
97
+ except ImportError:
98
+ return
99
+ if Trainer.__dict__.get("_layerpool", False):
100
+ return
101
+ _needs(Trainer, ("_save", "_load_from_checkpoint", "_wrap_model", "_load_best_model", "train"), "transformers")
102
+ save, load = Trainer._save, Trainer._load_from_checkpoint
103
+
104
+ def _save(self, output_dir=None, state_dict=None):
105
+ model = self.accelerator.unwrap_model(self.model) if hasattr(self, "accelerator") else self.model
106
+ if _is_ours(model):
107
+ output_dir = output_dir or self.args.output_dir
108
+ os.makedirs(output_dir, exist_ok=True)
109
+ model.layerpool_run.save(output_dir, optimizer=True)
110
+ if getattr(self, "processing_class", None) is not None:
111
+ self.processing_class.save_pretrained(output_dir)
112
+ torch.save(self.args, os.path.join(output_dir, "training_args.bin"))
113
+ return
114
+ return save(self, output_dir, state_dict)
115
+
116
+ def _load_from_checkpoint(self, resume_from_checkpoint, model=None):
117
+ target = model or self.model
118
+ if _is_ours(target):
119
+ target.layerpool_run.load(resume_from_checkpoint)
120
+ return
121
+ return load(self, resume_from_checkpoint, model)
122
+ wrap = Trainer._wrap_model
123
+
124
+ def _wrap_model(self, model, *args, **kwargs):
125
+ if _is_ours(model):
126
+ return model
127
+ return wrap(self, model, *args, **kwargs)
128
+ train = Trainer.train
129
+
130
+ def _train(self, *args, **kwargs):
131
+ model = self.accelerator.unwrap_model(self.model) if hasattr(self, "accelerator") else self.model
132
+ if _is_ours(model) and not any(getattr(c, "layerpool_run", None) is model.layerpool_run for c in self.callback_handler.callbacks):
133
+ self.add_callback(_tell_length(model.layerpool_run))
134
+ out = train(self, *args, **kwargs)
135
+ model = self.accelerator.unwrap_model(self.model) if hasattr(self, "accelerator") else self.model
136
+ if _is_ours(model):
137
+ model.layerpool_run.trained = True
138
+ return out
139
+ best = Trainer._load_best_model
140
+
141
+ def _load_best_model(self):
142
+ model = self.accelerator.unwrap_model(self.model) if hasattr(self, "accelerator") else self.model
143
+ if _is_ours(model):
144
+ if self.state.best_model_checkpoint:
145
+ model.layerpool_run.load(self.state.best_model_checkpoint)
146
+ return
147
+ return best(self)
148
+ Trainer._save, Trainer._load_from_checkpoint, Trainer._wrap_model, Trainer.train = _save, _load_from_checkpoint, _wrap_model, _train
149
+ Trainer._load_best_model = _load_best_model
150
+ Trainer._layerpool = True
151
+ _teach_preference_trainers()
152
+
153
+
154
+ def _teach_preference_trainers():
155
+ """TRL's DPO-style trainers load a second full copy of the model on this machine as the reference unless the reference
156
+ log-probs are computed up front. The policy at the start of the run is that reference, so compute them up front."""
157
+ try:
158
+ import trl
159
+ except Exception:
160
+ return
161
+ try:
162
+ major, minor = (int(x) for x in trl.__version__.split(".")[:2])
163
+ if (major, minor) < (1, 15):
164
+ warnings.warn(f"layerpool needs trl>=1.15 for TRL trainers (you have {trl.__version__}): pip install -U trl")
165
+ except ValueError:
166
+ pass
167
+ for name in ("DPOTrainer", "KTOTrainer"):
168
+ try:
169
+ cls = getattr(trl, name, None)
170
+ except Exception:
171
+ continue
172
+ if cls is None or cls.__dict__.get("_layerpool", False):
173
+ continue
174
+ init = cls.__init__
175
+ if list(inspect.signature(init).parameters)[1:4] != ["model", "ref_model", "args"]:
176
+ warnings.warn(f"layerpool: this TRL's {name} takes other arguments than the versions layerpool knows, so it is not adjusted; "
177
+ f"give it a {name.replace('Trainer', 'Config')} with precompute_ref_log_probs=True")
178
+ cls._layerpool = True
179
+ continue
180
+
181
+ def __init__(self, model=None, ref_model=None, args=None, *rest, _init=init, _name=name, **kwargs):
182
+ if _is_ours(model) and ref_model is None and args is None and hasattr(trl, _name.replace("Trainer", "Config")):
183
+ short = str(getattr(model.config, "_name_or_path", "model")).rstrip("/").split("/")[-1]
184
+ args = getattr(trl, _name.replace("Trainer", "Config"))(output_dir=f"{short}-{_name[:-7]}", precompute_ref_log_probs=True)
185
+ if _is_ours(model) and ref_model is None and args is not None and hasattr(args, "precompute_ref_log_probs") \
186
+ and not args.precompute_ref_log_probs:
187
+ warnings.warn(f"layerpool: {_name} computes the reference log-probs before training (precompute_ref_log_probs=True) "
188
+ "instead of loading a second copy of the model on this machine")
189
+ args.precompute_ref_log_probs = True
190
+ _init(self, model, ref_model, args, *rest, **kwargs)
191
+ cls.__init__, cls._layerpool = __init__, True
192
+
193
+
194
+ _LOADING = {"device_map", "low_cpu_mem_usage", "trust_remote_code", "revision", "cache_dir",
195
+ "token", "use_safetensors", "local_files_only", "force_download", "max_memory", "offload_folder", "quantization_config"}
196
+ _LOADING_WARN = {
197
+ "quantization_config": "load a checkpoint that is already 4-bit (for example an unsloth ...-bnb-4bit repo) for QLoRA",
198
+ "trust_remote_code": "layerpool runs the model classes that ship with transformers, not code from the repo",
199
+ "device_map": "the blocks go to the devices of the pool, and the rest stays on this machine",
200
+ "max_memory": "set each device's memory cap in the dashboard or with `layerpool set DEVICE --cap-gb`",
201
+ "offload_folder": "the blocks go to the devices of the pool",
202
+ "revision": "every device downloads the model's main branch; to train another revision, download it to a folder that every "
203
+ "device has, or push it to its own repo",
204
+ "token": "each device downloads with its own Hugging Face login: run `hf auth login` or set HF_TOKEN on every device",
205
+ "cache_dir": "each device uses its own Hugging Face cache (HF_HOME)",
206
+ "local_files_only": "each device downloads what it needs unless HF_HUB_OFFLINE=1 is set on it",
207
+ }
208
+ _RUN_ARGS = {"mode", "rank", "alpha", "lr", "schedule", "warmup", "min_lr_ratio", "weight_decay", "micro", "micro_batch_size", "codec",
209
+ "ckpt_every", "random_init", "expected_steps", "seq", "name", "timeout", "check", "dtype", "attn_implementation"}
210
+
211
+
212
+ class _Auto:
213
+ """layerpool.hf.AutoModelFor...: the same class name as in transformers; from_pretrained starts a run on the pool."""
214
+
215
+ def __init__(self, auto: str):
216
+ self.auto = auto
217
+
218
+ def from_pretrained(self, model: str, pool=None, mlx_model: str | None = None, lora_r: int = 16, lora_alpha: float | None = None,
219
+ full: bool = False, modules_to_save: list[str] | None = None, **kwargs):
220
+ """kwargs that transformers' from_pretrained takes for the config (num_labels=3, id2label=...) set the model's config;
221
+ dtype (or torch_dtype) is how this machine holds the parts around the blocks ("auto", "float32", "bfloat16", a torch
222
+ dtype); the ones about where weights load (device_map, ...) do not apply, since the devices hold the blocks; the rest go to
223
+ the run (micro, seq, codec, peer_replicas, ...)."""
224
+ _teach_trainer()
225
+ config = load_config(model)
226
+ overrides, run_kwargs = {}, {}
227
+ for key in ("mode", "rank", "alpha"):
228
+ if key in kwargs:
229
+ raise TypeError(f"from_pretrained takes {key} as {dict(mode='full=True', rank='lora_r', alpha='lora_alpha')[key]}")
230
+ for key, value in kwargs.items():
231
+ if key in ("dtype", "torch_dtype"):
232
+ run_kwargs["dtype"] = value
233
+ continue
234
+ if key == "quantization_config" and value is not None and not getattr(config, "quantization_config", None):
235
+ raise ValueError(f"layerpool cannot quantize {model} while loading it: for QLoRA load a checkpoint that is already 4-bit "
236
+ "with bitsandbytes (for example unsloth/<model>-bnb-4bit) and leave out quantization_config")
237
+ if key in _LOADING:
238
+ if key in _LOADING_WARN and value not in (None, False) and key != "quantization_config":
239
+ warnings.warn(f"layerpool: {key} does not apply here: {_LOADING_WARN[key]}", stacklevel=2)
240
+ continue
241
+ if key in ("num_labels", "id2label", "label2id") or (hasattr(config, key) and key not in _RUN_ARGS):
242
+ overrides[key] = value
243
+ else:
244
+ run_kwargs[key] = value
245
+ run_kwargs.setdefault("schedule", "constant")
246
+ run_kwargs.setdefault("device", None)
247
+ client = pool or connect()
248
+ run = client.run(model, mlx_model=mlx_model, mode="full" if full else "lora", rank=lora_r, alpha=lora_alpha,
249
+ auto=self.auto, modules_to_save=modules_to_save, config=overrides or None, **run_kwargs)
250
+ return wrap_run(run)
251
+
252
+
253
+ def wrap_run(run):
254
+ m = run.model
255
+ key = id(run.ends.anchor)
256
+ _runs[key] = run
257
+ m.layerpool_run = run
258
+ m.save_pretrained = lambda path, *a, **kw: run.save(path)
259
+ m.load_adapter = lambda path, *a, **kw: run.load(path)
260
+
261
+ def end(state: str = "finished"):
262
+ _runs.pop(key, None)
263
+ run.end(state)
264
+ m.end = end
265
+ zero_grad = m.zero_grad
266
+
267
+ def drop_device_grads():
268
+ """The training code threw this batch's gradients away without a step (a GradScaler skip, or zero_grad on purpose):
269
+ the devices drop theirs too."""
270
+ if run.ends.remote_norm:
271
+ run.ends.chain.drop_pending()
272
+ run.pool.optim_step(None, None, run._loss_accum, skip=True)
273
+ run.ends.remote_norm = 0.0
274
+ run._loss_accum, run._loss_parts = None, []
275
+
276
+ def zero_grad_and_skip(*a, **kw):
277
+ drop_device_grads()
278
+ return zero_grad(*a, **kw)
279
+ m.zero_grad = zero_grad_and_skip
280
+ run.ends.discard = drop_device_grads
281
+ m.gradient_checkpointing_enable = lambda *a, **kw: None
282
+ m.gradient_checkpointing_disable = lambda *a, **kw: None
283
+ m.activation_checkpointing_enable = m.gradient_checkpointing_enable
284
+ m.activation_checkpointing_disable = m.gradient_checkpointing_disable
285
+
286
+ def keep_loss(module, args, kwargs, output):
287
+ loss = getattr(output, "loss", None)
288
+ if loss is not None and torch.is_grad_enabled() and module.training:
289
+ whole_step = kwargs.get("num_items_in_batch") is not None
290
+ labels = kwargs.get("labels")
291
+ tokens = None if whole_step or not torch.is_tensor(labels) else max(1, int((labels != -100).sum()))
292
+ run._add_loss(float(loss.detach()), tokens)
293
+ m.register_forward_hook(keep_loss, with_kwargs=True)
294
+ return m
295
+
296
+
297
+ AutoModelForCausalLM = _Auto("AutoModelForCausalLM")
298
+
299
+
300
+ def __getattr__(name: str):
301
+ if name.startswith("AutoModel"):
302
+ return _Auto(name)
303
+ raise AttributeError(name)