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/driver.py
ADDED
|
@@ -0,0 +1,427 @@
|
|
|
1
|
+
"""The machine with the training code runs the model's own forward. Its blocks are stand-ins: each one notes the arguments
|
|
2
|
+
the model gave it, and the last one sends the stack input with all those arguments through the devices and returns what comes
|
|
3
|
+
back. Autograd sees the whole trip as one operation, so loss.backward() sends the gradient back the same way."""
|
|
4
|
+
import math
|
|
5
|
+
import queue
|
|
6
|
+
import threading
|
|
7
|
+
|
|
8
|
+
import numpy as np
|
|
9
|
+
|
|
10
|
+
from .blocks import pack_args, unpack_args
|
|
11
|
+
from .codec import decode, encode, pack, split_prefix, unpack, with_prefix
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class Box:
|
|
15
|
+
"""One trip through the devices: what was sent, and what is needed to bring the gradients back."""
|
|
16
|
+
|
|
17
|
+
def __init__(self, ends, hidden, per_block, sides, hidden_kw):
|
|
18
|
+
self.ends, self.hidden, self.per_block, self.sides, self.hidden_kw = ends, hidden, per_block, sides, hidden_kw
|
|
19
|
+
self.adapter = ends.adapter
|
|
20
|
+
self.train = False
|
|
21
|
+
self.state = None
|
|
22
|
+
self.dropped = False
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _remote_function():
|
|
26
|
+
import torch
|
|
27
|
+
|
|
28
|
+
class Remote(torch.autograd.Function):
|
|
29
|
+
@staticmethod
|
|
30
|
+
def forward(ctx, hidden, box, anchor, *sides):
|
|
31
|
+
ctx.box = box
|
|
32
|
+
return box.ends.chain.forward(box, hidden.detach()).cpu()
|
|
33
|
+
|
|
34
|
+
@staticmethod
|
|
35
|
+
def backward(ctx, grad):
|
|
36
|
+
box = ctx.box
|
|
37
|
+
if box.dropped:
|
|
38
|
+
raise RuntimeError("layerpool: this output was dropped because another forward, an optimizer step or a save came before its "
|
|
39
|
+
"backward(). Call backward() on each training output before the next forward.")
|
|
40
|
+
g_hidden, g_sides, norm = box.ends.chain.backward(box, grad)
|
|
41
|
+
anchor = box.ends.anchor
|
|
42
|
+
before = float(anchor.grad.item()) if anchor.grad is not None else 0.0
|
|
43
|
+
box.ends.remote_norm = norm
|
|
44
|
+
g_sides = [None if g is None else g.cpu() for g in g_sides]
|
|
45
|
+
return (None if g_hidden is None else g_hidden.cpu(), None, torch.tensor([norm - before]), *g_sides)
|
|
46
|
+
return Remote
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
_REMOTE = None
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _stand_in_class():
|
|
53
|
+
import torch
|
|
54
|
+
|
|
55
|
+
class StandIn(torch.nn.Module):
|
|
56
|
+
def __init__(self, index: int):
|
|
57
|
+
super().__init__()
|
|
58
|
+
self.index = index
|
|
59
|
+
|
|
60
|
+
def forward(self, *args, **kwargs):
|
|
61
|
+
ends = self.ends
|
|
62
|
+
hidden_kw = None
|
|
63
|
+
if args:
|
|
64
|
+
hidden, rest = args[0], tuple(args[1:])
|
|
65
|
+
else:
|
|
66
|
+
hidden_kw = "hidden_states" if "hidden_states" in kwargs else next(k for k, v in kwargs.items() if torch.is_tensor(v))
|
|
67
|
+
kwargs = dict(kwargs)
|
|
68
|
+
hidden, rest = kwargs.pop(hidden_kw), ()
|
|
69
|
+
call = ends.call
|
|
70
|
+
if self.index == 0:
|
|
71
|
+
ends.markers.clear()
|
|
72
|
+
ends.keep.clear()
|
|
73
|
+
call.clear()
|
|
74
|
+
call.update(input=hidden, blocks={}, hidden_kw=hidden_kw)
|
|
75
|
+
call["blocks"][self.index] = (rest, kwargs)
|
|
76
|
+
if ends.tuple_out is None:
|
|
77
|
+
ends.tuple_out = ends.probe(hidden, rest, kwargs, hidden_kw)
|
|
78
|
+
if self.index < ends.n - 1:
|
|
79
|
+
return ends.shaped(hidden, self.index)
|
|
80
|
+
return ends.shaped(ends.through(call), self.index)
|
|
81
|
+
return StandIn
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
class Ends:
|
|
85
|
+
"""The model on this machine, with its stack replaced by stand-ins (see blocks.load_ends)."""
|
|
86
|
+
|
|
87
|
+
def __init__(self, model, lay: dict, chain):
|
|
88
|
+
import torch
|
|
89
|
+
self.model, self.lay, self.chain = model, lay, chain
|
|
90
|
+
self.n = lay["n"]
|
|
91
|
+
self.local = threading.local()
|
|
92
|
+
self.tuple_out = None
|
|
93
|
+
self.markers, self.keep = {}, []
|
|
94
|
+
self.adapter = True
|
|
95
|
+
self.remote_norm = 0.0
|
|
96
|
+
self.discard = None
|
|
97
|
+
path = lay["stack"]
|
|
98
|
+
loaded = list(model.get_submodule(path))
|
|
99
|
+
self._probe_block = loaded[0]
|
|
100
|
+
picked = model.__dict__.get("_layerpool_picked", list(range(len(loaded))))
|
|
101
|
+
kinds = model.__dict__.get("_layerpool_kinds", {})
|
|
102
|
+
StandIn = _stand_in_class()
|
|
103
|
+
stand_ins = torch.nn.ModuleList([StandIn(i) for i in range(self.n)])
|
|
104
|
+
for i, s in enumerate(stand_ins):
|
|
105
|
+
object.__setattr__(s, "ends", self)
|
|
106
|
+
like = loaded[picked.index(kinds.get(i, picked[0]))] if kinds else loaded[0]
|
|
107
|
+
for key, value in like.__dict__.items():
|
|
108
|
+
if not key.startswith("_") and key not in ("training", "index") and isinstance(value, (str, int, float, bool, type(None))):
|
|
109
|
+
s.__dict__[key] = value
|
|
110
|
+
if "layer_idx" in s.__dict__:
|
|
111
|
+
s.__dict__["layer_idx"] = i
|
|
112
|
+
parent_path, _, attr = path.rpartition(".")
|
|
113
|
+
setattr(model.get_submodule(parent_path) if parent_path else model, attr, stand_ins)
|
|
114
|
+
self.anchor = torch.nn.Parameter(torch.zeros(1))
|
|
115
|
+
model.register_parameter("layerpool_anchor", self.anchor)
|
|
116
|
+
|
|
117
|
+
@property
|
|
118
|
+
def call(self) -> dict:
|
|
119
|
+
if not hasattr(self.local, "call"):
|
|
120
|
+
self.local.call = {}
|
|
121
|
+
return self.local.call
|
|
122
|
+
|
|
123
|
+
def shaped(self, hidden, index: int):
|
|
124
|
+
"""The hidden state in the form the model's blocks return it: alone, or first in a tuple or list as long as theirs. The
|
|
125
|
+
other places hold None, or a marker where a real block returns a tensor: when the model hands that tensor to a later
|
|
126
|
+
block (T5's position bias), the block's arguments name it ("output k of block i") and the devices put the real one there."""
|
|
127
|
+
kind, length, tensors = self.tuple_out
|
|
128
|
+
if kind is None:
|
|
129
|
+
return hidden
|
|
130
|
+
import torch
|
|
131
|
+
extras = []
|
|
132
|
+
for k in range(1, length):
|
|
133
|
+
if k in tensors:
|
|
134
|
+
marker = torch.empty(0)
|
|
135
|
+
self.markers[id(marker)] = (index, k)
|
|
136
|
+
self.keep.append(marker)
|
|
137
|
+
extras.append(marker)
|
|
138
|
+
else:
|
|
139
|
+
extras.append(None)
|
|
140
|
+
return kind([hidden] + extras)
|
|
141
|
+
|
|
142
|
+
def probe(self, hidden, rest, kwargs, hidden_kw) -> tuple:
|
|
143
|
+
"""How blocks of this model return their output, from one real block run on this input (its weights do not matter)."""
|
|
144
|
+
import torch
|
|
145
|
+
block = self._probe_block
|
|
146
|
+
if block is None:
|
|
147
|
+
return (None, 1, set())
|
|
148
|
+
try:
|
|
149
|
+
with torch.no_grad():
|
|
150
|
+
param = next(block.parameters())
|
|
151
|
+
h = hidden.detach().to(param.device, param.dtype)
|
|
152
|
+
kwargs = {k: (v.to(param.device) if torch.is_tensor(v) else v) for k, v in kwargs.items()}
|
|
153
|
+
rest = tuple(v.to(param.device) if torch.is_tensor(v) else v for v in rest)
|
|
154
|
+
out = block(**{hidden_kw: h}, **kwargs) if hidden_kw else block(h, *rest, **kwargs)
|
|
155
|
+
if isinstance(out, (tuple, list)):
|
|
156
|
+
return (type(out), len(out), {k for k, v in enumerate(out) if k > 0 and torch.is_tensor(v)})
|
|
157
|
+
return (None, 1, set())
|
|
158
|
+
except Exception:
|
|
159
|
+
return (None, 1, set())
|
|
160
|
+
finally:
|
|
161
|
+
self._probe_block = None
|
|
162
|
+
|
|
163
|
+
def through(self, call):
|
|
164
|
+
global _REMOTE
|
|
165
|
+
import torch
|
|
166
|
+
if sorted(call["blocks"]) != list(range(self.n)):
|
|
167
|
+
raise RuntimeError(f"the model ran {len(call['blocks'])} of its {self.n} blocks in this forward pass; layerpool needs "
|
|
168
|
+
"every block run once, in order (LayerDrop or skipped blocks are not supported)")
|
|
169
|
+
hidden = call["input"]
|
|
170
|
+
if self.discard is not None and self.remote_norm and torch.is_grad_enabled() and self.model.training and \
|
|
171
|
+
(self.anchor.grad is None or not float(self.anchor.grad.abs().sum())):
|
|
172
|
+
self.discard()
|
|
173
|
+
sides, seen = [], set()
|
|
174
|
+
|
|
175
|
+
def collect(v):
|
|
176
|
+
if torch.is_tensor(v):
|
|
177
|
+
if v.requires_grad and id(v) not in seen:
|
|
178
|
+
seen.add(id(v))
|
|
179
|
+
sides.append(v)
|
|
180
|
+
elif isinstance(v, (tuple, list)):
|
|
181
|
+
for x in v:
|
|
182
|
+
collect(x)
|
|
183
|
+
elif isinstance(v, dict):
|
|
184
|
+
for x in v.values():
|
|
185
|
+
collect(x)
|
|
186
|
+
if torch.is_grad_enabled():
|
|
187
|
+
for a, kw in call["blocks"].values():
|
|
188
|
+
collect(a)
|
|
189
|
+
collect(kw)
|
|
190
|
+
box = Box(self, hidden, dict(call["blocks"]), sides, call["hidden_kw"])
|
|
191
|
+
box.carried = dict(self.markers)
|
|
192
|
+
box.train = torch.is_grad_enabled()
|
|
193
|
+
if box.train:
|
|
194
|
+
if _REMOTE is None:
|
|
195
|
+
_REMOTE = _remote_function()
|
|
196
|
+
out = _REMOTE.apply(hidden.cpu(), box, self.anchor.cpu(), *(s.cpu() for s in sides))
|
|
197
|
+
return out.to(hidden.device)
|
|
198
|
+
with torch.no_grad():
|
|
199
|
+
return self.chain.forward(box, hidden.detach())
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def _split_points(rows: int, micro: int, micro_rows: int | None) -> list[tuple[int, int]]:
|
|
203
|
+
per = micro_rows or max(1, math.ceil(rows / max(1, micro)))
|
|
204
|
+
return [(a, min(rows, a + per)) for a in range(0, rows, per)]
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def split_args(per_block: dict, rows: int, cuts: list[tuple[int, int]]):
|
|
208
|
+
"""The block arguments of each micro-batch: tensors with the batch on their first dimension (or on the second, after a small
|
|
209
|
+
first one, like M-RoPE positions) are cut by rows; everything else is shared. Returns the per-micro trees and, for every cut
|
|
210
|
+
tensor, where it came from."""
|
|
211
|
+
import torch
|
|
212
|
+
if len(cuts) == 1:
|
|
213
|
+
return [per_block], [{}]
|
|
214
|
+
out, origins = [], []
|
|
215
|
+
for a, b in cuts:
|
|
216
|
+
made, origin = {}, {}
|
|
217
|
+
|
|
218
|
+
def cut(v, a=a, b=b, made=made, origin=origin):
|
|
219
|
+
if torch.is_tensor(v):
|
|
220
|
+
if id(v) in made:
|
|
221
|
+
return made[id(v)]
|
|
222
|
+
if v.dim() > 0 and v.shape[0] == rows:
|
|
223
|
+
piece, dim = v[a:b], 0
|
|
224
|
+
elif v.dim() > 1 and v.shape[1] == rows and 1 < v.shape[0] <= 4:
|
|
225
|
+
piece, dim = v[:, a:b], 1
|
|
226
|
+
else:
|
|
227
|
+
piece, dim = v, None
|
|
228
|
+
made[id(v)] = piece
|
|
229
|
+
origin[id(piece)] = (v, dim, a, b)
|
|
230
|
+
return piece
|
|
231
|
+
if isinstance(v, tuple):
|
|
232
|
+
return tuple(cut(x) for x in v)
|
|
233
|
+
if isinstance(v, list):
|
|
234
|
+
return [cut(x) for x in v]
|
|
235
|
+
if isinstance(v, dict):
|
|
236
|
+
return {k: cut(x) for k, x in v.items()}
|
|
237
|
+
return v
|
|
238
|
+
out.append({i: (tuple(cut(x) for x in args), {k: cut(x) for k, x in kw.items()}) for i, (args, kw) in per_block.items()})
|
|
239
|
+
origins.append(origin)
|
|
240
|
+
return out, origins
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
class PoolChain:
|
|
244
|
+
"""The devices of a pool: every batch is cut into micro-batches that are all in flight at once."""
|
|
245
|
+
|
|
246
|
+
def __init__(self, pool, job: dict):
|
|
247
|
+
self.pool, self.job = pool, job
|
|
248
|
+
self.io_codec = "fp32" if job.get("codec") == "fp32" else "fp16"
|
|
249
|
+
self.pending: Box | None = None
|
|
250
|
+
|
|
251
|
+
def drop_pending(self, redo: bool = False):
|
|
252
|
+
"""Finish the operation that waits for a backward. With redo, its backward can still come later (another forward came
|
|
253
|
+
first, as with a contrastive loss over two batches): it then runs again with the gradient it gets. Otherwise (an optimizer
|
|
254
|
+
step or a save came first) a later backward raises."""
|
|
255
|
+
box, self.pending = self.pending, None
|
|
256
|
+
if box is not None and box.state is not None and not box.state["done"].is_set():
|
|
257
|
+
box.state["cots"].put(None)
|
|
258
|
+
box.state["done"].wait()
|
|
259
|
+
if redo:
|
|
260
|
+
box.state["redo"] = True
|
|
261
|
+
else:
|
|
262
|
+
box.dropped = True
|
|
263
|
+
|
|
264
|
+
def pieces(self, rows: int) -> tuple[int, int]:
|
|
265
|
+
"""(rows of the biggest piece, number of pieces) a batch of `rows` rows is cut into."""
|
|
266
|
+
cuts = _split_points(rows, self.job.get("micro", 8), self.job.get("micro_batch_size"))
|
|
267
|
+
return max(b - a for a, b in cuts), len(cuts)
|
|
268
|
+
|
|
269
|
+
def expect(self, rows: int, seq: int, pieces: int | None = None):
|
|
270
|
+
"""Pieces of `rows` rows of up to `seq` tokens are coming: when that is more than the split was made for, the pool works
|
|
271
|
+
out the memory again (before the first step when the Trainer says its batch size, so the devices load their layers once)."""
|
|
272
|
+
shape = (rows, -(-int(seq) // 128) * 128)
|
|
273
|
+
seen = getattr(self, "_fitted", (0, 0))
|
|
274
|
+
told = getattr(self, "_pieces", None)
|
|
275
|
+
if shape[0] > seen[0] or shape[1] > seen[1] or (pieces and pieces != told):
|
|
276
|
+
self._fitted = (max(shape[0], seen[0]), max(shape[1], seen[1]))
|
|
277
|
+
self._pieces = pieces or told
|
|
278
|
+
fit = getattr(self.pool, "fit_batch", None)
|
|
279
|
+
if fit is not None:
|
|
280
|
+
fit(*self._fitted, pieces=self._pieces)
|
|
281
|
+
|
|
282
|
+
def _messages(self, box, hidden, micro_rows=None):
|
|
283
|
+
rows = hidden.shape[0]
|
|
284
|
+
cuts = _split_points(rows, self.job.get("micro", 8), micro_rows or self.job.get("micro_batch_size"))
|
|
285
|
+
if hidden.dim() > 2 and hidden.shape[1] == rows:
|
|
286
|
+
cuts = [(0, rows)]
|
|
287
|
+
trees, origins = split_args(box.per_block, rows, cuts)
|
|
288
|
+
messages, sides = [], []
|
|
289
|
+
for (a, b), tree, origin in zip(cuts, trees, origins):
|
|
290
|
+
meta, arrays, micro_sides = pack_args(tree, carried=box.carried)
|
|
291
|
+
sides.append([origin.get(id(s), (s, None, a, b)) for s in micro_sides])
|
|
292
|
+
h = hidden[a:b].detach().float().cpu().numpy()
|
|
293
|
+
messages.append(pack({"args": meta}, **with_prefix(encode(h, self.io_codec), "h_"), **with_prefix(arrays, "a_")))
|
|
294
|
+
return cuts, messages, sides
|
|
295
|
+
|
|
296
|
+
def forward(self, box, hidden):
|
|
297
|
+
self.drop_pending(redo=True)
|
|
298
|
+
cuts, messages, sides = self._messages(box, hidden)
|
|
299
|
+
if box.train and hidden.dim() > 2:
|
|
300
|
+
self.expect(max(b - a for a, b in cuts), int(hidden.shape[1]), len(cuts))
|
|
301
|
+
tokens = int(hidden.shape[0] * hidden.shape[1]) if hidden.dim() > 2 else int(hidden.shape[0])
|
|
302
|
+
if not box.train:
|
|
303
|
+
return self._join(self.pool.forward(messages, adapter=box.adapter), hidden)
|
|
304
|
+
state = {"outputs": queue.Queue(), "cots": queue.Queue(), "result": queue.Queue(), "done": threading.Event(), "cuts": cuts, "sides": sides,
|
|
305
|
+
"messages": messages, "tokens": tokens, "redo": False}
|
|
306
|
+
box.state = state
|
|
307
|
+
need_grads = bool(box.hidden.requires_grad or box.sides)
|
|
308
|
+
|
|
309
|
+
def provider(outputs):
|
|
310
|
+
state["outputs"].put(outputs)
|
|
311
|
+
cots = state["cots"].get()
|
|
312
|
+
if cots is None:
|
|
313
|
+
shapes = [decode(split_prefix(unpack(o)[1], "h_")).shape for o in outputs]
|
|
314
|
+
return [pack(None, **with_prefix(encode(np.zeros(s, np.float32), self.io_codec), "g_")) for s in shapes]
|
|
315
|
+
return cots
|
|
316
|
+
|
|
317
|
+
def work():
|
|
318
|
+
try:
|
|
319
|
+
state["result"].put(self.pool.forward_backward(messages, provider, tokens=tokens, grads=need_grads))
|
|
320
|
+
except BaseException as e:
|
|
321
|
+
state["outputs"].put(e)
|
|
322
|
+
state["result"].put(e)
|
|
323
|
+
finally:
|
|
324
|
+
state["done"].set()
|
|
325
|
+
threading.Thread(target=work, daemon=True).start()
|
|
326
|
+
got = state["outputs"].get()
|
|
327
|
+
if isinstance(got, BaseException):
|
|
328
|
+
raise got
|
|
329
|
+
self.pending = box
|
|
330
|
+
return self._join(got, hidden)
|
|
331
|
+
|
|
332
|
+
def _join(self, outputs, like):
|
|
333
|
+
import torch
|
|
334
|
+
parts = [decode(split_prefix(unpack(o)[1], "h_")) for o in outputs]
|
|
335
|
+
return torch.tensor(np.concatenate(parts, 0), dtype=like.dtype, device=like.device)
|
|
336
|
+
|
|
337
|
+
def backward(self, box, grad):
|
|
338
|
+
import torch
|
|
339
|
+
state = box.state
|
|
340
|
+
if self.pending is box:
|
|
341
|
+
self.pending = None
|
|
342
|
+
g = grad.detach().float().cpu().numpy()
|
|
343
|
+
cots = [pack(None, **with_prefix(encode(g[a:b], self.io_codec), "g_")) for a, b in state["cuts"]]
|
|
344
|
+
if state["redo"]:
|
|
345
|
+
self.drop_pending(redo=True)
|
|
346
|
+
result = self.pool.forward_backward(state["messages"], lambda outputs: cots, tokens=0,
|
|
347
|
+
grads=bool(box.hidden.requires_grad or box.sides))
|
|
348
|
+
else:
|
|
349
|
+
state["cots"].put(cots)
|
|
350
|
+
result = state["result"].get()
|
|
351
|
+
if isinstance(result, BaseException):
|
|
352
|
+
raise result
|
|
353
|
+
norm = float(np.sqrt(max(0.0, result.get("grad_sq", 0.0))))
|
|
354
|
+
g_hidden = None
|
|
355
|
+
side_grads = [None] * len(box.sides)
|
|
356
|
+
if result.get("grads"):
|
|
357
|
+
index = {id(s): i for i, s in enumerate(box.sides)}
|
|
358
|
+
rows = []
|
|
359
|
+
for m, blob in enumerate(result["grads"]):
|
|
360
|
+
arrays = unpack(blob)[1]
|
|
361
|
+
rows.append(decode(split_prefix(arrays, "g_")))
|
|
362
|
+
for k, (orig, dim, a, b) in enumerate(state["sides"][m]):
|
|
363
|
+
if not any(name.startswith(f"s{k}_") for name in arrays):
|
|
364
|
+
continue
|
|
365
|
+
i = index.get(id(orig))
|
|
366
|
+
if i is None:
|
|
367
|
+
continue
|
|
368
|
+
piece = torch.tensor(decode(split_prefix(arrays, f"s{k}_")))
|
|
369
|
+
if side_grads[i] is None:
|
|
370
|
+
side_grads[i] = torch.zeros(orig.shape, dtype=torch.float32)
|
|
371
|
+
if dim == 0:
|
|
372
|
+
side_grads[i][a:b] += piece
|
|
373
|
+
elif dim == 1:
|
|
374
|
+
side_grads[i][:, a:b] += piece
|
|
375
|
+
else:
|
|
376
|
+
side_grads[i] += piece
|
|
377
|
+
g_hidden = torch.tensor(np.concatenate(rows, 0), dtype=box.hidden.dtype)
|
|
378
|
+
side_grads = [None if v is None else v.to(s.dtype) for v, s in zip(side_grads, box.sides)]
|
|
379
|
+
return g_hidden, side_grads, norm
|
|
380
|
+
|
|
381
|
+
|
|
382
|
+
class LocalChain:
|
|
383
|
+
"""The device side in this process: block cores run one after another (the self-check and tests use it)."""
|
|
384
|
+
|
|
385
|
+
def __init__(self, cores):
|
|
386
|
+
self.cores = cores
|
|
387
|
+
|
|
388
|
+
def drop_pending(self, redo: bool = False):
|
|
389
|
+
pass
|
|
390
|
+
|
|
391
|
+
def forward(self, box, hidden):
|
|
392
|
+
meta, arrays, sides = pack_args(box.per_block, carried=getattr(box, "carried", None))
|
|
393
|
+
plan = meta.get("carry")
|
|
394
|
+
box.state = {"packed_sides": sides, "steps": [], "plan": plan}
|
|
395
|
+
h, carry = hidden, {}
|
|
396
|
+
import torch
|
|
397
|
+
keep = torch.is_grad_enabled()
|
|
398
|
+
for ci, core in enumerate(self.cores):
|
|
399
|
+
args, leaves = unpack_args(meta, arrays, core.device, core.dtype, range(core.first, core.last))
|
|
400
|
+
box.state["steps"].append((h, args, leaves, carry))
|
|
401
|
+
kept = {"key": (id(box), ci), "leaves": leaves} if keep else {}
|
|
402
|
+
if plan:
|
|
403
|
+
h, carry = core.forward(h, args, carry, plan, **kept)
|
|
404
|
+
else:
|
|
405
|
+
h = core.forward(h, args, **kept)
|
|
406
|
+
return h.to(hidden.device, hidden.dtype)
|
|
407
|
+
|
|
408
|
+
def backward(self, box, grad):
|
|
409
|
+
g = grad
|
|
410
|
+
side_grads = {}
|
|
411
|
+
plan, carry_grads = box.state["plan"], {}
|
|
412
|
+
for ci in reversed(range(len(self.cores))):
|
|
413
|
+
core, (x, args, leaves, carry) = self.cores[ci], box.state["steps"][ci]
|
|
414
|
+
if plan:
|
|
415
|
+
g, sides, carry_grads = core.backward(x, args, leaves, g, carry, carry_grads, plan, key=(id(box), ci))
|
|
416
|
+
else:
|
|
417
|
+
g, sides = core.backward(x, args, leaves, g, key=(id(box), ci))
|
|
418
|
+
for k, v in sides.items():
|
|
419
|
+
if v is not None:
|
|
420
|
+
side_grads[k] = side_grads.get(k, 0) + v.float().cpu()
|
|
421
|
+
index = {id(s): i for i, s in enumerate(box.sides)}
|
|
422
|
+
out = [None] * len(box.sides)
|
|
423
|
+
for k, s in enumerate(box.state["packed_sides"]):
|
|
424
|
+
if k in side_grads and id(s) in index:
|
|
425
|
+
out[index[id(s)]] = side_grads[k].to(s.dtype)
|
|
426
|
+
norm = math.sqrt(sum(c.grad_sq() for c in self.cores))
|
|
427
|
+
return g.to("cpu", box.hidden.dtype), out, norm
|
layerpool/export.py
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import os
|
|
3
|
+
import re
|
|
4
|
+
|
|
5
|
+
import numpy as np
|
|
6
|
+
|
|
7
|
+
from .blocks import load_config
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def _split(key: str) -> tuple[int, str, str]:
|
|
11
|
+
block, rest = key.split(".", 1)
|
|
12
|
+
module, which = rest.rsplit(".", 1)
|
|
13
|
+
return int(block), module, which
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
_TASKS = {"AutoModelForCausalLM": "CAUSAL_LM", "AutoModelForSequenceClassification": "SEQ_CLS", "AutoModelForTokenClassification": "TOKEN_CLS",
|
|
17
|
+
"AutoModelForSeq2SeqLM": "SEQ_2_SEQ_LM", "AutoModelForQuestionAnswering": "QUESTION_ANS", "AutoModel": "FEATURE_EXTRACTION"}
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def export_peft(adapter: dict[str, np.ndarray], out_dir: str, job: dict) -> str:
|
|
21
|
+
"""A PEFT LoRA adapter folder: load it with peft.PeftModel.from_pretrained(base_model, out_dir)."""
|
|
22
|
+
from safetensors.numpy import save_file
|
|
23
|
+
stack, rank, scale = job["layout"]["stack"], job["rank"], job["scale"]
|
|
24
|
+
os.makedirs(out_dir, exist_ok=True)
|
|
25
|
+
tensors, modules = {}, set()
|
|
26
|
+
for key, value in adapter.items():
|
|
27
|
+
i, module, which = _split(key)
|
|
28
|
+
modules.add(module)
|
|
29
|
+
tensors[f"base_model.model.{stack}.{i}.{module}.lora_{which}.weight"] = np.ascontiguousarray(value, dtype=np.float32)
|
|
30
|
+
save_file(tensors, os.path.join(out_dir, "adapter_model.safetensors"))
|
|
31
|
+
pattern = rf"^{re.escape(stack)}\.\d+\.({'|'.join(re.escape(m) for m in sorted(modules))})$"
|
|
32
|
+
config = {"peft_type": "LORA", "task_type": _TASKS.get(job.get("auto")),
|
|
33
|
+
"base_model_name_or_path": job["repo"], "r": rank, "lora_alpha": scale * rank, "lora_dropout": 0.0, "bias": "none",
|
|
34
|
+
"fan_in_fan_out": False, "inference_mode": True, "use_rslora": False, "target_modules": pattern}
|
|
35
|
+
with open(os.path.join(out_dir, "adapter_config.json"), "w", encoding="utf-8") as f:
|
|
36
|
+
json.dump(config, f, indent=2)
|
|
37
|
+
if job.get("mlx_ok"):
|
|
38
|
+
where = _mlx_layers_path(job)
|
|
39
|
+
if where:
|
|
40
|
+
_export_mlx(adapter, os.path.join(out_dir, "mlx"), job, where)
|
|
41
|
+
return out_dir
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _mlx_layers_path(job: dict) -> str | None:
|
|
45
|
+
"""Where mlx-lm keeps this model's blocks (model.layers, or language_model.model.layers in a vision-language family), so the
|
|
46
|
+
MLX copy of the adapter loads with mlx_lm.generate. Asked of mlx-lm when it is installed here; otherwise only a plain text
|
|
47
|
+
model's path is known."""
|
|
48
|
+
repo = job.get("mlx_repo") or job["repo"]
|
|
49
|
+
try:
|
|
50
|
+
from .backends.mlx_backend import layers_path
|
|
51
|
+
return layers_path(repo, job["layers"])
|
|
52
|
+
except ImportError:
|
|
53
|
+
from .job import load_config
|
|
54
|
+
return None if "text_config" in load_config(repo) else "model.layers"
|
|
55
|
+
except Exception:
|
|
56
|
+
return None
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _export_mlx(adapter: dict[str, np.ndarray], out_dir: str, job: dict, where: str = "model.layers"):
|
|
60
|
+
"""The same adapter in mlx-lm's format: `mlx_lm.generate --model <base> --adapter-path <out>/mlx`."""
|
|
61
|
+
from safetensors.numpy import save_file
|
|
62
|
+
os.makedirs(out_dir, exist_ok=True)
|
|
63
|
+
tensors, modules = {}, set()
|
|
64
|
+
for key, value in adapter.items():
|
|
65
|
+
i, module, which = _split(key)
|
|
66
|
+
modules.add(module)
|
|
67
|
+
tensors[f"{where}.{i}.{module}.lora_{which.lower()}"] = np.ascontiguousarray(np.asarray(value, dtype=np.float32).T)
|
|
68
|
+
save_file(tensors, os.path.join(out_dir, "adapters.safetensors"))
|
|
69
|
+
config = {"fine_tune_type": "lora", "num_layers": job["layers"],
|
|
70
|
+
"lora_parameters": {"rank": job["rank"], "scale": job["scale"], "dropout": 0.0, "keys": sorted(modules)}}
|
|
71
|
+
with open(os.path.join(out_dir, "adapter_config.json"), "w", encoding="utf-8") as f:
|
|
72
|
+
json.dump(config, f, indent=2)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def add_saved_modules(model, out_dir: str, modules: list[str]):
|
|
76
|
+
"""The modules a LoRA run trained in full, added to its PEFT adapter as modules_to_save."""
|
|
77
|
+
from safetensors.numpy import load_file, save_file
|
|
78
|
+
path = os.path.join(out_dir, "adapter_model.safetensors")
|
|
79
|
+
tensors = load_file(path)
|
|
80
|
+
for name, p in model.named_parameters():
|
|
81
|
+
if any(name.startswith(m + ".") for m in modules):
|
|
82
|
+
tensors[f"base_model.model.{name}"] = np.ascontiguousarray(p.detach().float().cpu().numpy())
|
|
83
|
+
save_file(tensors, path)
|
|
84
|
+
with open(os.path.join(out_dir, "adapter_config.json"), encoding="utf-8") as f:
|
|
85
|
+
config = json.load(f)
|
|
86
|
+
config["modules_to_save"] = sorted(modules)
|
|
87
|
+
with open(os.path.join(out_dir, "adapter_config.json"), "w", encoding="utf-8") as f:
|
|
88
|
+
json.dump(config, f, indent=2)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
BLOCKS_FILE = "model-blocks.safetensors"
|
|
92
|
+
ENDS_FILE = "model-ends.safetensors"
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _dtype(name: str):
|
|
96
|
+
import torch
|
|
97
|
+
return {"bfloat16": torch.bfloat16, "float16": torch.float16, "float32": torch.float32}[name]
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def export_blocks(weights: dict[str, np.ndarray], out_dir: str, job: dict, dtype: str = "bfloat16") -> str:
|
|
101
|
+
"""The trained blocks of a full fine-tuning run, under their names in the model. The rest of the model is written by the
|
|
102
|
+
training process (write_ends), which holds it."""
|
|
103
|
+
import torch
|
|
104
|
+
from safetensors.torch import save_file
|
|
105
|
+
os.makedirs(out_dir, exist_ok=True)
|
|
106
|
+
stack = job["layout"]["stack"]
|
|
107
|
+
target = _dtype(dtype)
|
|
108
|
+
tensors = {}
|
|
109
|
+
for key, value in weights.items():
|
|
110
|
+
block, name = key.split(".", 1)
|
|
111
|
+
tensors[f"{stack}.{block}.{name}"] = torch.tensor(np.ascontiguousarray(value)).to(target)
|
|
112
|
+
save_file(tensors, os.path.join(out_dir, BLOCKS_FILE), metadata={"format": "pt"})
|
|
113
|
+
return out_dir
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def write_ends(model, out_dir: str, job: dict, dtype: str = "bfloat16"):
|
|
117
|
+
"""The modules around the blocks, the config, the index of both files and the tokenizer: the folder then loads with
|
|
118
|
+
transformers like any model."""
|
|
119
|
+
from safetensors import safe_open
|
|
120
|
+
from safetensors.torch import save_file
|
|
121
|
+
stack = job["layout"]["stack"] + "."
|
|
122
|
+
target = _dtype(dtype)
|
|
123
|
+
seen, unique = set(), {}
|
|
124
|
+
for k, v in model.state_dict().items():
|
|
125
|
+
if k.startswith(stack) or k == "layerpool_anchor" or v.data_ptr() in seen:
|
|
126
|
+
continue
|
|
127
|
+
seen.add(v.data_ptr())
|
|
128
|
+
unique[k] = v.detach().to(target).contiguous()
|
|
129
|
+
save_file(unique, os.path.join(out_dir, ENDS_FILE), metadata={"format": "pt"})
|
|
130
|
+
index = {}
|
|
131
|
+
for name in (BLOCKS_FILE, ENDS_FILE):
|
|
132
|
+
with safe_open(os.path.join(out_dir, name), framework="pt") as f:
|
|
133
|
+
index.update({k: name for k in f.keys()})
|
|
134
|
+
with open(os.path.join(out_dir, "model.safetensors.index.json"), "w", encoding="utf-8") as f:
|
|
135
|
+
json.dump({"metadata": {}, "weight_map": index}, f, indent=1)
|
|
136
|
+
config = load_config(job["repo"])
|
|
137
|
+
for key, value in job.get("config", {}).items():
|
|
138
|
+
setattr(config, key, value)
|
|
139
|
+
if hasattr(config, "dtype") and "torch_dtype" not in config.__dict__:
|
|
140
|
+
config.dtype = dtype
|
|
141
|
+
else:
|
|
142
|
+
config.torch_dtype = dtype
|
|
143
|
+
if hasattr(config, "quantization_config"):
|
|
144
|
+
delattr(config, "quantization_config")
|
|
145
|
+
config.save_pretrained(out_dir)
|
|
146
|
+
write_extras(job["repo"], out_dir)
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def write_extras(repo: str, out_dir: str):
|
|
150
|
+
"""What the source model has besides its weights: the generation settings and the tokenizer, and the processor of an image or
|
|
151
|
+
speech model (its image processor or feature extractor), so AutoProcessor and generate() work on the folder."""
|
|
152
|
+
import transformers
|
|
153
|
+
for kind in ("GenerationConfig", "AutoProcessor", "AutoTokenizer"):
|
|
154
|
+
try:
|
|
155
|
+
getattr(transformers, kind).from_pretrained(repo).save_pretrained(out_dir)
|
|
156
|
+
except Exception:
|
|
157
|
+
pass
|