basal-engine 3.0.3__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.
- basal/__init__.py +7 -0
- basal/adapter.py +420 -0
- basal/adapters.py +8 -0
- basal/agree.py +393 -0
- basal/attach.py +160 -0
- basal/attn512.py +132 -0
- basal/auth.py +194 -0
- basal/bench.py +367 -0
- basal/blockquant.py +227 -0
- basal/calibrate.py +2198 -0
- basal/chat.py +175 -0
- basal/cli.py +70 -0
- basal/client.py +8 -0
- basal/decision_log.py +189 -0
- basal/decision_rules.py +569 -0
- basal/decisions.py +158 -0
- basal/derive.py +98 -0
- basal/disconnect.py +85 -0
- basal/engine.py +6023 -0
- basal/evidence.py +133 -0
- basal/examples/choice.jsonl +8 -0
- basal/examples/complex.jsonl +5 -0
- basal/examples/labelled_tickets.jsonl +500 -0
- basal/examples/local_backend.py +34 -0
- basal/examples/noul.jsonl +8 -0
- basal/examples/questions.jsonl +20 -0
- basal/examples/score.jsonl +8 -0
- basal/examples/selfcheck_basal-omni-pico-Q8_0.json +1 -0
- basal/examples/selfcheck_basal-omni-pico.json +1 -0
- basal/examples/types_demo.py +74 -0
- basal/facts.py +497 -0
- basal/feedback.py +234 -0
- basal/file_identity.py +39 -0
- basal/finetune.py +321 -0
- basal/fit_decisions.py +944 -0
- basal/fla_configs.json +1822 -0
- basal/fold.py +206 -0
- basal/fonts/OFL-DMSans.txt +93 -0
- basal/fonts/OFL-SpaceGrotesk.txt +93 -0
- basal/fonts/dm-sans-latin-ext.woff2 +0 -0
- basal/fonts/dm-sans-latin.woff2 +0 -0
- basal/fonts/space-grotesk-latin-ext.woff2 +0 -0
- basal/fonts/space-grotesk-latin.woff2 +0 -0
- basal/fp8block.py +100 -0
- basal/gdn_graph.py +1792 -0
- basal/gemma4.py +726 -0
- basal/gemma4_graph.py +931 -0
- basal/gguf_export.py +497 -0
- basal/identity.py +217 -0
- basal/int8block.py +50 -0
- basal/interpolate.py +330 -0
- basal/jsonl.py +172 -0
- basal/lean.py +204 -0
- basal/llama_attn.py +252 -0
- basal/llama_attn_kernels.py +266 -0
- basal/llama_graph.py +587 -0
- basal/llama_kernels.py +593 -0
- basal/loadtest.py +189 -0
- basal/mcp_server.py +432 -0
- basal/media.py +138 -0
- basal/metrics.py +16 -0
- basal/mlx_attn_kernels.py +1057 -0
- basal/mlx_forward.py +326 -0
- basal/mlx_kernels.py +543 -0
- basal/mlx_metal.py +510 -0
- basal/navcut.py +283 -0
- basal/navigate.py +646 -0
- basal/navtree.py +397 -0
- basal/nvfp4.py +245 -0
- basal/ordercheck.py +165 -0
- basal/pdf.py +183 -0
- basal/prepared.py +355 -0
- basal/presets.py +8 -0
- basal/prompt.py +462 -0
- basal/rank.py +373 -0
- basal/readout.py +121 -0
- basal/request.py +327 -0
- basal/response_cache.py +105 -0
- basal/router.py +1551 -0
- basal/router_ui.html +902 -0
- basal/router_ui.py +277 -0
- basal/run.py +376 -0
- basal/selfcheck.py +215 -0
- basal/server.py +5279 -0
- basal/sets.py +214 -0
- basal/signals.py +28 -0
- basal/state_disk.py +942 -0
- basal/strix.py +505 -0
- basal/synth.py +92 -0
- basal/tasks.py +848 -0
- basal/textio.py +21 -0
- basal/think.py +390 -0
- basal/tools.py +171 -0
- basal/tpu.py +336 -0
- basal/tpu_kernels.py +129 -0
- basal/trace.py +125 -0
- basal/ui.html +861 -0
- basal/ui.py +526 -0
- basal/varloop.py +813 -0
- basal/varloop_graph.py +1377 -0
- basal/varloop_kernels.py +907 -0
- basal/viz.html +660 -0
- basal/viz.py +375 -0
- basal/vllm_unified.py +100 -0
- basal_engine-3.0.3.dist-info/METADATA +416 -0
- basal_engine-3.0.3.dist-info/RECORD +111 -0
- basal_engine-3.0.3.dist-info/WHEEL +5 -0
- basal_engine-3.0.3.dist-info/entry_points.txt +21 -0
- basal_engine-3.0.3.dist-info/licenses/LICENSE +202 -0
- basal_engine-3.0.3.dist-info/licenses/NOTICE +34 -0
- basal_engine-3.0.3.dist-info/top_level.txt +1 -0
basal/prepared.py
ADDED
|
@@ -0,0 +1,355 @@
|
|
|
1
|
+
"""Prepared start-up (2.5): what the CUDA graph engine computes at its first start on a GPU class, saved once and loaded
|
|
2
|
+
at every later start, so a server starts warm and with the same kernels every time.
|
|
3
|
+
|
|
4
|
+
A start compiles the engine's layer functions (torch.compile / Inductor: code generation and the autotuning of its
|
|
5
|
+
kernels by timing) and, for Qwen3.5 models, times fla's Triton kernels at their first launch. That is most of the
|
|
6
|
+
150-600 s a server needs before it answers, and the timing can pick other kernels in another start (other last bits).
|
|
7
|
+
`basal-prepare` starts the engine once (its warm-up compiles every graph family at its first shapes, where every
|
|
8
|
+
compile happens, and captures every shape; Qwen3.5 warms every shape) and writes into one directory:
|
|
9
|
+
|
|
10
|
+
- inductor.bin: Inductor's cache artifacts (torch.compiler.save_cache_artifacts: compiled graphs, Triton kernels and
|
|
11
|
+
autotuning results);
|
|
12
|
+
- fla_configs.json (Qwen3.5 models): the configs fla's kernels picked (gdn_graph.fla_record);
|
|
13
|
+
- manifest.json: the key below and what was saved.
|
|
14
|
+
|
|
15
|
+
`basal-serve --prepared auto` (the default) loads a directory whose key matches before the engine is built: from the
|
|
16
|
+
model directory (prepared/<key>/, shipped with a model) or the user cache (~/.cache/basal/prepared/<key>/, where
|
|
17
|
+
basal-prepare writes). The key covers what the compiled code depends on: the GPU (name and compute capability), the
|
|
18
|
+
torch / triton / CUDA versions (fla's for Qwen3.5 models), the Python version and the basal release whose compiled
|
|
19
|
+
code this is (PREPARED_ENGINE), the model's architecture
|
|
20
|
+
(config.json, not its weights: they are inputs of the compiled functions), the mode, dtype and attention. Any
|
|
21
|
+
difference: nothing is loaded and the engine compiles as before. CUDA graphs are still captured at every start (they
|
|
22
|
+
hold device addresses). Inductor checks every loaded entry against its own key as well, so a directory that matches
|
|
23
|
+
but holds kernels for another graph only leaves the start cold: answers never depend on what was loaded.
|
|
24
|
+
|
|
25
|
+
Shipped with a model: a Hugging Face model repository holds prepared/<key>/ per GPU class and environment it was
|
|
26
|
+
built for (basal-prepare --into-model). Downloading the model leaves prepared/ out (resolve); a start with --prepared
|
|
27
|
+
auto fetches the one directory of its own key, if the repository has it (fetch).
|
|
28
|
+
"""
|
|
29
|
+
import argparse
|
|
30
|
+
import functools
|
|
31
|
+
import hashlib
|
|
32
|
+
import json
|
|
33
|
+
import os
|
|
34
|
+
import platform
|
|
35
|
+
import time
|
|
36
|
+
from pathlib import Path
|
|
37
|
+
|
|
38
|
+
import torch
|
|
39
|
+
|
|
40
|
+
FILES = ("inductor.bin", "fla_configs.json", "manifest.json")
|
|
41
|
+
# The compiled-code version, the basal version in the key: bump it when a release changes compiled / graph code (the
|
|
42
|
+
# engine's layer functions); a patch that only changes Python around it keeps it, so the directories shipped in the
|
|
43
|
+
# model repositories still load (2.5.1 keeps 2.5.0's). A new minor release sets its own (tests/test_prepared.py).
|
|
44
|
+
PREPARED_ENGINE = "3.0.0"
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def cache_root():
|
|
48
|
+
return Path(os.environ.get("BASAL_PREPARED_DIR") or Path.home() / ".cache" / "basal" / "prepared")
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def environment():
|
|
52
|
+
"""What compiled code depends on besides the model: GPU, library versions, basal (PREPARED_ENGINE)."""
|
|
53
|
+
python = ".".join(platform.python_version_tuple()[:2]) # (a patch release does not change compiled code)
|
|
54
|
+
env = dict(basal=PREPARED_ENGINE, torch=torch.__version__, cuda=torch.version.cuda, python=python)
|
|
55
|
+
try:
|
|
56
|
+
import triton
|
|
57
|
+
env["triton"] = triton.__version__
|
|
58
|
+
except ImportError:
|
|
59
|
+
env["triton"] = None
|
|
60
|
+
try:
|
|
61
|
+
import fla
|
|
62
|
+
env["fla"] = fla.__version__
|
|
63
|
+
except ImportError:
|
|
64
|
+
env["fla"] = None
|
|
65
|
+
if torch.cuda.is_available():
|
|
66
|
+
env["gpu"] = torch.cuda.get_device_name()
|
|
67
|
+
env["capability"] = list(torch.cuda.get_device_capability())
|
|
68
|
+
else:
|
|
69
|
+
env["gpu"], env["capability"] = None, None
|
|
70
|
+
return env
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def architecture(model_dir):
|
|
74
|
+
"""sha256 of the model's config.json with its keys sorted (the architecture; the weights do not enter the key)."""
|
|
75
|
+
cfg = json.loads((Path(model_dir) / "config.json").read_text(encoding="utf-8"))
|
|
76
|
+
for k in ("_name_or_path", "transformers_version"):
|
|
77
|
+
cfg.pop(k, None)
|
|
78
|
+
return hashlib.sha256(json.dumps(cfg, sort_keys=True).encode()).hexdigest()
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def key_fields(model_dir, mode, dtype="bfloat16", attn="auto", env=None):
|
|
82
|
+
from .gdn_graph import is_gdn
|
|
83
|
+
env = dict(env or environment())
|
|
84
|
+
if not is_gdn(model_dir): # fla's kernels run in Qwen3.5 models only: whether it is installed does not matter
|
|
85
|
+
env.pop("fla", None)
|
|
86
|
+
return dict(env, architecture=architecture(model_dir), mode=mode, dtype=dtype, attn=attn)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def key(fields):
|
|
90
|
+
return hashlib.sha256(json.dumps(fields, sort_keys=True).encode()).hexdigest()[:20]
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def locate(model_dir, fields, spec="auto"):
|
|
94
|
+
"""The prepared directory to load: spec "off" -> None; a path -> that directory if its manifest has these fields;
|
|
95
|
+
"auto" -> <model_dir>/prepared/<key>, then <cache_root>/<key>, the first whose manifest matches. A directory
|
|
96
|
+
counts only when every file its manifest lists is there: one that holds its manifest alone (as a metadata download
|
|
97
|
+
of basal 2.5.0 left it in a model's snapshot) is not loaded, so --prepared auto fetches the rest (fetch)."""
|
|
98
|
+
if spec in (None, "off"):
|
|
99
|
+
return None
|
|
100
|
+
k = key(fields)
|
|
101
|
+
cands = [Path(spec)] if spec != "auto" else [Path(model_dir) / "prepared" / k, cache_root() / k]
|
|
102
|
+
for d in cands:
|
|
103
|
+
m = d / "manifest.json"
|
|
104
|
+
if m.exists():
|
|
105
|
+
man = json.loads(m.read_text(encoding="utf-8"))
|
|
106
|
+
if man.get("fields") == fields and all((d / f).exists() for f in man.get("files", ())):
|
|
107
|
+
return d
|
|
108
|
+
return None
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def fetch(repo, revision, fields):
|
|
112
|
+
"""prepared/<key>/ of a Hugging Face model repository, downloaded next to the model's files (its snapshot) ->
|
|
113
|
+
that directory, or None when the repository has none for this key or the Hub cannot be reached (the engine then
|
|
114
|
+
compiles as before; with HF_HUB_OFFLINE a directory fetched before is used)."""
|
|
115
|
+
k = key(fields)
|
|
116
|
+
try:
|
|
117
|
+
from huggingface_hub import hf_hub_download
|
|
118
|
+
m = Path(hf_hub_download(repo, f"prepared/{k}/manifest.json", revision=revision))
|
|
119
|
+
man = json.loads(m.read_text(encoding="utf-8"))
|
|
120
|
+
except Exception: # (no such file, offline, no network)
|
|
121
|
+
return None
|
|
122
|
+
if man.get("fields") != fields:
|
|
123
|
+
return None
|
|
124
|
+
for f in man.get("files", FILES):
|
|
125
|
+
if f != "manifest.json":
|
|
126
|
+
try:
|
|
127
|
+
hf_hub_download(repo, f"prepared/{k}/{f}", revision=revision)
|
|
128
|
+
except Exception: # (a file this directory does not have; load reads what arrived)
|
|
129
|
+
pass
|
|
130
|
+
return m.parent
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
TRUSTED = ("Remek",) # publishers whose repositories' prepared kernels --prepared auto loads (BASAL_PREPARED_TRUST)
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def trusted(repo):
|
|
137
|
+
"""Whether --prepared auto loads the prepared kernels a Hugging Face repository ships: compiled kernels are code the
|
|
138
|
+
compiler cache runs, a trust beyond reading tensor weights, so only for the publishers in BASAL_PREPARED_TRUST
|
|
139
|
+
(comma-separated owners, "*" = every one; default TRUSTED). A local model directory or --prepared <dir> is
|
|
140
|
+
trusted by whoever points to it; kernels basal-prepare wrote into the user cache are local too."""
|
|
141
|
+
env = os.environ.get("BASAL_PREPARED_TRUST")
|
|
142
|
+
owners = TRUSTED if env is None else tuple(o.strip() for o in env.split(",") if o.strip())
|
|
143
|
+
return "*" in owners or str(repo).split("/")[0] in owners
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def startup(model_dir, fields, spec="auto", model=None, revision=None):
|
|
147
|
+
"""basal-serve's prepared start-up -> what was loaded (load), or None: the directory locate finds, else with spec
|
|
148
|
+
"auto" and a Hugging Face model (`model` not a local path) the one fetched from its repository. A Hugging Face
|
|
149
|
+
model of an untrusted publisher (trusted) loads neither: only the user cache. A given path that holds none for these
|
|
150
|
+
fields stops the start."""
|
|
151
|
+
hub = spec == "auto" and model is not None and not Path(model).exists()
|
|
152
|
+
if hub and not trusted(model):
|
|
153
|
+
d = locate(None, fields, str(cache_root() / key(fields))) # (basal-prepare's own, on this machine)
|
|
154
|
+
if d is None:
|
|
155
|
+
print(f"basal: prepared kernels of {model} not loaded: its publisher is not trusted "
|
|
156
|
+
f"(BASAL_PREPARED_TRUST={str(model).split('/')[0]} trusts it)", flush=True)
|
|
157
|
+
return load(d) if d is not None else None
|
|
158
|
+
d = locate(model_dir, fields, spec)
|
|
159
|
+
if d is None and hub:
|
|
160
|
+
d = fetch(model, revision, fields) # shipped in the model's repository
|
|
161
|
+
if d is None and spec not in ("auto", "off", None):
|
|
162
|
+
raise SystemExit(f"--prepared {spec}: no prepared start-up for this model, mode and GPU there "
|
|
163
|
+
f"(key {key(fields)}; basal-prepare writes one)")
|
|
164
|
+
return load(d) if d is not None else None
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def load(d):
|
|
168
|
+
"""Loads a prepared directory before the engine compiles -> what was loaded (for the start-up line). Inductor's
|
|
169
|
+
cache directory is set first, as the compiling engine sets it (engine.persist_compile_cache): the artifacts are
|
|
170
|
+
written into that directory, so they must land where the engine then looks. A file that cannot be read (a broken
|
|
171
|
+
download) is left out: those kernels compile as without it. Every Inductor file is loaded (inductor.bin: the
|
|
172
|
+
kernels of basal-serve's default flags; inductor-<flags>.bin: of other flag sets, save): Inductor checks each
|
|
173
|
+
entry against its own key, so kernels of flags this start does not use only cost the reading."""
|
|
174
|
+
from .engine import persist_compile_cache
|
|
175
|
+
persist_compile_cache()
|
|
176
|
+
own_autotune_cache()
|
|
177
|
+
out = {"dir": str(d)}
|
|
178
|
+
files, res = sorted(Path(d).glob("inductor*.bin")), []
|
|
179
|
+
for f in files:
|
|
180
|
+
try:
|
|
181
|
+
res.append(_count(torch.compiler.load_cache_artifacts(f.read_bytes())))
|
|
182
|
+
except Exception as e: # noqa: BLE001 (the fla configs below are loaded all the same)
|
|
183
|
+
res.append(f"not loaded ({type(e).__name__})")
|
|
184
|
+
if res: # (several flag sets: per file)
|
|
185
|
+
out["inductor"] = res[0] if len(res) == 1 else {f.name: r for f, r in zip(files, res)}
|
|
186
|
+
f = Path(d) / "fla_configs.json"
|
|
187
|
+
if f.exists():
|
|
188
|
+
from . import gdn_graph
|
|
189
|
+
gdn_graph.FLA_CONFIGS = f # fla_pin reads it when the Qwen3.5 engine is built
|
|
190
|
+
out["fla"] = str(f)
|
|
191
|
+
return out
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def _under(path, root):
|
|
195
|
+
"""A path outside the Inductor cache directory root -> its last two parts (<dir>/<file>, as torch names its cache
|
|
196
|
+
entries) under root; a path inside root, or none, as it is."""
|
|
197
|
+
if not path:
|
|
198
|
+
return path
|
|
199
|
+
p, r = os.path.abspath(path), os.path.abspath(root)
|
|
200
|
+
if p == r or p.startswith(r + os.sep):
|
|
201
|
+
return path
|
|
202
|
+
return os.path.join(r, *Path(p).parts[-2:])
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def _move_autotune_cache(kernel, root):
|
|
206
|
+
"""A loaded kernel's source path and autotune cache entry, both under root (_under)."""
|
|
207
|
+
if getattr(kernel, "filename", None):
|
|
208
|
+
kernel.filename = _under(kernel.filename, root)
|
|
209
|
+
cache = getattr(getattr(kernel, "save_cache_hook", None), "__self__", None)
|
|
210
|
+
local = getattr(cache, "local_cache", None)
|
|
211
|
+
if isinstance(local, tuple) and len(local) == 2 and isinstance(local[1], str):
|
|
212
|
+
cache.local_cache = (local[0], _under(local[1], root))
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def own_autotune_cache():
|
|
216
|
+
"""The autotune results of loaded kernels in this start's own Inductor cache only. A kernel that torch launches
|
|
217
|
+
statically comes out of inductor.bin as a pickled CachingAutotuner that kept the paths of the machine that compiled
|
|
218
|
+
it: its source file (filename) and the autotune cache entry its save hook writes, both in the builder's cache
|
|
219
|
+
(/tmp/basal-prepare/.cache/basal/torchinductor/... for the shipped directories). Such a kernel looked for its
|
|
220
|
+
autotune result there and missed it (load_cache_artifacts writes the prepared results into this start's cache),
|
|
221
|
+
timed its configs again at its first launch, kept that pick there, and read another user's pick when one was
|
|
222
|
+
there. Where that directory belongs to someone else or is read-only, the write raised and the launch failed.
|
|
223
|
+
Before torch rechecks such a kernel's autotune cache, both paths now move under this start's cache, to the same
|
|
224
|
+
<dir>/<file> as the loaded results: the kernel takes the prepared pick, as every other loaded kernel does, and
|
|
225
|
+
nothing is written outside this cache. Installed once; a torch without these internals is left as it is ->
|
|
226
|
+
whether it is installed."""
|
|
227
|
+
try:
|
|
228
|
+
from torch._inductor.runtime.runtime_utils import cache_dir
|
|
229
|
+
from torch._inductor.runtime.triton_heuristics import CachingAutotuner
|
|
230
|
+
except ImportError:
|
|
231
|
+
return False
|
|
232
|
+
recheck = getattr(CachingAutotuner, "recheck_autotune_cache", None)
|
|
233
|
+
if recheck is None:
|
|
234
|
+
return False
|
|
235
|
+
if getattr(recheck, "basal_own_cache", False):
|
|
236
|
+
return True
|
|
237
|
+
|
|
238
|
+
@functools.wraps(recheck)
|
|
239
|
+
def own(self, *args, **kwargs):
|
|
240
|
+
_move_autotune_cache(self, cache_dir())
|
|
241
|
+
return recheck(self, *args, **kwargs)
|
|
242
|
+
own.basal_own_cache = True
|
|
243
|
+
CachingAutotuner.recheck_autotune_cache = own
|
|
244
|
+
return True
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def _count(info):
|
|
248
|
+
"""Artifacts per kind of a torch CacheInfo (a dict of lists in recent torch)."""
|
|
249
|
+
if info is None:
|
|
250
|
+
return 0
|
|
251
|
+
d = getattr(info, "artifacts", None)
|
|
252
|
+
if isinstance(d, dict):
|
|
253
|
+
return sum(len(v) for v in d.values())
|
|
254
|
+
return 1
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def inductor_file(flags=None):
|
|
258
|
+
"""The Inductor file of one engine flag set in a prepared directory: inductor.bin for basal-serve's defaults (as
|
|
259
|
+
2.5.0 named it), inductor-<hash of the flags>.bin for others, so preparing one model with several flag sets
|
|
260
|
+
(the same key: the flags are not in it) adds their kernels instead of replacing them."""
|
|
261
|
+
if not flags:
|
|
262
|
+
return "inductor.bin"
|
|
263
|
+
h = hashlib.sha256(json.dumps(flags, sort_keys=True, default=str).encode()).hexdigest()[:12]
|
|
264
|
+
return f"inductor-{h}.bin"
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def _replace(path, write):
|
|
268
|
+
"""write(tmp) then rename it over path: an interrupted or concurrent save never leaves a truncated file."""
|
|
269
|
+
tmp = path.with_name(f".{path.name}.{os.getpid()}.tmp")
|
|
270
|
+
try:
|
|
271
|
+
out = write(tmp)
|
|
272
|
+
os.replace(tmp, path)
|
|
273
|
+
finally:
|
|
274
|
+
tmp.unlink(missing_ok=True)
|
|
275
|
+
return out
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
def save(d, fields, fla=False, flags=None):
|
|
279
|
+
"""Writes the artifacts of this process's compiles (and fla's picked configs) into d with the manifest; flags:
|
|
280
|
+
the engine flags that differ from basal-serve's defaults (inductor_file). A directory prepared before for the
|
|
281
|
+
same key keeps its other flag sets' files."""
|
|
282
|
+
d = Path(d)
|
|
283
|
+
d.mkdir(parents=True, exist_ok=True)
|
|
284
|
+
saved = {}
|
|
285
|
+
got = torch.compiler.save_cache_artifacts()
|
|
286
|
+
if got is not None:
|
|
287
|
+
data, info = got
|
|
288
|
+
_replace(d / inductor_file(flags), lambda p: p.write_bytes(data))
|
|
289
|
+
saved["inductor"] = _count(info)
|
|
290
|
+
saved["inductor_bytes"] = len(data)
|
|
291
|
+
if fla:
|
|
292
|
+
from .gdn_graph import fla_record
|
|
293
|
+
saved["fla_kernels"] = _replace(d / "fla_configs.json", fla_record)
|
|
294
|
+
try:
|
|
295
|
+
prev = json.loads((d / "manifest.json").read_text(encoding="utf-8"))
|
|
296
|
+
except (OSError, ValueError):
|
|
297
|
+
prev = {}
|
|
298
|
+
sets = prev.get("flag_sets", {}) if prev.get("fields") == fields else {}
|
|
299
|
+
sets[inductor_file(flags)] = flags or {}
|
|
300
|
+
files = sorted(p.name for p in d.iterdir() if p.name in FILES or p.name in sets) + ["manifest.json"]
|
|
301
|
+
man = dict(fields=fields, key=key(fields), saved=saved, files=sorted(set(files)), flag_sets=sets,
|
|
302
|
+
created_utc=time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()))
|
|
303
|
+
_replace(d / "manifest.json", lambda p: p.write_text(json.dumps(man, indent=1, sort_keys=True)))
|
|
304
|
+
return man
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
def main(argv=None):
|
|
308
|
+
"""basal-prepare: start the engine once as basal-serve starts it with the same flags (its warm-up compiles and
|
|
309
|
+
captures every graph shape) and save what a later start of the same model architecture, mode and environment can
|
|
310
|
+
load (basal-serve --prepared auto). Every option but --out / --into-model is basal-serve's, and the engine is built
|
|
311
|
+
by basal-serve's Server: the compiled code depends on the engine flags (--batches, --template-prefix,
|
|
312
|
+
--compile-scope, --merge, ...), so the prepared kernels are those of the configuration the server runs, its
|
|
313
|
+
defaults included (on Hopper: compact rows with the template prefix)."""
|
|
314
|
+
ap = argparse.ArgumentParser(description="prepare the start-up of the CUDA graph engine for this GPU",
|
|
315
|
+
epilog="Every other option is basal-serve's (basal-serve --help): give the model and "
|
|
316
|
+
"the engine flags the server will run with.")
|
|
317
|
+
ap.add_argument("--out", default=None, help="directory to write (default: the user cache, ~/.cache/basal/prepared/"
|
|
318
|
+
"<key>, where basal-serve --prepared auto looks)")
|
|
319
|
+
ap.add_argument("--into-model", dest="into_model", action="store_true",
|
|
320
|
+
help="write into the local model directory, as prepared/<key> (to ship with the model: basal-serve "
|
|
321
|
+
"--prepared auto finds it there, also in the model's Hugging Face repository)")
|
|
322
|
+
a, rest = ap.parse_known_args(argv)
|
|
323
|
+
from .server import MODES, Server, add_engine_args, compiler_refused, default_mode, parser, refuse_lean_flex
|
|
324
|
+
s = parser().parse_args(rest + ["--prepared", "off"]) # (this start compiles what a later one loads)
|
|
325
|
+
if a.into_model and (a.out or not Path(s.model).is_dir()):
|
|
326
|
+
raise SystemExit("--into-model: give --model as a local model directory, without --out")
|
|
327
|
+
if not torch.cuda.is_available():
|
|
328
|
+
raise SystemExit("basal-prepare needs a CUDA GPU (the prepared kernels are for the GPU it runs on)")
|
|
329
|
+
refuse_lean_flex(s.lean, s.tree) # as basal-serve's main, before default_mode
|
|
330
|
+
s.mode = s.mode or default_mode(s.model, s.revision)
|
|
331
|
+
kind, _, comp = MODES[s.mode]
|
|
332
|
+
if kind not in ("graph", "exit") or not comp:
|
|
333
|
+
raise SystemExit(f"basal-prepare: --mode {s.mode} compiles nothing to prepare (the CUDA graph engine's "
|
|
334
|
+
"compiled modes: fast, fp8, nvfp4, ...)")
|
|
335
|
+
why = compiler_refused(s.mode, s.model, s.revision) # (as basal-serve: before the model loads)
|
|
336
|
+
if why:
|
|
337
|
+
raise SystemExit(why)
|
|
338
|
+
defaults = vars(add_engine_args(argparse.ArgumentParser()).parse_args([]))
|
|
339
|
+
keyed = ("model", "revision", "mode", "dtype", "attn", "prepared") # (mode, dtype and attention are in the key)
|
|
340
|
+
flags = {k: v for k, v in sorted(vars(s).items()) if k in defaults and k not in keyed and v != defaults[k]}
|
|
341
|
+
from .gdn_graph import is_gdn
|
|
342
|
+
t0 = time.time()
|
|
343
|
+
if s.think == "off": # checks the flags as basal-serve does, then compiles, autotunes and captures every shape
|
|
344
|
+
srv = Server(s)
|
|
345
|
+
else: # its sidecar takes GPU memory before the graphs are sized, as in basal-serve
|
|
346
|
+
from .think import ThinkServer
|
|
347
|
+
srv = ThinkServer(s)
|
|
348
|
+
fields = key_fields(srv.md, s.mode, s.dtype, s.attn) # the key basal-serve computes for these flags
|
|
349
|
+
out = Path(a.out) if a.out else (Path(srv.md) / "prepared" if a.into_model else cache_root()) / key(fields)
|
|
350
|
+
man = save(out, fields, fla=is_gdn(srv.md), flags=flags)
|
|
351
|
+
print(json.dumps(dict(out=str(out), start_s=round(time.time() - t0, 1), **man), indent=1))
|
|
352
|
+
|
|
353
|
+
|
|
354
|
+
if __name__ == "__main__":
|
|
355
|
+
main()
|
basal/presets.py
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
"""basal.presets is basal_sdk.presets, the same module (the Python client is the basal-sdk distribution since 3.0, and
|
|
2
|
+
basal-engine installs it at its own version): code written for basal 2.x keeps importing it from here, and a monkeypatch
|
|
3
|
+
of basal.presets patches basal_sdk.presets."""
|
|
4
|
+
import sys
|
|
5
|
+
|
|
6
|
+
from basal_sdk import presets
|
|
7
|
+
|
|
8
|
+
sys.modules[__name__] = presets
|