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/gemma4.py
ADDED
|
@@ -0,0 +1,726 @@
|
|
|
1
|
+
"""The Gemma 4 (basal-omni) decoder forward of the eager backend (basal 2.3). It runs the layers of the transformers
|
|
2
|
+
model (the same modules and weights) in its own loop, for three things the transformers forward cannot do:
|
|
3
|
+
|
|
4
|
+
- **SOAM (state once, ask many):** the prompts of a group (the option orders of a question; with SOAM every question
|
|
5
|
+
and option order of a request) share a token prefix: the chat template, the state and, with media, the image /
|
|
6
|
+
audio soft tokens. The prefix runs once into keys and values; the rest of every prompt (its suffix) then runs as one
|
|
7
|
+
right-padded batch over them, positions continuing from the prefix. Each suffix sees the prefix and its own earlier
|
|
8
|
+
tokens only, so its readout equals the forward of its whole prompt (up to float rounding). Prefixes of several groups
|
|
9
|
+
are batched together, a long one runs alone in CHUNK-token parts; a single prompt longer than CHUNK runs its parts
|
|
10
|
+
the same way (the transformers path's chunked prefill). Sliding-window layers keep the last window - 1 keys of a
|
|
11
|
+
prefix only (the most a later token can see), global layers all of them. A state over 16k tokens (ATTN_PAIRS //
|
|
12
|
+
CHUNK) writes its global layers' keys and values into buffers of the whole state, and their attention runs in calls
|
|
13
|
+
of at most SCORES scores, each KV head's query heads as one block of queries (_split); up to 16k tokens every call
|
|
14
|
+
is as before.
|
|
15
|
+
- **Answer rows only (G1):** the layers from the last one with its own keys and values onwards matter only at the
|
|
16
|
+
readout positions: Gemma 4 E2B / E4B reuse the keys and values of earlier layers in their last layers (E4B: 18 of
|
|
17
|
+
42), so those layers produce nothing a later token reads. Such layers, and the attention and MLP of the last layer
|
|
18
|
+
with its own keys and values (on 12B / 31B the last layer), run at the answer rows only: one row per prompt, its
|
|
19
|
+
query attending the stored keys. A prefix stops after the keys and values of that layer. Same maths.
|
|
20
|
+
- **Media once per request:** the image and audio towers run once for all prompts of a request (the prompts carry the
|
|
21
|
+
same media), and the soft tokens are part of the shared prefix. On the larger Gemma 4 models
|
|
22
|
+
(use_bidirectional_attention "vision") the soft tokens of one image attend to each other as transformers builds the
|
|
23
|
+
masks: Gemma 4 31B in its sliding-window layers within the window, the unified models (basal-omni max, 1.1-max) in
|
|
24
|
+
every layer, past the window as well; a prefix part never ends inside an image.
|
|
25
|
+
|
|
26
|
+
Attention runs per layer type (E1, --eager-attn): torch SDPA with an explicit boolean mask (the math kernel by default;
|
|
27
|
+
EagerBackend turns the others off for Gemma 4, so the memory-efficient kernel runs only when chosen), or a
|
|
28
|
+
FlashAttention varlen kernel over the real queries and keys of every row. Measured on real activations of mini and
|
|
29
|
+
max (H100, 2026-10-20: every attention call of a 1,857-token and three 12.6k-token prompts against float64): in the
|
|
30
|
+
sliding-window layers (head size 256) FlashAttention 3 is within bf16 rounding of the math kernel at 11x its speed,
|
|
31
|
+
the memory-efficient kernel at 4.4x; in the global layers (512) only the math and memory-efficient kernels run on
|
|
32
|
+
Hopper (FA3 / FA4 take at most 256, cuDNN has no kernel, FlexAttention runs out of shared memory), the
|
|
33
|
+
memory-efficient one 3x faster. The 7 Oct wrong attention was the memory-efficient kernel on keys and values with a
|
|
34
|
+
zero-stride head dimension (pytorch/pytorch#191937, torch <= 2.13: query lengths = 1 mod 32 at head size 256 / 512):
|
|
35
|
+
transformers repeats max's one global KV head to 16 query heads as an expanded view, and on the 1,857-token prompt the
|
|
36
|
+
kernel returned errors of 10-28 on outputs of 14-22 in every global layer (fp32 and bf16). Here the keys and values are
|
|
37
|
+
copied per head before that kernel.
|
|
38
|
+
"""
|
|
39
|
+
import os
|
|
40
|
+
import sys
|
|
41
|
+
from contextlib import nullcontext
|
|
42
|
+
|
|
43
|
+
import torch
|
|
44
|
+
import torch.nn.functional as F
|
|
45
|
+
|
|
46
|
+
# attention kernels per layer type (E1): "sdpa" = torch SDPA with the boolean mask on the kernels the process allows
|
|
47
|
+
# (the math kernel: EagerBackend turns the others off for Gemma 4), "efficient" / "cudnn" = that SDPA kernel with the
|
|
48
|
+
# mask, "fa3" / "fa4" = a FlashAttention varlen kernel over the rows' real queries and keys (causal, aligned at each
|
|
49
|
+
# row's end, the sliding window as its left window)
|
|
50
|
+
SDPA_KERNELS = {"sdpa": None, "efficient": "EFFICIENT_ATTENTION", "cudnn": "CUDNN_ATTENTION"}
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _fa3(q, k, v, cu_q, cu_k, max_q, max_k, scale, window):
|
|
54
|
+
import flash_attn_interface as fa
|
|
55
|
+
o = fa.flash_attn_varlen_func(q, k, v, cu_q, cu_k, max_q, max_k, softmax_scale=scale, causal=True,
|
|
56
|
+
window_size=(window - 1, 0) if window else (-1, -1))
|
|
57
|
+
return o[0] if isinstance(o, (tuple, list)) else o
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _fa4(q, k, v, cu_q, cu_k, max_q, max_k, scale, window):
|
|
61
|
+
from flash_attn.cute import interface as fa
|
|
62
|
+
o = fa.flash_attn_varlen_func(q, k, v, cu_seqlens_q=cu_q, cu_seqlens_k=cu_k, max_seqlen_q=max_q,
|
|
63
|
+
max_seqlen_k=max_k, softmax_scale=scale, causal=True,
|
|
64
|
+
window_size=(window - 1, 0) if window else (None, None))
|
|
65
|
+
return o[0] if isinstance(o, (tuple, list)) else o
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
VARLEN_KERNELS = {"fa3": _fa3, "fa4": _fa4}
|
|
69
|
+
KERNELS = tuple(SDPA_KERNELS) + tuple(VARLEN_KERNELS)
|
|
70
|
+
TYPES = {"sliding": "sliding_attention", "full": "full_attention"}
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def attention_plan(spec="auto"):
|
|
74
|
+
"""--eager-attn -> {layer type: kernel} of Gemma4Forward. math: the SDPA math kernel in every layer (basal 2.2);
|
|
75
|
+
auto: on Hopper (sm90, where E1 measured them) FlashAttention 3 in the sliding-window layers (the memory-efficient
|
|
76
|
+
kernel without the flash_attn_3 package) and the memory-efficient kernel in the global layers (head size 512: no
|
|
77
|
+
flash kernel runs it on Hopper), the math kernel elsewhere; "sliding=K,full=K" with K one of KERNELS."""
|
|
78
|
+
if spec == "math":
|
|
79
|
+
return {}
|
|
80
|
+
if spec == "auto":
|
|
81
|
+
from .engine import attention_available
|
|
82
|
+
if not torch.cuda.is_available() or torch.cuda.get_device_capability()[0] != 9:
|
|
83
|
+
return {}
|
|
84
|
+
sliding = "fa3" if attention_available("fa3") is None else "efficient"
|
|
85
|
+
return {"sliding_attention": sliding, "full_attention": "efficient"}
|
|
86
|
+
plan = {}
|
|
87
|
+
for part in spec.split(","):
|
|
88
|
+
t, _, k = part.partition("=")
|
|
89
|
+
if t not in TYPES or k not in KERNELS:
|
|
90
|
+
raise ValueError(f"--eager-attn {spec!r}: math, auto, or sliding=K,full=K with K one of {', '.join(KERNELS)}")
|
|
91
|
+
plan[TYPES[t]] = k
|
|
92
|
+
return plan
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def text_model(model):
|
|
96
|
+
"""The decoder of a Gemma 4 model: Gemma4(Unified)ForConditionalGeneration -> model.language_model,
|
|
97
|
+
Gemma4ForCausalLM -> model."""
|
|
98
|
+
return getattr(model.model, "language_model", model.model)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def is_gemma4(model):
|
|
102
|
+
"""A loaded Gemma 4 model (basal-omni): model types gemma4, gemma4_text, gemma4_unified, ..."""
|
|
103
|
+
return str(getattr(model.config, "model_type", "")).startswith("gemma4")
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
class HostRows(torch.nn.Module):
|
|
107
|
+
"""Gemma 4's per-layer embedding table in host memory (G3, --ple-offload on): E2B / E4B look up 256 extra numbers
|
|
108
|
+
per layer for every token in a table of 262,144 rows (E4B: x 42 layers = 10,752 columns, 5.6 GB in bf16, a third
|
|
109
|
+
of mini's weights). Only the rows of a forward's tokens are copied to the GPU; the values are those of
|
|
110
|
+
Gemma4TextScaledWordEmbedding (the rows times the scale in the table's dtype). Not a parameter, so model.to(device)
|
|
111
|
+
leaves the table where it is; the transformers forward reads it the same way."""
|
|
112
|
+
|
|
113
|
+
def __init__(self, emb):
|
|
114
|
+
super().__init__()
|
|
115
|
+
w = emb.weight.data.to("cpu")
|
|
116
|
+
self.table = w.pin_memory() if torch.cuda.is_available() else w
|
|
117
|
+
self.scale = emb.scalar_embed_scale
|
|
118
|
+
self.embedding_dim = w.shape[1]
|
|
119
|
+
|
|
120
|
+
def forward(self, ids):
|
|
121
|
+
flat = ids.reshape(-1).cpu()
|
|
122
|
+
rows = torch.empty((flat.numel(), self.embedding_dim), dtype=self.table.dtype,
|
|
123
|
+
pin_memory=self.table.is_pinned())
|
|
124
|
+
torch.index_select(self.table, 0, flat, out=rows)
|
|
125
|
+
out = rows.to(ids.device, non_blocking=True).view(*ids.shape, -1)
|
|
126
|
+
return out * torch.tensor(self.scale, dtype=out.dtype, device=out.device)
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def offload_ple(model):
|
|
130
|
+
"""Move a Gemma 4 model's per-layer embedding table to host memory (before model.to(device)); -> bytes moved
|
|
131
|
+
(0: the model has no per-layer inputs)."""
|
|
132
|
+
lm = text_model(model)
|
|
133
|
+
emb = getattr(lm, "embed_tokens_per_layer", None)
|
|
134
|
+
if emb is None or isinstance(emb, HostRows):
|
|
135
|
+
return 0
|
|
136
|
+
lm.embed_tokens_per_layer = HostRows(emb)
|
|
137
|
+
return lm.embed_tokens_per_layer.table.numel() * lm.embed_tokens_per_layer.table.element_size()
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
class Gemma4Forward:
|
|
141
|
+
# memory bounds as in EagerBackend: prefix parts of at most CHUNK tokens; at most MAX_BATCH_TOKENS padded tokens and
|
|
142
|
+
# ATTN_PAIRS query-key pairs (rows x query tokens x keys: the attention scores of the math kernel) per forward,
|
|
143
|
+
# the pairs of one CHUNK-token part over a 16k-token context
|
|
144
|
+
CHUNK = 2048
|
|
145
|
+
MAX_BATCH_TOKENS = 16384
|
|
146
|
+
ATTN_PAIRS = 2048 * 16384
|
|
147
|
+
# keys and values repeated per query head (the math kernel's GQA, the memory-efficient kernel's input) over the
|
|
148
|
+
# rows of a suffix forward: each row repeats the prefix keys, so 31B (32 heads x 512 in its global layers, 64 KB a
|
|
149
|
+
# row and key) with five questions over a 10k-token state would hold 3.2 GB per layer; at most KV_BYTES
|
|
150
|
+
KV_BYTES = 2 << 30
|
|
151
|
+
# an attention call past those budgets (a state over 16k tokens) runs as calls of at most SCORES scores (query heads
|
|
152
|
+
# x queries x keys; fp32 in the math kernel: 256 MB), as the graph engine's math kernel (Gemma4Graph.SCORES)
|
|
153
|
+
SCORES = 2 ** 26
|
|
154
|
+
|
|
155
|
+
def __init__(self, model, answer_rows=True, attn=None, two_way=None, option_isolation=False, prefix=None):
|
|
156
|
+
self.model = model
|
|
157
|
+
# isolated options (basal.json "option_isolation", prompt.model_option_isolation): every prompt is an OptionIds
|
|
158
|
+
# (its blocks) and is read whole: an option block reads the prefix and itself, never another option, at shared
|
|
159
|
+
# positions; the suffix reads all of them (_iso_rows, _mask)
|
|
160
|
+
self.iso = bool(option_isolation)
|
|
161
|
+
assert not (self.iso and two_way), "isolated options are read one way"
|
|
162
|
+
# prefix-bidirectional reading (basal.json "prefix_bidir"): {"max_prefix"} or None. A request's state
|
|
163
|
+
# prefix (its cut, from the server) is read once with its global layers both ways, the questions causally over
|
|
164
|
+
# its keys (_shared with bidir); a prefix over max_prefix tokens, or a request without a cut, is read one way
|
|
165
|
+
self.prefix = dict(prefix) if prefix else None
|
|
166
|
+
assert not (self.iso and prefix), "isolated options are read one way"
|
|
167
|
+
# two-way reading (basal.json "two_way", prompt.model_two_way): {"max_prompt", "max_record"} or None. The
|
|
168
|
+
# global layers read a prompt's tokens both ways, the sliding-window layers stay causal; a prompt over
|
|
169
|
+
# max_prompt tokens, or every prompt of a request over max_record tokens, is read one way (two_way_rows)
|
|
170
|
+
self.two_way = dict(two_way) if two_way else None
|
|
171
|
+
lm = self.lm = text_model(model)
|
|
172
|
+
cfg = self.cfg = lm.config
|
|
173
|
+
self.layers = list(lm.layers[: cfg.num_hidden_layers])
|
|
174
|
+
self.types = list(cfg.layer_types)
|
|
175
|
+
self.window = cfg.sliding_window
|
|
176
|
+
self.own = [not layer.self_attn.is_kv_shared_layer for layer in self.layers]
|
|
177
|
+
# the last layer with its own keys and values; a shared layer reads the last such layer of its type (the
|
|
178
|
+
# layer transformers marks store_full_length_kv)
|
|
179
|
+
self.last_kv = max(i for i, o in enumerate(self.own) if o)
|
|
180
|
+
self.src = {i: max(j for j in range(len(self.layers)) if self.own[j] and self.types[j] == t)
|
|
181
|
+
for i, t in enumerate(self.types) if not self.own[i]}
|
|
182
|
+
self.store = set(self.src.values())
|
|
183
|
+
self.ple = bool(getattr(cfg, "hidden_size_per_layer_input", 0))
|
|
184
|
+
self.bidir = getattr(cfg, "use_bidirectional_attention", None) == "vision"
|
|
185
|
+
# where an image's soft tokens see each other: transformers' Gemma 4 (31B) masks the sliding-window layers only,
|
|
186
|
+
# the window still applying (create_masks_for_vision_model); Gemma 4 unified (max, 1.1-max) passes the image
|
|
187
|
+
# blocks to every layer's mask, OR-ed after the window (create_masks_for_generate). Taking the 31B rule for max
|
|
188
|
+
# moved image answers by up to 0.48 against the transformers forward (33 of 150 images over 0.05; H100,
|
|
189
|
+
# 2026-10-20); text and audio were unaffected
|
|
190
|
+
self.unified_blocks = str(getattr(cfg, "model_type", "")).startswith("gemma4_unified")
|
|
191
|
+
self.block_types = set(self.types) if self.unified_blocks else {"sliding_attention"}
|
|
192
|
+
self.rope = sys.modules[type(self.layers[0].self_attn).__module__].apply_rotary_pos_emb
|
|
193
|
+
self.answer_rows = answer_rows
|
|
194
|
+
self.attn = dict(attn or {}) # layer type -> kernel (SDPA_KERNELS, VARLEN_KERNELS); "sdpa" when absent
|
|
195
|
+
top = model.config
|
|
196
|
+
self.media_ids = {k: getattr(top, f"{k}_token_id", None) for k in ("image", "video", "audio")}
|
|
197
|
+
self.pad = cfg.pad_token_id
|
|
198
|
+
w = lm.embed_tokens.weight
|
|
199
|
+
self.kv_row_bytes = 2 * w.element_size() * max(cfg.num_attention_heads * layer.self_attn.head_dim
|
|
200
|
+
for layer in self.layers)
|
|
201
|
+
|
|
202
|
+
# -- embeddings ---------------------------------------------------------------------------------------------------
|
|
203
|
+
def _embed(self, ids, media=None, offsets=None):
|
|
204
|
+
"""Token ids [B, S] -> (embeddings [B, S, D], per-layer inputs [B, S, L, P] or None). media: {kind: soft
|
|
205
|
+
tokens [n, D]} of the request; a row's media tokens take them from offsets[b][kind] on (the number of that
|
|
206
|
+
kind's tokens before the row in its prompt). As transformers: media positions read the pad token's rows."""
|
|
207
|
+
lm = self.lm
|
|
208
|
+
kinds = [(k, self.media_ids[k]) for k in (media or {}) if self.media_ids.get(k) is not None]
|
|
209
|
+
llm = ids
|
|
210
|
+
if kinds:
|
|
211
|
+
mm = torch.zeros_like(ids, dtype=torch.bool)
|
|
212
|
+
for _, t in kinds:
|
|
213
|
+
mm |= ids == t
|
|
214
|
+
llm = torch.where(mm, self.pad, ids)
|
|
215
|
+
h = lm.embed_tokens(llm)
|
|
216
|
+
for k, t in kinds:
|
|
217
|
+
m = ids == t
|
|
218
|
+
counts = m.sum(1).tolist()
|
|
219
|
+
if not sum(counts):
|
|
220
|
+
continue
|
|
221
|
+
feats = torch.cat([media[k][offsets[b][k]: offsets[b][k] + c] for b, c in enumerate(counts) if c])
|
|
222
|
+
h = h.masked_scatter(m[..., None], feats.to(h.dtype))
|
|
223
|
+
pli = None
|
|
224
|
+
if self.ple:
|
|
225
|
+
pli = lm.project_per_layer_inputs(h, lm.get_per_layer_inputs(llm, None))
|
|
226
|
+
return h, pli
|
|
227
|
+
|
|
228
|
+
def _blocks(self, ids):
|
|
229
|
+
"""Vision block ids [B, S] (-1: not an image / video soft token): runs of soft tokens, as transformers'
|
|
230
|
+
get_block_sequence_ids_for_mask; None when the model attends causally only."""
|
|
231
|
+
if not self.bidir:
|
|
232
|
+
return None
|
|
233
|
+
vis = torch.zeros_like(ids, dtype=torch.bool)
|
|
234
|
+
for k in ("image", "video"):
|
|
235
|
+
if self.media_ids.get(k) is not None:
|
|
236
|
+
vis |= ids == self.media_ids[k]
|
|
237
|
+
if not vis.any():
|
|
238
|
+
return None
|
|
239
|
+
start = vis & ~F.pad(vis, (1, 0))[:, :-1]
|
|
240
|
+
return torch.where(vis, start.long().cumsum(1) - 1, -1)
|
|
241
|
+
|
|
242
|
+
# -- one forward --------------------------------------------------------------------------------------------------
|
|
243
|
+
def _mask(self, t, qpos, kc, pos, valid, qblk, two_way=False, iso=None):
|
|
244
|
+
"""Boolean attention mask [B, 1, Sq, Lc + S] of layer type t: keys of earlier passes (positions kc [B, Lc],
|
|
245
|
+
-1 = none) then this pass's tokens (positions pos [B, S]; valid = real tokens, a padding query sees itself so
|
|
246
|
+
that no row is empty). two_way: whole prompts (no earlier keys) read both ways in the global layers. iso:
|
|
247
|
+
(segment ids, option tokens) [B, S] of whole prompts with isolated options: causal in token order, no option
|
|
248
|
+
token sees another option's, the window over the shared positions."""
|
|
249
|
+
sliding = t == "sliding_attention"
|
|
250
|
+
d = qpos[:, :, None] - pos[:, None, :]
|
|
251
|
+
if iso is not None:
|
|
252
|
+
seg, opt = iso
|
|
253
|
+
i = torch.arange(pos.shape[1], device=pos.device)
|
|
254
|
+
m = (i[:, None] >= i[None, :])[None] & valid[:, None, :]
|
|
255
|
+
m = m & ~(opt[:, :, None] & opt[:, None, :] & (seg[:, :, None] != seg[:, None, :]))
|
|
256
|
+
if sliding:
|
|
257
|
+
m = m & (d < self.window)
|
|
258
|
+
return (m | (i[:, None] == i[None, :])[None])[:, None]
|
|
259
|
+
m = d >= 0
|
|
260
|
+
block = None
|
|
261
|
+
if qblk is not None and t in self.block_types:
|
|
262
|
+
block = (qblk[:, :, None] == qblk[:, None, :]) & (qblk[:, :, None] >= 0)
|
|
263
|
+
if block is not None and not self.unified_blocks:
|
|
264
|
+
m = m | block # 31B: within the window
|
|
265
|
+
if sliding:
|
|
266
|
+
m = m & (d < self.window)
|
|
267
|
+
if block is not None and self.unified_blocks:
|
|
268
|
+
m = m | block # unified: the whole image, past the window too
|
|
269
|
+
m = m & (valid[:, None, :] | (d == 0))
|
|
270
|
+
if two_way and not sliding:
|
|
271
|
+
m = valid[:, None, :] | (d == 0)
|
|
272
|
+
if kc is not None: # (comparisons, not distances: over an 82k-token state those were 1.3 GB of int64)
|
|
273
|
+
kq = kc[:, None, :]
|
|
274
|
+
mc = (kq >= 0) & (kq <= qpos[:, :, None])
|
|
275
|
+
if sliding:
|
|
276
|
+
mc = mc & (qpos[:, :, None] - kq < self.window)
|
|
277
|
+
m = torch.cat([mc, m], -1)
|
|
278
|
+
return m[:, None]
|
|
279
|
+
|
|
280
|
+
def _q(self, a, x, cs):
|
|
281
|
+
q = a.q_norm(a.q_proj(x).view(*x.shape[:2], -1, a.head_dim))
|
|
282
|
+
return self.rope(q, *cs, unsqueeze_dim=2).transpose(1, 2)
|
|
283
|
+
|
|
284
|
+
def _kv(self, a, x, cs):
|
|
285
|
+
shape = (*x.shape[:2], -1, a.head_dim)
|
|
286
|
+
k = a.k_proj(x).view(shape)
|
|
287
|
+
v = a.v_proj(x).view(shape) if a.v_proj is not None else k
|
|
288
|
+
return self.rope(a.k_norm(k), *cs, unsqueeze_dim=2).transpose(1, 2), a.v_norm(v).transpose(1, 2)
|
|
289
|
+
|
|
290
|
+
def _kernel(self, t, dtype, blk):
|
|
291
|
+
"""The kernel of layer type t in a forward: the masked SDPA math kernel for fp32 and, in the layers where an
|
|
292
|
+
image's soft tokens attend to each other (block_types), for rows with images (a flash kernel's mask is causal
|
|
293
|
+
only)."""
|
|
294
|
+
k = self.attn.get(t, "sdpa")
|
|
295
|
+
if k in VARLEN_KERNELS and (dtype not in (torch.bfloat16, torch.float16)
|
|
296
|
+
or blk is not None and t in self.block_types):
|
|
297
|
+
return "sdpa"
|
|
298
|
+
return k
|
|
299
|
+
|
|
300
|
+
def _split(self, a, q, k, v, mask):
|
|
301
|
+
"""An SDPA call past the budgets of a forward over a 16k-token context (ATTN_PAIRS query-key pairs, KV_BYTES of
|
|
302
|
+
keys and values repeated per query head; only states over 16k tokens reach them) as calls of SCORES scores:
|
|
303
|
+
per KV head, its query heads folded into one block of queries over its keys and values (nothing repeated per
|
|
304
|
+
query head), in parts of queries. Without it the 2,048 queries of a part of ultra over a 76k-token state were
|
|
305
|
+
one math-kernel call of 32 heads x 2,048 x 76k scores (fp32: 20 GB) over keys and values repeated 8x."""
|
|
306
|
+
B, H, Sq, d = q.shape
|
|
307
|
+
G, Lk = k.shape[1], k.shape[2]
|
|
308
|
+
r = H // G
|
|
309
|
+
n = max(1, self.SCORES // (B * r * Lk)) # queries per call
|
|
310
|
+
out = q.new_empty(B, H, Sq, d)
|
|
311
|
+
for j in range(G):
|
|
312
|
+
for s0 in range(0, Sq, n):
|
|
313
|
+
qs = q[:, j * r: (j + 1) * r, s0: s0 + n]
|
|
314
|
+
m = qs.shape[2]
|
|
315
|
+
o = F.scaled_dot_product_attention(qs.reshape(B, 1, r * m, d), k[:, j: j + 1], v[:, j: j + 1],
|
|
316
|
+
attn_mask=mask[:, :, s0: s0 + m].repeat(1, 1, r, 1), scale=a.scaling)
|
|
317
|
+
out[:, j * r: (j + 1) * r, s0: s0 + m] = o.view(B, r, m, d)
|
|
318
|
+
return out
|
|
319
|
+
|
|
320
|
+
def _attend(self, kind, a, q, k, v, mask, kval, qval, window, split=False):
|
|
321
|
+
"""Attention of one layer: q [B, H, Sq, d], k / v [B, kv heads, Lk, d] -> [B, H, Sq, d]. SDPA kernels take the
|
|
322
|
+
boolean mask; varlen kernels the real queries (qval [B, Sq]) and keys (kval [B, Lk]) of each row packed back to
|
|
323
|
+
back: a row's real keys are its earlier tokens' and its own, in position order, ending at its last real query,
|
|
324
|
+
so causal attention aligned at the row's end (with the window) is the mask's attention. split: an SDPA call in
|
|
325
|
+
_split's parts even within the budgets (a state over 16k tokens)."""
|
|
326
|
+
if kind in SDPA_KERNELS:
|
|
327
|
+
from torch.nn.attention import SDPBackend, sdpa_kernel
|
|
328
|
+
name = SDPA_KERNELS[kind]
|
|
329
|
+
B, H, Sq, d = q.shape
|
|
330
|
+
Lk = k.shape[2]
|
|
331
|
+
if split or B * Sq * Lk > self.ATTN_PAIRS or B * Lk * H * d * k.element_size() * 2 > self.KV_BYTES:
|
|
332
|
+
with sdpa_kernel([getattr(SDPBackend, name)]) if name else nullcontext():
|
|
333
|
+
return self._split(a, q, k, v, mask)
|
|
334
|
+
gqa = name is None
|
|
335
|
+
if not gqa: # the memory-efficient and cuDNN kernels take no enable_gqa: keys and values per query head,
|
|
336
|
+
# copied (an expanded, zero-stride view gives the memory-efficient kernel wrong attention at query
|
|
337
|
+
# lengths = 1 mod 32: pytorch/pytorch#191937, the 7 Oct case)
|
|
338
|
+
k, v = (x.repeat_interleave(q.shape[1] // k.shape[1], 1) for x in (k, v))
|
|
339
|
+
with sdpa_kernel([getattr(SDPBackend, name)]) if name else nullcontext():
|
|
340
|
+
return F.scaled_dot_product_attention(q, k, v, attn_mask=mask, scale=a.scaling, enable_gqa=gqa)
|
|
341
|
+
B, H, Sq, d = q.shape
|
|
342
|
+
nq, nk = qval.sum(1), kval.sum(1)
|
|
343
|
+
cu_q = F.pad(nq.cumsum(0), (1, 0)).to(torch.int32)
|
|
344
|
+
cu_k = F.pad(nk.cumsum(0), (1, 0)).to(torch.int32)
|
|
345
|
+
o = VARLEN_KERNELS[kind](q.transpose(1, 2)[qval], k.transpose(1, 2)[kval], v.transpose(1, 2)[kval], cu_q, cu_k,
|
|
346
|
+
int(nq.max()), int(nk.max()), a.scaling, window)
|
|
347
|
+
out = q.new_zeros(B, Sq, H, d)
|
|
348
|
+
out[qval] = o.to(q.dtype)
|
|
349
|
+
return out.transpose(1, 2)
|
|
350
|
+
|
|
351
|
+
def _rest(self, layer, h, o, pli):
|
|
352
|
+
"""The decoder layer after attention (transformers' Gemma 4 decoder layer: MLP, MoE block, per-layer input)."""
|
|
353
|
+
o = layer.self_attn.o_proj(o.transpose(1, 2).reshape(*h.shape[:2], -1))
|
|
354
|
+
h = h + layer.post_attention_layernorm(o)
|
|
355
|
+
y = layer.mlp(layer.pre_feedforward_layernorm(h))
|
|
356
|
+
if getattr(layer, "enable_moe_block", False):
|
|
357
|
+
flat = h.reshape(-1, h.shape[-1])
|
|
358
|
+
_, w, idx = layer.router(flat)
|
|
359
|
+
y2 = layer.experts(layer.pre_feedforward_layernorm_2(flat), idx, w).reshape(h.shape)
|
|
360
|
+
y = layer.post_feedforward_layernorm_1(y) + layer.post_feedforward_layernorm_2(y2)
|
|
361
|
+
h = h + layer.post_feedforward_layernorm(y)
|
|
362
|
+
if pli is not None:
|
|
363
|
+
g = layer.act_fn(layer.per_layer_input_gate(h)) * pli
|
|
364
|
+
h = h + layer.post_per_layer_input_norm(layer.per_layer_projection(g))
|
|
365
|
+
return h * layer.layer_scalar
|
|
366
|
+
|
|
367
|
+
def _pass(self, h, pli, pos, valid, ctx=None, grp=None, read=None, blk=None, split=False, two_way=False, iso=None):
|
|
368
|
+
"""One forward over token rows [B, S]: embeddings h [B, S, D], per-layer inputs pli [B, S, L, P] or None,
|
|
369
|
+
positions pos [B, S], valid [B, S] (right padding), blk vision block ids or None. ctx: (kv, kpos) of earlier
|
|
370
|
+
tokens, kv {own layer: (K, V) [G, kv heads, Lc, d]}, kpos {layer type: positions [G, Lc]}; row b continues
|
|
371
|
+
ctx row grp[b]. read [B]: the index of each row's readout token, or None for a prefix part (it stops after the
|
|
372
|
+
keys and values of the last layer that has its own). split: the global layers' attention in _split's parts.
|
|
373
|
+
-> ({own layer: (K, V) of this pass's tokens}, final hidden state at `read` [B, D] or None). A readout pass
|
|
374
|
+
keeps no keys and values ({}): nothing reads them, and ultra's of a 16k-token batch were 14 GB. two_way: rows
|
|
375
|
+
of whole prompts read both ways in the global layers (_mask). iso: (segment ids, option tokens) of whole prompts
|
|
376
|
+
with isolated options (_mask; pos are their shared positions)."""
|
|
377
|
+
assert not (two_way and ctx is not None), "a two-way prompt is read whole, without earlier keys"
|
|
378
|
+
assert not (iso is not None and ctx is not None), "a prompt with isolated options is read whole"
|
|
379
|
+
B, S = valid.shape
|
|
380
|
+
kv, kpos = ctx if ctx is not None else ({}, {})
|
|
381
|
+
if ctx is not None and grp is None:
|
|
382
|
+
grp = torch.zeros(B, dtype=torch.long, device=pos.device)
|
|
383
|
+
types = set(self.types)
|
|
384
|
+
rope = {t: self.lm.rotary_emb(h, pos, t) for t in types}
|
|
385
|
+
# a two-way forward's global layers take the masked SDPA kernel (a flash kernel's mask is causal only), and so
|
|
386
|
+
# does every layer of a forward with isolated options
|
|
387
|
+
kinds = {t: "sdpa" if iso is not None or two_way and t != "sliding_attention" else self._kernel(t, h.dtype, blk)
|
|
388
|
+
for t in types}
|
|
389
|
+
masks = {t: self._mask(t, pos, kpos[t][grp] if t in kpos else None, pos, valid, blk, two_way, iso)
|
|
390
|
+
for t in types if kinds[t] in SDPA_KERNELS}
|
|
391
|
+
kval = {t: torch.cat([kpos[t][grp] >= 0, valid], 1) if t in kpos else valid
|
|
392
|
+
for t in types if kinds[t] in VARLEN_KERNELS}
|
|
393
|
+
qval = valid
|
|
394
|
+
new, kept, sliced = {}, {}, False
|
|
395
|
+
rows = None if read is None else (torch.arange(B, device=pos.device), read)
|
|
396
|
+
# G1: the layers from the last one with its own keys and values on run at the answer rows only
|
|
397
|
+
cut = self.last_kv if self.answer_rows and read is not None and S > 1 else None
|
|
398
|
+
for i, layer in enumerate(self.layers):
|
|
399
|
+
a, t = layer.self_attn, self.types[i]
|
|
400
|
+
x = layer.input_layernorm(h)
|
|
401
|
+
if self.own[i]: # every own layer comes before the cut: its keys and values at every position
|
|
402
|
+
k, v = self._kv(a, x, rope[t])
|
|
403
|
+
if read is None:
|
|
404
|
+
new[i] = (k, v)
|
|
405
|
+
if i in kv:
|
|
406
|
+
K, V = kv[i]
|
|
407
|
+
K = K.expand(B, -1, -1, -1) if K.shape[0] == 1 else K.index_select(0, grp)
|
|
408
|
+
V = V.expand(B, -1, -1, -1) if V.shape[0] == 1 else V.index_select(0, grp)
|
|
409
|
+
k, v = torch.cat([K, k], 2), torch.cat([V, v], 2)
|
|
410
|
+
if i in self.store:
|
|
411
|
+
kept[t] = (k, v)
|
|
412
|
+
else:
|
|
413
|
+
k, v = kept[t]
|
|
414
|
+
if read is None and i == self.last_kv:
|
|
415
|
+
break
|
|
416
|
+
if i == cut:
|
|
417
|
+
h, x = h[rows][:, None], x[rows][:, None]
|
|
418
|
+
pli = pli[rows][:, None] if pli is not None else None
|
|
419
|
+
rope = {t2: (c[rows][:, None], s[rows][:, None]) for t2, (c, s) in rope.items()}
|
|
420
|
+
masks = {t2: m[rows[0], :, rows[1]][:, :, None] for t2, m in masks.items()}
|
|
421
|
+
qval = torch.ones(B, 1, dtype=torch.bool, device=pos.device)
|
|
422
|
+
sliced = True
|
|
423
|
+
q = self._q(a, x, rope[t])
|
|
424
|
+
o = self._attend(kinds[t], a, q, k, v, masks.get(t), kval.get(t), qval,
|
|
425
|
+
self.window if t == "sliding_attention" else None, split and t != "sliding_attention")
|
|
426
|
+
h = self._rest(layer, h, o, pli[:, :, i] if pli is not None else None)
|
|
427
|
+
if read is None:
|
|
428
|
+
return new, None
|
|
429
|
+
return new, self.lm.norm(h[:, 0] if sliced else h[rows])
|
|
430
|
+
|
|
431
|
+
# -- scheduling ---------------------------------------------------------------------------------------------------
|
|
432
|
+
def _vision(self, tok):
|
|
433
|
+
return self.bidir and tok in (self.media_ids.get("image"), self.media_ids.get("video"))
|
|
434
|
+
|
|
435
|
+
def _run_start(self, ids, n):
|
|
436
|
+
"""n moved back to the start of the image its cut would split (a prefix never ends inside an image)."""
|
|
437
|
+
while 0 < n < len(ids) and self._vision(ids[n - 1]) and self._vision(ids[n]):
|
|
438
|
+
n -= 1
|
|
439
|
+
return n
|
|
440
|
+
|
|
441
|
+
def _parts(self, ids, n):
|
|
442
|
+
"""CHUNK-token parts [(start, end)] of ids[:n], none ending inside an image (a longer image is one part)."""
|
|
443
|
+
out, s = [], 0
|
|
444
|
+
while s < n:
|
|
445
|
+
e = min(s + self.CHUNK, n)
|
|
446
|
+
if e < n:
|
|
447
|
+
e = self._run_start(ids, e)
|
|
448
|
+
while e <= s or (e < n and self._vision(ids[e - 1]) and self._vision(ids[e])):
|
|
449
|
+
e += 1
|
|
450
|
+
out.append((s, e))
|
|
451
|
+
s = e
|
|
452
|
+
return out
|
|
453
|
+
|
|
454
|
+
def _rows(self, seqs, starts, media=None, prompts=None):
|
|
455
|
+
"""Token rows (right-padded) -> (embeddings, per-layer inputs, positions, valid, block ids, lengths); a row
|
|
456
|
+
starts at position starts[b] of its prompt (prompts[b], for the media offsets)."""
|
|
457
|
+
dev = self.lm.embed_tokens.weight.device
|
|
458
|
+
S = max(map(len, seqs))
|
|
459
|
+
ids = torch.tensor([list(s) + [self.pad] * (S - len(s)) for s in seqs], device=dev)
|
|
460
|
+
lens = torch.tensor([len(s) for s in seqs], device=dev)
|
|
461
|
+
ar = torch.arange(S, device=dev)
|
|
462
|
+
valid = ar[None] < lens[:, None]
|
|
463
|
+
pos = torch.tensor(starts, device=dev)[:, None] + ar[None]
|
|
464
|
+
offsets = None
|
|
465
|
+
if media:
|
|
466
|
+
offsets = [{k: sum(1 for x in p[:s0] if x == self.media_ids[k]) for k in media}
|
|
467
|
+
for p, s0 in zip(prompts, starts)]
|
|
468
|
+
h, pli = self._embed(ids, media, offsets)
|
|
469
|
+
return h, pli, pos, valid, self._blocks(ids), lens
|
|
470
|
+
|
|
471
|
+
def _trim(self, kv, kpos):
|
|
472
|
+
"""Keys of sliding-window layers: the last window - 1 of each row (a later token sees no earlier ones); a row's
|
|
473
|
+
keys are its first ones (right padding)."""
|
|
474
|
+
t, keep = "sliding_attention", self.window - 1
|
|
475
|
+
if t not in kpos or kpos[t].shape[1] <= keep:
|
|
476
|
+
return kv, kpos
|
|
477
|
+
n = (kpos[t] >= 0).sum(1)
|
|
478
|
+
idx = (n - keep).clamp_min(0)[:, None] + torch.arange(keep, device=n.device)
|
|
479
|
+
ok = idx < n[:, None]
|
|
480
|
+
idx = idx.clamp_max(kpos[t].shape[1] - 1)
|
|
481
|
+
kpos = dict(kpos, **{t: torch.where(ok, kpos[t].gather(1, idx), -1)})
|
|
482
|
+
out = {}
|
|
483
|
+
for i, (K, V) in kv.items():
|
|
484
|
+
if self.types[i] == t:
|
|
485
|
+
g = idx[:, None, :, None].expand(-1, K.shape[1], -1, K.shape[3])
|
|
486
|
+
K, V = K.gather(2, g), V.gather(2, g)
|
|
487
|
+
out[i] = (K, V)
|
|
488
|
+
return out, kpos
|
|
489
|
+
|
|
490
|
+
def _prefix(self, seqs, media=None, bidir=False):
|
|
491
|
+
"""Keys and values of prefixes: short ones in one forward, a long one (alone) in parts through the keys of the
|
|
492
|
+
parts before it: global layers write theirs into buffers of the whole prefix (no copy of the earlier ones per
|
|
493
|
+
part; an 82k-token state of ultra holds 6.7 GB of them), sliding-window layers keep their last window - 1
|
|
494
|
+
after each part, layer by layer (_trim's keys). bidir (a prefix-bidirectional model): one forward whose global
|
|
495
|
+
layers read the prefixes both ways (at most max_prefix tokens each, never in parts)."""
|
|
496
|
+
if bidir:
|
|
497
|
+
h, pli, pos, valid, blk, _ = self._rows(seqs, [0] * len(seqs), media, seqs)
|
|
498
|
+
new, _ = self._pass(h, pli, pos, valid, blk=blk, two_way=True)
|
|
499
|
+
return self._trim(new, {t: torch.where(valid, pos, -1) for t in set(self.types)})
|
|
500
|
+
if len(seqs) == 1 and len(seqs[0]) > self.CHUNK:
|
|
501
|
+
seq, keep = seqs[0], self.window - 1
|
|
502
|
+
# a state over 16k tokens: every global-layer call in parts, from its first part on (its buffers leave
|
|
503
|
+
# no room for the scores of a part over 14k keys in one call: 3.5 GB on ultra at 76k)
|
|
504
|
+
split = len(seq) > self.ATTN_PAIRS // self.CHUNK
|
|
505
|
+
kv, bufs, kpos = {}, {}, None # kpos: set with kv's first keys, at the end of the first part
|
|
506
|
+
at = torch.arange(len(seq), device=self.lm.embed_tokens.weight.device)[None]
|
|
507
|
+
for s0, s1 in self._parts(seq, len(seq)):
|
|
508
|
+
h, pli, pos, valid, blk, _ = self._rows([seq[s0:s1]], [s0], media, seqs)
|
|
509
|
+
new, _ = self._pass(h, pli, pos, valid, ctx=(kv, kpos) if kv else None, blk=blk, split=split)
|
|
510
|
+
for i in list(new):
|
|
511
|
+
k, v = new.pop(i)
|
|
512
|
+
if self.types[i] == "sliding_attention":
|
|
513
|
+
if i in kv:
|
|
514
|
+
k, v = torch.cat([kv[i][0], k], 2), torch.cat([kv[i][1], v], 2)
|
|
515
|
+
kv[i] = (k[:, :, -keep:].clone(), v[:, :, -keep:].clone())
|
|
516
|
+
else:
|
|
517
|
+
if i not in bufs:
|
|
518
|
+
bufs[i] = tuple(x.new_empty(*x.shape[:2], len(seq), x.shape[3]) for x in (k, v))
|
|
519
|
+
bufs[i][0][:, :, s0:s1], bufs[i][1][:, :, s0:s1] = k, v
|
|
520
|
+
kv[i] = (bufs[i][0][:, :, :s1], bufs[i][1][:, :, :s1])
|
|
521
|
+
kpos = {t: at[:, max(0, s1 - keep): s1] if t == "sliding_attention" else at[:, :s1]
|
|
522
|
+
for t in set(self.types)}
|
|
523
|
+
return kv, kpos
|
|
524
|
+
h, pli, pos, valid, blk, _ = self._rows(seqs, [0] * len(seqs), media, seqs)
|
|
525
|
+
new, _ = self._pass(h, pli, pos, valid, blk=blk)
|
|
526
|
+
return self._trim(new, {t: torch.where(valid, pos, -1) for t in set(self.types)})
|
|
527
|
+
|
|
528
|
+
def _shared(self, jobs, groups, out, media=None, bidir=False):
|
|
529
|
+
"""A batch of jobs (group, prompt indices, prefix length): their prefixes once, then every suffix over them,
|
|
530
|
+
in forwards within MAX_BATCH_TOKENS tokens, ATTN_PAIRS query-key pairs and KV_BYTES of repeated keys. bidir:
|
|
531
|
+
the prefixes read both ways in the global layers (a prefix-bidirectional model's state prefixes)."""
|
|
532
|
+
ctx = self._prefix([groups[g][js[0]][:P] for g, js, P in jobs], media, bidir)
|
|
533
|
+
Lc = max(p.shape[1] for p in ctx[1].values())
|
|
534
|
+
rows = sorted(((b, g, j, P) for b, (g, js, P) in enumerate(jobs) for j in js),
|
|
535
|
+
key=lambda r: len(groups[r[1]][r[2]]) - r[3])
|
|
536
|
+
cur = []
|
|
537
|
+
for r in rows + [None]:
|
|
538
|
+
if cur and r is not None:
|
|
539
|
+
n, S = len(cur) + 1, len(groups[r[1]][r[2]]) - r[3]
|
|
540
|
+
if (n * S <= self.MAX_BATCH_TOKENS and n * S * (Lc + S) <= self.ATTN_PAIRS
|
|
541
|
+
and n * (Lc + S) * self.kv_row_bytes <= self.KV_BYTES):
|
|
542
|
+
cur.append(r)
|
|
543
|
+
continue
|
|
544
|
+
if cur:
|
|
545
|
+
prompts = [groups[g][j] for _, g, j, _ in cur]
|
|
546
|
+
h, pli, pos, valid, blk, lens = self._rows([p[P:] for p, (_, _, _, P) in zip(prompts, cur)],
|
|
547
|
+
[P for *_, P in cur], media, prompts)
|
|
548
|
+
grp = torch.tensor([b for b, *_ in cur], device=pos.device)
|
|
549
|
+
_, hid = self._pass(h, pli, pos, valid, ctx=ctx, grp=grp, read=lens - 1, blk=blk,
|
|
550
|
+
split=Lc > self.ATTN_PAIRS // self.CHUNK)
|
|
551
|
+
for (_, g, j, _), x in zip(cur, hid):
|
|
552
|
+
out[g][j] = x
|
|
553
|
+
cur = [r] if r is not None else []
|
|
554
|
+
|
|
555
|
+
def _iso_rows(self, prompts, valid):
|
|
556
|
+
"""Segment ids (0 the prefix, k + 1 option k, n + 1 the suffix), option tokens and shared positions [B, S] of
|
|
557
|
+
OptionIds rows (right padding): every option block starts at the prefix length, the suffix after the longest
|
|
558
|
+
block."""
|
|
559
|
+
B, S = valid.shape
|
|
560
|
+
seg, pos = [], []
|
|
561
|
+
for p in prompts:
|
|
562
|
+
bl = list(getattr(p, "blocks", ()))
|
|
563
|
+
assert len(bl) >= 4 and sum(bl) == len(p), "an OptionIds row without its blocks"
|
|
564
|
+
P, n, longest = bl[0], len(bl) - 2, max(bl[1:-1])
|
|
565
|
+
s = [0] * P + [k + 1 for k in range(n) for _ in range(bl[k + 1])] + [n + 1] * bl[-1]
|
|
566
|
+
q = list(range(P)) + [P + i for b in bl[1:-1] for i in range(b)] + [P + longest + i for i in range(bl[-1])]
|
|
567
|
+
seg.append(s + [-1] * (S - len(s)))
|
|
568
|
+
pos.append(q + [0] * (S - len(q)))
|
|
569
|
+
seg = torch.tensor(seg, device=valid.device)
|
|
570
|
+
last = seg.max(1, keepdim=True).values
|
|
571
|
+
return (seg, (seg > 0) & (seg < last)), torch.tensor(pos, device=valid.device)
|
|
572
|
+
|
|
573
|
+
def _singles(self, items, groups, out, media=None, two_way=False, iso=False):
|
|
574
|
+
"""Prompts without a shared prefix (each at most CHUNK tokens; two-way ones at most max_prompt; with isolated
|
|
575
|
+
options any length): batched by length, one forward each batch."""
|
|
576
|
+
items = sorted(items, key=lambda x: len(groups[x[0]][x[1]]))
|
|
577
|
+
cur = []
|
|
578
|
+
for it in items + [None]:
|
|
579
|
+
if it is not None and (not cur or (len(cur) + 1) * len(groups[it[0]][it[1]]) <= self.MAX_BATCH_TOKENS):
|
|
580
|
+
cur.append(it)
|
|
581
|
+
continue
|
|
582
|
+
if cur:
|
|
583
|
+
prompts = [groups[g][j] for g, j in cur]
|
|
584
|
+
h, pli, pos, valid, blk, lens = self._rows(prompts, [0] * len(cur), media, prompts)
|
|
585
|
+
segs = None
|
|
586
|
+
if iso:
|
|
587
|
+
segs, pos = self._iso_rows(prompts, valid)
|
|
588
|
+
_, hid = self._pass(h, pli, pos, valid, read=lens - 1, blk=blk, two_way=two_way, iso=segs)
|
|
589
|
+
for (g, j), x in zip(cur, hid):
|
|
590
|
+
out[g][j] = x
|
|
591
|
+
cur = [it] if it is not None else []
|
|
592
|
+
|
|
593
|
+
def two_way_rows(self, toks):
|
|
594
|
+
"""Which prompts of one request (token ids) are read two-way: those of at most max_prompt tokens, when the
|
|
595
|
+
request's record (its shared prefix once, then every prompt's own tokens) has at most max_record."""
|
|
596
|
+
if not self.two_way:
|
|
597
|
+
return [False] * len(toks)
|
|
598
|
+
P = len(os.path.commonprefix(toks))
|
|
599
|
+
record = P + sum(len(t) - P for t in toks)
|
|
600
|
+
return [record <= self.two_way["max_record"] and len(t) <= self.two_way["max_prompt"] for t in toks]
|
|
601
|
+
|
|
602
|
+
def _prefix_bidir(self, groups, cuts, media=None):
|
|
603
|
+
"""A prefix-bidirectional model: each group (one request) with a cut P (0 < P <= max_prefix, every prompt longer
|
|
604
|
+
than P and equal over its first P tokens) -> its state prefix once, read both ways, then every prompt's own
|
|
605
|
+
tokens causally over it; the other groups one way."""
|
|
606
|
+
out = [[None] * len(g) for g in groups]
|
|
607
|
+
jobs, rest = [], []
|
|
608
|
+
for gi, toks in enumerate(groups):
|
|
609
|
+
P = cuts[gi] or 0
|
|
610
|
+
if 0 < P <= self.prefix["max_prefix"] and P < min(map(len, toks)) and all(t[:P] == toks[0][:P] for t in toks):
|
|
611
|
+
jobs.append((gi, list(range(len(toks))), P))
|
|
612
|
+
else:
|
|
613
|
+
rest.append(gi)
|
|
614
|
+
for jb in sorted(jobs, key=lambda jb: jb[2]):
|
|
615
|
+
# each prefix alone: its two-way pass and its questions' rows in forwards of their own, so a group's numbers
|
|
616
|
+
# do not depend on the other groups of the engine call (padded bf16 forwards of other shapes move them, and
|
|
617
|
+
# which groups share a call depends on timing: a rank request's concurrent sub-requests)
|
|
618
|
+
self._shared([jb], groups, out, media, bidir=True)
|
|
619
|
+
if rest:
|
|
620
|
+
for gi, hs in zip(rest, self._one_way([groups[gi] for gi in rest], media)):
|
|
621
|
+
out[gi] = hs
|
|
622
|
+
return out
|
|
623
|
+
|
|
624
|
+
@torch.no_grad()
|
|
625
|
+
def hidden(self, groups, media=None, cuts=None):
|
|
626
|
+
"""groups: [[token ids of each prompt]] -> [[final hidden state of each prompt]] ([D] each). The prompts of a
|
|
627
|
+
group share a prefix (the option orders of a question, or every question of a request); media ({kind: soft
|
|
628
|
+
tokens}, media_features) are those of every prompt (one request). A two-way model: each group is a request;
|
|
629
|
+
its two-way prompts are read whole, one by one (nothing shared: their state depends on the question), the
|
|
630
|
+
others one way as below. Isolated options: every prompt (OptionIds) whole, nothing shared. A
|
|
631
|
+
prefix-bidirectional model: cuts [P per group] (the server's state cuts) -> _prefix_bidir. A dual model (both
|
|
632
|
+
readings): the groups with a cut (requests of several questions) _prefix_bidir, the others two-way."""
|
|
633
|
+
if self.iso:
|
|
634
|
+
assert not media, "isolated options: text prompts only"
|
|
635
|
+
out = [[None] * len(g) for g in groups]
|
|
636
|
+
self._singles([(gi, j) for gi, g in enumerate(groups) for j in range(len(g))], groups, out, iso=True)
|
|
637
|
+
return out
|
|
638
|
+
cuts = cuts or [None] * len(groups)
|
|
639
|
+
if self.prefix and self.two_way:
|
|
640
|
+
out = [None] * len(groups)
|
|
641
|
+
for want, fn in ((True, self._prefix_bidir), (False, None)):
|
|
642
|
+
gis = [gi for gi, c in enumerate(cuts) if bool(c) == want]
|
|
643
|
+
if not gis:
|
|
644
|
+
continue
|
|
645
|
+
part = [groups[gi] for gi in gis]
|
|
646
|
+
hs = fn(part, [cuts[gi] for gi in gis], media) if fn else self._two_way(part, media)
|
|
647
|
+
for gi, h in zip(gis, hs):
|
|
648
|
+
out[gi] = h
|
|
649
|
+
return out
|
|
650
|
+
if self.prefix:
|
|
651
|
+
return self._prefix_bidir(groups, cuts, media)
|
|
652
|
+
if not self.two_way:
|
|
653
|
+
return self._one_way(groups, media)
|
|
654
|
+
return self._two_way(groups, media)
|
|
655
|
+
|
|
656
|
+
def _two_way(self, groups, media=None):
|
|
657
|
+
"""A two-way model's groups: the prompts within the limits read whole, one by one, the others one way."""
|
|
658
|
+
out = [[None] * len(g) for g in groups]
|
|
659
|
+
both, rest = [], []
|
|
660
|
+
for gi, toks in enumerate(groups):
|
|
661
|
+
ok = self.two_way_rows(toks)
|
|
662
|
+
both += [(gi, j) for j, o in enumerate(ok) if o]
|
|
663
|
+
if not all(ok):
|
|
664
|
+
rest.append((gi, [j for j, o in enumerate(ok) if not o]))
|
|
665
|
+
if both:
|
|
666
|
+
self._singles(both, groups, out, media, two_way=True)
|
|
667
|
+
if rest:
|
|
668
|
+
for (gi, js), hs in zip(rest, self._one_way([[groups[gi][j] for j in js] for gi, js in rest], media)):
|
|
669
|
+
for j, h in zip(js, hs):
|
|
670
|
+
out[gi][j] = h
|
|
671
|
+
return out
|
|
672
|
+
|
|
673
|
+
def _one_way(self, groups, media=None):
|
|
674
|
+
out = [[None] * len(g) for g in groups]
|
|
675
|
+
jobs, singles = [], []
|
|
676
|
+
for gi, toks in enumerate(groups):
|
|
677
|
+
if len(toks) > 1:
|
|
678
|
+
P = self._run_start(toks[0], min(len(os.path.commonprefix(toks)), min(map(len, toks)) - 1))
|
|
679
|
+
if P > 0 and max(map(len, toks)) - P <= self.CHUNK:
|
|
680
|
+
jobs.append((gi, list(range(len(toks))), P))
|
|
681
|
+
continue
|
|
682
|
+
for j, t in enumerate(toks):
|
|
683
|
+
if len(t) <= self.CHUNK:
|
|
684
|
+
singles.append((gi, j))
|
|
685
|
+
continue
|
|
686
|
+
# a long prompt alone: its CHUNK-token parts through the keys of the earlier ones, the last part reads
|
|
687
|
+
P = self._run_start(t, (len(t) - 1) // self.CHUNK * self.CHUNK)
|
|
688
|
+
if P > 0:
|
|
689
|
+
jobs.append((gi, [j], P))
|
|
690
|
+
else:
|
|
691
|
+
singles.append((gi, j))
|
|
692
|
+
if singles:
|
|
693
|
+
self._singles(singles, groups, out, media)
|
|
694
|
+
jobs.sort(key=lambda jb: jb[2])
|
|
695
|
+
cur = []
|
|
696
|
+
for jb in jobs + [None]:
|
|
697
|
+
if jb is not None and jb[2] <= self.CHUNK and (not cur or (len(cur) + 1) * jb[2] <= self.MAX_BATCH_TOKENS):
|
|
698
|
+
cur.append(jb)
|
|
699
|
+
continue
|
|
700
|
+
if cur:
|
|
701
|
+
self._shared(cur, groups, out, media)
|
|
702
|
+
cur = []
|
|
703
|
+
if jb is not None and jb[2] > self.CHUNK:
|
|
704
|
+
self._shared([jb], groups, out, media)
|
|
705
|
+
elif jb is not None:
|
|
706
|
+
cur = [jb]
|
|
707
|
+
if jobs and jobs[-1][2] > self.ATTN_PAIRS // self.CHUNK and self.lm.embed_tokens.weight.is_cuda:
|
|
708
|
+
torch.cuda.empty_cache() # a state over 16k tokens: its parts' cached blocks back to the GPU (as the fast
|
|
709
|
+
# engine's long roots: after one large request the next ones ran out of memory sooner, ultra, 20 Oct)
|
|
710
|
+
return out
|
|
711
|
+
|
|
712
|
+
@torch.no_grad()
|
|
713
|
+
def media_features(self, enc):
|
|
714
|
+
"""The soft tokens of a request's media from one prompt's processor output ({kind: [n, D]}): the image and audio
|
|
715
|
+
towers run once for all prompts of the request."""
|
|
716
|
+
mm, w = self.model.model, self.lm.embed_tokens.weight
|
|
717
|
+
out = {}
|
|
718
|
+
if enc.get("pixel_values") is not None:
|
|
719
|
+
f = mm.get_image_features(enc["pixel_values"].to(w.device, w.dtype), enc["image_position_ids"].to(w.device),
|
|
720
|
+
return_dict=True).pooler_output
|
|
721
|
+
out["image"] = torch.cat(f, 0).to(w.dtype)
|
|
722
|
+
if enc.get("input_features") is not None and enc.get("input_features_mask") is not None:
|
|
723
|
+
a = mm.get_audio_features(enc["input_features"].to(w.device, w.dtype),
|
|
724
|
+
enc["input_features_mask"].to(w.device), return_dict=True)
|
|
725
|
+
out["audio"] = a.pooler_output[a.attention_mask.to(a.pooler_output.device)].to(w.dtype)
|
|
726
|
+
return out
|