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/fold.py
ADDED
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
"""basal-fold-temperature: fold a calibrated temperature into a checkpoint, so engines that read the model's logits as
|
|
2
|
+
they are (vLLM, SGLang, llama.cpp / GGUF, transformers) return probabilities calibrated at that temperature.
|
|
3
|
+
|
|
4
|
+
basal reads a question from the logits of its option codes: z = c tanh(x / c) with x = W h (the head W over the final
|
|
5
|
+
norm's output h, c the final logit soft cap; z = x without one), and calibrates p = softmax(z / T). Scaling the final
|
|
6
|
+
norm's scale by 1 / T scales h and x by 1 / T, and a soft cap of c / T then gives (c / T) tanh((x / T) / (c / T)) =
|
|
7
|
+
z / T: the folded model's code logits are the calibrated ones, exactly up to the rounding of the norm weight in its
|
|
8
|
+
dtype. The norm's scale is its weight w in Llama and Gemma 4 (w / T is written) and 1 + w in Qwen3.5 ((1 + w) / T - 1
|
|
9
|
+
is written); other decoders are refused (NORMS). One temperature is folded (a model has one head): by default the choice type's (its 2-10 option bucket where the
|
|
10
|
+
calibration has one), or --type / --bucket / --temperature. The folded model's CALIBRATION files keep every other
|
|
11
|
+
temperature as its ratio to the folded one, so basal-serve serves the same probabilities from the folded model with one
|
|
12
|
+
option order (with two orders the mean of the two orders' probabilities is taken after the folded temperature instead of
|
|
13
|
+
before the type's). Thresholds carry forward for a known single order. Other policies need recertification.
|
|
14
|
+
|
|
15
|
+
basal-fold-temperature --model Remek/basal-omni-1.0-mini --out mini-folded
|
|
16
|
+
basal-fold-temperature --model ./model --out ./model-T --type noul
|
|
17
|
+
"""
|
|
18
|
+
import argparse
|
|
19
|
+
import json
|
|
20
|
+
import math
|
|
21
|
+
import shutil
|
|
22
|
+
from pathlib import Path
|
|
23
|
+
|
|
24
|
+
CALIBRATIONS = "CALIBRATION*.json"
|
|
25
|
+
# the final norm's scale per decoder (config.json model_type, a multimodal config's text_config): "scale" multiplies by
|
|
26
|
+
# the weight (transformers' LlamaRMSNorm, Gemma4RMSNorm), "offset" by 1 + weight (Qwen3_5RMSNorm). A decoder not here
|
|
27
|
+
# is refused rather than folded by a guess: dividing an offset norm's weight by T gives other probabilities
|
|
28
|
+
NORMS = {"llama": "scale", "gemma4": "scale", "gemma4_text": "scale", "qwen3_5": "offset", "qwen3_5_text": "offset"}
|
|
29
|
+
# the question types basal-serve asks a temperature for (server.temperature; act and tool questions take their base
|
|
30
|
+
# type, multi noul's): a type a calibration leaves out takes 1, which a folded file must give as 1 / T
|
|
31
|
+
TEMPERATURE_TYPES = ("choice", "noul", "score")
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def norm_name(names):
|
|
35
|
+
"""The final norm's tensor among a checkpoint's tensor names: the one norm weight outside the decoder layers and the
|
|
36
|
+
vision / audio towers (Gemma 4: model.language_model.norm.weight; Llama: model.norm.weight)."""
|
|
37
|
+
skip = ("layers.", "vision", "audio", "embed", "lm_head")
|
|
38
|
+
cands = [n for n in names if (n == "norm.weight" or n.endswith(".norm.weight")) and not any(s in n for s in skip)]
|
|
39
|
+
if len(cands) != 1:
|
|
40
|
+
raise SystemExit(f"cannot find the final norm: {len(cands)} candidates ({', '.join(sorted(cands)[:5])})")
|
|
41
|
+
return cands[0]
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def text_config(cfg):
|
|
45
|
+
"""The decoder's part of config.json (Gemma 4 multimodal: text_config) as a dict that is part of cfg."""
|
|
46
|
+
return cfg["text_config"] if isinstance(cfg.get("text_config"), dict) else cfg
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def norm_kind(cfg):
|
|
50
|
+
"""How the decoder's final norm applies its weight (NORMS: "scale" or "offset"); SystemExit for a decoder whose
|
|
51
|
+
norm folding does not know."""
|
|
52
|
+
types = [text_config(cfg).get("model_type"), cfg.get("model_type")]
|
|
53
|
+
kind = next((NORMS[t] for t in types if t in NORMS), None)
|
|
54
|
+
if kind is None:
|
|
55
|
+
raise SystemExit(f"basal-fold-temperature: config.json model_type {types[0] or types[1]!r}: folding is "
|
|
56
|
+
f"implemented for Llama, Gemma 4 and Qwen3.5 checkpoints ({', '.join(sorted(NORMS))}), whose "
|
|
57
|
+
"final norms it knows; another decoder's norm may apply its weight otherwise")
|
|
58
|
+
return kind
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def folded_norm(w, T, kind):
|
|
62
|
+
"""The final norm's weight w with T folded in, in w's dtype (computed in float64): the norm's scale divided by T,
|
|
63
|
+
so w / T for a "scale" norm and (1 + w) / T - 1 for an "offset" one (whose scale is 1 + w)."""
|
|
64
|
+
import torch
|
|
65
|
+
w64 = w.to(torch.float64)
|
|
66
|
+
return (w64 / T if kind == "scale" else (1 + w64) / T - 1).to(w.dtype)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def pick(cal, q_type="choice", bucket=None):
|
|
70
|
+
"""The temperature to fold: the type's bucket temperature (default "2-10" where there is one), else its type
|
|
71
|
+
temperature, else 1."""
|
|
72
|
+
per_bucket = (cal.get("temperature_per_bucket") or {}).get(q_type) or {}
|
|
73
|
+
b = bucket or ("2-10" if "2-10" in per_bucket else None)
|
|
74
|
+
if b is not None and b in per_bucket:
|
|
75
|
+
return float(per_bucket[b])
|
|
76
|
+
if bucket is not None:
|
|
77
|
+
raise SystemExit(f"--bucket {bucket}: the calibration has no {q_type} temperature for it")
|
|
78
|
+
return float((cal.get("temperature_per_prim") or {}).get(q_type, 1.0))
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def rescaled(cal, T, out_dir=None, content=None, weights=None):
|
|
82
|
+
"""A calibration file for the folded model: every temperature divided by T (the folded part), the rest kept. A
|
|
83
|
+
type without a temperature took 1, so it gets 1 / T, named in temperature_defaulted (a temperature nobody fitted,
|
|
84
|
+
which server.fitted_temperatures does not count). A basal-calibrate file names the folded model in fitted_on: its
|
|
85
|
+
folder, and `content` / `weights`, the folded folder's own model_content and model_weights (server.model_content_id,
|
|
86
|
+
model_weights_id), so the file holds for the folded files (--strict-calibration); the source's identity (revision,
|
|
87
|
+
model_files, model_content, model_weights) is kept apart as folded_from_identity, its name as folded_from."""
|
|
88
|
+
out = json.loads(json.dumps(cal))
|
|
89
|
+
fitted = cal.get("fitted_on")
|
|
90
|
+
if isinstance(fitted, dict) and fitted.get("model") and out_dir is not None:
|
|
91
|
+
origin = fitted["model"] + (f"@{fitted['revision'][:12]}" if fitted.get("revision") else "")
|
|
92
|
+
ids = ("revision", "model_files", "model_content", "model_weights")
|
|
93
|
+
fo = dict({k: v for k, v in fitted.items() if k not in ids}, model=Path(out_dir).resolve().name,
|
|
94
|
+
folded_from=f"{origin}/T={T:g}")
|
|
95
|
+
source = {k: fitted[k] for k in ids if fitted.get(k)}
|
|
96
|
+
if source:
|
|
97
|
+
fo["folded_from_identity"] = source
|
|
98
|
+
if content:
|
|
99
|
+
fo["model_content"] = content
|
|
100
|
+
if weights:
|
|
101
|
+
fo["model_weights"] = weights
|
|
102
|
+
out["fitted_on"] = fo
|
|
103
|
+
prim = dict(cal.get("temperature_per_prim") or {})
|
|
104
|
+
defaulted = sorted(set(cal.get("temperature_defaulted") or ()) | {t for t in TEMPERATURE_TYPES if t not in prim})
|
|
105
|
+
prim.update({t: 1.0 for t in TEMPERATURE_TYPES if t not in prim})
|
|
106
|
+
out["temperature_per_prim"] = {t: float(v) / T for t, v in prim.items()}
|
|
107
|
+
if defaulted:
|
|
108
|
+
out["temperature_defaulted"] = defaulted
|
|
109
|
+
out["temperature_per_bucket"] = {t: {b: float(v) / T for b, v in bs.items()}
|
|
110
|
+
for t, bs in (cal.get("temperature_per_bucket") or {}).items()}
|
|
111
|
+
from .server import UNVALIDATED_OUT, calibration_orders
|
|
112
|
+
if T != 1.0 and calibration_orders(cal) != 1:
|
|
113
|
+
removed = [key for key in UNVALIDATED_OUT if key in out]
|
|
114
|
+
for key in removed:
|
|
115
|
+
del out[key]
|
|
116
|
+
if removed:
|
|
117
|
+
out["recertification_required"] = {"reason": "temperature folded before averaging option orders",
|
|
118
|
+
"orders": calibration_orders(cal), "removed": removed}
|
|
119
|
+
out["temperature_folded"] = float(T) * float(cal.get("temperature_folded", 1.0))
|
|
120
|
+
return out
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def fold_checkpoint(md, out, T):
|
|
124
|
+
"""Write checkpoint md with temperature T folded in to `out` (a new or empty directory): the final norm's scale
|
|
125
|
+
divided by T (folded_norm, in the weight's dtype) in the safetensors file that holds it, every other tensor and file
|
|
126
|
+
as it is, config.json with the soft cap divided by T, basal.json with "temperature_folded". A decoder whose norm
|
|
127
|
+
folding does not know (norm_kind) is refused before anything is written. -> (norm tensor name, soft cap before or
|
|
128
|
+
None, norm kind)."""
|
|
129
|
+
from safetensors import safe_open
|
|
130
|
+
from safetensors.torch import save_file
|
|
131
|
+
md, out = Path(md), Path(out)
|
|
132
|
+
cfg = json.loads((md / "config.json").read_text(encoding="utf-8"))
|
|
133
|
+
kind = norm_kind(cfg)
|
|
134
|
+
files = sorted(md.glob("*.safetensors"))
|
|
135
|
+
where = {}
|
|
136
|
+
for f in files:
|
|
137
|
+
with safe_open(f, "pt") as st:
|
|
138
|
+
for name in st.keys():
|
|
139
|
+
where[name] = f
|
|
140
|
+
name = norm_name(list(where))
|
|
141
|
+
out.mkdir(parents=True, exist_ok=True)
|
|
142
|
+
for f in files:
|
|
143
|
+
if f != where[name]:
|
|
144
|
+
shutil.copyfile(f, out / f.name)
|
|
145
|
+
continue
|
|
146
|
+
with safe_open(f, "pt") as st:
|
|
147
|
+
meta = st.metadata()
|
|
148
|
+
tensors = {n: st.get_tensor(n) for n in st.keys()}
|
|
149
|
+
tensors[name] = folded_norm(tensors[name], T, kind)
|
|
150
|
+
save_file(tensors, str(out / f.name), metadata=meta)
|
|
151
|
+
del tensors
|
|
152
|
+
for f in sorted(md.iterdir()):
|
|
153
|
+
if f.is_file() and f.suffix != ".safetensors" and not f.match(CALIBRATIONS) and f.name not in (
|
|
154
|
+
"config.json", "basal.json"):
|
|
155
|
+
shutil.copy2(f, out / f.name)
|
|
156
|
+
tc = text_config(cfg)
|
|
157
|
+
cap = tc.get("final_logit_softcapping")
|
|
158
|
+
for c in {id(tc): tc, id(cfg): cfg}.values(): # (a multimodal config may repeat it at the top)
|
|
159
|
+
if c.get("final_logit_softcapping"):
|
|
160
|
+
c["final_logit_softcapping"] = float(c["final_logit_softcapping"]) / T
|
|
161
|
+
(out / "config.json").write_text(json.dumps(cfg, indent=2) + "\n", encoding="utf-8")
|
|
162
|
+
bj = md / "basal.json"
|
|
163
|
+
meta = json.loads(bj.read_text(encoding="utf-8")) if bj.exists() else {}
|
|
164
|
+
meta["temperature_folded"] = float(T) * float(meta.get("temperature_folded", 1.0))
|
|
165
|
+
(out / "basal.json").write_text(json.dumps(meta, indent=1, ensure_ascii=False) + "\n", encoding="utf-8")
|
|
166
|
+
return name, cap, kind
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def main(argv=None):
|
|
170
|
+
ap = argparse.ArgumentParser(description=(__doc__ or "").split("\n\n")[0])
|
|
171
|
+
ap.add_argument("--model", required=True, help="model directory or Hugging Face repo id")
|
|
172
|
+
ap.add_argument("--revision", default=None)
|
|
173
|
+
ap.add_argument("--out", required=True, help="output directory (new or empty)")
|
|
174
|
+
ap.add_argument("--calibration", default=None, help="the calibration file to fold from (default: the model's "
|
|
175
|
+
"CALIBRATION.json)")
|
|
176
|
+
ap.add_argument("--type", dest="q_type", default="choice", help="the question type whose temperature is folded")
|
|
177
|
+
ap.add_argument("--bucket", default=None, help="its option-count bucket (default 2-10 where the file has one)")
|
|
178
|
+
ap.add_argument("--temperature", type=float, default=None, help="fold this temperature instead")
|
|
179
|
+
a = ap.parse_args(argv)
|
|
180
|
+
out = Path(a.out)
|
|
181
|
+
if out.exists() and (not out.is_dir() or any(out.iterdir())):
|
|
182
|
+
raise SystemExit(f"--out {out}: exists and is not an empty directory")
|
|
183
|
+
from .adapter import check_space
|
|
184
|
+
from .engine import resolve
|
|
185
|
+
md = Path(resolve(a.model, a.revision))
|
|
186
|
+
calp = Path(a.calibration) if a.calibration else md / "CALIBRATION.json"
|
|
187
|
+
cal = json.loads(calp.read_text(encoding="utf-8")) if calp.exists() else {}
|
|
188
|
+
T = a.temperature if a.temperature is not None else pick(cal, a.q_type, a.bucket)
|
|
189
|
+
if not (T > 0 and math.isfinite(T)):
|
|
190
|
+
raise SystemExit(f"temperature {T}: give a positive number")
|
|
191
|
+
check_space(md, out, f"--out {out}: the folded checkpoint has the size of the model's weights")
|
|
192
|
+
name, cap, kind = fold_checkpoint(md, out, T)
|
|
193
|
+
from .server import model_content_id, model_weights_id
|
|
194
|
+
content = model_content_id(out) # (the folded folder's files; its CALIBRATION files are none of them)
|
|
195
|
+
weights = model_weights_id(out)
|
|
196
|
+
for f in sorted(md.glob(CALIBRATIONS)):
|
|
197
|
+
c = json.loads(f.read_text(encoding="utf-8"))
|
|
198
|
+
folded = rescaled(c, T, out, content, weights)
|
|
199
|
+
(out / f.name).write_text(json.dumps(folded, indent=1, ensure_ascii=False) + "\n", encoding="utf-8")
|
|
200
|
+
form = f"{name} / T" if kind == "scale" else f"(1 + {name}) / T - 1"
|
|
201
|
+
print(f"basal-fold-temperature: T = {T:g} folded into {out} ({form}"
|
|
202
|
+
+ (f", soft cap {cap:g} -> {cap / T:g}" if cap else ", no soft cap") + ")")
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
if __name__ == "__main__":
|
|
206
|
+
main()
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
Copyright 2014 The DM Sans Project Authors (https://github.com/googlefonts/dm-fonts) DMSans-Italic[opsz,wght].ttf: Copyright 2014 The DM Sans Project Authors (https://github.com/googlefonts/dm-fonts)
|
|
2
|
+
|
|
3
|
+
This Font Software is licensed under the SIL Open Font License, Version 1.1.
|
|
4
|
+
This license is copied below, and is also available with a FAQ at:
|
|
5
|
+
http://scripts.sil.org/OFL
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
-----------------------------------------------------------
|
|
9
|
+
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
|
10
|
+
-----------------------------------------------------------
|
|
11
|
+
|
|
12
|
+
PREAMBLE
|
|
13
|
+
The goals of the Open Font License (OFL) are to stimulate worldwide
|
|
14
|
+
development of collaborative font projects, to support the font creation
|
|
15
|
+
efforts of academic and linguistic communities, and to provide a free and
|
|
16
|
+
open framework in which fonts may be shared and improved in partnership
|
|
17
|
+
with others.
|
|
18
|
+
|
|
19
|
+
The OFL allows the licensed fonts to be used, studied, modified and
|
|
20
|
+
redistributed freely as long as they are not sold by themselves. The
|
|
21
|
+
fonts, including any derivative works, can be bundled, embedded,
|
|
22
|
+
redistributed and/or sold with any software provided that any reserved
|
|
23
|
+
names are not used by derivative works. The fonts and derivatives,
|
|
24
|
+
however, cannot be released under any other type of license. The
|
|
25
|
+
requirement for fonts to remain under this license does not apply
|
|
26
|
+
to any document created using the fonts or their derivatives.
|
|
27
|
+
|
|
28
|
+
DEFINITIONS
|
|
29
|
+
"Font Software" refers to the set of files released by the Copyright
|
|
30
|
+
Holder(s) under this license and clearly marked as such. This may
|
|
31
|
+
include source files, build scripts and documentation.
|
|
32
|
+
|
|
33
|
+
"Reserved Font Name" refers to any names specified as such after the
|
|
34
|
+
copyright statement(s).
|
|
35
|
+
|
|
36
|
+
"Original Version" refers to the collection of Font Software components as
|
|
37
|
+
distributed by the Copyright Holder(s).
|
|
38
|
+
|
|
39
|
+
"Modified Version" refers to any derivative made by adding to, deleting,
|
|
40
|
+
or substituting -- in part or in whole -- any of the components of the
|
|
41
|
+
Original Version, by changing formats or by porting the Font Software to a
|
|
42
|
+
new environment.
|
|
43
|
+
|
|
44
|
+
"Author" refers to any designer, engineer, programmer, technical
|
|
45
|
+
writer or other person who contributed to the Font Software.
|
|
46
|
+
|
|
47
|
+
PERMISSION & CONDITIONS
|
|
48
|
+
Permission is hereby granted, free of charge, to any person obtaining
|
|
49
|
+
a copy of the Font Software, to use, study, copy, merge, embed, modify,
|
|
50
|
+
redistribute, and sell modified and unmodified copies of the Font
|
|
51
|
+
Software, subject to the following conditions:
|
|
52
|
+
|
|
53
|
+
1) Neither the Font Software nor any of its individual components,
|
|
54
|
+
in Original or Modified Versions, may be sold by itself.
|
|
55
|
+
|
|
56
|
+
2) Original or Modified Versions of the Font Software may be bundled,
|
|
57
|
+
redistributed and/or sold with any software, provided that each copy
|
|
58
|
+
contains the above copyright notice and this license. These can be
|
|
59
|
+
included either as stand-alone text files, human-readable headers or
|
|
60
|
+
in the appropriate machine-readable metadata fields within text or
|
|
61
|
+
binary files as long as those fields can be easily viewed by the user.
|
|
62
|
+
|
|
63
|
+
3) No Modified Version of the Font Software may use the Reserved Font
|
|
64
|
+
Name(s) unless explicit written permission is granted by the corresponding
|
|
65
|
+
Copyright Holder. This restriction only applies to the primary font name as
|
|
66
|
+
presented to the users.
|
|
67
|
+
|
|
68
|
+
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
|
69
|
+
Software shall not be used to promote, endorse or advertise any
|
|
70
|
+
Modified Version, except to acknowledge the contribution(s) of the
|
|
71
|
+
Copyright Holder(s) and the Author(s) or with their explicit written
|
|
72
|
+
permission.
|
|
73
|
+
|
|
74
|
+
5) The Font Software, modified or unmodified, in part or in whole,
|
|
75
|
+
must be distributed entirely under this license, and must not be
|
|
76
|
+
distributed under any other license. The requirement for fonts to
|
|
77
|
+
remain under this license does not apply to any document created
|
|
78
|
+
using the Font Software.
|
|
79
|
+
|
|
80
|
+
TERMINATION
|
|
81
|
+
This license becomes null and void if any of the above conditions are
|
|
82
|
+
not met.
|
|
83
|
+
|
|
84
|
+
DISCLAIMER
|
|
85
|
+
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
|
86
|
+
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
|
87
|
+
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
|
88
|
+
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
|
89
|
+
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
|
90
|
+
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
|
91
|
+
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
|
92
|
+
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
|
93
|
+
OTHER DEALINGS IN THE FONT SOFTWARE.
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
Copyright 2020 The Space Grotesk Project Authors (https://github.com/floriankarsten/space-grotesk)
|
|
2
|
+
|
|
3
|
+
This Font Software is licensed under the SIL Open Font License, Version 1.1.
|
|
4
|
+
This license is copied below, and is also available with a FAQ at:
|
|
5
|
+
http://scripts.sil.org/OFL
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
-----------------------------------------------------------
|
|
9
|
+
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
|
10
|
+
-----------------------------------------------------------
|
|
11
|
+
|
|
12
|
+
PREAMBLE
|
|
13
|
+
The goals of the Open Font License (OFL) are to stimulate worldwide
|
|
14
|
+
development of collaborative font projects, to support the font creation
|
|
15
|
+
efforts of academic and linguistic communities, and to provide a free and
|
|
16
|
+
open framework in which fonts may be shared and improved in partnership
|
|
17
|
+
with others.
|
|
18
|
+
|
|
19
|
+
The OFL allows the licensed fonts to be used, studied, modified and
|
|
20
|
+
redistributed freely as long as they are not sold by themselves. The
|
|
21
|
+
fonts, including any derivative works, can be bundled, embedded,
|
|
22
|
+
redistributed and/or sold with any software provided that any reserved
|
|
23
|
+
names are not used by derivative works. The fonts and derivatives,
|
|
24
|
+
however, cannot be released under any other type of license. The
|
|
25
|
+
requirement for fonts to remain under this license does not apply
|
|
26
|
+
to any document created using the fonts or their derivatives.
|
|
27
|
+
|
|
28
|
+
DEFINITIONS
|
|
29
|
+
"Font Software" refers to the set of files released by the Copyright
|
|
30
|
+
Holder(s) under this license and clearly marked as such. This may
|
|
31
|
+
include source files, build scripts and documentation.
|
|
32
|
+
|
|
33
|
+
"Reserved Font Name" refers to any names specified as such after the
|
|
34
|
+
copyright statement(s).
|
|
35
|
+
|
|
36
|
+
"Original Version" refers to the collection of Font Software components as
|
|
37
|
+
distributed by the Copyright Holder(s).
|
|
38
|
+
|
|
39
|
+
"Modified Version" refers to any derivative made by adding to, deleting,
|
|
40
|
+
or substituting -- in part or in whole -- any of the components of the
|
|
41
|
+
Original Version, by changing formats or by porting the Font Software to a
|
|
42
|
+
new environment.
|
|
43
|
+
|
|
44
|
+
"Author" refers to any designer, engineer, programmer, technical
|
|
45
|
+
writer or other person who contributed to the Font Software.
|
|
46
|
+
|
|
47
|
+
PERMISSION & CONDITIONS
|
|
48
|
+
Permission is hereby granted, free of charge, to any person obtaining
|
|
49
|
+
a copy of the Font Software, to use, study, copy, merge, embed, modify,
|
|
50
|
+
redistribute, and sell modified and unmodified copies of the Font
|
|
51
|
+
Software, subject to the following conditions:
|
|
52
|
+
|
|
53
|
+
1) Neither the Font Software nor any of its individual components,
|
|
54
|
+
in Original or Modified Versions, may be sold by itself.
|
|
55
|
+
|
|
56
|
+
2) Original or Modified Versions of the Font Software may be bundled,
|
|
57
|
+
redistributed and/or sold with any software, provided that each copy
|
|
58
|
+
contains the above copyright notice and this license. These can be
|
|
59
|
+
included either as stand-alone text files, human-readable headers or
|
|
60
|
+
in the appropriate machine-readable metadata fields within text or
|
|
61
|
+
binary files as long as those fields can be easily viewed by the user.
|
|
62
|
+
|
|
63
|
+
3) No Modified Version of the Font Software may use the Reserved Font
|
|
64
|
+
Name(s) unless explicit written permission is granted by the corresponding
|
|
65
|
+
Copyright Holder. This restriction only applies to the primary font name as
|
|
66
|
+
presented to the users.
|
|
67
|
+
|
|
68
|
+
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
|
69
|
+
Software shall not be used to promote, endorse or advertise any
|
|
70
|
+
Modified Version, except to acknowledge the contribution(s) of the
|
|
71
|
+
Copyright Holder(s) and the Author(s) or with their explicit written
|
|
72
|
+
permission.
|
|
73
|
+
|
|
74
|
+
5) The Font Software, modified or unmodified, in part or in whole,
|
|
75
|
+
must be distributed entirely under this license, and must not be
|
|
76
|
+
distributed under any other license. The requirement for fonts to
|
|
77
|
+
remain under this license does not apply to any document created
|
|
78
|
+
using the Font Software.
|
|
79
|
+
|
|
80
|
+
TERMINATION
|
|
81
|
+
This license becomes null and void if any of the above conditions are
|
|
82
|
+
not met.
|
|
83
|
+
|
|
84
|
+
DISCLAIMER
|
|
85
|
+
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
|
86
|
+
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
|
87
|
+
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
|
88
|
+
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
|
89
|
+
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
|
90
|
+
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
|
91
|
+
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
|
92
|
+
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
|
93
|
+
OTHER DEALINGS IN THE FONT SOFTWARE.
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
basal/fp8block.py
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
"""Block-scaled FP8 linears for the CUDA graph engine (--mode fp8 --fp8-scaling block; basal-omni, Gemma 4): weights
|
|
2
|
+
in 128 x 128 blocks and activations in 1 x 128 tiles (a token's 128 consecutive input features), each block with its
|
|
3
|
+
own fp32 scale (amax / 448, e4m3); the GEMM applies both scales to every 128-deep slice of the reduction and adds the
|
|
4
|
+
slices in fp32 (the tensor cores' FP8 accumulator never sums more than 128 products). Finer than torchao's per-row
|
|
5
|
+
scales (one scale per output row of the weight and per token of the input), which failed the port gate on
|
|
6
|
+
basal-omni-1.1-max by 0.0001 (2-10 options at margin >= 0.2, 20 Oct).
|
|
7
|
+
|
|
8
|
+
The GEMM: on Hopper flashinfer's SM90 block-scaled kernel (DeepGEMM's, compiled with nvcc on first use of a shape; it
|
|
9
|
+
quantises the bf16 activations itself) when flashinfer is installed: 1.05-1.7x cuBLAS bf16 at ultra's shapes, the same
|
|
10
|
+
bits from one process to the next and a row's output independent of the other rows (flashinfer 0.7.3, H100, 10 Nov).
|
|
11
|
+
Elsewhere one Triton kernel with fixed tiles (128 x 128 x 128, no split of the reduction: a row's output does not
|
|
12
|
+
depend on the other rows): at ultra's shapes and 1,000 rows or more 0.75-0.95x cuBLAS bf16 on the H100, 1.1-1.45x on an
|
|
13
|
+
RTX PRO 6000 Blackwell.
|
|
14
|
+
|
|
15
|
+
The blocks, the Triton GEMM and the layer are basal/blockquant.py's, shared with --mode int8 (FP8: the format
|
|
16
|
+
FORMAT, values saturated to +-448 and cast to e4m3).
|
|
17
|
+
|
|
18
|
+
quantize(w) weight [N, K] -> (FP8 [N, K], scales [N / 128, K / 128])
|
|
19
|
+
act_quant(x) activations [M, K] -> (FP8 [M, K], scales [M, K / 128])
|
|
20
|
+
gemm(q, s, w, ws, dt) the Triton GEMM: [M, N] in dt (CPU: the same maths dequantised)
|
|
21
|
+
linear(x, w, ws, b) x [..., K] -> [..., N]: flashinfer's kernel, or act_quant + gemm; the bias
|
|
22
|
+
BlockFP8Linear a linear layer holding (w, ws, bias); lean.linear runs its parameters in compiled layers
|
|
23
|
+
"""
|
|
24
|
+
import torch
|
|
25
|
+
|
|
26
|
+
from .blockquant import BLOCK, TILES, BlockFormat, BlockLinear, fits, grid # noqa: F401 (the shared core)
|
|
27
|
+
from .blockquant import reference as _reference # noqa: F401 (tests)
|
|
28
|
+
|
|
29
|
+
E4M3 = torch.float8_e4m3fn
|
|
30
|
+
FP8_MAX = 448.0
|
|
31
|
+
CONFIG = dict(TILES, num_stages=4) # the GEMM's tiles and launch (blockquant.TILES), 4 pipeline stages
|
|
32
|
+
FORMAT = BlockFormat("fp8_block_gemm", E4M3, FP8_MAX, rounded=False, stages=CONFIG["num_stages"])
|
|
33
|
+
quantize, act_quant, gemm = FORMAT.quantize, FORMAT.act_quant, FORMAT.gemm
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
_SM90 = []
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def sm90():
|
|
40
|
+
"""True where flashinfer's SM90 block-scaled GEMM runs: a Hopper GPU, flashinfer installed and nvcc, since its
|
|
41
|
+
kernels are compiled at first use with nvcc: when nvcc is not on PATH, CUDA_HOME's or /usr/local/cuda's is added;
|
|
42
|
+
with none of them (the container image's CUDA base) the Triton kernel."""
|
|
43
|
+
if not _SM90:
|
|
44
|
+
ok = torch.cuda.is_available() and torch.cuda.get_device_capability() == (9, 0)
|
|
45
|
+
if ok:
|
|
46
|
+
try:
|
|
47
|
+
import flashinfer.gemm # noqa: F401
|
|
48
|
+
except ImportError:
|
|
49
|
+
ok = False
|
|
50
|
+
if ok:
|
|
51
|
+
import os
|
|
52
|
+
import shutil
|
|
53
|
+
if shutil.which("nvcc") is None:
|
|
54
|
+
for d in (os.environ.get("CUDA_HOME"), "/usr/local/cuda"):
|
|
55
|
+
if d and os.path.exists(os.path.join(d, "bin", "nvcc")):
|
|
56
|
+
os.environ["PATH"] = os.path.join(d, "bin") + os.pathsep + os.environ.get("PATH", "")
|
|
57
|
+
break
|
|
58
|
+
else: # (flashinfer would fail at its first GEMM)
|
|
59
|
+
ok = False
|
|
60
|
+
_SM90.append(ok)
|
|
61
|
+
if not ok: # the Triton kernel, before any layer is compiled
|
|
62
|
+
FORMAT.build()
|
|
63
|
+
return _SM90[0]
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
@torch.library.custom_op("basal::fp8_block_linear_sm90", mutates_args=())
|
|
67
|
+
def _linear_sm90(x: torch.Tensor, w: torch.Tensor, ws: torch.Tensor) -> torch.Tensor:
|
|
68
|
+
from flashinfer.gemm import fp8_blockscale_gemm_sm90
|
|
69
|
+
if not x.shape[0]:
|
|
70
|
+
return x.new_empty(0, w.shape[0])
|
|
71
|
+
return fp8_blockscale_gemm_sm90(x, w, None, ws, out_dtype=x.dtype)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
@_linear_sm90.register_fake
|
|
75
|
+
def _(x, w, ws):
|
|
76
|
+
return x.new_empty(x.shape[0], w.shape[0])
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def linear(x, w, ws, bias=None):
|
|
80
|
+
"""x [..., K] (bf16) through a block-scaled FP8 weight -> [..., N] in x's dtype."""
|
|
81
|
+
shape = x.shape
|
|
82
|
+
x2 = x.reshape(-1, shape[-1])
|
|
83
|
+
if x.is_cuda and x.dtype == torch.bfloat16 and sm90():
|
|
84
|
+
y = torch.ops.basal.fp8_block_linear_sm90(x2.contiguous(), w, ws)
|
|
85
|
+
else:
|
|
86
|
+
q, s = act_quant(x2)
|
|
87
|
+
y = gemm(q, s, w, ws, x.dtype)
|
|
88
|
+
if bias is not None:
|
|
89
|
+
y = y + bias.to(y.dtype)
|
|
90
|
+
return y.reshape(*shape[:-1], w.shape[0])
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
class BlockFP8Linear(BlockLinear):
|
|
94
|
+
"""A linear layer with a block-scaled FP8 weight (quantize) and an optional bias (blockquant.BlockLinear: part(o, n)
|
|
95
|
+
a view of output rows o..o + n); forward: linear (flashinfer's kernel on Hopper)."""
|
|
96
|
+
|
|
97
|
+
FORMAT = FORMAT
|
|
98
|
+
|
|
99
|
+
def forward(self, x):
|
|
100
|
+
return linear(x, self.weight, self.weight_scale, self.bias)
|