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.
Files changed (111) hide show
  1. basal/__init__.py +7 -0
  2. basal/adapter.py +420 -0
  3. basal/adapters.py +8 -0
  4. basal/agree.py +393 -0
  5. basal/attach.py +160 -0
  6. basal/attn512.py +132 -0
  7. basal/auth.py +194 -0
  8. basal/bench.py +367 -0
  9. basal/blockquant.py +227 -0
  10. basal/calibrate.py +2198 -0
  11. basal/chat.py +175 -0
  12. basal/cli.py +70 -0
  13. basal/client.py +8 -0
  14. basal/decision_log.py +189 -0
  15. basal/decision_rules.py +569 -0
  16. basal/decisions.py +158 -0
  17. basal/derive.py +98 -0
  18. basal/disconnect.py +85 -0
  19. basal/engine.py +6023 -0
  20. basal/evidence.py +133 -0
  21. basal/examples/choice.jsonl +8 -0
  22. basal/examples/complex.jsonl +5 -0
  23. basal/examples/labelled_tickets.jsonl +500 -0
  24. basal/examples/local_backend.py +34 -0
  25. basal/examples/noul.jsonl +8 -0
  26. basal/examples/questions.jsonl +20 -0
  27. basal/examples/score.jsonl +8 -0
  28. basal/examples/selfcheck_basal-omni-pico-Q8_0.json +1 -0
  29. basal/examples/selfcheck_basal-omni-pico.json +1 -0
  30. basal/examples/types_demo.py +74 -0
  31. basal/facts.py +497 -0
  32. basal/feedback.py +234 -0
  33. basal/file_identity.py +39 -0
  34. basal/finetune.py +321 -0
  35. basal/fit_decisions.py +944 -0
  36. basal/fla_configs.json +1822 -0
  37. basal/fold.py +206 -0
  38. basal/fonts/OFL-DMSans.txt +93 -0
  39. basal/fonts/OFL-SpaceGrotesk.txt +93 -0
  40. basal/fonts/dm-sans-latin-ext.woff2 +0 -0
  41. basal/fonts/dm-sans-latin.woff2 +0 -0
  42. basal/fonts/space-grotesk-latin-ext.woff2 +0 -0
  43. basal/fonts/space-grotesk-latin.woff2 +0 -0
  44. basal/fp8block.py +100 -0
  45. basal/gdn_graph.py +1792 -0
  46. basal/gemma4.py +726 -0
  47. basal/gemma4_graph.py +931 -0
  48. basal/gguf_export.py +497 -0
  49. basal/identity.py +217 -0
  50. basal/int8block.py +50 -0
  51. basal/interpolate.py +330 -0
  52. basal/jsonl.py +172 -0
  53. basal/lean.py +204 -0
  54. basal/llama_attn.py +252 -0
  55. basal/llama_attn_kernels.py +266 -0
  56. basal/llama_graph.py +587 -0
  57. basal/llama_kernels.py +593 -0
  58. basal/loadtest.py +189 -0
  59. basal/mcp_server.py +432 -0
  60. basal/media.py +138 -0
  61. basal/metrics.py +16 -0
  62. basal/mlx_attn_kernels.py +1057 -0
  63. basal/mlx_forward.py +326 -0
  64. basal/mlx_kernels.py +543 -0
  65. basal/mlx_metal.py +510 -0
  66. basal/navcut.py +283 -0
  67. basal/navigate.py +646 -0
  68. basal/navtree.py +397 -0
  69. basal/nvfp4.py +245 -0
  70. basal/ordercheck.py +165 -0
  71. basal/pdf.py +183 -0
  72. basal/prepared.py +355 -0
  73. basal/presets.py +8 -0
  74. basal/prompt.py +462 -0
  75. basal/rank.py +373 -0
  76. basal/readout.py +121 -0
  77. basal/request.py +327 -0
  78. basal/response_cache.py +105 -0
  79. basal/router.py +1551 -0
  80. basal/router_ui.html +902 -0
  81. basal/router_ui.py +277 -0
  82. basal/run.py +376 -0
  83. basal/selfcheck.py +215 -0
  84. basal/server.py +5279 -0
  85. basal/sets.py +214 -0
  86. basal/signals.py +28 -0
  87. basal/state_disk.py +942 -0
  88. basal/strix.py +505 -0
  89. basal/synth.py +92 -0
  90. basal/tasks.py +848 -0
  91. basal/textio.py +21 -0
  92. basal/think.py +390 -0
  93. basal/tools.py +171 -0
  94. basal/tpu.py +336 -0
  95. basal/tpu_kernels.py +129 -0
  96. basal/trace.py +125 -0
  97. basal/ui.html +861 -0
  98. basal/ui.py +526 -0
  99. basal/varloop.py +813 -0
  100. basal/varloop_graph.py +1377 -0
  101. basal/varloop_kernels.py +907 -0
  102. basal/viz.html +660 -0
  103. basal/viz.py +375 -0
  104. basal/vllm_unified.py +100 -0
  105. basal_engine-3.0.3.dist-info/METADATA +416 -0
  106. basal_engine-3.0.3.dist-info/RECORD +111 -0
  107. basal_engine-3.0.3.dist-info/WHEEL +5 -0
  108. basal_engine-3.0.3.dist-info/entry_points.txt +21 -0
  109. basal_engine-3.0.3.dist-info/licenses/LICENSE +202 -0
  110. basal_engine-3.0.3.dist-info/licenses/NOTICE +34 -0
  111. basal_engine-3.0.3.dist-info/top_level.txt +1 -0
