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/llama_graph.py
ADDED
|
@@ -0,0 +1,587 @@
|
|
|
1
|
+
"""Pure-Triton Llama / Bielik 3.0 forward for the CUDA graph engine (basal-engine 3.0.1).
|
|
2
|
+
|
|
3
|
+
Mirrors basal/gemma4_graph.py for LlamaForCausalLM models (Bielik-1.5B nano: 32L GQA-6 biased; Bielik-4.5B mini:
|
|
4
|
+
60L GQA-8 biased; Bielik-11B max: 50L GQA-4 unbiased) with zero external CUDA dependencies (pure Triton + PyTorch):
|
|
5
|
+
|
|
6
|
+
- Native NHD layout [B, L, H, D] throughout (zero transpose copies).
|
|
7
|
+
- Fused Triton layer ops (basal/llama_kernels.py): add_rmsnorm (+FP8), qkv_rope, kv_rope, q_rope, swiglu (+FP8).
|
|
8
|
+
- Unified pure-Triton metadata attention (basal/attn_meta.py): D=64/128 tiles for sm_90, sm_100, sm_120/sm_121 (GB10),
|
|
9
|
+
safe non-pow2 GQA (GQA=6 -> HP=2), two_way / prefix_bidir / dual rows (HAS_TW + optional bidir_layers; served:
|
|
10
|
+
basal.json "two_way" with --llama-graph on, 3.0.1 - prefix_bidir / dual are refused by engine.graph_prefix_refused),
|
|
11
|
+
Single-Pass Flat SOAM (forward_flat), Pass-2 Tree (forward_suffix without KV concat/repeat/dense mask), and
|
|
12
|
+
Split-KV readout attention on long states.
|
|
13
|
+
- Complete last-layer readout slicing: layer N-1 keeps q_proj separate from merged kv_proj (preserving biases on
|
|
14
|
+
1.5B & 4.5B!). Pass 1 with kv_only=True stops immediately after layer N-1's K/V; Plain, Compact, Flat, and Pass 2
|
|
15
|
+
with ro run layer N-1's q_proj, readout attention, o_proj, MLP, and final norm on the R readout rows ONLY.
|
|
16
|
+
- Quantization: lossless merged ModelOpt FP8 (LosslessMergedFP8Linear, per-column scale_b, zero weight re-quant),
|
|
17
|
+
pure-Triton 128x128 Block-FP8 and Block-INT8 (all Bielik 3.0 projection dims are multiples of 128), and BF16.
|
|
18
|
+
"""
|
|
19
|
+
from collections import namedtuple
|
|
20
|
+
|
|
21
|
+
import torch
|
|
22
|
+
import torch.nn.functional as F
|
|
23
|
+
|
|
24
|
+
from . import blockquant, fp8block, int8block, llama_attn, llama_kernels
|
|
25
|
+
from .lean import TreeMask, linear as _lean_linear, _params as _lean_params
|
|
26
|
+
|
|
27
|
+
LlamaLayerC = namedtuple("LlamaLayerC", "heads kv_heads d eps scale bidir")
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def bidir_layers_of(model_dir):
|
|
31
|
+
"""Optional `bidir_layers` list from basal.json (None = all layers bidirectional when two_way / prefix_bidir)."""
|
|
32
|
+
import json
|
|
33
|
+
from pathlib import Path
|
|
34
|
+
p = Path(model_dir) / "basal.json"
|
|
35
|
+
if not p.exists():
|
|
36
|
+
return None
|
|
37
|
+
try:
|
|
38
|
+
meta = json.loads(p.read_text(encoding="utf-8"))
|
|
39
|
+
except (OSError, ValueError):
|
|
40
|
+
return None
|
|
41
|
+
bl = meta.get("bidir_layers")
|
|
42
|
+
if bl is None and isinstance(meta.get("dual"), dict):
|
|
43
|
+
bl = ((meta["dual"].get("modes") or {}).get("prefix_header") or {}).get("bidir_layers")
|
|
44
|
+
if bl is None:
|
|
45
|
+
return None
|
|
46
|
+
if not isinstance(bl, list) or not all(isinstance(i, int) and not isinstance(i, bool) and i >= 0 for i in bl):
|
|
47
|
+
raise ValueError(f"{p}: \"bidir_layers\" must be a list of non-negative layer indices, not {bl!r}")
|
|
48
|
+
return bl
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def flat_plan(packs, idx, pad_id, T=None, R=None, has_tw=False):
|
|
52
|
+
"""Build host numpy metadata for a single-pass Flat SOAM forward of units `idx`:
|
|
53
|
+
Returns ([ids, pos, start, prq, se, ro] (+ [tw] if has_tw), slots).
|
|
54
|
+
Packs arbitrary mixes of single causal prompts, multi-question SOAM tries, two_way prompts, and prefix_bidir
|
|
55
|
+
units back-to-back in ONE [1, T] row!"""
|
|
56
|
+
import numpy as np
|
|
57
|
+
A = sum(len(packs[k][0]) for k in idx)
|
|
58
|
+
T = T or A
|
|
59
|
+
ids = np.full((1, T), pad_id, dtype=np.int64)
|
|
60
|
+
pos = np.zeros((1, T), dtype=np.int64)
|
|
61
|
+
start = np.full(T, A, dtype=np.int64)
|
|
62
|
+
prq = np.arange(1, T + 1, dtype=np.int64)
|
|
63
|
+
se = np.full(T, T, dtype=np.int64)
|
|
64
|
+
tw = np.zeros(T, dtype=np.int64) if has_tw else None
|
|
65
|
+
ro, slot, slots, o = [], {}, [], 0
|
|
66
|
+
for k in idx:
|
|
67
|
+
pk = packs[k]
|
|
68
|
+
t, pp, sg, last, par = pk
|
|
69
|
+
m = len(t)
|
|
70
|
+
ids[0, o: o + m] = t
|
|
71
|
+
pos[0, o: o + m] = pp
|
|
72
|
+
start[o: o + m] = o
|
|
73
|
+
is_tw = bool(getattr(pk, "two_way", False))
|
|
74
|
+
bidir = int(getattr(pk, "bidir", 0))
|
|
75
|
+
if len(par) > 1:
|
|
76
|
+
sg_a = np.asarray(sg)
|
|
77
|
+
P = int(np.searchsorted(sg_a, 1))
|
|
78
|
+
prq[o + P: o + m] = o + P
|
|
79
|
+
if bidir > 0:
|
|
80
|
+
bp = min(bidir, P)
|
|
81
|
+
prq[o: o + bp] = o + bp
|
|
82
|
+
if tw is not None:
|
|
83
|
+
tw[o: o + bp] = o + bp
|
|
84
|
+
sub = np.searchsorted(sg_a, np.arange(len(par)), "right")
|
|
85
|
+
for b in range(len(par) - 1, 0, -1):
|
|
86
|
+
sub[par[b]] = max(sub[par[b]], sub[b])
|
|
87
|
+
se[o: o + m] = o + sub[sg_a]
|
|
88
|
+
else:
|
|
89
|
+
se[o: o + m] = o + m
|
|
90
|
+
if is_tw:
|
|
91
|
+
prq[o: o + m] = o + m
|
|
92
|
+
if tw is not None:
|
|
93
|
+
tw[o: o + m] = o + m
|
|
94
|
+
elif bidir > 0:
|
|
95
|
+
bp = min(bidir, m)
|
|
96
|
+
prq[o: o + bp] = o + bp
|
|
97
|
+
if tw is not None:
|
|
98
|
+
tw[o: o + bp] = o + bp
|
|
99
|
+
for i in last:
|
|
100
|
+
slots.append(slot.setdefault(o + i, len(ro)))
|
|
101
|
+
if slots[-1] == len(ro):
|
|
102
|
+
ro.append(o + i)
|
|
103
|
+
o += m
|
|
104
|
+
pos[0, A:] = np.arange(T - A)
|
|
105
|
+
h_ro = np.zeros(R or len(ro), dtype=np.int64)
|
|
106
|
+
h_ro[: len(ro)] = ro
|
|
107
|
+
tensors = [ids, pos, start, prq, se, h_ro] + ([tw] if tw is not None else [])
|
|
108
|
+
return tensors, slots
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def is_llama(model):
|
|
112
|
+
"""True for a standard LlamaForCausalLM decoder with LlamaDecoderLayer / LlamaAttention / LlamaMLP / SiLU."""
|
|
113
|
+
mm = getattr(model, "model", None)
|
|
114
|
+
layers = getattr(mm, "layers", None)
|
|
115
|
+
if not layers:
|
|
116
|
+
return False
|
|
117
|
+
return (all(type(layer).__name__ == "LlamaDecoderLayer"
|
|
118
|
+
and type(layer.self_attn).__name__ == "LlamaAttention"
|
|
119
|
+
and type(layer.mlp).__name__ == "LlamaMLP" for layer in layers)
|
|
120
|
+
and getattr(model.config, "hidden_act", "silu") == "silu"
|
|
121
|
+
and not getattr(model.config, "sliding_window", None))
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _params(m):
|
|
125
|
+
"""Extract linear module tensors for functional execution in compiled layers."""
|
|
126
|
+
if isinstance(m, llama_kernels.LosslessMergedFP8Linear):
|
|
127
|
+
return ("mfp8", m.weight, m.weight_scale_col, m.input_scale, m.bias)
|
|
128
|
+
return _lean_params(m)
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _linear(x, p):
|
|
132
|
+
"""Dispatch BF16 / FP32, ModelOpt FP8, LosslessMergedFP8, Block-FP8, Block-INT8, or NVFP4 linear."""
|
|
133
|
+
if isinstance(p, tuple) and len(p) == 5 and p[0] == "mfp8":
|
|
134
|
+
from .engine import FP8_FAST_ACCUM, fp8_cast
|
|
135
|
+
_, w, ws_col, xs, b = p
|
|
136
|
+
shape, dt = x.shape, x.dtype
|
|
137
|
+
x2 = x.reshape(-1, shape[-1])
|
|
138
|
+
q = fp8_cast(x2, xs)
|
|
139
|
+
return _linear_mfp8_q(q, w, ws_col, xs, b, dt, shape, FP8_FAST_ACCUM[0])
|
|
140
|
+
return _lean_linear(x, p)
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def _linear_mfp8_q(q2, w, ws_col, xs, b, dt, shape, fast_accum):
|
|
144
|
+
if q2.is_cuda:
|
|
145
|
+
m = q2.shape[0]
|
|
146
|
+
if m % 16:
|
|
147
|
+
q2 = F.pad(q2.view(torch.uint8), (0, 0, 0, -m % 16)).view(torch.float8_e4m3fn)
|
|
148
|
+
sa = xs.reshape(1, 1).expand(q2.shape[0], 1).contiguous()
|
|
149
|
+
y = torch._scaled_mm(q2, w.t(), scale_a=sa, scale_b=ws_col,
|
|
150
|
+
bias=None if b is None else b.to(dt), out_dtype=dt,
|
|
151
|
+
use_fast_accum=fast_accum)[:m]
|
|
152
|
+
else:
|
|
153
|
+
y = (q2.float() * xs) @ (w.float() * ws_col.t()).t()
|
|
154
|
+
y = (y if b is None else y + b.float()).to(dt)
|
|
155
|
+
return y.reshape(*shape[:-1], w.shape[0])
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _linear_q_fp8(q_fp8, p, dt):
|
|
159
|
+
"""Run an already-quantized FP8 activation through FP8Linear or LosslessMergedFP8Linear."""
|
|
160
|
+
from .engine import FP8_FAST_ACCUM
|
|
161
|
+
shape = q_fp8.shape
|
|
162
|
+
q2 = q_fp8.reshape(-1, shape[-1])
|
|
163
|
+
if len(p) == 5 and p[0] == "mfp8":
|
|
164
|
+
_, w, ws_col, xs, b = p
|
|
165
|
+
return _linear_mfp8_q(q2, w, ws_col, xs, b, dt, shape, FP8_FAST_ACCUM[0])
|
|
166
|
+
w, ws, xs, b = p
|
|
167
|
+
if q2.is_cuda:
|
|
168
|
+
m = q2.shape[0]
|
|
169
|
+
if m % 16:
|
|
170
|
+
q2 = F.pad(q2.view(torch.uint8), (0, 0, 0, -m % 16)).view(torch.float8_e4m3fn)
|
|
171
|
+
y = torch._scaled_mm(q2, w.t(), scale_a=xs, scale_b=ws,
|
|
172
|
+
bias=None if b is None else b.to(dt), out_dtype=dt,
|
|
173
|
+
use_fast_accum=FP8_FAST_ACCUM[0])[:m]
|
|
174
|
+
else:
|
|
175
|
+
y = (q2.float() * xs) @ (w.float() * ws).t()
|
|
176
|
+
y = (y if b is None else y + b.float()).to(dt)
|
|
177
|
+
return y.reshape(*shape[:-1], w.shape[0])
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def _static_fp8_input_scale(p):
|
|
181
|
+
"""Return static FP8 input_scale tensor if `p` is FP8Linear or LosslessMergedFP8Linear, else None."""
|
|
182
|
+
if isinstance(p, tuple):
|
|
183
|
+
if len(p) == 5 and p[0] == "mfp8":
|
|
184
|
+
return p[3]
|
|
185
|
+
if len(p) == 4:
|
|
186
|
+
return p[2]
|
|
187
|
+
return None
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def _attend_nhd(q, k, v, scale, meta):
|
|
191
|
+
"""Attention on NHD tensors q [B, Lq, H, D], k / v [B, Lk, Hkv, D] -> [B, Lq, H * D].
|
|
192
|
+
Passes zero-copy transposed views [B, H, L, D] (16-aligned strides) directly to llama_attn."""
|
|
193
|
+
B, Lq, H, D = q.shape
|
|
194
|
+
o = llama_attn.attention(q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2), scale=scale, **meta)
|
|
195
|
+
return o.reshape(B, Lq, H * D)
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def _layer_step(h, res, P, C, cos, sin, kb, vb, pk, pv, meta):
|
|
199
|
+
"""Full decoder layer (layers 0 .. N - 2) in NHD layout with fused Triton ops."""
|
|
200
|
+
dt = h.dtype
|
|
201
|
+
qkv_p = P.get("qkv")
|
|
202
|
+
xs1 = _static_fp8_input_scale(qkv_p) if qkv_p is not None else None
|
|
203
|
+
if xs1 is not None:
|
|
204
|
+
h, x_q = llama_kernels.add_rmsnorm_fp8(h, res, P["ln1"], C.eps, xs1)
|
|
205
|
+
qkv = _linear_q_fp8(x_q, qkv_p, dt)
|
|
206
|
+
q, k, v = llama_kernels.qkv_rope(qkv, cos, sin, C.heads, C.kv_heads, C.d)
|
|
207
|
+
else:
|
|
208
|
+
h, x = llama_kernels.add_rmsnorm(h, res, P["ln1"], C.eps)
|
|
209
|
+
if qkv_p is not None:
|
|
210
|
+
qkv = _linear(x, qkv_p)
|
|
211
|
+
q, k, v = llama_kernels.qkv_rope(qkv, cos, sin, C.heads, C.kv_heads, C.d)
|
|
212
|
+
else:
|
|
213
|
+
q_raw, k_raw, v_raw = _linear(x, P["q"]), _linear(x, P["k"]), _linear(x, P["v"])
|
|
214
|
+
q = llama_kernels.q_rope(q_raw, cos, sin, C.heads, C.d)
|
|
215
|
+
k, v = llama_kernels.kv_rope(torch.cat([k_raw, v_raw], -1), cos, sin, C.kv_heads, C.d)
|
|
216
|
+
if kb is not None:
|
|
217
|
+
# kb / vb are [B, Hkv, L, D] (GraphBackend's KV layout); store transposed view
|
|
218
|
+
kb.copy_(k.transpose(1, 2))
|
|
219
|
+
vb.copy_(v.transpose(1, 2))
|
|
220
|
+
if pk is not None:
|
|
221
|
+
# Pass 2: prefix is [B, Hkv, P, D]; attend over prefix + own keys without dense mask!
|
|
222
|
+
k_all = torch.cat([pk.transpose(1, 2), k], dim=1)
|
|
223
|
+
v_all = torch.cat([pv.transpose(1, 2), v], dim=1)
|
|
224
|
+
a = _attend_nhd(q, k_all, v_all, C.scale, meta)
|
|
225
|
+
else:
|
|
226
|
+
a = _attend_nhd(q, k, v, C.scale, meta)
|
|
227
|
+
attn_out = _linear(a, P["o"])
|
|
228
|
+
gu_p = P.get("gu")
|
|
229
|
+
xs2 = _static_fp8_input_scale(gu_p) if gu_p is not None else None
|
|
230
|
+
if xs2 is not None:
|
|
231
|
+
h, x2_q = llama_kernels.add_rmsnorm_fp8(h, attn_out, P["ln2"], C.eps, xs2)
|
|
232
|
+
gu = _linear_q_fp8(x2_q, gu_p, dt)
|
|
233
|
+
else:
|
|
234
|
+
h, x2 = llama_kernels.add_rmsnorm(h, attn_out, P["ln2"], C.eps)
|
|
235
|
+
if gu_p is not None:
|
|
236
|
+
gu = _linear(x2, gu_p)
|
|
237
|
+
else:
|
|
238
|
+
gu = torch.cat([_linear(x2, P["gate"]), _linear(x2, P["up"])], -1)
|
|
239
|
+
down_p = P["down"]
|
|
240
|
+
xs_d = _static_fp8_input_scale(down_p)
|
|
241
|
+
if xs_d is not None:
|
|
242
|
+
mid_q = llama_kernels.swiglu_fp8(gu, xs_d)
|
|
243
|
+
mlp_out = _linear_q_fp8(mid_q, down_p, dt)
|
|
244
|
+
elif isinstance(down_p, tuple) and len(down_p) == 3 and down_p[0].dtype == torch.float8_e4m3fn and (gu.shape[-1] // 2) % 128 == 0:
|
|
245
|
+
# Pure-Triton fused SwiGLU + 1x128 block-FP8 activation quant -> block GEMM!
|
|
246
|
+
mid_q, mid_s = llama_kernels.swiglu_fp8_block(gu)
|
|
247
|
+
w, ws, b = down_p
|
|
248
|
+
y = fp8block.gemm(mid_q.reshape(-1, mid_q.shape[-1]), mid_s, w, ws, dt)
|
|
249
|
+
if b is not None:
|
|
250
|
+
y = y + b.to(dt)
|
|
251
|
+
mlp_out = y.reshape(*gu.shape[:-1], w.shape[0])
|
|
252
|
+
else:
|
|
253
|
+
mlp_out = _linear(llama_kernels.swiglu(gu), down_p)
|
|
254
|
+
return h, mlp_out
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def _last_layer_kv(h, res, P, C, cos, sin, kb, vb, pk, pv):
|
|
258
|
+
"""Last layer (N - 1) pre-attention: compute updated residual `h`, normalized `x`, and K/V for all tokens."""
|
|
259
|
+
h, x = llama_kernels.add_rmsnorm(h, res, P["ln1"], C.eps)
|
|
260
|
+
if "kv" in P:
|
|
261
|
+
k, v = llama_kernels.kv_rope(_linear(x, P["kv"]), cos, sin, C.kv_heads, C.d)
|
|
262
|
+
else:
|
|
263
|
+
k, v = llama_kernels.kv_rope(torch.cat([_linear(x, P["k"]), _linear(x, P["v"])], -1), cos, sin, C.kv_heads, C.d)
|
|
264
|
+
if kb is not None:
|
|
265
|
+
kb.copy_(k.transpose(1, 2))
|
|
266
|
+
vb.copy_(v.transpose(1, 2))
|
|
267
|
+
if pk is not None:
|
|
268
|
+
k = torch.cat([pk.transpose(1, 2), k], dim=1)
|
|
269
|
+
v = torch.cat([pv.transpose(1, 2), v], dim=1)
|
|
270
|
+
return h, x, k, v
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def _last_layer_readout(h_ro, x_ro, k, v, P, C, cos_ro, sin_ro, meta, norm_w):
|
|
274
|
+
"""Last layer (N - 1) readout-only execution: Q_proj, RoPE(Q), readout attention, O_proj, MLP, and final norm
|
|
275
|
+
on the R readout rows ONLY!"""
|
|
276
|
+
dt = h_ro.dtype
|
|
277
|
+
q = llama_kernels.q_rope(_linear(x_ro, P["q"]), cos_ro, sin_ro, C.heads, C.d)
|
|
278
|
+
a = _attend_nhd(q, k, v, C.scale, meta)
|
|
279
|
+
attn_out = _linear(a, P["o"])
|
|
280
|
+
h_ro, x2 = llama_kernels.add_rmsnorm(h_ro, attn_out, P["ln2"], C.eps)
|
|
281
|
+
if "gu" in P:
|
|
282
|
+
gu = _linear(x2, P["gu"])
|
|
283
|
+
else:
|
|
284
|
+
gu = torch.cat([_linear(x2, P["gate"]), _linear(x2, P["up"])], -1)
|
|
285
|
+
down_p = P["down"]
|
|
286
|
+
xs_d = _static_fp8_input_scale(down_p)
|
|
287
|
+
if xs_d is not None:
|
|
288
|
+
mlp_out = _linear_q_fp8(llama_kernels.swiglu_fp8(gu, xs_d), down_p, dt)
|
|
289
|
+
else:
|
|
290
|
+
mlp_out = _linear(llama_kernels.swiglu(gu), down_p)
|
|
291
|
+
_, out = llama_kernels.add_rmsnorm(h_ro, mlp_out, norm_w, C.eps)
|
|
292
|
+
return out
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
class LlamaGraph:
|
|
296
|
+
"""Pure-Triton Llama / Bielik 3.0 execution engine for GraphBackend."""
|
|
297
|
+
|
|
298
|
+
def __init__(self, model, compile=False, merge=True, fp8=None, fp8_bf16_layers=2, bidir_layers=None,
|
|
299
|
+
stream=None, deterministic=False):
|
|
300
|
+
if not is_llama(model):
|
|
301
|
+
raise ValueError("LlamaGraph requires a standard LlamaForCausalLM decoder with SiLU MLP")
|
|
302
|
+
self.lm = model.model
|
|
303
|
+
self.cfg = cfg = model.config
|
|
304
|
+
self.layers = list(self.lm.layers[: cfg.num_hidden_layers])
|
|
305
|
+
n = len(self.layers)
|
|
306
|
+
self.H = cfg.num_attention_heads
|
|
307
|
+
self.Hkv = cfg.num_key_value_heads
|
|
308
|
+
self.d = getattr(cfg, "head_dim", None) or cfg.hidden_size // self.H
|
|
309
|
+
self.eps = cfg.rms_norm_eps
|
|
310
|
+
self.scale = self.d ** -0.5
|
|
311
|
+
self.kv_shapes = [(self.Hkv, self.d)] * n
|
|
312
|
+
self.softcap = None
|
|
313
|
+
self.last_idx = n - 1
|
|
314
|
+
# Per-layer bidirectional flag (None = all layers participate when tw/twl is passed)
|
|
315
|
+
if bidir_layers is None:
|
|
316
|
+
self.bidir_layer = [True] * n
|
|
317
|
+
else:
|
|
318
|
+
bset = set(bidir_layers)
|
|
319
|
+
self.bidir_layer = [i in bset for i in range(n)]
|
|
320
|
+
# Precompute fp32 RoPE cos/sin tables up to max_position_embeddings
|
|
321
|
+
dev = self.lm.embed_tokens.weight.device
|
|
322
|
+
dt = self.lm.embed_tokens.weight.dtype
|
|
323
|
+
rope = self.lm.rotary_emb
|
|
324
|
+
max_pos = getattr(cfg, "max_position_embeddings", 32768)
|
|
325
|
+
f = torch.outer(torch.arange(max_pos, device=dev, dtype=torch.float32), rope.inv_freq.float().to(dev))
|
|
326
|
+
e = torch.cat([f, f], -1)
|
|
327
|
+
s = getattr(rope, "attention_scaling", 1.0)
|
|
328
|
+
self.cos = (e.cos() * s).to(dt)
|
|
329
|
+
self.sin = (e.sin() * s).to(dt)
|
|
330
|
+
self.qkv, self.kv_last, self.gu = {}, None, {}
|
|
331
|
+
if stream is None:
|
|
332
|
+
self.merged = self._merge() if merge else 0
|
|
333
|
+
self.fp8 = self._quant_block(fp8_bf16_layers, int8=fp8 == "int8") if fp8 in ("block", "int8") else 0
|
|
334
|
+
else:
|
|
335
|
+
self.merged = self.fp8 = 0
|
|
336
|
+
for i, layer in enumerate(self.layers):
|
|
337
|
+
layer.to(stream)
|
|
338
|
+
self.merged += self._merge([i]) if merge else 0
|
|
339
|
+
if fp8 in ("block", "int8"):
|
|
340
|
+
self.fp8 += self._quant_block(fp8_bf16_layers, [i], int8=fp8 == "int8")
|
|
341
|
+
self.args = self._layer_args()
|
|
342
|
+
if dev.type == "cuda":
|
|
343
|
+
llama_attn.prepare()
|
|
344
|
+
llama_kernels.prepare()
|
|
345
|
+
self.compiled = bool(compile)
|
|
346
|
+
if self.compiled:
|
|
347
|
+
from .engine import compile_llama
|
|
348
|
+
fk = llama_kernels.fp8_rows_cache_key()
|
|
349
|
+
self.step_fn = compile_llama(_layer_step, dynamic=True, deterministic=deterministic, extra_key=fk)
|
|
350
|
+
self.last_kv_fn = compile_llama(_last_layer_kv, dynamic=True, deterministic=deterministic, extra_key=fk)
|
|
351
|
+
self.last_ro_fn = compile_llama(_last_layer_readout, dynamic=True, deterministic=deterministic, extra_key=fk)
|
|
352
|
+
else:
|
|
353
|
+
self.step_fn = _layer_step
|
|
354
|
+
self.last_kv_fn = _last_layer_kv
|
|
355
|
+
self.last_ro_fn = _last_layer_readout
|
|
356
|
+
|
|
357
|
+
@staticmethod
|
|
358
|
+
def _fuse_plain(mods):
|
|
359
|
+
"""Merge plain nn.Linear modules preserving optional biases (Bielik 1.5B & 4.5B have bias=True)."""
|
|
360
|
+
w, sizes = blockquant.fuse(mods)
|
|
361
|
+
if all(m.bias is None for m in mods):
|
|
362
|
+
b = None
|
|
363
|
+
elif any(m.bias is None for m in mods):
|
|
364
|
+
raise ValueError("cannot fuse biased and unbiased linear modules together")
|
|
365
|
+
else:
|
|
366
|
+
b = torch.cat([m.bias.detach() for m in mods])
|
|
367
|
+
for m, part in zip(mods, b.split(sizes)):
|
|
368
|
+
m.bias = torch.nn.Parameter(part, requires_grad=False)
|
|
369
|
+
lin = torch.nn.Linear(w.shape[1], w.shape[0], bias=b is not None, device="meta", dtype=w.dtype)
|
|
370
|
+
lin.weight = torch.nn.Parameter(w, requires_grad=False)
|
|
371
|
+
if b is not None:
|
|
372
|
+
lin.bias = torch.nn.Parameter(b, requires_grad=False)
|
|
373
|
+
return lin, sizes
|
|
374
|
+
|
|
375
|
+
@torch.no_grad()
|
|
376
|
+
def _merge(self, layers=None):
|
|
377
|
+
"""Merge projections per layer:
|
|
378
|
+
- Layers 0 .. N-2: q/k/v -> qkv_proj, gate/up -> gate_up_proj
|
|
379
|
+
- Last layer N-1: k/v -> kv_proj (q_proj stays separate for readout-only slicing!), gate/up -> gate_up_proj
|
|
380
|
+
Supports plain BF16/FP32 linears (with or without biases) AND ModelOpt FP8Linear (lossless per-column merge)."""
|
|
381
|
+
from .engine import FP8Linear
|
|
382
|
+
|
|
383
|
+
def can_plain(mods):
|
|
384
|
+
return (all(type(x) is torch.nn.Linear for x in mods)
|
|
385
|
+
and len({x.weight.dtype for x in mods}) == 1
|
|
386
|
+
and len({x.bias is None for x in mods}) == 1)
|
|
387
|
+
|
|
388
|
+
def merge_group(mods):
|
|
389
|
+
if can_plain(mods):
|
|
390
|
+
return self._fuse_plain(mods)
|
|
391
|
+
if all(isinstance(x, FP8Linear) for x in mods):
|
|
392
|
+
m = llama_kernels.LosslessMergedFP8Linear.from_fp8_linears(mods)
|
|
393
|
+
if m is not None:
|
|
394
|
+
return m, [x.out_features for x in mods]
|
|
395
|
+
return None
|
|
396
|
+
|
|
397
|
+
n = 0
|
|
398
|
+
for i in (range(len(self.layers)) if layers is None else layers):
|
|
399
|
+
layer = self.layers[i]
|
|
400
|
+
a, m = layer.self_attn, layer.mlp
|
|
401
|
+
did = False
|
|
402
|
+
if i == self.last_idx:
|
|
403
|
+
res = merge_group([a.k_proj, a.v_proj])
|
|
404
|
+
if res is not None:
|
|
405
|
+
self.kv_last = res
|
|
406
|
+
did = True
|
|
407
|
+
else:
|
|
408
|
+
res = merge_group([a.q_proj, a.k_proj, a.v_proj])
|
|
409
|
+
if res is not None:
|
|
410
|
+
self.qkv[i] = res
|
|
411
|
+
did = True
|
|
412
|
+
res_gu = merge_group([m.gate_proj, m.up_proj])
|
|
413
|
+
if res_gu is not None:
|
|
414
|
+
self.gu[i] = res_gu
|
|
415
|
+
did = True
|
|
416
|
+
n += int(did)
|
|
417
|
+
if torch.cuda.is_available():
|
|
418
|
+
torch.cuda.empty_cache()
|
|
419
|
+
return n
|
|
420
|
+
|
|
421
|
+
@torch.no_grad()
|
|
422
|
+
def _quant_block(self, keep=2, layers=None, int8=False):
|
|
423
|
+
"""Pure-Triton 128x128 Block-FP8 (or Block-INT8) quantization for Llama layers (preserving biases on 1.5B/4.5B).
|
|
424
|
+
Every Bielik 3.0 projection dimension (1536, 2048, 4096, 256, 1024, 8960, 11008, 14336) is a multiple of 128."""
|
|
425
|
+
cls = int8block.Int8BlockLinear if int8 else fp8block.BlockFP8Linear
|
|
426
|
+
if int8:
|
|
427
|
+
int8block.build()
|
|
428
|
+
else:
|
|
429
|
+
fp8block.FORMAT.build() # pure Triton (no FlashInfer dependency required)
|
|
430
|
+
n = 0
|
|
431
|
+
|
|
432
|
+
def ok_merged(pair):
|
|
433
|
+
return pair is not None and blockquant.fits(pair[0]) and all(k % blockquant.BLOCK == 0 for k in pair[1])
|
|
434
|
+
|
|
435
|
+
def quant_merged(lin, sizes, mod, names):
|
|
436
|
+
f, o = cls.of(lin), 0
|
|
437
|
+
for name, k in zip(names, sizes):
|
|
438
|
+
setattr(mod, name, f.part(o, k))
|
|
439
|
+
o += k
|
|
440
|
+
return f
|
|
441
|
+
|
|
442
|
+
for i in (range(len(self.layers)) if layers is None else layers):
|
|
443
|
+
if i < keep or i >= len(self.layers) - keep:
|
|
444
|
+
continue
|
|
445
|
+
layer = self.layers[i]
|
|
446
|
+
a, m = layer.self_attn, layer.mlp
|
|
447
|
+
if i == self.last_idx:
|
|
448
|
+
if ok_merged(self.kv_last):
|
|
449
|
+
self.kv_last = (quant_merged(self.kv_last[0], self.kv_last[1], a, ["k_proj", "v_proj"]),
|
|
450
|
+
self.kv_last[1])
|
|
451
|
+
n += 1
|
|
452
|
+
if blockquant.fits(a.q_proj):
|
|
453
|
+
a.q_proj = cls.of(a.q_proj)
|
|
454
|
+
n += 1
|
|
455
|
+
elif ok_merged(self.qkv.get(i)):
|
|
456
|
+
self.qkv[i] = (quant_merged(self.qkv[i][0], self.qkv[i][1], a, ["q_proj", "k_proj", "v_proj"]),
|
|
457
|
+
self.qkv[i][1])
|
|
458
|
+
n += 1
|
|
459
|
+
elif i not in self.qkv:
|
|
460
|
+
for name in ("q_proj", "k_proj", "v_proj"):
|
|
461
|
+
if blockquant.fits(getattr(a, name)):
|
|
462
|
+
setattr(a, name, cls.of(getattr(a, name)))
|
|
463
|
+
n += 1
|
|
464
|
+
if ok_merged(self.gu.get(i)):
|
|
465
|
+
self.gu[i] = (quant_merged(self.gu[i][0], self.gu[i][1], m, ["gate_proj", "up_proj"]), self.gu[i][1])
|
|
466
|
+
n += 1
|
|
467
|
+
elif i not in self.gu:
|
|
468
|
+
for name in ("gate_proj", "up_proj"):
|
|
469
|
+
if blockquant.fits(getattr(m, name)):
|
|
470
|
+
setattr(m, name, cls.of(getattr(m, name)))
|
|
471
|
+
n += 1
|
|
472
|
+
for mod, name in ((a, "o_proj"), (m, "down_proj")):
|
|
473
|
+
if blockquant.fits(getattr(mod, name)):
|
|
474
|
+
setattr(mod, name, cls.of(getattr(mod, name)))
|
|
475
|
+
n += 1
|
|
476
|
+
if torch.cuda.is_available():
|
|
477
|
+
torch.cuda.empty_cache()
|
|
478
|
+
return n
|
|
479
|
+
|
|
480
|
+
def _layer_args(self):
|
|
481
|
+
out = []
|
|
482
|
+
for i, layer in enumerate(self.layers):
|
|
483
|
+
a, m = layer.self_attn, layer.mlp
|
|
484
|
+
P = dict(ln1=layer.input_layernorm.weight, ln2=layer.post_attention_layernorm.weight,
|
|
485
|
+
o=_params(a.o_proj), down=_params(m.down_proj))
|
|
486
|
+
if i == self.last_idx:
|
|
487
|
+
P["q"] = _params(a.q_proj)
|
|
488
|
+
if self.kv_last is not None:
|
|
489
|
+
P["kv"] = _params(self.kv_last[0])
|
|
490
|
+
else:
|
|
491
|
+
P["k"], P["v"] = _params(a.k_proj), _params(a.v_proj)
|
|
492
|
+
elif i in self.qkv:
|
|
493
|
+
P["qkv"] = _params(self.qkv[i][0])
|
|
494
|
+
else:
|
|
495
|
+
P["q"], P["k"], P["v"] = _params(a.q_proj), _params(a.k_proj), _params(a.v_proj)
|
|
496
|
+
if i in self.gu:
|
|
497
|
+
P["gu"] = _params(self.gu[i][0])
|
|
498
|
+
else:
|
|
499
|
+
P["gate"], P["up"] = _params(m.gate_proj), _params(m.up_proj)
|
|
500
|
+
out.append((P, LlamaLayerC(self.H, self.Hkv, self.d, self.eps, self.scale, self.bidir_layer[i])))
|
|
501
|
+
return out
|
|
502
|
+
|
|
503
|
+
def _rope_for(self, pos):
|
|
504
|
+
"""pos [B, L] -> (cos [B, L, D], sin [B, L, D])."""
|
|
505
|
+
return self.cos[pos], self.sin[pos]
|
|
506
|
+
|
|
507
|
+
def _run_core(self, ids, pos, meta_all, meta_ro, kv=None, prefix=None, ro=None, between=None,
|
|
508
|
+
compiled=True, kv_only=False, tw=None):
|
|
509
|
+
"""Unified forward core for plain, flat, compact, and pass-2 suffix execution."""
|
|
510
|
+
use_c = compiled and self.compiled and between is None
|
|
511
|
+
step = self.step_fn if use_c else _layer_step
|
|
512
|
+
last_kv = self.last_kv_fn if use_c else _last_layer_kv
|
|
513
|
+
last_ro = self.last_ro_fn if use_c else _last_layer_readout
|
|
514
|
+
h = self.lm.embed_tokens(ids)
|
|
515
|
+
res = None
|
|
516
|
+
cos, sin = self._rope_for(pos)
|
|
517
|
+
for i in range(self.last_idx):
|
|
518
|
+
if between is not None:
|
|
519
|
+
between(i)
|
|
520
|
+
P, C = self.args[i]
|
|
521
|
+
kb, vb = kv[i] if kv is not None else (None, None)
|
|
522
|
+
pk, pv = prefix[i] if prefix is not None else (None, None)
|
|
523
|
+
m = dict(meta_all, tw=tw) if (tw is not None and C.bidir) else meta_all
|
|
524
|
+
h, res = step(h, res, P, C, cos, sin, kb, vb, pk, pv, m)
|
|
525
|
+
# Last layer (N - 1): K/V on all tokens, then early-stop (Pass 1 kv_only) or readout-only slicing!
|
|
526
|
+
if between is not None:
|
|
527
|
+
between(self.last_idx)
|
|
528
|
+
P, C = self.args[self.last_idx]
|
|
529
|
+
kb, vb = kv[self.last_idx] if kv is not None else (None, None)
|
|
530
|
+
pk, pv = prefix[self.last_idx] if prefix is not None else (None, None)
|
|
531
|
+
h, x, k, v = last_kv(h, res, P, C, cos, sin, kb, vb, pk, pv)
|
|
532
|
+
if kv_only:
|
|
533
|
+
return None
|
|
534
|
+
if ro is not None:
|
|
535
|
+
g = ro[:, :, None]
|
|
536
|
+
h_ro = h.gather(1, g.expand(-1, -1, h.shape[-1]))
|
|
537
|
+
x_ro = x.gather(1, g.expand(-1, -1, x.shape[-1]))
|
|
538
|
+
cos_ro = cos.gather(1, g.expand(-1, -1, cos.shape[-1]))
|
|
539
|
+
sin_ro = sin.gather(1, g.expand(-1, -1, sin.shape[-1]))
|
|
540
|
+
m_ro = dict(meta_ro, qi=ro, tw=tw) if (tw is not None and C.bidir) else dict(meta_ro, qi=ro)
|
|
541
|
+
return last_ro(h_ro, x_ro, k, v, P, C, cos_ro, sin_ro, m_ro, self.lm.norm.weight)
|
|
542
|
+
m_full = dict(meta_all, tw=tw) if (tw is not None and C.bidir) else meta_all
|
|
543
|
+
return last_ro(h, x, k, v, P, C, cos, sin, m_full, self.lm.norm.weight)
|
|
544
|
+
|
|
545
|
+
@torch.no_grad()
|
|
546
|
+
def forward(self, ids, kv=None, ro=None, between=None, compiled=True, twl=None, kv_only=False):
|
|
547
|
+
"""Plain rows [B, L] from position 0: causal, two_way, or prefix_bidir (twl [B]: last bidir token, -1 = causal).
|
|
548
|
+
kv_only=True (Pass 1 root): fills kv[0..N-1] and skips layer N-1 Q/Attn/O/MLP/norm!
|
|
549
|
+
ro [B, R]: readout positions -> [B, R, D] (None -> [B, L, D])."""
|
|
550
|
+
B, L = ids.shape
|
|
551
|
+
pos = torch.arange(L, device=ids.device)[None].expand(B, L)
|
|
552
|
+
tw = (twl + 1).clamp(min=0) if twl is not None else None
|
|
553
|
+
meta_all = {}
|
|
554
|
+
meta_ro = {"splitk": True}
|
|
555
|
+
return self._run_core(ids, pos, meta_all, meta_ro, kv=kv, ro=ro, between=between,
|
|
556
|
+
compiled=compiled, kv_only=kv_only, tw=tw)
|
|
557
|
+
|
|
558
|
+
@torch.no_grad()
|
|
559
|
+
def forward_flat(self, ids, pos, start, prq, se, ro, tw=None, between=None, compiled=True):
|
|
560
|
+
"""Single-Pass Flat SOAM: arbitrary single prompts, multi-question prefix tries, two_way, and prefix_bidir
|
|
561
|
+
units packed back-to-back in ONE row [1, T] -> [R, D] at readout indices ro [R].
|
|
562
|
+
Weights are read ONCE from HBM; zero KV copy; last-layer Q/Attn/O/MLP run on R readout rows ONLY!"""
|
|
563
|
+
meta_all = dict(start=start, pr=prq, se=se)
|
|
564
|
+
meta_ro = dict(start=start, pr=prq, se=se, splitk=True)
|
|
565
|
+
out = self._run_core(ids, pos, meta_all, meta_ro, ro=ro[None], between=between, compiled=compiled, tw=tw)
|
|
566
|
+
return out[0]
|
|
567
|
+
|
|
568
|
+
@torch.no_grad()
|
|
569
|
+
def forward_compact(self, ids, pos, cu, ro, compiled=True):
|
|
570
|
+
"""Compact single prompts packed back-to-back in [1, T] (cu: cumulative lengths) -> [R, D] at ro [R]."""
|
|
571
|
+
T = ids.shape[1]
|
|
572
|
+
doc = torch.bucketize(torch.arange(T, device=ids.device), cu[1:], right=True)
|
|
573
|
+
start = cu[doc].long()
|
|
574
|
+
meta_all = dict(start=start)
|
|
575
|
+
meta_ro = dict(start=start, splitk=True)
|
|
576
|
+
out = self._run_core(ids, pos, meta_all, meta_ro, ro=ro[None], compiled=compiled)
|
|
577
|
+
return out[0]
|
|
578
|
+
|
|
579
|
+
@torch.no_grad()
|
|
580
|
+
def forward_suffix(self, ids, mask, pos, prefix, ro=None, compiled=True, kv=None):
|
|
581
|
+
"""Pass 2 over cached root KV: ids [B, S], mask = TreeMask(pr, s, anc), pos [B, S],
|
|
582
|
+
prefix = per-layer (K, V) [B, Hkv, P, D] -> [B, R, D] at ro [B, R] (or [B, S, D] when ro is None)."""
|
|
583
|
+
if not isinstance(mask, TreeMask):
|
|
584
|
+
raise ValueError("LlamaGraph.forward_suffix expects a TreeMask (zero dense masks)")
|
|
585
|
+
nr = prefix[0][0].shape[2]
|
|
586
|
+
meta = dict(nr=nr, pr=mask.pr, sb=mask.s, anc=mask.anc)
|
|
587
|
+
return self._run_core(ids, pos, meta, meta, kv=kv, prefix=prefix, ro=ro, compiled=compiled)
|