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