basal/__init__.py ADDED
@@ -0,0 +1,7 @@
1
+ """basal: fast, calibrated typed decisions (choice / yes-no / score) for Polish and English."""
2
+ import os
3
+
4
+ __version__ = "3.0.3"
5
+ # TORCHINDUCTOR_CACHE_DIR as given before anything imported torch's compiler (importing transformers' models makes
6
+ # Inductor write its /tmp default there): engine.persist_compile_cache keeps a directory the user chose
7
+ INDUCTOR_CACHE_DIR_GIVEN = bool(os.environ.get("TORCHINDUCTOR_CACHE_DIR"))
basal/adapter.py ADDED
@@ -0,0 +1,420 @@
1
+ """LoRA adapters: read an mlx-lm or PEFT adapter directory, merge it into a model's weights at load (torch, MLX, the
2
+ TPU backend's numpy weights), and fuse it into a checkpoint (basal-fuse-adapter; also the copy vLLM and SGLang serve
3
+ under --adapter, fused_copy) for the engines that load weights basal cannot touch.
4
+
5
+ Formats, by the files in the directory:
6
+ mlx-lm adapter_config.json (fine_tune_type "lora" or absent, lora_parameters.scale) + adapters.safetensors,
7
+ keys <path>.lora_a [in, r] / <path>.lora_b [r, out]
8
+ PEFT adapter_config.json (peft_type "LORA", r, lora_alpha, use_rslora) + adapter_model.safetensors,
9
+ keys base_model.model.<path>.lora_A.weight [r, in] / .lora_B.weight [out, r]
10
+
11
+ The merge is PEFT's merge_and_unload on the CPU, on every framework: delta = (b @ a) * scale in float32 ([out, in],
12
+ torch's CPU GEMM, the factors float32 whatever their stored dtype), added to the weight in float32 and rounded once to
13
+ the weight's dtype. (mlx-lm's LoRALinear.fuse rounds the delta to the weight's dtype before adding it: about 0.4% of a
14
+ merged bf16 weight's elements then end one unit in the last place apart, which moved near-tie answers.)"""
15
+ import argparse
16
+ import atexit
17
+ import functools
18
+ import hashlib
19
+ import json
20
+ import math
21
+ import re
22
+ import shutil
23
+ import tempfile
24
+ from dataclasses import dataclass, field
25
+ from pathlib import Path
26
+
27
+ import numpy as np
28
+
29
+ from . import derive
30
+ from .textio import read_text
31
+
32
+ MLX_WEIGHTS, PEFT_WEIGHTS, CONFIG = "adapters.safetensors", "adapter_model.safetensors", "adapter_config.json"
33
+ # a text decoder's layer under the prefixes of mlx-lm, PEFT and transformers (model., base_model.model.model.,
34
+ # language_model.model., base_model.model.model.language_model. ...); anything else (vision_tower.encoder.layers.N,
35
+ # audio_tower...) is another tower whose layer N is not the decoder's
36
+ _LAYER = re.compile(r"^(?:(?:base_model|model|language_model)\.)*layers\.(\d+)\.(.+)$")
37
+ _MLX_KEY = re.compile(r"^(.+)\.lora_([ab])$")
38
+ _PEFT_KEY = re.compile(r"^(.+)\.lora_([AB])(?:\.[^.]+)?\.weight$")
39
+
40
+
41
+ @dataclass
42
+ class Adapter:
43
+ path: Path
44
+ name: str # the directory's basename
45
+ identity: str # name@sha256(adapter_config.json + weights file)[:12]: what a calibration file is fitted with
46
+ scale: float
47
+ rank: int
48
+ fmt: str # "mlx" | "peft"
49
+ deltas: dict = field(default_factory=dict) # canonical key -> (a [r, in], b [out, r]), float32
50
+
51
+
52
+ def _name(path):
53
+ return Path(path).resolve().name
54
+
55
+
56
+ def _fail(path, why):
57
+ raise SystemExit(f"--adapter {_name(path)}: {why}")
58
+
59
+
60
+ def validate(path):
61
+ """Refuse (SystemExit) what is not a plain LoRA adapter directory -> (fmt, weights file, scale)."""
62
+ p = Path(path)
63
+ if not (p / CONFIG).is_file():
64
+ _fail(path, f"no {CONFIG} in {p} (an mlx-lm or PEFT LoRA adapter directory)")
65
+ cfg = json.loads((p / CONFIG).read_text(encoding="utf-8"))
66
+ if "peft_type" in cfg:
67
+ if cfg["peft_type"] != "LORA":
68
+ _fail(path, f"peft_type {cfg['peft_type']}: only LORA adapters can be merged")
69
+ if cfg.get("use_dora"):
70
+ _fail(path, "a DoRA adapter (use_dora): only LORA adapters can be merged")
71
+ if cfg.get("fan_in_fan_out"):
72
+ _fail(path, "fan_in_fan_out (Conv1D layers): not a layout the engines use")
73
+ if cfg.get("rank_pattern") or cfg.get("alpha_pattern"):
74
+ _fail(path, "rank_pattern / alpha_pattern: per-module scales are not supported")
75
+ r, alpha = cfg.get("r"), cfg.get("lora_alpha")
76
+ if not r or alpha is None:
77
+ _fail(path, f"{CONFIG} lacks r / lora_alpha")
78
+ fmt, weights, scale = "peft", p / PEFT_WEIGHTS, alpha / (math.sqrt(r) if cfg.get("use_rslora") else r)
79
+ else:
80
+ kind = cfg.get("fine_tune_type", "lora")
81
+ if kind != "lora":
82
+ _fail(path, f"fine_tune_type {kind}: only LoRA adapters can be merged")
83
+ lp = cfg.get("lora_parameters") or {}
84
+ if "scale" not in lp:
85
+ _fail(path, f"{CONFIG} lacks lora_parameters.scale")
86
+ fmt, weights, scale = "mlx", p / MLX_WEIGHTS, float(lp["scale"])
87
+ if not weights.is_file():
88
+ _fail(path, f"no {weights.name} next to its {fmt} {CONFIG}")
89
+ return fmt, weights, float(scale)
90
+
91
+
92
+ def identity(path):
93
+ """The adapter's identity without reading the tensors: name@sha256 of adapter_config.json (scale, rank) followed by
94
+ the weights file, 12 hex digits."""
95
+ _, weights, _ = validate(path)
96
+ h = hashlib.sha256((Path(path) / CONFIG).read_bytes())
97
+ with open(weights, "rb") as fh:
98
+ for chunk in iter(lambda: fh.read(1 << 20), b""):
99
+ h.update(chunk)
100
+ return f"{_name(path)}@{h.hexdigest()[:12]}"
101
+
102
+
103
+ def canonical(key):
104
+ """'layers.N.<rest>' from a module path of the text decoder under any framework prefix; ValueError for a module
105
+ outside the decoder layers (an embedding, the head, a vision or audio tower)."""
106
+ m = _LAYER.match(key)
107
+ if not m:
108
+ raise ValueError(f"{key}: not a module of the text decoder's layers (layers.N.<module>)")
109
+ return f"layers.{m[1]}.{m[2]}"
110
+
111
+
112
+ def read(path):
113
+ from safetensors.torch import load_file # (the numpy reader has no bfloat16: PEFT / Unsloth save bf16 adapters)
114
+ fmt, weights, scale = validate(path)
115
+ pat = _MLX_KEY if fmt == "mlx" else _PEFT_KEY
116
+ parts = {}
117
+ for k, v in load_file(str(weights)).items():
118
+ m = pat.match(k)
119
+ if not m:
120
+ _fail(path, f"{k}: not a LoRA tensor (lora_a / lora_b, lora_A / lora_B)")
121
+ try:
122
+ key = canonical(m[1])
123
+ except ValueError as e:
124
+ _fail(path, str(e))
125
+ side = m[2].lower()
126
+ if side in parts.setdefault(key, {}):
127
+ _fail(path, f"{k}: a second {side} tensor for {key}")
128
+ v = np.asarray(v.float().numpy(), dtype=np.float32)
129
+ parts[key][side] = v.T if fmt == "mlx" else v # mlx-lm stores a [in, r], b [r, out]
130
+ deltas = {}
131
+ for key, ab in sorted(parts.items()):
132
+ if len(ab) != 2:
133
+ _fail(path, f"{key}: lora_{'b' if 'a' in ab else 'a'} is missing")
134
+ a, b = np.ascontiguousarray(ab["a"]), np.ascontiguousarray(ab["b"])
135
+ if a.ndim != 2 or b.ndim != 2 or a.shape[0] != b.shape[1]:
136
+ _fail(path, f"{key}: lora shapes a {a.shape} / b {b.shape} do not chain")
137
+ deltas[key] = (a, b)
138
+ if not deltas:
139
+ _fail(path, f"{weights.name} holds no LoRA tensors")
140
+ p = Path(path).resolve()
141
+ return Adapter(path=p, name=p.name, identity=identity(p), scale=scale,
142
+ rank=max(a.shape[0] for a, _ in deltas.values()), fmt=fmt, deltas=deltas)
143
+
144
+
145
+ def delta(ad, key):
146
+ """The update of one module as PEFT's merge computes it on the CPU: (b @ a) * scale in float32 ([out, in]), a torch
147
+ tensor. Every merge (torch on any device, MLX, the TPU's numpy weights, basal-fuse-adapter) takes it from here and
148
+ adds it with merged(), so --adapter and the fused checkpoint get bit-identical weights whatever GEMM the device
149
+ would have used."""
150
+ import torch
151
+ a, b = ad.deltas[key]
152
+ with torch.no_grad():
153
+ return (torch.from_numpy(b) @ torch.from_numpy(a)) * ad.scale
154
+
155
+
156
+ def merged(w, d):
157
+ """Weight w (torch) plus the float32 delta d, added in float32 and rounded once to w's dtype (PEFT's
158
+ `weight.data += delta` with a float32 delta)."""
159
+ return (w.float() + d.to(w.device)).to(w.dtype)
160
+
161
+
162
+ def _layers(ad, get):
163
+ try:
164
+ return get()
165
+ except AttributeError:
166
+ raise SystemExit(f"--adapter {ad.name}: the model has no decoder layers (model.layers) to merge into") from None
167
+
168
+
169
+ def _target(ad, layers, key):
170
+ _, n, rest = key.split(".", 2)
171
+ try:
172
+ layer = layers[int(n)]
173
+ parent = functools.reduce(getattr, rest.split(".")[:-1], layer)
174
+ return parent, rest.split(".")[-1], getattr(parent, rest.split(".")[-1])
175
+ except (IndexError, AttributeError):
176
+ raise SystemExit(f"--adapter {ad.name}: {key}: no such module in the model") from None
177
+
178
+
179
+ def _check_shape(ad, key, shape):
180
+ a, b = ad.deltas[key]
181
+ if tuple(shape) != (b.shape[0], a.shape[1]):
182
+ raise SystemExit(f"--adapter {ad.name}: {key}: the model's weight is {tuple(shape)}, the adapter's delta "
183
+ f"{(b.shape[0], a.shape[1])}")
184
+
185
+
186
+ def merge_torch(model, ad):
187
+ """Merge into a transformers model's decoder linears in place -> the number of merged modules."""
188
+ import torch
189
+ root = getattr(model, "model", model)
190
+ root = getattr(root, "language_model", root)
191
+ layers = _layers(ad, lambda: root.layers)
192
+ with torch.no_grad():
193
+ for key in ad.deltas:
194
+ _, _, mod = _target(ad, layers, key)
195
+ if not isinstance(mod, torch.nn.Linear):
196
+ raise SystemExit(f"--adapter {ad.name}: {key}: {type(mod).__name__} is not a linear layer the "
197
+ "adapter can be merged into")
198
+ w = mod.weight
199
+ if w.dtype in (torch.float8_e4m3fn, torch.float8_e5m2):
200
+ raise SystemExit(f"--adapter {ad.name}: {key}: FP8 weights cannot take a merge")
201
+ if not w.dtype.is_floating_point or w.element_size() < 2: # (int8 / 4-bit quantised linears)
202
+ raise SystemExit(f"--adapter {ad.name}: {key}: {str(w.dtype).replace('torch.', '')} weights cannot "
203
+ "take a merge (merge into the bf16 model)")
204
+ _check_shape(ad, key, w.shape)
205
+ w.copy_(merged(w, delta(ad, key)))
206
+ return len(ad.deltas)
207
+
208
+
209
+ def merge_mlx(model, ad):
210
+ """Merge into an mlx-lm model's decoder linears in place (QuantizedLinear: dequantised, merged and re-quantised
211
+ with its group size and bits, as LoRALinear.fuse) -> the number of merged modules. Each merged weight is evaluated
212
+ here, so on a lazily loaded model (MLXBackend's q8) only the adapter's layers are materialised in bf16."""
213
+ import mlx.core as mx
214
+ import mlx.nn as nn
215
+ lm = getattr(model, "language_model", model)
216
+ layers = _layers(ad, lambda: lm.model.layers)
217
+ for key in ad.deltas:
218
+ parent, attr, mod = _target(ad, layers, key)
219
+ quantized = isinstance(mod, nn.QuantizedLinear)
220
+ if not (quantized or isinstance(mod, nn.Linear)):
221
+ raise SystemExit(f"--adapter {ad.name}: {key}: {type(mod).__name__} is not a linear layer the adapter "
222
+ "can be merged into")
223
+ w = mod.weight
224
+ if quantized:
225
+ w = mx.dequantize(w, mod.scales, mod.biases, group_size=mod.group_size, bits=mod.bits, mode=mod.mode)
226
+ _check_shape(ad, key, w.shape)
227
+ w = (w.astype(mx.float32) + mx.array(delta(ad, key).numpy())).astype(w.dtype) # one rounding, as merged()
228
+ if quantized:
229
+ out, inp = w.shape
230
+ fused = nn.Linear(inp, out, bias="bias" in mod)
231
+ fused.weight = w
232
+ if "bias" in mod:
233
+ fused.bias = mod.bias
234
+ fused = nn.QuantizedLinear.from_linear(fused, mod.group_size, mod.bits, mode=mod.mode)
235
+ mx.eval(fused.parameters())
236
+ setattr(parent, attr, fused)
237
+ else:
238
+ mx.eval(w)
239
+ mod.weight = w
240
+ return len(ad.deltas)
241
+
242
+
243
+ def merge_numpy(weights, ad):
244
+ """Merge into Hugging Face-named numpy weights ("model.layers.N.<rest>.weight"; bf16 through ml_dtypes); the
245
+ entries are replaced (the arrays may be read-only memory maps) -> the number of merged modules."""
246
+ for key in ad.deltas:
247
+ name = f"model.{key}.weight"
248
+ if name not in weights:
249
+ raise SystemExit(f"--adapter {ad.name}: {key}: no such module in the model")
250
+ w = np.asarray(weights[name])
251
+ _check_shape(ad, key, w.shape)
252
+ weights[name] = (w.astype(np.float32) + delta(ad, key).numpy()).astype(w.dtype) # one rounding, as merged()
253
+ return len(ad.deltas)
254
+
255
+
256
+ def _temp_dir():
257
+ out = Path(tempfile.mkdtemp(prefix="basal-adapter-"))
258
+ atexit.register(shutil.rmtree, out, True) # read by the engine's own process until basal-serve exits
259
+ return out
260
+
261
+
262
+ def _weight_names(ad, md):
263
+ """{canonical key: (safetensors file, tensor name)} of the adapter's modules in checkpoint md; refused when a module
264
+ is missing or found twice."""
265
+ from safetensors import safe_open
266
+ found = {}
267
+ for f in sorted(Path(md).glob("*.safetensors")):
268
+ with safe_open(f, "pt") as st:
269
+ for name in st.keys():
270
+ if not name.endswith(".weight"):
271
+ continue
272
+ try:
273
+ key = canonical(name.removesuffix(".weight"))
274
+ except ValueError:
275
+ continue # not a decoder layer (embeddings, the head, a vision or audio tower)
276
+ if key in ad.deltas:
277
+ if key in found:
278
+ raise SystemExit(f"--adapter {ad.name}: {key}: two weights in {md} ({found[key][1]}, {name})")
279
+ found[key] = (f, name)
280
+ missing = sorted(set(ad.deltas) - set(found))
281
+ if missing:
282
+ raise SystemExit(f"--adapter {ad.name}: {missing[0]}: no such module in the model"
283
+ + (f" (and {len(missing) - 1} more)" if len(missing) > 1 else ""))
284
+ return found
285
+
286
+
287
+ def fuse_checkpoint(md, ad, out):
288
+ """Write checkpoint md with the adapter merged into `out` (a new or empty directory): every safetensors file again,
289
+ with the same tensor names, dtypes and metadata, its decoder layers' weights merged as merge_torch merges them
290
+ (merged()), so a server of `out` loads the weights --adapter merges at load bit for bit; every other file is copied
291
+ as it is (config.json, the index, tokenizer, template, basal.json), but not subdirectories nor what does not hold
292
+ for other weights (derive.stale: the base model's calibrations, NVFP4 activation scales, evidence head, card,
293
+ manifest and checksums; the adapter's calibration is copied, fused_calibration) -> the number of merged modules.
294
+ FP8 and integer weights cannot take a merge (refused)."""
295
+ import torch
296
+ from safetensors import safe_open
297
+ from safetensors.torch import save_file
298
+ md, out = Path(md), Path(out)
299
+ names = _weight_names(ad, md)
300
+ by_file = {}
301
+ for key, (f, name) in names.items():
302
+ by_file.setdefault(f, {})[name] = key
303
+ out.mkdir(parents=True, exist_ok=True)
304
+ for f in sorted(md.glob("*.safetensors")):
305
+ if f not in by_file: # nothing of the adapter in this file: the same bytes
306
+ shutil.copyfile(f, out / f.name)
307
+ continue
308
+ tensors = {}
309
+ with safe_open(f, "pt") as st:
310
+ meta = st.metadata()
311
+ for name in st.keys():
312
+ t = st.get_tensor(name)
313
+ key = by_file[f].get(name)
314
+ if key is not None:
315
+ if t.dtype not in (torch.bfloat16, torch.float16, torch.float32):
316
+ raise SystemExit(f"--adapter {ad.name}: {key}: {t.dtype} weights cannot take a merge (an FP8 "
317
+ "checkpoint: fuse the bf16 repository)")
318
+ _check_shape(ad, key, t.shape)
319
+ t = merged(t, delta(ad, key))
320
+ tensors[name] = t
321
+ save_file(tensors, str(out / f.name), metadata=meta)
322
+ del tensors
323
+ for f in sorted(md.iterdir()):
324
+ if f.is_file() and f.suffix != ".safetensors" and not derive.stale(f.name):
325
+ shutil.copy2(f, out / f.name)
326
+ return len(names)
327
+
328
+
329
+ def check_space(md, where, why):
330
+ """Refuse (SystemExit, before anything is written) when the file system of `where` (or its nearest existing
331
+ parent) has less free space than checkpoint md's weights plus 1 GB."""
332
+ where = Path(where).resolve()
333
+ while not where.exists():
334
+ where = where.parent
335
+ need = sum(f.stat().st_size for f in Path(md).glob("*.safetensors")) + (1 << 30)
336
+ free = shutil.disk_usage(where).free
337
+ if free < need:
338
+ raise SystemExit(f"{why}: {need / 2 ** 30:.1f} GB needed in {where}, {free / 2 ** 30:.1f} GB free")
339
+
340
+
341
+ def fused_copy(md, ad):
342
+ """--adapter for the engines that load a checkpoint themselves (vLLM, SGLang): the checkpoint with the adapter
343
+ merged (fuse_checkpoint) in a temporary directory ($TMPDIR; the model's size on disk), removed when basal exits;
344
+ the engine serves it as it serves basal-fuse-adapter's output -> its path. Written by a child process
345
+ (basal-fuse-adapter): the server process never runs torch's CPU thread pool before vLLM forks its engine (a forked
346
+ child deadlocks on that pool), and the shard it holds in memory is freed when the child exits."""
347
+ import os
348
+ import subprocess
349
+ import sys
350
+ check_space(md, tempfile.gettempdir(), f"--adapter {ad.name}: vLLM / SGLang serve a merged copy of the checkpoint "
351
+ "(the size of its weights) in $TMPDIR; set TMPDIR to a directory with room for it, or serve a "
352
+ "checkpoint written by basal-fuse-adapter")
353
+ out = _temp_dir()
354
+ here = str(Path(__file__).resolve().parent.parent) # this basal package, whatever the child's working directory
355
+ env = dict(os.environ, PYTHONPATH=os.pathsep.join(x for x in (here, os.environ.get("PYTHONPATH")) if x))
356
+ r = subprocess.run([sys.executable, "-m", "basal.adapter", "--model", str(md), "--adapter", str(ad.path),
357
+ "--out", str(out)], capture_output=True, text=True, env=env)
358
+ if r.returncode:
359
+ raise SystemExit((r.stderr.strip().splitlines() or [f"basal-fuse-adapter exited with {r.returncode}"])[-1])
360
+ print(f"basal: --adapter {ad.name}: {len(ad.deltas)} layers merged into a copy of the checkpoint at {out} "
361
+ "(removed at exit)", flush=True)
362
+ return out
363
+
364
+
365
+ def fused_calibration(cal, ad, out, source=None):
366
+ """An adapter's calibration file for the merged checkpoint `out`: fitted_on names the merged model (no revision, no
367
+ model files, no adapter) and keeps the origin as fused_from; None for a file fitted with another adapter (or
368
+ none)."""
369
+ from .server import UNVALIDATED_OUT, calibration_mismatch, model_content_id
370
+ if source is not None and any(cal.get(k) for k in UNVALIDATED_OUT):
371
+ if calibration_mismatch(cal, str(source), source, adapter=ad):
372
+ return None
373
+ fitted = cal.get("fitted_on")
374
+ if not isinstance(fitted, dict) or not fitted.get("model"):
375
+ return cal # not written by basal-calibrate: copied as it is
376
+ if fitted.get("adapter") != ad.identity:
377
+ return None
378
+ origin = fitted["model"] + (f"@{fitted['revision'][:12]}" if fitted.get("revision") else "")
379
+ fitted = {k: v for k, v in fitted.items() if k not in ("revision", "model_files", "adapter")}
380
+ fitted["model_content"] = model_content_id(out)
381
+ fitted.pop("model_weights", None)
382
+ return dict(cal, fitted_on=dict(fitted, model=Path(out).resolve().name, fused_from=f"{origin}+{ad.identity}"))
383
+
384
+
385
+ def main():
386
+ ap = argparse.ArgumentParser(description="Merge a LoRA adapter into a model and write the merged checkpoint (for "
387
+ "the engines that cannot take --adapter: GGUF via basal-export-gguf, Ollama, "
388
+ "llama.cpp, FP8 ports). The safetensors files are rewritten with the decoder layers' "
389
+ "weights merged as --adapter merges them at load (same names and dtypes); the other "
390
+ "files are copied, except the base model's CALIBRATION files.")
391
+ ap.add_argument("--model", required=True, help="model directory or Hugging Face repo id")
392
+ ap.add_argument("--revision", default=None)
393
+ ap.add_argument("--adapter", required=True, help="LoRA adapter directory (mlx-lm or PEFT)")
394
+ ap.add_argument("--out", required=True, help="output directory (new or empty)")
395
+ a = ap.parse_args()
396
+ out = Path(a.out)
397
+ if out.exists() and not out.is_dir():
398
+ raise SystemExit(f"--out {out}: not a directory")
399
+ if out.exists() and any(out.iterdir()):
400
+ raise SystemExit(f"--out {out}: exists and is not empty")
401
+ from .engine import resolve
402
+ why = derive.modelopt_refused(resolve(a.model, a.revision, metadata_only=True), a.model, "basal-fuse-adapter",
403
+ "merge the adapter into")
404
+ if why: # (before the weights download; --adapter's merged copy for vLLM / SGLang runs this too)
405
+ raise SystemExit(why)
406
+ ad = read(a.adapter)
407
+ md = resolve(a.model, a.revision)
408
+ check_space(md, out, f"--out {out}: the merged checkpoint has the size of the model's weights")
409
+ n = fuse_checkpoint(md, ad, out)
410
+ for f in sorted(ad.path.glob("CALIBRATION*.json")): # fitted with this adapter
411
+ cal = fused_calibration(json.loads(read_text(f)), ad, out, source=md)
412
+ if cal is None:
413
+ print(f"basal-fuse-adapter: {f.name} does not match the source weights and adapter {ad.identity}: not copied")
414
+ else:
415
+ (out / f.name).write_text(json.dumps(cal, indent=1, ensure_ascii=False) + "\n", encoding="utf-8")
416
+ print(f"fused {n} layers of {ad.name} into {out}")
417
+
418
+
419
+ if __name__ == "__main__":
420
+ main()
basal/adapters.py ADDED
@@ -0,0 +1,8 @@
1
+ """basal.adapters is basal_sdk.adapters, 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.adapters patches basal_sdk.adapters."""
4
+ import sys
5
+
6
+ from basal_sdk import adapters
7
+
8
+ sys.modules[__name__] = adapters