layerpool 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- layerpool/__init__.py +11 -0
- layerpool/__main__.py +3 -0
- layerpool/api.py +682 -0
- layerpool/backends/__init__.py +0 -0
- layerpool/backends/common.py +21 -0
- layerpool/backends/mlx_backend.py +622 -0
- layerpool/blocks.py +1061 -0
- layerpool/cli.py +567 -0
- layerpool/codec.py +195 -0
- layerpool/control.py +447 -0
- layerpool/driver.py +427 -0
- layerpool/export.py +157 -0
- layerpool/fetch.py +324 -0
- layerpool/hf.py +303 -0
- layerpool/job.py +242 -0
- layerpool/losses.py +108 -0
- layerpool/net.py +529 -0
- layerpool/planner.py +104 -0
- layerpool/pool.py +1670 -0
- layerpool/selfcheck.py +348 -0
- layerpool/telemetry.py +195 -0
- layerpool/trainers.py +168 -0
- layerpool/tunnel.py +165 -0
- layerpool/ui/app.js +479 -0
- layerpool/ui/index.html +82 -0
- layerpool/ui/style.css +148 -0
- layerpool/worker.py +1277 -0
- layerpool-0.1.0.dist-info/METADATA +407 -0
- layerpool-0.1.0.dist-info/RECORD +32 -0
- layerpool-0.1.0.dist-info/WHEEL +4 -0
- layerpool-0.1.0.dist-info/entry_points.txt +2 -0
- layerpool-0.1.0.dist-info/licenses/LICENSE +21 -0
layerpool/blocks.py
ADDED
|
@@ -0,0 +1,1061 @@
|
|
|
1
|
+
"""Any transformers model, split by its repeated blocks.
|
|
2
|
+
|
|
3
|
+
A model is a stack of identical blocks with some modules around it (embeddings, an image or audio encoder, the output head).
|
|
4
|
+
The machine that runs the training code keeps the modules around the stack and runs the model's own forward from transformers;
|
|
5
|
+
the devices hold slices of the stack. Each block is called with the arguments the model itself computed for it (masks, rotary
|
|
6
|
+
tables, positions, encoder states), so no architecture needs code of its own here."""
|
|
7
|
+
import copy
|
|
8
|
+
import hashlib
|
|
9
|
+
import json
|
|
10
|
+
import os
|
|
11
|
+
import re
|
|
12
|
+
import shutil
|
|
13
|
+
import time
|
|
14
|
+
|
|
15
|
+
import numpy as np
|
|
16
|
+
|
|
17
|
+
from . import fetch
|
|
18
|
+
from .backends import common
|
|
19
|
+
|
|
20
|
+
STACK_COUNT_ATTRS = ("num_hidden_layers", "n_layer", "num_layers", "decoder_layers", "n_layers", "num_decoder_layers")
|
|
21
|
+
RANGE_CACHE = os.path.join(os.path.expanduser("~"), ".cache", "layerpool", "ranges")
|
|
22
|
+
BETAS = (0.9, 0.999)
|
|
23
|
+
SCALE_GROWTH_STEPS = 200
|
|
24
|
+
EPS = 1e-8
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def auto_class(name: str):
|
|
28
|
+
import transformers
|
|
29
|
+
return getattr(transformers, name)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def stack_candidates(model) -> list[tuple[str, object]]:
|
|
33
|
+
"""Lists of same-class modules that could be the repeated blocks, most likely first: those as long as a layer count of the
|
|
34
|
+
model's config (the text model's first), then the biggest. Lists of embeddings, convolutions or norms are not blocks."""
|
|
35
|
+
import torch
|
|
36
|
+
counts = set()
|
|
37
|
+
for config in (getattr(model, "config", None), getattr(getattr(model, "config", None), "get_text_config", lambda: None)()):
|
|
38
|
+
for attr in STACK_COUNT_ATTRS:
|
|
39
|
+
value = getattr(config, attr, None) if config is not None else None
|
|
40
|
+
if isinstance(value, int):
|
|
41
|
+
counts.add(value)
|
|
42
|
+
leaf = (torch.nn.Embedding, torch.nn.Conv1d, torch.nn.Conv2d, torch.nn.LayerNorm, torch.nn.Linear)
|
|
43
|
+
found = []
|
|
44
|
+
for name, mod in model.named_modules():
|
|
45
|
+
if isinstance(mod, torch.nn.ModuleList) and len(mod) > 1 and len({type(m) for m in mod}) == 1 and not isinstance(mod[0], leaf):
|
|
46
|
+
size = sum(p.numel() for p in mod.parameters())
|
|
47
|
+
found.append((len(mod) in counts, size, name, mod))
|
|
48
|
+
found.sort(key=lambda f: (f[0], f[1]), reverse=True)
|
|
49
|
+
return [(name, mod) for _, _, name, mod in found]
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _parallel_lists(model, path: str, stack) -> list[str]:
|
|
53
|
+
"""Other lists as long as the stack beside it (XLM keeps attentions, norms and FFNs as parallel lists): such a model's
|
|
54
|
+
layers are not single modules, and splitting one of the lists would compute something else."""
|
|
55
|
+
import torch
|
|
56
|
+
parent_path, _, name = path.rpartition(".")
|
|
57
|
+
parent = model.get_submodule(parent_path) if parent_path else model
|
|
58
|
+
return [n for n, m in parent.named_children() if n != name and isinstance(m, torch.nn.ModuleList) and len(m) == len(stack)]
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def load_config(repo: str):
|
|
62
|
+
from transformers import AutoConfig
|
|
63
|
+
check_source(repo)
|
|
64
|
+
return AutoConfig.from_pretrained(repo)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def check_source(repo: str):
|
|
68
|
+
"""A model given as a folder must exist on this device too; say so instead of a Hugging Face "not found"."""
|
|
69
|
+
looks_local = os.path.isabs(repo) or repo.startswith((".", "~")) or "\\" in repo or repo.count("/") > 1
|
|
70
|
+
if looks_local and not os.path.isdir(os.path.expanduser(repo)):
|
|
71
|
+
raise FileNotFoundError(f"the model folder {repo} is not on this device ({os.uname().nodename if hasattr(os, 'uname') else 'here'}): "
|
|
72
|
+
"copy it to the same path on every device, or push it to the Hugging Face Hub and use its name")
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def skeleton(config, auto: str):
|
|
76
|
+
import torch
|
|
77
|
+
cls = auto_class(auto)
|
|
78
|
+
try:
|
|
79
|
+
cls._model_mapping[type(config)]
|
|
80
|
+
except Exception:
|
|
81
|
+
pass
|
|
82
|
+
with torch.device("meta"):
|
|
83
|
+
return cls.from_config(copy.deepcopy(config))
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _sub(config, sub):
|
|
87
|
+
return config if sub is None else getattr(config, sub)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _subconfigs(config) -> list:
|
|
91
|
+
names = [None]
|
|
92
|
+
for key in sorted(vars(config)):
|
|
93
|
+
try:
|
|
94
|
+
value = getattr(config, key, None)
|
|
95
|
+
except Exception:
|
|
96
|
+
value = vars(config).get(key)
|
|
97
|
+
if key.endswith("_config") and hasattr(value, "to_dict") and value is not config:
|
|
98
|
+
names.append(key)
|
|
99
|
+
return names
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def with_count(config, sub, attr: str, first: int, last: int):
|
|
103
|
+
"""A copy of `config` whose stack has blocks first..last-1 of the full model, with every per-block list sliced to match."""
|
|
104
|
+
return with_blocks(config, sub, attr, list(range(first, last)))
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def with_blocks(config, sub, attr: str, indices: list[int]):
|
|
108
|
+
"""A copy of `config` whose stack has only the given blocks of the full model, with every per-block list cut to match."""
|
|
109
|
+
data = config.to_dict()
|
|
110
|
+
target = data if sub is None else data[sub]
|
|
111
|
+
holder = _sub(config, sub)
|
|
112
|
+
n = getattr(holder, attr)
|
|
113
|
+
names = {attr}
|
|
114
|
+
for alias, real in getattr(holder, "attribute_map", {}).items():
|
|
115
|
+
if attr in (alias, real):
|
|
116
|
+
names.update((alias, real))
|
|
117
|
+
types = holder.__dict__.get("layer_types")
|
|
118
|
+
if types is not None and len(types) == n and "layer_types" not in target:
|
|
119
|
+
target["layer_types"] = list(types)
|
|
120
|
+
for key, value in list(target.items()):
|
|
121
|
+
if isinstance(value, list) and len(value) == n and key not in names:
|
|
122
|
+
target[key] = [value[i] for i in indices]
|
|
123
|
+
per_layer = target.get("per_layer_config")
|
|
124
|
+
if isinstance(per_layer, dict):
|
|
125
|
+
target["per_layer_config"] = {new: per_layer[k] for new, i in enumerate(indices) for k in (i, str(i)) if k in per_layer}
|
|
126
|
+
for key in ("out_features", "out_indices", "stage_names"):
|
|
127
|
+
target.pop(key, None)
|
|
128
|
+
for name in names:
|
|
129
|
+
if name in target:
|
|
130
|
+
target[name] = len(indices)
|
|
131
|
+
try:
|
|
132
|
+
return type(config).from_dict(data)
|
|
133
|
+
except Exception:
|
|
134
|
+
made = copy.deepcopy(config)
|
|
135
|
+
holder = _sub(made, sub)
|
|
136
|
+
for key, value in target.items():
|
|
137
|
+
if key in names or key == "per_layer_config" or (isinstance(value, list) and isinstance(getattr(holder, key, None), list)):
|
|
138
|
+
object.__setattr__(holder, key, value)
|
|
139
|
+
return made
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _signatures(holder, attr) -> list[str]:
|
|
143
|
+
"""For every block, the values of every per-block list in the config: blocks with the same signature are built alike."""
|
|
144
|
+
n = getattr(holder, attr)
|
|
145
|
+
lists = [v for v in holder.__dict__.values() if isinstance(v, list) and len(v) == n]
|
|
146
|
+
return [json.dumps([v[i] for v in lists], sort_keys=True, default=str) for i in range(n)]
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _representatives(config, sub, attr) -> list[int]:
|
|
150
|
+
"""One block of every kind (each distinct value of every per-block list), so modules built from those lists exist."""
|
|
151
|
+
holder = _sub(config, sub)
|
|
152
|
+
n = getattr(holder, attr)
|
|
153
|
+
picked = {0}
|
|
154
|
+
lists = [v for v in holder.__dict__.values() if isinstance(v, list) and len(v) == n]
|
|
155
|
+
for values in lists:
|
|
156
|
+
seen = {}
|
|
157
|
+
for i, v in enumerate(values):
|
|
158
|
+
seen.setdefault(json.dumps(v, sort_keys=True, default=str), i)
|
|
159
|
+
picked.update(seen.values())
|
|
160
|
+
return sorted(picked)
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
NOT_SPLITTABLE = {
|
|
164
|
+
"funnel": "it pools the sequence between groups of blocks",
|
|
165
|
+
"fsmt": "its split outputs differ slightly from the whole model's",
|
|
166
|
+
"diffusion_gemma": "its split outputs differ from the whole model's",
|
|
167
|
+
"nemotron_asr_streaming_encoder": "its split outputs differ from the whole model's",
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def layout(config, auto: str) -> dict:
|
|
172
|
+
"""Where the blocks are: the stack's module path, how many there are, and which config field sets that number."""
|
|
173
|
+
kind = str(getattr(config, "model_type", ""))
|
|
174
|
+
if kind in NOT_SPLITTABLE:
|
|
175
|
+
raise ValueError(f"layerpool cannot split {kind} models yet: {NOT_SPLITTABLE[kind]}")
|
|
176
|
+
model = skeleton(config, auto)
|
|
177
|
+
candidates = stack_candidates(model)
|
|
178
|
+
if not candidates:
|
|
179
|
+
raise ValueError(f"{type(model).__name__} has no stack of repeated blocks that layerpool could split (convolutional and "
|
|
180
|
+
"staged vision models, for example, are not built that way)")
|
|
181
|
+
tried = []
|
|
182
|
+
for path, stack in candidates:
|
|
183
|
+
n = len(stack)
|
|
184
|
+
beside = _parallel_lists(model, path, stack)
|
|
185
|
+
if beside:
|
|
186
|
+
tried.append(f"{path} has parallel lists beside it ({', '.join(beside)})")
|
|
187
|
+
continue
|
|
188
|
+
for sub in _subconfigs(config):
|
|
189
|
+
holder = _sub(config, sub)
|
|
190
|
+
for attr in STACK_COUNT_ATTRS:
|
|
191
|
+
if getattr(holder, attr, None) != n:
|
|
192
|
+
continue
|
|
193
|
+
try:
|
|
194
|
+
trial = skeleton(with_count(config, sub, attr, 0, 1), auto)
|
|
195
|
+
if len(trial.get_submodule(path)) == 1:
|
|
196
|
+
return {"auto": auto, "stack": path, "n": n, "sub": sub, "attr": attr, "block": type(stack[0]).__name__}
|
|
197
|
+
except Exception as e:
|
|
198
|
+
tried.append(f"{path} with {attr}=1: {type(e).__name__}: {str(e)[:120]}")
|
|
199
|
+
tried.append(f"{path}: no setting of the config sets its {n} blocks")
|
|
200
|
+
raise ValueError(f"layerpool cannot split {type(model).__name__}: " + "; ".join(tried[:4]))
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def block_index(key: str, stack: str, strict: bool = True) -> tuple[int, int, int] | None:
|
|
204
|
+
"""(block index, start, end of the index in the key) when `key` belongs to a block of `stack`."""
|
|
205
|
+
last = stack.split(".")[-1]
|
|
206
|
+
need = set(stack.split(".")) - {"model", last}
|
|
207
|
+
for found in re.finditer(rf"(?:^|\.){re.escape(last)}\.(\d+)\.", key):
|
|
208
|
+
before = set(key[:found.start()].split("."))
|
|
209
|
+
if strict and need - before:
|
|
210
|
+
continue
|
|
211
|
+
return int(found.group(1)), found.start(1), found.end(1)
|
|
212
|
+
return None
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def block_spans(keys, stack: str, n: int) -> dict[str, tuple[int, int, int]]:
|
|
216
|
+
"""Checkpoint keys of the stack's blocks: {key: (block index, start, end of the index in the key)}. Keys are grouped by what
|
|
217
|
+
comes before the block number, and a group must cover every block: another list with the same name (an audio encoder's own
|
|
218
|
+
"layers") is a different group. A checkpoint that stores the blocks under older names than the model's (ViT's
|
|
219
|
+
vit.encoder.layer.N for vit.layers.N) is matched by its numbered group alone; transformers renames such keys when it loads."""
|
|
220
|
+
keys = list(keys)
|
|
221
|
+
for mode in ("strict", "loose", "any"):
|
|
222
|
+
groups: dict[str, dict] = {}
|
|
223
|
+
for key in keys:
|
|
224
|
+
if mode == "any":
|
|
225
|
+
hits = [(int(m.group(1)), m.start(1), m.end(1)) for m in re.finditer(r"\.(\d+)\.", key)]
|
|
226
|
+
hit = hits[0] if hits else None
|
|
227
|
+
else:
|
|
228
|
+
hit = block_index(key, stack, mode == "strict")
|
|
229
|
+
if hit and hit[0] < n:
|
|
230
|
+
groups.setdefault(key[:hit[1]], {})[key] = hit
|
|
231
|
+
complete = {p: g for p, g in groups.items() if len({h[0] for h in g.values()}) == n}
|
|
232
|
+
if complete:
|
|
233
|
+
words = set(re.split(r"[._]", stack))
|
|
234
|
+
best = max(complete, key=lambda p: (len(words & set(re.split(r"[._]", p))), len(complete[p])))
|
|
235
|
+
return complete[best]
|
|
236
|
+
raise ValueError(f"the checkpoint has no weights for all {n} blocks of {stack}")
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def block_keys(keys, stack: str, n: int) -> dict[str, int]:
|
|
240
|
+
"""Checkpoint keys of the stack's blocks, with their block index."""
|
|
241
|
+
return {key: hit[0] for key, hit in block_spans(keys, stack, n).items()}
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def _revision(repo: str) -> str:
|
|
245
|
+
try:
|
|
246
|
+
return fetch.revision(repo)
|
|
247
|
+
except Exception:
|
|
248
|
+
return ""
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
CACHE_FORMAT = 1
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def _range_dir(repo: str, tag: str) -> str:
|
|
255
|
+
"""Where a cut-out part of a model is cached: one folder per checkpoint revision, part, cache layout and transformers
|
|
256
|
+
major.minor (the version writes the config the part loads with)."""
|
|
257
|
+
import transformers
|
|
258
|
+
source = os.path.abspath(repo) if os.path.isdir(repo) else repo
|
|
259
|
+
made_by = ".".join(transformers.__version__.split(".")[:2])
|
|
260
|
+
key = hashlib.sha1(f"{source}@{_revision(repo)}|{tag}|v{CACHE_FORMAT}|tf{made_by}".encode()).hexdigest()[:16]
|
|
261
|
+
if os.path.isdir(repo) and os.path.basename(source.rstrip("/")).startswith(("layerpool_check_", "layerpool_mlx_check_")):
|
|
262
|
+
return os.path.join(source, ".parts", key)
|
|
263
|
+
return os.path.join(RANGE_CACHE, f"{os.path.basename(source.rstrip('/'))}_{key}")
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
UNUSED_AFTER_S = 600
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
def _prune_ranges(repo: str, keep: str):
|
|
270
|
+
"""A device whose layers changed (a rebalance) no longer needs the folders of its earlier layer ranges of this model: they go
|
|
271
|
+
once nothing has used them for ten minutes (another device on this machine may still be loading one). They are rebuilt from
|
|
272
|
+
the downloaded weights if needed again."""
|
|
273
|
+
source = os.path.abspath(repo) if os.path.isdir(repo) else repo
|
|
274
|
+
marker = {"repo": source, "kind": "blocks"}
|
|
275
|
+
os.makedirs(keep, exist_ok=True)
|
|
276
|
+
with open(os.path.join(keep, "layerpool_part.json"), "w", encoding="utf-8") as f:
|
|
277
|
+
json.dump(marker, f)
|
|
278
|
+
now = time.time()
|
|
279
|
+
for name in os.listdir(RANGE_CACHE):
|
|
280
|
+
folder = os.path.join(RANGE_CACHE, name)
|
|
281
|
+
if folder == keep:
|
|
282
|
+
continue
|
|
283
|
+
try:
|
|
284
|
+
with open(os.path.join(folder, "layerpool_part.json"), encoding="utf-8") as f:
|
|
285
|
+
theirs = json.load(f)
|
|
286
|
+
if theirs == marker and now - os.path.getmtime(os.path.join(folder, "layerpool_part.json")) > UNUSED_AFTER_S:
|
|
287
|
+
shutil.rmtree(folder, ignore_errors=True)
|
|
288
|
+
except (OSError, ValueError):
|
|
289
|
+
continue
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def _write_checkpoint(out: str, config, files: dict[str, list[str]], rename):
|
|
293
|
+
"""A model folder with these tensors, renamed, copied byte for byte (never all in memory at once)."""
|
|
294
|
+
os.makedirs(out, exist_ok=True)
|
|
295
|
+
config.save_pretrained(out)
|
|
296
|
+
fetch.copy_tensors(files, rename, os.path.join(out, "model.safetensors"))
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
def _no_quant(config):
|
|
300
|
+
data = config.to_dict()
|
|
301
|
+
data.pop("quantization_config", None)
|
|
302
|
+
return type(config).from_dict(data)
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
def _overridden(config, overrides: dict | None):
|
|
306
|
+
"""A copy of the config with the run's settings (such as num_labels) applied."""
|
|
307
|
+
config = copy.deepcopy(config)
|
|
308
|
+
for key, value in (overrides or {}).items():
|
|
309
|
+
setattr(config, key, value)
|
|
310
|
+
return config
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
def _shrink_vocab(config):
|
|
314
|
+
"""A part with only blocks needs no real vocabulary; a small one saves memory. Configs that check the vocabulary against
|
|
315
|
+
another setting keep theirs."""
|
|
316
|
+
trial = copy.deepcopy(config)
|
|
317
|
+
try:
|
|
318
|
+
_small_vocab(trial)
|
|
319
|
+
trial.to_dict()
|
|
320
|
+
type(trial).from_dict(trial.to_dict())
|
|
321
|
+
except Exception:
|
|
322
|
+
return config
|
|
323
|
+
return _small_vocab(config)
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
def _small_vocab(config):
|
|
327
|
+
text = config.get_text_config()
|
|
328
|
+
for key in ("vocab_size",):
|
|
329
|
+
if getattr(text, key, None):
|
|
330
|
+
setattr(text, key, 16)
|
|
331
|
+
for key in ("pad_token_id", "bos_token_id", "eos_token_id"):
|
|
332
|
+
if getattr(text, key, None) is not None:
|
|
333
|
+
setattr(text, key, 0)
|
|
334
|
+
return config
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
def _load(auto: str, path: str, dtype, device, quantized: bool, overrides: dict | None = None):
|
|
338
|
+
from transformers.utils import logging
|
|
339
|
+
direct = quantized or not str(device).startswith("mps")
|
|
340
|
+
kwargs = {**(overrides or {}), "dtype": dtype, "output_loading_info": True}
|
|
341
|
+
if direct:
|
|
342
|
+
kwargs["device_map"] = {"": str(device)}
|
|
343
|
+
level = logging.get_verbosity()
|
|
344
|
+
logging.set_verbosity_error()
|
|
345
|
+
try:
|
|
346
|
+
model, info = auto_class(auto).from_pretrained(path, **kwargs)
|
|
347
|
+
finally:
|
|
348
|
+
logging.set_verbosity(level)
|
|
349
|
+
if not direct:
|
|
350
|
+
model = model.to(device)
|
|
351
|
+
for p in model.parameters():
|
|
352
|
+
p.requires_grad_(False)
|
|
353
|
+
return model.eval(), info
|
|
354
|
+
|
|
355
|
+
|
|
356
|
+
def random_weights(shapes: dict[str, tuple], config) -> dict:
|
|
357
|
+
"""Initial values for training from scratch that depend only on each weight's full-model name, so every split of the model
|
|
358
|
+
starts from the same weights, on PyTorch and on MLX (backends.common.random_weights makes them for both)."""
|
|
359
|
+
import torch
|
|
360
|
+
text = config.get_text_config()
|
|
361
|
+
made = common.random_weights(shapes, {"initializer_range": getattr(text, "initializer_range", None), "model_type": getattr(text, "model_type", "")})
|
|
362
|
+
return {name: torch.from_numpy(value) for name, value in made.items()}
|
|
363
|
+
|
|
364
|
+
|
|
365
|
+
def load_blocks(repo: str, lay: dict, first: int, last: int, device, dtype, quantized: bool = False, random_init: bool = False, log=None,
|
|
366
|
+
overrides: dict | None = None, in_place: bool = True):
|
|
367
|
+
"""Blocks first..last-1 of the model, built by transformers from only their own weights."""
|
|
368
|
+
import torch
|
|
369
|
+
stored = load_config(repo)
|
|
370
|
+
if not quantized:
|
|
371
|
+
stored = _no_quant(stored)
|
|
372
|
+
config = _overridden(stored, overrides)
|
|
373
|
+
part = _shrink_vocab(with_count(config, lay["sub"], lay["attr"], first, last))
|
|
374
|
+
if random_init:
|
|
375
|
+
model = auto_class(lay["auto"]).from_config(part).to(dtype)
|
|
376
|
+
stack = model.get_submodule(lay["stack"])
|
|
377
|
+
shapes = {f"{lay['stack']}.{first + j}.{n}": tuple(p.shape) for j, block in enumerate(stack) for n, p in block.named_parameters()}
|
|
378
|
+
made = random_weights(shapes, config)
|
|
379
|
+
with torch.no_grad():
|
|
380
|
+
for j, block in enumerate(stack):
|
|
381
|
+
for n, p in block.named_parameters():
|
|
382
|
+
p.copy_(made[f"{lay['stack']}.{first + j}.{n}"].to(p.dtype))
|
|
383
|
+
model = model.to(device).eval()
|
|
384
|
+
for p in model.parameters():
|
|
385
|
+
p.requires_grad_(False)
|
|
386
|
+
else:
|
|
387
|
+
out = _range_dir(repo, f"blocks {first}-{last} q{int(quantized)}")
|
|
388
|
+
_prune_ranges(repo, out)
|
|
389
|
+
if not os.path.exists(os.path.join(out, "model.safetensors")):
|
|
390
|
+
spans = {k: h for k, h in block_spans(fetch.weight_map(repo), lay["stack"], lay["n"]).items() if first <= h[0] < last}
|
|
391
|
+
renumbered = lambda k: k[:spans[k][1]] + str(spans[k][0] - first) + k[spans[k][2]:]
|
|
392
|
+
_write_checkpoint(out, _shrink_vocab(with_count(stored, lay["sub"], lay["attr"], first, last)), fetch.fetch(repo, list(spans), log), renumbered)
|
|
393
|
+
model, info = _load(lay["auto"], out, dtype, device, quantized, overrides)
|
|
394
|
+
prefix = lay["stack"] + "."
|
|
395
|
+
missing = {k for k in info.get("missing_keys", []) if k.startswith(prefix)}
|
|
396
|
+
blocks = list(model.get_submodule(lay["stack"]))
|
|
397
|
+
if not quantized and in_place:
|
|
398
|
+
saved = None if random_init else os.path.join(out, "model.safetensors")
|
|
399
|
+
blocks = _as_in_full_model(blocks, config, lay, first, device, missing if not random_init else set(), repo, saved, dtype)
|
|
400
|
+
elif not random_init and missing:
|
|
401
|
+
raise RuntimeError(f"could not load blocks {first}-{last - 1} of {repo}: missing {sorted(missing)[:5]}")
|
|
402
|
+
for j, block in enumerate(blocks):
|
|
403
|
+
for mod in block.modules():
|
|
404
|
+
if isinstance(getattr(mod, "layer_idx", None), int):
|
|
405
|
+
mod.layer_idx = first + j
|
|
406
|
+
return blocks
|
|
407
|
+
|
|
408
|
+
|
|
409
|
+
def _as_in_full_model(loaded: list, config, lay: dict, first: int, device, missing: set, repo: str, saved: str | None = None,
|
|
410
|
+
dtype=None) -> list:
|
|
411
|
+
"""The blocks as the full model builds them, holding the loaded weights. A model built with fewer blocks numbers them from 0
|
|
412
|
+
and sees a smaller total, and some blocks depend on both (T5's position bias lives in block 0; ModernBERT, DiffLlama and
|
|
413
|
+
MiniCPM3 compute constants, layer kinds or rotary tables from the block index or the block count). So the full model is built
|
|
414
|
+
with empty weights (no memory) but real buffers, and each block takes the loaded weights: the tensors move over, not copies."""
|
|
415
|
+
import torch
|
|
416
|
+
from accelerate import init_empty_weights
|
|
417
|
+
with init_empty_weights(include_buffers=False):
|
|
418
|
+
full = auto_class(lay["auto"]).from_config(copy.deepcopy(config))
|
|
419
|
+
stack = full.get_submodule(lay["stack"])
|
|
420
|
+
prefix = lay["stack"] + "."
|
|
421
|
+
out = []
|
|
422
|
+
for j, source in enumerate(loaded):
|
|
423
|
+
i = first + j
|
|
424
|
+
target = stack[i]
|
|
425
|
+
have = dict(source.named_parameters())
|
|
426
|
+
absent = {k[len(f"{prefix}{j}."):] for k in missing if k.startswith(f"{prefix}{j}.")}
|
|
427
|
+
wanted = dict(target.named_parameters())
|
|
428
|
+
lost = [n for n in wanted if n not in have or n in absent or have[n].shape != wanted[n].shape]
|
|
429
|
+
if lost and saved:
|
|
430
|
+
from safetensors import safe_open
|
|
431
|
+
with safe_open(saved, framework="pt") as f:
|
|
432
|
+
names = set(f.keys())
|
|
433
|
+
for n in list(lost):
|
|
434
|
+
key = f"{prefix}{j}.{n}"
|
|
435
|
+
if key in names and tuple(f.get_slice(key).get_shape()) == tuple(wanted[n].shape):
|
|
436
|
+
have[n] = f.get_tensor(key).to(device, dtype or wanted[n].dtype)
|
|
437
|
+
lost.remove(n)
|
|
438
|
+
if lost:
|
|
439
|
+
raise RuntimeError(f"could not load block {i} of {repo}: no weights for {lost[:5]}")
|
|
440
|
+
stored = set(source.state_dict().keys())
|
|
441
|
+
theirs = dict(source.named_buffers())
|
|
442
|
+
for name in wanted:
|
|
443
|
+
owner, _, leaf = name.rpartition(".")
|
|
444
|
+
(target.get_submodule(owner) if owner else target)._parameters[leaf] = torch.nn.Parameter(have[name].detach(), requires_grad=False)
|
|
445
|
+
for name, buf in list(target.named_buffers()):
|
|
446
|
+
owner, _, leaf = name.rpartition(".")
|
|
447
|
+
value = theirs[name] if name in stored and name in theirs else buf.to(device)
|
|
448
|
+
(target.get_submodule(owner) if owner else target)._buffers[leaf] = value
|
|
449
|
+
out.append(target.eval())
|
|
450
|
+
loaded[j] = None
|
|
451
|
+
return out
|
|
452
|
+
|
|
453
|
+
|
|
454
|
+
def _owner_config(model, stack: str):
|
|
455
|
+
"""The config of the nearest module above the stack that has one (DistilBERT's `transformer` has none)."""
|
|
456
|
+
parts = stack.split(".")[:-1]
|
|
457
|
+
while parts:
|
|
458
|
+
config = getattr(model.get_submodule(".".join(parts)), "config", None)
|
|
459
|
+
if config is not None:
|
|
460
|
+
return config
|
|
461
|
+
parts.pop()
|
|
462
|
+
return model.config
|
|
463
|
+
|
|
464
|
+
|
|
465
|
+
def load_ends(repo: str, lay: dict, dtype, device="cpu", random_init: bool = False, log=None, overrides: dict | None = None):
|
|
466
|
+
"""The model without its blocks: what runs on the machine with the training code. overrides are config settings such as
|
|
467
|
+
num_labels. Weights the checkpoint does not have (a new classification head) start as transformers initialises them, and
|
|
468
|
+
model._layerpool_new names them."""
|
|
469
|
+
import torch
|
|
470
|
+
stored = _no_quant(load_config(repo))
|
|
471
|
+
config = _overridden(stored, overrides)
|
|
472
|
+
new = []
|
|
473
|
+
picked = _representatives(config, lay["sub"], lay["attr"])
|
|
474
|
+
part = with_blocks(config, lay["sub"], lay["attr"], picked)
|
|
475
|
+
if random_init:
|
|
476
|
+
model = auto_class(lay["auto"]).from_config(part).to(dtype)
|
|
477
|
+
shapes = {n: tuple(p.shape) for n, p in model.named_parameters() if not n.startswith(lay["stack"] + ".")}
|
|
478
|
+
made = random_weights(shapes, config)
|
|
479
|
+
with torch.no_grad():
|
|
480
|
+
for n, p in model.named_parameters():
|
|
481
|
+
if n in made:
|
|
482
|
+
p.copy_(made[n].to(p.dtype))
|
|
483
|
+
model = model.to(device).eval()
|
|
484
|
+
for p in model.parameters():
|
|
485
|
+
p.requires_grad_(False)
|
|
486
|
+
else:
|
|
487
|
+
out = _range_dir(repo, f"ends {picked}")
|
|
488
|
+
if not os.path.exists(os.path.join(out, "model.safetensors")):
|
|
489
|
+
stack_keys = block_keys(fetch.weight_map(repo), lay["stack"], lay["n"])
|
|
490
|
+
wanted = [k for k in fetch.weight_map(repo) if k not in stack_keys and not k.endswith((".absmax", ".quant_map", ".quant_state", ".nested_absmax",
|
|
491
|
+
".nested_quant_map")) and "quant_state" not in k]
|
|
492
|
+
_write_checkpoint(out, with_blocks(stored, lay["sub"], lay["attr"], picked), fetch.fetch(repo, wanted, log), lambda k: k)
|
|
493
|
+
model, info = _load(lay["auto"], out, dtype, device, False, overrides)
|
|
494
|
+
prefix = lay["stack"] + "."
|
|
495
|
+
names = {n for n, _ in model.named_parameters()}
|
|
496
|
+
new = sorted(k for k in info.get("missing_keys", []) if not k.startswith(prefix) and k in names)
|
|
497
|
+
base = getattr(model, "base_model_prefix", "")
|
|
498
|
+
inside = base + "." if base and hasattr(model, base) else ""
|
|
499
|
+
lost = [k for k in new if k.startswith(inside) and ".pooler." not in f".{k}"]
|
|
500
|
+
if lost:
|
|
501
|
+
raise RuntimeError(f"could not load the parts of {repo} around its blocks: missing {lost[:5]}")
|
|
502
|
+
if new and log:
|
|
503
|
+
log(f"{repo} has no weights for {', '.join(new)}: they start new and are trained")
|
|
504
|
+
holder = _owner_config(model, lay["stack"])
|
|
505
|
+
full = _sub(config, lay["sub"])
|
|
506
|
+
target = holder if getattr(holder, lay["attr"], None) is not None else _sub(model.config, lay["sub"])
|
|
507
|
+
amap = getattr(target, "attribute_map", {})
|
|
508
|
+
for name in {lay["attr"], amap.get(lay["attr"], lay["attr"])}:
|
|
509
|
+
object.__setattr__(target, name, lay["n"])
|
|
510
|
+
for name in STACK_COUNT_ATTRS:
|
|
511
|
+
if name in vars(target) and vars(target)[name] == len(picked) and len(picked) != lay["n"]:
|
|
512
|
+
object.__setattr__(target, name, lay["n"])
|
|
513
|
+
for key, value in full.__dict__.items():
|
|
514
|
+
if isinstance(value, list) and len(value) == lay["n"]:
|
|
515
|
+
object.__setattr__(target, key, list(value))
|
|
516
|
+
signature = _signatures(full, lay["attr"])
|
|
517
|
+
model.__dict__["_layerpool_kinds"] = {i: picked[[signature[p] for p in picked].index(signature[i])] for i in range(lay["n"])}
|
|
518
|
+
model.__dict__["_layerpool_picked"] = picked
|
|
519
|
+
model.__dict__["_layerpool_new"] = new
|
|
520
|
+
for c in {id(x): x for x in (model.config, model.config.get_text_config(), target)}.values():
|
|
521
|
+
if hasattr(c, "use_cache"):
|
|
522
|
+
object.__setattr__(c, "use_cache", False)
|
|
523
|
+
_no_layerdrop(model, log)
|
|
524
|
+
_generate_without_cache(model)
|
|
525
|
+
_lean_loss(model)
|
|
526
|
+
configs = [model.config] + [v for v in vars(model.config).values() if hasattr(v, "to_dict") and hasattr(v, "model_type")]
|
|
527
|
+
if any(getattr(c, "use_weighted_layer_sum", False) for c in configs):
|
|
528
|
+
raise ValueError("use_weighted_layer_sum needs every block's output on this machine, and the blocks run on the devices; "
|
|
529
|
+
"turn it off (use_weighted_layer_sum=False)")
|
|
530
|
+
if any(getattr(c, "output_hidden_states", False) or getattr(c, "output_attentions", False) for c in configs):
|
|
531
|
+
raise ValueError(NO_INNER_OUTPUTS)
|
|
532
|
+
return model
|
|
533
|
+
|
|
534
|
+
|
|
535
|
+
NO_INNER_OUTPUTS = ("layerpool cannot give the outputs or attention weights of each block (output_hidden_states, "
|
|
536
|
+
"output_attentions): the blocks run on the devices, which send back only the last block's output")
|
|
537
|
+
|
|
538
|
+
|
|
539
|
+
def _lean_loss(model):
|
|
540
|
+
"""The default causal LM loss, computed in pieces (losses.lean_causal_loss): the machine with the training code holds the
|
|
541
|
+
output layer, and a big vocabulary's logits in float32 take gigabytes there."""
|
|
542
|
+
try:
|
|
543
|
+
from transformers.loss.loss_utils import LOSS_MAPPING
|
|
544
|
+
current = model.loss_function
|
|
545
|
+
except Exception:
|
|
546
|
+
return
|
|
547
|
+
if current is LOSS_MAPPING.get("ForCausalLM"):
|
|
548
|
+
from .losses import lean_causal_loss
|
|
549
|
+
try:
|
|
550
|
+
model.loss_function = lean_causal_loss(current)
|
|
551
|
+
except AttributeError:
|
|
552
|
+
pass
|
|
553
|
+
|
|
554
|
+
|
|
555
|
+
def _generate_without_cache(model):
|
|
556
|
+
"""The blocks run on the devices and keep no key/value cache, so generate() runs the whole sequence at each new token
|
|
557
|
+
instead of feeding only the last one to a cache that stays empty."""
|
|
558
|
+
if getattr(model, "generation_config", None) is not None:
|
|
559
|
+
model.generation_config.use_cache = False
|
|
560
|
+
generate = getattr(model, "generate", None)
|
|
561
|
+
if callable(generate):
|
|
562
|
+
def without_cache(*args, **kwargs):
|
|
563
|
+
kwargs["use_cache"] = False
|
|
564
|
+
return generate(*args, **kwargs)
|
|
565
|
+
model.generate = without_cache
|
|
566
|
+
|
|
567
|
+
|
|
568
|
+
def _no_layerdrop(model, log=None):
|
|
569
|
+
"""LayerDrop (wav2vec2, HuBERT, ...) skips random blocks while training; the devices run every block of their range on every
|
|
570
|
+
step, so it is turned off, in the configs and in the modules that copied it."""
|
|
571
|
+
dropped = set()
|
|
572
|
+
configs = [model.config] + [v for v in vars(model.config).values() if hasattr(v, "to_dict") and hasattr(v, "model_type")]
|
|
573
|
+
for c in configs:
|
|
574
|
+
for key, value in list(vars(c).items()):
|
|
575
|
+
if "layerdrop" in key and isinstance(value, (int, float)) and value:
|
|
576
|
+
object.__setattr__(c, key, 0.0)
|
|
577
|
+
dropped.add(key)
|
|
578
|
+
for module in model.modules():
|
|
579
|
+
for key, value in list(vars(module).items()):
|
|
580
|
+
if "layerdrop" in key and isinstance(value, (int, float)) and not isinstance(value, bool) and value:
|
|
581
|
+
setattr(module, key, 0.0)
|
|
582
|
+
dropped.add(key)
|
|
583
|
+
if dropped and log:
|
|
584
|
+
log(f"LayerDrop ({', '.join(sorted(dropped))}) is off: every block runs on every step")
|
|
585
|
+
|
|
586
|
+
|
|
587
|
+
def is_linear(module) -> bool:
|
|
588
|
+
"""A layer LoRA can train: torch's Linear (not subclasses that return something else, such as some MoE routers) and
|
|
589
|
+
transformers' Conv1D, GPT-2's linear layer with its weight stored the other way round."""
|
|
590
|
+
import torch
|
|
591
|
+
if isinstance(module, torch.nn.Linear):
|
|
592
|
+
return type(module).forward is torch.nn.Linear.forward or type(module).__name__ in ("Linear4bit", "Linear8bitLt")
|
|
593
|
+
return type(module).__name__ == "Conv1D" and hasattr(module, "nf") and hasattr(module, "nx")
|
|
594
|
+
|
|
595
|
+
|
|
596
|
+
def linear_size(module) -> tuple[int, int]:
|
|
597
|
+
"""(inputs, outputs) of a layer is_linear accepts."""
|
|
598
|
+
if hasattr(module, "in_features"):
|
|
599
|
+
return module.in_features, module.out_features
|
|
600
|
+
return module.nx, module.nf
|
|
601
|
+
|
|
602
|
+
|
|
603
|
+
def lora_targets(block) -> list[str]:
|
|
604
|
+
"""Every linear layer inside a block, by name (PEFT's "all-linear")."""
|
|
605
|
+
return sorted(name for name, mod in block.named_modules() if name and is_linear(mod))
|
|
606
|
+
|
|
607
|
+
|
|
608
|
+
def targeted(name: str, targets: list[str] | None) -> bool:
|
|
609
|
+
"""Whether LoRA goes on this linear layer: every one without target_modules, else the ones named like PEFT's target_modules
|
|
610
|
+
(q_proj matches self_attn.q_proj)."""
|
|
611
|
+
return not targets or any(name == t or name.endswith("." + t) for t in targets)
|
|
612
|
+
|
|
613
|
+
|
|
614
|
+
def lora_init(block_index: int, module_index: int, fan_in: int, fan_out: int, rank: int) -> tuple[np.ndarray, np.ndarray]:
|
|
615
|
+
rng = np.random.default_rng(block_index * 1000 + module_index)
|
|
616
|
+
return rng.normal(0, 1 / np.sqrt(fan_in), (rank, fan_in)).astype(np.float32), np.zeros((fan_out, rank), np.float32)
|
|
617
|
+
|
|
618
|
+
|
|
619
|
+
def _dtype_name(t) -> str:
|
|
620
|
+
return str(t.dtype).replace("torch.", "")
|
|
621
|
+
|
|
622
|
+
|
|
623
|
+
def pack_args(per_block: dict, grads: bool = True, carried: dict | None = None) -> tuple[dict, dict]:
|
|
624
|
+
"""The arguments the model passed to each block, as JSON plus arrays. Tensors shared by several blocks are stored once.
|
|
625
|
+
Masks are sent as bits. Tensors that need gradients (encoder states, image features) are marked so devices return their
|
|
626
|
+
gradients."""
|
|
627
|
+
import torch
|
|
628
|
+
arrays, seen, sides, infos = {}, {}, [], {}
|
|
629
|
+
|
|
630
|
+
def tensor(t):
|
|
631
|
+
if id(t) in seen:
|
|
632
|
+
return {"__t__": seen[id(t)]}
|
|
633
|
+
k = len(seen)
|
|
634
|
+
seen[id(t)] = k
|
|
635
|
+
entry = {"__t__": k}
|
|
636
|
+
name = f"t{k}"
|
|
637
|
+
x = t.detach()
|
|
638
|
+
info = {"dtype": _dtype_name(x), "shape": list(x.shape), "grad": bool(grads and t.requires_grad)}
|
|
639
|
+
if info["grad"]:
|
|
640
|
+
sides.append(t)
|
|
641
|
+
info["side"] = len(sides) - 1
|
|
642
|
+
if x.dtype == torch.bool:
|
|
643
|
+
arrays[name] = np.packbits(x.cpu().numpy().reshape(-1))
|
|
644
|
+
info["bits"] = True
|
|
645
|
+
elif x.is_floating_point() and x.numel() > 1024 and not info["grad"] and bool(((x == 0) | (x <= torch.finfo(x.dtype).min / 2)).all()):
|
|
646
|
+
arrays[name] = np.packbits((x == 0).cpu().numpy().reshape(-1))
|
|
647
|
+
info["bits"], info["additive"] = True, True
|
|
648
|
+
else:
|
|
649
|
+
arrays[name] = (x.float() if x.dtype == torch.bfloat16 else x).cpu().numpy()
|
|
650
|
+
infos[str(k)] = info
|
|
651
|
+
return entry
|
|
652
|
+
|
|
653
|
+
carried = carried or {}
|
|
654
|
+
uses: dict[tuple, int] = {}
|
|
655
|
+
|
|
656
|
+
def walk(v, block=None):
|
|
657
|
+
if torch.is_tensor(v):
|
|
658
|
+
if id(v) in carried:
|
|
659
|
+
source = carried[id(v)]
|
|
660
|
+
uses[source] = max(uses.get(source, -1), block)
|
|
661
|
+
return {"__carry__": list(source)}
|
|
662
|
+
return tensor(v)
|
|
663
|
+
if isinstance(v, tuple):
|
|
664
|
+
return {"__tuple__": [walk(x, block) for x in v]}
|
|
665
|
+
if isinstance(v, list):
|
|
666
|
+
return {"__list__": [walk(x, block) for x in v]}
|
|
667
|
+
if isinstance(v, dict):
|
|
668
|
+
return {"__dict__": {str(k): walk(x, block) for k, x in v.items()}}
|
|
669
|
+
if v is None or isinstance(v, (bool, int, float, str)):
|
|
670
|
+
return v
|
|
671
|
+
if type(v).__name__.endswith("Cache"):
|
|
672
|
+
return None
|
|
673
|
+
raise TypeError(f"layerpool cannot send a {type(v).__name__} to the devices (a block argument)")
|
|
674
|
+
meta = {str(i): [walk(list(a), i), walk(dict(kw), i)] for i, (a, kw) in per_block.items()}
|
|
675
|
+
out = {"blocks": meta, "tensors": infos, "sides": len(sides)}
|
|
676
|
+
if uses:
|
|
677
|
+
out["carry"] = [[i, k, last] for (i, k), last in sorted(uses.items())]
|
|
678
|
+
return out, arrays, sides
|
|
679
|
+
|
|
680
|
+
|
|
681
|
+
def unpack_args(meta: dict, arrays: dict, device, dtype, wanted=None) -> tuple[dict, dict]:
|
|
682
|
+
"""Back to tensors on this device. Returns {block: (args, kwargs)} and {side index: leaf tensor needing a gradient}."""
|
|
683
|
+
import torch
|
|
684
|
+
made, leaves = {}, {}
|
|
685
|
+
|
|
686
|
+
def tensor(entry):
|
|
687
|
+
k = entry["__t__"]
|
|
688
|
+
if k in made:
|
|
689
|
+
return made[k]
|
|
690
|
+
info = meta["tensors"][str(k)]
|
|
691
|
+
raw = arrays[f"t{k}"]
|
|
692
|
+
shape = tuple(info["shape"])
|
|
693
|
+
target = getattr(torch, info["dtype"])
|
|
694
|
+
if info.get("bits"):
|
|
695
|
+
flat = np.unpackbits(raw)[: int(np.prod(shape))].astype(bool).reshape(shape)
|
|
696
|
+
if info.get("additive"):
|
|
697
|
+
out_dtype = dtype if target.is_floating_point else target
|
|
698
|
+
t = torch.zeros(shape, dtype=out_dtype).masked_fill(~torch.from_numpy(flat), torch.finfo(out_dtype).min)
|
|
699
|
+
else:
|
|
700
|
+
t = torch.from_numpy(flat)
|
|
701
|
+
else:
|
|
702
|
+
t = torch.from_numpy(np.asarray(raw)).to(target)
|
|
703
|
+
if t.is_floating_point():
|
|
704
|
+
t = t.to(dtype)
|
|
705
|
+
t = t.to(device)
|
|
706
|
+
if info.get("grad"):
|
|
707
|
+
t = t.requires_grad_()
|
|
708
|
+
leaves[info["side"]] = t
|
|
709
|
+
made[k] = t
|
|
710
|
+
return t
|
|
711
|
+
|
|
712
|
+
def walk(v):
|
|
713
|
+
if isinstance(v, dict):
|
|
714
|
+
if "__t__" in v:
|
|
715
|
+
return tensor(v)
|
|
716
|
+
if "__tuple__" in v:
|
|
717
|
+
return tuple(walk(x) for x in v["__tuple__"])
|
|
718
|
+
if "__list__" in v:
|
|
719
|
+
return [walk(x) for x in v["__list__"]]
|
|
720
|
+
if "__dict__" in v:
|
|
721
|
+
return {k: walk(x) for k, x in v["__dict__"].items()}
|
|
722
|
+
return v
|
|
723
|
+
out = {}
|
|
724
|
+
for key, (a, kw) in meta["blocks"].items():
|
|
725
|
+
if wanted is not None and int(key) not in wanted:
|
|
726
|
+
continue
|
|
727
|
+
out[int(key)] = (tuple(walk(a)), walk(kw))
|
|
728
|
+
return out, leaves
|
|
729
|
+
|
|
730
|
+
|
|
731
|
+
def mlx_masks(meta: dict | None, arrays: dict, wanted) -> dict | None:
|
|
732
|
+
"""Where each token may look in each wanted block, {block: (rows, 1, tokens, tokens) bool array}, or which tokens are real
|
|
733
|
+
((rows, tokens), what linear-attention blocks get), from the masks the model gave its blocks; None when it gave none, so the
|
|
734
|
+
blocks are plainly causal. MLX blocks take this instead of the torch arguments."""
|
|
735
|
+
if not meta or not meta.get("blocks"):
|
|
736
|
+
return None
|
|
737
|
+
import torch
|
|
738
|
+
blocks = {}
|
|
739
|
+
for key, (_, kw) in meta["blocks"].items():
|
|
740
|
+
inner = kw.get("__dict__", kw) if isinstance(kw, dict) else {}
|
|
741
|
+
if isinstance(inner, dict):
|
|
742
|
+
kept = {k: inner[k] for k in ("attention_mask", "position_ids") if isinstance(inner.get(k), dict)}
|
|
743
|
+
if kept:
|
|
744
|
+
blocks[key] = ([], {"__dict__": kept})
|
|
745
|
+
if not blocks:
|
|
746
|
+
return None
|
|
747
|
+
got, _ = unpack_args({**meta, "blocks": blocks}, arrays, "cpu", torch.float32, wanted)
|
|
748
|
+
out, made = {}, {}
|
|
749
|
+
for i, (_, kw) in got.items():
|
|
750
|
+
positions = kw.get("position_ids")
|
|
751
|
+
if torch.is_tensor(positions) and positions.dim() >= 1:
|
|
752
|
+
plain = torch.arange(positions.shape[-1]).expand_as(positions)
|
|
753
|
+
if not torch.equal(positions.long(), plain):
|
|
754
|
+
raise ValueError("MLX blocks number the tokens of each row 0, 1, 2, ... themselves, and this batch gives other "
|
|
755
|
+
"positions (several sequences packed into one row?); train it without packing, or start the Mac "
|
|
756
|
+
"with --backend torch")
|
|
757
|
+
m = kw.get("attention_mask")
|
|
758
|
+
if not torch.is_tensor(m):
|
|
759
|
+
continue
|
|
760
|
+
if id(m) not in made:
|
|
761
|
+
if m.dim() == 2:
|
|
762
|
+
attend = m if m.dtype == torch.bool else m != 0
|
|
763
|
+
else:
|
|
764
|
+
attend = m if m.dtype == torch.bool else (m > m.min() / 2 if m.min() < 0 else torch.ones_like(m, dtype=torch.bool))
|
|
765
|
+
made[id(m)] = attend.detach().numpy()
|
|
766
|
+
out[i] = made[id(m)]
|
|
767
|
+
return out or None
|
|
768
|
+
|
|
769
|
+
|
|
770
|
+
def _with_carried(v, carry: dict):
|
|
771
|
+
"""Block arguments with each reference to an earlier block's output replaced by that output."""
|
|
772
|
+
if isinstance(v, dict):
|
|
773
|
+
if "__carry__" in v:
|
|
774
|
+
return carry[tuple(v["__carry__"])]
|
|
775
|
+
return {k: _with_carried(x, carry) for k, x in v.items()}
|
|
776
|
+
if isinstance(v, tuple):
|
|
777
|
+
return tuple(_with_carried(x, carry) for x in v)
|
|
778
|
+
if isinstance(v, list):
|
|
779
|
+
return [_with_carried(x, carry) for x in v]
|
|
780
|
+
return v
|
|
781
|
+
|
|
782
|
+
|
|
783
|
+
def first_tensor(out):
|
|
784
|
+
return out[0] if isinstance(out, (tuple, list)) else out
|
|
785
|
+
|
|
786
|
+
|
|
787
|
+
def _attach_lora(base, A, B, scale: float, core):
|
|
788
|
+
"""LoRA on a linear layer without replacing it: a forward hook adds scale * B(A x) to its output, so the layer keeps its
|
|
789
|
+
class and attributes for the model code around it."""
|
|
790
|
+
def hook(module, inputs, output):
|
|
791
|
+
if not core.adapter or not hasattr(output, "dtype"):
|
|
792
|
+
return output
|
|
793
|
+
x = inputs[0]
|
|
794
|
+
return output + (scale * ((x.float() @ A.T) @ B.T)).to(output.dtype)
|
|
795
|
+
handle = base.register_forward_hook(hook)
|
|
796
|
+
handles = base.__dict__.setdefault("_layerpool_lora", [])
|
|
797
|
+
handles.append(handle)
|
|
798
|
+
|
|
799
|
+
|
|
800
|
+
def unwrap_lora(blocks):
|
|
801
|
+
"""The blocks without the LoRA of an earlier run, to put new ones on them."""
|
|
802
|
+
for block in blocks:
|
|
803
|
+
for mod in block.modules():
|
|
804
|
+
for handle in mod.__dict__.pop("_layerpool_lora", []):
|
|
805
|
+
handle.remove()
|
|
806
|
+
return blocks
|
|
807
|
+
|
|
808
|
+
|
|
809
|
+
class BlockCore:
|
|
810
|
+
"""A slice of the stack on one torch device: forward, backward, its own AdamW, and its state for checkpoints."""
|
|
811
|
+
|
|
812
|
+
def __init__(self, blocks, first: int, rank: int, scale: float, lr: float, loss_scale: float = 1.0, checkpointing: bool = True,
|
|
813
|
+
mode: str = "lora", weight_decay: float = 0.0, targets: list[str] | None = None):
|
|
814
|
+
import torch
|
|
815
|
+
self.layers, self.first = blocks, first
|
|
816
|
+
self.adapter = True
|
|
817
|
+
self.loss_scale, self.checkpointing, self.mode = loss_scale, checkpointing, mode
|
|
818
|
+
|
|
819
|
+
self.device = next(blocks[0].parameters()).device
|
|
820
|
+
floats = [p for p in blocks[0].parameters() if p.is_floating_point()]
|
|
821
|
+
self.dtype = floats[0].dtype if floats else torch.float32
|
|
822
|
+
if self.dtype not in (torch.float32, torch.float16, torch.bfloat16):
|
|
823
|
+
self.dtype = torch.float16
|
|
824
|
+
if self.dtype == torch.float32:
|
|
825
|
+
self.loss_scale = 1.0
|
|
826
|
+
self.max_loss_scale, self.good_steps, self.overflows = max(1.0, self.loss_scale), 0, 0
|
|
827
|
+
self.params, self.init = {}, {}
|
|
828
|
+
if mode == "full":
|
|
829
|
+
for j, block in enumerate(blocks):
|
|
830
|
+
for n, p in block.named_parameters():
|
|
831
|
+
self.params[f"{first + j}.{n}"] = p
|
|
832
|
+
p.requires_grad_(True)
|
|
833
|
+
else:
|
|
834
|
+
for j, block in enumerate(blocks):
|
|
835
|
+
i = first + j
|
|
836
|
+
for k, name in enumerate(lora_targets(block)):
|
|
837
|
+
if not targeted(name, targets):
|
|
838
|
+
continue
|
|
839
|
+
base = block.get_submodule(name)
|
|
840
|
+
fan_in, fan_out = linear_size(base)
|
|
841
|
+
A, B = lora_init(i, k, fan_in, fan_out, rank)
|
|
842
|
+
d = next(base.parameters()).device
|
|
843
|
+
A, B = torch.nn.Parameter(torch.tensor(A, device=d)), torch.nn.Parameter(torch.tensor(B, device=d))
|
|
844
|
+
_attach_lora(base, A, B, scale, self)
|
|
845
|
+
self.params[f"{i}.{name}.A"], self.params[f"{i}.{name}.B"] = A, B
|
|
846
|
+
self.init[f"{i}.{name}"] = (i, k, fan_in, fan_out, rank)
|
|
847
|
+
if not self.params and targets:
|
|
848
|
+
raise ValueError(f"target_modules {targets} names none of the linear layers in {type(blocks[0]).__name__}: "
|
|
849
|
+
f"{', '.join(lora_targets(blocks[0]))}")
|
|
850
|
+
if not self.params:
|
|
851
|
+
raise ValueError(f"layerpool found no linear layers to put LoRA on in {type(blocks[0]).__name__}; train this model with "
|
|
852
|
+
"full=True (mode=\"full\") instead")
|
|
853
|
+
decayed = [p for p in self.params.values() if p.dim() > 1]
|
|
854
|
+
plain = [p for p in self.params.values() if p.dim() <= 1]
|
|
855
|
+
groups = [{"params": decayed, "weight_decay": weight_decay}] + ([{"params": plain, "weight_decay": 0.0}] if plain else [])
|
|
856
|
+
self.opt = torch.optim.AdamW(groups, lr=lr, betas=BETAS, eps=EPS)
|
|
857
|
+
self.graphs = {}
|
|
858
|
+
self.initial_state = {k: v.detach().float().cpu().numpy().copy() for k, v in self.params.items()} if mode == "full" else None
|
|
859
|
+
|
|
860
|
+
@property
|
|
861
|
+
def last(self) -> int:
|
|
862
|
+
return self.first + len(self.layers)
|
|
863
|
+
|
|
864
|
+
def tensor(self, array: np.ndarray):
|
|
865
|
+
import torch
|
|
866
|
+
return torch.from_numpy(np.ascontiguousarray(array))
|
|
867
|
+
|
|
868
|
+
def numpy(self, value) -> np.ndarray:
|
|
869
|
+
return value.detach().float().cpu().numpy()
|
|
870
|
+
|
|
871
|
+
def set_adapter(self, enabled: bool):
|
|
872
|
+
self.adapter = enabled
|
|
873
|
+
|
|
874
|
+
def _run(self, h, args: dict, carry: dict | None = None, plan: list | None = None):
|
|
875
|
+
"""The slice on h. carry holds outputs of earlier blocks that later blocks take as arguments (T5's position bias), by
|
|
876
|
+
(block, place in its output); plan lists [block, place, last block using it] for the whole model."""
|
|
877
|
+
import torch
|
|
878
|
+
import torch.utils.checkpoint as ckpt
|
|
879
|
+
carry = dict(carry or {})
|
|
880
|
+
for j, block in enumerate(self.layers):
|
|
881
|
+
index = self.first + j
|
|
882
|
+
a, kw = args[index]
|
|
883
|
+
if plan:
|
|
884
|
+
a, kw = _with_carried(a, carry), _with_carried(kw, carry)
|
|
885
|
+
want = [k for i, k, _ in plan or [] if i == index]
|
|
886
|
+
d = next(block.parameters()).device
|
|
887
|
+
h = h.to(d)
|
|
888
|
+
|
|
889
|
+
def call(x, block=block, a=a, kw=kw, want=want):
|
|
890
|
+
out = block(x, *a, **kw)
|
|
891
|
+
return (first_tensor(out), *[out[k] for k in want]) if want else first_tensor(out)
|
|
892
|
+
res = ckpt.checkpoint(call, h, use_reentrant=False) if self.checkpointing and torch.is_grad_enabled() else call(h)
|
|
893
|
+
if want:
|
|
894
|
+
h = res[0]
|
|
895
|
+
for k, value in zip(want, res[1:]):
|
|
896
|
+
carry[(index, k)] = value
|
|
897
|
+
else:
|
|
898
|
+
h = res
|
|
899
|
+
if plan is None:
|
|
900
|
+
return h
|
|
901
|
+
onward = {(i, k) for i, k, last in plan if last >= self.last}
|
|
902
|
+
return h, {key: v for key, v in carry.items() if key in onward}
|
|
903
|
+
|
|
904
|
+
def _here(self, value):
|
|
905
|
+
"""A carried tensor on this slice's device, in its precision when it holds numbers (the whole model, run in one
|
|
906
|
+
precision, would have made it in that one)."""
|
|
907
|
+
return value.to(self.device, self.dtype) if value.is_floating_point() else value.to(self.device)
|
|
908
|
+
|
|
909
|
+
def forward(self, x, args: dict, carry: dict | None = None, plan: list | None = None, key=None, leaves: dict | None = None):
|
|
910
|
+
"""The slice's output; with a plan (a model whose blocks hand tensors on), also the carried tensors later slices need.
|
|
911
|
+
With a key (a micro-batch whose backward comes later), the forward pass keeps its graph for backward(key=...): with
|
|
912
|
+
checkpointing only each block's input, so the backward runs every block forward once more, not twice."""
|
|
913
|
+
import torch
|
|
914
|
+
if key is None:
|
|
915
|
+
with torch.no_grad():
|
|
916
|
+
if plan is None:
|
|
917
|
+
return self._run(x.to(self.device, self.dtype), args)
|
|
918
|
+
carry = {k: self._here(v) for k, v in (carry or {}).items()}
|
|
919
|
+
return self._run(x.to(self.device, self.dtype), args, carry, plan)
|
|
920
|
+
received = None
|
|
921
|
+
with torch.enable_grad():
|
|
922
|
+
inp = x.to(self.device, self.dtype).detach().requires_grad_(True)
|
|
923
|
+
if plan is None:
|
|
924
|
+
out, onward = self._run(inp, args), None
|
|
925
|
+
else:
|
|
926
|
+
received = {k: self._here(v).detach().requires_grad_(v.is_floating_point()) for k, v in (carry or {}).items()}
|
|
927
|
+
out, onward = self._run(inp, args, received, plan)
|
|
928
|
+
self.graphs[key] = (inp, out, onward, received, leaves or {}, args)
|
|
929
|
+
if plan is None:
|
|
930
|
+
return out.detach()
|
|
931
|
+
return out.detach(), {k: v.detach() for k, v in onward.items()}
|
|
932
|
+
|
|
933
|
+
def backward(self, x, args: dict, leaves: dict, grad_out, carry: dict | None = None, carry_grads: dict | None = None,
|
|
934
|
+
plan: list | None = None, key=None):
|
|
935
|
+
"""Gradient of the stage input, and of every argument tensor that needs one, for the given output gradient. With a plan,
|
|
936
|
+
also takes the gradients of the carried tensors this slice passed on, and returns those of the ones it received.
|
|
937
|
+
The trained weights' gradients add up unscaled in float32. When a 16-bit backward overflows, the loss scale halves and
|
|
938
|
+
this micro-batch's backward runs again, so the step goes on instead of being skipped on every device."""
|
|
939
|
+
import torch
|
|
940
|
+
kept = self.graphs.pop(key, None) if key is not None else None
|
|
941
|
+
if kept is None and args is None:
|
|
942
|
+
raise RuntimeError("layerpool: a backward came for a micro-batch whose forward graph is gone")
|
|
943
|
+
if kept is not None:
|
|
944
|
+
inp, out, onward, received, leaves, args = kept
|
|
945
|
+
else:
|
|
946
|
+
inp = x.to(self.device, self.dtype).detach().requires_grad_(True)
|
|
947
|
+
received = {k: self._here(v).detach().requires_grad_(v.is_floating_point()) for k, v in (carry or {}).items()} \
|
|
948
|
+
if plan is not None else None
|
|
949
|
+
out = onward = None
|
|
950
|
+
trained = list(self.params.values())
|
|
951
|
+
inputs = [t for t in [inp, *leaves.values(), *(received or {}).values()] if t.requires_grad]
|
|
952
|
+
while True:
|
|
953
|
+
with torch.enable_grad():
|
|
954
|
+
if out is None:
|
|
955
|
+
out, onward = (self._run(inp, args), None) if plan is None else self._run(inp, args, received, plan)
|
|
956
|
+
outs, grads = [out], [self._scaled(grad_out, out)]
|
|
957
|
+
for k, g in (carry_grads or {}).items() if plan is not None else ():
|
|
958
|
+
if k in onward and onward[k].requires_grad:
|
|
959
|
+
outs.append(onward[k])
|
|
960
|
+
grads.append(self._scaled(g, onward[k]))
|
|
961
|
+
if self.loss_scale == 1.0:
|
|
962
|
+
for t in inputs:
|
|
963
|
+
t.grad = None
|
|
964
|
+
torch.autograd.backward(outs, grads)
|
|
965
|
+
found = {id(t): t.grad for t in inputs if t.grad is not None}
|
|
966
|
+
break
|
|
967
|
+
targets = inputs + [p for p in trained if p.requires_grad]
|
|
968
|
+
got = torch.autograd.grad(outs, targets, grads, allow_unused=True)
|
|
969
|
+
found = {id(t): g for t, g in zip(targets, got) if g is not None}
|
|
970
|
+
if self.loss_scale <= 1.0 or bool(torch.stack([torch.isfinite(g).all().to(self.device) for g in found.values()]).all()):
|
|
971
|
+
break
|
|
972
|
+
self.loss_scale, self.good_steps, out = self.loss_scale / 2, 0, None
|
|
973
|
+
self.overflows += 1
|
|
974
|
+
for p in trained:
|
|
975
|
+
if id(p) in found:
|
|
976
|
+
g = self._unscaled(found[id(p)])
|
|
977
|
+
if p.grad is None:
|
|
978
|
+
p.grad = g
|
|
979
|
+
else:
|
|
980
|
+
p.grad.add_(g)
|
|
981
|
+
back = lambda t: self._unscaled(found[id(t)]) if id(t) in found else None
|
|
982
|
+
sides = {k: back(v) for k, v in leaves.items()}
|
|
983
|
+
if plan is None:
|
|
984
|
+
return back(inp), sides
|
|
985
|
+
return back(inp), sides, {k: back(v) for k, v in received.items() if id(v) in found}
|
|
986
|
+
|
|
987
|
+
def _scaled(self, grad, like):
|
|
988
|
+
"""The loss scale goes on in float32, before the cast to a 16-bit dtype, so small gradients survive it."""
|
|
989
|
+
return (grad.to(like.device).float() * self.loss_scale).to(like.dtype)
|
|
990
|
+
|
|
991
|
+
def _unscaled(self, grad):
|
|
992
|
+
return grad.detach().float() / self.loss_scale
|
|
993
|
+
|
|
994
|
+
def grad_sq(self) -> float:
|
|
995
|
+
total = 0.0
|
|
996
|
+
for p in self.params.values():
|
|
997
|
+
if p.grad is not None:
|
|
998
|
+
total += float(p.grad.float().pow(2).sum())
|
|
999
|
+
return total
|
|
1000
|
+
|
|
1001
|
+
def step(self, lr: float | None = None, clip: float = 1.0, skip: bool = False):
|
|
1002
|
+
if skip:
|
|
1003
|
+
self.opt.zero_grad(set_to_none=True)
|
|
1004
|
+
return
|
|
1005
|
+
for p in self.params.values():
|
|
1006
|
+
if p.grad is not None:
|
|
1007
|
+
p.grad *= clip
|
|
1008
|
+
if lr is not None:
|
|
1009
|
+
for group in self.opt.param_groups:
|
|
1010
|
+
group["lr"] = lr
|
|
1011
|
+
self.opt.step()
|
|
1012
|
+
self.opt.zero_grad(set_to_none=True)
|
|
1013
|
+
self.good_steps += 1
|
|
1014
|
+
if self.good_steps >= SCALE_GROWTH_STEPS and self.loss_scale < self.max_loss_scale:
|
|
1015
|
+
self.loss_scale, self.good_steps = min(self.max_loss_scale, self.loss_scale * 2), 0
|
|
1016
|
+
|
|
1017
|
+
def zero_grad(self):
|
|
1018
|
+
self.opt.zero_grad(set_to_none=True)
|
|
1019
|
+
self.graphs.clear()
|
|
1020
|
+
|
|
1021
|
+
def set_weight_decay(self, value: float):
|
|
1022
|
+
"""Weight decay for the matrices; norms and biases (one-dimensional) never decay, as in the Trainer."""
|
|
1023
|
+
self.opt.param_groups[0]["weight_decay"] = value
|
|
1024
|
+
|
|
1025
|
+
def state(self) -> dict[str, np.ndarray]:
|
|
1026
|
+
out = {}
|
|
1027
|
+
for k, p in self.params.items():
|
|
1028
|
+
out[k] = p.detach().float().cpu().numpy()
|
|
1029
|
+
st = self.opt.state.get(p)
|
|
1030
|
+
if st:
|
|
1031
|
+
out[k + ".m"] = st["exp_avg"].detach().float().cpu().numpy()
|
|
1032
|
+
out[k + ".v"] = st["exp_avg_sq"].detach().float().cpu().numpy()
|
|
1033
|
+
out[k + ".t"] = np.array([float(st["step"])], np.float32)
|
|
1034
|
+
return out
|
|
1035
|
+
|
|
1036
|
+
def weights(self) -> dict[str, np.ndarray]:
|
|
1037
|
+
return {k: p.detach().float().cpu().numpy() for k, p in self.params.items()}
|
|
1038
|
+
|
|
1039
|
+
def initial(self) -> dict[str, np.ndarray]:
|
|
1040
|
+
if self.mode == "full":
|
|
1041
|
+
return dict(self.initial_state)
|
|
1042
|
+
out = {}
|
|
1043
|
+
for key, args in self.init.items():
|
|
1044
|
+
out[key + ".A"], out[key + ".B"] = lora_init(*args)
|
|
1045
|
+
return out
|
|
1046
|
+
|
|
1047
|
+
def load_state(self, saved: dict[str, np.ndarray]) -> int:
|
|
1048
|
+
import torch
|
|
1049
|
+
restored = 0
|
|
1050
|
+
for k, p in self.params.items():
|
|
1051
|
+
if k in saved:
|
|
1052
|
+
with torch.no_grad():
|
|
1053
|
+
p.data.copy_(torch.tensor(saved[k], device=p.device, dtype=p.dtype))
|
|
1054
|
+
restored += 1
|
|
1055
|
+
self.opt.state.pop(p, None)
|
|
1056
|
+
if k + ".m" in saved:
|
|
1057
|
+
self.opt.state[p] = {"step": torch.tensor(float(saved[k + ".t"][0])),
|
|
1058
|
+
"exp_avg": torch.tensor(saved[k + ".m"], device=p.device, dtype=p.dtype),
|
|
1059
|
+
"exp_avg_sq": torch.tensor(saved[k + ".v"], device=p.device, dtype=p.dtype)}
|
|
1060
|
+
return restored
|
|
1061
|
+
|