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/selfcheck.py
ADDED
|
@@ -0,0 +1,348 @@
|
|
|
1
|
+
"""Before a run, a small copy of the model's own architecture is split the way the run will split it and compared with the whole
|
|
2
|
+
copy. A model whose split would compute something else (an architecture layerpool does not handle yet, or one added to
|
|
3
|
+
transformers later) is stopped here with a clear message instead of training wrong. Each architecture is checked once per
|
|
4
|
+
transformers version."""
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
import tempfile
|
|
8
|
+
|
|
9
|
+
from . import __version__
|
|
10
|
+
from .blocks import BlockCore, layout, load_blocks, load_config, load_ends
|
|
11
|
+
from .codec import replace_file
|
|
12
|
+
from .driver import Ends, LocalChain
|
|
13
|
+
|
|
14
|
+
CACHE = os.path.join(os.path.expanduser("~"), ".cache", "layerpool", "checked.json")
|
|
15
|
+
SIZE = {
|
|
16
|
+
"hidden_size": 64, "d_model": 64, "n_embd": 64, "embed_dim": 64, "dim": 64, "n_embed": 64, "out_hidden_size": 64,
|
|
17
|
+
"intermediate_size": 128, "ffn_dim": 128, "encoder_ffn_dim": 128, "decoder_ffn_dim": 128, "d_ff": 128, "n_inner": 128,
|
|
18
|
+
"hidden_dim": 128, "decoder_intermediate_size": 128,
|
|
19
|
+
"num_attention_heads": 4, "n_head": 4, "encoder_attention_heads": 4, "decoder_attention_heads": 4, "num_heads": 4,
|
|
20
|
+
"n_heads": 4, "decoder_num_attention_heads": 4,
|
|
21
|
+
"num_key_value_heads": 2, "num_kv_heads": 2, "multi_query_group_num": 2, "decoder_num_key_value_heads": 2,
|
|
22
|
+
"head_dim": 16, "kv_channels": 16, "d_kv": 16,
|
|
23
|
+
"num_experts": 4, "num_local_experts": 4, "n_routed_experts": 4, "moe_num_experts": 4, "num_experts_per_tok": 2,
|
|
24
|
+
"moe_intermediate_size": 64, "shared_expert_intermediate_size": 64, "n_shared_experts": 1, "n_group": 1, "topk_group": 1,
|
|
25
|
+
"moe_topk": 2, "kv_lora_rank": 16, "q_lora_rank": 32, "qk_rope_head_dim": 8, "qk_nope_head_dim": 8, "v_head_dim": 16,
|
|
26
|
+
"state_size": 8, "ssm_state_size": 8, "d_state": 8, "mamba_d_state": 8,
|
|
27
|
+
}
|
|
28
|
+
LAYERS = ("num_hidden_layers", "n_layer", "num_layers", "decoder_layers", "num_decoder_layers", "n_layers", "encoder_layers",
|
|
29
|
+
"num_encoder_layers", "depth", "decoder_num_hidden_layers", "text_layers")
|
|
30
|
+
BLOCKS = 4
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _small(d: dict, side: bool = False) -> dict:
|
|
34
|
+
"""The config's sizes made tiny; its structure (kinds of layers, experts, attention patterns) stays."""
|
|
35
|
+
out = dict(d)
|
|
36
|
+
counts = {d[k] for k in LAYERS if isinstance(d.get(k), int) and not isinstance(d.get(k), bool) and d[k] > 1}
|
|
37
|
+
period = max([v for v in (d.get("sliding_window_pattern"), d.get("full_attention_interval")) if isinstance(v, int)] or [0])
|
|
38
|
+
blocks = period if period > BLOCKS and period in range(BLOCKS + 1, 13) else BLOCKS
|
|
39
|
+
for k, v in d.items():
|
|
40
|
+
if isinstance(v, dict) and k.endswith("_config") and "model_type" in v:
|
|
41
|
+
out[k] = _small(v, side or any(w in k for w in ("vision", "audio", "speech", "encoder", "perceiver", "qformer", "image")))
|
|
42
|
+
elif isinstance(v, dict) and k in ("rope_parameters", "rope_scaling") and "mrope_section" in v:
|
|
43
|
+
out[k] = {**v, "mrope_section": [2, 3, 3]}
|
|
44
|
+
elif k in SIZE and isinstance(v, int) and not isinstance(v, bool):
|
|
45
|
+
out[k] = 64 if side and k in ("intermediate_size", "ffn_dim", "d_ff", "hidden_dim", "encoder_ffn_dim") else SIZE[k]
|
|
46
|
+
elif k in LAYERS and isinstance(v, int) and not isinstance(v, bool) and v > 1:
|
|
47
|
+
out[k] = 2 if side or k in ("encoder_layers", "num_encoder_layers") else min(v, blocks)
|
|
48
|
+
elif isinstance(v, list) and len(v) in counts and len(v) > blocks and blocks > BLOCKS:
|
|
49
|
+
out[k] = list(v[:blocks])
|
|
50
|
+
elif isinstance(v, list) and len(v) in counts and len(v) > BLOCKS:
|
|
51
|
+
kinds = []
|
|
52
|
+
for i, x in enumerate(v):
|
|
53
|
+
if x not in [v[j] for j in kinds]:
|
|
54
|
+
kinds.append(i)
|
|
55
|
+
kinds = kinds[:BLOCKS]
|
|
56
|
+
picked = sorted(kinds + [i for i in range(len(v)) if i not in kinds][:BLOCKS - len(kinds)])
|
|
57
|
+
out[k] = [v[i] for i in picked]
|
|
58
|
+
for k in ("quantization_config", "_name_or_path"):
|
|
59
|
+
out.pop(k, None)
|
|
60
|
+
return out
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _inputs(model, config, auto: str):
|
|
64
|
+
"""Inputs the model takes, by its kind: token ids, pixels, audio features or a waveform."""
|
|
65
|
+
import torch
|
|
66
|
+
g = torch.Generator().manual_seed(2)
|
|
67
|
+
text = config.get_text_config() if hasattr(config, "get_text_config") else config
|
|
68
|
+
vocab = min(getattr(text, "vocab_size", None) or 300, 300)
|
|
69
|
+
ids = torch.randint(3, vocab, (2, 12), generator=g)
|
|
70
|
+
extra = {"decoder_input_ids": torch.randint(3, vocab, (2, 6), generator=g)} if getattr(config, "is_encoder_decoder", False) else {}
|
|
71
|
+
main = getattr(model, "main_input_name", "input_ids")
|
|
72
|
+
if main == "input_ids" or auto == "AutoModelForImageTextToText":
|
|
73
|
+
eos = getattr(text, "eos_token_id", None)
|
|
74
|
+
eos = eos[0] if isinstance(eos, list) and eos else eos
|
|
75
|
+
if isinstance(eos, int) and 0 <= eos < (getattr(text, "vocab_size", None) or 300):
|
|
76
|
+
ids[:, -1] = eos
|
|
77
|
+
yield {"input_ids": ids, "use_cache": False, **extra}
|
|
78
|
+
yield {"input_ids": ids, **extra}
|
|
79
|
+
elif main == "pixel_values":
|
|
80
|
+
vision = getattr(config, "vision_config", None) or config
|
|
81
|
+
size = getattr(vision, "image_size", None) or 224
|
|
82
|
+
h, w = (size[0], size[-1]) if isinstance(size, (list, tuple)) else (size.get("height", 224), size.get("width", 224)) \
|
|
83
|
+
if isinstance(size, dict) else (size, size)
|
|
84
|
+
yield {"pixel_values": torch.randn(2, getattr(vision, "num_channels", None) or 3, h, w, generator=g), **extra}
|
|
85
|
+
elif main == "input_features":
|
|
86
|
+
mel = getattr(config, "num_mel_bins", None) or 80
|
|
87
|
+
positions = getattr(config, "max_source_positions", None)
|
|
88
|
+
if positions:
|
|
89
|
+
yield {"input_features": torch.randn(2, mel, 2 * positions, generator=g), **extra}
|
|
90
|
+
yield {"input_features": torch.randn(2, 64, mel, generator=g), **extra}
|
|
91
|
+
elif main == "input_values":
|
|
92
|
+
yield {"input_values": torch.randn(2, 4000, generator=g), **extra}
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _output(out):
|
|
96
|
+
for key in ("logits", "last_hidden_state", "prediction_logits", "pooler_output", "image_embeds", "text_embeds"):
|
|
97
|
+
value = out.get(key) if isinstance(out, dict) else getattr(out, key, None)
|
|
98
|
+
if value is not None and hasattr(value, "shape"):
|
|
99
|
+
return value
|
|
100
|
+
return out[0] if isinstance(out, (tuple, list)) else out
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
SIZE_KEYS = set(SIZE) | set(LAYERS) | {"vocab_size", "max_position_embeddings", "layer_types", "_name_or_path", "transformers_version",
|
|
104
|
+
"torch_dtype", "dtype", "quantization_config", "architectures"}
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def settings_hash(config) -> str:
|
|
108
|
+
"""What decides how an architecture computes, beyond its kind: rope settings, activation, attention pattern, flags. Sizes,
|
|
109
|
+
names and the vocabulary are left out, since the small copy replaces them. Results are remembered per kind and this hash, so
|
|
110
|
+
two models of one kind with different settings (Phi-3 and Phi-3.5's longrope) are each checked."""
|
|
111
|
+
import hashlib
|
|
112
|
+
|
|
113
|
+
def keep(d):
|
|
114
|
+
out = {}
|
|
115
|
+
for k, v in sorted(d.items()):
|
|
116
|
+
if k in SIZE_KEYS:
|
|
117
|
+
continue
|
|
118
|
+
out[k] = keep(v) if isinstance(v, dict) else v
|
|
119
|
+
return out
|
|
120
|
+
data = config.to_dict() if hasattr(config, "to_dict") else dict(config)
|
|
121
|
+
return hashlib.sha1(json.dumps(keep(data), sort_keys=True, default=str).encode()).hexdigest()[:12]
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def kept_rng(fn):
|
|
125
|
+
"""Checks draw random numbers; the training code's own random state (its seed) is left as it was."""
|
|
126
|
+
def wrapped(*a, **kw):
|
|
127
|
+
import random
|
|
128
|
+
|
|
129
|
+
import numpy as np
|
|
130
|
+
import torch
|
|
131
|
+
states = (torch.get_rng_state(), random.getstate(), np.random.get_state())
|
|
132
|
+
try:
|
|
133
|
+
return fn(*a, **kw)
|
|
134
|
+
finally:
|
|
135
|
+
torch.set_rng_state(states[0])
|
|
136
|
+
random.setstate(states[1])
|
|
137
|
+
np.random.set_state(states[2])
|
|
138
|
+
return wrapped
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def _remembered(key: str):
|
|
142
|
+
try:
|
|
143
|
+
with open(CACHE, encoding="utf-8") as f:
|
|
144
|
+
return json.load(f).get(key)
|
|
145
|
+
except (OSError, ValueError):
|
|
146
|
+
return None
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _remember(key: str, result: str):
|
|
150
|
+
try:
|
|
151
|
+
os.makedirs(os.path.dirname(CACHE), exist_ok=True)
|
|
152
|
+
try:
|
|
153
|
+
with open(CACHE, encoding="utf-8") as f:
|
|
154
|
+
known = json.load(f)
|
|
155
|
+
except (OSError, ValueError):
|
|
156
|
+
known = {}
|
|
157
|
+
known[key] = result
|
|
158
|
+
tmp = f"{CACHE}.{os.getpid()}.tmp"
|
|
159
|
+
with open(tmp, "w", encoding="utf-8") as f:
|
|
160
|
+
json.dump(known, f, indent=1)
|
|
161
|
+
replace_file(tmp, CACHE)
|
|
162
|
+
except OSError:
|
|
163
|
+
pass
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
@kept_rng
|
|
167
|
+
def check(repo: str, auto: str, log=print) -> set:
|
|
168
|
+
"""Raises ValueError when this architecture does not split correctly; otherwise returns what else was learnt about it:
|
|
169
|
+
"whole_batches" (its blocks give other results when a batch is cut into pieces) and "place" (its blocks depend on where
|
|
170
|
+
they sit in the model, which the 4-bit path does not rebuild). Returns nothing when no small copy can be made here (then it
|
|
171
|
+
says so)."""
|
|
172
|
+
from transformers.utils import logging
|
|
173
|
+
level, bars = logging.get_verbosity(), logging.is_progress_bar_enabled()
|
|
174
|
+
logging.set_verbosity_error()
|
|
175
|
+
logging.disable_progress_bar()
|
|
176
|
+
try:
|
|
177
|
+
return _check(repo, auto, log) or set()
|
|
178
|
+
finally:
|
|
179
|
+
logging.set_verbosity(level)
|
|
180
|
+
if bars:
|
|
181
|
+
logging.enable_progress_bar()
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def _check(repo: str, auto: str, log) -> set | None:
|
|
185
|
+
import torch
|
|
186
|
+
import transformers
|
|
187
|
+
config = load_config(repo)
|
|
188
|
+
kind = str(getattr(config, "model_type", ""))
|
|
189
|
+
key = f"{kind}|{settings_hash(config)}|{auto}|transformers {transformers.__version__}|layerpool {__version__}"
|
|
190
|
+
known = _remembered(key)
|
|
191
|
+
if known and known.startswith("ok"):
|
|
192
|
+
return set(known.split(":")[1:])
|
|
193
|
+
if known and known.startswith("wrong:"):
|
|
194
|
+
raise ValueError(known[6:])
|
|
195
|
+
with tempfile.TemporaryDirectory(prefix="layerpool_check_") as folder:
|
|
196
|
+
try:
|
|
197
|
+
small = type(config).from_dict(_small(config.to_dict()))
|
|
198
|
+
torch.manual_seed(0)
|
|
199
|
+
whole = getattr(transformers, auto).from_config(small).float().eval()
|
|
200
|
+
with torch.no_grad():
|
|
201
|
+
for name, p in whole.named_parameters():
|
|
202
|
+
if "norm" in name and p.is_floating_point():
|
|
203
|
+
p.add_(torch.randn_like(p) * 0.3)
|
|
204
|
+
whole.save_pretrained(folder)
|
|
205
|
+
want, inputs = None, None
|
|
206
|
+
for candidate in _inputs(whole, small, auto):
|
|
207
|
+
try:
|
|
208
|
+
with torch.no_grad():
|
|
209
|
+
want = _output(whole(**candidate))
|
|
210
|
+
again = _output(whole(**candidate))
|
|
211
|
+
inputs = candidate
|
|
212
|
+
break
|
|
213
|
+
except Exception:
|
|
214
|
+
continue
|
|
215
|
+
if inputs is None:
|
|
216
|
+
raise RuntimeError("no inputs fit the small copy")
|
|
217
|
+
if not torch.equal(want, again):
|
|
218
|
+
log(f"note: {kind} gives different outputs for the same input (it draws random numbers), so its split cannot be "
|
|
219
|
+
"checked by comparison; training goes on")
|
|
220
|
+
return
|
|
221
|
+
lay = layout(load_config(folder), auto)
|
|
222
|
+
n = lay["n"]
|
|
223
|
+
cuts = sorted({0, 1, max(1, n - 1), n})
|
|
224
|
+
cores = [BlockCore(load_blocks(folder, lay, a, b, "cpu", torch.float32), a, 4, 2.0, 1e-3, mode="full")
|
|
225
|
+
for a, b in zip(cuts, cuts[1:])]
|
|
226
|
+
model = load_ends(folder, lay, torch.float32)
|
|
227
|
+
Ends(model, lay, LocalChain(cores))
|
|
228
|
+
model.eval()
|
|
229
|
+
except Exception as e:
|
|
230
|
+
log(f"note: layerpool could not make a small copy of {kind} to check its split ({type(e).__name__}); training goes on")
|
|
231
|
+
return
|
|
232
|
+
try:
|
|
233
|
+
with torch.no_grad():
|
|
234
|
+
got = _output(model(**inputs))
|
|
235
|
+
except Exception as e:
|
|
236
|
+
text = f"layerpool cannot split {kind} models yet: split across devices, the model fails ({type(e).__name__}: {str(e)[:200]})"
|
|
237
|
+
_remember(key, "wrong:" + text)
|
|
238
|
+
raise ValueError(text) from None
|
|
239
|
+
gap = float((got.float() - want.float()).abs().max())
|
|
240
|
+
scale = float(want.float().abs().max()) or 1.0
|
|
241
|
+
if gap > 1e-4 * max(1.0, scale):
|
|
242
|
+
text = (f"layerpool cannot split {kind} models correctly yet: on a small copy of this architecture the split model's "
|
|
243
|
+
f"outputs differ from the whole model's (by {gap:.3g}), so training would not be right")
|
|
244
|
+
_remember(key, "wrong:" + text)
|
|
245
|
+
raise ValueError(text)
|
|
246
|
+
notes = []
|
|
247
|
+
try:
|
|
248
|
+
if _cuts_change_results(whole, folder, auto, lay):
|
|
249
|
+
notes.append("whole_batches")
|
|
250
|
+
log(f"note: {kind} blocks compute differently when a batch is cut into pieces, so its batches go to the devices whole")
|
|
251
|
+
if _depends_on_place(whole, folder, auto, lay):
|
|
252
|
+
notes.append("place")
|
|
253
|
+
except Exception:
|
|
254
|
+
pass
|
|
255
|
+
_remember(key, "ok" + "".join(f":{n}" for n in notes))
|
|
256
|
+
return set(notes)
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def _block_calls(whole, lay: dict, inputs: dict) -> dict:
|
|
260
|
+
"""What each block is given when the whole model runs on these inputs: {block: (input, args, kwargs)}."""
|
|
261
|
+
import torch
|
|
262
|
+
seen = {}
|
|
263
|
+
blocks = whole.get_submodule(lay["stack"])
|
|
264
|
+
|
|
265
|
+
def grab(i):
|
|
266
|
+
def hook(module, args, kwargs):
|
|
267
|
+
kwargs = {k: v for k, v in kwargs.items() if k not in ("past_key_values", "past_key_value", "cache_params")}
|
|
268
|
+
if args:
|
|
269
|
+
seen[i] = (args[0].detach(), tuple(args[1:]), kwargs)
|
|
270
|
+
else:
|
|
271
|
+
kwargs = dict(kwargs)
|
|
272
|
+
seen[i] = (kwargs.pop("hidden_states").detach(), (), kwargs)
|
|
273
|
+
return hook
|
|
274
|
+
hooks = [b.register_forward_pre_hook(grab(i), with_kwargs=True) for i, b in enumerate(blocks)]
|
|
275
|
+
try:
|
|
276
|
+
with torch.no_grad():
|
|
277
|
+
whole(**inputs)
|
|
278
|
+
finally:
|
|
279
|
+
for h in hooks:
|
|
280
|
+
h.remove()
|
|
281
|
+
return seen
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
def _text_inputs(whole, rows: int) -> dict | None:
|
|
285
|
+
import torch
|
|
286
|
+
if getattr(whole, "main_input_name", "input_ids") != "input_ids" or getattr(whole.config, "is_encoder_decoder", False):
|
|
287
|
+
return None
|
|
288
|
+
vocab = min(getattr(whole.config.get_text_config(), "vocab_size", 300) or 300, 300)
|
|
289
|
+
return {"input_ids": torch.randint(3, vocab, (rows, 12), generator=torch.Generator().manual_seed(5)), "use_cache": False}
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def _cuts_change_results(whole, folder: str, auto: str, lay: dict) -> bool:
|
|
293
|
+
"""Whether the blocks give other results when a batch is cut into micro-batches the way the devices get them. The batch has
|
|
294
|
+
as many rows as the small copy has heads, so a tensor whose size merely equals the heads is cut too if the cutting rule
|
|
295
|
+
mistakes it for the batch (MPT's and Bloom's attention biases)."""
|
|
296
|
+
import torch
|
|
297
|
+
from .driver import split_args
|
|
298
|
+
rows = 4
|
|
299
|
+
inputs = _text_inputs(whole, rows)
|
|
300
|
+
if inputs is None:
|
|
301
|
+
return False
|
|
302
|
+
calls = _block_calls(whole, lay, inputs)
|
|
303
|
+
blocks = whole.get_submodule(lay["stack"])
|
|
304
|
+
first = min(calls)
|
|
305
|
+
per_block = {i: (a, kw) for i, (_, a, kw) in calls.items()}
|
|
306
|
+
|
|
307
|
+
def through(h, trees):
|
|
308
|
+
for i in sorted(trees):
|
|
309
|
+
a, kw = trees[i]
|
|
310
|
+
h = blocks[i](h, *a, **kw)
|
|
311
|
+
h = h[0] if isinstance(h, tuple) else h
|
|
312
|
+
return h
|
|
313
|
+
with torch.no_grad():
|
|
314
|
+
try:
|
|
315
|
+
want = through(calls[first][0], per_block)
|
|
316
|
+
except Exception:
|
|
317
|
+
return False
|
|
318
|
+
cuts = [(0, 2), (2, rows)]
|
|
319
|
+
trees, _ = split_args(per_block, rows, cuts)
|
|
320
|
+
try:
|
|
321
|
+
got = torch.cat([through(calls[first][0][a:b], tree) for (a, b), tree in zip(cuts, trees)])
|
|
322
|
+
except Exception:
|
|
323
|
+
return True
|
|
324
|
+
return not torch.allclose(got, want, atol=1e-4, rtol=1e-4)
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
def _depends_on_place(whole, folder: str, auto: str, lay: dict) -> bool:
|
|
328
|
+
"""Whether a block computes differently when transformers builds it in a model of just its range (numbered from 0, with a
|
|
329
|
+
smaller total) than in the whole model. The 16-bit path rebuilds blocks inside the whole model; the 4-bit path cannot."""
|
|
330
|
+
import torch
|
|
331
|
+
inputs = _text_inputs(whole, 2)
|
|
332
|
+
if inputs is None or lay["n"] < 2:
|
|
333
|
+
return False
|
|
334
|
+
calls = _block_calls(whole, lay, inputs)
|
|
335
|
+
i = lay["n"] - 1
|
|
336
|
+
if i not in calls:
|
|
337
|
+
return False
|
|
338
|
+
alone = load_blocks(folder, lay, i, i + 1, "cpu", torch.float32, in_place=False)[0]
|
|
339
|
+
h, a, kw = calls[i]
|
|
340
|
+
with torch.no_grad():
|
|
341
|
+
want = whole.get_submodule(lay["stack"])[i](h, *a, **kw)
|
|
342
|
+
try:
|
|
343
|
+
got = alone(h, *a, **kw)
|
|
344
|
+
except Exception:
|
|
345
|
+
return True
|
|
346
|
+
want = want[0] if isinstance(want, tuple) else want
|
|
347
|
+
got = got[0] if isinstance(got, tuple) else got
|
|
348
|
+
return not torch.allclose(got, want, atol=1e-5, rtol=1e-4)
|
layerpool/telemetry.py
ADDED
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
import glob
|
|
2
|
+
import json
|
|
3
|
+
import os
|
|
4
|
+
import re
|
|
5
|
+
import shutil
|
|
6
|
+
import subprocess
|
|
7
|
+
import sys
|
|
8
|
+
import threading
|
|
9
|
+
import time
|
|
10
|
+
import warnings
|
|
11
|
+
|
|
12
|
+
_macmon = {"proc": None, "last": None}
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _macmon_reader():
|
|
16
|
+
path = shutil.which("macmon")
|
|
17
|
+
if not path:
|
|
18
|
+
return
|
|
19
|
+
try:
|
|
20
|
+
proc = subprocess.Popen([path, "pipe", "-i", "2000"], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True)
|
|
21
|
+
except OSError:
|
|
22
|
+
return
|
|
23
|
+
_macmon["proc"] = proc
|
|
24
|
+
for line in proc.stdout:
|
|
25
|
+
try:
|
|
26
|
+
_macmon["last"] = (time.time(), json.loads(line))
|
|
27
|
+
except ValueError:
|
|
28
|
+
continue
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _mac_extra() -> dict:
|
|
32
|
+
if _macmon["proc"] is None and shutil.which("macmon"):
|
|
33
|
+
threading.Thread(target=_macmon_reader, daemon=True).start()
|
|
34
|
+
got = _macmon["last"]
|
|
35
|
+
if not got or time.time() - got[0] > 10:
|
|
36
|
+
return {}
|
|
37
|
+
data = got[1]
|
|
38
|
+
temp = data.get("temp", {})
|
|
39
|
+
return {"gpu_util": round(100 * float(data.get("gpu_usage", [0, 0])[1]), 1) if isinstance(data.get("gpu_usage"), list) else None,
|
|
40
|
+
"temp_c": temp.get("gpu_temp_avg") or temp.get("cpu_temp_avg"), "power_w": data.get("all_power")}
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
_heat = {"at": 0.0, "value": None}
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _mac_heat() -> str | None:
|
|
47
|
+
"""macOS's heat level, readable without admin rights (the temperature itself is not): "normal", or how far it slowed down."""
|
|
48
|
+
if time.time() - _heat["at"] < 15:
|
|
49
|
+
return _heat["value"]
|
|
50
|
+
_heat["at"] = time.time()
|
|
51
|
+
try:
|
|
52
|
+
text = subprocess.run(["pmset", "-g", "therm"], capture_output=True, text=True, timeout=5).stdout
|
|
53
|
+
except (OSError, subprocess.SubprocessError):
|
|
54
|
+
return None
|
|
55
|
+
limit = re.search(r"CPU_Speed_Limit\s*=\s*(\d+)", text)
|
|
56
|
+
if limit and int(limit.group(1)) < 100:
|
|
57
|
+
_heat["value"] = f"hot: slowed to {limit.group(1)}% speed"
|
|
58
|
+
elif "No thermal warning level has been recorded" in text or limit:
|
|
59
|
+
_heat["value"] = "normal (no heat warning)"
|
|
60
|
+
else:
|
|
61
|
+
_heat["value"] = None
|
|
62
|
+
return _heat["value"]
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _cpu_temp() -> float | None:
|
|
66
|
+
"""The CPU temperature where the system shares it without admin rights (Linux)."""
|
|
67
|
+
try:
|
|
68
|
+
import psutil
|
|
69
|
+
sensors = psutil.sensors_temperatures() if hasattr(psutil, "sensors_temperatures") else {}
|
|
70
|
+
except Exception:
|
|
71
|
+
return None
|
|
72
|
+
values = [t.current for name in ("coretemp", "k10temp", "cpu_thermal", "zenpower") for t in sensors.get(name, []) if t.current]
|
|
73
|
+
return round(max(values), 1) if values else None
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
warnings.filterwarnings("ignore", message="'sin' and 'sout' swap memory stats couldn't be determined", category=RuntimeWarning)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _ram() -> dict:
|
|
80
|
+
import psutil
|
|
81
|
+
vm, sw = psutil.virtual_memory(), psutil.swap_memory()
|
|
82
|
+
return {"ram_used_gb": round((vm.total - vm.available) / 1e9, 2), "ram_total_gb": round(vm.total / 1e9, 1), "swap_gb": round(sw.used / 1e9, 2)}
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
_NVML = {"ready": False}
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _nvml_handles(pynvml) -> list:
|
|
89
|
+
"""NVML handles of the GPUs PyTorch uses, in PyTorch's order: NVML counts every GPU by bus, PyTorch only the visible ones,
|
|
90
|
+
fastest first."""
|
|
91
|
+
if not _NVML["ready"]:
|
|
92
|
+
try:
|
|
93
|
+
pynvml.nvmlInit()
|
|
94
|
+
except Exception:
|
|
95
|
+
_NVML["failed"] = True
|
|
96
|
+
raise
|
|
97
|
+
_NVML["ready"] = True
|
|
98
|
+
try:
|
|
99
|
+
import torch
|
|
100
|
+
handles = []
|
|
101
|
+
for i in range(torch.cuda.device_count()):
|
|
102
|
+
uuid = str(torch.cuda.get_device_properties(i).uuid)
|
|
103
|
+
handles.append(pynvml.nvmlDeviceGetHandleByUUID(uuid if uuid.startswith("GPU-") else f"GPU-{uuid}"))
|
|
104
|
+
if handles:
|
|
105
|
+
return handles
|
|
106
|
+
except Exception:
|
|
107
|
+
pass
|
|
108
|
+
return [pynvml.nvmlDeviceGetHandleByIndex(i) for i in range(pynvml.nvmlDeviceGetCount())]
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
AMD_SYSFS = "/sys/class/drm"
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _amd() -> list:
|
|
115
|
+
"""AMD GPUs from the amdgpu driver's files (Linux), which need no extra package or admin rights."""
|
|
116
|
+
gpus = []
|
|
117
|
+
for total_file in sorted(glob.glob(os.path.join(AMD_SYSFS, "card*", "device", "mem_info_vram_total"))):
|
|
118
|
+
folder = os.path.dirname(total_file)
|
|
119
|
+
|
|
120
|
+
def read(name, folder=folder):
|
|
121
|
+
try:
|
|
122
|
+
with open(os.path.join(folder, name), encoding="ascii") as f:
|
|
123
|
+
return float(f.read().strip())
|
|
124
|
+
except (OSError, ValueError):
|
|
125
|
+
return None
|
|
126
|
+
total, used = read("mem_info_vram_total"), read("mem_info_vram_used")
|
|
127
|
+
if not total:
|
|
128
|
+
continue
|
|
129
|
+
temps = [read(os.path.relpath(path, folder)) for path in glob.glob(os.path.join(folder, "hwmon", "hwmon*", "temp*_input"))]
|
|
130
|
+
temps = [t / 1000 for t in temps if t]
|
|
131
|
+
gpus.append({"used_gb": round((used or 0) / 1e9, 2), "total_gb": round(total / 1e9, 1), "util": read("gpu_busy_percent"),
|
|
132
|
+
"temp_c": round(max(temps), 1) if temps else None, "power_w": None})
|
|
133
|
+
return gpus
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def _cuda() -> dict:
|
|
137
|
+
out = {"gpus": []}
|
|
138
|
+
try:
|
|
139
|
+
import torch
|
|
140
|
+
if getattr(torch.version, "hip", None) and sys.platform.startswith("linux"):
|
|
141
|
+
out["gpus"] = _amd()
|
|
142
|
+
if out["gpus"]:
|
|
143
|
+
return out
|
|
144
|
+
except Exception:
|
|
145
|
+
pass
|
|
146
|
+
try:
|
|
147
|
+
if _NVML.get("failed"):
|
|
148
|
+
raise RuntimeError("no NVML here")
|
|
149
|
+
import pynvml
|
|
150
|
+
for h in _nvml_handles(pynvml):
|
|
151
|
+
mem = pynvml.nvmlDeviceGetMemoryInfo(h)
|
|
152
|
+
gpu = {"used_gb": round(mem.used / 1e9, 2), "total_gb": round(mem.total / 1e9, 1)}
|
|
153
|
+
for key, fn in (("util", lambda: pynvml.nvmlDeviceGetUtilizationRates(h).gpu), ("temp_c", lambda: pynvml.nvmlDeviceGetTemperature(h, 0)),
|
|
154
|
+
("power_w", lambda: pynvml.nvmlDeviceGetPowerUsage(h) / 1000)):
|
|
155
|
+
try:
|
|
156
|
+
gpu[key] = round(float(fn()), 1)
|
|
157
|
+
except Exception:
|
|
158
|
+
gpu[key] = None
|
|
159
|
+
out["gpus"].append(gpu)
|
|
160
|
+
return out
|
|
161
|
+
except Exception:
|
|
162
|
+
pass
|
|
163
|
+
try:
|
|
164
|
+
import torch
|
|
165
|
+
for i in range(torch.cuda.device_count()):
|
|
166
|
+
free, total = torch.cuda.mem_get_info(i)
|
|
167
|
+
out["gpus"].append({"used_gb": round((total - free) / 1e9, 2), "total_gb": round(total / 1e9, 1), "util": None, "temp_c": None, "power_w": None})
|
|
168
|
+
except Exception:
|
|
169
|
+
pass
|
|
170
|
+
return out
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def sample(backend: str, cpu: bool = False) -> dict:
|
|
174
|
+
out = {"time": round(time.time(), 1), **_ram()}
|
|
175
|
+
if backend == "mlx" and not cpu:
|
|
176
|
+
try:
|
|
177
|
+
import mlx.core as mx
|
|
178
|
+
out["mlx_active_gb"] = round(mx.get_active_memory() / 1e9, 2)
|
|
179
|
+
out["mlx_peak_gb"] = round(mx.get_peak_memory() / 1e9, 2)
|
|
180
|
+
out["mlx_cache_gb"] = round(mx.get_cache_memory() / 1e9, 2)
|
|
181
|
+
except Exception:
|
|
182
|
+
pass
|
|
183
|
+
out.update({k: v for k, v in _mac_extra().items() if v is not None})
|
|
184
|
+
elif backend == "torch" and not cpu:
|
|
185
|
+
out.update(_cuda())
|
|
186
|
+
if out.get("temp_c") is None and not any(g.get("temp_c") for g in out.get("gpus", [])):
|
|
187
|
+
if sys.platform == "darwin":
|
|
188
|
+
heat = _mac_heat()
|
|
189
|
+
if heat:
|
|
190
|
+
out["heat"] = heat
|
|
191
|
+
else:
|
|
192
|
+
cpu_temp = _cpu_temp()
|
|
193
|
+
if cpu_temp is not None:
|
|
194
|
+
out["temp_c"] = cpu_temp
|
|
195
|
+
return out
|