model-runtime 0.5.0__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.
- model_runtime-0.5.0.dist-info/METADATA +618 -0
- model_runtime-0.5.0.dist-info/RECORD +36 -0
- model_runtime-0.5.0.dist-info/WHEEL +4 -0
- model_runtime-0.5.0.dist-info/entry_points.txt +2 -0
- model_runtime-0.5.0.dist-info/licenses/LICENSE +202 -0
- model_runtime-0.5.0.dist-info/licenses/NOTICE +6 -0
- saturn/__init__.py +28 -0
- saturn/adapters/__init__.py +63 -0
- saturn/adapters/_residency.py +196 -0
- saturn/adapters/decoder.py +1679 -0
- saturn/adapters/diffusion.py +438 -0
- saturn/adapters/flux1.py +661 -0
- saturn/adapters/flux2.py +630 -0
- saturn/adapters/mamba.py +620 -0
- saturn/adapters/qwen.py +637 -0
- saturn/causal.py +260 -0
- saturn/cli.py +382 -0
- saturn/contracts.py +175 -0
- saturn/core.py +1979 -0
- saturn/dependencies.py +61 -0
- saturn/interop/__init__.py +37 -0
- saturn/interop/circuit_tracer.py +1198 -0
- saturn/investigation.py +109 -0
- saturn/numerics.py +213 -0
- saturn/observers.py +289 -0
- saturn/paths.py +324 -0
- saturn/program.py +364 -0
- saturn/route.py +774 -0
- saturn/shared_store.py +257 -0
- saturn/store.py +835 -0
- saturn/symbols.py +398 -0
- saturn/training/__init__.py +61 -0
- saturn/training/_checkpoint.py +1618 -0
- saturn/trial.py +514 -0
- saturn/values.py +223 -0
- saturn/writers.py +82 -0
saturn/adapters/qwen.py
ADDED
|
@@ -0,0 +1,637 @@
|
|
|
1
|
+
"""Batch-one, greedy Qwen2 token/layer machine using native HF decoder layers."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import platform
|
|
6
|
+
from collections.abc import Mapping, Sequence
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
import torch
|
|
10
|
+
import transformers
|
|
11
|
+
from transformers import DynamicCache, Qwen2Config, Qwen2ForCausalLM
|
|
12
|
+
|
|
13
|
+
from ..contracts import ExecutionPoint, SlotSpec, SurfaceManifest, TransitionSpec
|
|
14
|
+
from ..core import Adapter, Session
|
|
15
|
+
from ..numerics import check_numeric_environment, live_numeric_environment
|
|
16
|
+
from ..values import clone, digest, identity
|
|
17
|
+
from ._residency import BlockResidency
|
|
18
|
+
from .decoder import _causal_mask_kwargs
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _stable_configuration(value: Any, *, key: str = "") -> Any:
|
|
22
|
+
if isinstance(value, Mapping):
|
|
23
|
+
return {name: _stable_configuration(item, key=name) for name, item in value.items()}
|
|
24
|
+
if isinstance(value, (tuple, list)):
|
|
25
|
+
items = [_stable_configuration(item) for item in value]
|
|
26
|
+
return sorted(items) if key == "_use_default_values" else items
|
|
27
|
+
return value
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _tensor_guards(module: Any, *, prefix: str = "") -> tuple[tuple[Any, ...], ...]:
|
|
31
|
+
return tuple(
|
|
32
|
+
(
|
|
33
|
+
f"{prefix}{name}",
|
|
34
|
+
id(value),
|
|
35
|
+
value._version,
|
|
36
|
+
value.data_ptr(),
|
|
37
|
+
value.untyped_storage().data_ptr(),
|
|
38
|
+
)
|
|
39
|
+
for name, value in (*module.named_parameters(), *module.named_buffers())
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class QwenAdapter(Adapter):
|
|
44
|
+
def __init__(
|
|
45
|
+
self,
|
|
46
|
+
model: Qwen2ForCausalLM,
|
|
47
|
+
*,
|
|
48
|
+
granularity: str = "layer",
|
|
49
|
+
residency: str = "resident",
|
|
50
|
+
device: Any = None,
|
|
51
|
+
pin_host: bool = False,
|
|
52
|
+
prefetch: bool = False,
|
|
53
|
+
host_embedding: bool = False,
|
|
54
|
+
):
|
|
55
|
+
if model.config.model_type != "qwen2":
|
|
56
|
+
raise ValueError("v1 supports Qwen2/Qwen2.5 full-attention models")
|
|
57
|
+
if getattr(model.config, "use_sliding_window", False):
|
|
58
|
+
raise ValueError("sliding-window attention is not supported")
|
|
59
|
+
if model.config._attn_implementation != "eager":
|
|
60
|
+
raise ValueError("QwenAdapter requires attn_implementation='eager'")
|
|
61
|
+
if granularity not in {"layer", "operation"}:
|
|
62
|
+
raise ValueError("granularity must be 'layer' or 'operation'")
|
|
63
|
+
self.model = model.eval()
|
|
64
|
+
self.granularity = granularity
|
|
65
|
+
# Block-streamed residency parks frozen weights in host memory and copies one native
|
|
66
|
+
# module to the execution device at a time; place() precedes the frozen guard because
|
|
67
|
+
# host pinning reassigns parameter storage.
|
|
68
|
+
if residency == "streamed":
|
|
69
|
+
target = (
|
|
70
|
+
device if device is not None else ("cuda" if torch.cuda.is_available() else "cpu")
|
|
71
|
+
)
|
|
72
|
+
self._residency = BlockResidency(
|
|
73
|
+
target,
|
|
74
|
+
mode="streamed",
|
|
75
|
+
pin_host=pin_host,
|
|
76
|
+
prefetch=prefetch,
|
|
77
|
+
host_embedding=host_embedding,
|
|
78
|
+
)
|
|
79
|
+
else:
|
|
80
|
+
target = device if device is not None else next(model.parameters()).device
|
|
81
|
+
self._residency = BlockResidency(target, mode="resident")
|
|
82
|
+
self._residency.place(self.model)
|
|
83
|
+
self.device = self._residency.device
|
|
84
|
+
self.dtype = next(model.parameters()).dtype
|
|
85
|
+
self.layers = len(model.model.layers)
|
|
86
|
+
configuration = _stable_configuration(model.config.to_dict())
|
|
87
|
+
self._configuration_fingerprint = digest(configuration)
|
|
88
|
+
self.model_identity = identity(model, configuration)
|
|
89
|
+
self._frozen_versions = _tensor_guards(model)
|
|
90
|
+
self.execution = {
|
|
91
|
+
"family": "qwen2",
|
|
92
|
+
"adapter": "native-boundary-v2",
|
|
93
|
+
"granularity": granularity,
|
|
94
|
+
"attention": "eager",
|
|
95
|
+
"dtype": str(self.dtype),
|
|
96
|
+
"device": {"type": self.device.type, "index": self.device.index},
|
|
97
|
+
"batch": {"size": 1, "padding": False},
|
|
98
|
+
"environment_versions": {
|
|
99
|
+
"torch": torch.__version__,
|
|
100
|
+
"transformers": transformers.__version__,
|
|
101
|
+
"python": platform.python_version(),
|
|
102
|
+
},
|
|
103
|
+
"model_program": (
|
|
104
|
+
"embed->decoder_layer[*]->rms_norm->lm_head->greedy_argmax->token_commit"
|
|
105
|
+
),
|
|
106
|
+
"kernel": {"attention": "transformers-eager", "cache": "DynamicCache"},
|
|
107
|
+
"numeric_scope": {
|
|
108
|
+
"inference_mode": True,
|
|
109
|
+
"autocast": False,
|
|
110
|
+
**live_numeric_environment(),
|
|
111
|
+
"tensor_layout": "state-slot-bound-stride",
|
|
112
|
+
},
|
|
113
|
+
"sampler": "greedy",
|
|
114
|
+
"parity": "bounded-logits",
|
|
115
|
+
}
|
|
116
|
+
# Resident execution keeps the historical contract verbatim; only streamed residency
|
|
117
|
+
# adds a field, so existing resident receipts stay byte-identical.
|
|
118
|
+
if self._residency.mode == "streamed":
|
|
119
|
+
self.execution["residency"] = self._residency.to_dict()
|
|
120
|
+
|
|
121
|
+
@classmethod
|
|
122
|
+
def tiny(
|
|
123
|
+
cls,
|
|
124
|
+
seed: int = 7,
|
|
125
|
+
*,
|
|
126
|
+
granularity: str = "layer",
|
|
127
|
+
residency: str = "resident",
|
|
128
|
+
device: Any = None,
|
|
129
|
+
pin_host: bool = False,
|
|
130
|
+
prefetch: bool = False,
|
|
131
|
+
host_embedding: bool = False,
|
|
132
|
+
) -> QwenAdapter:
|
|
133
|
+
with torch.random.fork_rng():
|
|
134
|
+
torch.manual_seed(seed)
|
|
135
|
+
config = Qwen2Config(
|
|
136
|
+
vocab_size=64,
|
|
137
|
+
hidden_size=32,
|
|
138
|
+
intermediate_size=64,
|
|
139
|
+
num_hidden_layers=2,
|
|
140
|
+
num_attention_heads=4,
|
|
141
|
+
num_key_value_heads=2,
|
|
142
|
+
head_dim=8,
|
|
143
|
+
max_position_embeddings=128,
|
|
144
|
+
attn_implementation="eager",
|
|
145
|
+
)
|
|
146
|
+
return cls(
|
|
147
|
+
Qwen2ForCausalLM(config),
|
|
148
|
+
granularity=granularity,
|
|
149
|
+
residency=residency,
|
|
150
|
+
device=device,
|
|
151
|
+
pin_host=pin_host,
|
|
152
|
+
prefetch=prefetch,
|
|
153
|
+
host_embedding=host_embedding,
|
|
154
|
+
)
|
|
155
|
+
|
|
156
|
+
@classmethod
|
|
157
|
+
def from_pretrained(
|
|
158
|
+
cls,
|
|
159
|
+
path: str,
|
|
160
|
+
*,
|
|
161
|
+
granularity: str = "layer",
|
|
162
|
+
residency: str = "resident",
|
|
163
|
+
device: Any = None,
|
|
164
|
+
pin_host: bool = False,
|
|
165
|
+
prefetch: bool = False,
|
|
166
|
+
host_embedding: bool = False,
|
|
167
|
+
**kwargs: Any,
|
|
168
|
+
) -> QwenAdapter:
|
|
169
|
+
return cls(
|
|
170
|
+
Qwen2ForCausalLM.from_pretrained(path, attn_implementation="eager", **kwargs),
|
|
171
|
+
granularity=granularity,
|
|
172
|
+
residency=residency,
|
|
173
|
+
device=device,
|
|
174
|
+
pin_host=pin_host,
|
|
175
|
+
prefetch=prefetch,
|
|
176
|
+
host_embedding=host_embedding,
|
|
177
|
+
)
|
|
178
|
+
|
|
179
|
+
def _verify_frozen_model(self) -> None:
|
|
180
|
+
current = _tensor_guards(self.model)
|
|
181
|
+
if current != self._frozen_versions:
|
|
182
|
+
raise ValueError(
|
|
183
|
+
"model parameters or buffers changed after adapter identity was frozen; "
|
|
184
|
+
"rewrap the model in a new adapter"
|
|
185
|
+
)
|
|
186
|
+
|
|
187
|
+
def validate_execution(self) -> None:
|
|
188
|
+
self._verify_frozen_model()
|
|
189
|
+
if (
|
|
190
|
+
digest(_stable_configuration(self.model.config.to_dict()))
|
|
191
|
+
!= self._configuration_fingerprint
|
|
192
|
+
):
|
|
193
|
+
raise ValueError(
|
|
194
|
+
"model configuration changed after adapter identity was frozen; rewrap"
|
|
195
|
+
)
|
|
196
|
+
check_numeric_environment(self.execution["numeric_scope"])
|
|
197
|
+
|
|
198
|
+
def _cache(self, keys: Sequence[torch.Tensor], values: Sequence[torch.Tensor]) -> DynamicCache:
|
|
199
|
+
cache = DynamicCache(config=self.model.config)
|
|
200
|
+
for index, (key, value) in enumerate(zip(keys, values)):
|
|
201
|
+
if key.shape[-2]:
|
|
202
|
+
cache.update(key.to(self.device), value.to(self.device), index)
|
|
203
|
+
return cache
|
|
204
|
+
|
|
205
|
+
def _cache_values(self, cache: DynamicCache) -> tuple[list[torch.Tensor], list[torch.Tensor]]:
|
|
206
|
+
shape = (
|
|
207
|
+
1,
|
|
208
|
+
self.model.config.num_key_value_heads,
|
|
209
|
+
0,
|
|
210
|
+
self.model.config.hidden_size // self.model.config.num_attention_heads,
|
|
211
|
+
)
|
|
212
|
+
keys, values = [], []
|
|
213
|
+
for layer in cache.layers:
|
|
214
|
+
keys.append(
|
|
215
|
+
clone(layer.keys)
|
|
216
|
+
if layer.keys is not None
|
|
217
|
+
else torch.empty(shape, device=self.device, dtype=self.dtype)
|
|
218
|
+
)
|
|
219
|
+
values.append(
|
|
220
|
+
clone(layer.values)
|
|
221
|
+
if layer.values is not None
|
|
222
|
+
else torch.empty(shape, device=self.device, dtype=self.dtype)
|
|
223
|
+
)
|
|
224
|
+
return keys, values
|
|
225
|
+
|
|
226
|
+
def _streamed_backbone(self, tokens: torch.Tensor) -> tuple[torch.Tensor, DynamicCache]:
|
|
227
|
+
"""Block-streamed replica of the Qwen2 backbone forward over a full token span.
|
|
228
|
+
|
|
229
|
+
Streams the embedding, rotary, and every decoder layer one module at a time while the
|
|
230
|
+
model's own ``create_causal_mask`` builds the eager mask. Byte-preserving copies and
|
|
231
|
+
``functional_call`` substitution make the returned hidden state and key/value cache
|
|
232
|
+
bitwise-identical to a resident ``model(tokens)`` forward on the same device. Used only
|
|
233
|
+
in streamed residency, where the whole model may not fit the device.
|
|
234
|
+
"""
|
|
235
|
+
from transformers.masking_utils import create_causal_mask
|
|
236
|
+
|
|
237
|
+
run = self._residency.run
|
|
238
|
+
length = tokens.shape[1]
|
|
239
|
+
hidden = run(self.model.model.embed_tokens, tokens)
|
|
240
|
+
position_ids = torch.arange(length, device=self.device).unsqueeze(0)
|
|
241
|
+
cache = DynamicCache(config=self.model.config)
|
|
242
|
+
cache_position = torch.arange(length, device=self.device)
|
|
243
|
+
mask = create_causal_mask(
|
|
244
|
+
**_causal_mask_kwargs(
|
|
245
|
+
create_causal_mask,
|
|
246
|
+
config=self.model.config,
|
|
247
|
+
hidden=hidden,
|
|
248
|
+
cache=cache,
|
|
249
|
+
position_ids=position_ids,
|
|
250
|
+
cache_position=cache_position,
|
|
251
|
+
)
|
|
252
|
+
)
|
|
253
|
+
position_embeddings = run(self.model.model.rotary_emb, hidden, position_ids)
|
|
254
|
+
for layer in self.model.model.layers:
|
|
255
|
+
hidden = run(
|
|
256
|
+
layer,
|
|
257
|
+
hidden,
|
|
258
|
+
attention_mask=mask,
|
|
259
|
+
position_ids=position_ids,
|
|
260
|
+
past_key_values=cache,
|
|
261
|
+
position_embeddings=position_embeddings,
|
|
262
|
+
use_cache=True,
|
|
263
|
+
)
|
|
264
|
+
return hidden, cache
|
|
265
|
+
|
|
266
|
+
@torch.inference_mode()
|
|
267
|
+
def session(self, token_ids: Sequence[int]) -> Session:
|
|
268
|
+
self.validate_execution()
|
|
269
|
+
tokens = torch.tensor([list(token_ids)], dtype=torch.long, device=self.device)
|
|
270
|
+
if tokens.shape[-1] < 1:
|
|
271
|
+
raise ValueError("at least one pending token is required")
|
|
272
|
+
cache = DynamicCache(config=self.model.config)
|
|
273
|
+
if tokens.shape[-1] > 1:
|
|
274
|
+
if self._residency.mode == "streamed":
|
|
275
|
+
cache = self._streamed_backbone(tokens[:, :-1])[1]
|
|
276
|
+
else:
|
|
277
|
+
cache = self.model(tokens[:, :-1], use_cache=True).past_key_values
|
|
278
|
+
keys, values = self._cache_values(cache)
|
|
279
|
+
return Session(
|
|
280
|
+
self,
|
|
281
|
+
{
|
|
282
|
+
"tokens": tokens,
|
|
283
|
+
"keys": keys,
|
|
284
|
+
"values": values,
|
|
285
|
+
"layer": 0,
|
|
286
|
+
"phase": "embed",
|
|
287
|
+
"hidden": None,
|
|
288
|
+
"logits": None,
|
|
289
|
+
"sampled_token": None,
|
|
290
|
+
},
|
|
291
|
+
)
|
|
292
|
+
|
|
293
|
+
def boundary(self, state: Mapping[str, Any]) -> str:
|
|
294
|
+
if self.granularity == "layer":
|
|
295
|
+
if state["hidden"] is None:
|
|
296
|
+
return "token"
|
|
297
|
+
return f"layer:{state['layer']}"
|
|
298
|
+
phase = state["phase"]
|
|
299
|
+
if phase == "layer":
|
|
300
|
+
return f"token:{state['tokens'].shape[1] - 1}/layer:{state['layer']}"
|
|
301
|
+
return f"token:{state['tokens'].shape[1] - 1}/{phase}"
|
|
302
|
+
|
|
303
|
+
def point(self, state: Mapping[str, Any]) -> ExecutionPoint:
|
|
304
|
+
phase = state["phase"]
|
|
305
|
+
operator = phase
|
|
306
|
+
index = state["layer"] if phase == "layer" else None
|
|
307
|
+
next_operation = {
|
|
308
|
+
"embed": "model.embed_tokens",
|
|
309
|
+
"normalization": "model.norm",
|
|
310
|
+
"readout": "lm_head",
|
|
311
|
+
"sample": "greedy_argmax",
|
|
312
|
+
"commit": "token_commit",
|
|
313
|
+
}.get(
|
|
314
|
+
phase,
|
|
315
|
+
(
|
|
316
|
+
f"decoder_layer.{state['layer']}"
|
|
317
|
+
if state["layer"] < self.layers
|
|
318
|
+
else "normalization_readout_sampler_commit"
|
|
319
|
+
),
|
|
320
|
+
)
|
|
321
|
+
return ExecutionPoint(
|
|
322
|
+
family="qwen2",
|
|
323
|
+
logical_step=state["tokens"].shape[1] - 1,
|
|
324
|
+
phase=phase,
|
|
325
|
+
operator=operator,
|
|
326
|
+
index=index,
|
|
327
|
+
edge="before",
|
|
328
|
+
next_operation=next_operation,
|
|
329
|
+
local_clock=state["layer"],
|
|
330
|
+
)
|
|
331
|
+
|
|
332
|
+
def transition(self, state: Mapping[str, Any]) -> TransitionSpec:
|
|
333
|
+
phase = state["phase"]
|
|
334
|
+
if state["hidden"] is None:
|
|
335
|
+
reads, writes = ("tokens",), ("hidden", "logits", "phase")
|
|
336
|
+
elif state["layer"] < self.layers:
|
|
337
|
+
reads = ("tokens", "hidden", "keys", "values", "layer")
|
|
338
|
+
writes = ("hidden", "keys", "values", "layer", "phase")
|
|
339
|
+
elif self.granularity == "operation":
|
|
340
|
+
reads, writes = {
|
|
341
|
+
"normalization": (("hidden",), ("hidden", "phase")),
|
|
342
|
+
"readout": (("hidden",), ("logits", "phase")),
|
|
343
|
+
"sample": (("logits",), ("sampled_token", "phase")),
|
|
344
|
+
"commit": (
|
|
345
|
+
("tokens", "sampled_token"),
|
|
346
|
+
("tokens", "hidden", "sampled_token", "layer", "phase"),
|
|
347
|
+
),
|
|
348
|
+
}[phase]
|
|
349
|
+
else:
|
|
350
|
+
reads = ("hidden", "tokens")
|
|
351
|
+
writes = ("logits", "tokens", "hidden", "layer", "phase")
|
|
352
|
+
return TransitionSpec(
|
|
353
|
+
self.point(state).next_operation,
|
|
354
|
+
reads,
|
|
355
|
+
writes,
|
|
356
|
+
consumer="native-qwen2-suffix",
|
|
357
|
+
footprint="declared",
|
|
358
|
+
)
|
|
359
|
+
|
|
360
|
+
def surface(self, state: Mapping[str, Any]) -> SurfaceManifest:
|
|
361
|
+
def tensor_schema(value: torch.Tensor | None, *, optional: bool = False) -> dict[str, Any]:
|
|
362
|
+
if value is None:
|
|
363
|
+
return {"kind": "tensor", "optional": optional}
|
|
364
|
+
return {
|
|
365
|
+
"kind": "tensor",
|
|
366
|
+
"shape": list(value.shape),
|
|
367
|
+
"stride": list(value.stride()),
|
|
368
|
+
"dtype": str(value.dtype),
|
|
369
|
+
"device": str(value.device),
|
|
370
|
+
"optional": optional,
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
slots = (
|
|
374
|
+
SlotSpec(
|
|
375
|
+
"tokens",
|
|
376
|
+
role="cursor",
|
|
377
|
+
producer="token_commit",
|
|
378
|
+
consumer="embed",
|
|
379
|
+
schema=tensor_schema(state["tokens"]),
|
|
380
|
+
),
|
|
381
|
+
SlotSpec(
|
|
382
|
+
"keys",
|
|
383
|
+
role="cache",
|
|
384
|
+
producer="decoder_layer",
|
|
385
|
+
consumer="attention",
|
|
386
|
+
schema={"kind": "tensor_sequence", "length": self.layers},
|
|
387
|
+
),
|
|
388
|
+
SlotSpec(
|
|
389
|
+
"values",
|
|
390
|
+
role="cache",
|
|
391
|
+
producer="decoder_layer",
|
|
392
|
+
consumer="attention",
|
|
393
|
+
schema={"kind": "tensor_sequence", "length": self.layers},
|
|
394
|
+
),
|
|
395
|
+
SlotSpec(
|
|
396
|
+
"hidden",
|
|
397
|
+
role="carrier",
|
|
398
|
+
writable=state["hidden"] is not None,
|
|
399
|
+
persistence="authoritative",
|
|
400
|
+
producer="embed_or_layer",
|
|
401
|
+
consumer="native_suffix",
|
|
402
|
+
schema=tensor_schema(state["hidden"], optional=True),
|
|
403
|
+
),
|
|
404
|
+
SlotSpec(
|
|
405
|
+
"logits",
|
|
406
|
+
role="observation",
|
|
407
|
+
producer="lm_head",
|
|
408
|
+
consumer="greedy_argmax",
|
|
409
|
+
schema=tensor_schema(state["logits"], optional=True),
|
|
410
|
+
),
|
|
411
|
+
SlotSpec(
|
|
412
|
+
"sampled_token",
|
|
413
|
+
role="decision",
|
|
414
|
+
producer="greedy_argmax",
|
|
415
|
+
consumer="token_commit",
|
|
416
|
+
schema=tensor_schema(state["sampled_token"], optional=True),
|
|
417
|
+
),
|
|
418
|
+
SlotSpec(
|
|
419
|
+
"layer",
|
|
420
|
+
role="clock",
|
|
421
|
+
producer="decoder_layer",
|
|
422
|
+
consumer="runtime",
|
|
423
|
+
schema={"kind": "integer", "minimum": 0, "maximum": self.layers},
|
|
424
|
+
),
|
|
425
|
+
SlotSpec(
|
|
426
|
+
"phase",
|
|
427
|
+
role="clock",
|
|
428
|
+
producer="runtime",
|
|
429
|
+
consumer="runtime",
|
|
430
|
+
schema={
|
|
431
|
+
"kind": "enum",
|
|
432
|
+
"values": ["embed", "layer", "normalization", "readout", "sample", "commit"],
|
|
433
|
+
},
|
|
434
|
+
),
|
|
435
|
+
)
|
|
436
|
+
return SurfaceManifest(
|
|
437
|
+
slots=slots,
|
|
438
|
+
state_schema="saturn-pub-qwen2-state-v2",
|
|
439
|
+
consumer="native-qwen2-suffix",
|
|
440
|
+
horizon="native-autoregressive-suffix",
|
|
441
|
+
)
|
|
442
|
+
|
|
443
|
+
def addresses(self, state: Mapping[str, Any]) -> tuple[str, ...]:
|
|
444
|
+
result = ("tokens",)
|
|
445
|
+
if state["hidden"] is not None:
|
|
446
|
+
result += ("hidden",)
|
|
447
|
+
if state["logits"] is not None:
|
|
448
|
+
result += ("logits",)
|
|
449
|
+
return result
|
|
450
|
+
|
|
451
|
+
def validate(self, state: Mapping[str, Any]) -> None:
|
|
452
|
+
self._verify_frozen_model()
|
|
453
|
+
expected_keys = {
|
|
454
|
+
"tokens",
|
|
455
|
+
"keys",
|
|
456
|
+
"values",
|
|
457
|
+
"layer",
|
|
458
|
+
"phase",
|
|
459
|
+
"hidden",
|
|
460
|
+
"logits",
|
|
461
|
+
"sampled_token",
|
|
462
|
+
}
|
|
463
|
+
if set(state) != expected_keys:
|
|
464
|
+
raise ValueError("Qwen state schema keys differ from the execution contract")
|
|
465
|
+
tokens = state["tokens"]
|
|
466
|
+
if (
|
|
467
|
+
tokens.ndim != 2
|
|
468
|
+
or tokens.shape[0] != 1
|
|
469
|
+
or tokens.dtype != torch.long
|
|
470
|
+
or tokens.device != self.device
|
|
471
|
+
):
|
|
472
|
+
raise ValueError("Qwen state requires batch-one integer tokens")
|
|
473
|
+
if not 0 < tokens.shape[1] <= self.model.config.max_position_embeddings:
|
|
474
|
+
raise ValueError("token count outside configured context")
|
|
475
|
+
if (tokens < 0).any() or (tokens >= self.model.config.vocab_size).any():
|
|
476
|
+
raise ValueError("token ID outside vocabulary")
|
|
477
|
+
layer = state["layer"]
|
|
478
|
+
if type(layer) is not int or not 0 <= layer <= self.layers:
|
|
479
|
+
raise ValueError("invalid layer cursor")
|
|
480
|
+
phase = state["phase"]
|
|
481
|
+
allowed_phases = {"embed", "layer"}
|
|
482
|
+
if self.granularity == "operation":
|
|
483
|
+
allowed_phases |= {"normalization", "readout", "sample", "commit"}
|
|
484
|
+
if phase not in allowed_phases:
|
|
485
|
+
raise ValueError("invalid Qwen operation phase")
|
|
486
|
+
if phase == "embed" and (state["hidden"] is not None or layer != 0):
|
|
487
|
+
raise ValueError("invalid embedding boundary closure")
|
|
488
|
+
if phase != "embed" and state["hidden"] is None:
|
|
489
|
+
raise ValueError("missing hidden carrier")
|
|
490
|
+
if phase == "layer" and layer > self.layers:
|
|
491
|
+
raise ValueError("layer phase exceeds the native layer program")
|
|
492
|
+
if self.granularity == "operation" and phase == "layer" and layer == self.layers:
|
|
493
|
+
raise ValueError("operation mode must expose the normalization boundary")
|
|
494
|
+
if phase in {"normalization", "readout", "sample", "commit"} and layer != self.layers:
|
|
495
|
+
raise ValueError("post-layer phase requires a complete decoder stack")
|
|
496
|
+
expected = tokens.shape[1] - 1
|
|
497
|
+
keys, values = state["keys"], state["values"]
|
|
498
|
+
if len(keys) != self.layers or len(values) != self.layers:
|
|
499
|
+
raise ValueError("missing layer K/V")
|
|
500
|
+
for index, (key, value) in enumerate(zip(keys, values)):
|
|
501
|
+
length = expected + (1 if state["hidden"] is not None and index < layer else 0)
|
|
502
|
+
shape = (
|
|
503
|
+
1,
|
|
504
|
+
self.model.config.num_key_value_heads,
|
|
505
|
+
length,
|
|
506
|
+
self.model.config.hidden_size // self.model.config.num_attention_heads,
|
|
507
|
+
)
|
|
508
|
+
if tuple(key.shape) != shape or tuple(value.shape) != shape:
|
|
509
|
+
raise ValueError("K/V closure does not match token/layer cursor")
|
|
510
|
+
if key.dtype != self.dtype or value.dtype != self.dtype:
|
|
511
|
+
raise ValueError("K/V dtype mismatch")
|
|
512
|
+
if key.device != self.device or value.device != self.device:
|
|
513
|
+
raise ValueError("K/V device mismatch")
|
|
514
|
+
if not torch.isfinite(key).all() or not torch.isfinite(value).all():
|
|
515
|
+
raise ValueError("non-finite K/V")
|
|
516
|
+
hidden = state["hidden"]
|
|
517
|
+
if hidden is not None and (
|
|
518
|
+
tuple(hidden.shape) != (1, 1, self.model.config.hidden_size)
|
|
519
|
+
or hidden.dtype != self.dtype
|
|
520
|
+
or hidden.device != self.device
|
|
521
|
+
or not torch.isfinite(hidden).all()
|
|
522
|
+
):
|
|
523
|
+
raise ValueError("invalid hidden carrier")
|
|
524
|
+
logits = state["logits"]
|
|
525
|
+
if logits is not None and (
|
|
526
|
+
tuple(logits.shape) != (1, self.model.config.vocab_size)
|
|
527
|
+
or logits.dtype != self.dtype
|
|
528
|
+
or logits.device != self.device
|
|
529
|
+
or not torch.isfinite(logits).all()
|
|
530
|
+
):
|
|
531
|
+
raise ValueError("invalid logit observation")
|
|
532
|
+
if phase in {"sample", "commit"} and logits is None:
|
|
533
|
+
raise ValueError("sampling requires the native logit observation")
|
|
534
|
+
sampled = state["sampled_token"]
|
|
535
|
+
if sampled is not None and (
|
|
536
|
+
tuple(sampled.shape) != (1, 1)
|
|
537
|
+
or sampled.dtype != torch.long
|
|
538
|
+
or sampled.device != self.device
|
|
539
|
+
or bool((sampled < 0).any())
|
|
540
|
+
or bool((sampled >= self.model.config.vocab_size).any())
|
|
541
|
+
):
|
|
542
|
+
raise ValueError("invalid sampled token")
|
|
543
|
+
if (phase == "commit") != (sampled is not None):
|
|
544
|
+
raise ValueError("sampled token exists only at the commit boundary")
|
|
545
|
+
|
|
546
|
+
def write(
|
|
547
|
+
self, state: Mapping[str, Any], writes: Mapping[str, Any], invalidates: tuple[str, ...]
|
|
548
|
+
) -> Mapping[str, Any]:
|
|
549
|
+
if "tokens" in writes:
|
|
550
|
+
raise ValueError("token writes require a new prefill; use adapter.session(new_tokens)")
|
|
551
|
+
if "logits" in writes:
|
|
552
|
+
raise ValueError("logits are observations; intervene on hidden before readout")
|
|
553
|
+
if "sampled_token" in writes:
|
|
554
|
+
raise ValueError("sampled tokens are decisions; intervene on logits upstream")
|
|
555
|
+
if invalidates:
|
|
556
|
+
raise ValueError(
|
|
557
|
+
"Qwen derived state is recomputed automatically; no manual invalidation"
|
|
558
|
+
)
|
|
559
|
+
return super().write(state, writes, ())
|
|
560
|
+
|
|
561
|
+
@torch.inference_mode()
|
|
562
|
+
def advance(self, state: Mapping[str, Any]) -> Mapping[str, Any]:
|
|
563
|
+
self.validate(state)
|
|
564
|
+
out = clone(state)
|
|
565
|
+
run = self._residency.run
|
|
566
|
+
tokens = out["tokens"].to(self.device)
|
|
567
|
+
if out["hidden"] is None:
|
|
568
|
+
if tokens.shape[1] >= self.model.config.max_position_embeddings:
|
|
569
|
+
raise ValueError("context capacity reached")
|
|
570
|
+
out["hidden"] = run(self.model.model.embed_tokens, tokens[:, -1:])
|
|
571
|
+
out["logits"] = None
|
|
572
|
+
out["phase"] = "layer"
|
|
573
|
+
return out
|
|
574
|
+
hidden = out["hidden"].to(self.device)
|
|
575
|
+
layer = out["layer"]
|
|
576
|
+
if layer < self.layers:
|
|
577
|
+
cache = self._cache(out["keys"], out["values"])
|
|
578
|
+
positions = torch.tensor([[tokens.shape[1] - 1]], device=self.device)
|
|
579
|
+
embeddings = run(self.model.model.rotary_emb, hidden, positions)
|
|
580
|
+
out["hidden"] = run(
|
|
581
|
+
self.model.model.layers[layer],
|
|
582
|
+
hidden,
|
|
583
|
+
attention_mask=None,
|
|
584
|
+
position_ids=positions,
|
|
585
|
+
past_key_values=cache,
|
|
586
|
+
position_embeddings=embeddings,
|
|
587
|
+
use_cache=True,
|
|
588
|
+
)
|
|
589
|
+
out["keys"], out["values"] = self._cache_values(cache)
|
|
590
|
+
out["layer"] = layer + 1
|
|
591
|
+
if self.granularity == "operation" and out["layer"] == self.layers:
|
|
592
|
+
out["phase"] = "normalization"
|
|
593
|
+
elif self.granularity == "operation" and out["phase"] == "normalization":
|
|
594
|
+
out["hidden"] = run(self.model.model.norm, hidden)
|
|
595
|
+
out["phase"] = "readout"
|
|
596
|
+
elif self.granularity == "operation" and out["phase"] == "readout":
|
|
597
|
+
out["logits"] = run(self.model.lm_head, hidden)[:, -1]
|
|
598
|
+
out["phase"] = "sample"
|
|
599
|
+
elif self.granularity == "operation" and out["phase"] == "sample":
|
|
600
|
+
out["sampled_token"] = out["logits"].argmax(-1, keepdim=True)
|
|
601
|
+
out["phase"] = "commit"
|
|
602
|
+
elif self.granularity == "operation" and out["phase"] == "commit":
|
|
603
|
+
out["tokens"] = torch.cat((tokens, out["sampled_token"]), dim=-1)
|
|
604
|
+
out["hidden"] = None
|
|
605
|
+
out["sampled_token"] = None
|
|
606
|
+
out["layer"] = 0
|
|
607
|
+
out["phase"] = "embed"
|
|
608
|
+
else:
|
|
609
|
+
logits = run(self.model.lm_head, run(self.model.model.norm, hidden))[:, -1]
|
|
610
|
+
out["logits"] = logits
|
|
611
|
+
out["tokens"] = torch.cat((tokens, logits.argmax(-1, keepdim=True)), dim=-1)
|
|
612
|
+
out["hidden"] = None
|
|
613
|
+
out["layer"] = 0
|
|
614
|
+
out["phase"] = "embed"
|
|
615
|
+
return out
|
|
616
|
+
|
|
617
|
+
def generate(self, session: Session, tokens: int = 1) -> None:
|
|
618
|
+
if tokens < 1:
|
|
619
|
+
raise ValueError("generation budget must be positive")
|
|
620
|
+
for _ in range(tokens):
|
|
621
|
+
initial = session.read("tokens").shape[1]
|
|
622
|
+
while session.read("tokens").shape[1] == initial:
|
|
623
|
+
session.continue_()
|
|
624
|
+
|
|
625
|
+
@torch.inference_mode()
|
|
626
|
+
def native_logits(self, tokens: Sequence[int]) -> torch.Tensor:
|
|
627
|
+
"""Uninstrumented full forward used as the numerical comparator.
|
|
628
|
+
|
|
629
|
+
In streamed residency the full forward is itself block-streamed (the whole model may
|
|
630
|
+
not fit the device), reproducing the resident ``model(tokens)`` logits bitwise.
|
|
631
|
+
"""
|
|
632
|
+
sequence = torch.tensor([list(tokens)], device=self.device)
|
|
633
|
+
if self._residency.mode == "streamed":
|
|
634
|
+
hidden, _ = self._streamed_backbone(sequence)
|
|
635
|
+
run = self._residency.run
|
|
636
|
+
return run(self.model.lm_head, run(self.model.model.norm, hidden))[:, -1]
|
|
637
|
+
return self.model(sequence).logits[:, -1]
|