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/gguf_export.py
ADDED
|
@@ -0,0 +1,497 @@
|
|
|
1
|
+
"""Export a basal checkpoint to GGUF whose tokenizer matches the Hugging Face one.
|
|
2
|
+
|
|
3
|
+
llama.cpp's converter writes basal's BPE vocabulary as a SentencePiece-style vocabulary with one constant score for
|
|
4
|
+
every token and with a word-boundary prefix, so llama.cpp (and Ollama, LM Studio, llama-server with text prompts)
|
|
5
|
+
splits text differently from the tokenizer the models were trained with. This tool runs the converter and then fixes
|
|
6
|
+
the file as the -GGUF repositories are fixed (docs/PORTS.md, "Tokenizer fix"). With --gguf it fixes an existing GGUF
|
|
7
|
+
instead (a stock conversion, a llama-quantize output, an older basal GGUF); the model then only supplies
|
|
8
|
+
tokenizer.json, downloaded without the weights:
|
|
9
|
+
|
|
10
|
+
- tokenizer.ggml.scores: minus the rank of the first BPE merge that creates each token (the first merge scores 0), so
|
|
11
|
+
llama.cpp's greedy highest-score-first merging follows the BPE merge order; the added tokens of tokenizer.json score
|
|
12
|
+
-1000 (the converter's value), every other token (single characters, byte tokens) scores 0;
|
|
13
|
+
- tokenizer.ggml.add_space_prefix = false: the Hugging Face tokenizer adds no word-boundary marker after special
|
|
14
|
+
tokens such as <|im_start|>;
|
|
15
|
+
- tokenizer.ggml.token_type: every added token of tokenizer.json is CONTROL (special) or USER_DEFINED, as the Hugging
|
|
16
|
+
Face tokenizer matches them whole; the converter reads special tokens from tokenizer_config.json only, and
|
|
17
|
+
basal-1.0-4.5B's and the max models' do not list <|im_start|>, so llama.cpp split it into characters.
|
|
18
|
+
|
|
19
|
+
Fixing a fixed file changes nothing (the -GGUF files of basal-1.5 and basal-2.0 come out byte-identical). The tokenizer
|
|
20
|
+
matches the Hugging Face one for text that starts with a special token (every basal prompt starts with <s>); for text
|
|
21
|
+
without one, Hugging Face adds a word-boundary marker at the very start and llama.cpp does not.
|
|
22
|
+
|
|
23
|
+
With --systemone the file also becomes a decision model for llama.cpp's /v1/systemone (llama-server b11908 or newer,
|
|
24
|
+
LM Studio 0.4.26 or newer, whose /v1/decisions reads it too); the tensors are not touched. llama.cpp knows a fixed list
|
|
25
|
+
of decision encodings; basal prompt format 2 is the "openjev" one up to 26 options: one prompt per question, the
|
|
26
|
+
logits of the option codes A-Z at the last prompt token, a softmax divided by a temperature. The file gets
|
|
27
|
+
<arch>.decision.type = "openjev", tokenizer.chat_template.systemone (basal's prompt as a template: the system prompt,
|
|
28
|
+
state, question and coded options in the model's chat template, plus the answer prefill; Polish or English as
|
|
29
|
+
basal-serve picks) and <arch>.decision.temperature.<type>.<bucket> from the model's calibration
|
|
30
|
+
(CALIBRATION.llamacpp.json, else CALIBRATION.gguf.json, else CALIBRATION.json; or --calibration). The template is
|
|
31
|
+
checked against basal-serve's own prompts on a fixed set of requests before anything is written. llama.cpp applies
|
|
32
|
+
only these temperatures: thresholds, coverage and the engine-level types (act, multi, tool) stay with basal-serve.
|
|
33
|
+
|
|
34
|
+
basal-export-gguf Remek/basal-2.0-4.5B basal-2.0-4.5B-F16.gguf --outtype f16 --llama-cpp ~/llama.cpp
|
|
35
|
+
basal-export-gguf Remek/basal-1.0-1.5B fixed/basal-1.0-1.5B-Q8_0.gguf --gguf basal-1.0-1.5B-Q8_0.gguf
|
|
36
|
+
basal-export-gguf Remek/basal-2.0-4.5B-GGUF lmstudio/basal-2.0-4.5B-Q8_0.gguf --gguf basal-2.0-4.5B-Q8_0.gguf \\
|
|
37
|
+
--systemone
|
|
38
|
+
"""
|
|
39
|
+
import argparse
|
|
40
|
+
import json
|
|
41
|
+
import os
|
|
42
|
+
import re
|
|
43
|
+
import subprocess
|
|
44
|
+
import sys
|
|
45
|
+
import tempfile
|
|
46
|
+
import unicodedata
|
|
47
|
+
from pathlib import Path
|
|
48
|
+
|
|
49
|
+
from .textio import read_text
|
|
50
|
+
|
|
51
|
+
ADDED_TOKEN_SCORE = -1000.0 # llama.cpp's converter scores the added tokens so; the -GGUF files keep it
|
|
52
|
+
|
|
53
|
+
SYSTEMONE_TYPE = "openjev" # llama.cpp's decision encoding that reads basal's prompt format 2 (codes A-Z)
|
|
54
|
+
SYSTEMONE_TEMPLATE = "tokenizer.chat_template.systemone"
|
|
55
|
+
SYSTEMONE_MAX_OPTIONS = 26 # openjev's labels after Z are a-z, basal's codes are AA, AB, ...: the template refuses more
|
|
56
|
+
# llama.cpp's temperature buckets by option count (server-decision.cpp) and the counts of each question type
|
|
57
|
+
LLAMA_BUCKETS = (("2", 2, 2), ("3_5", 3, 5), ("6_10", 6, 10), ("11", 11, SYSTEMONE_MAX_OPTIONS))
|
|
58
|
+
SYSTEMONE_COUNTS = {"choice": (2, SYSTEMONE_MAX_OPTIONS), "noul": (2, 2), "score": (2, 10)}
|
|
59
|
+
SYSTEMONE_CALIBRATIONS = ("CALIBRATION.llamacpp.json", "CALIBRATION.gguf.json", "CALIBRATION.json")
|
|
60
|
+
MODEL_FILES = ["tokenizer.json", "tokenizer_config.json", "special_tokens_map.json", "chat_template.jinja",
|
|
61
|
+
"basal.json", "CALIBRATION*.json"] # --gguf --systemone: what the model folder supplies
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def merge_rank_scores(tokenizer_json, tokens):
|
|
65
|
+
"""Token scores as in the -GGUF files: -(rank of the first BPE merge producing the token); -1000 for the added
|
|
66
|
+
tokens of tokenizer.json, whatever the input file had; 0 for the rest (single characters, byte tokens: llama.cpp
|
|
67
|
+
only compares the scores of merge results, and basal's vocabulary has no other multi-character token). Returns
|
|
68
|
+
(scores, tokens ranked)."""
|
|
69
|
+
rank = {}
|
|
70
|
+
for i, m in enumerate(tokenizer_json["model"]["merges"]):
|
|
71
|
+
a, b = m if isinstance(m, list) else m.split(" ", 1)
|
|
72
|
+
rank.setdefault(a + b, i)
|
|
73
|
+
added = {t["id"] for t in tokenizer_json.get("added_tokens", [])}
|
|
74
|
+
return ([ADDED_TOKEN_SCORE if i in added else -float(rank[t]) if t in rank else 0.0 for i, t in enumerate(tokens)],
|
|
75
|
+
sum(t in rank for t in tokens))
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def added_token_types(tokenizer_json, token_types):
|
|
79
|
+
"""GGUF token types with the added tokens of tokenizer.json marked CONTROL (special) or USER_DEFINED."""
|
|
80
|
+
import gguf
|
|
81
|
+
|
|
82
|
+
types = list(token_types)
|
|
83
|
+
for t in tokenizer_json.get("added_tokens", []):
|
|
84
|
+
if 0 <= t["id"] < len(types):
|
|
85
|
+
types[t["id"]] = int(gguf.TokenType.CONTROL if t.get("special") else gguf.TokenType.USER_DEFINED)
|
|
86
|
+
return types
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _lit(text):
|
|
90
|
+
"""`text` as a Jinja string literal (llama.cpp's template lexer reads the escapes used here)."""
|
|
91
|
+
if any(ord(c) < 32 and c not in "\n\t" for c in text):
|
|
92
|
+
raise ValueError(f"a control character in the chat template's text: {text!r}")
|
|
93
|
+
return '"' + text.replace("\\", "\\\\").replace('"', '\\"').replace("\n", "\\n").replace("\t", "\\t") + '"'
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
STRING_T = '(t ~ "")' # the option as a string, whatever the label or description was
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _fang(var, specials):
|
|
100
|
+
"""Jinja expression for `var` as basal-serve shows it after prompt.defang (each special token broken by a
|
|
101
|
+
zero-width space after its first character)."""
|
|
102
|
+
from .prompt import _ZWSP
|
|
103
|
+
|
|
104
|
+
for n in specials:
|
|
105
|
+
var = f"{var}.replace({_lit(n)}, {_lit(n[0] + _ZWSP + n[1:])})"
|
|
106
|
+
return var
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def chat_frame(tok):
|
|
110
|
+
"""The model's chat template around one system and one user message, with the generation prompt as basal renders
|
|
111
|
+
it (no thinking): (before the system text, between the two, after the user text, whether the template trims the
|
|
112
|
+
user text)."""
|
|
113
|
+
sys_mark, user_mark = "\ue000basal-system\ue000", "\ue000basal-user\ue000"
|
|
114
|
+
padded = f"\t{user_mark} \n"
|
|
115
|
+
text = tok.apply_chat_template([{"role": "system", "content": sys_mark}, {"role": "user", "content": padded}],
|
|
116
|
+
tokenize=False, add_generation_prompt=True, enable_thinking=False)
|
|
117
|
+
if text.count(sys_mark) != 1 or text.count(user_mark) != 1 or text.index(sys_mark) > text.index(user_mark):
|
|
118
|
+
raise ValueError("the chat template does not place a system and a user message once each")
|
|
119
|
+
trims = padded not in text
|
|
120
|
+
head, rest = text.split(sys_mark)
|
|
121
|
+
mid, tail = rest.split(user_mark if trims else padded)
|
|
122
|
+
if trims and (mid.endswith(padded[0]) or tail.startswith(padded[-2:])):
|
|
123
|
+
raise ValueError("the chat template changes the whitespace around a message in a way basal cannot follow")
|
|
124
|
+
return head, mid, tail, trims
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def systemone_template(head, mid, tail, trims=False, specials=()):
|
|
128
|
+
"""basal prompt format 2 (canonical layout, one option order) as a template for llama.cpp's /v1/systemone. Its
|
|
129
|
+
variables: state, instructions (text or JSON), type, options [{key, description}] in the order llama.cpp reads the
|
|
130
|
+
labels A, B, ... (a choice in request order, noul true then false, score levels low to high). `trims`: the chat
|
|
131
|
+
template strips the user text (llama.cpp's trim strips ASCII whitespace only, Python's strip all of it).
|
|
132
|
+
`specials`: the special tokens of the tokenizer (prompt.special_names), broken in the state, the question and the
|
|
133
|
+
options as prompt.defang does."""
|
|
134
|
+
from .prompt import CODES, PL_CHARS, PREFILL, TEMPLATES_2
|
|
135
|
+
|
|
136
|
+
def turn(lang):
|
|
137
|
+
parts = re.split(r"\{(state|q|opts)\}", TEMPLATES_2[lang]["user"])
|
|
138
|
+
names = {"state": "s", "q": "q", "opts": "ns.opts"}
|
|
139
|
+
user = " ~ ".join(names[p] if i % 2 else _lit(p) for i, p in enumerate(parts))
|
|
140
|
+
return " ~ ".join([_lit(head + TEMPLATES_2[lang]["system"] + mid), f"({user}) | trim" if trims else user,
|
|
141
|
+
_lit(tail + PREFILL)])
|
|
142
|
+
|
|
143
|
+
def text(v):
|
|
144
|
+
return f"({v} if {v} is string else {v} | tojson)"
|
|
145
|
+
|
|
146
|
+
# the Polish letters, and their NFD spellings (a + U+0328 for "ą"; "ł" has none), which basal-serve normalises
|
|
147
|
+
# (prompt.lang_of) and a template cannot
|
|
148
|
+
nfd = sorted({unicodedata.normalize("NFD", c) for c in PL_CHARS} - PL_CHARS)
|
|
149
|
+
pl, codes = ", ".join(map(_lit, sorted(PL_CHARS) + nfd)), ", ".join(map(_lit, CODES[:SYSTEMONE_MAX_OPTIONS]))
|
|
150
|
+
return "\n".join([
|
|
151
|
+
"{#- basal prompt format 2 for llama.cpp's /v1/systemone, written by basal-export-gguf -#}",
|
|
152
|
+
"{%- if options | length < 2 or options | length > " + str(SYSTEMONE_MAX_OPTIONS) + " -%}",
|
|
153
|
+
"{{- raise_exception(" + _lit(f"basal: a question has 2 to {SYSTEMONE_MAX_OPTIONS} options here") + ") -}}",
|
|
154
|
+
"{%- endif -%}",
|
|
155
|
+
"{%- set ns = namespace(pl=false, opts=\"\") -%}",
|
|
156
|
+
f"{{%- set s = {text('state')} -%}}",
|
|
157
|
+
f"{{%- set q = {text('instructions')} -%}}",
|
|
158
|
+
# a request text cannot write a special token of the tokenizer (prompt.defang); Polish letters are not changed
|
|
159
|
+
f"{{%- set s = {_fang('s', specials)} -%}}",
|
|
160
|
+
f"{{%- set q = {_fang('q', specials)} -%}}",
|
|
161
|
+
# Polish when the state has a Polish letter (also in NFD), else when the question has one (basal-serve's rule)
|
|
162
|
+
f"{{%- for c in [{pl}] -%}}{{%- if c in s -%}}{{%- set ns.pl = true -%}}{{%- endif -%}}{{%- endfor -%}}",
|
|
163
|
+
"{%- if not ns.pl -%}",
|
|
164
|
+
f"{{%- for c in [{pl}] -%}}{{%- if c in q -%}}{{%- set ns.pl = true -%}}{{%- endif -%}}{{%- endfor -%}}",
|
|
165
|
+
"{%- endif -%}",
|
|
166
|
+
f"{{%- set codes = [{codes}] -%}}",
|
|
167
|
+
"{%- for o in options -%}",
|
|
168
|
+
"{%- set d = o.description -%}{%- set k = o.key -%}{%- set keyed = type == \"choice\" -%}",
|
|
169
|
+
# LM Studio's /v1/decisions passes OpenAI choices as {"value", "description"} and levels as {"label",
|
|
170
|
+
# "description"}: shown as the System One request {value: description} / {label: description} would be
|
|
171
|
+
"{%- if d is mapping and d | length == 2 and \"description\" in d and ((type == \"choice\" and \"value\" in d)"
|
|
172
|
+
" or (type == \"score\" and \"label\" in d)) -%}",
|
|
173
|
+
"{%- set k = (d.value if d.value is string else d.value | tojson) if type == \"choice\" else d.label -%}",
|
|
174
|
+
"{%- set d = d.description -%}{%- set keyed = true -%}",
|
|
175
|
+
"{%- endif -%}",
|
|
176
|
+
"{%- if type == \"noul\" -%}",
|
|
177
|
+
"{%- if d -%}" f"{{%- set t = {text('d')} -%}}",
|
|
178
|
+
"{%- elif k == \"true\" -%}{%- set t = \"Tak\" if ns.pl else \"Yes\" -%}",
|
|
179
|
+
"{%- else -%}{%- set t = \"Nie\" if ns.pl else \"No\" -%}{%- endif -%}",
|
|
180
|
+
f"{{%- elif not keyed -%}}{{%- set t = {text('d')} -%}}",
|
|
181
|
+
"{%- elif d is none -%}{%- set t = k -%}",
|
|
182
|
+
f"{{%- else -%}}{{%- set t = k ~ \": \" ~ {text('d')} -%}}",
|
|
183
|
+
"{%- endif -%}",
|
|
184
|
+
f"{{%- set t = {_fang(STRING_T, specials)} -%}}",
|
|
185
|
+
"{%- set ns.opts = ns.opts ~ (\"\" if loop.first else \"\\n\") ~ codes[loop.index0] ~ \". \" ~ t -%}",
|
|
186
|
+
"{%- endfor -%}",
|
|
187
|
+
"{%- if ns.pl -%}{{- " + turn("pl") + " -}}{%- else -%}{{- " + turn("en") + " -}}{%- endif -%}"])
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
# requests the template is checked on before it is written: Polish from the state or from the question, descriptions
|
|
191
|
+
# or none, JSON states and descriptions, quotes and backslashes, whitespace at the ends, 26 options
|
|
192
|
+
SYSTEMONE_PROBES = (
|
|
193
|
+
("Customer: I was charged twice for order 1182 and nobody answered my emails.",
|
|
194
|
+
{"type": "choice", "instructions": "Which team should handle this?",
|
|
195
|
+
"criteria": {"billing": "payments, refunds, invoices", "shipping": None, "technical": "the app or the website"}}),
|
|
196
|
+
("Klient: zamówienie nie dotarło, proszę o zwrot pieniędzy.",
|
|
197
|
+
{"type": "noul", "instructions": "Is the customer asking for a refund?"}),
|
|
198
|
+
("Order 1182: delivered on 3 May.",
|
|
199
|
+
{"type": "noul", "instructions": "Czy zamówienie dotarło?", "criteria": {"true": "tak, dotarło", "false": ""}}),
|
|
200
|
+
(" The patient reports mild pain since Monday.\n",
|
|
201
|
+
{"type": "score", "instructions": "How urgent is this?", "criteria": ["can wait", "this week", "today", " now "]}),
|
|
202
|
+
({"ticket": 1182, "text": "Zażółć gęślą jaźń", "tags": ["a", "b"], "paid": True},
|
|
203
|
+
{"type": "choice", "instructions": {"ask": "category"}, "criteria": {f"k{i}": None for i in range(26)}}),
|
|
204
|
+
('He said "stop" \\ and left.\n\nThen {{ nothing }} happened.',
|
|
205
|
+
{"type": "choice", "instructions": "Who left?", "criteria": {"x": {"name": "X", "id": 7}, "y": "Y "}}),
|
|
206
|
+
# Polish in NFD, as macOS writes it ("o" + U+0301): in the state, then in the question only
|
|
207
|
+
(unicodedata.normalize("NFD", "Proszę o zwrot pieniędzy za zamówienie 1182."),
|
|
208
|
+
{"type": "noul", "instructions": "Is the customer asking for a refund?"}),
|
|
209
|
+
("Order 1182: delivered on 3 May.",
|
|
210
|
+
{"type": "noul", "instructions": unicodedata.normalize("NFD", "Czy zamówienie jest już opóźnione?")}),
|
|
211
|
+
)
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def systemone_options(q):
|
|
215
|
+
"""The options llama.cpp gives the template, in its label order (openjev: noul true first)."""
|
|
216
|
+
crit = q.get("criteria")
|
|
217
|
+
if q["type"] == "choice":
|
|
218
|
+
return [{"key": k, "description": v} for k, v in crit.items()]
|
|
219
|
+
if q["type"] == "score":
|
|
220
|
+
return [{"key": str(i), "description": v} for i, v in enumerate(crit)]
|
|
221
|
+
return [{"key": k, "description": (crit or {}).get(k)} for k in ("true", "false")]
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def render_systemone(template, state, q):
|
|
225
|
+
"""The template's prompt for one question, rendered as llama.cpp does (trim_blocks, lstrip_blocks; tojson as
|
|
226
|
+
compact JSON with ", " and ": " and no ASCII escaping)."""
|
|
227
|
+
import jinja2
|
|
228
|
+
|
|
229
|
+
def raise_exception(msg):
|
|
230
|
+
raise ValueError(msg)
|
|
231
|
+
|
|
232
|
+
env = jinja2.Environment(trim_blocks=True, lstrip_blocks=True, undefined=jinja2.StrictUndefined)
|
|
233
|
+
env.filters["tojson"] = lambda x: json.dumps(x, ensure_ascii=False)
|
|
234
|
+
env.globals["raise_exception"] = raise_exception
|
|
235
|
+
return env.from_string(template).render(id="q", type=q["type"], instructions=q["instructions"], state=state,
|
|
236
|
+
options=systemone_options(q), images=[])
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def check_systemone(tok, template):
|
|
240
|
+
"""The template renders basal-serve's prompt on every probe, and the option codes A-Z are the single tokens
|
|
241
|
+
llama.cpp reads (each code's own token); raises ValueError otherwise."""
|
|
242
|
+
from .prompt import CODES, letter_ids, render
|
|
243
|
+
from .server import to_items
|
|
244
|
+
|
|
245
|
+
for i, (state, q) in enumerate(SYSTEMONE_PROBES):
|
|
246
|
+
item = to_items(state, {"q": q}, max_opts=SYSTEMONE_MAX_OPTIONS)[0]
|
|
247
|
+
want = render(tok, item["state"], item["question"], item["options"], item["lang"], fmt=2)
|
|
248
|
+
if render_systemone(template, state, q) != want:
|
|
249
|
+
raise ValueError(f"the systemone template differs from basal's prompt on probe {i}: the model's chat "
|
|
250
|
+
"template changes the messages (e.g. trims them)")
|
|
251
|
+
codes = CODES[:SYSTEMONE_MAX_OPTIONS]
|
|
252
|
+
own = tok.convert_tokens_to_ids(list(codes))
|
|
253
|
+
at_answer = letter_ids(tok, render_systemone(template, *SYSTEMONE_PROBES[0]), len(codes), fmt=2)
|
|
254
|
+
if at_answer != own or tok.unk_token_id in own:
|
|
255
|
+
raise ValueError("the option codes A-Z are not the tokens llama.cpp reads at the answer position")
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def systemone_temperatures(cal):
|
|
259
|
+
"""{"<type>.<llama.cpp bucket>": T} of a basal calibration (calibration file 2, one option order); ValueError when a
|
|
260
|
+
llama.cpp bucket would need two of basal's temperatures."""
|
|
261
|
+
from .server import temperature
|
|
262
|
+
|
|
263
|
+
if cal.get("prompt", 2) != 2 or cal.get("orders", 1) != 1:
|
|
264
|
+
raise ValueError("the calibration was fitted for another prompt format or for several option orders; "
|
|
265
|
+
"llama.cpp reads prompt format 2 in one option order")
|
|
266
|
+
out = {}
|
|
267
|
+
for typ, (lo, hi) in SYSTEMONE_COUNTS.items():
|
|
268
|
+
for name, b_lo, b_hi in LLAMA_BUCKETS:
|
|
269
|
+
temps = {temperature(cal, typ, k) for k in range(max(lo, b_lo), min(hi, b_hi) + 1)}
|
|
270
|
+
if len(temps) > 1:
|
|
271
|
+
raise ValueError(f"{typ} options {b_lo}-{b_hi} have {len(temps)} temperatures in this calibration; "
|
|
272
|
+
"llama.cpp keeps one per bucket (2, 3-5, 6-10, 11+)")
|
|
273
|
+
if temps:
|
|
274
|
+
out[f"{typ}.{name}"] = temps.pop()
|
|
275
|
+
return out
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
def systemone_calibration(model_dir, path=None):
|
|
279
|
+
"""The calibration file written into the GGUF: `path`, else the first of SYSTEMONE_CALIBRATIONS in the model
|
|
280
|
+
folder (the llama.cpp ports' own fits first)."""
|
|
281
|
+
if path:
|
|
282
|
+
return Path(path)
|
|
283
|
+
for name in SYSTEMONE_CALIBRATIONS:
|
|
284
|
+
if (Path(model_dir) / name).is_file():
|
|
285
|
+
return Path(model_dir) / name
|
|
286
|
+
raise ValueError(f"{model_dir} has no calibration file ({', '.join(SYSTEMONE_CALIBRATIONS)}); pass --calibration")
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
def systemone_metadata(model_dir, calibration=None):
|
|
290
|
+
"""(the decision keys of --systemone, without the architecture prefix, as {key: (kind, value)}; the calibration
|
|
291
|
+
file used). The model must be prompt format 2 in the canonical layout, read one way, without isolated options."""
|
|
292
|
+
from transformers import AutoTokenizer
|
|
293
|
+
|
|
294
|
+
from .derive import reading_refused
|
|
295
|
+
from .prompt import model_format, model_layout
|
|
296
|
+
|
|
297
|
+
if model_format(model_dir) != 2 or model_layout(model_dir) != "canonical" or reading_refused(model_dir):
|
|
298
|
+
raise ValueError("--systemone needs a prompt-format-2 model in the canonical layout, read one way, without "
|
|
299
|
+
"isolated options (its basal.json)")
|
|
300
|
+
tok = AutoTokenizer.from_pretrained(model_dir)
|
|
301
|
+
from .prompt import special_names
|
|
302
|
+
|
|
303
|
+
template = systemone_template(*chat_frame(tok), specials=special_names(tok))
|
|
304
|
+
check_systemone(tok, template)
|
|
305
|
+
cal_path = systemone_calibration(model_dir, calibration)
|
|
306
|
+
temps = systemone_temperatures(json.loads(read_text(cal_path)))
|
|
307
|
+
meta = {"decision.type": ("string", SYSTEMONE_TYPE), SYSTEMONE_TEMPLATE: ("string", template)}
|
|
308
|
+
meta.update({f"decision.temperature.{k}": ("float32", t) for k, t in temps.items()})
|
|
309
|
+
return meta, cal_path
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
def fix_gguf(raw, outfile, model_dir, decision=None):
|
|
313
|
+
"""Copy `raw` to `outfile` with the three tokenizer fields fixed from `model_dir`/tokenizer.json. The input's
|
|
314
|
+
<arch>.decision.* keys and systemone template are dropped; `decision` (systemone_metadata) writes new ones. Returns
|
|
315
|
+
(tokens ranked, tokens)."""
|
|
316
|
+
import gguf
|
|
317
|
+
from gguf.scripts.gguf_new_metadata import MetadataDetails, copy_with_new_metadata
|
|
318
|
+
|
|
319
|
+
reader = gguf.GGUFReader(raw)
|
|
320
|
+
tokens = reader.fields[gguf.Keys.Tokenizer.LIST].contents()
|
|
321
|
+
tokenizer_json = json.loads((Path(model_dir) / "tokenizer.json").read_text(encoding="utf-8"))
|
|
322
|
+
if any(i >= len(tokens) or tokens[i] != t for t, i in tokenizer_json["model"]["vocab"].items()):
|
|
323
|
+
raise ValueError(f"the vocabulary of {raw} differs from {Path(model_dir) / 'tokenizer.json'}")
|
|
324
|
+
scores, ranked = merge_rank_scores(tokenizer_json, tokens)
|
|
325
|
+
token_types = added_token_types(tokenizer_json, reader.fields[gguf.Keys.Tokenizer.TOKEN_TYPE].contents())
|
|
326
|
+
arch = reader.fields[gguf.Keys.General.ARCHITECTURE].contents()
|
|
327
|
+
new = {gguf.Keys.Tokenizer.ADD_PREFIX: MetadataDetails(gguf.GGUFValueType.BOOL, False),
|
|
328
|
+
gguf.Keys.Tokenizer.SCORES: MetadataDetails(gguf.GGUFValueType.ARRAY, scores,
|
|
329
|
+
sub_type=gguf.GGUFValueType.FLOAT32),
|
|
330
|
+
gguf.Keys.Tokenizer.TOKEN_TYPE: MetadataDetails(gguf.GGUFValueType.ARRAY, token_types,
|
|
331
|
+
sub_type=gguf.GGUFValueType.INT32)}
|
|
332
|
+
kinds = {"string": gguf.GGUFValueType.STRING, "float32": gguf.GGUFValueType.FLOAT32}
|
|
333
|
+
for key, (kind, value) in (decision or {}).items():
|
|
334
|
+
new[key if key.startswith("tokenizer.") else f"{arch}.{key}"] = MetadataDetails(kinds[kind], value)
|
|
335
|
+
stale = [k for k in reader.fields if k.startswith(f"{arch}.decision.") or k == SYSTEMONE_TEMPLATE]
|
|
336
|
+
writer = gguf.GGUFWriter(outfile, arch=arch, endianess=reader.endianess)
|
|
337
|
+
copy_with_new_metadata(reader, writer, new, stale)
|
|
338
|
+
return ranked, len(tokens)
|
|
339
|
+
|
|
340
|
+
|
|
341
|
+
MTP_KEYS = ("mtp_num_hidden_layers", "num_nextn_predict_layers") # config.json: multi-token prediction layers
|
|
342
|
+
NO_MTP_FLAGS = ("--no-mtp", "--no-nextn") # llama.cpp's converter (2026-05): leave them out
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
def model_config(model_dir):
|
|
346
|
+
"""The model's config.json with its text_config's keys over it ({} without one)."""
|
|
347
|
+
p = Path(model_dir) / "config.json"
|
|
348
|
+
if not p.is_file():
|
|
349
|
+
return {}
|
|
350
|
+
cfg = json.loads(read_text(p))
|
|
351
|
+
return {**cfg, **(cfg.get("text_config") or {})}
|
|
352
|
+
|
|
353
|
+
|
|
354
|
+
def model_name(spec):
|
|
355
|
+
"""The model's name for the GGUF's general.name: the last part of a repo id or folder, the repository's name for
|
|
356
|
+
a folder in the Hugging Face cache (models--<org>--<name>/snapshots/<commit>)."""
|
|
357
|
+
m = re.search(r"models--[^/\\]+--([^/\\]+)[/\\]snapshots[/\\][^/\\]+[/\\]?$", str(spec))
|
|
358
|
+
return m.group(1) if m else Path(spec).name
|
|
359
|
+
|
|
360
|
+
|
|
361
|
+
def converter_args(converter, model_dir, name):
|
|
362
|
+
"""Arguments for llama.cpp's converter after --outfile: --model-name (else it names the model after the folder, a
|
|
363
|
+
Hugging Face snapshot's hash), and --no-mtp for a model whose config.json declares multi-token prediction layers:
|
|
364
|
+
basal reads no MTP head and its checkpoints have none, but the converter would write the layers from the config
|
|
365
|
+
alone, and llama.cpp then refuses the file (a tensor not found). The converter refuses --no-mtp for architectures
|
|
366
|
+
without MTP layers, so it is passed only for these."""
|
|
367
|
+
args = ["--model-name", name]
|
|
368
|
+
if any(model_config(model_dir).get(k) for k in MTP_KEYS):
|
|
369
|
+
out = subprocess.run([sys.executable, str(converter), "--help"], capture_output=True, text=True)
|
|
370
|
+
flag = next((f for f in NO_MTP_FLAGS if f in out.stdout), None)
|
|
371
|
+
if flag is None:
|
|
372
|
+
raise ValueError(f"{model_dir}/config.json declares multi-token prediction layers, which basal's checkpoints "
|
|
373
|
+
f"do not have, and {converter} has no {NO_MTP_FLAGS[0]} to leave them out: update llama.cpp")
|
|
374
|
+
args.append(flag)
|
|
375
|
+
return args
|
|
376
|
+
|
|
377
|
+
|
|
378
|
+
def check_block_count(raw, model_dir):
|
|
379
|
+
"""The converted file must have as many blocks as the model has layers (config.json num_hidden_layers): llama.cpp
|
|
380
|
+
refuses a file whose blocks have no tensors."""
|
|
381
|
+
import gguf
|
|
382
|
+
|
|
383
|
+
layers = model_config(model_dir).get("num_hidden_layers")
|
|
384
|
+
reader = gguf.GGUFReader(raw)
|
|
385
|
+
arch = reader.fields[gguf.Keys.General.ARCHITECTURE].contents()
|
|
386
|
+
field = reader.fields.get(gguf.Keys.LLM.BLOCK_COUNT.format(arch=arch))
|
|
387
|
+
if layers and field is not None and field.contents() != layers:
|
|
388
|
+
raise ValueError(f"the converter wrote {field.contents()} blocks for a model of {layers} layers "
|
|
389
|
+
"(config.json num_hidden_layers): llama.cpp would not load the file")
|
|
390
|
+
|
|
391
|
+
|
|
392
|
+
def main(argv=None):
|
|
393
|
+
ap = argparse.ArgumentParser(description=(__doc__ or "").split("\n\n")[0]) # no docstring under python -OO
|
|
394
|
+
ap.add_argument("model", help="local directory or Hugging Face repo id (with --gguf: only its tokenizer.json is "
|
|
395
|
+
"read)")
|
|
396
|
+
ap.add_argument("outfile")
|
|
397
|
+
ap.add_argument("--gguf", default=None, help="fix this GGUF file instead of converting the model (a stock "
|
|
398
|
+
"conversion, a llama-quantize output, an older basal GGUF)")
|
|
399
|
+
ap.add_argument("--outtype", default="f16", help="converter output type: f16, q8_0, bf16, f32")
|
|
400
|
+
ap.add_argument("--llama-cpp", default=None, help="llama.cpp checkout containing convert_hf_to_gguf.py "
|
|
401
|
+
"(not needed with --gguf)")
|
|
402
|
+
ap.add_argument("--revision", default=None)
|
|
403
|
+
ap.add_argument("--systemone", action="store_true",
|
|
404
|
+
help="also write the decision metadata of llama.cpp's /v1/systemone (llama-server, LM Studio "
|
|
405
|
+
"0.4.26+): basal's prompt as a template and the calibrated temperatures; prompt-format-2 "
|
|
406
|
+
"models, at most 26 options per question")
|
|
407
|
+
ap.add_argument("--one-way", dest="one_way", action="store_true",
|
|
408
|
+
help="export a two-way model (basal.json \"two_way\") for llama.cpp's one-way (causal) reading "
|
|
409
|
+
"anyway: its answers then differ from basal-serve's")
|
|
410
|
+
ap.add_argument("--calibration", default=None,
|
|
411
|
+
help="--systemone: the calibration file whose temperatures are written (default: the model's "
|
|
412
|
+
+ ", else ".join(SYSTEMONE_CALIBRATIONS) + ")")
|
|
413
|
+
a = ap.parse_args(argv)
|
|
414
|
+
if a.calibration and not a.systemone:
|
|
415
|
+
ap.error("--calibration needs --systemone")
|
|
416
|
+
out = Path(a.outfile)
|
|
417
|
+
if out.is_dir():
|
|
418
|
+
ap.error(f"{out} is a directory; give the name of the output file")
|
|
419
|
+
if a.gguf:
|
|
420
|
+
if not Path(a.gguf).is_file():
|
|
421
|
+
ap.error(f"{a.gguf} not found")
|
|
422
|
+
if out.exists() and out.samefile(a.gguf):
|
|
423
|
+
ap.error("the output must be a new file: the input is read while the output is written")
|
|
424
|
+
else:
|
|
425
|
+
converter = Path(a.llama_cpp or "").expanduser() / "convert_hf_to_gguf.py"
|
|
426
|
+
if not a.llama_cpp or not converter.is_file():
|
|
427
|
+
ap.error(f"{converter} not found; clone https://github.com/ggml-org/llama.cpp and pass it as --llama-cpp "
|
|
428
|
+
"(or fix an existing file with --gguf)")
|
|
429
|
+
if not a.gguf: # converting the weights: a ModelOpt checkpoint is refused from its metadata, before they download
|
|
430
|
+
from . import derive
|
|
431
|
+
from .engine import resolve
|
|
432
|
+
why = derive.modelopt_refused(resolve(a.model, a.revision, metadata_only=True), a.model, "basal-export-gguf",
|
|
433
|
+
"convert")
|
|
434
|
+
if why:
|
|
435
|
+
sys.exit(why)
|
|
436
|
+
try:
|
|
437
|
+
import gguf # noqa: F401
|
|
438
|
+
except ImportError:
|
|
439
|
+
ap.error('the gguf package is missing; install the gguf-export extra (from a clone: uv pip install -e '
|
|
440
|
+
'".[gguf-export]") or uv pip install "gguf>=0.19"')
|
|
441
|
+
from huggingface_hub import snapshot_download
|
|
442
|
+
|
|
443
|
+
files = (MODEL_FILES if a.systemone else ["tokenizer.json", "basal.json"]) if a.gguf else None
|
|
444
|
+
model_dir = Path(a.model) if Path(a.model).exists() else Path(snapshot_download(
|
|
445
|
+
a.model, revision=a.revision, allow_patterns=files))
|
|
446
|
+
if not (model_dir / "tokenizer.json").is_file():
|
|
447
|
+
ap.error(f"{a.model} has no tokenizer.json; pass the basal model the GGUF was converted from")
|
|
448
|
+
from .prompt import model_two_way
|
|
449
|
+
try:
|
|
450
|
+
two_way = model_two_way(model_dir)
|
|
451
|
+
except ValueError as e:
|
|
452
|
+
sys.exit(f"basal-export-gguf: {e}")
|
|
453
|
+
if two_way and not a.one_way: # before the converter runs
|
|
454
|
+
sys.exit(f"basal-export-gguf: {a.model} is trained to read two ways (basal.json \"two_way\"), but llama.cpp "
|
|
455
|
+
"reads a GGUF one way (causally), so its answers differ from basal-serve's (on a two-way model we "
|
|
456
|
+
"measured, 61% of the top answers agreed). Pass --one-way to export it for that reading anyway.")
|
|
457
|
+
if a.one_way and not two_way:
|
|
458
|
+
ap.error("--one-way is for a two-way model (basal.json \"two_way\"); this one is read one way already")
|
|
459
|
+
decision = cal = None
|
|
460
|
+
if a.systemone:
|
|
461
|
+
try:
|
|
462
|
+
decision, cal = systemone_metadata(model_dir, a.calibration)
|
|
463
|
+
except ValueError as e:
|
|
464
|
+
sys.exit(f"basal-export-gguf: {e}")
|
|
465
|
+
out.parent.mkdir(parents=True, exist_ok=True)
|
|
466
|
+
with tempfile.TemporaryDirectory(dir=out.parent) as tmp:
|
|
467
|
+
raw = Path(a.gguf or Path(tmp) / "converted.gguf")
|
|
468
|
+
if not a.gguf:
|
|
469
|
+
try:
|
|
470
|
+
extra = converter_args(converter, model_dir, model_name(a.model))
|
|
471
|
+
except ValueError as e:
|
|
472
|
+
sys.exit(f"basal-export-gguf: {e}")
|
|
473
|
+
done = subprocess.run([sys.executable, str(converter), str(model_dir), "--outtype", a.outtype,
|
|
474
|
+
"--outfile", str(raw), *extra])
|
|
475
|
+
if done.returncode != 0:
|
|
476
|
+
sys.exit(f"basal-export-gguf: llama.cpp's converter failed (exit {done.returncode}); "
|
|
477
|
+
"see its output above")
|
|
478
|
+
try:
|
|
479
|
+
check_block_count(raw, model_dir)
|
|
480
|
+
except ValueError as e:
|
|
481
|
+
sys.exit(f"basal-export-gguf: {e}")
|
|
482
|
+
part = Path(tmp) / out.name # written in full first, then renamed: an interrupted export leaves no
|
|
483
|
+
try: # truncated file under the output's name (nor overwrites an older one)
|
|
484
|
+
ranked, total = fix_gguf(raw, part, model_dir, decision)
|
|
485
|
+
except ValueError as e:
|
|
486
|
+
sys.exit(f"basal-export-gguf: {e}")
|
|
487
|
+
os.replace(part, out)
|
|
488
|
+
print(f"wrote {out}: {ranked}/{total} token scores from BPE merges, add_space_prefix=false")
|
|
489
|
+
if two_way:
|
|
490
|
+
print(" read one way (--one-way): llama.cpp reads it causally, not two ways as basal-serve does")
|
|
491
|
+
if decision:
|
|
492
|
+
print(f" decision model for /v1/systemone ({SYSTEMONE_TYPE}, at most {SYSTEMONE_MAX_OPTIONS} options), "
|
|
493
|
+
f"temperatures from {cal.name}")
|
|
494
|
+
|
|
495
|
+
|
|
496
|
+
if __name__ == "__main__":
|
|
497
|
+
main()
|