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/net.py ADDED
@@ -0,0 +1,529 @@
1
+ import hmac
2
+ import http.client
3
+ import json
4
+ import queue
5
+ import secrets
6
+ import socket
7
+ import ssl
8
+ import sys
9
+ import threading
10
+ import time
11
+ import urllib.error
12
+ from concurrent.futures import ThreadPoolExecutor
13
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
14
+ from urllib.parse import parse_qs, urlparse
15
+
16
+
17
+ class HTTPError(urllib.error.HTTPError):
18
+ def __init__(self, url: str, code: int, detail: str = ""):
19
+ super().__init__(url, code, detail or f"HTTP {code}", None, None)
20
+ self.detail = detail
21
+
22
+ def __str__(self):
23
+ return f"HTTP {self.code}: {self.detail}" if self.detail else f"HTTP {self.code}"
24
+
25
+
26
+ def _detail(body: bytes) -> str:
27
+ text = body.decode("utf-8", "replace").strip()
28
+ try:
29
+ found = json.loads(text)
30
+ if isinstance(found, dict) and found.get("error"):
31
+ return str(found["error"])
32
+ except ValueError:
33
+ pass
34
+ return text[:500]
35
+
36
+ CHUNK = 16 << 20
37
+ MAX_BODY = 256 << 20
38
+ UPLOAD_TTL_S = 600
39
+
40
+
41
+ class Cancelled(ConnectionError):
42
+ pass
43
+
44
+
45
+ class Inbox:
46
+ def __init__(self):
47
+ self.items: dict[tuple, bytes] = {}
48
+ self.parts: dict[tuple, dict[int, bytes]] = {}
49
+ self.taken: dict[tuple, None] = {}
50
+ self.cond = threading.Condition()
51
+
52
+ def put(self, key: tuple, data: bytes, part: int = 0, parts: int = 1):
53
+ with self.cond:
54
+ if key in self.taken or key in self.items:
55
+ return
56
+ if parts == 1:
57
+ self.items[key] = data
58
+ else:
59
+ got = self.parts.setdefault(key, {})
60
+ got[part] = data
61
+ if len(got) == parts:
62
+ self.items[key] = b"".join(got[i] for i in range(parts))
63
+ del self.parts[key]
64
+ self.cond.notify_all()
65
+
66
+ def get(self, key: tuple, timeout: float | None = None, cancel=None) -> bytes | None:
67
+ deadline = None if timeout is None else time.time() + timeout
68
+ with self.cond:
69
+ while key not in self.items:
70
+ if cancel is not None and cancel():
71
+ return None
72
+ left = None if deadline is None else deadline - time.time()
73
+ if left is not None and left <= 0:
74
+ return None
75
+ self.cond.wait(timeout=0.5 if left is None else min(0.5, left))
76
+ self.taken[key] = None
77
+ if len(self.taken) > 4096:
78
+ del self.taken[next(iter(self.taken))]
79
+ return self.items.pop(key)
80
+
81
+ def drop(self, keep):
82
+ with self.cond:
83
+ for key in [k for k in self.items if not keep(k)]:
84
+ del self.items[key]
85
+ for key in [k for k in self.parts if not keep(k)]:
86
+ del self.parts[key]
87
+ for key in [k for k in self.taken if not keep(k)]:
88
+ del self.taken[key]
89
+
90
+
91
+ class _Server(ThreadingHTTPServer):
92
+ def handle_error(self, request, client_address):
93
+ if isinstance(sys.exc_info()[1], (ConnectionError, TimeoutError)):
94
+ return
95
+ super().handle_error(request, client_address)
96
+
97
+
98
+ class PeerServer:
99
+ def __init__(self, port: int = 0, token: str | None = None, routes: dict | None = None, host: str = "0.0.0.0", check=None,
100
+ limits: dict | None = None):
101
+ self.token = token or secrets.token_hex(16)
102
+ self.limits = limits or {}
103
+ self.inbox = Inbox()
104
+ self.routes = routes or {}
105
+ self.uploads: dict[tuple, dict[int, bytes]] = {}
106
+ self.upload_times: dict[tuple, float] = {}
107
+ self.uploads_lock = threading.Lock()
108
+ self.served: dict[tuple, tuple[float, int, bytes]] = {}
109
+ self.check = check
110
+ self.closed = False
111
+ server = self
112
+
113
+ class Handler(BaseHTTPRequestHandler):
114
+ protocol_version = "HTTP/1.1"
115
+ timeout = 300
116
+
117
+ def log_message(self, *args):
118
+ pass
119
+
120
+ def reply(self, code: int, body: bytes = b"", content_type: str | None = None, headers: dict | None = None):
121
+ self.send_response(code)
122
+ self.send_header("Content-Length", str(len(body)))
123
+ if content_type:
124
+ self.send_header("Content-Type", content_type)
125
+ for k, v in (headers or {}).items():
126
+ self.send_header(k, v)
127
+ self.end_headers()
128
+ self.wfile.write(body)
129
+
130
+ def stream(self, code: int, source):
131
+ self.send_response(code)
132
+ self.send_header("Content-Type", getattr(source, "content_type", "text/event-stream"))
133
+ self.send_header("Cache-Control", "no-cache")
134
+ self.send_header("Connection", "close")
135
+ self.end_headers()
136
+ self.close_connection = True
137
+ try:
138
+ for piece in source:
139
+ self.wfile.write(piece)
140
+ self.wfile.flush()
141
+ except (BrokenPipeError, ConnectionResetError):
142
+ pass
143
+ finally:
144
+ close = getattr(source, "close", None)
145
+ if close:
146
+ close()
147
+
148
+ def read_chunked(self, most: int):
149
+ """A body sent in chunks (what tunnels such as Cloudflare's send), whole; "large" past the limit, None when the
150
+ connection broke inside it."""
151
+ parts, total = [], 0
152
+ while True:
153
+ line = self.rfile.readline(1024)
154
+ if not line.endswith(b"\n"):
155
+ return None
156
+ try:
157
+ size = int(line.split(b";")[0].strip() or b"0", 16)
158
+ except ValueError:
159
+ return None
160
+ if size == 0:
161
+ while True:
162
+ trailer = self.rfile.readline(1024)
163
+ if trailer in (b"\r\n", b"\n"):
164
+ return b"".join(parts)
165
+ if not trailer.endswith(b"\n"):
166
+ return None
167
+ total += size
168
+ if total > most:
169
+ return "large"
170
+ data = self.rfile.read(size)
171
+ if len(data) != size or self.rfile.readline(1024) not in (b"\r\n", b"\n"):
172
+ return None
173
+ parts.append(data)
174
+
175
+ def handle_any(self, method: str):
176
+ url = urlparse(self.path)
177
+ query = {k: v[0] for k, v in parse_qs(url.query).items()}
178
+ if server.closed:
179
+ self.close_connection = True
180
+ return self.reply(503)
181
+ if url.path == "/ping":
182
+ return self.reply(200, b"pong")
183
+ if server.check is not None:
184
+ verdict = server.check(self, method, url.path, query)
185
+ if verdict is not None:
186
+ code, out = verdict
187
+ if isinstance(out, (dict, list)):
188
+ out = json.dumps(out).encode()
189
+ self.close_connection = True
190
+ return self.reply(code, out or b"")
191
+ elif not hmac.compare_digest((self.headers.get("X-Token") or "").encode("utf-8", "surrogateescape"), server.token.encode()):
192
+ self.close_connection = True
193
+ return self.reply(403)
194
+ most = server.limits.get(url.path, MAX_BODY)
195
+ if method == "POST" and "chunked" in (self.headers.get("Transfer-Encoding") or "").lower():
196
+ body = self.read_chunked(most)
197
+ if not isinstance(body, bytes):
198
+ self.close_connection = True
199
+ return self.reply(413) if body == "large" else None
200
+ else:
201
+ try:
202
+ length = int(self.headers.get("Content-Length") or 0)
203
+ except ValueError:
204
+ length = -1
205
+ if length < 0 or length > most:
206
+ self.close_connection = True
207
+ return self.reply(413 if length > most else 400)
208
+ body = self.rfile.read(length) if method == "POST" else b""
209
+ if len(body) != (length if method == "POST" else 0):
210
+ self.close_connection = True
211
+ return
212
+ try:
213
+ return self.route(method, url, query, body)
214
+ except (KeyError, ValueError) as e:
215
+ return self.reply(400, json.dumps({"error": repr(e)}).encode())
216
+ except Exception as e:
217
+ return self.reply(500, json.dumps({"error": repr(e)}).encode())
218
+
219
+ def route(self, method: str, url, query: dict, body: bytes):
220
+ if url.path == "/msg" and method == "POST":
221
+ key = tuple(query["key"].split(","))
222
+ server.inbox.put(key, body, int(query.get("part", 0)), int(query.get("parts", 1)))
223
+ return self.reply(200)
224
+ route = server.routes.get((method, url.path))
225
+ if route is None:
226
+ return self.reply(404)
227
+ with server.uploads_lock:
228
+ now = time.time()
229
+ for old in [k for k, t in server.upload_times.items() if now - t > UPLOAD_TTL_S]:
230
+ server.uploads.pop(old, None)
231
+ server.upload_times.pop(old, None)
232
+ for old in [k for k, v in server.served.items() if now - v[0] > 120]:
233
+ server.served.pop(old, None)
234
+ upload = None
235
+ if method == "POST" and "blob_parts" in query:
236
+ parts, part = int(query.pop("blob_parts")), int(query.pop("blob_part"))
237
+ upload = (url.path, tuple(sorted(query.items())))
238
+ query.pop("blob_id", None)
239
+ with server.uploads_lock:
240
+ now = time.time()
241
+ got = server.uploads.setdefault(upload, {})
242
+ server.upload_times[upload] = now
243
+ got[part] = body
244
+ if len(got) < parts:
245
+ return self.reply(200)
246
+ body = b"".join(got[i] for i in range(parts))
247
+ chunk = query.pop("blob_chunk", None)
248
+ sizing = query.pop("blob_size", None)
249
+ cache_key = (url.path, tuple(sorted(query.items())))
250
+ content_type, extra_headers = None, None
251
+ with server.uploads_lock:
252
+ cached = server.served.get(cache_key) if chunk is not None else None
253
+ if cached:
254
+ server.served[cache_key] = (time.time(), cached[1], cached[2])
255
+ if cached:
256
+ code, out = cached[1], cached[2]
257
+ else:
258
+ answer = route(query, body)
259
+ code, out = answer[0], answer[1]
260
+ content_type = answer[2] if len(answer) > 2 else None
261
+ extra_headers = answer[3] if len(answer) > 3 else None
262
+ if upload is not None:
263
+ with server.uploads_lock:
264
+ if code == 200:
265
+ server.uploads.pop(upload, None)
266
+ server.upload_times.pop(upload, None)
267
+ if hasattr(out, "content_type") and hasattr(out, "__iter__"):
268
+ return self.stream(code, out)
269
+ if isinstance(out, (dict, list)):
270
+ out = json.dumps(out).encode()
271
+ out = out or b""
272
+ if code == 200 and sizing is not None:
273
+ if len(out) > CHUNK:
274
+ with server.uploads_lock:
275
+ server.served[cache_key] = (time.time(), code, out)
276
+ return self.reply(200, json.dumps({"size": len(out)}).encode())
277
+ if code == 200 and chunk is not None:
278
+ if cached and (int(chunk) + 1) * CHUNK >= len(out):
279
+ with server.uploads_lock:
280
+ server.served.pop(cache_key, None)
281
+ out = out[int(chunk) * CHUNK:(int(chunk) + 1) * CHUNK]
282
+ return self.reply(code, out, content_type, extra_headers)
283
+
284
+ def do_GET(self):
285
+ self.handle_any("GET")
286
+
287
+ def do_POST(self):
288
+ self.handle_any("POST")
289
+
290
+ self.httpd = _Server((host, port), Handler)
291
+ self.httpd.daemon_threads = True
292
+ self.port = self.httpd.server_address[1]
293
+ threading.Thread(target=self.httpd.serve_forever, daemon=True).start()
294
+
295
+ def lan_url(self) -> str:
296
+ return f"http://{lan_ip()}:{self.port}"
297
+
298
+ def url_at(self, address: str) -> str:
299
+ """An address given by hand (http://10.0.0.5:7400, or just 10.0.0.5 for this server's own port) as a full URL."""
300
+ address = address if "://" in address else f"http://{address}"
301
+ parsed = urlparse(address)
302
+ return address if parsed.port or parsed.scheme == "https" else f"{address.rstrip('/')}:{self.port}"
303
+
304
+ def close(self):
305
+ self.closed = True
306
+ self.httpd.shutdown()
307
+ self.httpd.server_close()
308
+
309
+
310
+ def lan_ip() -> str:
311
+ s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
312
+ try:
313
+ s.connect(("10.255.255.255", 1))
314
+ return s.getsockname()[0]
315
+ except OSError:
316
+ return "127.0.0.1"
317
+ finally:
318
+ s.close()
319
+
320
+
321
+ _resolved: dict[str, tuple[str, float]] = {}
322
+
323
+
324
+ def _ask_public_dns(host: str) -> str | None:
325
+ for server, path in (("1.1.1.1", "/dns-query"), ("8.8.8.8", "/resolve")):
326
+ try:
327
+ conn = http.client.HTTPSConnection(server, timeout=5, context=ssl.create_default_context())
328
+ conn.request("GET", f"{path}?name={host}&type=A", headers={"Accept": "application/dns-json"})
329
+ answer = json.loads(conn.getresponse().read())
330
+ conn.close()
331
+ for record in answer.get("Answer") or []:
332
+ if record.get("type") == 1:
333
+ return record["data"]
334
+ except Exception:
335
+ continue
336
+ return None
337
+
338
+
339
+ def resolve(host: str) -> str:
340
+ """The address to connect to. A fresh tunnel name is often cached as missing by the local resolver for many
341
+ minutes, so when the system cannot find a name, ask public DNS over HTTPS instead."""
342
+ try:
343
+ socket.getaddrinfo(host, None)
344
+ return host
345
+ except socket.gaierror:
346
+ cached = _resolved.get(host)
347
+ if cached and cached[1] > time.time():
348
+ return cached[0]
349
+ ip = _ask_public_dns(host)
350
+ if ip is None:
351
+ raise
352
+ _resolved[host] = (ip, time.time() + 300)
353
+ return ip
354
+
355
+
356
+ class _HTTPSConnection(http.client.HTTPSConnection):
357
+ def __init__(self, host, port=None, timeout=None, context=None):
358
+ super().__init__(host, port, timeout=timeout, context=context)
359
+ self.tls = context
360
+
361
+ def connect(self):
362
+ sock = socket.create_connection((resolve(self.host), self.port or 443), self.timeout, self.source_address)
363
+ sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
364
+ self.sock = self.tls.wrap_socket(sock, server_hostname=self.host)
365
+
366
+
367
+ def connection(url: str, timeout: float):
368
+ parsed = urlparse(url)
369
+ if parsed.scheme == "https":
370
+ return _HTTPSConnection(parsed.hostname, parsed.port, timeout=timeout, context=ssl.create_default_context())
371
+ return http.client.HTTPConnection(parsed.hostname, parsed.port, timeout=timeout)
372
+
373
+
374
+ def ping(url: str, timeout: float = 10) -> bool:
375
+ conn = connection(url, timeout)
376
+ try:
377
+ conn.request("GET", "/ping")
378
+ r = conn.getresponse()
379
+ return r.status == 200 and r.read() == b"pong"
380
+ except Exception:
381
+ return False
382
+ finally:
383
+ conn.close()
384
+
385
+
386
+ class Peer:
387
+ def __init__(self, urls: list[str], token: str):
388
+ self.urls = [u for u in urls if u]
389
+ self.token = token
390
+ self.url = None
391
+ self.local = threading.local()
392
+
393
+ def _connection(self, url: str, timeout: float):
394
+ conns = getattr(self.local, "conns", None)
395
+ if conns is None:
396
+ conns = self.local.conns = {}
397
+ conn = conns.get(url)
398
+ if conn is None:
399
+ conn = conns[url] = connection(url, timeout)
400
+ conn.timeout = timeout
401
+ if conn.sock is not None:
402
+ conn.sock.settimeout(timeout)
403
+ return conn
404
+
405
+ def _drop(self, url: str):
406
+ conn = getattr(self.local, "conns", {}).pop(url, None)
407
+ if conn is not None:
408
+ conn.close()
409
+
410
+ def pick(self) -> str:
411
+ if self.url:
412
+ return self.url
413
+ for u in self.urls:
414
+ if ping(u, 2 if u.startswith("http://") else 15):
415
+ self.url = u
416
+ return u
417
+ raise ConnectionError(f"no address of this peer answers: {self.urls}")
418
+
419
+ def request(self, path: str, data: bytes | None = None, timeout: float = 90, retries: int = 5, cancel=None) -> bytes:
420
+ last = None
421
+ for attempt in range(retries):
422
+ if cancel is not None and cancel():
423
+ raise Cancelled(path)
424
+ url = None
425
+ try:
426
+ url = self.pick()
427
+ conn = self._connection(url, timeout)
428
+ conn.request("POST" if data is not None else "GET", path, body=data, headers={"X-Token": self.token or "", "Content-Length": str(len(data or b""))})
429
+ r = conn.getresponse()
430
+ body = r.read()
431
+ if r.status >= 400:
432
+ raise HTTPError(url + path, r.status, _detail(body))
433
+ return body
434
+ except urllib.error.HTTPError as e:
435
+ if e.code in (400, 403, 404, 409, 410, 413):
436
+ raise
437
+ last = e
438
+ if url:
439
+ self._drop(url)
440
+ except Exception as e:
441
+ last = e
442
+ if url:
443
+ self._drop(url)
444
+ self.url = None
445
+ if attempt == retries - 1:
446
+ break
447
+ pause = time.time() + min(2 ** attempt, 10)
448
+ while time.time() < pause and not (cancel is not None and cancel()):
449
+ time.sleep(0.1)
450
+ raise ConnectionError(f"request {path} failed: {last!r}")
451
+
452
+ def send(self, key: tuple, data: bytes, cancel=None, retries: int = 5):
453
+ k = ",".join(str(x) for x in key)
454
+ if len(data) <= CHUNK:
455
+ self.request(f"/msg?key={k}", data, cancel=cancel, retries=retries)
456
+ return
457
+ parts = (len(data) + CHUNK - 1) // CHUNK
458
+ view = memoryview(data)
459
+ with ThreadPoolExecutor(max_workers=4) as pool:
460
+ for future in [pool.submit(self.request, f"/msg?key={k}&part={i}&parts={parts}", view[i * CHUNK:(i + 1) * CHUNK], cancel=cancel,
461
+ retries=retries) for i in range(parts)]:
462
+ future.result()
463
+
464
+ def post_blob(self, path: str, data: bytes, timeout: float = 120, retries: int = 5, cancel=None):
465
+ if len(data) <= CHUNK:
466
+ return self.request(path, data, timeout=timeout, retries=retries, cancel=cancel)
467
+ parts = (len(data) + CHUNK - 1) // CHUNK
468
+ sep = "&" if "?" in path else "?"
469
+ blob = secrets.token_hex(6)
470
+ view = memoryview(data)
471
+ for i in range(parts):
472
+ self.request(f"{path}{sep}blob_id={blob}&blob_part={i}&blob_parts={parts}", view[i * CHUNK:(i + 1) * CHUNK], timeout=timeout,
473
+ retries=retries, cancel=cancel)
474
+ return b""
475
+
476
+ def get_blob(self, path: str, timeout: float = 120, retries: int = 5) -> bytes:
477
+ sep = "&" if "?" in path else "?"
478
+ size = json.loads(self.request(f"{path}{sep}blob_size=1", timeout=timeout, retries=retries))["size"]
479
+ if size <= CHUNK:
480
+ return self.request(path, timeout=timeout, retries=retries)
481
+ return b"".join(self.request(f"{path}{sep}blob_chunk={i}", timeout=timeout, retries=retries) for i in range((size + CHUNK - 1) // CHUNK))
482
+
483
+ def json(self, path: str, payload=None, timeout: float = 90):
484
+ body = None if payload is None else json.dumps(payload).encode()
485
+ out = self.request(path, body, timeout=timeout)
486
+ return json.loads(out) if out else None
487
+
488
+
489
+ class Sender:
490
+ def __init__(self, peer: Peer, streams: int = 3, cancel=None):
491
+ self.peer, self.cancel = peer, cancel
492
+ self.jobs: queue.Queue = queue.Queue()
493
+ self.errors: list[Exception] = []
494
+ self.busy = 0.0
495
+ self.lock = threading.Lock()
496
+ self.threads = [threading.Thread(target=self._run, daemon=True) for _ in range(streams)]
497
+ [t.start() for t in self.threads]
498
+
499
+ def _run(self):
500
+ while True:
501
+ job = self.jobs.get()
502
+ if job is None:
503
+ self.jobs.task_done()
504
+ return
505
+ key, data = job
506
+ t = time.time()
507
+ try:
508
+ if not self.errors:
509
+ self.peer.send(key, data, cancel=self.cancel)
510
+ except Exception as e:
511
+ self.errors.append(e)
512
+ finally:
513
+ with self.lock:
514
+ self.busy += time.time() - t
515
+ self.jobs.task_done()
516
+
517
+ def put(self, key: tuple, data: bytes):
518
+ if self.errors:
519
+ raise self.errors[0]
520
+ self.jobs.put((key, data))
521
+
522
+ def flush(self):
523
+ self.jobs.join()
524
+ if self.errors:
525
+ raise self.errors[0]
526
+
527
+ def close(self):
528
+ for _ in self.threads:
529
+ self.jobs.put(None)
layerpool/planner.py ADDED
@@ -0,0 +1,104 @@
1
+ import math
2
+ from dataclasses import dataclass
3
+
4
+
5
+ @dataclass
6
+ class Node:
7
+ name: str
8
+ cap_gb: float
9
+ fixed_gb: float
10
+ sec_per_layer: float
11
+ max_layers: int | None = None
12
+ layer_gb: float | None = None
13
+ min_layers: int = 0
14
+ link_sec: float = 0.0
15
+ spill_gb: float = 0.0
16
+ spill_layer_gb: float = 0.0
17
+ spill_sec_per_layer: float = 0.0
18
+
19
+ def on_gpu(self, count: int, layer_gb: float) -> int:
20
+ """How many of `count` layers the device's own memory holds; with spill_gb, the rest go to its RAM (its CPU runs them)."""
21
+ if not self.spill_gb:
22
+ return count
23
+ per = self.layer_gb if self.layer_gb is not None else layer_gb
24
+ room = int(max(0.0, self.cap_gb - self.fixed_gb) / per) if per > 0 else count
25
+ return min(count, room)
26
+
27
+ def fits(self, count: int, layer_gb: float) -> bool:
28
+ if self.max_layers is not None and count > self.max_layers or count < self.min_layers:
29
+ return False
30
+ per = self.layer_gb if self.layer_gb is not None else layer_gb
31
+ fast = self.on_gpu(count, layer_gb)
32
+ if self.fixed_gb + fast * per > self.cap_gb:
33
+ return False
34
+ return (count - fast) * self.spill_layer_gb <= self.spill_gb
35
+
36
+ def seconds(self, count: int, layer_gb: float) -> float:
37
+ """Time per step: the GPU part and the RAM part work as a pipeline, so the slower of the two sets the pace."""
38
+ fast = self.on_gpu(count, layer_gb)
39
+ return max(self.sec_per_layer * fast, self.spill_sec_per_layer * (count - fast)) + self.link_sec
40
+
41
+
42
+ @dataclass
43
+ class Stage:
44
+ name: str
45
+ first: int
46
+ last: int
47
+ gb: float
48
+ sec: float
49
+ on_gpu: int | None = None
50
+
51
+
52
+ def layer_bounds(spec, n_layers: int) -> tuple[int, int | None]:
53
+ """A device's layer setting as (fewest, most): "auto" or None, a count ("8"), a share of the model ("30%") or a range ("4-10")."""
54
+ if spec in (None, "", "auto"):
55
+ return 0, None
56
+ text = str(spec).strip()
57
+ if text.endswith("%"):
58
+ exact = n_layers * float(text[:-1]) / 100
59
+ return max(1, math.floor(exact)), max(1, math.ceil(exact))
60
+ if "-" in text:
61
+ low, high = (int(x) for x in text.split("-", 1))
62
+ return low, high
63
+ return int(text), int(text)
64
+
65
+
66
+ def plan(nodes: list[Node], n_layers: int, layer_gb: float) -> list[Stage] | None:
67
+ """Split the layers so the slowest stage (its compute plus its sending) is as fast as possible."""
68
+ n = len(nodes)
69
+ if n == 0 or n > n_layers:
70
+ return None
71
+
72
+ def fits(node: Node, count: int) -> bool:
73
+ return node.fits(count, layer_gb)
74
+
75
+ inf = float("inf")
76
+ best = [[inf] * (n_layers + 1) for _ in range(n + 1)]
77
+ choice = [[0] * (n_layers + 1) for _ in range(n + 1)]
78
+ best[0][0] = 0.0
79
+ for i in range(1, n + 1):
80
+ node = nodes[i - 1]
81
+ for used in range(i, n_layers - (n - i) + 1):
82
+ for count in range(1, used - (i - 1) + 1):
83
+ prev = best[i - 1][used - count]
84
+ if prev == inf or not fits(node, count):
85
+ continue
86
+ cost = max(prev, node.seconds(count, layer_gb))
87
+ if cost < best[i][used]:
88
+ best[i][used] = cost
89
+ choice[i][used] = count
90
+ if best[n][n_layers] == inf:
91
+ return None
92
+ counts, used = [], n_layers
93
+ for i in range(n, 0, -1):
94
+ counts.append(choice[i][used])
95
+ used -= choice[i][used]
96
+ counts.reverse()
97
+ stages, first = [], 0
98
+ for node, count in zip(nodes, counts):
99
+ fast = node.on_gpu(count, layer_gb)
100
+ gb = node.fixed_gb + fast * (layer_gb if node.layer_gb is None else node.layer_gb)
101
+ stages.append(Stage(node.name, first, first + count, round(gb, 2), round(node.seconds(count, layer_gb), 3),
102
+ fast if node.spill_gb else None))
103
+ first += count
104
+ return stages