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/mlx_forward.py
ADDED
|
@@ -0,0 +1,326 @@
|
|
|
1
|
+
"""The opt-in decoder forward of the MLX backend (basal 2.5, --mlx-forward basal): the layers of the mlx-lm model (the
|
|
2
|
+
same modules and weights) in basal's own loop, for the Llama decoders (basal-1.x, 2.x) and Gemma 4 (basal-omni). What
|
|
3
|
+
mlx-lm's forward does not do:
|
|
4
|
+
|
|
5
|
+
- **Readout rows only.** From the last layer with its own keys and values on, a layer's output matters only at the
|
|
6
|
+
readout positions (the last token of each prompt). That layer computes its keys and values at every position, and its
|
|
7
|
+
queries, attention, output projection and MLP at the readout rows only; Gemma 4 E2B / E4B reuse the keys and values of
|
|
8
|
+
earlier layers in the layers after it (E4B: the last 18 of 42), which run at the readout rows only as well. A shared
|
|
9
|
+
prefix stops after the keys and values of that layer. A readout row's query sees the same keys through the same mask
|
|
10
|
+
row, as a row of its own, so its probabilities equal the full forward's up to float rounding.
|
|
11
|
+
- **Early start.** mx.async_eval after the first layer and then every ASYNC_EVERY layers: the GPU runs the first layers
|
|
12
|
+
while Python builds the graph of the rest.
|
|
13
|
+
- **Merged projections, checked at load.** The gate and up projections (and q / k / v) become one matrix each, made at
|
|
14
|
+
load; the separate modules keep views of it, so the weights take no extra memory. Every merged product is compared
|
|
15
|
+
with the separate ones bit for bit, on the real weights of one layer of each shape and on CHECK_ROWS (1 to 4,096
|
|
16
|
+
rows); a merge whose bits differ anywhere is undone (MLX picks its matmul kernel by shape, so a wider matrix can sum
|
|
17
|
+
in another order).
|
|
18
|
+
|
|
19
|
+
The layers before that last own-key layer compute what mlx-lm's do, op for op (bit-identical with no merge or a merge
|
|
20
|
+
that passed its check). Other architectures, and Llama models with sliding windows or a RoPE whose frequencies depend on
|
|
21
|
+
the sequence length, keep mlx-lm's forward (build returns None).
|
|
22
|
+
"""
|
|
23
|
+
import mlx.core as mx
|
|
24
|
+
import mlx.nn as nn
|
|
25
|
+
from mlx_lm.models import gemma4_text, llama
|
|
26
|
+
from mlx_lm.models.activations import swiglu
|
|
27
|
+
from mlx_lm.models.base import create_causal_mask, scaled_dot_product_attention
|
|
28
|
+
from mlx_lm.models.rope_utils import Llama3RoPE, ProportionalRoPE
|
|
29
|
+
|
|
30
|
+
STATIC_ROPES = (nn.RoPE, Llama3RoPE, ProportionalRoPE) # frequencies independent of the sequence length
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def bits_equal(a, b):
|
|
34
|
+
"""Same shape, dtype and bits in every element."""
|
|
35
|
+
if a.shape != b.shape or a.dtype != b.dtype:
|
|
36
|
+
return False
|
|
37
|
+
view = {2: mx.uint16, 4: mx.uint32}.get(a.dtype.size)
|
|
38
|
+
if view is None:
|
|
39
|
+
return bool(mx.array_equal(a, b).item())
|
|
40
|
+
return bool(mx.all(mx.contiguous(a).view(view) == mx.contiguous(b).view(view)).item())
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _stacked(mods):
|
|
44
|
+
"""One linear layer of the class of mods[0] whose arrays (weight; scales and biases when quantised; bias) are those
|
|
45
|
+
of mods stacked along the output dimension; None if they do not stack."""
|
|
46
|
+
m0 = mods[0]
|
|
47
|
+
if any(type(m) is not type(m0) or set(m.keys()) != set(m0.keys()) for m in mods):
|
|
48
|
+
return None
|
|
49
|
+
if any(getattr(m, k, None) != getattr(m0, k, None) for m in mods for k in ("group_size", "bits", "mode")):
|
|
50
|
+
return None
|
|
51
|
+
new = type(m0).__new__(type(m0))
|
|
52
|
+
nn.Module.__init__(new)
|
|
53
|
+
for k in ("group_size", "bits", "mode"):
|
|
54
|
+
if hasattr(m0, k):
|
|
55
|
+
setattr(new, k, getattr(m0, k))
|
|
56
|
+
for k, v in m0.items():
|
|
57
|
+
if not isinstance(v, mx.array) or v.ndim == 0 or any(m[k].shape[1:] != v.shape[1:] for m in mods):
|
|
58
|
+
return None
|
|
59
|
+
new[k] = mx.concatenate([m[k] for m in mods], axis=0)
|
|
60
|
+
mx.eval(new.parameters())
|
|
61
|
+
return new
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _signature(mods):
|
|
65
|
+
"""What decides the matmul kernels of a group: classes, quantisation and array shapes / dtypes."""
|
|
66
|
+
return tuple((type(m).__name__, getattr(m, "bits", None), getattr(m, "group_size", None), getattr(m, "mode", None),
|
|
67
|
+
tuple((k, v.shape, str(v.dtype)) for k, v in sorted(m.items()) if isinstance(v, mx.array)))
|
|
68
|
+
for m in mods)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class _Group:
|
|
72
|
+
"""Linear layers that read the same input: one product of the merged layer (split), or one product each."""
|
|
73
|
+
|
|
74
|
+
def __init__(self, label, mods):
|
|
75
|
+
self.label, self.mods, self.cat = label, list(mods), None
|
|
76
|
+
sizes = [m["weight"].shape[0] for m in self.mods]
|
|
77
|
+
self.cuts = [sum(sizes[: k + 1]) for k in range(len(sizes) - 1)]
|
|
78
|
+
|
|
79
|
+
def __call__(self, x):
|
|
80
|
+
if self.cat is None:
|
|
81
|
+
return [m(x) for m in self.mods]
|
|
82
|
+
return mx.split(self.cat(x), self.cuts, axis=-1)
|
|
83
|
+
|
|
84
|
+
def merge(self, cat):
|
|
85
|
+
"""Use the merged layer; the separate layers keep views of its arrays (the old arrays are released)."""
|
|
86
|
+
self.cat, start = cat, 0
|
|
87
|
+
for m, end in zip(self.mods, self.cuts + [None]):
|
|
88
|
+
for k in list(m.keys()):
|
|
89
|
+
if isinstance(m[k], mx.array):
|
|
90
|
+
m[k] = cat[k][start:end]
|
|
91
|
+
start = end
|
|
92
|
+
mx.eval([m.parameters() for m in self.mods])
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
class MLXForward:
|
|
96
|
+
"""The forward over the layers of an mlx-lm Llama or Gemma 4 text model (see the module docstring)."""
|
|
97
|
+
|
|
98
|
+
ASYNC_EVERY = 4
|
|
99
|
+
# (rows, tokens) of the self-check inputs: the one-row and batched calls of the backend, 1 to 4,096 rows per product
|
|
100
|
+
CHECK_ROWS = ((1, 1), (3, 1), (8, 1), (16, 1), (1, 9), (2, 16), (1, 64), (16, 24), (1, 255), (4, 128), (1, 1000),
|
|
101
|
+
(8, 256), (1, 2048), (1, 4096))
|
|
102
|
+
|
|
103
|
+
@classmethod
|
|
104
|
+
def build(cls, lm, merge=True):
|
|
105
|
+
"""The forward of this mlx-lm model, or None when it keeps mlx-lm's (another architecture, sliding windows on
|
|
106
|
+
Llama, a RoPE that depends on the sequence length)."""
|
|
107
|
+
if isinstance(lm, llama.Model):
|
|
108
|
+
if lm.model.swa_idx is not None:
|
|
109
|
+
return None
|
|
110
|
+
elif not isinstance(lm, gemma4_text.Model):
|
|
111
|
+
return None
|
|
112
|
+
if not all(type(layer.self_attn.rope) in STATIC_ROPES for layer in lm.model.layers):
|
|
113
|
+
return None
|
|
114
|
+
return cls(lm, merge)
|
|
115
|
+
|
|
116
|
+
def __init__(self, lm, merge=True):
|
|
117
|
+
self.m = lm.model
|
|
118
|
+
self.layers = list(self.m.layers)
|
|
119
|
+
n = len(self.layers)
|
|
120
|
+
self.gemma = isinstance(lm, gemma4_text.Model)
|
|
121
|
+
if self.gemma:
|
|
122
|
+
self.own = [layer.self_attn.has_kv for layer in self.layers]
|
|
123
|
+
self.prev = list(self.m.previous_kvs)
|
|
124
|
+
self.types = [layer.layer_type for layer in self.layers]
|
|
125
|
+
else:
|
|
126
|
+
self.own, self.prev, self.types = [True] * n, list(range(n)), ["full_attention"] * n
|
|
127
|
+
self.last = max(i for i in range(n) if self.own[i]) # from this layer on: the readout rows only
|
|
128
|
+
# the projections that read the same input: q / k / v of an own-key layer (k / v in the last one, whose
|
|
129
|
+
# queries are the readout rows'; k alone with Gemma's attention_k_eq_v), gate / up of every MLP
|
|
130
|
+
self.qkv, self.gu = [], []
|
|
131
|
+
for i, layer in enumerate(self.layers):
|
|
132
|
+
a = layer.self_attn
|
|
133
|
+
names = ["q_proj", "k_proj", "v_proj"]
|
|
134
|
+
if self.gemma and a.use_k_eq_v:
|
|
135
|
+
names.remove("v_proj")
|
|
136
|
+
if i == self.last:
|
|
137
|
+
names.remove("q_proj")
|
|
138
|
+
self.qkv.append(_Group("k/v" if i == self.last else "q/k/v", [getattr(a, k) for k in names])
|
|
139
|
+
if self.own[i] else None)
|
|
140
|
+
self.gu.append(_Group("gate/up", [layer.mlp.gate_proj, layer.mlp.up_proj]))
|
|
141
|
+
self.checks = {} # group label -> "merged" or why it was kept
|
|
142
|
+
if merge:
|
|
143
|
+
self._merge()
|
|
144
|
+
|
|
145
|
+
# ---- merged projections and their self-check -------------------------------------------------------------------
|
|
146
|
+
|
|
147
|
+
def _check(self, mods, cat, cuts, dim, dtype):
|
|
148
|
+
""""merged" if the merged product equals the separate ones bit for bit on every CHECK_ROWS input."""
|
|
149
|
+
key = mx.random.key(0)
|
|
150
|
+
for B, L in self.CHECK_ROWS:
|
|
151
|
+
key, sub = mx.random.split(key)
|
|
152
|
+
x = mx.random.normal((B, L, dim), key=sub).astype(dtype)
|
|
153
|
+
got = mx.split(cat(x), cuts, axis=-1)
|
|
154
|
+
if not all(bits_equal(g, m(x)) for g, m in zip(got, mods)):
|
|
155
|
+
return f"kept (bits differ at {B} x {L})"
|
|
156
|
+
return "merged"
|
|
157
|
+
|
|
158
|
+
def _merge(self):
|
|
159
|
+
"""Merges every group of two or more projections whose shape signature passed the self-check (run once per
|
|
160
|
+
signature, on the first layer that has it)."""
|
|
161
|
+
verdict = {}
|
|
162
|
+
dtype = self.layers[0].input_layernorm.weight.dtype
|
|
163
|
+
for i, g in [(i, g) for groups in (self.qkv, self.gu) for i, g in enumerate(groups)]:
|
|
164
|
+
if g is None or len(g.mods) < 2:
|
|
165
|
+
continue
|
|
166
|
+
sig = _signature(g.mods)
|
|
167
|
+
cat = _stacked(g.mods) if verdict.get(sig, "merged") == "merged" else None
|
|
168
|
+
if sig not in verdict:
|
|
169
|
+
verdict[sig] = "kept (does not stack)" if cat is None else \
|
|
170
|
+
self._check(g.mods, cat, g.cuts, self.layers[i].input_layernorm.weight.shape[0], dtype)
|
|
171
|
+
if cat is not None and verdict[sig] == "merged":
|
|
172
|
+
g.merge(cat)
|
|
173
|
+
if self.checks.get(g.label, "merged") == "merged":
|
|
174
|
+
self.checks[g.label] = verdict[sig]
|
|
175
|
+
|
|
176
|
+
def describe(self):
|
|
177
|
+
"""One line for the start-up message."""
|
|
178
|
+
merged = ", ".join(f"{k} {v}" for k, v in self.checks.items())
|
|
179
|
+
return f"readout rows from layer {self.last + 1} of {len(self.layers)}" + (f"; {merged}" if merged else "")
|
|
180
|
+
|
|
181
|
+
# ---- the forward ---------------------------------------------------------------------------------------------
|
|
182
|
+
|
|
183
|
+
def prefix(self, ids, past=None):
|
|
184
|
+
"""ids [1, P] -> per own-key layer up to the last one, (keys, values) [1, H, P, D] of every position; nothing
|
|
185
|
+
after the last one's keys and values runs. past: those of the tokens before ids (M of them, a cached state),
|
|
186
|
+
which the forward continues (positions from M) -> keys / values of all M + P positions."""
|
|
187
|
+
out = []
|
|
188
|
+
self._run(ids, None, past, None, None, out)
|
|
189
|
+
return out
|
|
190
|
+
|
|
191
|
+
def hidden(self, ids, ro, past=None, pos=None, mask=None, full=False):
|
|
192
|
+
"""ids [B, L] right-padded rows -> final-norm hidden states [B, R, D] at the token indices ro [B, R] of each
|
|
193
|
+
row. past: per own-key layer (keys, values) [1, H, P, D] of a prefix every row continues (positions from P).
|
|
194
|
+
pos / mask: packed rows (no past): positions [B, L] and the boolean block mask [B, 1, L, L]. full: every
|
|
195
|
+
layer at every position and the rows taken after the final norm, as mlx-lm's forward (for checks)."""
|
|
196
|
+
return self._run(ids, ro, past, pos, mask, None, full)
|
|
197
|
+
|
|
198
|
+
def _run(self, ids, ro, past, pos, mask, kv_out, full=False):
|
|
199
|
+
m = self.m
|
|
200
|
+
B, L = ids.shape
|
|
201
|
+
cached = past is not None or kv_out is not None # mlx-lm with a KV cache: its masks and RoPE offsets
|
|
202
|
+
P = past[0][0].shape[2] if past is not None else 0
|
|
203
|
+
h = m.embed_tokens(ids)
|
|
204
|
+
pli = [None] * len(self.layers)
|
|
205
|
+
if self.gemma:
|
|
206
|
+
emb, h = h, h * m.embed_scale
|
|
207
|
+
if m.hidden_size_per_layer_input:
|
|
208
|
+
p = m._project_per_layer_inputs(h, m._get_per_layer_inputs(ids, emb))
|
|
209
|
+
pli = [p[:, :, i, :] for i in range(len(self.layers))]
|
|
210
|
+
off = mx.array(P) if cached else 0
|
|
211
|
+
else:
|
|
212
|
+
off = P
|
|
213
|
+
masks = {t: self._mask(t, L, P, cached, mask) for t in set(self.types)}
|
|
214
|
+
kv = [None] * len(self.layers) # (keys, values, RoPE offset) of the own-key layers
|
|
215
|
+
for i, layer in enumerate(self.layers[: self.last] if not full else self.layers):
|
|
216
|
+
h = self._layer(i, layer, h, masks[self.types[i]], past, off, pos, pli[i], kv)
|
|
217
|
+
if i == 0 or (i + 1) % self.ASYNC_EVERY == 0:
|
|
218
|
+
mx.async_eval(h)
|
|
219
|
+
if full:
|
|
220
|
+
return mx.take_along_axis(m.norm(h), ro[..., None], axis=1)
|
|
221
|
+
i = self.last
|
|
222
|
+
if kv_out is not None: # a prefix: the last own-key layer's keys and values, then stop
|
|
223
|
+
self._keys(i, self.layers[i].self_attn, self.layers[i].input_layernorm(h), past, off, pos, kv)
|
|
224
|
+
kv_out += [x[:2] for x in kv[: i + 1]]
|
|
225
|
+
return None
|
|
226
|
+
# the readout rows: their positions, mask rows and states
|
|
227
|
+
rows = mx.take_along_axis(pos, ro, axis=1) if pos is not None else ro + P
|
|
228
|
+
rmask = {t: self._row_mask(t, rows, P + L, mask, ro) for t in set(self.types)}
|
|
229
|
+
x = h
|
|
230
|
+
h = mx.take_along_axis(h, ro[..., None], axis=1)
|
|
231
|
+
for i in range(self.last, len(self.layers)):
|
|
232
|
+
layer = self.layers[i]
|
|
233
|
+
p = mx.take_along_axis(pli[i], ro[..., None], axis=1) if pli[i] is not None else None
|
|
234
|
+
if i == self.last:
|
|
235
|
+
self._keys(i, layer.self_attn, layer.input_layernorm(x), past, off, pos, kv)
|
|
236
|
+
h = self._layer(i, layer, h, rmask[self.types[i]], past, off, pos, p, kv, rows)
|
|
237
|
+
return m.norm(h)
|
|
238
|
+
|
|
239
|
+
def _mask(self, t, L, P, cached, mask):
|
|
240
|
+
"""The mask of a layer type for every position, as mlx-lm builds it (with or without a KV cache)."""
|
|
241
|
+
if mask is not None:
|
|
242
|
+
return mask
|
|
243
|
+
window = self.m.window_size if self.gemma and t == "sliding_attention" else None
|
|
244
|
+
if window is not None and (cached or L > window):
|
|
245
|
+
return create_causal_mask(L, P, window_size=window)
|
|
246
|
+
return "causal" if L > 1 else None
|
|
247
|
+
|
|
248
|
+
def _row_mask(self, t, rows, n, mask, ro):
|
|
249
|
+
"""Boolean mask [B, 1, R, n] of the readout rows (absolute positions rows [B, R]) over n keys: the rows of the
|
|
250
|
+
packed block mask, else causal (within the window on a sliding-window layer)."""
|
|
251
|
+
if mask is not None:
|
|
252
|
+
return mx.take_along_axis(mask, ro[:, None, :, None], axis=2)
|
|
253
|
+
k, q = mx.arange(n)[None, None], rows[..., None]
|
|
254
|
+
out = k <= q
|
|
255
|
+
if self.gemma and t == "sliding_attention":
|
|
256
|
+
out = out & (q < k + self.m.window_size)
|
|
257
|
+
return out[:, None]
|
|
258
|
+
|
|
259
|
+
@staticmethod
|
|
260
|
+
def _rope(rope, x, off, pos):
|
|
261
|
+
"""RoPE of x [B, H, L, D] at offset off, or at the positions pos [B, L]: each token as its own row of the same
|
|
262
|
+
kernel (bit-identical to a contiguous run; MLXBackend's packed rows do the same)."""
|
|
263
|
+
if pos is None:
|
|
264
|
+
return rope(x, offset=off)
|
|
265
|
+
B, H, L, D = x.shape
|
|
266
|
+
y = rope(x.transpose(0, 2, 1, 3).reshape(B * L, H, 1, D), offset=pos.reshape(-1))
|
|
267
|
+
return y.reshape(B, L, H, D).transpose(0, 2, 1, 3)
|
|
268
|
+
|
|
269
|
+
def _keys(self, i, a, x, past, off, pos, kv, outs=None):
|
|
270
|
+
"""Keys and values of own-key layer i from its normed input x [B, L, D] (every position), after the prefix's
|
|
271
|
+
when there is one: kv[i] = (keys, values, RoPE offset). outs: its k / v projections when already made."""
|
|
272
|
+
B, L, _ = x.shape
|
|
273
|
+
k, *v = outs if outs is not None else self.qkv[i](x)
|
|
274
|
+
if self.gemma:
|
|
275
|
+
k = k.reshape(B, L, a.n_kv_heads, a.head_dim)
|
|
276
|
+
v = v[0].reshape(B, L, a.n_kv_heads, a.head_dim) if v else k # attention_k_eq_v: the key projection
|
|
277
|
+
k = self._rope(a.rope, a.k_norm(k).transpose(0, 2, 1, 3), off, pos)
|
|
278
|
+
v = a.v_norm(v).transpose(0, 2, 1, 3)
|
|
279
|
+
else:
|
|
280
|
+
k = self._rope(a.rope, k.reshape(B, L, a.n_kv_heads, -1).transpose(0, 2, 1, 3), off, pos)
|
|
281
|
+
v = v[0].reshape(B, L, a.n_kv_heads, -1).transpose(0, 2, 1, 3)
|
|
282
|
+
if past is not None:
|
|
283
|
+
pk, pv = past[i]
|
|
284
|
+
k = mx.concatenate([mx.repeat(pk, B, axis=0), k], axis=2)
|
|
285
|
+
v = mx.concatenate([mx.repeat(pv, B, axis=0), v], axis=2)
|
|
286
|
+
kv[i] = (k, v, off)
|
|
287
|
+
|
|
288
|
+
def _layer(self, i, layer, h, mask, past, off, pos, pli, kv, rows=None):
|
|
289
|
+
"""Layer i on h [B, L, D] (every position), or with rows (their absolute positions [B, R]) on the readout
|
|
290
|
+
rows h [B, R, D], over the keys and values in kv."""
|
|
291
|
+
a = layer.self_attn
|
|
292
|
+
B, L, _ = h.shape
|
|
293
|
+
x = layer.input_layernorm(h)
|
|
294
|
+
if rows is None and self.own[i]:
|
|
295
|
+
q, *outs = self.qkv[i](x) if i != self.last else [a.q_proj(x)] + self.qkv[i](x)
|
|
296
|
+
self._keys(i, a, x, past, off, pos, kv, outs)
|
|
297
|
+
else:
|
|
298
|
+
q = a.q_proj(x)
|
|
299
|
+
k, v, qoff = kv[self.prev[i]]
|
|
300
|
+
q = q.reshape(B, L, a.n_heads, -1)
|
|
301
|
+
if self.gemma:
|
|
302
|
+
q = a.q_norm(q)
|
|
303
|
+
q = q.transpose(0, 2, 1, 3)
|
|
304
|
+
q = self._rope(a.rope, q, qoff, pos) if rows is None else self._rope(a.rope, q, None, rows)
|
|
305
|
+
o = scaled_dot_product_attention(q, k, v, cache=None, scale=a.scale, mask=mask)
|
|
306
|
+
r = a.o_proj(o.transpose(0, 2, 1, 3).reshape(B, L, -1))
|
|
307
|
+
if not self.gemma:
|
|
308
|
+
h = h + r
|
|
309
|
+
g, u = self.gu[i](layer.post_attention_layernorm(h))
|
|
310
|
+
return h + layer.mlp.down_proj(swiglu(g, u))
|
|
311
|
+
h = h + layer.post_attention_layernorm(r)
|
|
312
|
+
res = h
|
|
313
|
+
g, u = self.gu[i](layer.pre_feedforward_layernorm(h))
|
|
314
|
+
h = layer.mlp.down_proj(gemma4_text.geglu(g, u))
|
|
315
|
+
if layer.enable_moe:
|
|
316
|
+
h1 = layer.post_feedforward_layernorm_1(h)
|
|
317
|
+
idx, w = layer.router(res)
|
|
318
|
+
h2 = layer.post_feedforward_layernorm_2(layer.experts(layer.pre_feedforward_layernorm_2(res), idx, w))
|
|
319
|
+
h = h1 + h2
|
|
320
|
+
h = res + layer.post_feedforward_layernorm(h)
|
|
321
|
+
if layer.per_layer_input_gate is not None and pli is not None:
|
|
322
|
+
gate = nn.gelu_approx(layer.per_layer_input_gate(h))
|
|
323
|
+
h = h + layer.post_per_layer_input_norm(layer.per_layer_projection(mx.multiply(gate, pli)))
|
|
324
|
+
if layer.layer_scalar is not None:
|
|
325
|
+
h = h * layer.layer_scalar
|
|
326
|
+
return h
|