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/feedback.py ADDED
@@ -0,0 +1,234 @@
1
+ """basal-feedback (3.0): the decisions people reviewed in production, as basal-calibrate input.
2
+
3
+ basal-feedback decisions.jsonl labels.jsonl -o labelled.jsonl # then: basal-calibrate labelled.jsonl ...
4
+
5
+ It joins basal-serve's decision log (--log-decisions with --log-requests and --review-sample, basal/decision_log.py)
6
+ with your reviewers' labels and writes the standard labelled input of basal-calibrate (docs/CALIBRATION.md): one
7
+ request per line, each labelled question with its "gold". The fit and the certification are basal-calibrate's,
8
+ unchanged.
9
+
10
+ Labels (JSONL): {"id": <the request's id: its X-Request-Id / request_id, or the body's "id">, "gold": {<question>:
11
+ <answer>, ...}} per line, the answers as basal-calibrate takes them (an option key, "yes" / "no", a level, labels);
12
+ other fields (a reviewer's name) are ignored.
13
+
14
+ What it keeps, and why:
15
+ - only the requests of the audit sample (their line's "review_sample" says "in"): a uniform sample of requests,
16
+ automated and deferred decisions alike. Labels of the decisions basal deferred alone describe the uncertain tail
17
+ and say nothing about the errors among the accepted ones, which is what a threshold certifies;
18
+ - one serving configuration (the line's "serving": model, revision, adapter, mode, layout, orders, calibration file):
19
+ by default the one of the log's last line (--serving all lists them), since another model or calibration answered
20
+ other probabilities;
21
+ - one line per request: a "cache": "hit" line repeats a decision computed once, and a request logged twice (the same
22
+ request_sha256) is kept once;
23
+ - the logged request as it was sent (its "request": the server needs --log-requests), with its "group" when it has
24
+ one, its questions reduced to the labelled ones. A request with images or audio is left out: the log keeps them as
25
+ their sha256 and size only, so basal-calibrate could not read it again.
26
+ Every line or label left out is counted and said; a label whose id names no kept request, or several, is named.
27
+ A label names a request by either of its ids: the labels of one request are merged, so it is written once, and a
28
+ question they answer differently is left out and named (by the request's id as written: the body's, else its
29
+ request id).
30
+ """
31
+ import argparse
32
+ import json
33
+ import sys
34
+ from collections import Counter, OrderedDict
35
+
36
+ from .decision_log import has_media
37
+ from .jsonl import JSONLError, records, write
38
+
39
+ REASONS = {
40
+ "no_request": "logged without the request (start basal-serve with --log-requests)",
41
+ "media": "with images or audio, which the log keeps as their sha256 and size only",
42
+ "not_sampled": "not in the audit sample (or logged without --review-sample)",
43
+ "other_serving": "served by another configuration",
44
+ "cache_hit": "a response-cache hit (the decision repeated)",
45
+ "repeat": "the same request logged again",
46
+ }
47
+
48
+
49
+ def serving_key(line):
50
+ return json.dumps(line.get("serving") or {}, sort_keys=True)
51
+
52
+
53
+ def read_log(path):
54
+ """The log's lines that are decision lines (a "request_sha256"), in order; JSONLError at a line that is not JSON."""
55
+ out = []
56
+ for n, rec in records(path, objects=True):
57
+ if "request_sha256" in rec:
58
+ out.append((n, rec))
59
+ return out
60
+
61
+
62
+ def choose_serving(lines, which="latest"):
63
+ """The serving configuration the join keeps: the log's last line's ("latest"), or the most frequent ("most")."""
64
+ if not lines:
65
+ return None
66
+ if which == "most":
67
+ return Counter(serving_key(r) for _, r in lines).most_common(1)[0][0]
68
+ return serving_key(lines[-1][1])
69
+
70
+
71
+ def kept_lines(lines, serving):
72
+ """The lines the join can use, one per request, and the count of each left out (REASONS)."""
73
+ kept, dropped, seen = [], Counter(), set()
74
+ for n, r in lines:
75
+ if r.get("cache") == "hit":
76
+ dropped["cache_hit"] += 1
77
+ elif serving_key(r) != serving:
78
+ dropped["other_serving"] += 1
79
+ elif not (r.get("review_sample") or {}).get("in"):
80
+ dropped["not_sampled"] += 1
81
+ elif not isinstance(r.get("request"), dict):
82
+ dropped["no_request"] += 1
83
+ elif has_media(r["request"]):
84
+ dropped["media"] += 1
85
+ elif r["request_sha256"] in seen:
86
+ dropped["repeat"] += 1
87
+ else:
88
+ seen.add(r["request_sha256"])
89
+ kept.append((n, r))
90
+ return kept, dropped
91
+
92
+
93
+ def read_labels(path):
94
+ """{id: (line, gold)}; a label with no id or no gold object is an error with its line; two labels of one id are
95
+ merged when they agree, and a question they disagree on is left out (returned in the conflicts)."""
96
+ labels, conflicts = OrderedDict(), set()
97
+ for n, rec in records(path, objects=True):
98
+ ident, gold = rec.get("id"), rec.get("gold")
99
+ if not isinstance(ident, (str, int)) or isinstance(ident, bool):
100
+ raise JSONLError(f"{path}:{n}: a label needs an \"id\" (the request id or the body's id)")
101
+ if not isinstance(gold, dict) or not gold:
102
+ raise JSONLError(f"{path}:{n}: a label needs \"gold\": {{question: answer, ...}}")
103
+ key = str(ident)
104
+ if key not in labels:
105
+ labels[key] = (n, dict(gold))
106
+ continue
107
+ first = labels[key][1]
108
+ for q, v in gold.items():
109
+ if q in first and first[q] != v:
110
+ conflicts.add((key, q))
111
+ first.setdefault(q, v)
112
+ for key, (n, gold) in labels.items():
113
+ labels[key] = (n, {q: v for q, v in gold.items() if (key, q) not in conflicts})
114
+ return labels, sorted(conflicts)
115
+
116
+
117
+ def labelled(line, gold):
118
+ """The labelled request of a kept line: its request as sent, its id (the body's, else the request id), its group
119
+ as logged, only the labelled questions with their gold -> (request, the label's questions it has not)."""
120
+ req = json.loads(json.dumps(line["request"])) # (a copy)
121
+ questions = req.get("questions") if isinstance(req.get("questions"), dict) else {}
122
+ unknown = sorted(q for q in gold if q not in questions)
123
+ req["questions"] = {q: {**questions[q], "gold": gold[q]} for q in questions if gold.get(q) is not None}
124
+ req["id"] = line.get("id") if line.get("id") is not None else line["request_id"]
125
+ if line.get("group") is not None:
126
+ req["group"] = line["group"]
127
+ return req, unknown
128
+
129
+
130
+ def join(log_path, labels_path, serving="latest"):
131
+ """-> (labelled requests, report)."""
132
+ lines = read_log(log_path)
133
+ labels, conflicts = read_labels(labels_path)
134
+ chosen = choose_serving(lines, serving)
135
+ kept, dropped = kept_lines(lines, chosen)
136
+ by_id = {}
137
+ canonical = {r["request_sha256"]: r for _, r in kept}
138
+ for _, r in lines:
139
+ original = canonical.get(r["request_sha256"])
140
+ if original is None or serving_key(r) != serving_key(original):
141
+ continue
142
+ if not (r.get("review_sample") or {}).get("in") and r.get("cache") != "hit":
143
+ continue
144
+ for ident in {str(r["request_id"]), *((str(r["id"]),) if r.get("id") is not None else ())}:
145
+ by_id.setdefault(ident, []).append(original)
146
+ # each label resolved to the kept request it names (kept lines are one per request_sha256), by either of its ids,
147
+ # so that the labels of one request are merged, and checked against each other, whichever id they used
148
+ named, unmatched, ambiguous = OrderedDict(), [], []
149
+ for ident, (n, gold) in labels.items():
150
+ hits = by_id.get(ident, [])
151
+ if not hits:
152
+ unmatched.append(ident)
153
+ elif len({r["request_sha256"] for r in hits}) > 1:
154
+ ambiguous.append(ident)
155
+ else:
156
+ named.setdefault(hits[0]["request_sha256"], (hits[0], []))[1].append((ident, gold))
157
+ out, unknown, clashes = [], [], set()
158
+ for line, golds in named.values():
159
+ name = str(line["id"] if line.get("id") is not None else line["request_id"]) # as labelled() writes it
160
+ gold, bad = {}, {q for ident, _ in golds for i, q in conflicts if i == ident} # (two labels of one id)
161
+ for _, g in golds:
162
+ for q, v in g.items():
163
+ if q in gold and gold[q] != v:
164
+ bad.add(q)
165
+ gold.setdefault(q, v)
166
+ clashes |= {(name, q) for q in bad}
167
+ req, extra = labelled(line, {q: v for q, v in gold.items() if q not in bad})
168
+ unknown += [(name, q) for q in extra]
169
+ if req["questions"]:
170
+ out.append(req)
171
+ report = {"log_lines": len(lines), "kept_lines": len(kept), "dropped": dict(dropped), "labels": len(labels),
172
+ "labelled_requests": len(out), "labelled_decisions": sum(len(r["questions"]) for r in out),
173
+ "unmatched": unmatched, "ambiguous": ambiguous, "unknown_questions": unknown,
174
+ "conflicts": sorted(clashes),
175
+ "serving": json.loads(chosen) if chosen else None,
176
+ "servings": dict(Counter(serving_key(r) for _, r in lines))}
177
+ return out, report
178
+
179
+
180
+ def summary(report, out):
181
+ s = report["serving"] or {}
182
+ lines = [f"basal-feedback: {report['labelled_requests']} labelled requests ({report['labelled_decisions']} "
183
+ f"decisions) from {report['kept_lines']} of the log's {report['log_lines']} lines and "
184
+ f"{report['labels']} labels -> {out}",
185
+ f" serving: {s.get('model')} (revision {s.get('revision')}, mode {s.get('mode')}, calibration "
186
+ f"{(s.get('calibration_sha256') or 'none')[:12]}): calibrate with that model and mode"]
187
+ for k, n in report["dropped"].items():
188
+ lines.append(f" left out: {n} lines {REASONS[k]}")
189
+ for name, what in (("unmatched", "labels whose id names no kept request"),
190
+ ("ambiguous", "labels whose id names several requests")):
191
+ if report[name]:
192
+ lines.append(f" {len(report[name])} {what}: {', '.join(report[name][:10])}"
193
+ + (" ..." if len(report[name]) > 10 else ""))
194
+ if report["unknown_questions"]:
195
+ lines.append(f" {len(report['unknown_questions'])} labelled questions the request does not have: "
196
+ + ", ".join(f"{i}/{q}" for i, q in report["unknown_questions"][:10]))
197
+ if report["conflicts"]:
198
+ lines.append(f" {len(report['conflicts'])} questions labelled differently by two labels, left out: "
199
+ + ", ".join(f"{i}/{q}" for i, q in report["conflicts"][:10]))
200
+ return "\n".join(lines)
201
+
202
+
203
+ def main(argv=None):
204
+ ap = argparse.ArgumentParser(prog="basal-feedback", description=__doc__.split("\n\n")[0],
205
+ formatter_class=argparse.RawDescriptionHelpFormatter, epilog=__doc__.split("\n\n", 1)[1])
206
+ ap.add_argument("log", help="basal-serve's --log-decisions file (with --log-requests and --review-sample)")
207
+ ap.add_argument("labels", help='JSONL: {"id", "gold": {question: answer}} per line')
208
+ ap.add_argument("-o", "--out", required=True, help="the labelled requests for basal-calibrate (JSONL)")
209
+ ap.add_argument("--serving", choices=["latest", "most", "all"], default="latest",
210
+ help="the serving configuration to keep: that of the log's last line (default) or its most "
211
+ "frequent; all: list the configurations in the log and write nothing")
212
+ ap.add_argument("--report", default=None, help="also write the counts as JSON to this file")
213
+ a = ap.parse_args(argv)
214
+ try:
215
+ if a.serving == "all":
216
+ for key, n in Counter(serving_key(r) for _, r in read_log(a.log)).most_common():
217
+ print(f"{n:>8} {key}")
218
+ return 0
219
+ out, report = join(a.log, a.labels, a.serving)
220
+ except (JSONLError, OSError) as e:
221
+ raise SystemExit(f"basal-feedback: {e}") from None
222
+ if not out:
223
+ print(summary(report, a.out), file=sys.stderr)
224
+ raise SystemExit("basal-feedback: no labelled request to write")
225
+ write(a.out, out)
226
+ if a.report:
227
+ from .jsonl import write_json
228
+ write_json(a.report, report, indent=1)
229
+ print(summary(report, a.out), file=sys.stderr)
230
+ return 0
231
+
232
+
233
+ if __name__ == "__main__":
234
+ raise SystemExit(main())
basal/file_identity.py ADDED
@@ -0,0 +1,39 @@
1
+ """Exact local artifact identities used in calibration and serving manifests."""
2
+ from functools import lru_cache
3
+ import hashlib
4
+ import os
5
+
6
+
7
+ def _identity(st):
8
+ return st.st_dev, st.st_ino, st.st_size, st.st_mtime_ns, st.st_ctime_ns
9
+
10
+
11
+ def _path_identity(path):
12
+ # On Windows stat(path) and fstat(fd) can expose different metadata for the same file.
13
+ # Reopen the name for the final check so a replacement is detected even if the old handle survived.
14
+ if os.name == "nt":
15
+ with open(path, "rb") as f:
16
+ return _identity(os.fstat(f.fileno()))
17
+ return _identity(os.stat(path))
18
+
19
+
20
+ @lru_cache(maxsize=2048)
21
+ def _digest(path, identity):
22
+ h = hashlib.sha256()
23
+ with open(path, "rb") as f:
24
+ if _identity(os.fstat(f.fileno())) != identity:
25
+ raise OSError(f"model file changed before hashing: {path}")
26
+ for block in iter(lambda: f.read(4 << 20), b""):
27
+ h.update(block)
28
+ if _identity(os.fstat(f.fileno())) != identity:
29
+ raise OSError(f"model file changed during hashing: {path}")
30
+ return h.hexdigest()
31
+
32
+
33
+ def verified_file(path):
34
+ path = os.path.realpath(path)
35
+ identity = _path_identity(path)
36
+ digest = _digest(path, identity)
37
+ if _path_identity(path) != identity:
38
+ raise OSError(f"model file changed while resolving identity: {path}")
39
+ return identity[2], digest
basal/finetune.py ADDED
@@ -0,0 +1,321 @@
1
+ """Adapt a basal model to your own labelled decisions with LoRA (2.5), then calibrate it with basal-calibrate.
2
+
3
+ pip install "basal-engine[finetune]"
4
+ basal-finetune labelled.jsonl --model Remek/basal-omni-pico --out my-pico # trains, merges, writes my-pico/
5
+ basal-calibrate my-pico/heldout.jsonl --model my-pico --mode eager --out my-pico/CALIBRATION.json
6
+ basal-serve --model my-pico --mode eager
7
+
8
+ The input is the JSONL of basal-calibrate (docs/CALIBRATION.md): one request per line, every question with its correct
9
+ answer in "gold". The lines are split by group into a training part and a held-out part (--holdout, default 25%): the
10
+ LoRA sees the first only, basal-calibrate must fit on the second (a calibration fitted on lines the model trained on
11
+ is over-confident). Training uses the prompt basal-serve builds, in the model's format, and the loss of the served
12
+ readout: the softmax over the option codes at the answer position. Each example is shown in the given option order or
13
+ the reversed one, the two orders basal-serve averages. choice, noul, score and act questions are trained; multi
14
+ questions and task types are skipped (counted).
15
+
16
+ The base is a basal model (a directory with basal.json) or a chat model attached with basal-attach. It is not
17
+ changed: --out gets a full merged model (and the adapter in --out/lora)."""
18
+ import argparse
19
+ import hashlib
20
+ import json
21
+ import math
22
+ import random
23
+ import shutil
24
+ import sys
25
+ import time
26
+ from pathlib import Path
27
+
28
+ import torch
29
+ import torch.nn.functional as F
30
+
31
+ from . import __version__, derive
32
+ from .calibrate import InputError, load
33
+ from .engine import default_device, resolve
34
+ from .facts import inject as inject_facts
35
+ from .jsonl import read_lines
36
+ from .prompt import letter_ids, max_options, model_format, model_layout, render
37
+ from .server import to_items
38
+
39
+ WEIGHT_SUFFIXES = (".safetensors", ".bin", ".pt", ".gguf")
40
+
41
+
42
+ def in_holdout(group, holdout, seed):
43
+ """Whether a group is held out: a hash of the group, so twins and one customer's lines stay on the same side."""
44
+ h = int(hashlib.sha1(f"{seed}:{group}".encode()).hexdigest()[:8], 16)
45
+ return h / 0x100000000 < holdout
46
+
47
+
48
+ def split(path, holdout=0.25, seed=0):
49
+ """Labelled JSONL -> (train decisions with their bodies, held-out line texts, skipped counts). Lines that share a
50
+ group on any of their decisions (a per-question "group") form one unit, so no group is on both sides; a unit goes
51
+ with the group of the first decision of its first line (a line that shares no group: its first decision's group)."""
52
+ bodies, decisions = load(path)
53
+ lines = read_lines(path)
54
+ root, first, owner = {}, {}, {} # line -> parent line (union-find), line -> its first group, group -> a line
55
+
56
+ def find(x):
57
+ while root[x] != x:
58
+ root[x] = root[root[x]]
59
+ x = root[x]
60
+ return x
61
+ for d in decisions:
62
+ n = d["line"]
63
+ root.setdefault(n, n)
64
+ first.setdefault(n, d["group"])
65
+ other = owner.setdefault(d["group"], n)
66
+ a, b = find(n), find(other)
67
+ root[max(a, b)] = min(a, b) # the unit's root is its first line
68
+ side = {n: in_holdout(first[find(n)], holdout, seed) for n in root}
69
+ train, skipped = [], {}
70
+ for d in decisions:
71
+ if side[d["line"]]:
72
+ continue
73
+ if d["prim"] == "multi":
74
+ skipped["multi"] = skipped.get("multi", 0) + 1
75
+ else:
76
+ train.append((bodies[d["req"]], d))
77
+ held = [lines[n - 1] for n in sorted(k for k, v in side.items() if v)]
78
+ return train, held, skipped
79
+
80
+
81
+ def example(tok, body, d, fmt, layout, max_len):
82
+ """(prompt ids per option order, code ids, gold index per order) for one labelled decision, or None with why."""
83
+ state = body["state"]
84
+ if body.get("facts") == "auto":
85
+ state = inject_facts(state if isinstance(state, str) else json.dumps(state, ensure_ascii=False))
86
+ item = to_items(state, {d["name"]: body["questions"][d["name"]]}, max_options(fmt), force_lang=body.get("lang"))[0]
87
+ opts, k = item["options"], len(item["options"])
88
+ orders = []
89
+ for perm in (list(range(k)), list(range(k))[::-1]):
90
+ prompt = render(tok, item["state"], item["question"], [opts[i] for i in perm], item["lang"], fmt, layout)
91
+ codes = letter_ids(tok, prompt, k, fmt)
92
+ if codes is None:
93
+ return None, "an option code is not one token at the answer position"
94
+ ids = tok(prompt, add_special_tokens=False).input_ids
95
+ if len(ids) > max_len:
96
+ return None, f"longer than --max-len {max_len} tokens"
97
+ orders.append((ids, codes, perm.index(d["gold"])))
98
+ return orders, None
99
+
100
+
101
+ def refused(src):
102
+ """Why basal-finetune cannot train model src, or None: it trains and scores with the plain causal forward, and a
103
+ model the engine reads another way (derive.reading_refused) would be trained under masks it is not served with
104
+ (and the merged model, keeping its basal.json, served that way)."""
105
+ why = derive.reading_refused(src)
106
+ return why and (f"{src}: {why}: basal-finetune trains with the plain causal forward only; this model is served "
107
+ "with other attention masks")
108
+
109
+
110
+ def lora_targets(model):
111
+ """The linear layers LoRA trains: those of the text decoder's layers only (layers.N.<module>, as --adapter takes
112
+ them), not the vision / audio towers ("all-linear" would train those too, and --adapter refuses such an adapter)."""
113
+ from .adapter import _LAYER
114
+ return sorted(n for n, mod in model.named_modules() if isinstance(mod, torch.nn.Linear) and _LAYER.match(n))
115
+
116
+
117
+ def copy_side_files(src, out):
118
+ """The base model's files the merged model keeps (tokenizer, chat template, processor ...): not the weights, the
119
+ index, basal.json (written anew), .gitattributes, nor what does not hold for other weights (derive.stale: its
120
+ calibrations, NVFP4 activation scales, evidence head, card, manifest and checksums; no subdirectory)."""
121
+ for f in sorted(Path(src).iterdir()):
122
+ if f.is_file() and not f.name.endswith(WEIGHT_SUFFIXES) and not f.name.endswith(".index.json") \
123
+ and f.name not in ("basal.json", ".gitattributes") and not derive.stale(f.name):
124
+ shutil.copy2(f, Path(out) / f.name)
125
+
126
+
127
+ def code_logits(model, ids, codes, softcap, device):
128
+ """The logits of the option codes at the answer position as basal-serve reads them (basal/readout.py, the one code
129
+ readout of every engine): the output head's input (the final norm's output at the last position) times the code
130
+ rows in fp32, the head's bias and the model's final logit soft cap once. (The model's own logits are capped already:
131
+ a Gemma forward applies final_logit_softcapping itself.) In fp32 also under the training steps' autocast, which
132
+ would take the product in bf16 / fp16."""
133
+ from .readout import CodeReadout
134
+ head = model.get_output_embeddings()
135
+ got = {}
136
+ hook = head.register_forward_pre_hook(lambda mod, args: got.__setitem__("h", args[0]))
137
+ try:
138
+ model(input_ids=torch.tensor([ids], device=device), logits_to_keep=1)
139
+ finally:
140
+ hook.remove()
141
+ rd = CodeReadout(head, softcap)
142
+ rows, idx, _ = rd.rows([codes])
143
+ with torch.autocast(torch.device(device).type, enabled=False): # fp32 under the training steps' autocast too
144
+ return rd.logits(got["h"][:, -1], rows)[0].index_select(0, idx[0])
145
+
146
+
147
+ def accuracy(model, examples, softcap, device):
148
+ """Top-1 accuracy of the given option order over examples."""
149
+ hits = 0
150
+ with torch.no_grad():
151
+ for orders in examples:
152
+ ids, codes, gold = orders[0]
153
+ hits += int(code_logits(model, ids, codes, softcap, device).argmax().item() == gold)
154
+ return hits / max(len(examples), 1)
155
+
156
+
157
+ def pick_dtype(name, device):
158
+ if name != "auto":
159
+ return getattr(torch, name)
160
+ if device == "cuda":
161
+ return torch.bfloat16 if torch.cuda.is_bf16_supported() else torch.float16 # a T4 has no bfloat16
162
+ return torch.bfloat16 if device == "mps" else torch.float32
163
+
164
+
165
+ def main(argv=None):
166
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
167
+ ap.add_argument("labelled", help="labelled JSONL, the input of basal-calibrate")
168
+ ap.add_argument("--model", required=True, help="a basal model: local directory or Hugging Face repo id")
169
+ ap.add_argument("--out", required=True, help="directory to write: the merged model, heldout.jsonl, lora/")
170
+ ap.add_argument("--holdout", type=float, default=0.25, help="share of the groups kept out of training (default 0.25)")
171
+ ap.add_argument("--epochs", type=float, default=2.0)
172
+ ap.add_argument("--max-steps", dest="max_steps", type=int, default=None, help="stop after this many optimizer steps")
173
+ ap.add_argument("--lr", type=float, default=1e-4)
174
+ ap.add_argument("--batch", type=int, default=16, help="examples per optimizer step (accumulated one by one)")
175
+ ap.add_argument("--rank", type=int, default=16)
176
+ ap.add_argument("--alpha", type=int, default=32)
177
+ ap.add_argument("--dropout", type=float, default=0.05)
178
+ ap.add_argument("--max-len", dest="max_len", type=int, default=2048, help="examples with a longer prompt are skipped")
179
+ ap.add_argument("--dtype", default="auto", choices=["auto", "float32", "float16", "bfloat16"],
180
+ help="auto: bfloat16 on a GPU that has it, float16 on a T4, bfloat16 on Apple Silicon, else float32")
181
+ ap.add_argument("--device", default=None, choices=["cuda", "mps", "cpu"])
182
+ ap.add_argument("--grad-checkpointing", dest="grad_ckpt", action="store_true",
183
+ help="less memory, about a third slower (use it on a 16 GB GPU with a model of 3B or more)")
184
+ ap.add_argument("--eval-max", dest="eval_max", type=int, default=200, help="held-out decisions scored before and after")
185
+ ap.add_argument("--seed", type=int, default=0)
186
+ ap.add_argument("--force", action="store_true", help="write into a directory that is not empty")
187
+ a = ap.parse_args(argv)
188
+
189
+ out = Path(a.out).resolve()
190
+ meta = resolve(a.model, metadata_only=True)
191
+ why = derive.modelopt_refused(meta, a.model, "basal-finetune", "train a LoRA on")
192
+ if why:
193
+ raise SystemExit(why)
194
+ src = Path(resolve(a.model)).resolve()
195
+ if out == src or out in src.parents or src in out.parents:
196
+ raise SystemExit("--out and the input checkpoint must not overlap")
197
+ if out.exists() and any(out.iterdir()) and not a.force:
198
+ raise SystemExit(f"--out {out}: not empty (--force writes into it)")
199
+
200
+ try:
201
+ from peft import LoraConfig, get_peft_model
202
+ except ImportError:
203
+ raise SystemExit('basal-finetune needs peft: pip install "basal-engine[finetune]"') from None
204
+ from transformers import AutoModelForCausalLM, AutoTokenizer
205
+
206
+ if not (src / "basal.json").exists():
207
+ raise SystemExit(f"{a.model} has no basal.json: use a basal model, or attach a chat model first "
208
+ "(basal-attach, docs/SERVING.md)")
209
+ if refused(src):
210
+ raise SystemExit(refused(src))
211
+ fmt, layout = model_format(src), model_layout(src)
212
+ try:
213
+ train, held, skipped = split(a.labelled, a.holdout, a.seed)
214
+ except InputError as e:
215
+ raise SystemExit(str(e)) from None
216
+ if not train or not held:
217
+ raise SystemExit(f"{a.labelled}: {len(train)} training decisions and {len(held)} held-out lines; need both "
218
+ "(more groups, or a different --holdout)")
219
+ random.seed(a.seed)
220
+ torch.manual_seed(a.seed)
221
+ device = a.device or default_device()
222
+ dtype = pick_dtype(a.dtype, device)
223
+ tok = AutoTokenizer.from_pretrained(src)
224
+
225
+ def build(pairs):
226
+ ex = []
227
+ for body, d in pairs:
228
+ orders, why = example(tok, body, d, fmt, layout, a.max_len)
229
+ if orders:
230
+ ex.append(orders)
231
+ else:
232
+ skipped[why] = skipped.get(why, 0) + 1
233
+ return ex
234
+
235
+ examples = build(train)
236
+ if not examples:
237
+ raise SystemExit(f"no trainable decision ({skipped})")
238
+ out.mkdir(parents=True, exist_ok=True)
239
+ (out / "heldout.jsonl").write_text("\n".join(held) + "\n", encoding="utf-8")
240
+ bodies, decisions = load(out / "heldout.jsonl")
241
+ dev_pairs = [(bodies[d["req"]], d) for d in decisions if d["prim"] != "multi"][: a.eval_max]
242
+ dev = build(dev_pairs)
243
+ print(f"basal-finetune: {len(examples)} training decisions, {len(dev)} held-out scored, {len(held)} held-out lines"
244
+ + (f", skipped {skipped}" if skipped else "") + f"; {a.model} format {fmt} on {device} {str(dtype)[6:]}",
245
+ file=sys.stderr)
246
+
247
+ model = AutoModelForCausalLM.from_pretrained(src, dtype=dtype).to(device)
248
+ cfg = model.config.get_text_config() if hasattr(model.config, "get_text_config") else model.config
249
+ softcap = getattr(cfg, "final_logit_softcapping", None)
250
+ model.eval()
251
+ before = accuracy(model, dev, softcap, device) if dev else None
252
+ if a.grad_ckpt:
253
+ model.gradient_checkpointing_enable()
254
+ model.enable_input_require_grads()
255
+ model = get_peft_model(model, LoraConfig(r=a.rank, lora_alpha=a.alpha, lora_dropout=a.dropout,
256
+ target_modules=lora_targets(model), task_type="CAUSAL_LM"))
257
+ params = [p for p in model.parameters() if p.requires_grad]
258
+ print(f"basal-finetune: LoRA rank {a.rank} on the decoder's linear layers, {sum(p.numel() for p in params) / 1e6:.1f}M "
259
+ "parameters", file=sys.stderr)
260
+ opt = torch.optim.AdamW(params, lr=a.lr, weight_decay=0.0)
261
+ scaler = torch.amp.GradScaler(device) if dtype == torch.float16 and device == "cuda" else None
262
+ steps = math.ceil(len(examples) * a.epochs / a.batch)
263
+ steps = min(steps, a.max_steps) if a.max_steps else steps
264
+ warm = max(1, steps // 20)
265
+ sched = torch.optim.lr_scheduler.LambdaLR( # linear warm-up, then cosine to zero
266
+ opt, lambda s: (s + 1) / warm if s < warm else 0.5 * (1 + math.cos(math.pi * (s - warm) / max(steps - warm, 1))))
267
+ model.train()
268
+ t0, order, pos, run = time.time(), [], 0, []
269
+ for step in range(steps):
270
+ for _ in range(a.batch):
271
+ if pos >= len(order):
272
+ order, pos = random.sample(range(len(examples)), len(examples)), 0
273
+ ids, codes, gold = random.choice(examples[order[pos]]) # the given option order or the reversed one
274
+ pos += 1
275
+ with torch.autocast(device, dtype=dtype, enabled=dtype != torch.float32 and device != "mps"):
276
+ lg = code_logits(model, ids, codes, softcap, device)
277
+ loss = F.cross_entropy(lg[None], torch.tensor([gold], device=device)) / a.batch
278
+ (scaler.scale(loss) if scaler else loss).backward()
279
+ run.append(loss.item() * a.batch)
280
+ if scaler:
281
+ scaler.unscale_(opt)
282
+ torch.nn.utils.clip_grad_norm_(params, 1.0)
283
+ if scaler:
284
+ scaler.step(opt)
285
+ scaler.update()
286
+ else:
287
+ opt.step()
288
+ opt.zero_grad(set_to_none=True)
289
+ sched.step()
290
+ if (step + 1) % max(1, steps // 10) == 0 or step + 1 == steps:
291
+ print(f"basal-finetune: step {step + 1}/{steps} loss {sum(run) / len(run):.4f} "
292
+ f"({time.time() - t0:.0f}s)", file=sys.stderr)
293
+ run = []
294
+ model.eval()
295
+ after = accuracy(model, dev, softcap, device) if dev else None
296
+
297
+ model.save_pretrained(out / "lora")
298
+ merged = model.merge_and_unload()
299
+ copy_side_files(src, out)
300
+ for old in out.glob("*.safetensors"):
301
+ old.unlink()
302
+ merged.save_pretrained(out, safe_serialization=True)
303
+ meta = json.loads((src / "basal.json").read_text(encoding="utf-8"))
304
+ meta.pop("test_metrics", None)
305
+ meta["finetuned"] = {"base": str(a.model), "method": f"LoRA rank {a.rank}", "decisions": len(examples),
306
+ "epochs": a.epochs, "tool": f"basal-finetune {__version__}"}
307
+ (out / "basal.json").write_text(json.dumps(meta, indent=1, ensure_ascii=False) + "\n", encoding="utf-8")
308
+ cal = {"prompt": fmt, "temperature_per_prim": {}, "thresholds": {},
309
+ "source_tag": "basal-finetune defaults, uncalibrated: fit with basal-calibrate on heldout.jsonl"}
310
+ (out / "CALIBRATION.json").write_text(json.dumps(cal, indent=1) + "\n", encoding="utf-8")
311
+ report = {"train_decisions": len(examples), "heldout_lines": len(held), "scored": len(dev), "skipped": skipped,
312
+ "top1_before": before, "top1_after": after, "steps": steps, "seconds": round(time.time() - t0)}
313
+ (out / "finetune.json").write_text(json.dumps(report, indent=1) + "\n", encoding="utf-8")
314
+ print(f"basal-finetune: held-out top-1 {before:.3f} -> {after:.3f}" if dev else "basal-finetune: done", file=sys.stderr)
315
+ print(f"wrote {out} (uncalibrated). Next:\n"
316
+ f" basal-calibrate {out}/heldout.jsonl --model {out} --mode eager --out {out}/CALIBRATION.json\n"
317
+ f" basal-serve --model {out} --mode eager", file=sys.stderr)
318
+
319
+
320
+ if __name__ == "__main__":
321
+ main()