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.
File without changes
@@ -0,0 +1,21 @@
1
+ import zlib
2
+
3
+ import numpy as np
4
+
5
+ ONE_PLUS_NORM = ("gemma", "qwen3_next", "qwen3_5")
6
+
7
+
8
+ def random_weights(shapes: dict[str, tuple], config: dict) -> dict[str, np.ndarray]:
9
+ """Initial values for training from scratch, from each weight's full-model name only: the same on every device and backend."""
10
+ std = config.get("initializer_range") or 0.02
11
+ out = {}
12
+ one_plus = str(config.get("model_type") or "").startswith(ONE_PLUS_NORM)
13
+ for name, shape in shapes.items():
14
+ if len(shape) == 1:
15
+ parts = name.lower().split(".")
16
+ is_norm = "norm" in name.lower() or any(p == "ln" or p.startswith("ln_") or p.endswith("_ln") for p in parts)
17
+ ones = is_norm and name.endswith("weight") and not one_plus
18
+ out[name] = (np.ones if ones else np.zeros)(shape, np.float32)
19
+ else:
20
+ out[name] = np.random.default_rng(zlib.crc32(name.encode())).normal(0, std, shape).astype(np.float32)
21
+ return out
@@ -0,0 +1,622 @@
1
+ import functools
2
+ import inspect
3
+ import json
4
+ from concurrent.futures import ThreadPoolExecutor
5
+
6
+ import mlx.core as mx
7
+ import mlx.nn as nn
8
+ import numpy as np
9
+ from mlx.utils import tree_flatten, tree_unflatten
10
+
11
+ from .. import fetch
12
+ from ..blocks import BETAS, EPS, SCALE_GROWTH_STEPS, lora_init, targeted
13
+ from .common import random_weights
14
+
15
+
16
+ class LoRA(nn.Module):
17
+ def __init__(self, base, A: mx.array, B: mx.array, scale: float):
18
+ super().__init__()
19
+ self.base, self.scale = base, scale
20
+ self.enabled = True
21
+ self.A, self.B = A, B
22
+
23
+ def __call__(self, x):
24
+ if not self.enabled:
25
+ return self.base(x)
26
+ return self.base(x) + (self.scale * ((x.astype(mx.float32) @ self.A.T) @ self.B.T)).astype(x.dtype)
27
+
28
+
29
+ class Body(nn.Module):
30
+ def __init__(self, layers):
31
+ super().__init__()
32
+ self.layers = layers
33
+
34
+
35
+ def _mlx_lm_classes():
36
+ try:
37
+ from mlx_lm.utils import _get_classes
38
+ except ImportError:
39
+ import importlib.metadata
40
+ try:
41
+ version = importlib.metadata.version("mlx-lm")
42
+ except importlib.metadata.PackageNotFoundError:
43
+ raise RuntimeError("MLX training needs mlx-lm: run pip install mlx-lm, or start this device with --backend torch") from None
44
+ raise RuntimeError(f"this mlx-lm ({version}) has no mlx_lm.utils._get_classes, which layerpool uses to build MLX layers; "
45
+ "install the mlx-lm version layerpool was released with, or start this device with --backend torch") from None
46
+ return _get_classes
47
+
48
+
49
+ MX_DTYPES = {"BF16": "bfloat16", "F16": "float16", "F32": "float32", "F64": "float32", "U32": "uint32", "I32": "int32", "U8": "uint8",
50
+ "I8": "int8", "I64": "int64", "U16": "uint16", "I16": "int16", "BOOL": "bool_"}
51
+
52
+
53
+ def _stack_owner(module, n: int, path: str = ""):
54
+ """The module holding the model's list of n blocks, and its path: mlx-lm keeps it under different names per family (model,
55
+ language_model.model, ...)."""
56
+ for key, value in module.items():
57
+ if key == "layers" and isinstance(value, list) and len(value) == n:
58
+ return module, path
59
+ for key, value in module.items():
60
+ if isinstance(value, nn.Module):
61
+ found = _stack_owner(value, n, f"{path}.{key}" if path else key)
62
+ if found:
63
+ return found
64
+ return None
65
+
66
+
67
+ def _placeholders(repo: str, real: dict) -> dict:
68
+ """Every tensor of the checkpoint: the ones loaded, and zeros of the right shape for the rest. MLX builds zeros only when they
69
+ are used, and they never are: they only let mlx-lm's sanitize see the whole checkpoint, as some families decide by it how to
70
+ convert their weights."""
71
+ out = {}
72
+ for name in sorted(set(fetch.weight_map(repo).values())):
73
+ for key, info in fetch.header(repo, name).items():
74
+ if key == "__metadata__" or key in real:
75
+ continue
76
+ out[key] = mx.zeros(tuple(info["shape"]), getattr(mx, MX_DTYPES.get(info["dtype"], "float32")))
77
+ out.update(real)
78
+ return out
79
+
80
+
81
+ def _for_mlx_lm(config: dict) -> dict:
82
+ """The config as mlx-lm reads it. transformers 5 writes rope settings inside rope_parameters, where many mlx-lm families do
83
+ not look (they would fall back to their default base), and keeps a hybrid model's pattern only as layer_types, where mlx-lm
84
+ reads full_attention_interval; a text-only config of a vision-language family (qwen3_5_text) is built by that family's code."""
85
+ import importlib.util
86
+ config = json.loads(json.dumps(config))
87
+ for c in [config] + ([config["text_config"]] if isinstance(config.get("text_config"), dict) else []):
88
+ rope = c.get("rope_parameters")
89
+ if isinstance(rope, dict) and isinstance(rope.get("full_attention"), dict):
90
+ local = rope.get("sliding_attention")
91
+ if isinstance(local, dict) and c.get("rope_local_base_freq") is None and "rope_theta" in local:
92
+ c["rope_local_base_freq"] = local["rope_theta"]
93
+ rope = rope["full_attention"]
94
+ if isinstance(rope, dict):
95
+ for k in ("rope_theta", "partial_rotary_factor"):
96
+ if c.get(k) is None and k in rope:
97
+ c[k] = rope[k]
98
+ if rope.get("rope_type") not in (None, "default") and not c.get("rope_scaling"):
99
+ c["rope_scaling"] = {**rope, "type": rope["rope_type"]}
100
+ kinds = c.get("layer_types")
101
+ if isinstance(kinds, list) and "full_attention" in kinds:
102
+ every = kinds.index("full_attention") + 1
103
+ if all((kind == "full_attention") == ((i + 1) % every == 0) for i, kind in enumerate(kinds)):
104
+ if "linear_attention" in kinds and c.get("full_attention_interval") is None:
105
+ c["full_attention_interval"] = every
106
+ if "sliding_attention" in kinds and c.get("sliding_window_pattern") is None:
107
+ c["sliding_window_pattern"] = every
108
+ kind = str(config.get("model_type") or "")
109
+ if kind.endswith("_text") and importlib.util.find_spec(f"mlx_lm.models.{kind}") is None:
110
+ config["model_type"] = kind[:-len("_text")]
111
+ return config
112
+
113
+
114
+ def layers_path(repo: str, n: int) -> str:
115
+ """The path of the list of blocks in mlx-lm's model of this checkpoint (model.layers, language_model.model.layers, ...)."""
116
+ config = _for_mlx_lm(fetch.load_json(repo, "config.json"))
117
+ model_class, args_class = _mlx_lm_classes()(config)
118
+ found = _stack_owner(model_class(args_class.from_dict(config)), n)
119
+ if found is None:
120
+ raise ValueError(f"mlx-lm's model of {repo} has no list of {n} blocks")
121
+ return f"{found[1]}.layers" if found[1] else "layers"
122
+
123
+
124
+ def load_range(repo: str, first: int, last: int, n: int, stack: str = "model.layers", dtype=None, random_init: bool = False, log=None):
125
+ """Blocks first..last of a model mlx-lm can run, built by mlx-lm's own code for its family, without the embeddings and the
126
+ output head (those stay on the training machine). The whole model is described, so each block keeps what depends on its place
127
+ (linear or full attention, sliding windows), but only these blocks are ever made in memory."""
128
+ from ..blocks import block_spans
129
+ import re
130
+ config = fetch.load_json(repo, "config.json")
131
+ model_type = str(config.get("model_type") or (config.get("text_config") or {}).get("model_type") or "")
132
+ model_class, args_class = _mlx_lm_classes()(_for_mlx_lm(config))
133
+ model = model_class(args_class.from_dict(_for_mlx_lm(config)))
134
+ found = _stack_owner(model, n)
135
+ if found is None:
136
+ raise ValueError(f"mlx-lm's {model_type} model has no list of {n} blocks layerpool can find")
137
+ owner, path = found
138
+ prefix = f"{path}.layers." if path else "layers."
139
+ layers = list(owner["layers"])[first:last]
140
+ owner["layers"] = layers
141
+ body = Body(layers)
142
+ renamed = {}
143
+ if random_init:
144
+ local = dict(tree_flatten(body.parameters()))
145
+ made = random_weights({f"{stack}.{int(k.split('.')[1]) + first}.{k.split('.', 2)[2]}": tuple(v.shape) for k, v in local.items()},
146
+ config)
147
+ renamed = {k: mx.array(made[f"{stack}.{int(k.split('.')[1]) + first}.{k.split('.', 2)[2]}"]) for k in local}
148
+ else:
149
+ spans = block_spans(fetch.weight_map(repo), stack, n)
150
+ wanted = [k for k, (i, _, _) in spans.items() if first <= i < last]
151
+ real = {}
152
+ for file, keys in fetch.fetch(repo, wanted, log).items():
153
+ arrays = mx.load(file)
154
+ real.update({k: arrays[k] for k in keys})
155
+ weights = model.sanitize(_placeholders(repo, real)) if hasattr(model, "sanitize") else real
156
+ pattern = re.compile(rf"^{re.escape(prefix)}(\d+)\.(.+)$")
157
+ for key, value in weights.items():
158
+ hit = pattern.match(key)
159
+ if hit and first <= int(hit.group(1)) < last:
160
+ renamed[f"layers.{int(hit.group(1)) - first}.{hit.group(2)}"] = value
161
+ quant = config.get("quantization") or (config.get("text_config") or {}).get("quantization")
162
+ if quant:
163
+ extra = {"mode": quant.get("mode", "affine")} if "mode" in inspect.signature(nn.quantize).parameters else {}
164
+
165
+ def chosen(p, m):
166
+ if not hasattr(m, "to_quantized") or f"{p}.scales" not in renamed:
167
+ return False
168
+ j, rest = p.split(".", 2)[1:]
169
+ own = quant.get(f"{prefix}{int(j) + first}.{rest}")
170
+ return own if isinstance(own, dict) else True
171
+ nn.quantize(body, group_size=quant["group_size"], bits=quant["bits"], **extra, class_predicate=chosen)
172
+ body.load_weights(list(renamed.items()), strict=False)
173
+ missing = [k for k, _ in tree_flatten(body.parameters()) if k not in renamed and not k.endswith((".A", ".B"))]
174
+ if missing:
175
+ raise ValueError(f"{repo} has no weights for {missing[:5]}{' ...' if len(missing) > 5 else ''} of its blocks as mlx-lm builds "
176
+ "them; this model's layout is not supported by the MLX backend")
177
+ if dtype is not None:
178
+ body.set_dtype(dtype)
179
+ body.train()
180
+ del model
181
+ return body, layers
182
+
183
+
184
+ def _pinned(fn):
185
+ @functools.wraps(fn)
186
+ def run(self, *args, **kwargs):
187
+ return self.thread.submit(fn, self, *args, **kwargs).result()
188
+ return run
189
+
190
+
191
+
192
+ def _linear_names(layer) -> list[str]:
193
+ """Every linear layer in a block, sorted by name: the same LoRA targets and order as the torch blocks."""
194
+ return sorted(name for name, mod in layer.named_modules()
195
+ if name and not name.endswith(".base") and isinstance(mod, (nn.Linear, nn.QuantizedLinear, LoRA)))
196
+
197
+
198
+ def _get(module, path: str):
199
+ for part in path.split(".") if path else []:
200
+ module = module[int(part)] if part.isdigit() else getattr(module, part)
201
+ return module
202
+
203
+
204
+ class StageCore:
205
+ """Consecutive blocks on one Apple GPU (or CPU) with MLX: forward, backward, its own AdamW, and its state for checkpoints,
206
+ the same as the torch BlockCore."""
207
+
208
+ def __init__(self, loader, first: int, rank: int, scale: float, lr: float, loss_scale: float = 1.0, checkpointing: bool = True,
209
+ device=None, mode: str = "lora", weight_decay: float = 0.0, targets: list[str] | None = None):
210
+ device = device or mx.default_device()
211
+ self.targets = targets
212
+ self.thread = ThreadPoolExecutor(1, initializer=mx.set_default_device, initargs=(device,))
213
+ self._setup(loader, first, rank, scale, lr, loss_scale, checkpointing, mode, weight_decay)
214
+
215
+ @_pinned
216
+ def _setup(self, loader, first, rank, scale, lr, loss_scale, checkpointing, mode, weight_decay):
217
+ model, layers = loader()
218
+ mx.eval(model.parameters())
219
+ self.model, self.first, self.mode = model, first, mode
220
+ self.loss_scale, self.checkpointing, self.lr, self.weight_decay = loss_scale, checkpointing, lr, weight_decay
221
+ self.max_loss_scale, self.good_steps, self.overflows = max(1.0, loss_scale), 0, 0
222
+ self.body = Body(layers)
223
+ self.layers = self.body.layers
224
+ self.model.freeze()
225
+ self.init, self.loras, names = {}, [], []
226
+ if mode == "full":
227
+ self.body.unfreeze()
228
+ for k, _ in tree_flatten(self.body.trainable_parameters()):
229
+ j, rest = k.split(".", 2)[1:]
230
+ names.append((k, f"{first + int(j)}.{rest}"))
231
+ else:
232
+ for layer in self.layers:
233
+ for name, module in [(n, m) for n, m in layer.named_modules() if isinstance(m, LoRA)]:
234
+ parent, _, attr = name.rpartition(".")
235
+ setattr(_get(layer, parent), attr, module.base)
236
+ for j, layer in enumerate(self.layers):
237
+ for k, name in enumerate(_linear_names(layer)):
238
+ if not targeted(name, self.targets):
239
+ continue
240
+ parent_name, _, attr = name.rpartition(".")
241
+ holder = _get(layer, parent_name)
242
+ base = getattr(holder, attr)
243
+ base = base.base if isinstance(base, LoRA) else base
244
+ fan_out = base.weight.shape[0]
245
+ fan_in = base.weight.shape[1] * 32 // base.bits if isinstance(base, nn.QuantizedLinear) else base.weight.shape[1]
246
+ A, B = lora_init(first + j, k, fan_in, fan_out, rank)
247
+ lora = LoRA(base, mx.array(A), mx.array(B), scale)
248
+ lora.freeze()
249
+ lora.unfreeze(keys=["A", "B"], recurse=False)
250
+ setattr(holder, attr, lora)
251
+ self.loras.append(lora)
252
+ self.init[f"{first + j}.{name}"] = (first + j, k, fan_in, fan_out, rank)
253
+ names.append((f"layers.{j}.{name}.A", f"{first + j}.{name}.A"))
254
+ names.append((f"layers.{j}.{name}.B", f"{first + j}.{name}.B"))
255
+ if mode != "full" and not self.loras:
256
+ raise ValueError(f"target_modules {self.targets} names none of the linear layers of the MLX blocks")
257
+ self.names = dict(names)
258
+ self.dtype = self._dtype()
259
+ if self.dtype == mx.float32:
260
+ self.loss_scale = self.max_loss_scale = 1.0
261
+ self.grads = None
262
+ self.graphs = {}
263
+ self.m = self.v = None
264
+ self.t = 0
265
+ self.params = {ours: None for ours in self.names.values()}
266
+ self.initial_state = self._flat_params() if mode == "full" else None
267
+ if self.initial_state is not None:
268
+ self.initial_state = {self.names[k]: np.array(v.astype(mx.float32)) for k, v in self.initial_state.items()}
269
+
270
+ def _flat_params(self) -> dict:
271
+ return dict(tree_flatten(self.body.trainable_parameters()))
272
+
273
+ def _update(self, flat: dict):
274
+ if flat:
275
+ self.body.update(tree_unflatten(list(flat.items())))
276
+
277
+ def _dtype(self):
278
+ for _, value in tree_flatten(self.layers[0].parameters()):
279
+ if mx.issubdtype(value.dtype, mx.floating) and value.dtype != mx.float32:
280
+ return value.dtype
281
+ return mx.float32
282
+
283
+ @_pinned
284
+ def tensor(self, array: np.ndarray):
285
+ return mx.array(array.astype(np.int32) if np.issubdtype(array.dtype, np.integer) else array)
286
+
287
+ @_pinned
288
+ def numpy(self, value) -> np.ndarray:
289
+ return np.array(value.astype(mx.float32))
290
+
291
+ @_pinned
292
+ def set_adapter(self, enabled: bool):
293
+ for lora in self.loras:
294
+ lora.enabled = enabled
295
+
296
+ def _layer(self, layer, h, mask):
297
+ if not self.checkpointing:
298
+ return layer(h, mask, None)
299
+
300
+ def inner(params, h):
301
+ layer.update(params)
302
+ return layer(h, mask, None)
303
+ return mx.checkpoint(inner)(layer.trainable_parameters(), h)
304
+
305
+ def _mask(self, attend, made, linear: bool):
306
+ """The mask one block takes, from where each token may look (rows, 1, tokens, tokens), or from which tokens are real
307
+ (rows, tokens): full-attention blocks take the first, linear-attention blocks (mlx-lm marks them is_linear) the second.
308
+ None means plainly causal with no padding."""
309
+ if attend is None:
310
+ return None if linear else "causal"
311
+ key = (id(attend), linear)
312
+ if key not in made:
313
+ if linear:
314
+ keep = attend if attend.ndim == 2 else attend[:, 0].any(axis=-2)
315
+ made[key] = None if keep.all() else mx.array(keep)
316
+ else:
317
+ if attend.ndim == 2:
318
+ q = attend.shape[1]
319
+ attend = np.tril(np.ones((q, q), bool))[None, None] & attend[:, None, None, :]
320
+ attend = attend | ~attend.any(-1, keepdims=True)
321
+ q, k = attend.shape[-2:]
322
+ causal = np.tril(np.ones((q, k), bool), k - q)
323
+ made[key] = "causal" if (attend == causal).all() else mx.array(attend)
324
+ return made[key]
325
+
326
+ def _run(self, h, masks=None):
327
+ """masks: {block index: where each token may look (rows, 1, tokens, tokens), or which tokens are real (rows, tokens)},
328
+ from the masks transformers gives its blocks, so padded rows train as there; a block without one is causal."""
329
+ made = {}
330
+ for j, layer in enumerate(self.layers):
331
+ attend = (masks or {}).get(self.first + j)
332
+ mask = self._mask(attend, made, bool(getattr(layer, "is_linear", False))) if h.shape[1] > 1 else None
333
+ h = self._layer(layer, h, mask)
334
+ return h
335
+
336
+ @_pinned
337
+ def forward(self, x, args=None, key=None, leaves=None):
338
+ """The slice's output. With a key (a micro-batch whose backward comes later), each block's input is kept, so the
339
+ backward runs every block forward once more instead of the whole slice twice."""
340
+ if key is None:
341
+ out = self._run(x.astype(self.dtype), args)
342
+ mx.eval(out)
343
+ return out
344
+ h, made, kept = x.astype(self.dtype), {}, []
345
+ for j, layer in enumerate(self.layers):
346
+ attend = (args or {}).get(self.first + j)
347
+ mask = self._mask(attend, made, bool(getattr(layer, "is_linear", False))) if h.shape[1] > 1 else None
348
+ kept.append((h, mask))
349
+ h = layer(h, mask, None)
350
+ mx.eval(h, *[k[0] for k in kept])
351
+ self.graphs[key] = kept
352
+ return h
353
+
354
+ @_pinned
355
+ def backward(self, x, args=None, leaves=None, grad_out=None, key=None):
356
+ """Blocks only: the gradient of the input for the given output gradient (unscaled in and out, like the torch blocks)."""
357
+ kept = self.graphs.pop(key, None) if key is not None else None
358
+ if kept is None and x is None:
359
+ raise RuntimeError("layerpool: a backward came for a micro-batch whose forward is gone")
360
+ while True:
361
+ grad_cot = (grad_out.astype(mx.float32) * self.loss_scale).astype(self.dtype)
362
+ if kept is not None:
363
+ grads = {}
364
+ for j in reversed(range(len(self.layers))):
365
+ layer, (h, mask) = self.layers[j], kept[j]
366
+
367
+ def objective(params, inp, layer=layer, mask=mask, cot=grad_cot):
368
+ layer.update(params)
369
+ return (layer(inp, mask, None) * cot).astype(mx.float32).sum()
370
+ got, grad_cot = mx.grad(objective, argnums=(0, 1))(layer.trainable_parameters(), h)
371
+ for k, v in tree_flatten(got):
372
+ grads[f"layers.{j}.{k}"] = v
373
+ mx.eval(grad_cot, list(grads.values()))
374
+ grad_in = grad_cot
375
+ else:
376
+ def whole(params, inp, cot=grad_cot):
377
+ self._update(params)
378
+ return (self._run(inp, args) * cot).astype(mx.float32).sum()
379
+ grads, grad_in = mx.grad(whole, argnums=(0, 1))(self._flat_params(), x.astype(self.dtype))
380
+ mx.eval(grads, grad_in)
381
+ finite = bool(mx.all(mx.array([mx.isfinite(v).all() for v in [grad_in, *grads.values()]])).item())
382
+ if finite or self.loss_scale <= 1.0:
383
+ break
384
+ self.loss_scale, self.good_steps = self.loss_scale / 2, 0
385
+ self.overflows += 1
386
+ grads = {k: v.astype(mx.float32) / self.loss_scale for k, v in grads.items()}
387
+ self.grads = grads if self.grads is None else {k: self.grads[k] + grads[k] for k in grads}
388
+ out = grad_in.astype(mx.float32) / self.loss_scale
389
+ mx.eval(self.grads, out)
390
+ return out, {}
391
+
392
+ @_pinned
393
+ def grad_sq(self) -> float:
394
+ if self.grads is None:
395
+ return 0.0
396
+ return float(sum((v.astype(mx.float32) ** 2).sum() for v in self.grads.values()).item())
397
+
398
+ @_pinned
399
+ def step(self, lr: float | None = None, clip: float = 1.0, skip: bool = False):
400
+ if self.grads is None or skip:
401
+ self.grads = None
402
+ return
403
+ if lr is not None:
404
+ self.lr = lr
405
+ params = self._flat_params()
406
+ grads = {k: v.astype(mx.float32) * clip for k, v in self.grads.items()}
407
+ if self.m is None:
408
+ self.m = {k: mx.zeros(v.shape, mx.float32) for k, v in params.items()}
409
+ self.v = {k: mx.zeros(v.shape, mx.float32) for k, v in params.items()}
410
+ self.t += 1
411
+ b1, b2 = BETAS
412
+ c1, c2 = 1 - b1 ** self.t, 1 - b2 ** self.t
413
+ new = {}
414
+ for k, p in params.items():
415
+ g = grads[k]
416
+ p32 = p.astype(mx.float32)
417
+ if self.weight_decay and p.ndim > 1:
418
+ p32 = p32 * (1 - self.lr * self.weight_decay)
419
+ self.m[k] = b1 * self.m[k] + (1 - b1) * g
420
+ self.v[k] = b2 * self.v[k] + (1 - b2) * g * g
421
+ new[k] = (p32 - (self.lr / c1) * self.m[k] / (mx.sqrt(self.v[k]) / (c2 ** 0.5) + EPS)).astype(p.dtype)
422
+ self._update(new)
423
+ mx.eval(list(new.values()), list(self.m.values()), list(self.v.values()))
424
+ self.grads = None
425
+ self.good_steps += 1
426
+ if self.good_steps >= SCALE_GROWTH_STEPS and self.loss_scale < self.max_loss_scale:
427
+ self.loss_scale, self.good_steps = min(self.max_loss_scale, self.loss_scale * 2), 0
428
+
429
+ @_pinned
430
+ def zero_grad(self):
431
+ self.grads = None
432
+ self.graphs.clear()
433
+
434
+ def set_weight_decay(self, value: float):
435
+ self.weight_decay = value
436
+
437
+ @_pinned
438
+ def state(self) -> dict[str, np.ndarray]:
439
+ params = self._flat_params()
440
+ out = {}
441
+ for k, ours in self.names.items():
442
+ out[ours] = np.array(params[k].astype(mx.float32))
443
+ if self.m is not None:
444
+ out[ours + ".m"] = np.array(self.m[k])
445
+ out[ours + ".v"] = np.array(self.v[k])
446
+ out[ours + ".t"] = np.array([float(self.t)], np.float32)
447
+ return out
448
+
449
+ def initial(self) -> dict[str, np.ndarray]:
450
+ if self.mode == "full":
451
+ return dict(self.initial_state)
452
+ out = {}
453
+ for key, args in self.init.items():
454
+ out[key + ".A"], out[key + ".B"] = lora_init(*args)
455
+ return out
456
+
457
+ @_pinned
458
+ def load_state(self, saved: dict[str, np.ndarray]) -> int:
459
+ params = self._flat_params()
460
+ new, restored = {}, 0
461
+ if not any(k.endswith(".m") for k in saved):
462
+ self.m = self.v = None
463
+ self.t = 0
464
+ for k, ours in self.names.items():
465
+ if ours in saved:
466
+ new[k] = mx.array(saved[ours].astype(np.float32)).astype(params[k].dtype)
467
+ restored += 1
468
+ if ours + ".m" in saved:
469
+ if self.m is None:
470
+ self.m = {key: mx.zeros(value.shape, mx.float32) for key, value in params.items()}
471
+ self.v = {key: mx.zeros(value.shape, mx.float32) for key, value in params.items()}
472
+ self.m[k] = mx.array(saved[ours + ".m"].astype(np.float32))
473
+ self.v[k] = mx.array(saved[ours + ".v"].astype(np.float32))
474
+ self.t = int(saved[ours + ".t"][0])
475
+ if new:
476
+ self._update(new)
477
+ mx.eval(list(new.values()))
478
+ return restored
479
+
480
+
481
+ def verify(repo: str, auto: str, mode: str, log=print) -> str | None:
482
+ """Before MLX trains blocks of an architecture, a small copy of it is built and the same blocks are run by transformers (PyTorch)
483
+ and by mlx-lm (MLX) on a left-padded batch: outputs, the gradient going back and the trained weights' gradients must match,
484
+ and in full fine-tuning the weights themselves. Returns None when they do, else why not. Each architecture is checked once per
485
+ mlx-lm, transformers and layerpool version."""
486
+ import importlib.metadata
487
+ import tempfile
488
+
489
+ import torch
490
+ import transformers
491
+ from transformers.utils import logging
492
+
493
+ from .. import __version__
494
+ from ..blocks import BlockCore, layout, load_blocks, load_config, mlx_masks, pack_args, unpack_args
495
+ from ..job import load_config as raw_config
496
+ from ..selfcheck import _remember, _remembered, _small, kept_rng, settings_hash
497
+ config = load_config(repo)
498
+ kind = str(getattr(config.get_text_config(), "model_type", "") or getattr(config, "model_type", ""))
499
+ key = (f"mlx|{kind}|{settings_hash(config)}|{auto}|{mode}|mlx-lm {importlib.metadata.version('mlx-lm')}"
500
+ f"|transformers {transformers.__version__}|layerpool {__version__}")
501
+ known = _remembered(key)
502
+ if known is not None:
503
+ return None if known == "ok" else known
504
+ level = logging.get_verbosity()
505
+ logging.set_verbosity_error()
506
+ try:
507
+ with tempfile.TemporaryDirectory(prefix="layerpool_mlx_check_") as folder:
508
+ reason = kept_rng(_compare)(config, raw_config(repo), auto, mode, folder, torch, transformers, BlockCore, layout, load_blocks,
509
+ load_config, mlx_masks, pack_args, unpack_args, _small)
510
+ except Exception as e:
511
+ return f"the check could not run ({type(e).__name__}: {str(e)[:200]})"
512
+ finally:
513
+ logging.set_verbosity(level)
514
+ _remember(key, reason or "ok")
515
+ return reason
516
+
517
+
518
+ def _compare(config, raw, auto, mode, folder, torch, transformers, BlockCore, layout, load_blocks, load_config, mlx_masks, pack_args,
519
+ unpack_args, _small) -> str | None:
520
+ small = type(config).from_dict(_small(config.to_dict()))
521
+ torch.manual_seed(0)
522
+ whole = getattr(transformers, auto).from_config(small).float().eval()
523
+ with torch.no_grad():
524
+ for name, p in whole.named_parameters():
525
+ if "norm" in name and p.is_floating_point():
526
+ p.add_(torch.randn_like(p) * 0.3)
527
+ whole.save_pretrained(folder)
528
+ import os
529
+ import shutil
530
+ theirs_folder = os.path.join(folder, "as_run")
531
+ os.makedirs(theirs_folder)
532
+ for name in os.listdir(folder):
533
+ if name.endswith((".safetensors", ".json")) and name != "config.json":
534
+ shutil.copy(os.path.join(folder, name), theirs_folder)
535
+ with open(os.path.join(theirs_folder, "config.json"), "w", encoding="utf-8") as f:
536
+ json.dump(_small(raw), f)
537
+ lay = layout(load_config(folder), auto)
538
+ n = lay["n"]
539
+ first, last = (1, n) if n > 2 else (0, n)
540
+ blocks = whole.get_submodule(lay["stack"])
541
+ vocab = min(getattr(small.get_text_config(), "vocab_size", 300) or 300, 300)
542
+ ids = torch.randint(3, vocab, (3, 64), generator=torch.Generator().manual_seed(1))
543
+ keep = torch.ones(3, 64, dtype=torch.long)
544
+ keep[0, :5] = 0
545
+ keep[1, :2] = 0
546
+ seen = {}
547
+
548
+ def grab(i):
549
+ def hook(module, args, kwargs):
550
+ kwargs = {k: v for k, v in kwargs.items() if k not in ("past_key_values", "past_key_value", "cache_params")}
551
+ if args:
552
+ seen[i] = (tuple(args[1:]), kwargs)
553
+ hidden = args[0]
554
+ else:
555
+ kwargs = dict(kwargs)
556
+ hidden = kwargs.pop("hidden_states")
557
+ seen[i] = ((), kwargs)
558
+ if i == first:
559
+ seen["input"] = hidden.detach()
560
+ return hook
561
+ hooks = [blocks[i].register_forward_pre_hook(grab(i), with_kwargs=True) for i in range(first, last)]
562
+ with torch.no_grad():
563
+ whole(input_ids=ids, attention_mask=keep, use_cache=False)
564
+ for h in hooks:
565
+ h.remove()
566
+ meta, arrays, _ = pack_args({i: seen[i] for i in range(first, last)}, grads=False)
567
+ masks = mlx_masks(meta, arrays, range(first, last))
568
+ args, leaves = unpack_args(meta, arrays, "cpu", torch.float32, range(first, last))
569
+ ours = BlockCore(load_blocks(folder, lay, first, last, "cpu", torch.float32), first, 4, 2.0, 1e-2, loss_scale=1.0, mode=mode)
570
+ theirs = StageCore(lambda: load_range(theirs_folder, first, last, n, lay["stack"], mx.float32), first, 4, 2.0, 1e-2, loss_scale=1.0,
571
+ mode=mode, device=mx.cpu)
572
+ x = seen["input"]
573
+ real = keep.numpy().astype(bool)
574
+
575
+ def close(a, b, what):
576
+ a, b = np.asarray(a, np.float64), np.asarray(b, np.float64)
577
+ if a.shape != b.shape:
578
+ return f"{what}: shapes {a.shape} and {b.shape} differ"
579
+ gap, scale = float(np.abs(a - b).max()) if a.size else 0.0, float(np.abs(a).max()) if a.size else 0.0
580
+ return None if gap <= 5e-4 * max(1.0, scale) else f"{what} differ by {gap:.3g} (largest value {scale:.3g})"
581
+ if mode == "full":
582
+ mine = {k: v for k, v in ours.state().items() if not k.endswith((".m", ".v", ".t"))}
583
+ other = {k: v for k, v in theirs.state().items() if not k.endswith((".m", ".v", ".t"))}
584
+ if set(mine) != set(other):
585
+ return f"the blocks' weights are named differently ({sorted(set(mine) ^ set(other))[:3]})"
586
+ for k in mine:
587
+ wrong = close(mine[k], other[k], f"weight {k}")
588
+ if wrong:
589
+ return wrong
590
+ out = ours.forward(x, args)
591
+ got = np.array(theirs.forward(theirs.tensor(x.numpy()), masks, key=0))
592
+ wrong = close(out.detach().numpy()[real], got[real], "outputs")
593
+ if wrong:
594
+ return wrong
595
+ g = np.random.default_rng(0).standard_normal(out.shape).astype(np.float32) * real[..., None]
596
+ g_ours, _ = ours.backward(x, args, leaves, torch.from_numpy(g))
597
+ g_theirs, _ = theirs.backward(None, None, None, theirs.tensor(g), key=0)
598
+ wrong = close(g_ours.numpy()[real], np.array(g_theirs)[real], "input gradients")
599
+ if wrong:
600
+ return wrong
601
+ mine = {k: p.grad.detach().numpy() for k, p in ours.params.items() if p.grad is not None}
602
+ other = {theirs.names[k]: np.array(v.astype(mx.float32)) for k, v in tree_flatten(theirs.grads)}
603
+ if set(mine) != set(other):
604
+ return f"the trained weights are named differently ({sorted(set(mine) ^ set(other))[:3]})"
605
+ for k in mine:
606
+ wrong = close(mine[k], other[k], f"gradient of {k}")
607
+ if wrong:
608
+ return wrong
609
+ if mx.default_device() != mx.cpu:
610
+ try:
611
+ gpu = StageCore(lambda: load_range(theirs_folder, first, last, n, lay["stack"], mx.float32), first, 4, 2.0, 1e-2, loss_scale=1.0,
612
+ mode=mode, device=mx.default_device())
613
+ got_gpu = np.array(gpu.forward(gpu.tensor(x.numpy()), masks, key=0))
614
+ g_gpu, _ = gpu.backward(None, None, None, gpu.tensor(g), key=0)
615
+ except Exception as e:
616
+ return f"the blocks fail on the Apple GPU ({type(e).__name__}: {str(e)[:150]})"
617
+ for a, b, what in ((out.detach().numpy()[real], got_gpu[real], "outputs on the Apple GPU"),
618
+ (g_ours.numpy()[real], np.array(g_gpu)[real], "input gradients on the Apple GPU")):
619
+ gap, scale = float(np.abs(a - b).max()), float(np.abs(a).max())
620
+ if gap > 2e-2 * max(1.0, scale):
621
+ return f"{what} differ by {gap:.3g} (largest value {scale:.3g})"
622
+ return None