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/identity.py
ADDED
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
"""Identity gate of the fast path: every prefix-reuse path of the basal engine against the eager per-prompt reference.
|
|
2
|
+
|
|
3
|
+
basal-bench --identity --model Remek/basal-1.5-4.5B # fp32: the paths' exactness
|
|
4
|
+
basal-bench --identity --model Remek/basal-1.5-4.5B --dtype bfloat16 # as served
|
|
5
|
+
basal-bench --identity --model Remek/basal-1.5-4.5B --dtype bfloat16 --quant fp8
|
|
6
|
+
|
|
7
|
+
Items are synthetic (basal.synth, no real data): single questions over ~1.5k-token states, requests with five
|
|
8
|
+
questions over one state, and long states (4-8k tokens); every question is rendered in both option orders. The
|
|
9
|
+
reference runs every prompt alone in an eager forward (no padding, no mask, no graph) and reads the option codes from
|
|
10
|
+
the full log-softmax. The paths, each through the engine's normal entry point (run_shared):
|
|
11
|
+
|
|
12
|
+
plain single prompts, one call each (plain CUDA graphs, padded to the length bucket)
|
|
13
|
+
plain-batch 16 single prompts of different requests per call (cross-request batching)
|
|
14
|
+
orders2 both orders of a question as one packed row (masked graph), one call each
|
|
15
|
+
orders2-batch 16 questions per call
|
|
16
|
+
soam every question and order of a request over one state (one packed row), one call each
|
|
17
|
+
soam-batch 8 requests per call
|
|
18
|
+
long-plain long single prompts (plain graphs up to 8192 tokens, an eager forward beyond)
|
|
19
|
+
long-tree long states, both orders (two passes over the root's KV cache)
|
|
20
|
+
|
|
21
|
+
Per path: readouts, argmax agreement with the reference, max and p99 |dp| over all option probabilities, how many of
|
|
22
|
+
the disagreements are near ties (top two within 0.02 in the reference) and, for the single questions, the agreement of
|
|
23
|
+
the decisions (both orders averaged, as served; also for the --questions items alone). Gate: agreement >= 0.999.
|
|
24
|
+
In bfloat16 any change of tensor shapes changes the rounding, so near ties can flip on any path, the plain one
|
|
25
|
+
included; fp32 shows whether a path is exact, and --reference plain compares every path with each prompt computed
|
|
26
|
+
alone in the same engine.
|
|
27
|
+
|
|
28
|
+
--questions FILE adds your own simple items (state / question / options) to the single questions; --against MODEL
|
|
29
|
+
takes the reference forwards from another model with the same tokenizer (the bf16 weights of an FP8 checkpoint), so
|
|
30
|
+
the agreement then measures the quantisation too.
|
|
31
|
+
|
|
32
|
+
The same check for every backend against the native engine, with question independence and bootstrap intervals, is
|
|
33
|
+
basal-agree (basal/agree.py), which also runs this gate: basal-agree --identity.
|
|
34
|
+
"""
|
|
35
|
+
import argparse
|
|
36
|
+
import json
|
|
37
|
+
import random
|
|
38
|
+
import statistics
|
|
39
|
+
import time
|
|
40
|
+
|
|
41
|
+
import torch
|
|
42
|
+
|
|
43
|
+
from .agree import QUESTIONS, build, compare, decisions, orders, own_questions # noqa: F401 (shared with basal-agree)
|
|
44
|
+
from .engine import ATTN, GraphBackend, resolve
|
|
45
|
+
from .jsonl import finite, write_json
|
|
46
|
+
from .server import default_orders, lean_arg, merge_arg, nvfp4_args
|
|
47
|
+
from .prompt import model_format
|
|
48
|
+
|
|
49
|
+
GATE = 0.999
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
@torch.no_grad()
|
|
53
|
+
def reference(be, toks, ids):
|
|
54
|
+
if getattr(be, "gemma", None) is not None:
|
|
55
|
+
return reference_gemma(be, toks, ids)
|
|
56
|
+
h = be.model.model(input_ids=torch.tensor([toks], device=be.dev), use_cache=False).last_hidden_state[0, -1]
|
|
57
|
+
lp = torch.log_softmax(be.model.lm_head(h).float(), -1)
|
|
58
|
+
return torch.softmax(lp[ids], -1).tolist()
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
@torch.no_grad()
|
|
62
|
+
def reference_gemma(be, toks, ids):
|
|
63
|
+
"""Gemma 4 (basal-omni): the transformers forward of the decoder on SDPA's math kernel, as --mode eager runs it, and
|
|
64
|
+
the code logits as eager reads them (fp32 from the head's input, the final logit softcap in fp32; a softmax over
|
|
65
|
+
the code rows equals the softmax over the codes of the full log-softmax)."""
|
|
66
|
+
from torch.nn.attention import SDPBackend, sdpa_kernel
|
|
67
|
+
with sdpa_kernel([SDPBackend.MATH]):
|
|
68
|
+
h = be.gemma.lm(input_ids=torch.tensor([toks], device=be.dev), use_cache=False).last_hidden_state[0, -1]
|
|
69
|
+
z = h.float() @ be.model.lm_head.weight[ids].float().T
|
|
70
|
+
if be.softcap:
|
|
71
|
+
z = torch.tanh(z / be.softcap) * be.softcap
|
|
72
|
+
return torch.softmax(z, -1).tolist()
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def run_path(be, groups, per_call):
|
|
76
|
+
out = []
|
|
77
|
+
for i in range(0, len(groups), per_call):
|
|
78
|
+
out += be.run_shared(groups[i: i + per_call])
|
|
79
|
+
torch.cuda.synchronize()
|
|
80
|
+
return [p for g in out for p in g]
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def main(argv=None):
|
|
84
|
+
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
85
|
+
ap.add_argument("--model", default="Remek/basal-1.5-4.5B")
|
|
86
|
+
ap.add_argument("--dtype", default="float32", choices=["float32", "bfloat16"])
|
|
87
|
+
ap.add_argument("--quant", default=None, choices=["fp8", "nvfp4"])
|
|
88
|
+
ap.add_argument("--nvfp4-amax", dest="nvfp4_amax", default=None,
|
|
89
|
+
help="--quant nvfp4: the calibrated input amax (as basal-serve; default: the model's NVFP4_AMAX.json)")
|
|
90
|
+
ap.add_argument("--no-compile", dest="compile", action="store_false")
|
|
91
|
+
ap.add_argument("--n-single", dest="n_single", type=int, default=200)
|
|
92
|
+
ap.add_argument("--n-multi", dest="n_multi", type=int, default=60)
|
|
93
|
+
ap.add_argument("--n-long", dest="n_long", type=int, default=30)
|
|
94
|
+
ap.add_argument("--seed", type=int, default=0)
|
|
95
|
+
ap.add_argument("--questions", default=None,
|
|
96
|
+
help="JSONL of simple items {state, question, options} added to the single questions")
|
|
97
|
+
ap.add_argument("--n-questions", dest="n_questions", type=int, default=500)
|
|
98
|
+
ap.add_argument("--reference", default="eager", choices=["eager", "plain"],
|
|
99
|
+
help="eager: every prompt in an eager forward (default); plain: every prompt alone through the "
|
|
100
|
+
"engine's plain graphs, so in bf16 the gate isolates what prefix reuse and batching change")
|
|
101
|
+
ap.add_argument("--against", default=None,
|
|
102
|
+
help="another model (e.g. the bf16 weights of an FP8 checkpoint): the reference forwards use it, "
|
|
103
|
+
"so the agreement measures the quantisation as well as the paths")
|
|
104
|
+
ap.add_argument("--attn", choices=list(ATTN), default="auto", help="attention kernel of the engine under test")
|
|
105
|
+
ap.add_argument("--reference-attn", dest="reference_attn", choices=list(ATTN), default=None,
|
|
106
|
+
help="compute the reference with this attention kernel first (e.g. fa2 against --attn fa3), in a "
|
|
107
|
+
"separate engine that is freed before the engine under test is built")
|
|
108
|
+
ap.add_argument("--merge", choices=["auto", "on", "off"], default="auto",
|
|
109
|
+
help="merged q/k/v and gate/up in the engine (auto: on for bf16 weights, off for FP8 checkpoints)")
|
|
110
|
+
ap.add_argument("--reference-merge", dest="reference_merge", choices=["on", "off"], default=None,
|
|
111
|
+
help="the reference engine with (on) or without (off) merged projections; like --reference-attn, "
|
|
112
|
+
"it is built and freed first")
|
|
113
|
+
ap.add_argument("--lean", choices=["on", "pass2", "off"], default="off",
|
|
114
|
+
help="the lean layer function in the engine (both passes, or pass 2 only)")
|
|
115
|
+
ap.add_argument("--tree", choices=["dense", "flex"], default="dense", help="pass-2 mask with --lean on")
|
|
116
|
+
ap.add_argument("--reference-lean", dest="reference_lean", choices=["on", "pass2", "off"], default=None,
|
|
117
|
+
help="the reference engine with or without the lean layer (built and freed first)")
|
|
118
|
+
ap.add_argument("--gemma-attn", dest="gemma_attn", choices=["auto", "math", "flex", "fa3", "fa3+math"],
|
|
119
|
+
default="auto",
|
|
120
|
+
help="Gemma 4 models: the attention kernel of the engine under test (basal-serve --gemma-attn)")
|
|
121
|
+
ap.add_argument("--out", default=None)
|
|
122
|
+
a = ap.parse_args(argv)
|
|
123
|
+
if (a.reference_merge or a.reference_lean) and not a.reference_attn:
|
|
124
|
+
a.reference_attn = a.attn
|
|
125
|
+
md = resolve(a.model)
|
|
126
|
+
fmt = model_format(md)
|
|
127
|
+
quant_args = nvfp4_args(a, md, a.quant) # basal-omni in NVFP4: the input amax, as basal-serve reads it
|
|
128
|
+
early = None
|
|
129
|
+
if a.reference_attn: # the reference engine first: the attention kernel is process-wide and fixed at capture
|
|
130
|
+
if a.against:
|
|
131
|
+
raise SystemExit("--reference-attn and --against do not combine")
|
|
132
|
+
t0 = time.time()
|
|
133
|
+
early = [GraphBackend(md, a.dtype, a.quant, compile=a.compile, shared=True, warm=a.reference == "plain",
|
|
134
|
+
attn=a.reference_attn, merge=merge_arg(a.reference_merge or a.merge),
|
|
135
|
+
lean=lean_arg(a.reference_lean or a.lean), **quant_args)]
|
|
136
|
+
early.append(round(time.time() - t0, 1))
|
|
137
|
+
t0 = time.time()
|
|
138
|
+
be = None if early else GraphBackend(md, a.dtype, a.quant, compile=a.compile, shared=True, attn=a.attn,
|
|
139
|
+
merge=merge_arg(a.merge), lean=lean_arg(a.lean), tree=a.tree,
|
|
140
|
+
gemma_attn=a.gemma_attn, **quant_args)
|
|
141
|
+
if be is not None:
|
|
142
|
+
print(json.dumps(dict(model=a.model, dtype=a.dtype, quant=a.quant, prompt_format=fmt, graphs=len(be.graphs),
|
|
143
|
+
attention=be.attn, fp8_checkpoint=be.fp8_checkpoint,
|
|
144
|
+
startup_s=round(time.time() - t0, 1))), flush=True)
|
|
145
|
+
ref_be = early[0] if early else be
|
|
146
|
+
if a.against: # same tokenizer required: the prompts are tokenized once
|
|
147
|
+
ref_be = GraphBackend(resolve(a.against), a.dtype, None, compile=a.compile, shared=False,
|
|
148
|
+
warm=a.reference == "plain")
|
|
149
|
+
probe = "Stan: zażalenie złożono 3 marca 2026 r. State: 12.50 EUR"
|
|
150
|
+
if ref_be.tok(probe).input_ids != be.tok(probe).input_ids or len(ref_be.tok) != len(be.tok):
|
|
151
|
+
raise SystemExit(f"--against {a.against}: a different tokenizer")
|
|
152
|
+
qs = None
|
|
153
|
+
if a.questions:
|
|
154
|
+
qs = own_questions(a.questions, fmt, a.n_questions)
|
|
155
|
+
single, multi, long = build(ref_be.tok, fmt, a.n_single, a.n_multi, a.n_long, a.seed, qs)
|
|
156
|
+
rnd = random.Random(a.seed)
|
|
157
|
+
origin = list(range(len(single))) # index >= a.n_single: an item of --questions
|
|
158
|
+
rnd.shuffle(origin)
|
|
159
|
+
single = [single[i] for i in origin]
|
|
160
|
+
real = [i >= a.n_single for i in origin]
|
|
161
|
+
one = [([t], [x]) for toks, ids in single for t, x in zip(toks, ids)]
|
|
162
|
+
one_long = [([t], [x]) for toks, ids in long for t, x in zip(toks, ids)]
|
|
163
|
+
# path: (groups, groups per call, data set); the groups of a data set flatten to the same prompts in the same order
|
|
164
|
+
paths = {"plain": (one, 1, "single"), "plain-batch": (one, 16, "single"), "orders2": (single, 1, "single"),
|
|
165
|
+
"orders2-batch": (single, 16, "single"), "soam": (multi, 1, "multi"), "soam-batch": (multi, 8, "multi"),
|
|
166
|
+
"long-plain": (one_long, 1, "long"), "long-tree": (long, 1, "long")}
|
|
167
|
+
t0 = time.time()
|
|
168
|
+
if a.reference == "plain": # each prompt alone through the plain graphs (no prefix reuse, no batching)
|
|
169
|
+
refs = {k: run_path(ref_be, [([t], [x]) for toks, ids in groups for t, x in zip(toks, ids)], 1)
|
|
170
|
+
for k, groups in (("single", single), ("multi", multi), ("long", long))}
|
|
171
|
+
else:
|
|
172
|
+
refs = {k: [reference(ref_be, t, x) for toks, ids in groups for t, x in zip(toks, ids)]
|
|
173
|
+
for k, groups in (("single", single), ("multi", multi), ("long", long))}
|
|
174
|
+
if early: # free the reference engine, then build the one under test with its attention kernel
|
|
175
|
+
print(json.dumps(dict(reference_attention=ref_be.attn, reference_startup_s=early[1])), flush=True)
|
|
176
|
+
del ref_be, early
|
|
177
|
+
import gc
|
|
178
|
+
gc.collect()
|
|
179
|
+
torch.cuda.empty_cache()
|
|
180
|
+
t0 = time.time()
|
|
181
|
+
be = GraphBackend(md, a.dtype, a.quant, compile=a.compile, shared=True, attn=a.attn, merge=merge_arg(a.merge),
|
|
182
|
+
lean=lean_arg(a.lean), tree=a.tree, gemma_attn=a.gemma_attn, **quant_args)
|
|
183
|
+
print(json.dumps(dict(model=a.model, dtype=a.dtype, quant=a.quant, prompt_format=fmt, graphs=len(be.graphs),
|
|
184
|
+
attention=be.attn, fp8_checkpoint=be.fp8_checkpoint,
|
|
185
|
+
startup_s=round(time.time() - t0, 1))), flush=True)
|
|
186
|
+
lens = [len(t) for toks, _ in single for t in toks]
|
|
187
|
+
long_lens = [len(t) for toks, _ in long for t in toks]
|
|
188
|
+
print(json.dumps(dict(reference_s=round(time.time() - t0, 1), prompt_tokens_p50=statistics.median(lens),
|
|
189
|
+
long_tokens=[min(long_lens), max(long_lens)])), flush=True)
|
|
190
|
+
rows = []
|
|
191
|
+
for name, (groups, per_call, data) in paths.items():
|
|
192
|
+
got = run_path(be, groups, per_call)
|
|
193
|
+
r = dict(path=name, per_call=per_call, **compare(refs[data], got))
|
|
194
|
+
if data == "single": # decisions in the canonical order, as the server answers by default (default_orders)
|
|
195
|
+
ref_d, got_d = decisions(refs[data], default_orders(None, fmt)), decisions(got, default_orders(None, fmt))
|
|
196
|
+
r["decision_agreement"] = compare(ref_d, got_d)["agreement"]
|
|
197
|
+
if any(real):
|
|
198
|
+
r["decision_agreement_questions"] = compare([x for x, q in zip(ref_d, real) if q],
|
|
199
|
+
[x for x, q in zip(got_d, real) if q])["agreement"]
|
|
200
|
+
r["gate"] = "pass" if r["agreement"] >= GATE else "FAIL"
|
|
201
|
+
rows.append(r)
|
|
202
|
+
print(json.dumps({k: round(v, 7) if isinstance(v, float) else v for k, v in r.items()}), flush=True)
|
|
203
|
+
print(f"\n{'path':<15}{'readouts':>9}{'agree':>9}{'max|dp|':>10}{'p99|dp|':>10}{'ties':>7}{'decisions':>10} gate "
|
|
204
|
+
f"({a.dtype}{', ' + a.quant if a.quant else ''})")
|
|
205
|
+
for r in rows:
|
|
206
|
+
d = f"{r['decision_agreement']:.4f}" if "decision_agreement" in r else "–"
|
|
207
|
+
print(f"{r['path']:<15}{r['readouts']:>9}{r['agreement']:>9.4f}{r['max_dp']:>10.2e}{r['p99_dp']:>10.2e}"
|
|
208
|
+
f"{str(r['near_ties']) + '/' + str(r['disagreements']):>7}{d:>10} {r['gate']}")
|
|
209
|
+
if a.out:
|
|
210
|
+
write_json(a.out, finite(dict(model=a.model, dtype=a.dtype, quant=a.quant, prompt_format=fmt,
|
|
211
|
+
attention=be.attn, reference_attention=a.reference_attn,
|
|
212
|
+
merged_layers=be.merged, reference_merge=a.reference_merge,
|
|
213
|
+
lean=be.lean is not None, reference_lean=a.reference_lean,
|
|
214
|
+
tree="flex" if be.flex else "dense",
|
|
215
|
+
reference=a.reference, against=a.against,
|
|
216
|
+
questions=a.questions and len(qs), rows=rows)), indent=1)
|
|
217
|
+
return rows
|
basal/int8block.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"""Block-scaled int8 linears for the CUDA graph engine (--mode int8; basal-omni, Gemma 4): the layout of
|
|
2
|
+
basal/fp8block.py with int8 values. Weights in 128 x 128 blocks and activations in 1 x 128 tiles (a token's 128
|
|
3
|
+
consecutive input features), each block with its own fp32 scale (amax / 127, values rounded to the nearest integer);
|
|
4
|
+
the GEMM multiplies int8 by int8 into int32 for every 128-deep slice of the reduction (exact), applies both scales and
|
|
5
|
+
adds the slices in fp32. For GPUs without FP8 (Ampere, sm80 / sm86): their int8 tensor cores, half the memory of bf16.
|
|
6
|
+
|
|
7
|
+
quantize(w) weight [N, K] -> (int8 [N, K], scales [N / 128, K / 128])
|
|
8
|
+
act_quant(x) activations [M, K] -> (int8 [M, K], scales [M, K / 128])
|
|
9
|
+
gemm(q, s, w, ws, dt) the Triton GEMM: [M, N] in dt (CPU: the same maths dequantised)
|
|
10
|
+
linear(x, w, ws, b) x [..., K] -> [..., N]: act_quant + gemm; the bias
|
|
11
|
+
Int8BlockLinear a linear layer holding (w, ws, bias) (lean.linear picks the GEMM by the weight's dtype)
|
|
12
|
+
|
|
13
|
+
The blocks, the Triton GEMM and the layer are basal/blockquant.py's, shared with --mode fp8 (int8: the format FORMAT,
|
|
14
|
+
values rounded to the nearest integer within +-127, each 128-deep slice's product in int32).
|
|
15
|
+
"""
|
|
16
|
+
import torch
|
|
17
|
+
|
|
18
|
+
from .blockquant import BLOCK, TILES, BlockFormat, BlockLinear, fits, grid # noqa: F401 (the shared core)
|
|
19
|
+
from .blockquant import reference as _reference # noqa: F401 (tests)
|
|
20
|
+
|
|
21
|
+
INT8_MAX = 127.0
|
|
22
|
+
CONFIG = TILES # the GEMM's tiles and launch, fixed for every shape as fp8block's; pipeline stages: _stages()
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def int8_refused():
|
|
26
|
+
"""Why --mode int8 cannot run here, None if it can: its GEMM is a Triton kernel on int8 tensor cores (compute
|
|
27
|
+
capability 8.0 or newer: Ampere, Ada, Hopper, Blackwell)."""
|
|
28
|
+
if not torch.cuda.is_available():
|
|
29
|
+
return "--mode int8 needs a CUDA GPU of compute capability 8.0 or newer (Ampere and newer)"
|
|
30
|
+
cc = torch.cuda.get_device_capability()
|
|
31
|
+
if tuple(cc) < (8, 0):
|
|
32
|
+
return (f"--mode int8 needs a GPU of compute capability 8.0 or newer (Ampere and newer); "
|
|
33
|
+
f"{torch.cuda.get_device_name()} is sm_{cc[0]}{cc[1]}. Serve with --mode fast (bf16) on this GPU")
|
|
34
|
+
return None
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _stages():
|
|
38
|
+
"""Pipeline stages from the GPU's shared memory (32 KB a stage: 4 on A100 / H100, 2 on sm86 / sm89)."""
|
|
39
|
+
smem = torch.cuda.get_device_properties(torch.cuda.current_device()).shared_memory_per_block_optin
|
|
40
|
+
return max(2, min(4, (smem - 8 * 1024) // (32 * 1024)))
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
FORMAT = BlockFormat("int8_block_gemm", torch.int8, INT8_MAX, rounded=True, stages=_stages)
|
|
44
|
+
quantize, act_quant, gemm, build, linear = FORMAT.quantize, FORMAT.act_quant, FORMAT.gemm, FORMAT.build, FORMAT.linear
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class Int8BlockLinear(BlockLinear):
|
|
48
|
+
"""A linear layer with a block-scaled int8 weight (quantize) and an optional bias (blockquant.BlockLinear)."""
|
|
49
|
+
|
|
50
|
+
FORMAT = FORMAT
|
basal/interpolate.py
ADDED
|
@@ -0,0 +1,330 @@
|
|
|
1
|
+
"""Linear weight interpolation of two checkpoints that share a base model (WiSE-FT / model soups, issue #42).
|
|
2
|
+
|
|
3
|
+
theta(alpha) = (1 - alpha) * theta_old + alpha * theta_new
|
|
4
|
+
|
|
5
|
+
alpha is the weight of the new checkpoint: 0 gives the old weights, 1 the new ones. Each tensor is mixed in fp32 and
|
|
6
|
+
stored in the dtype of the new checkpoint; tensors that are not floating point (position ids) are taken from the new
|
|
7
|
+
checkpoint. The output keeps the new checkpoint's shard layout and is streamed to disk tensor by tensor, byte for byte
|
|
8
|
+
as safetensors.torch.save_file would write it, so memory holds one tensor at a time (peak: the largest tensor in fp32,
|
|
9
|
+
three times), whatever the shard size. The result is written to a temporary folder next to --out and renamed only once
|
|
10
|
+
every shard is written, so a failed merge leaves no partial checkpoint.
|
|
11
|
+
|
|
12
|
+
The checkpoints must have the same tensor names, shapes and dtypes, unquantized weights (no quantization_config nor
|
|
13
|
+
ModelOpt's hf_quant_config.json: FP8 / NVFP4 exports store encoded weights and scales, which do not interpolate), the
|
|
14
|
+
same architecture (config.json, compared without serialization-only keys) and the same vocabulary (tokenizer.json:
|
|
15
|
+
vocab, BPE merges, added tokens).
|
|
16
|
+
The tokenizers must also have the same settings that decide how text is split (normalizer, pre-tokenizer,
|
|
17
|
+
post-processor, decoder, model options; merges compared in either serialization). A pair whose vocabulary matches but
|
|
18
|
+
whose settings differ, such as the Bielik-*-v3.0-Instruct base models (an older tokenizers layout that adds a word
|
|
19
|
+
boundary after special tokens) against basal-2.0, is refused unless --allow-tokenizer-difference is given: the merged
|
|
20
|
+
model is served with the --meta-from tokenizer only. The refusal shows a probe text the two split differently, when
|
|
21
|
+
one does.
|
|
22
|
+
|
|
23
|
+
The non-weight files (basal.json, tokenizer, chat template, config, CALIBRATION*.json) come from --meta-from (default:
|
|
24
|
+
the new checkpoint; another checkpoint must have their config.json architecture and tokenizer.json vocabulary), so the merged model is served in that checkpoint's prompt format: merging basal-1.5 and basal-2.0
|
|
25
|
+
weights with --meta-from old gives a format 1 model, otherwise format 2. The prompt format moves accuracy as much as
|
|
26
|
+
the weights do (docs/INTERPOLATION.md), so evaluate a merge together with the format it ships with. The shipped
|
|
27
|
+
calibration is only a starting point: fit one per merged model with basal-calibrate.
|
|
28
|
+
|
|
29
|
+
basal-interpolate Remek/basal-1.5-mini Remek/basal-2.0-mini --alpha 0.25 0.5 0.75 --out merged/mini --meta-from old
|
|
30
|
+
"""
|
|
31
|
+
import argparse
|
|
32
|
+
import functools
|
|
33
|
+
import json
|
|
34
|
+
import shutil
|
|
35
|
+
from pathlib import Path
|
|
36
|
+
|
|
37
|
+
from . import derive
|
|
38
|
+
|
|
39
|
+
# not copied from --meta-from: .gitattributes, and what does not hold for the merged weights (derive.stale: the model
|
|
40
|
+
# card, manifest and checksums describe the source checkpoint; its NVFP4 activation scales, evidence head, early-exit
|
|
41
|
+
# heads and thinking adapter were measured or trained on its weights). Its calibrations are copied (derive.CALIBRATIONS)
|
|
42
|
+
SKIP = {".gitattributes"}
|
|
43
|
+
# weight files of any format, and their indexes: the merged weights are the only ones in the output
|
|
44
|
+
WEIGHT_SUFFIXES = {".safetensors", ".bin", ".pt", ".pth", ".ckpt", ".gguf", ".h5", ".msgpack", ".onnx"}
|
|
45
|
+
WEIGHT_PREFIXES = ("model.safetensors.index", "pytorch_model", "tf_model", "flax_model", "model.onnx")
|
|
46
|
+
# config.json keys that do not describe the architecture (serialization, runtime defaults)
|
|
47
|
+
CONFIG_IGNORE = {"transformers_version", "torch_dtype", "dtype", "use_cache"}
|
|
48
|
+
@functools.cache
|
|
49
|
+
def torch_dtypes():
|
|
50
|
+
"""safetensors dtype name -> torch dtype (torch is imported lazily, as everywhere in this module)."""
|
|
51
|
+
import torch
|
|
52
|
+
|
|
53
|
+
names = {"F64": "float64", "F32": "float32", "F16": "float16", "BF16": "bfloat16", "I64": "int64", "I32": "int32",
|
|
54
|
+
"I16": "int16", "I8": "int8", "U8": "uint8", "U16": "uint16", "U32": "uint32", "U64": "uint64",
|
|
55
|
+
"BOOL": "bool", "F8_E4M3": "float8_e4m3fn", "F8_E5M2": "float8_e5m2"}
|
|
56
|
+
return {k: getattr(torch, v) for k, v in names.items() if hasattr(torch, v)}
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
# tokenizer.json sections that do not change the token ids of a text
|
|
60
|
+
TOKENIZER_IGNORE = {"version", "truncation", "padding"}
|
|
61
|
+
# safetensors dtypes of encoded (quantized) weights
|
|
62
|
+
QUANTIZED_DTYPES = {"F8_E4M3", "F8_E5M2", "F8_E8M0", "F4", "U8", "I8", "U4", "I4"}
|
|
63
|
+
PROBES = ["Zażółć gęślą jaźń. Ala ma kota, 123 zł!", " leading space\n\nnew lines\ttab", "x y ", "",
|
|
64
|
+
"<s>[INST] Pytanie? [/INST]", "<|im_start|>user\nHello world<|im_end|>\n<|im_start|>assistant\n",
|
|
65
|
+
"emoji 🙂 and ünïcödé", "A) tak\nB) nie\nOdpowiedź:"]
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def outside(v, flavour=Path):
|
|
69
|
+
"""A shard path of an index that leaves the model folder: absolute, with a drive, rooted or with a ".." part. On
|
|
70
|
+
Windows "/x" and "\\x" are rooted but not absolute (no drive), and model_dir / "/x" is <drive>:/x."""
|
|
71
|
+
p = flavour(v)
|
|
72
|
+
return bool(p.is_absolute() or p.drive or p.root or ".." in p.parts)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def shards(model_dir):
|
|
76
|
+
"""tensor name -> safetensors file holding it."""
|
|
77
|
+
from safetensors import safe_open
|
|
78
|
+
|
|
79
|
+
d = Path(model_dir)
|
|
80
|
+
index = d / "model.safetensors.index.json"
|
|
81
|
+
if index.exists():
|
|
82
|
+
out = {}
|
|
83
|
+
for k, v in json.loads(index.read_text(encoding="utf-8"))["weight_map"].items():
|
|
84
|
+
# the shard paths are reused under the output folder: nothing absolute, nothing that leaves the model.
|
|
85
|
+
# Checked on the path as written, not on where it resolves to: the files of a Hugging Face snapshot are
|
|
86
|
+
# symlinks into the cache's blobs/ folder, outside the snapshot, and are read like any other file
|
|
87
|
+
if outside(v):
|
|
88
|
+
raise SystemExit(f"{index}: shard path {v!r} is outside the model folder")
|
|
89
|
+
out[k] = d / v
|
|
90
|
+
return out
|
|
91
|
+
out = {}
|
|
92
|
+
for f in sorted(d.glob("*.safetensors")):
|
|
93
|
+
with safe_open(f, "pt") as s:
|
|
94
|
+
out.update(dict.fromkeys(s.keys(), f))
|
|
95
|
+
return out
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def config_key(path):
|
|
99
|
+
"""config.json as compared: rope_theta folded into rope_parameters (the transformers 5 layout), keys that do not
|
|
100
|
+
describe the architecture dropped."""
|
|
101
|
+
c = json.loads(Path(path).read_text(encoding="utf-8"))
|
|
102
|
+
if "rope_theta" in c:
|
|
103
|
+
c.setdefault("rope_parameters", {"rope_theta": c["rope_theta"], "rope_type": "default"})
|
|
104
|
+
if c.get("rope_scaling") is None:
|
|
105
|
+
c.pop("rope_scaling", None)
|
|
106
|
+
c.pop("rope_theta")
|
|
107
|
+
return {k: v for k, v in c.items() if k not in CONFIG_IGNORE}
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def tokenizer_key(path):
|
|
111
|
+
"""What fixes the meaning of a token id: vocabulary, BPE merges (string or pair form) and added tokens with their
|
|
112
|
+
flags."""
|
|
113
|
+
t = json.loads(Path(path).read_text(encoding="utf-8"))
|
|
114
|
+
m = t.get("model", {})
|
|
115
|
+
merges = [tuple(x.split(" ", 1)) if isinstance(x, str) else tuple(x) for x in m.get("merges") or []]
|
|
116
|
+
return m.get("type"), m.get("vocab"), merges, t.get("added_tokens", [])
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def tokenizer_settings(path):
|
|
120
|
+
"""tokenizer.json without the sections that do not change token ids, merges in pair form."""
|
|
121
|
+
t = json.loads(Path(path).read_text(encoding="utf-8"))
|
|
122
|
+
t = {k: v for k, v in t.items() if k not in TOKENIZER_IGNORE}
|
|
123
|
+
m = t.get("model", {})
|
|
124
|
+
if m.get("merges"):
|
|
125
|
+
t["model"] = {**m, "merges": [tuple(x.split(" ", 1)) if isinstance(x, str) else tuple(x) for x in m["merges"]]}
|
|
126
|
+
return t
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def tokenization_difference(po, pn):
|
|
130
|
+
"""The first probe text the two tokenizers split differently, as a message, or None."""
|
|
131
|
+
from tokenizers import Tokenizer
|
|
132
|
+
|
|
133
|
+
a, b = Tokenizer.from_file(str(po)), Tokenizer.from_file(str(pn))
|
|
134
|
+
for text in PROBES:
|
|
135
|
+
for special in (True, False):
|
|
136
|
+
ea, eb = a.encode(text, add_special_tokens=special), b.encode(text, add_special_tokens=special)
|
|
137
|
+
if ea.ids != eb.ids:
|
|
138
|
+
return f"{text!r}: {ea.tokens[:12]} vs {eb.tokens[:12]}"
|
|
139
|
+
return None
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def check_pair(old, new, allow_tokenizer_difference=False):
|
|
143
|
+
"""Refuses (SystemExit) a pair that cannot be interpolated; returns the tensor -> shard maps of both and
|
|
144
|
+
tensor -> (safetensors dtype, shape) of the new checkpoint, read from the headers."""
|
|
145
|
+
from safetensors import safe_open
|
|
146
|
+
|
|
147
|
+
for name in ("config.json", "tokenizer.json"):
|
|
148
|
+
missing = [d for d in (old, new) if not (Path(d) / name).is_file()]
|
|
149
|
+
if missing:
|
|
150
|
+
raise SystemExit(f"{name} missing in {missing[0]}: cannot check that the checkpoints share an "
|
|
151
|
+
"architecture / tokenizer")
|
|
152
|
+
for d in (old, new):
|
|
153
|
+
quantised = ("quantization_config" if "quantization_config" in json.loads(
|
|
154
|
+
(Path(d) / "config.json").read_text(encoding="utf-8")) else
|
|
155
|
+
"hf_quant_config.json" if (Path(d) / "hf_quant_config.json").exists() else None) # (ModelOpt's own file)
|
|
156
|
+
if quantised:
|
|
157
|
+
raise SystemExit(f"{d} is quantized ({quantised}): interpolate the unquantized checkpoints and "
|
|
158
|
+
"quantize the result")
|
|
159
|
+
po, pn = Path(old) / "config.json", Path(new) / "config.json"
|
|
160
|
+
if po.read_bytes() != pn.read_bytes() and config_key(po) != config_key(pn):
|
|
161
|
+
raise SystemExit("config.json differs: the checkpoints do not share an architecture")
|
|
162
|
+
po, pn = Path(old) / "tokenizer.json", Path(new) / "tokenizer.json"
|
|
163
|
+
if po.read_bytes() != pn.read_bytes():
|
|
164
|
+
if tokenizer_key(po) != tokenizer_key(pn):
|
|
165
|
+
raise SystemExit("tokenizer.json differs: the checkpoints do not share a vocabulary")
|
|
166
|
+
so, sn = tokenizer_settings(po), tokenizer_settings(pn)
|
|
167
|
+
if so != sn and not allow_tokenizer_difference:
|
|
168
|
+
keys = sorted(k for k in so.keys() | sn.keys() if so.get(k) != sn.get(k))
|
|
169
|
+
example = tokenization_difference(po, pn)
|
|
170
|
+
raise SystemExit(f"the tokenizers share the vocabulary but their settings differ ({', '.join(keys)}"
|
|
171
|
+
+ (f"; for example {example}" if example else "") + "); the merged model is served with "
|
|
172
|
+
"the --meta-from tokenizer only. Pass --allow-tokenizer-difference if that is intended "
|
|
173
|
+
"(a base model written by an older tokenizers release)")
|
|
174
|
+
|
|
175
|
+
a, b = shards(old), shards(new)
|
|
176
|
+
if not b:
|
|
177
|
+
raise SystemExit(f"{new}: no safetensors weights")
|
|
178
|
+
if a.keys() != b.keys():
|
|
179
|
+
raise SystemExit(f"different tensors: only old {sorted(a.keys() - b.keys())[:5]}, "
|
|
180
|
+
f"only new {sorted(b.keys() - a.keys())[:5]}")
|
|
181
|
+
specs = {}
|
|
182
|
+
for k in b: # shapes and dtypes from the headers, before anything is written
|
|
183
|
+
with safe_open(a[k], "pt") as fo, safe_open(b[k], "pt") as fn:
|
|
184
|
+
so, sn = fo.get_slice(k), fn.get_slice(k)
|
|
185
|
+
if so.get_shape() != sn.get_shape():
|
|
186
|
+
raise SystemExit(f"{k}: shape {tuple(so.get_shape())} vs {tuple(sn.get_shape())}")
|
|
187
|
+
dt = {so.get_dtype(), sn.get_dtype()}
|
|
188
|
+
if dt & QUANTIZED_DTYPES and k.endswith("weight"):
|
|
189
|
+
raise SystemExit(f"{k}: quantized weights ({'/'.join(sorted(dt))}) do not interpolate")
|
|
190
|
+
if sn.get_dtype() not in torch_dtypes():
|
|
191
|
+
raise SystemExit(f"{k}: unsupported dtype {sn.get_dtype()}")
|
|
192
|
+
specs[k] = (sn.get_dtype(), tuple(sn.get_shape()))
|
|
193
|
+
return a, b, specs
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def check_meta(new, meta):
|
|
197
|
+
"""--meta-from a checkpoint other than the two: its config.json and tokenizer.json become the merged model's, so
|
|
198
|
+
they must describe the checkpoints' architecture and vocabulary (SystemExit otherwise, before anything is
|
|
199
|
+
written)."""
|
|
200
|
+
for name, key, what in (("config.json", config_key, "architecture"), ("tokenizer.json", tokenizer_key, "vocabulary")):
|
|
201
|
+
p, q = Path(meta) / name, Path(new) / name
|
|
202
|
+
if not p.is_file():
|
|
203
|
+
raise SystemExit(f"--meta-from {meta}: no {name}; the merged model takes its {name} from there")
|
|
204
|
+
if p.read_bytes() != q.read_bytes() and key(p) != key(q):
|
|
205
|
+
raise SystemExit(f"--meta-from {meta}: its {name} differs from the checkpoints' (another {what}); the "
|
|
206
|
+
f"merged model would be served with it")
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def save_streamed(path, specs, produce, metadata):
|
|
210
|
+
"""Writes a safetensors file tensor by tensor: specs is name -> (safetensors dtype, shape), produce(name) returns
|
|
211
|
+
the tensor. The layout is that of safetensors.torch.save_file (tensors ordered by dtype, then name; header padded to
|
|
212
|
+
8 bytes): the order is read from a file of 1-element tensors, so only one tensor is in memory at a time."""
|
|
213
|
+
import struct
|
|
214
|
+
|
|
215
|
+
import torch
|
|
216
|
+
from safetensors.torch import save
|
|
217
|
+
|
|
218
|
+
DTYPES = torch_dtypes()
|
|
219
|
+
proxy = save({k: torch.zeros(1, dtype=DTYPES[d]) for k, (d, _) in specs.items()})
|
|
220
|
+
order = [k for k in json.loads(proxy[8:8 + struct.unpack("<Q", proxy[:8])[0]]) if k != "__metadata__"]
|
|
221
|
+
header, offset = {"__metadata__": metadata}, 0
|
|
222
|
+
for k in order:
|
|
223
|
+
d, shape = specs[k]
|
|
224
|
+
size = torch.Size(shape).numel() * torch.empty(0, dtype=DTYPES[d]).element_size()
|
|
225
|
+
header[k] = {"dtype": d, "shape": list(shape), "data_offsets": [offset, offset + size]}
|
|
226
|
+
offset += size
|
|
227
|
+
h = json.dumps(header, separators=(",", ":"), ensure_ascii=False).encode()
|
|
228
|
+
h += b" " * (-len(h) % 8)
|
|
229
|
+
with open(path, "wb") as f:
|
|
230
|
+
f.write(struct.pack("<Q", len(h)) + h)
|
|
231
|
+
for k in order:
|
|
232
|
+
t = produce(k)
|
|
233
|
+
if t.dtype != DTYPES[specs[k][0]] or tuple(t.shape) != specs[k][1]:
|
|
234
|
+
raise SystemExit(f"{k}: produced {t.dtype} {tuple(t.shape)}, header says {specs[k]}")
|
|
235
|
+
f.write(t.contiguous().reshape(-1).view(torch.uint8).numpy().tobytes())
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def interpolate(old, new, alpha, out, meta_from=None, allow_tokenizer_difference=False):
|
|
239
|
+
"""Writes the merged checkpoint to out (a new or empty directory) and returns its path."""
|
|
240
|
+
import torch
|
|
241
|
+
from safetensors import safe_open
|
|
242
|
+
|
|
243
|
+
if not 0.0 <= alpha <= 1.0:
|
|
244
|
+
raise SystemExit(f"alpha {alpha} outside [0, 1]")
|
|
245
|
+
old, new, out = Path(old), Path(new), Path(out)
|
|
246
|
+
meta_from = Path(meta_from or new)
|
|
247
|
+
if out.exists() and (not out.is_dir() or any(out.iterdir())):
|
|
248
|
+
raise SystemExit(f"{out} exists and is not empty; remove it or choose another --out")
|
|
249
|
+
a, b, specs = check_pair(old, new, allow_tokenizer_difference)
|
|
250
|
+
if meta_from.resolve() not in (old.resolve(), new.resolve()):
|
|
251
|
+
check_meta(new, meta_from)
|
|
252
|
+
tmp = out.parent / f".{out.name}.partial"
|
|
253
|
+
shutil.rmtree(tmp, ignore_errors=True)
|
|
254
|
+
tmp.mkdir(parents=True)
|
|
255
|
+
try:
|
|
256
|
+
by_file = {} # tensors grouped by the new checkpoint's shard (path relative to the model, as in the index)
|
|
257
|
+
for k, f in b.items():
|
|
258
|
+
by_file.setdefault(f.relative_to(new), []).append(k)
|
|
259
|
+
|
|
260
|
+
def mixed(k):
|
|
261
|
+
with safe_open(a[k], "pt") as fo, safe_open(b[k], "pt") as fn: # no handle outlives its tensor
|
|
262
|
+
t_old, t_new = fo.get_tensor(k), fn.get_tensor(k)
|
|
263
|
+
if not t_new.is_floating_point():
|
|
264
|
+
return t_new
|
|
265
|
+
return torch.lerp(t_old.float(), t_new.float(), alpha).to(t_new.dtype)
|
|
266
|
+
|
|
267
|
+
for rel, keys in by_file.items():
|
|
268
|
+
(tmp / rel).parent.mkdir(parents=True, exist_ok=True)
|
|
269
|
+
save_streamed(tmp / rel, {k: specs[k] for k in keys}, mixed, {"format": "pt"})
|
|
270
|
+
if (new / "model.safetensors.index.json").exists():
|
|
271
|
+
shutil.copy(new / "model.safetensors.index.json", tmp)
|
|
272
|
+
|
|
273
|
+
for f in meta_from.rglob("*"):
|
|
274
|
+
rel = f.relative_to(meta_from)
|
|
275
|
+
if not f.is_file() or rel.name in SKIP or derive.stale(rel, calibrations=False) \
|
|
276
|
+
or rel.parts[0].startswith("."):
|
|
277
|
+
continue
|
|
278
|
+
if f.suffix in WEIGHT_SUFFIXES or rel.name.startswith(WEIGHT_PREFIXES):
|
|
279
|
+
continue
|
|
280
|
+
(tmp / rel).parent.mkdir(parents=True, exist_ok=True)
|
|
281
|
+
shutil.copy(f, tmp / rel)
|
|
282
|
+
info = json.loads((tmp / "basal.json").read_text(encoding="utf-8")) if (tmp / "basal.json").exists() else {}
|
|
283
|
+
info.update({"name": f"{info.get('name', new.name)}-interp-a{alpha:g}",
|
|
284
|
+
"interpolation": {"old": str(old), "new": str(new), "alpha": alpha,
|
|
285
|
+
"rule": "(1 - alpha) * old + alpha * new, fp32 accumulate"}})
|
|
286
|
+
(tmp / "basal.json").write_text(json.dumps(info, indent=1) + "\n", encoding="utf-8")
|
|
287
|
+
if out.exists():
|
|
288
|
+
out.rmdir() # empty, checked above
|
|
289
|
+
tmp.rename(out)
|
|
290
|
+
except BaseException:
|
|
291
|
+
shutil.rmtree(tmp, ignore_errors=True)
|
|
292
|
+
raise
|
|
293
|
+
return out
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
def main(argv=None):
|
|
297
|
+
ap = argparse.ArgumentParser(description=(__doc__ or "").split("\n\n")[0]) # no docstring under python -OO
|
|
298
|
+
ap.add_argument("old", help="local directory or Hugging Face repo id")
|
|
299
|
+
ap.add_argument("new", help="local directory or Hugging Face repo id")
|
|
300
|
+
ap.add_argument("--alpha", type=float, nargs="+", required=True, help="weight of the new checkpoint, in [0, 1]")
|
|
301
|
+
ap.add_argument("--out", required=True, help="output prefix: one new directory <out>-a<alpha> per alpha")
|
|
302
|
+
ap.add_argument("--meta-from", default=None, help="checkpoint whose non-weight files (prompt format, tokenizer, "
|
|
303
|
+
"calibration) are copied: old, new (default) or a path / repo id")
|
|
304
|
+
ap.add_argument("--allow-tokenizer-difference", action="store_true",
|
|
305
|
+
help="accept tokenizers with the same vocabulary that split text differently (see above)")
|
|
306
|
+
a = ap.parse_args(argv)
|
|
307
|
+
if any(not 0.0 <= x <= 1.0 for x in a.alpha):
|
|
308
|
+
ap.error("--alpha values must be in [0, 1]")
|
|
309
|
+
names = [f"{a.out}-a{x:g}" for x in a.alpha]
|
|
310
|
+
if len(set(names)) != len(names):
|
|
311
|
+
ap.error(f"--alpha values give the same output directory: {sorted({n for n in names if names.count(n) > 1})}")
|
|
312
|
+
from huggingface_hub import snapshot_download
|
|
313
|
+
|
|
314
|
+
from .engine import resolve
|
|
315
|
+
|
|
316
|
+
def local(m):
|
|
317
|
+
return Path(m) if Path(m).exists() else Path(snapshot_download(m))
|
|
318
|
+
|
|
319
|
+
for m in (a.old, a.new): # (from their metadata, before any weights download)
|
|
320
|
+
why = derive.modelopt_refused(resolve(m, metadata_only=True), m, "basal-interpolate", "interpolate")
|
|
321
|
+
if why:
|
|
322
|
+
raise SystemExit(why)
|
|
323
|
+
old, new = local(a.old), local(a.new)
|
|
324
|
+
meta = {"old": old, "new": new, None: new}.get(a.meta_from) or local(a.meta_from)
|
|
325
|
+
for alpha, out in zip(a.alpha, names):
|
|
326
|
+
print(interpolate(old, new, alpha, out, meta, a.allow_tokenizer_difference))
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
if __name__ == "__main__":
|
|
330
|
+
main()
|