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/navtree.py
ADDED
|
@@ -0,0 +1,397 @@
|
|
|
1
|
+
"""Trees for basal-navigate (experimental, 2.5): documents -> pages -> passages, optionally sections under long
|
|
2
|
+
pages, folders as topics, or topics found by k-means (basal-engine[navigate]: scikit-learn).
|
|
3
|
+
|
|
4
|
+
build(["docs/"], split_long=60) -> the nodes, for basal.navigate.Tree (basal-navigate build writes them)
|
|
5
|
+
cluster(texts, 100, embed=None) -> topic assignments (recursive with max_children)
|
|
6
|
+
|
|
7
|
+
Documents: Markdown (# headings; paragraphs, list items and table rows are passages), HTML (h1-h6 headings; p, li, tr,
|
|
8
|
+
dt, dd, pre, blockquote are passages), plain text (blank-line paragraphs), JSONL ({"id"?, "title"?, "text" |
|
|
9
|
+
"markdown" | "html", "group"?} per line) and PDF (basal-engine[pdf]: a page per PDF page with text, under the outline's
|
|
10
|
+
headings; read within the limits of basal/pdf.py). A page's description is its title and its top headings; a passage keeps its
|
|
11
|
+
heading path. Passages longer than max_chars are split at sentence ends; with min_chars, short neighbours under one
|
|
12
|
+
heading are merged. A cluster is described without generation: its most central titles and its top terms.
|
|
13
|
+
"""
|
|
14
|
+
import html.parser
|
|
15
|
+
import re
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
|
|
18
|
+
from .jsonl import records
|
|
19
|
+
from .tasks import units
|
|
20
|
+
|
|
21
|
+
SUFFIXES = {".md": "markdown", ".markdown": "markdown", ".html": "html", ".htm": "html", ".txt": "text",
|
|
22
|
+
".jsonl": "jsonl", ".pdf": "pdf"}
|
|
23
|
+
PAGE_CHARS = 300
|
|
24
|
+
CENTRAL, TERMS = 6, 6
|
|
25
|
+
DESCRIBE = {"en": ("Pages such as: {titles}. Key terms: {terms}.", "Folder {name}: {titles}", "Document {name}: {titles}"),
|
|
26
|
+
"pl": ("Strony takie jak: {titles}. Kluczowe słowa: {terms}.", "Folder {name}: {titles}",
|
|
27
|
+
"Dokument {name}: {titles}")}
|
|
28
|
+
STOP_PL = ("a", "aby", "albo", "ale", "bez", "być", "był", "była", "było", "były", "bo", "co", "czy", "dla", "do", "gdy",
|
|
29
|
+
"go", "i", "ich", "jak", "jako", "jest", "jego", "jej", "już", "lub", "ma", "może", "na", "nad", "nie", "o",
|
|
30
|
+
"od", "oraz", "po", "pod", "przez", "przy", "się", "są", "ta", "tak", "te", "tego", "też", "to", "tu", "w",
|
|
31
|
+
"we", "z", "za", "ze", "że") # key terms of a topic: not these
|
|
32
|
+
HEADING = re.compile(r"^(#{1,6})\s+(.*?)\s*#*\s*$")
|
|
33
|
+
ITEM = re.compile(r"^\s*(?:[-*+]|\d+[.)])\s+")
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _clean(s):
|
|
37
|
+
return re.sub(r"\s+", " ", s).strip()
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def parse_markdown(text, keep_h1=False):
|
|
41
|
+
"""(title or None, [(heading path, passage text)]): ATX headings; paragraphs, list items and table rows. The first
|
|
42
|
+
level-1 heading is the title, unless keep_h1 (the title is given elsewhere): then it is a heading like the others."""
|
|
43
|
+
title, path, out, buf, fence = None, [], [], [], None
|
|
44
|
+
|
|
45
|
+
def flush():
|
|
46
|
+
t = _clean(" ".join(buf)) if fence is None else "\n".join(buf).strip()
|
|
47
|
+
if t:
|
|
48
|
+
out.append((tuple(h for _, h in path), t))
|
|
49
|
+
buf.clear()
|
|
50
|
+
for line in text.splitlines():
|
|
51
|
+
if fence is not None:
|
|
52
|
+
if line.strip().startswith(fence):
|
|
53
|
+
flush()
|
|
54
|
+
fence = None
|
|
55
|
+
else:
|
|
56
|
+
buf.append(line)
|
|
57
|
+
continue
|
|
58
|
+
if line.strip().startswith(("```", "~~~")):
|
|
59
|
+
flush()
|
|
60
|
+
fence = line.strip()[:3]
|
|
61
|
+
continue
|
|
62
|
+
m = HEADING.match(line)
|
|
63
|
+
if m:
|
|
64
|
+
flush()
|
|
65
|
+
level, h = len(m.group(1)), _clean(m.group(2))
|
|
66
|
+
if level == 1 and title is None and not out and not keep_h1:
|
|
67
|
+
title = h
|
|
68
|
+
continue
|
|
69
|
+
path = [x for x in path if x[0] < level] + [(level, h)]
|
|
70
|
+
elif not line.strip():
|
|
71
|
+
flush()
|
|
72
|
+
elif ITEM.match(line) or line.lstrip().startswith("|"):
|
|
73
|
+
flush()
|
|
74
|
+
if not re.fullmatch(r"\s*\|?[\s:|-]+\|?\s*", line): # a table's separator row
|
|
75
|
+
buf.append(ITEM.sub("", line, count=1).strip().strip("|").replace("|", " | "))
|
|
76
|
+
flush()
|
|
77
|
+
else:
|
|
78
|
+
buf.append(line)
|
|
79
|
+
flush()
|
|
80
|
+
return title, out
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
class _HTML(html.parser.HTMLParser):
|
|
84
|
+
UNITS = {"p", "li", "tr", "dt", "dd", "pre", "blockquote", "caption", "figcaption"}
|
|
85
|
+
SKIP = {"script", "style", "noscript", "template"}
|
|
86
|
+
|
|
87
|
+
def __init__(self, keep_h1=False):
|
|
88
|
+
super().__init__(convert_charrefs=True)
|
|
89
|
+
self.keep_h1 = keep_h1
|
|
90
|
+
self.title, self.path, self.out, self.buf, self.where, self.skip, self.cells = None, [], [], [], None, 0, []
|
|
91
|
+
|
|
92
|
+
def flush(self):
|
|
93
|
+
if self.where == "tr" and self.cells:
|
|
94
|
+
self.cells.append(_clean("".join(self.buf)))
|
|
95
|
+
t = " | ".join(c for c in self.cells if c)
|
|
96
|
+
else:
|
|
97
|
+
t = _clean("".join(self.buf))
|
|
98
|
+
if t and self.where not in (None, "title") and not self.where.startswith("h"):
|
|
99
|
+
self.out.append((tuple(h for _, h in self.path), t))
|
|
100
|
+
elif t and self.where == "title" and self.title is None:
|
|
101
|
+
self.title = t
|
|
102
|
+
elif t and self.where and self.where[0] == "h" and self.where[1:].isdigit():
|
|
103
|
+
level = int(self.where[1:])
|
|
104
|
+
if level == 1 and not self.out and self.title in (None, t) and not self.keep_h1: # the title (or <title>)
|
|
105
|
+
self.title = t
|
|
106
|
+
else:
|
|
107
|
+
self.path = [x for x in self.path if x[0] < level] + [(level, t)]
|
|
108
|
+
self.buf, self.cells = [], []
|
|
109
|
+
|
|
110
|
+
def handle_starttag(self, tag, attrs):
|
|
111
|
+
if tag in self.SKIP:
|
|
112
|
+
self.skip += 1
|
|
113
|
+
elif tag in self.UNITS or tag == "title" or re.fullmatch(r"h[1-6]", tag):
|
|
114
|
+
if self.where != "tr" or tag not in ("p",):
|
|
115
|
+
self.flush()
|
|
116
|
+
self.where = tag
|
|
117
|
+
elif tag in ("td", "th") and self.where == "tr":
|
|
118
|
+
self.cells.append(_clean("".join(self.buf)))
|
|
119
|
+
self.buf = []
|
|
120
|
+
elif tag == "br":
|
|
121
|
+
self.buf.append(" ")
|
|
122
|
+
|
|
123
|
+
def handle_endtag(self, tag):
|
|
124
|
+
if tag in self.SKIP:
|
|
125
|
+
self.skip = max(0, self.skip - 1)
|
|
126
|
+
elif tag == self.where:
|
|
127
|
+
self.flush()
|
|
128
|
+
self.where = None
|
|
129
|
+
|
|
130
|
+
def handle_data(self, data):
|
|
131
|
+
if not self.skip and self.where is not None:
|
|
132
|
+
self.buf.append(data)
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def parse_html(text, keep_h1=False):
|
|
136
|
+
"""(title or None, [(heading path, passage text)]): h1-h6 headings; text outside the unit tags is left out. The
|
|
137
|
+
<title> or the first h1 is the title; with keep_h1 (the title is given elsewhere) every h1 is a heading."""
|
|
138
|
+
p = _HTML(keep_h1)
|
|
139
|
+
p.feed(text)
|
|
140
|
+
p.close()
|
|
141
|
+
p.flush()
|
|
142
|
+
return p.title, p.out
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def parse_text(text, keep_h1=False):
|
|
146
|
+
return None, [((), _clean(b)) for b in re.split(r"\n[ \t]*\n", text) if b.strip()]
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def split_long(text, max_chars):
|
|
150
|
+
"""Pieces of at most about max_chars, cut at sentence ends (a longer sentence is its own piece)."""
|
|
151
|
+
if not max_chars or len(text) <= max_chars:
|
|
152
|
+
return [text]
|
|
153
|
+
out, cur = [], ""
|
|
154
|
+
for a, b in units(text, "sentence"):
|
|
155
|
+
s = text[a:b]
|
|
156
|
+
if cur and len(cur) + 1 + len(s) > max_chars:
|
|
157
|
+
out.append(cur)
|
|
158
|
+
cur = s
|
|
159
|
+
else:
|
|
160
|
+
cur = f"{cur} {s}" if cur else s
|
|
161
|
+
return out + ([cur] if cur else [])
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def passages(blocks, max_chars=2000, min_chars=0):
|
|
165
|
+
"""Blocks -> passages: long ones split, short neighbours under one heading merged (min_chars)."""
|
|
166
|
+
out = []
|
|
167
|
+
for path, t in blocks:
|
|
168
|
+
for piece in split_long(t, max_chars):
|
|
169
|
+
if min_chars and out and out[-1][0] == path and len(out[-1][1]) < min_chars:
|
|
170
|
+
out[-1] = (path, out[-1][1] + "\n" + piece)
|
|
171
|
+
else:
|
|
172
|
+
out.append((path, piece))
|
|
173
|
+
return out
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def pdf_pages(f, name, pdf=None):
|
|
177
|
+
"""(id, title, group, "pdf", {"path", "starts", "text"}) of each page with text of the PDF f (basal/pdf.py: read in
|
|
178
|
+
a child process within its limits, `pdf` overriding them): page n is the page "<name>/p<n>", titled "<file name>
|
|
179
|
+
(p. n)", in the group <name> (a topic of its own with group_dirs); its heading path is the outline's at that page
|
|
180
|
+
(an entry names the page it starts on), "starts" the entries that start there. Pages without text (scanned) and
|
|
181
|
+
those pypdf cannot read are left out, and said on stderr."""
|
|
182
|
+
import sys
|
|
183
|
+
|
|
184
|
+
from .pdf import read
|
|
185
|
+
doc = read(f, **(pdf or {}))
|
|
186
|
+
marks, path, kept = {}, [], 0
|
|
187
|
+
for page, depth, title in doc["outline"]:
|
|
188
|
+
marks.setdefault(page, []).append((depth, _clean(title)))
|
|
189
|
+
for n, text in enumerate(doc["pages"]):
|
|
190
|
+
starts = []
|
|
191
|
+
for depth, title in marks.get(n, ()):
|
|
192
|
+
del path[depth:]
|
|
193
|
+
path.append(title)
|
|
194
|
+
starts.append(title)
|
|
195
|
+
if text.strip():
|
|
196
|
+
kept += 1
|
|
197
|
+
yield f"{name}/p{n + 1}", f"{f.stem} (p. {n + 1})", name, "pdf", \
|
|
198
|
+
{"path": tuple(path), "starts": starts, "text": text}
|
|
199
|
+
empty = len(doc["pages"]) - kept - doc["unreadable"]
|
|
200
|
+
if empty or doc["unreadable"]:
|
|
201
|
+
print(f"basal-navigate build: {f}: " + ", ".join(
|
|
202
|
+
x for x in (f"{empty} of {len(doc['pages'])} pages without text (scanned pages need OCR first)" if empty
|
|
203
|
+
else "", f"{doc['unreadable']} pages pypdf could not read" if doc["unreadable"] else "") if x),
|
|
204
|
+
file=sys.stderr)
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def parse_pdf(page, keep_h1=False):
|
|
208
|
+
"""A PDF page's text -> (None, blocks): blank-line paragraphs (a page with none is one block, split at sentence ends
|
|
209
|
+
later), each under the page's heading path."""
|
|
210
|
+
return None, [(page["path"], _clean(b)) for b in re.split(r"\n[ \t]*\n", page["text"]) if b.strip()]
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def pdf_description(title, page):
|
|
214
|
+
"""What the model reads of a PDF page: its title, the outline headings that start on it (or the one it is under),
|
|
215
|
+
and the start of its text."""
|
|
216
|
+
heads = page["starts"] or list(page["path"][-1:])
|
|
217
|
+
s = title + (": " + "; ".join(heads) if heads else "") + ". " + _clean(page["text"])
|
|
218
|
+
return s if len(s) <= PAGE_CHARS else s[: PAGE_CHARS - 1].rstrip() + "…"
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def documents(inputs, skip=(), pdf=None):
|
|
222
|
+
"""(id, title, group, kind, text) of every document under the inputs (folders: in sorted order); skip: files to
|
|
223
|
+
leave out (the tree being written, which a second build in the same folder would read as documents); a PDF gives
|
|
224
|
+
one document per page (pdf_pages; pdf: its limits)."""
|
|
225
|
+
skip = {Path(x).resolve() for x in skip}
|
|
226
|
+
for inp in inputs:
|
|
227
|
+
root = Path(inp)
|
|
228
|
+
files = sorted(p for p in root.rglob("*") if p.is_file() and p.suffix.lower() in SUFFIXES) \
|
|
229
|
+
if root.is_dir() else [root]
|
|
230
|
+
for f in files:
|
|
231
|
+
if skip and f.resolve() in skip:
|
|
232
|
+
continue
|
|
233
|
+
kind = SUFFIXES.get(f.suffix.lower())
|
|
234
|
+
if kind is None:
|
|
235
|
+
raise ValueError(f"{f}: unknown document type (one of {', '.join(SUFFIXES)})")
|
|
236
|
+
rel = f.relative_to(root) if root.is_dir() else Path(f.name)
|
|
237
|
+
if kind == "jsonl": # a BOM (Notepad) or UTF-16 (PowerShell 5) too; a line not a JSON object: its place
|
|
238
|
+
for n, d in records(f, objects=True):
|
|
239
|
+
k = next((x for x in ("markdown", "html", "text") if isinstance(d.get(x), str)), None)
|
|
240
|
+
if k is None:
|
|
241
|
+
raise ValueError(f"{f}:{n}: a document needs text, markdown or html")
|
|
242
|
+
if d.get("title") is not None and not isinstance(d["title"], str):
|
|
243
|
+
raise ValueError(f"{f}:{n}: title must be a string, got {type(d['title']).__name__}")
|
|
244
|
+
yield str(d.get("id", f"{rel.with_suffix('').as_posix()}:{n}")), d.get("title"), \
|
|
245
|
+
d.get("group"), k, d[k]
|
|
246
|
+
elif kind == "pdf":
|
|
247
|
+
yield from pdf_pages(f, rel.with_suffix("").as_posix(), pdf)
|
|
248
|
+
else:
|
|
249
|
+
yield rel.with_suffix("").as_posix(), None, \
|
|
250
|
+
rel.parent.as_posix() if rel.parent != Path(".") else None, kind, \
|
|
251
|
+
f.read_text(encoding="utf-8", errors="replace")
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def page_description(title, blocks):
|
|
255
|
+
tops = list(dict.fromkeys(p[0] for p, _ in blocks if p))
|
|
256
|
+
s = title + (": " + "; ".join(tops) if tops else "")
|
|
257
|
+
return s if len(s) <= PAGE_CHARS else s[: PAGE_CHARS - 1].rstrip() + "…"
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def _prefix(inp):
|
|
261
|
+
"""The id prefix of an input's documents when two inputs give the same id: the folder as given, or a file's
|
|
262
|
+
folder (so docs/a.md and docs/ give the same ids)."""
|
|
263
|
+
p = Path(inp)
|
|
264
|
+
return (p if p.is_dir() else p.parent).as_posix()
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def build(inputs, split_long=0, group_dirs=False, clusters=0, max_children=0, max_chars=2000, min_chars=0, lang=None,
|
|
268
|
+
embed=None, seed=0, skip=(), pdf=None):
|
|
269
|
+
"""The nodes of a tree (dicts for basal.navigate.Tree) from documents: [topics ->] pages [-> sections] ->
|
|
270
|
+
passages. split_long: a section level under pages with more than this many passages; group_dirs: folders (or
|
|
271
|
+
JSONL "group", or a PDF for its pages) as topics; clusters: k-means topics (cluster(); embed: your embedding
|
|
272
|
+
function); skip: files under the inputs to leave out (the output); pdf: the limits of reading a PDF (basal/pdf.py
|
|
273
|
+
LIMITS). Page ids are paths relative to their input (a PDF's pages: "<path>/p<n>"); when two inputs give the same
|
|
274
|
+
id (docs1/index.md and docs2/index.md), every page id gets its input's folder in front (docs1/index,
|
|
275
|
+
docs2/index)."""
|
|
276
|
+
if group_dirs and clusters:
|
|
277
|
+
raise ValueError("give group_dirs or clusters, not both")
|
|
278
|
+
pages, nodes = [], []
|
|
279
|
+
parse = {"markdown": parse_markdown, "html": parse_html, "text": parse_text, "pdf": parse_pdf}
|
|
280
|
+
for k, inp in enumerate(inputs):
|
|
281
|
+
for doc_id, title, group, kind, text in documents([inp], skip, pdf):
|
|
282
|
+
t, blocks = parse[kind](text, title is not None)
|
|
283
|
+
title = _clean(title or t or doc_id.rsplit("/", 1)[-1])
|
|
284
|
+
ps = passages(blocks, max_chars, min_chars)
|
|
285
|
+
if ps:
|
|
286
|
+
pages.append(dict(id=doc_id, title=title, group=group, passages=ps, input=k, pdf=kind == "pdf",
|
|
287
|
+
text=pdf_description(title, text) if kind == "pdf" else page_description(title, blocks),
|
|
288
|
+
heads=text["path"][:1] if kind == "pdf" else ()))
|
|
289
|
+
if not pages:
|
|
290
|
+
raise ValueError("no passages found in the inputs")
|
|
291
|
+
first = {}
|
|
292
|
+
if any(first.setdefault(p["id"], p["input"]) != p["input"] for p in pages): # the same id from two inputs
|
|
293
|
+
for p in pages:
|
|
294
|
+
p["id"] = f"{_prefix(inputs[p['input']])}/{p['id']}"
|
|
295
|
+
seen = {}
|
|
296
|
+
for p in pages:
|
|
297
|
+
if p["id"] in seen:
|
|
298
|
+
where = sorted({str(inputs[seen[p["id"]]]), str(inputs[p["input"]])})
|
|
299
|
+
raise ValueError(f"two documents give the page id {p['id']!r} ({' and '.join(where)}): x.md and x.txt in "
|
|
300
|
+
"one folder, a JSONL id used twice, or one input given twice")
|
|
301
|
+
seen[p["id"]] = p["input"]
|
|
302
|
+
lang = lang or _majority_lang(p["title"] for p in pages)
|
|
303
|
+
parent = {}
|
|
304
|
+
if group_dirs:
|
|
305
|
+
for g in dict.fromkeys(p["group"] for p in pages if p["group"]):
|
|
306
|
+
members = [p for p in pages if p["group"] == g]
|
|
307
|
+
if all(p["pdf"] for p in members): # a PDF: its top headings, else the start of its first page
|
|
308
|
+
heads = list(dict.fromkeys(h for p in members for h in p["heads"]))
|
|
309
|
+
lead = members[0]["text"].split(". ", 1)[-1]
|
|
310
|
+
text = DESCRIBE[lang][2].format(name=g, titles="; ".join(heads[:CENTRAL]) if heads else lead)
|
|
311
|
+
text = text if len(text) <= PAGE_CHARS else text[: PAGE_CHARS - 1].rstrip() + "…"
|
|
312
|
+
else:
|
|
313
|
+
text = DESCRIBE[lang][1].format(name=g, titles="; ".join(p["title"] for p in members[:CENTRAL]))
|
|
314
|
+
nodes.append({"id": f"dir:{g}", "parent": None, "kind": "topic", "title": g, "text": text})
|
|
315
|
+
parent = {p["id"]: f"dir:{p['group']}" for p in pages if p["group"]}
|
|
316
|
+
elif clusters:
|
|
317
|
+
texts = [p["title"] + ". " + (p["passages"][0][1][:300] if p["passages"] else "") for p in pages]
|
|
318
|
+
for topic in cluster(texts, clusters, embed=embed, max_children=max_children, lang=lang, seed=seed,
|
|
319
|
+
titles=[p["title"] for p in pages]):
|
|
320
|
+
nodes.append({"id": topic["id"], "parent": topic["parent"], "kind": "topic", "text": topic["text"]})
|
|
321
|
+
for m in topic["members"]:
|
|
322
|
+
parent[pages[m]["id"]] = topic["id"]
|
|
323
|
+
for p in pages:
|
|
324
|
+
nodes.append({"id": p["id"], "parent": parent.get(p["id"]), "kind": "page", "title": p["title"],
|
|
325
|
+
"text": p["text"]})
|
|
326
|
+
sections = {}
|
|
327
|
+
if split_long and len(p["passages"]) > split_long:
|
|
328
|
+
for path, _ in p["passages"]:
|
|
329
|
+
if path and path[0] not in sections:
|
|
330
|
+
sections[path[0]] = f"{p['id']}#s{len(sections) + 1}"
|
|
331
|
+
subs = list(dict.fromkeys(q[1] for q, _ in p["passages"] if len(q) > 1 and q[0] == path[0]))
|
|
332
|
+
nodes.append({"id": sections[path[0]], "parent": p["id"], "kind": "section", "title": path[0],
|
|
333
|
+
"text": path[0] + (": " + "; ".join(subs) if subs else "")[:PAGE_CHARS]})
|
|
334
|
+
for n, (path, t) in enumerate(p["passages"], 1):
|
|
335
|
+
x = {"id": f"{p['id']}#{n}", "parent": sections.get(path[0], p["id"]) if path else p["id"],
|
|
336
|
+
"kind": "passage", "text": t}
|
|
337
|
+
if path:
|
|
338
|
+
x["path"] = " > ".join(path)
|
|
339
|
+
nodes.append(x)
|
|
340
|
+
return nodes
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
def _majority_lang(titles):
|
|
344
|
+
from .prompt import lang_of
|
|
345
|
+
titles = list(titles)
|
|
346
|
+
return "pl" if sum(lang_of(t) == "pl" for t in titles) * 2 > len(titles) else "en"
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
def cluster(texts, k, embed=None, max_children=0, lang="en", seed=0, titles=None):
|
|
350
|
+
"""Topics over texts by k-means: [{"id", "parent", "text", "members"}] (members: indices of texts, only on the
|
|
351
|
+
deepest topics). Vectors: embed(texts) when given (rows are normalised), else TF-IDF reduced by SVD. A topic of
|
|
352
|
+
more than max_children texts is split again (recursive k-means), into ceil(n / max_children) or k topics, the
|
|
353
|
+
smaller. Described by its most central titles and top TF-IDF terms."""
|
|
354
|
+
try:
|
|
355
|
+
import numpy as np
|
|
356
|
+
from sklearn.cluster import KMeans, MiniBatchKMeans
|
|
357
|
+
from sklearn.decomposition import TruncatedSVD
|
|
358
|
+
from sklearn.feature_extraction.text import TfidfVectorizer
|
|
359
|
+
from sklearn.preprocessing import normalize
|
|
360
|
+
except ImportError as e:
|
|
361
|
+
raise SystemExit("topics by k-means need scikit-learn: pip install 'basal-engine[navigate]'") from e
|
|
362
|
+
titles = titles or texts
|
|
363
|
+
tfidf = TfidfVectorizer(sublinear_tf=True, max_df=0.5, min_df=1, max_features=1 << 18,
|
|
364
|
+
token_pattern=r"(?u)\b\w\w+\b", stop_words="english" if lang == "en" else list(STOP_PL))
|
|
365
|
+
T = tfidf.fit_transform(texts)
|
|
366
|
+
vocab = tfidf.get_feature_names_out()
|
|
367
|
+
if embed is not None:
|
|
368
|
+
X = normalize(np.asarray(embed(texts), dtype=np.float32))
|
|
369
|
+
else:
|
|
370
|
+
dims = min(256, T.shape[1] - 1, T.shape[0] - 1)
|
|
371
|
+
X = normalize(TruncatedSVD(dims, random_state=seed).fit_transform(T)) if dims >= 2 else T.toarray()
|
|
372
|
+
out = []
|
|
373
|
+
|
|
374
|
+
def split(idx, n, parent, prefix):
|
|
375
|
+
n = max(1, min(n, len(idx)))
|
|
376
|
+
km = (MiniBatchKMeans(n, random_state=seed, n_init=3, batch_size=4096) if len(idx) > 20000 else
|
|
377
|
+
KMeans(n, random_state=seed, n_init=3)).fit(X[idx])
|
|
378
|
+
for c in range(n):
|
|
379
|
+
members = idx[km.labels_ == c]
|
|
380
|
+
if not len(members):
|
|
381
|
+
continue
|
|
382
|
+
tid = f"{prefix}{len([o for o in out if o['parent'] == parent]) + 1}"
|
|
383
|
+
centre = km.cluster_centers_[c]
|
|
384
|
+
near = members[np.argsort(-(X[members] @ centre))][:CENTRAL]
|
|
385
|
+
w = np.asarray(T[members].mean(axis=0)).ravel()
|
|
386
|
+
terms = [vocab[j] for j in np.argsort(-w)[:TERMS] if w[j] > 0]
|
|
387
|
+
topic = {"id": tid, "parent": parent, "text": DESCRIBE[lang][0].format(
|
|
388
|
+
titles="; ".join(titles[j] for j in near), terms=", ".join(terms))}
|
|
389
|
+
out.append(topic)
|
|
390
|
+
if max_children and len(members) > max_children and len(members) < len(idx):
|
|
391
|
+
split(members, min(k, -(-len(members) // max_children)), tid, tid + ".")
|
|
392
|
+
else:
|
|
393
|
+
topic["members"] = [int(j) for j in members]
|
|
394
|
+
split(np.arange(len(texts)), k, None, "topic:")
|
|
395
|
+
for t in out:
|
|
396
|
+
t.setdefault("members", [])
|
|
397
|
+
return out
|
basal/nvfp4.py
ADDED
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
"""NVFP4 linears for the CUDA graph engine (--mode nvfp4; basal-omni, Gemma 4; Blackwell): e2m1 values, one e4m3
|
|
2
|
+
scale per 16 consecutive input features, one fp32 global scale per tensor; the GEMM is torch._scaled_mm on cuBLAS's
|
|
3
|
+
block-scaled FP4 kernel (sm_100 / sm_120), the scales in its 128 x 4 tile swizzle.
|
|
4
|
+
|
|
5
|
+
Weights: the global scale is amax / (6 * 448); each block of 16 takes the scale (of 8 candidates, amax / 6 times
|
|
6
|
+
1.00, 0.96, ..., 0.72, rounded to e4m3) with the smallest squared error. Activations: a fixed global scale per linear
|
|
7
|
+
(calibrated: 2 x the largest input |x| over calibration prompts in bf16, / (6 * 448)), the block scales per token
|
|
8
|
+
from the block's own amax, so a row's codes do not depend on the other rows. Values round to the nearest e2m1 (ties
|
|
9
|
+
to even).
|
|
10
|
+
|
|
11
|
+
quantize(w) weight [N, K] -> (codes [N, K / 2] uint8, swizzled e4m3 scales, global scale)
|
|
12
|
+
act_quant(x, inv_g) activations [M, K] -> (codes [Mp, K / 2], swizzled scales); Mp = M rounded up to 128
|
|
13
|
+
linear(x, p) x [..., K] -> [..., N] through (codes, scales, alpha, inv_g, bias)
|
|
14
|
+
NVFP4Linear a linear layer holding them; lean.linear runs its parameters in compiled layers
|
|
15
|
+
"""
|
|
16
|
+
import torch
|
|
17
|
+
|
|
18
|
+
BLOCK = 16
|
|
19
|
+
E2M1 = (0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0) # the e2m1 magnitude of each code 0-7 (code bit 3: the sign)
|
|
20
|
+
# rounding to the nearest e2m1 value: the midpoints between neighbouring codes, a value at a midpoint to the even code
|
|
21
|
+
# (ties to even): from code k to k + 1 above the midpoint (>) when k is even, at or above it (>=) when k is odd
|
|
22
|
+
CUTS = tuple(((a + b) / 2, k % 2 == 1) for k, (a, b) in enumerate(zip(E2M1, E2M1[1:])))
|
|
23
|
+
FP4_MAX, E4M3_MAX = E2M1[-1], 448.0
|
|
24
|
+
E4M3 = torch.float8_e4m3fn
|
|
25
|
+
MARGIN = 2.0 # activations: the global scale covers 2 x the calibrated amax (values past it are clipped)
|
|
26
|
+
CANDIDATES = tuple(1.0 - 0.04 * j for j in range(8))
|
|
27
|
+
_KERNEL = []
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def fits(lin):
|
|
31
|
+
"""True for a weight this module can hold: K a multiple of 64 (four scale blocks), N a multiple of 16."""
|
|
32
|
+
n, k = lin.weight.shape
|
|
33
|
+
return k % 64 == 0 and n % 16 == 0
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _codes(u):
|
|
37
|
+
"""fp32 values in units of their block scale -> e2m1 codes (sign bit 8), round to nearest, ties to even (CUTS;
|
|
38
|
+
the activation kernel in _build compares with the same cuts)."""
|
|
39
|
+
a = u.abs()
|
|
40
|
+
c = sum(((a >= t) if odd else (a > t)).int() for t, odd in CUTS)
|
|
41
|
+
return (c | ((u < 0).int() << 3)).to(torch.uint8)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _values(c):
|
|
45
|
+
v = torch.tensor(E2M1, device=c.device)[(c & 7).long()]
|
|
46
|
+
return torch.where(c >= 8, -v, v)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def swizzle(s):
|
|
50
|
+
"""[rows, K / 16] e4m3 scales -> cuBLAS's 128 x 4 tiles, flattened (rows padded to 128, columns to 4 with 0)."""
|
|
51
|
+
r, c = s.shape
|
|
52
|
+
R, C = -(-r // 128), -(-c // 4)
|
|
53
|
+
p = torch.zeros(R * 128, C * 4, dtype=torch.uint8, device=s.device)
|
|
54
|
+
p[:r, :c] = s.view(torch.uint8)
|
|
55
|
+
b = p.view(R, 128, C, 4).permute(0, 2, 1, 3)
|
|
56
|
+
return b.reshape(-1, 4, 32, 4).transpose(1, 2).reshape(-1).view(E4M3)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def unswizzle(f, rows, cols):
|
|
60
|
+
"""The inverse of swizzle -> [rows, cols] e4m3."""
|
|
61
|
+
R, C = -(-rows // 128), -(-cols // 4)
|
|
62
|
+
b = f.view(torch.uint8).view(R * C, 32, 4, 4).transpose(1, 2).reshape(R, C, 128, 4).permute(0, 2, 1, 3)
|
|
63
|
+
return b.reshape(R * 128, C * 4)[:rows, :cols].contiguous().view(E4M3)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def pack(c):
|
|
67
|
+
"""[M, K] codes -> [M, K / 2] bytes (even feature in the low nibble)."""
|
|
68
|
+
return c[:, 0::2] | (c[:, 1::2] << 4)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def unpack(p):
|
|
72
|
+
return torch.stack([p & 15, p >> 4], -1).view(p.shape[0], -1)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
@torch.no_grad()
|
|
76
|
+
def quantize(w, rows=4096):
|
|
77
|
+
"""[N, K] -> (codes [N, K / 2] uint8, swizzled e4m3 block scales, fp32 global scale [1]), in parts of rows."""
|
|
78
|
+
N, K = w.shape
|
|
79
|
+
g = (w.float().abs().amax() / (FP4_MAX * E4M3_MAX)).clamp(min=1e-12)
|
|
80
|
+
codes, scales = [], []
|
|
81
|
+
for o in range(0, N, rows):
|
|
82
|
+
b = w[o: o + rows].float().view(-1, K // BLOCK, BLOCK) / g
|
|
83
|
+
amax = b.abs().amax(-1, keepdim=True)
|
|
84
|
+
best = err = None
|
|
85
|
+
for f in CANDIDATES:
|
|
86
|
+
s = (amax * f / FP4_MAX).clamp(max=E4M3_MAX).to(E4M3).float()
|
|
87
|
+
u = torch.where(s > 0, b / s, torch.zeros_like(b))
|
|
88
|
+
c = _codes(u)
|
|
89
|
+
e = ((_values(c) * s - b) ** 2).sum(-1, keepdim=True)
|
|
90
|
+
if best is None:
|
|
91
|
+
best, err, sc = c, e, s
|
|
92
|
+
else:
|
|
93
|
+
m = e < err
|
|
94
|
+
best, err, sc = torch.where(m, c, best), torch.where(m, e, err), torch.where(m, s, sc)
|
|
95
|
+
codes.append(pack(best.view(best.shape[0], K)))
|
|
96
|
+
scales.append(sc[..., 0].to(E4M3))
|
|
97
|
+
return torch.cat(codes), swizzle(torch.cat(scales)), g.reshape(1)
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def dequantize(codes, scales, g, N, K):
|
|
101
|
+
"""The weight's values as fp32 [N, K] (tests, the reference maths)."""
|
|
102
|
+
s = unswizzle(scales, N, K // BLOCK).float()
|
|
103
|
+
return (_values(unpack(codes)).view(N, K // BLOCK, BLOCK) * s[..., None]).view(N, K) * g
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _act_ops(x, inv_g):
|
|
107
|
+
"""act_quant's maths in torch ops (CPU, tests): -> (codes [M, K / 2], e4m3 scales [M, K / 16], unswizzled)."""
|
|
108
|
+
M, K = x.shape
|
|
109
|
+
b = x.float().view(M, K // BLOCK, BLOCK) * inv_g
|
|
110
|
+
s = (b.abs().amax(-1, keepdim=True) / FP4_MAX).clamp(max=E4M3_MAX).to(E4M3).float()
|
|
111
|
+
u = torch.where(s > 0, b / s, torch.zeros_like(b))
|
|
112
|
+
return pack(_codes(u).view(M, K)), s[..., 0].to(E4M3)
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _build():
|
|
116
|
+
"""The activation quantiser: one Triton program per 128 rows x 64 features writes the packed codes and the four
|
|
117
|
+
block scales of each row straight into cuBLAS's swizzle."""
|
|
118
|
+
import triton
|
|
119
|
+
import triton.language as tl
|
|
120
|
+
|
|
121
|
+
@triton.jit(do_not_specialize=["M"])
|
|
122
|
+
def kernel(x, q, s, inv_g, M, K, C4, BM: tl.constexpr):
|
|
123
|
+
pm, pk = tl.program_id(0), tl.program_id(1)
|
|
124
|
+
rm = pm * BM + tl.arange(0, BM)
|
|
125
|
+
rk = pk * 64 + tl.arange(0, 64)
|
|
126
|
+
v = tl.load(x + rm.to(tl.int64)[:, None] * K + rk[None, :], mask=(rm < M)[:, None], other=0.0).to(tl.float32)
|
|
127
|
+
v = tl.reshape(v * tl.load(inv_g), (BM, 4, 16)) # IEEE division below (Triton's / is approximate)
|
|
128
|
+
amax = tl.max(tl.abs(v), 2)
|
|
129
|
+
sc = tl.minimum(tl.math.div_rn(amax, 6.0), 448.0).to(tl.float8e4nv)
|
|
130
|
+
scf = sc.to(tl.float32)
|
|
131
|
+
u = tl.where(scf[:, :, None] > 0, tl.math.div_rn(v, tl.broadcast_to(scf[:, :, None], (BM, 4, 16))), 0.0)
|
|
132
|
+
a = tl.abs(u)
|
|
133
|
+
# (CUTS, written out: a Triton kernel cannot loop over a Python table; test_nvfp4 checks them against it)
|
|
134
|
+
c = ((a > 0.25).to(tl.int32) + (a >= 0.75).to(tl.int32) + (a > 1.25).to(tl.int32) + (a >= 1.75).to(tl.int32)
|
|
135
|
+
+ (a > 2.5).to(tl.int32) + (a >= 3.5).to(tl.int32) + (a > 5.0).to(tl.int32))
|
|
136
|
+
c = c | ((u < 0).to(tl.int32) << 3)
|
|
137
|
+
lo, hi = tl.split(tl.reshape(c, (BM, 32, 2)))
|
|
138
|
+
byte = (lo | (hi << 4)).to(tl.uint8)
|
|
139
|
+
tl.store(q + rm.to(tl.int64)[:, None] * (K // 2) + pk * 32 + tl.arange(0, 32)[None, :], byte)
|
|
140
|
+
# scale (row r, block 4 pk + j): tile (r // 128, pk) of 512 bytes, at (r % 32) * 16 + (r % 128 // 32) * 4 + j
|
|
141
|
+
r = rm % 128
|
|
142
|
+
off = ((rm // 128).to(tl.int64) * C4 + pk) * 512 + (r % 32) * 16 + (r // 32) * 4
|
|
143
|
+
tl.store(s + off[:, None] + tl.arange(0, 4)[None, :], sc.to(tl.uint8, bitcast=True))
|
|
144
|
+
|
|
145
|
+
return kernel
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def act_quant(x, inv_g):
|
|
149
|
+
"""[M, K] bf16 -> (codes [Mp, K / 2] uint8, swizzled scales uint8 [Mp * K / 16]), Mp = M rounded up to 128; rows
|
|
150
|
+
past M are zeros."""
|
|
151
|
+
build()
|
|
152
|
+
M, K = x.shape
|
|
153
|
+
Mp = (M + 127) // 128 * 128
|
|
154
|
+
q = torch.empty((Mp, K // 2), dtype=torch.uint8, device=x.device)
|
|
155
|
+
s = torch.empty((Mp * (K // BLOCK),), dtype=torch.uint8, device=x.device)
|
|
156
|
+
if M:
|
|
157
|
+
_KERNEL[0][(Mp // 128, K // 64)](x, q, s, inv_g, M, K, K // 64, BM=128)
|
|
158
|
+
return q, s
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def build():
|
|
162
|
+
"""The Triton kernel, built once (before any layer is compiled)."""
|
|
163
|
+
if torch.cuda.is_available() and not _KERNEL:
|
|
164
|
+
_KERNEL.append(_build())
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def _mm(q, s, w, ws, alpha, m, dtype):
|
|
168
|
+
"""cuBLAS's block-scaled FP4 GEMM, the global scales (alpha) applied in its fp32 epilogue (F.scaled_mm, torch 2.10+;
|
|
169
|
+
the same bits as torch._scaled_mm in fp32 times alpha and 1.1-2.1x faster on sm_120, 24 Oct)."""
|
|
170
|
+
a, b = q.view(torch.float4_e2m1fn_x2), w.view(torch.float4_e2m1fn_x2).t()
|
|
171
|
+
F = torch.nn.functional
|
|
172
|
+
if hasattr(F, "scaled_mm"):
|
|
173
|
+
st, sw = F.ScalingType, F.SwizzleType
|
|
174
|
+
y = F.scaled_mm(a, b, [s.view(E4M3), alpha], [st.BlockWise1x16, st.TensorWise],
|
|
175
|
+
[ws.view(E4M3), torch.ones_like(alpha)], [st.BlockWise1x16, st.TensorWise],
|
|
176
|
+
swizzle_a=[sw.SWIZZLE_32_4_4, sw.NO_SWIZZLE], swizzle_b=[sw.SWIZZLE_32_4_4, sw.NO_SWIZZLE],
|
|
177
|
+
output_dtype=dtype)
|
|
178
|
+
return y[:m].clone() if m < y.shape[0] else y
|
|
179
|
+
y = torch._scaled_mm(a, b, s.view(E4M3), ws.view(E4M3), out_dtype=torch.float32)
|
|
180
|
+
return (y[:m] * alpha).to(dtype)
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
@torch.library.custom_op("basal::nvfp4_linear", mutates_args=())
|
|
184
|
+
def _linear_cuda(x: torch.Tensor, w: torch.Tensor, ws: torch.Tensor, alpha: torch.Tensor,
|
|
185
|
+
inv_g: torch.Tensor) -> torch.Tensor:
|
|
186
|
+
"""x [M, K] bf16 -> [M, N]: the quantiser and the GEMM as one opaque op (compiled layers keep it whole; a CUDA
|
|
187
|
+
graph captures its two kernels)."""
|
|
188
|
+
q, s = act_quant(x, inv_g)
|
|
189
|
+
return _mm(q, s, w, ws, alpha, x.shape[0], x.dtype)
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
@_linear_cuda.register_fake
|
|
193
|
+
def _(x, w, ws, alpha, inv_g):
|
|
194
|
+
return x.new_empty((x.shape[0], w.shape[0]))
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def linear(x, w, ws, alpha, inv_g, bias=None):
|
|
198
|
+
"""x [..., K] (bf16) through an NVFP4 weight (codes w [N, K / 2], swizzled scales ws, alpha = the two global
|
|
199
|
+
scales' product, inv_g = 1 / the input's global scale) -> [..., N] in x's dtype."""
|
|
200
|
+
shape = x.shape
|
|
201
|
+
x2 = x.reshape(-1, shape[-1])
|
|
202
|
+
N = w.shape[0]
|
|
203
|
+
if x.is_cuda:
|
|
204
|
+
y = torch.ops.basal.nvfp4_linear(x2.contiguous(), w, ws, alpha, inv_g)
|
|
205
|
+
else: # the reference maths: both operands dequantised, fp32 products
|
|
206
|
+
K = x2.shape[1]
|
|
207
|
+
qc, sc = _act_ops(x2, inv_g)
|
|
208
|
+
xd = (_values(unpack(qc)).view(-1, K // BLOCK, BLOCK) * sc.float()[..., None]).view(-1, K)
|
|
209
|
+
wd = _values(unpack(w)).view(N, K // BLOCK, BLOCK) * unswizzle(ws, N, K // BLOCK).float()[..., None]
|
|
210
|
+
y = ((xd @ wd.view(N, K).t()) * alpha).to(x.dtype)
|
|
211
|
+
if bias is not None:
|
|
212
|
+
y = y + bias.to(y.dtype)
|
|
213
|
+
return y.reshape(*shape[:-1], N)
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
class NVFP4Linear(torch.nn.Module):
|
|
217
|
+
"""A linear layer with an NVFP4 weight (quantize) and a fixed input global scale; part(o, n) is a view of output
|
|
218
|
+
rows o..o + n (multiples of 128: whole scale tiles), so the projections of a merged weight stay modules."""
|
|
219
|
+
|
|
220
|
+
def __init__(self, weight, scale, wg, xg, bias=None, out_features=None):
|
|
221
|
+
super().__init__()
|
|
222
|
+
self.weight = torch.nn.Parameter(weight, requires_grad=False)
|
|
223
|
+
self.weight_scale = torch.nn.Parameter(scale, requires_grad=False)
|
|
224
|
+
self.alpha = torch.nn.Parameter((wg * xg).float().reshape(1), requires_grad=False)
|
|
225
|
+
self.inv_g = torch.nn.Parameter((1.0 / xg).float().reshape(1), requires_grad=False)
|
|
226
|
+
self.wg, self.xg = wg, xg
|
|
227
|
+
self.bias = bias
|
|
228
|
+
self.out_features, self.in_features = weight.shape[0], weight.shape[1] * 2
|
|
229
|
+
|
|
230
|
+
@classmethod
|
|
231
|
+
def of(cls, lin, amax):
|
|
232
|
+
"""The NVFP4 version of a torch.nn.Linear whose inputs reached |x| <= amax in calibration (bf16 not kept)."""
|
|
233
|
+
q, s, wg = quantize(lin.weight.detach())
|
|
234
|
+
xg = torch.tensor([max(float(amax), 1e-6) * MARGIN / (FP4_MAX * E4M3_MAX)], device=q.device)
|
|
235
|
+
return cls(q, s, wg, xg, None if lin.bias is None else lin.bias.detach())
|
|
236
|
+
|
|
237
|
+
def part(self, o, n):
|
|
238
|
+
assert o % 128 == 0 and n % 128 == 0, "parts of whole scale tiles"
|
|
239
|
+
cols = self.in_features // BLOCK
|
|
240
|
+
C = -(-cols // 4) * 4
|
|
241
|
+
return NVFP4Linear(self.weight[o: o + n], self.weight_scale[o * C: (o + n) * C], self.wg, self.xg,
|
|
242
|
+
None if self.bias is None else self.bias[o: o + n])
|
|
243
|
+
|
|
244
|
+
def forward(self, x):
|
|
245
|
+
return linear(x, self.weight, self.weight_scale, self.alpha, self.inv_g, self.bias)
|