decisionnode-edge 0.9.2__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.
@@ -0,0 +1,397 @@
1
+ """Backends: what reads the backbone. Every backend gives, for a prompt's token ids, the hidden state at the last position
2
+ after the final norm (float32, one vector). The package's readout table and calibration go on top in model.py, so the
3
+ answers are the package's whichever backend reads the prompt.
4
+
5
+ torch transformers; every input, pictures included (always installed) NVIDIA GPU, CPU, Apple (mps)
6
+ vllm vLLM's pooling runner, LAST pooling with no normalization NVIDIA GPU
7
+ openvino OpenVINO, bf16, one IR per static length (python -m decisionnode_edge.build) x86 CPU
8
+ mlx mlx-lm's Qwen3.5 text model, reading the model directory as it is Apple silicon
9
+ llamacpp llama.cpp's llama-server (--embeddings --pooling last) on a GGUF Q8_0 file any machine llama.cpp builds for
10
+
11
+ The fast backends read text. A prompt one of them cannot take (pictures; a prompt longer than an OpenVINO build's largest
12
+ length or a llama.cpp context) is read by torch, loaded on first use.
13
+
14
+ Choosing: `backend` (EdgeModel.load) or DECISIONNODE_EDGE_BACKEND; "auto" (the default) takes the first that can run here,
15
+ in the order of `ORDER` for the device class. A backend that needs built files (openvino, llamacpp) runs only with the
16
+ directory the build tool wrote (`artifacts`, or DECISIONNODE_EDGE_ARTIFACTS). Options are flat, or under a backend's name
17
+ ({"openvino": {"threads": 16}}) so one set can serve whichever backend auto takes.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import dataclasses
23
+ import hashlib
24
+ import importlib.util
25
+ import json
26
+ import logging
27
+ import os
28
+ import platform
29
+ import shutil
30
+ import socket
31
+ import subprocess
32
+ import sys
33
+ import tempfile
34
+ import time
35
+ import urllib.error
36
+ import urllib.request
37
+ import weakref
38
+ from typing import Any, Sequence
39
+
40
+ NAMES = ("torch", "vllm", "openvino", "mlx", "llamacpp")
41
+ # per device class, fastest first (the runtime README's table)
42
+ ORDER = {
43
+ "cuda": ("vllm", "llamacpp", "torch"),
44
+ "apple": ("mlx", "llamacpp", "torch"),
45
+ "cpu": ("openvino", "llamacpp", "torch"),
46
+ }
47
+ ENV_BACKEND = "DECISIONNODE_EDGE_BACKEND"
48
+ ENV_ARTIFACTS = "DECISIONNODE_EDGE_ARTIFACTS"
49
+ ENV_OPTIONS = "DECISIONNODE_EDGE_OPTIONS"
50
+ BUILD_FILE = "decisionnode_edge_build.json"
51
+ BUILD_FORMAT = "decisionnode-edge-build-1"
52
+ # what a backend that reads the model directory needs from it: never readout.safetensors (vLLM loads every .safetensors file)
53
+ MODEL_FILES = ("config.json", "model.safetensors", "tokenizer.json", "tokenizer_config.json", "preprocessor_config.json", "video_preprocessor_config.json")
54
+
55
+ log = logging.getLogger("decisionnode_edge")
56
+
57
+
58
+ # ---------------------------------------------------------------------------
59
+ # Choosing
60
+ # ---------------------------------------------------------------------------
61
+
62
+
63
+ def apple_silicon() -> bool:
64
+ return sys.platform == "darwin" and platform.machine() == "arm64"
65
+
66
+
67
+ def linux() -> bool:
68
+ return sys.platform.startswith("linux")
69
+
70
+
71
+ def device_class(device: str | None) -> str:
72
+ """"cuda", "apple" or "cpu": the device given, else CUDA when present, else Apple silicon, else the CPU."""
73
+ if device is not None:
74
+ device = str(device)
75
+ return "cuda" if device.startswith("cuda") else "apple" if device.startswith("mps") else "cpu"
76
+ import torch
77
+
78
+ if torch.cuda.is_available():
79
+ return "cuda"
80
+ return "apple" if apple_silicon() else "cpu"
81
+
82
+
83
+ def env_options() -> dict:
84
+ raw = os.environ.get(ENV_OPTIONS)
85
+ if not raw:
86
+ return {}
87
+ value = json.loads(raw)
88
+ if not isinstance(value, dict):
89
+ raise ValueError(f"{ENV_OPTIONS} must be a JSON object")
90
+ return value
91
+
92
+
93
+ def read_build(artifacts: str | None) -> dict | None:
94
+ """The build tool's record in `artifacts` (decisionnode_edge_build.json), or None."""
95
+ if not artifacts or not os.path.isfile(os.path.join(artifacts, BUILD_FILE)):
96
+ return None
97
+ with open(os.path.join(artifacts, BUILD_FILE), encoding="utf-8") as f:
98
+ build = json.load(f)
99
+ if build.get("format") != BUILD_FORMAT:
100
+ raise ValueError(f"{artifacts}: not a build of this runtime ({build.get('format')!r})")
101
+ return build
102
+
103
+
104
+ def own_options(name: str, options: dict) -> dict:
105
+ """The options for one backend: the flat ones, then the ones under its name."""
106
+ return {**{k: v for k, v in options.items() if k not in NAMES}, **(options.get(name) or {})}
107
+
108
+
109
+ def _installed(*modules: str) -> bool:
110
+ return all(importlib.util.find_spec(m) is not None for m in modules)
111
+
112
+
113
+ def unavailable(name: str, device: str | None, artifacts: str | None, options: dict) -> str | None:
114
+ """Why `name` cannot run here, or None when it can."""
115
+ if name == "torch":
116
+ return None
117
+ if name == "vllm":
118
+ if not linux() or not _installed("vllm"):
119
+ return "vLLM is not installed (pip install 'decisionnode-edge[vllm]', Linux with an NVIDIA GPU)"
120
+ return None if device_class(device) == "cuda" else "vLLM needs an NVIDIA GPU"
121
+ if name == "mlx":
122
+ if not apple_silicon():
123
+ return "MLX needs Apple silicon"
124
+ return None if _installed("mlx", "mlx_lm") else "MLX is not installed (pip install 'decisionnode-edge[mlx]')"
125
+ build = read_build(artifacts)
126
+ if name == "openvino":
127
+ if not _installed("openvino"):
128
+ return "OpenVINO is not installed (pip install 'decisionnode-edge[openvino]')"
129
+ if not build or build.get("backend") != "openvino":
130
+ return "OpenVINO needs a build: python -m decisionnode_edge.build openvino <model> --out <dir>, then artifacts=<dir>"
131
+ return None
132
+ if name == "llamacpp":
133
+ options = own_options(name, options)
134
+ if options.get("url"):
135
+ return None
136
+ if not build or build.get("backend") != "llamacpp":
137
+ return "llama.cpp needs a GGUF build (python -m decisionnode_edge.build gguf) as artifacts, or options={'url': <a running llama-server>}"
138
+ if not (options.get("server") or shutil.which("llama-server")):
139
+ return "llama-server is not on PATH: give options={'server': <path to llama-server>} or {'url': <a running llama-server>}"
140
+ return None
141
+ raise ValueError(f"unknown backend {name!r}: one of {', '.join(NAMES)} or auto")
142
+
143
+
144
+ def choose(requested: str | None, device: str | None, artifacts: str | None, options: dict) -> str:
145
+ """The backend to load: the one asked for (argument, else DECISIONNODE_EDGE_BACKEND), or for "auto" the first of the
146
+ device class's order that can run here."""
147
+ name = (requested or os.environ.get(ENV_BACKEND) or "auto").strip().lower()
148
+ if name != "auto":
149
+ reason = unavailable(name, device, artifacts, options)
150
+ if reason:
151
+ raise RuntimeError(f"backend {name!r}: {reason}")
152
+ return name
153
+ for candidate in ORDER[device_class(device)]:
154
+ reason = unavailable(candidate, device, artifacts, options)
155
+ if reason is None:
156
+ return candidate
157
+ log.info("auto: not %s: %s", candidate, reason)
158
+ return "torch"
159
+
160
+
161
+ def load(name: str, path: str, config: dict, artifacts: str | None, options: dict, device: str | None):
162
+ """The backend object for a name other than torch (model.py loads torch itself)."""
163
+ max_tokens = int(config["limits"]["max_input_tokens"])
164
+ options = own_options(name, options)
165
+ if name == "vllm":
166
+ return VLLM(path, max_tokens, options, device)
167
+ if name == "mlx":
168
+ return MLX(path)
169
+ build = read_build(artifacts)
170
+ if build is not None and build.get("model_fingerprint") != fingerprint(path):
171
+ raise ValueError(f"{artifacts} was built from another model than {path}")
172
+ if name == "openvino":
173
+ return OpenVINO(artifacts, build, options)
174
+ if name == "llamacpp":
175
+ return LlamaCpp(artifacts, build, max_tokens, options)
176
+ raise ValueError(f"unknown backend {name!r}")
177
+
178
+
179
+ def fingerprint(path: str) -> str:
180
+ """A quick identity of a model directory's weights, kept in every build: the file's size, its safetensors header and
181
+ 1 MiB every 256 MiB plus the last MiB (hashing all of it would add seconds to every load)."""
182
+ weights = os.path.join(path, "model.safetensors")
183
+ size = os.path.getsize(weights)
184
+ h = hashlib.sha256(str(size).encode())
185
+ with open(weights, "rb") as f:
186
+ n = int.from_bytes(f.read(8), "little")
187
+ h.update(f.read(n))
188
+ for offset in list(range(8 + n, size, 256 << 20)) + [max(0, size - (1 << 20))]:
189
+ f.seek(offset)
190
+ h.update(f.read(1 << 20))
191
+ return h.hexdigest()
192
+
193
+
194
+ def link_model_files(path: str, target: str) -> None:
195
+ """Links in `target` to the model directory's backbone files (MODEL_FILES), never its readout."""
196
+ for name in MODEL_FILES:
197
+ src = os.path.join(os.path.abspath(path), name)
198
+ if os.path.exists(src):
199
+ os.symlink(src, os.path.join(target, name))
200
+
201
+
202
+ # ---------------------------------------------------------------------------
203
+ # Backends: hidden(ids) gives the float32 hidden state of the last position; accepts(n) says whether a prompt of n
204
+ # tokens is theirs (torch reads the others)
205
+ # ---------------------------------------------------------------------------
206
+
207
+
208
+ class VLLM:
209
+ """vLLM's pooling runner (convert "embed", LAST pooling, use_activation False: the raw hidden state after the final norm)
210
+ on a temporary directory of links to the model files. Text only: the multimodal limits are 0. Its engine runs in this
211
+ process (VLLM_ENABLE_V1_MULTIPROCESSING 0 unless set): as fast at batch 1, and a child process would need the caller's
212
+ script to be importable (vLLM starts it with spawn once CUDA is up)."""
213
+
214
+ name = "vllm"
215
+ KV_CACHE_BYTES = 2 << 30 # several prompts of the full 16,384 tokens
216
+ HEADROOM_BYTES = 4 << 30 # activations at 16,384 tokens, CUDA graphs, the CUDA context
217
+
218
+ def __init__(self, path: str, max_tokens: int, options: dict, device: str | None):
219
+ if device is not None and str(device) not in ("cuda", "cuda:0"):
220
+ raise ValueError("vLLM runs on the first visible GPU: choose the card with CUDA_VISIBLE_DEVICES")
221
+ os.environ.setdefault("VLLM_ENABLE_V1_MULTIPROCESSING", "0")
222
+ from vllm import LLM
223
+ from vllm.config import PoolerConfig
224
+ from vllm.engine.arg_utils import EngineArgs
225
+ from vllm.platforms import current_platform
226
+
227
+ self.dir = tempfile.mkdtemp(prefix="decisionnode-edge-vllm-")
228
+ self._cleanup = weakref.finalize(self, shutil.rmtree, self.dir, True)
229
+ link_model_files(path, self.dir)
230
+ # the KV cache is sized, not a share of the card: the share only has to cover it, the weights and the headroom
231
+ total = current_platform.get_device_total_memory(0)
232
+ need = os.path.getsize(os.path.join(path, "model.safetensors")) + self.KV_CACHE_BYTES + self.HEADROOM_BYTES
233
+ args: dict[str, Any] = {
234
+ "model": self.dir,
235
+ "runner": "pooling",
236
+ "convert": "embed",
237
+ "pooler_config": PoolerConfig(pooling_type="LAST", use_activation=False),
238
+ "dtype": "bfloat16",
239
+ "max_model_len": max_tokens,
240
+ "kv_cache_memory_bytes": self.KV_CACHE_BYTES,
241
+ "gpu_memory_utilization": round(min(0.92, need / total), 3),
242
+ "enable_prefix_caching": False,
243
+ "limit_mm_per_prompt": {"image": 0, "video": 0},
244
+ "seed": 0,
245
+ "disable_log_stats": True,
246
+ }
247
+ fields = {f.name for f in dataclasses.fields(EngineArgs)}
248
+ args.update({k: v for k, v in options.items() if k in fields}) # any vLLM engine argument, as given
249
+ if set(options) - fields:
250
+ log.warning("options vLLM does not know, not used: %s", sorted(set(options) - fields))
251
+ self.llm = LLM(**args)
252
+
253
+ def accepts(self, n: int) -> bool:
254
+ return True
255
+
256
+ def hidden(self, ids: Sequence[int]):
257
+ import torch
258
+
259
+ out = self.llm.embed([{"prompt_token_ids": list(ids)}], use_tqdm=False)[0]
260
+ return torch.tensor(out.outputs.embedding, dtype=torch.float32)
261
+
262
+
263
+ class OpenVINO:
264
+ """OpenVINO on the CPU, one compiled model per static length of the build. A prompt is padded on the right to the
265
+ smallest length that holds it and the row of its last token is read: the backbone is causal (attention, the short
266
+ convolution and the delta rule), so the padding never reaches the earlier rows. The weights are float32 in the IR (the
267
+ bf16 weights, exactly) and run with OpenVINO's bf16 inference precision."""
268
+
269
+ name = "openvino"
270
+
271
+ def __init__(self, artifacts: str, build: dict, options: dict):
272
+ import openvino as ov
273
+
274
+ config = {"PERFORMANCE_HINT": "LATENCY", "INFERENCE_PRECISION_HINT": options.get("precision", "bf16")}
275
+ if options.get("threads"):
276
+ config["INFERENCE_NUM_THREADS"] = int(options["threads"])
277
+ config.update(options.get("config") or {})
278
+ core = ov.Core()
279
+ self.pad = int(build["pad_token_id"])
280
+ self.runners = {}
281
+ for length, file in sorted(((int(L), f) for L, f in build["files"].items())):
282
+ compiled = core.compile_model(os.path.join(artifacts, file), "CPU", config)
283
+ self.runners[length] = (compiled.create_infer_request(), compiled.output(0))
284
+ self.lengths = sorted(self.runners)
285
+
286
+ def accepts(self, n: int) -> bool:
287
+ return n <= self.lengths[-1]
288
+
289
+ def hidden(self, ids: Sequence[int]):
290
+ import numpy as np
291
+ import torch
292
+
293
+ n = len(ids)
294
+ length = next(L for L in self.lengths if L >= n)
295
+ request, output = self.runners[length]
296
+ x = np.full((1, length), self.pad, dtype=np.int64)
297
+ x[0, :n] = ids
298
+ out = request.infer({0: x})[output]
299
+ return torch.from_numpy(np.asarray(out[0, n - 1], dtype=np.float32))
300
+
301
+
302
+ class MLX:
303
+ """mlx-lm's Qwen3.5 model on the model directory (it reads model*.safetensors, leaves the picture encoder out and never
304
+ touches readout.safetensors); the text model's output is the hidden state after the final norm."""
305
+
306
+ name = "mlx"
307
+
308
+ def __init__(self, path: str):
309
+ from pathlib import Path
310
+
311
+ import mlx.core as mx
312
+ from mlx_lm.utils import load_model
313
+
314
+ self.mx = mx
315
+ model, _ = load_model(Path(path))
316
+ self.text = model.language_model.model
317
+
318
+ def accepts(self, n: int) -> bool:
319
+ return True
320
+
321
+ def hidden(self, ids: Sequence[int]):
322
+ import numpy as np
323
+ import torch
324
+
325
+ h = self.text(self.mx.array([list(ids)]))[0, -1].astype(self.mx.float32)
326
+ self.mx.eval(h)
327
+ return torch.from_numpy(np.array(h))
328
+
329
+
330
+ class LlamaCpp:
331
+ """llama.cpp's llama-server answering /embedding with the last position's hidden state after the final norm,
332
+ unnormalized (embd_normalize -1). The prompt goes as token ids, so llama.cpp's tokenizer is never used. Either a server
333
+ you run (options["url"]) or one started here on the build's GGUF, on 127.0.0.1, stopped with the model."""
334
+
335
+ name = "llamacpp"
336
+
337
+ def __init__(self, artifacts: str | None, build: dict | None, max_tokens: int, options: dict):
338
+ self.context = int(options.get("context", max_tokens))
339
+ self.process = None
340
+ url = options.get("url")
341
+ if not url:
342
+ gguf = options.get("gguf") or os.path.join(artifacts, build["files"]["gguf"])
343
+ server = options.get("server") or shutil.which("llama-server")
344
+ with socket.socket() as s:
345
+ s.bind(("127.0.0.1", 0))
346
+ port = s.getsockname()[1]
347
+ # the embedding endpoint needs the whole prompt in one micro-batch: batch and micro-batch are the context
348
+ command = [server, "-m", gguf, "--embeddings", "--pooling", "last", "-c", str(self.context), "-b", str(self.context), "-ub", str(self.context),
349
+ "-ngl", str(options.get("gpu_layers", 999)), "--parallel", "1", "--host", "127.0.0.1", "--port", str(port)] # fmt: skip
350
+ if options.get("threads"):
351
+ command += ["-t", str(int(options["threads"]))]
352
+ self.output = tempfile.TemporaryFile()
353
+ self.process = subprocess.Popen(command, stdout=self.output, stderr=subprocess.STDOUT, stdin=subprocess.DEVNULL)
354
+ self._stop = weakref.finalize(self, _stop, self.process)
355
+ url = f"http://127.0.0.1:{port}"
356
+ self._wait(url, float(options.get("start_timeout", 600)))
357
+ self.url = url.rstrip("/") + "/embedding"
358
+
359
+ def _wait(self, url: str, timeout: float) -> None:
360
+ deadline = time.monotonic() + timeout
361
+ while time.monotonic() < deadline:
362
+ if self.process.poll() is not None:
363
+ self.output.seek(0)
364
+ tail = self.output.read().decode("utf-8", "replace")[-2000:]
365
+ raise RuntimeError(f"llama-server stopped (exit {self.process.returncode}):\n{tail}")
366
+ try:
367
+ with urllib.request.urlopen(url + "/health", timeout=5) as r:
368
+ if r.status == 200:
369
+ return
370
+ except (urllib.error.URLError, OSError):
371
+ pass
372
+ time.sleep(0.5)
373
+ raise RuntimeError(f"llama-server did not answer within {timeout:.0f} s")
374
+
375
+ def accepts(self, n: int) -> bool:
376
+ return n <= self.context
377
+
378
+ def hidden(self, ids: Sequence[int]):
379
+ import torch
380
+
381
+ body = json.dumps({"content": list(ids), "embd_normalize": -1, "cache_prompt": False}).encode()
382
+ request = urllib.request.Request(self.url, data=body, headers={"Content-Type": "application/json"})
383
+ with urllib.request.urlopen(request, timeout=600) as r:
384
+ out = json.loads(r.read())
385
+ vector = (out[0] if isinstance(out, list) else out)["embedding"]
386
+ if vector and isinstance(vector[0], list): # one row per position: the last
387
+ vector = vector[-1]
388
+ return torch.tensor(vector, dtype=torch.float32)
389
+
390
+
391
+ def _stop(process: subprocess.Popen) -> None:
392
+ if process.poll() is None:
393
+ process.terminate()
394
+ try:
395
+ process.wait(10)
396
+ except subprocess.TimeoutExpired:
397
+ process.kill()
@@ -0,0 +1,169 @@
1
+ """Build the files a faster backend loads, from a model directory (only read) into a new directory.
2
+
3
+ python -m decisionnode_edge.build openvino path/to/model --out path/to/model-openvino [--lengths 512,2048]
4
+ python -m decisionnode_edge.build gguf path/to/model --out path/to/model-gguf --llama-cpp path/to/llama.cpp
5
+
6
+ openvino The backbone's text path (the token embedding, the layers, the final norm: input_ids [1, L] to the hidden
7
+ states [1, L, hidden]) exported with torch.onnx's dynamo exporter in float32 at each static length, then
8
+ saved as OpenVINO IR with float32 weights (the bf16 weights, exactly); the runtime runs it in bf16. One IR per
9
+ length, since the export unrolls the delta rule over the length: each takes 15 to 20 minutes, and lengths
10
+ above a few thousand tokens take hours. Then each IR is run once against torch. Needs the `openvino` extra
11
+ (openvino, onnx, onnxscript); `--device cuda` (the default when a GPU is present) keeps the weights on the card.
12
+ gguf llama.cpp's converter (convert_hf_to_gguf.py --no-mtp) on links to the backbone files, Q8_0 by default: 8-bit
13
+ keeps the answers, 4-bit does not. Needs a llama.cpp checkout and its converter's Python requirements, in the
14
+ environment of `--python` (default: this one).
15
+
16
+ Both write decisionnode_edge_build.json (the backend, the files, the model's fingerprint, versions, times), which
17
+ EdgeModel.load reads from `artifacts`.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import argparse
23
+ import importlib.metadata
24
+ import json
25
+ import os
26
+ import shutil
27
+ import subprocess
28
+ import sys
29
+ import time
30
+
31
+ from .backends import BUILD_FILE, BUILD_FORMAT, fingerprint, link_model_files
32
+
33
+ DEFAULT_LENGTHS = (512, 2048)
34
+
35
+
36
+ def versions(*names: str) -> dict:
37
+ out = {}
38
+ for name in names:
39
+ try:
40
+ out[name] = importlib.metadata.version(name)
41
+ except importlib.metadata.PackageNotFoundError:
42
+ out[name] = None
43
+ return out
44
+
45
+
46
+ def new_directory(out: str) -> None:
47
+ if os.path.exists(out):
48
+ raise SystemExit(f"{out} exists: the build writes a new directory")
49
+ os.makedirs(out)
50
+
51
+
52
+ def write_record(out: str, record: dict) -> None:
53
+ with open(os.path.join(out, BUILD_FILE), "w", encoding="utf-8") as f:
54
+ json.dump(record, f, indent=2)
55
+ f.write("\n")
56
+
57
+
58
+ def model_name(model: str) -> str:
59
+ with open(os.path.join(model, "decisionnode_edge.json"), encoding="utf-8") as f:
60
+ return json.load(f)["name"]
61
+
62
+
63
+ def build_openvino(model: str, out: str, lengths: list[int], device: str | None) -> dict:
64
+ import numpy as np
65
+ import openvino as ov
66
+ import torch
67
+ from transformers import AutoModelForImageTextToText, AutoTokenizer
68
+
69
+ device = device or ("cuda" if torch.cuda.is_available() else "cpu")
70
+ record = {"format": BUILD_FORMAT, "backend": "openvino", "model": model_name(model), "model_fingerprint": fingerprint(model), "files": {},
71
+ "weights": "float32 (the bf16 weights, exactly); run in bf16", "export_device": device,
72
+ "versions": versions("torch", "transformers", "onnx", "onnxscript", "openvino"), "seconds": {}, "check": {}} # fmt: skip
73
+ tokenizer = AutoTokenizer.from_pretrained(model)
74
+ record["pad_token_id"] = tokenizer.pad_token_id if tokenizer.pad_token_id is not None else 0
75
+
76
+ class LastHidden(torch.nn.Module):
77
+ def __init__(self, text):
78
+ super().__init__()
79
+ self.text = text
80
+
81
+ def forward(self, input_ids):
82
+ return self.text(input_ids=input_ids, use_cache=False).last_hidden_state
83
+
84
+ full = AutoModelForImageTextToText.from_pretrained(model, dtype=torch.float32).to(device).eval()
85
+ text = LastHidden(full.model.language_model).eval()
86
+ generator = torch.Generator().manual_seed(0)
87
+ for length in lengths:
88
+ work = os.path.join(out, f"onnx-{length}")
89
+ os.makedirs(work)
90
+ onnx_file = os.path.join(work, "edge.onnx")
91
+ ids = torch.randint(10, 200000, (1, length), generator=generator).to(device)
92
+ t0 = time.perf_counter()
93
+ with torch.inference_mode():
94
+ torch.onnx.export(text, (ids,), onnx_file, dynamo=True, external_data=True, input_names=["input_ids"], output_names=["last_hidden_state"], optimize=True)
95
+ t1 = time.perf_counter()
96
+ ir = ov.convert_model(onnx_file)
97
+ name = f"openvino-{length}.xml"
98
+ ov.save_model(ir, os.path.join(out, name), compress_to_fp16=False)
99
+ del ir
100
+ shutil.rmtree(work)
101
+ record["files"][str(length)] = name
102
+ record["seconds"][str(length)] = {"export": round(t1 - t0, 1), "convert": round(time.perf_counter() - t1, 1)}
103
+ print(json.dumps({"length": length, **record["seconds"][str(length)]}), flush=True)
104
+
105
+ # each IR against torch (float32) on a prompt shorter than its length, so the padding is read past as at run time
106
+ core = ov.Core()
107
+ for length in lengths:
108
+ n = length - 37
109
+ ids = torch.randint(10, 200000, (1, n), generator=generator)
110
+ with torch.inference_mode():
111
+ want = text(ids.to(device))[0, -1].float().cpu()
112
+ compiled = core.compile_model(os.path.join(out, record["files"][str(length)]), "CPU", {"INFERENCE_PRECISION_HINT": "bf16"})
113
+ x = np.full((1, length), record["pad_token_id"], dtype=np.int64)
114
+ x[0, :n] = ids[0].numpy()
115
+ got = torch.from_numpy(np.asarray(compiled.create_infer_request().infer({0: x})[compiled.output(0)][0, n - 1], dtype=np.float32))
116
+ cosine = float(torch.nn.functional.cosine_similarity(got, want, dim=0))
117
+ record["check"][str(length)] = {"tokens": n, "cosine_to_torch_float32": round(cosine, 6), "largest_difference": round(float((got - want).abs().max()), 4)}
118
+ print(json.dumps({"check": length, **record["check"][str(length)]}), flush=True)
119
+ del compiled
120
+ if not torch.isfinite(got).all() or cosine < 0.99:
121
+ raise SystemExit(f"the IR at {length} tokens does not reproduce the backbone (cosine {cosine:.4f}): {out} is incomplete")
122
+ return record
123
+
124
+
125
+ def build_gguf(model: str, out: str, llama_cpp: str, outtype: str, python: str) -> dict:
126
+ converter = os.path.join(llama_cpp, "convert_hf_to_gguf.py")
127
+ if not os.path.isfile(converter):
128
+ raise SystemExit(f"{converter} not found: --llama-cpp is the llama.cpp checkout")
129
+ source = os.path.join(out, "source") # the converter reads links to the backbone files, never the readout
130
+ os.makedirs(source)
131
+ link_model_files(model, source)
132
+ name = f"model-{outtype}.gguf"
133
+ t0 = time.perf_counter()
134
+ subprocess.run([python, converter, source, "--no-mtp", "--outfile", os.path.join(out, name), "--outtype", outtype], check=True)
135
+ shutil.rmtree(source)
136
+ commit = subprocess.run(["git", "-C", llama_cpp, "rev-parse", "--short", "HEAD"], capture_output=True, text=True).stdout.strip() or None
137
+ return {"format": BUILD_FORMAT, "backend": "llamacpp", "model": model_name(model), "model_fingerprint": fingerprint(model), "files": {"gguf": name},
138
+ "type": outtype, "bytes": os.path.getsize(os.path.join(out, name)), "llama_cpp": commit, "seconds": round(time.perf_counter() - t0, 1)} # fmt: skip
139
+
140
+
141
+ def main(argv: list[str] | None = None) -> int:
142
+ parser = argparse.ArgumentParser(prog="python -m decisionnode_edge.build", description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
143
+ parser.add_argument("backend", choices=("openvino", "gguf"))
144
+ parser.add_argument("model", help="the model directory (only read)")
145
+ parser.add_argument("--out", required=True, help="the directory to write (must not exist)")
146
+ parser.add_argument("--lengths", default=",".join(map(str, DEFAULT_LENGTHS)), help="openvino: the static lengths in tokens (default 512,2048)")
147
+ parser.add_argument("--device", default=None, help="openvino: where the export runs, cuda or cpu (default: cuda when present)")
148
+ parser.add_argument("--llama-cpp", help="gguf: the llama.cpp checkout (its convert_hf_to_gguf.py)")
149
+ parser.add_argument("--type", default="q8_0", choices=("q8_0", "bf16"), help="gguf: the weight type (default q8_0)")
150
+ parser.add_argument("--python", default=sys.executable, help="gguf: the Python that runs llama.cpp's converter (default: this one)")
151
+ args = parser.parse_args(argv)
152
+ for name in ("config.json", "model.safetensors", "decisionnode_edge.json"):
153
+ if not os.path.isfile(os.path.join(args.model, name)):
154
+ raise SystemExit(f"{args.model} is not a DecisionNode Edge model directory (no {name})")
155
+ if args.backend == "gguf" and not args.llama_cpp:
156
+ raise SystemExit("gguf needs --llama-cpp")
157
+ new_directory(args.out)
158
+ if args.backend == "openvino":
159
+ lengths = sorted({int(x) for x in args.lengths.split(",") if x.strip()})
160
+ record = build_openvino(args.model, args.out, lengths, args.device)
161
+ else:
162
+ record = build_gguf(args.model, args.out, args.llama_cpp, args.type, args.python)
163
+ write_record(args.out, record)
164
+ print(json.dumps({k: v for k, v in record.items() if k != "versions"}), flush=True)
165
+ return 0
166
+
167
+
168
+ if __name__ == "__main__":
169
+ sys.exit(main())