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.
@@ -0,0 +1,1679 @@
1
+ """Batch-one, greedy native decoder machine for registered HF autoregressive families.
2
+
3
+ One generic adapter drives many families (gpt2, gpt_neox/Pythia, phi, llama, mistral,
4
+ mixtral, gemma-v1, qwen2, qwen3) through their *native* HF decoder layers, one token and
5
+ one layer at a time, over an externally held key/value cache. The state grammar, surface
6
+ manifest, execution/numeric contract, frozen-model guards, ``validate``/``write`` rules,
7
+ ``layer`` vs ``operation`` granularity, and ``generate``/``native_logits`` semantics match
8
+ ``adapters/qwen.py``. Family differences (absolute vs rotary position, parallel residual,
9
+ Gemma's embedding normalizer, MoE layers, sliding-window attention, module paths) are
10
+ declared per family and refused fail-closed when a config is outside the registered rule.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import inspect
16
+ import operator
17
+ from itertools import chain
18
+ import platform
19
+ from collections.abc import Callable, Mapping, Sequence
20
+ from dataclasses import dataclass, field
21
+ from typing import Any
22
+
23
+ import torch
24
+ import transformers
25
+ from transformers import DynamicCache
26
+ from transformers.cache_utils import DynamicLayer
27
+
28
+ from ..contracts import ExecutionPoint, SlotSpec, SurfaceManifest, TransitionSpec
29
+ from ..core import Adapter, Session, seal_append
30
+ from ..numerics import (
31
+ check_numeric_environment,
32
+ live_numeric_environment,
33
+ measure_accumulation,
34
+ needs_accumulation_measurement,
35
+ )
36
+ from ..values import TENSOR_FACTS, clone, digest, identity
37
+ from ._residency import BlockResidency
38
+
39
+
40
+ def _stable_configuration(value: Any, *, key: str = "") -> Any:
41
+ if isinstance(value, Mapping):
42
+ return {name: _stable_configuration(item, key=name) for name, item in value.items()}
43
+ if isinstance(value, (tuple, list)):
44
+ items = [_stable_configuration(item) for item in value]
45
+ return sorted(items) if key == "_use_default_values" else items
46
+ return value
47
+
48
+
49
+ def _tensor_guards(module: Any, *, prefix: str = "") -> tuple[tuple[Any, ...], ...]:
50
+ return tuple(
51
+ (
52
+ f"{prefix}{name}",
53
+ id(value),
54
+ value._version,
55
+ value.data_ptr(),
56
+ value.untyped_storage().data_ptr(),
57
+ )
58
+ for name, value in (*module.named_parameters(), *module.named_buffers())
59
+ )
60
+
61
+
62
+ class _FrozenSnapshot:
63
+ """A flat record of a module tree's structure and tensors, to re-check the frozen-model
64
+ guard (``_tensor_guards`` unchanged) without the named walk, in C-level passes: every
65
+ module's parameter, buffer and submodule dicts must be the same dict objects holding the
66
+ same ``(name, object)`` items (names equal, objects identical: the snapshot keeps the
67
+ objects alive, so identity is meaningful), and every tensor must keep its version counter and pointers. Any difference
68
+ (or a comparison that cannot be made) is reported as a change; the caller then falls back
69
+ to the exact ``_tensor_guards`` comparison, which decides."""
70
+
71
+ __slots__ = ("root", "modules", "tables", "items", "values", "tensors", "marks")
72
+
73
+ _GETTERS = tuple(
74
+ operator.attrgetter(name)
75
+ for name in ("_parameters", "_buffers", "_modules")
76
+ )
77
+
78
+ def __init__(self, module: Any):
79
+ self.root = module
80
+ modules: list[Any] = []
81
+ stack, seen = [module], set()
82
+ while stack:
83
+ current = stack.pop()
84
+ if id(current) in seen:
85
+ continue
86
+ seen.add(id(current))
87
+ modules.append(current)
88
+ stack.extend(child for child in current._modules.values() if child is not None)
89
+ self.modules = tuple(modules)
90
+ self.tables = self._tables()
91
+ self.items = list(map(tuple, self.tables)) # names
92
+ self.values = tuple(chain.from_iterable(map(dict.values, self.tables)))
93
+ self.tensors = tuple(
94
+ value
95
+ for module in modules
96
+ for table in (module._parameters, module._buffers)
97
+ for value in table.values()
98
+ if value is not None
99
+ )
100
+ self.marks = self._marks()
101
+
102
+ def _tables(self) -> list[Any]:
103
+ tables: list[Any] = []
104
+ for getter in self._GETTERS:
105
+ tables += map(getter, self.modules)
106
+ return tables
107
+
108
+ def _marks(self) -> tuple[list[int], list[int], list[int]]:
109
+ tensors = self.tensors
110
+ return (
111
+ [t._version for t in tensors],
112
+ list(map(torch.Tensor.data_ptr, tensors)),
113
+ [t.untyped_storage().data_ptr() for t in tensors],
114
+ )
115
+
116
+ def holds(self) -> bool:
117
+ tables = self._tables()
118
+ if not all(map(operator.is_, tables, self.tables)):
119
+ return False
120
+ # names are compared by equality, values by identity: a replaced tensor of equal value
121
+ # (a one-element clone, another dtype) must not pass through Tensor.__eq__
122
+ if list(map(tuple, tables)) != self.items:
123
+ return False
124
+ if not all(map(operator.is_, chain.from_iterable(map(dict.values, tables)), self.values)):
125
+ return False
126
+ return self._marks() == self.marks
127
+
128
+
129
+ def _require(condition: bool, message: str) -> None:
130
+ if not condition:
131
+ raise ValueError(message)
132
+
133
+
134
+ def _reject_common(config: Any) -> None:
135
+ """Fail-closed refusals shared by every registered dense family."""
136
+ if getattr(config, "quantization_config", None):
137
+ raise ValueError("quantized checkpoints are not supported; load a raw-float model")
138
+ if getattr(config, "auto_map", None):
139
+ raise ValueError("remote-code (auto_map) checkpoints are not supported")
140
+
141
+
142
+ def _rope_type(config: Any) -> str:
143
+ """Transformers 5.x stores RoPE as a dict (``rope_type`` defaults to ``'default'``)."""
144
+ rope = getattr(config, "rope_parameters", None)
145
+ if rope is None:
146
+ rope = getattr(config, "rope_scaling", None)
147
+ if isinstance(rope, Mapping):
148
+ return rope.get("rope_type") or rope.get("type") or "default"
149
+ return "default" if rope is None else "unknown"
150
+
151
+
152
+ def _partial_rotary_factor(config: Any) -> float | None:
153
+ rope = getattr(config, "rope_parameters", None)
154
+ if isinstance(rope, Mapping) and rope.get("partial_rotary_factor") is not None:
155
+ return float(rope["partial_rotary_factor"])
156
+ factor = getattr(config, "partial_rotary_factor", None)
157
+ return None if factor is None else float(factor)
158
+
159
+
160
+ def _causal_mask_kwargs(
161
+ create_fn: Callable[..., Any],
162
+ *,
163
+ config: Any,
164
+ hidden: Any,
165
+ cache: Any,
166
+ position_ids: Any,
167
+ cache_position: Any,
168
+ ) -> dict[str, Any]:
169
+ """Version-robust keyword set for ``transformers`` ``create_causal_mask``.
170
+
171
+ The streamed backbone (unlike the resident path) builds the eager attention mask itself,
172
+ and ``create_causal_mask``'s signature differs across transformers majors:
173
+
174
+ * transformers 5.x: ``(config, inputs_embeds, attention_mask, past_key_values, position_ids)``
175
+ * transformers 4.x: ``(config, input_embeds, attention_mask, cache_position, past_key_values,
176
+ position_ids)`` -- the embeds keyword loses its ``s`` and ``cache_position`` is required.
177
+
178
+ Inspecting the live signature keeps the streamed path bitwise-correct on either major (the
179
+ resident path is unaffected -- it never calls ``create_causal_mask``).
180
+ """
181
+ params = inspect.signature(create_fn).parameters
182
+ kwargs: dict[str, Any] = {
183
+ "config": config,
184
+ "attention_mask": None,
185
+ "past_key_values": cache,
186
+ "position_ids": position_ids,
187
+ }
188
+ kwargs["inputs_embeds" if "inputs_embeds" in params else "input_embeds"] = hidden
189
+ if "cache_position" in params:
190
+ kwargs["cache_position"] = cache_position
191
+ return kwargs
192
+
193
+
194
+ # --- per-family config validators (ported semantic rules from the private registry) ----
195
+
196
+
197
+ def _validate_gpt2(config: Any) -> None:
198
+ _reject_common(config)
199
+ if config.activation_function != "gelu_new":
200
+ raise ValueError("registered GPT-2 semantics require gelu_new (tanh-approximated) MLP")
201
+ if not getattr(config, "scale_attn_weights", True):
202
+ raise ValueError("registered GPT-2 attention requires head-dimension scaling")
203
+ if getattr(config, "scale_attn_by_inverse_layer_idx", False):
204
+ raise ValueError("inverse-layer GPT-2 attention scaling is not registered")
205
+ if getattr(config, "reorder_and_upcast_attn", False):
206
+ raise ValueError("reordered/upcast GPT-2 attention is not registered")
207
+ if getattr(config, "add_cross_attention", False):
208
+ raise ValueError("cross-attention GPT-2 topology is not registered")
209
+ _require(config.n_embd % config.n_head == 0, "GPT-2 n_embd must be divisible by n_head")
210
+
211
+
212
+ def _validate_gpt_neox(config: Any) -> None:
213
+ _reject_common(config)
214
+ if config.hidden_act != "gelu":
215
+ raise ValueError("registered GPT-NeoX semantics require exact erf gelu")
216
+ kv = getattr(config, "num_key_value_heads", None) or config.num_attention_heads
217
+ if kv != config.num_attention_heads:
218
+ raise ValueError("registered GPT-NeoX fused QKV requires one K/V head per query head")
219
+ if getattr(config, "tie_word_embeddings", False):
220
+ raise ValueError("registered GPT-NeoX/Pythia topology requires untied embeddings")
221
+ if _rope_type(config) != "default":
222
+ raise ValueError("registered GPT-NeoX semantics certify default (unscaled) RoPE only")
223
+ pct = getattr(config, "rotary_pct", 0.25)
224
+ if not (0.0 < float(pct) <= 1.0):
225
+ raise ValueError("GPT-NeoX rotary_pct must be in (0, 1]")
226
+
227
+
228
+ def _validate_phi(config: Any) -> None:
229
+ _reject_common(config)
230
+ if config.hidden_act != "gelu_new":
231
+ raise ValueError("registered Phi semantics require gelu_new")
232
+ if getattr(config, "tie_word_embeddings", False):
233
+ raise ValueError("registered Phi topology requires untied lexical matrices")
234
+ if getattr(config, "qk_layernorm", False):
235
+ raise ValueError("Phi qk_layernorm is not registered")
236
+ if _rope_type(config) != "default":
237
+ raise ValueError("registered Phi semantics require unscaled default RoPE")
238
+ factor = _partial_rotary_factor(config)
239
+ factor = 0.5 if factor is None else factor
240
+ if not (0.0 < factor <= 1.0):
241
+ raise ValueError("Phi partial_rotary_factor must be in (0, 1]")
242
+ head_dim = getattr(config, "head_dim", None)
243
+ if head_dim is not None and head_dim != config.hidden_size // config.num_attention_heads:
244
+ raise ValueError("Phi head_dim must equal hidden_size / num_attention_heads")
245
+
246
+
247
+ def _reject_scaled_rope(config: Any, *, llama3: bool = False) -> None:
248
+ """Default RoPE only; ``llama3`` also admits Llama-3.1 frequency scaling. The adapter runs
249
+ the backbone's native ``rotary_emb``, which builds its ``inv_freq`` buffer once with
250
+ transformers' own rule for the type (llama3: ``_compute_llama3_parameters``, static, no cos/sin
251
+ scaling), so the stepped rotation is the native one. Every other type (linear, dynamic, yarn,
252
+ longrope, ...) is refused."""
253
+ kind = _rope_type(config)
254
+ if kind != "default" and not (llama3 and kind == "llama3"):
255
+ allowed = "default (unscaled) or llama3-scaled" if llama3 else "default (unscaled)"
256
+ raise ValueError(f"this adapter certifies {allowed} RoPE only (rope_type {kind!r})")
257
+ factor = _partial_rotary_factor(config)
258
+ if factor is not None and factor != 1.0:
259
+ raise ValueError("partial rotary dimensions require a distinct semantic variant")
260
+
261
+
262
+ def _validate_llama(config: Any) -> None:
263
+ _reject_common(config)
264
+ _reject_scaled_rope(config, llama3=True)
265
+ tp = getattr(config, "pretraining_tp", 1)
266
+ if tp not in (None, 1):
267
+ raise ValueError("llama pretraining_tp must be 1; partitioned arithmetic is not registered")
268
+ if getattr(config, "rope_interleaved", False):
269
+ raise ValueError("interleaved llama rotary coordinates are not registered")
270
+
271
+
272
+ def _validate_mistral(config: Any) -> None:
273
+ _reject_common(config)
274
+ _reject_scaled_rope(config)
275
+
276
+
277
+ def _validate_mixtral(config: Any) -> None:
278
+ _reject_common(config)
279
+ _reject_scaled_rope(config)
280
+ if getattr(config, "attention_bias", False):
281
+ raise ValueError("registered Mixtral attention is biasless")
282
+ experts = config.num_local_experts
283
+ top_k = config.num_experts_per_tok
284
+ if not (isinstance(experts, int) and experts >= 2):
285
+ raise ValueError("Mixtral requires at least two routed experts")
286
+ if not (isinstance(top_k, int) and 0 < top_k < experts):
287
+ raise ValueError("Mixtral top-k must be a positive count smaller than the expert count")
288
+ if getattr(config, "output_router_logits", False):
289
+ raise ValueError("router-logit outputs require a separate declared output space")
290
+
291
+
292
+ def _validate_gemma(config: Any) -> None:
293
+ _reject_common(config)
294
+ _reject_scaled_rope(config)
295
+ act = getattr(config, "hidden_activation", None) or config.hidden_act
296
+ if config.hidden_act != "gelu_pytorch_tanh" or act != "gelu_pytorch_tanh":
297
+ raise ValueError("registered Gemma-1 semantics require gelu_pytorch_tanh")
298
+ if getattr(config, "attention_bias", False):
299
+ raise ValueError("registered Gemma-1 attention is biasless")
300
+ if getattr(config, "mlp_bias", False):
301
+ raise ValueError("registered Gemma-1 MLP is biasless")
302
+
303
+
304
+ def _validate_gemma2(config: Any) -> None:
305
+ """Gemma-2: GeGLU, soft-capped attention/logits, alternating local/global attention.
306
+
307
+ Both logit-softcaps and the sliding window are read from the config and honored by the
308
+ adapter (final-logit softcap applied at readout, attention softcap inside the native
309
+ eager layer). Sliding-window attention alternates with full attention layer by layer;
310
+ the adapter reproduces it exactly while the context stays within one window (full causal
311
+ and windowed causal coincide there) and refuses a context longer than one window.
312
+ """
313
+ _reject_common(config)
314
+ _reject_scaled_rope(config)
315
+ act = getattr(config, "hidden_activation", None) or config.hidden_act
316
+ if act != "gelu_pytorch_tanh":
317
+ raise ValueError("registered Gemma-2 semantics require gelu_pytorch_tanh (GeGLU)")
318
+ if getattr(config, "attention_bias", False):
319
+ raise ValueError("registered Gemma-2 attention is biasless")
320
+ if getattr(config, "mlp_bias", False):
321
+ raise ValueError("registered Gemma-2 MLP is biasless")
322
+ if not getattr(config, "sliding_window", None):
323
+ raise ValueError(
324
+ "registered Gemma-2 requires a sliding_window (alternating local/global attention)"
325
+ )
326
+ if getattr(config, "query_pre_attn_scalar", None) is None:
327
+ raise ValueError("registered Gemma-2 requires query_pre_attn_scalar attention scaling")
328
+
329
+
330
+ def _validate_qwen2(config: Any) -> None:
331
+ _reject_common(config)
332
+ _reject_scaled_rope(config)
333
+ if getattr(config, "use_sliding_window", False):
334
+ raise ValueError("sliding-window Qwen2 attention is not registered")
335
+
336
+
337
+ def _validate_qwen3(config: Any) -> None:
338
+ _reject_common(config)
339
+ _reject_scaled_rope(config)
340
+ if getattr(config, "use_sliding_window", False):
341
+ raise ValueError("sliding-window Qwen3 attention is not registered")
342
+
343
+
344
+ @dataclass(frozen=True)
345
+ class _FamilySpec:
346
+ model_type: str
347
+ model_cls: type
348
+ config_cls: type
349
+ backbone: str # attribute on the CausalLM giving the backbone Model
350
+ layers: str # attribute on the backbone giving the decoder ModuleList
351
+ embed: str # attribute on the backbone giving the token embedding module
352
+ final_norm: str # attribute on the backbone giving the final norm module
353
+ position: str # "rotary" | "absolute"
354
+ cache_kwarg: str # "past_key_values" | "layer_past"
355
+ validate: Callable[[Any], None]
356
+ abs_pos: str | None = None # attribute for absolute position embedding (gpt2 wpe)
357
+ moe: bool = False
358
+ tiny_config: Mapping[str, Any] = field(default_factory=dict)
359
+
360
+
361
+ def _import_families() -> dict[str, _FamilySpec]:
362
+ from transformers import (
363
+ Gemma2Config,
364
+ Gemma2ForCausalLM,
365
+ GemmaConfig,
366
+ GemmaForCausalLM,
367
+ GPT2Config,
368
+ GPT2LMHeadModel,
369
+ GPTNeoXConfig,
370
+ GPTNeoXForCausalLM,
371
+ LlamaConfig,
372
+ LlamaForCausalLM,
373
+ MistralConfig,
374
+ MistralForCausalLM,
375
+ MixtralConfig,
376
+ MixtralForCausalLM,
377
+ PhiConfig,
378
+ PhiForCausalLM,
379
+ Qwen2Config,
380
+ Qwen2ForCausalLM,
381
+ Qwen3Config,
382
+ Qwen3ForCausalLM,
383
+ )
384
+
385
+ common = dict(
386
+ vocab_size=64,
387
+ hidden_size=32,
388
+ intermediate_size=64,
389
+ num_hidden_layers=2,
390
+ num_attention_heads=4,
391
+ max_position_embeddings=128,
392
+ attn_implementation="eager",
393
+ )
394
+ specs = [
395
+ _FamilySpec(
396
+ "gpt2",
397
+ GPT2LMHeadModel,
398
+ GPT2Config,
399
+ "transformer",
400
+ "h",
401
+ "wte",
402
+ "ln_f",
403
+ "absolute",
404
+ "past_key_values",
405
+ _validate_gpt2,
406
+ abs_pos="wpe",
407
+ tiny_config=dict(
408
+ vocab_size=64,
409
+ n_embd=32,
410
+ n_layer=2,
411
+ n_head=4,
412
+ n_positions=128,
413
+ n_inner=64,
414
+ activation_function="gelu_new",
415
+ attn_implementation="eager",
416
+ ),
417
+ ),
418
+ _FamilySpec(
419
+ "gpt_neox",
420
+ GPTNeoXForCausalLM,
421
+ GPTNeoXConfig,
422
+ "gpt_neox",
423
+ "layers",
424
+ "embed_in",
425
+ "final_layer_norm",
426
+ "rotary",
427
+ "layer_past",
428
+ _validate_gpt_neox,
429
+ tiny_config=dict(
430
+ **common, rotary_pct=0.25, use_parallel_residual=True, hidden_act="gelu"
431
+ ),
432
+ ),
433
+ _FamilySpec(
434
+ "phi",
435
+ PhiForCausalLM,
436
+ PhiConfig,
437
+ "model",
438
+ "layers",
439
+ "embed_tokens",
440
+ "final_layernorm",
441
+ "rotary",
442
+ "past_key_values",
443
+ _validate_phi,
444
+ tiny_config=dict(**common, partial_rotary_factor=0.5, hidden_act="gelu_new"),
445
+ ),
446
+ _FamilySpec(
447
+ "llama",
448
+ LlamaForCausalLM,
449
+ LlamaConfig,
450
+ "model",
451
+ "layers",
452
+ "embed_tokens",
453
+ "norm",
454
+ "rotary",
455
+ "past_key_values",
456
+ _validate_llama,
457
+ tiny_config=dict(**common, num_key_value_heads=2, head_dim=8),
458
+ ),
459
+ _FamilySpec(
460
+ "mistral",
461
+ MistralForCausalLM,
462
+ MistralConfig,
463
+ "model",
464
+ "layers",
465
+ "embed_tokens",
466
+ "norm",
467
+ "rotary",
468
+ "past_key_values",
469
+ _validate_mistral,
470
+ tiny_config=dict(**common, num_key_value_heads=2, head_dim=8, sliding_window=128),
471
+ ),
472
+ _FamilySpec(
473
+ "mixtral",
474
+ MixtralForCausalLM,
475
+ MixtralConfig,
476
+ "model",
477
+ "layers",
478
+ "embed_tokens",
479
+ "norm",
480
+ "rotary",
481
+ "past_key_values",
482
+ _validate_mixtral,
483
+ moe=True,
484
+ tiny_config=dict(
485
+ **common,
486
+ num_key_value_heads=2,
487
+ head_dim=8,
488
+ num_local_experts=4,
489
+ num_experts_per_tok=2,
490
+ ),
491
+ ),
492
+ _FamilySpec(
493
+ "gemma",
494
+ GemmaForCausalLM,
495
+ GemmaConfig,
496
+ "model",
497
+ "layers",
498
+ "embed_tokens",
499
+ "norm",
500
+ "rotary",
501
+ "past_key_values",
502
+ _validate_gemma,
503
+ tiny_config=dict(
504
+ **common,
505
+ num_key_value_heads=2,
506
+ head_dim=8,
507
+ hidden_act="gelu_pytorch_tanh",
508
+ hidden_activation="gelu_pytorch_tanh",
509
+ ),
510
+ ),
511
+ _FamilySpec(
512
+ "gemma2",
513
+ Gemma2ForCausalLM,
514
+ Gemma2Config,
515
+ "model",
516
+ "layers",
517
+ "embed_tokens",
518
+ "norm",
519
+ "rotary",
520
+ "past_key_values",
521
+ _validate_gemma2,
522
+ tiny_config=dict(
523
+ **common,
524
+ num_key_value_heads=2,
525
+ head_dim=8,
526
+ hidden_act="gelu_pytorch_tanh",
527
+ hidden_activation="gelu_pytorch_tanh",
528
+ sliding_window=16,
529
+ query_pre_attn_scalar=8,
530
+ attn_logit_softcapping=4.0,
531
+ final_logit_softcapping=2.0,
532
+ ),
533
+ ),
534
+ _FamilySpec(
535
+ "qwen2",
536
+ Qwen2ForCausalLM,
537
+ Qwen2Config,
538
+ "model",
539
+ "layers",
540
+ "embed_tokens",
541
+ "norm",
542
+ "rotary",
543
+ "past_key_values",
544
+ _validate_qwen2,
545
+ tiny_config=dict(**common, num_key_value_heads=2, head_dim=8),
546
+ ),
547
+ _FamilySpec(
548
+ "qwen3",
549
+ Qwen3ForCausalLM,
550
+ Qwen3Config,
551
+ "model",
552
+ "layers",
553
+ "embed_tokens",
554
+ "norm",
555
+ "rotary",
556
+ "past_key_values",
557
+ _validate_qwen3,
558
+ tiny_config=dict(**common, num_key_value_heads=2, head_dim=8),
559
+ ),
560
+ ]
561
+ return {spec.model_type: spec for spec in specs}
562
+
563
+
564
+ _FAMILIES: dict[str, _FamilySpec] | None = None
565
+
566
+
567
+ def families() -> dict[str, _FamilySpec]:
568
+ global _FAMILIES
569
+ if _FAMILIES is None:
570
+ _FAMILIES = _import_families()
571
+ return _FAMILIES
572
+
573
+
574
+ SUPPORTED_FAMILIES = (
575
+ "gpt2",
576
+ "gpt_neox",
577
+ "phi",
578
+ "llama",
579
+ "mistral",
580
+ "mixtral",
581
+ "gemma",
582
+ "gemma2",
583
+ "qwen2",
584
+ "qwen3",
585
+ )
586
+
587
+
588
+ class DecoderAdapter(Adapter):
589
+ """Generic native decoder adapter. Same session grammar as ``QwenAdapter``.
590
+
591
+ ``shares_state``: ``advance`` never writes a tensor of its input state in place (the K/V
592
+ tensors the native layer sees are copies made by ``_cache``; the hidden carrier and the
593
+ logits are only read), and its result keeps the input's tensor for every K/V layer the
594
+ transition did not change, so consecutive cuts of a Session share them. Native calls run
595
+ under ``torch.no_grad`` (version counters kept) rather than inference mode.
596
+ """
597
+
598
+ shares_state = True
599
+
600
+ def __init__(
601
+ self,
602
+ model: Any,
603
+ *,
604
+ granularity: str = "layer",
605
+ residency: str = "resident",
606
+ device: Any = None,
607
+ pin_host: bool = False,
608
+ prefetch: bool = False,
609
+ host_embedding: bool = False,
610
+ ):
611
+ model_type = getattr(model.config, "model_type", None)
612
+ spec = families().get(model_type)
613
+ if spec is None:
614
+ raise ValueError(
615
+ f"unregistered decoder model_type: {model_type!r}; "
616
+ f"supported families are {', '.join(SUPPORTED_FAMILIES)}"
617
+ )
618
+ if not isinstance(model, spec.model_cls):
619
+ raise ValueError(f"{model_type} adapter requires a {spec.model_cls.__name__}")
620
+ spec.validate(model.config)
621
+ if getattr(model.config, "_attn_implementation", "eager") != "eager":
622
+ raise ValueError("DecoderAdapter requires attn_implementation='eager'")
623
+ if granularity not in {"layer", "operation"}:
624
+ raise ValueError("granularity must be 'layer' or 'operation'")
625
+ self.spec = spec
626
+ self.model = model.eval()
627
+ self.granularity = granularity
628
+ # Block-streamed residency parks frozen weights in host memory and copies one native
629
+ # module to the execution device at a time; resident keeps the historical zero-overhead
630
+ # path. place() must run before the frozen guard because host pinning reassigns storage.
631
+ if residency == "streamed":
632
+ target = (
633
+ device if device is not None else ("cuda" if torch.cuda.is_available() else "cpu")
634
+ )
635
+ self._residency = BlockResidency(
636
+ target,
637
+ mode="streamed",
638
+ pin_host=pin_host,
639
+ prefetch=prefetch,
640
+ host_embedding=host_embedding,
641
+ )
642
+ else:
643
+ target = device if device is not None else next(model.parameters()).device
644
+ self._residency = BlockResidency(target, mode="resident")
645
+ self._residency.place(self.model)
646
+ self.device = self._residency.device
647
+ self.dtype = next(model.parameters()).dtype
648
+ config = model.config
649
+ self.backbone = getattr(model, spec.backbone)
650
+ self._layer_modules = getattr(self.backbone, spec.layers)
651
+ self.layers = len(self._layer_modules)
652
+ layer_types = getattr(config, "layer_types", None)
653
+ if layer_types is not None and len(layer_types) != self.layers:
654
+ raise ValueError(
655
+ f"config.layer_types has {len(layer_types)} entries but the model has "
656
+ f"{self.layers} decoder layers (num_hidden_layers = {config.num_hidden_layers}); "
657
+ f"layer_types must have exactly {self.layers} entries, so trim it together with "
658
+ "num_hidden_layers when truncating a config"
659
+ )
660
+ self.hidden_size = config.hidden_size
661
+ self.vocab_size = config.vocab_size
662
+ self.max_positions = config.max_position_embeddings
663
+ self.num_heads = config.num_attention_heads
664
+ self.num_kv_heads = getattr(config, "num_key_value_heads", None) or self.num_heads
665
+ self.head_dim = getattr(config, "head_dim", None) or self.hidden_size // self.num_heads
666
+ self.sliding_window = (
667
+ getattr(config, "sliding_window", None)
668
+ if spec.model_type in {"mistral", "gemma2"}
669
+ else None
670
+ )
671
+ # Gemma-2 soft-caps the final logits inside the CausalLM (not the lm_head); reproduce it
672
+ # at readout so the stepped logits match a native full forward. Attention-logit softcap
673
+ # and query_pre_attn_scalar scaling live inside the native eager layer, unchanged.
674
+ self.final_logit_softcapping = (
675
+ getattr(config, "final_logit_softcapping", None)
676
+ if spec.model_type == "gemma2"
677
+ else None
678
+ )
679
+ # Gemma scales token embeddings by sqrt(hidden_size). transformers>=5 folds that scale
680
+ # into a scaled-embedding module (``embed_scale``); older transformers apply it in
681
+ # ``Model.forward`` with a plain ``nn.Embedding``. Detect which, and apply the scale in
682
+ # ``_embed`` only when the embedding module does not already carry it, so the adapter
683
+ # reproduces the native forward on either transformers version.
684
+ self._embed_scale: float | None = None
685
+ if spec.model_type in {"gemma", "gemma2"}:
686
+ embed_module = getattr(self.backbone, spec.embed)
687
+ if getattr(embed_module, "embed_scale", None) is None:
688
+ self._embed_scale = float(config.hidden_size) ** 0.5
689
+ self.rotary = getattr(self.backbone, "rotary_emb", None)
690
+ if spec.position == "rotary" and self.rotary is None:
691
+ raise ValueError(f"{spec.model_type} backbone is missing rotary_emb")
692
+ if spec.model_type == "qwen3" and not hasattr(self._layer_modules[0].self_attn, "q_norm"):
693
+ raise ValueError("registered Qwen3 semantics require attention qk-norm")
694
+ stable = _stable_configuration(config.to_dict())
695
+ self._configuration_fingerprint = digest(stable)
696
+ self.model_identity = identity(model, stable)
697
+ self._frozen_versions = _tensor_guards(model)
698
+ self._frozen_snapshot = _FrozenSnapshot(model)
699
+ self._layer_forward_kwargs = _accepts_kwargs(self._layer_modules[0].forward)
700
+ parity = "bounded-logits-moe" if spec.moe else "bounded-logits"
701
+ self.execution = {
702
+ "family": spec.model_type,
703
+ "adapter": "native-decoder-v1",
704
+ "granularity": granularity,
705
+ "attention": "eager",
706
+ "position": spec.position,
707
+ "dtype": str(self.dtype),
708
+ "device": {"type": self.device.type, "index": self.device.index},
709
+ "batch": {"size": 1, "padding": False},
710
+ "environment_versions": {
711
+ "torch": torch.__version__,
712
+ "transformers": transformers.__version__,
713
+ "python": platform.python_version(),
714
+ },
715
+ "model_program": self._model_program(),
716
+ "kernel": {"attention": "transformers-eager", "cache": "DynamicCache"},
717
+ "numeric_scope": {
718
+ # native calls run under torch.no_grad (not inference mode) so that state
719
+ # tensors keep version counters: the shares_state guard needs them
720
+ "inference_mode": False,
721
+ "grad_enabled": False,
722
+ "autocast": False,
723
+ **live_numeric_environment(),
724
+ "tensor_layout": "state-slot-bound-stride",
725
+ },
726
+ "sampler": "greedy",
727
+ "parity": parity,
728
+ }
729
+ if self._residency.mode == "resident" and needs_accumulation_measurement(
730
+ self.device.type, self.dtype
731
+ ):
732
+ # the accumulation precision of native 16-bit matmuls, measured on this device
733
+ # (a handful of linear stages, no forward); bounds read it from the scope
734
+ self.execution["numeric_scope"]["accumulation"] = measure_accumulation(
735
+ self._layer_modules, getattr(model, "lm_head", None)
736
+ )
737
+ # Resident execution keeps the historical contract verbatim; only streamed residency
738
+ # adds a field, so existing resident receipts stay byte-identical.
739
+ if self._residency.mode == "streamed":
740
+ self.execution["residency"] = self._residency.to_dict()
741
+ if spec.model_type == "gemma2":
742
+ self.execution["logit_softcap"] = {
743
+ "final": self.final_logit_softcapping,
744
+ "attention": getattr(config, "attn_logit_softcapping", None),
745
+ }
746
+ self.execution["attention_schedule"] = "alternating-local-global-sliding-window"
747
+ self.execution["sliding_window"] = self.sliding_window
748
+
749
+ def _model_program(self) -> str:
750
+ embed = "embed+abs_pos" if self.spec.position == "absolute" else "embed"
751
+ readout = "lm_head"
752
+ if self.spec.model_type == "gemma2" and self.final_logit_softcapping is not None:
753
+ readout = "lm_head->logit_softcap"
754
+ return f"{embed}->decoder_layer[*]->final_norm->{readout}->greedy_argmax->token_commit"
755
+
756
+ def _apply_logit_softcap(self, logits: torch.Tensor) -> torch.Tensor:
757
+ """Gemma-2 final-logit soft-cap, applied after ``lm_head`` to match native logits."""
758
+ cap = self.final_logit_softcapping
759
+ if cap is None:
760
+ return logits
761
+ return torch.tanh(logits / cap) * cap
762
+
763
+ def native_cache(
764
+ self, keys: Sequence[torch.Tensor], values: Sequence[torch.Tensor], layer_index: int
765
+ ) -> DynamicCache:
766
+ """A native KV cache over ``keys``/``values`` for a run that starts at ``layer_index``."""
767
+ return self._cache(keys, values, layer_index)
768
+
769
+ def run_layer(
770
+ self,
771
+ index: int,
772
+ hidden: torch.Tensor,
773
+ cache: DynamicCache,
774
+ position: int,
775
+ ports: Any = None,
776
+ ) -> torch.Tensor:
777
+ """Run decoder layer ``index`` on ``hidden`` at token ``position`` against ``cache``."""
778
+ return self._run_layer(index, hidden, cache, position, ports)
779
+
780
+ def apply_logit_softcap(self, logits: torch.Tensor) -> torch.Tensor:
781
+ """Apply the family's final-logit soft-cap (identity unless the model has one)."""
782
+ return self._apply_logit_softcap(logits)
783
+
784
+ @classmethod
785
+ def tiny(
786
+ cls,
787
+ family: str,
788
+ seed: int = 7,
789
+ *,
790
+ granularity: str = "layer",
791
+ residency: str = "resident",
792
+ device: Any = None,
793
+ pin_host: bool = False,
794
+ prefetch: bool = False,
795
+ host_embedding: bool = False,
796
+ ) -> DecoderAdapter:
797
+ spec = families().get(family)
798
+ if spec is None:
799
+ raise ValueError(
800
+ f"unknown family {family!r}; supported: {', '.join(SUPPORTED_FAMILIES)}"
801
+ )
802
+ with torch.random.fork_rng():
803
+ torch.manual_seed(seed)
804
+ config = spec.config_cls(**dict(spec.tiny_config))
805
+ return cls(
806
+ spec.model_cls(config),
807
+ granularity=granularity,
808
+ residency=residency,
809
+ device=device,
810
+ pin_host=pin_host,
811
+ prefetch=prefetch,
812
+ host_embedding=host_embedding,
813
+ )
814
+
815
+ @classmethod
816
+ def from_pretrained(
817
+ cls,
818
+ path: str,
819
+ *,
820
+ granularity: str = "layer",
821
+ residency: str = "resident",
822
+ device: Any = None,
823
+ pin_host: bool = False,
824
+ prefetch: bool = False,
825
+ host_embedding: bool = False,
826
+ **kwargs: Any,
827
+ ) -> DecoderAdapter:
828
+ from transformers import AutoConfig
829
+
830
+ model_type = AutoConfig.from_pretrained(path).model_type
831
+ spec = families().get(model_type)
832
+ if spec is None:
833
+ raise ValueError(
834
+ f"unregistered decoder model_type: {model_type!r}; "
835
+ f"supported families are {', '.join(SUPPORTED_FAMILIES)}"
836
+ )
837
+ model = spec.model_cls.from_pretrained(path, attn_implementation="eager", **kwargs)
838
+ return cls(
839
+ model,
840
+ granularity=granularity,
841
+ residency=residency,
842
+ device=device,
843
+ pin_host=pin_host,
844
+ prefetch=prefetch,
845
+ host_embedding=host_embedding,
846
+ )
847
+
848
+ # --- frozen-model guards (identical policy to QwenAdapter) --------------------------
849
+
850
+ def _verify_frozen_model(self) -> None:
851
+ snapshot = getattr(self, "_frozen_snapshot", None)
852
+ if snapshot is not None and snapshot.root is self.model and snapshot.holds():
853
+ return # same structure, same tensor objects, versions and pointers
854
+ if _tensor_guards(self.model) != self._frozen_versions:
855
+ raise ValueError(
856
+ "model parameters or buffers changed after adapter identity was frozen; "
857
+ "rewrap the model in a new adapter"
858
+ )
859
+ # a structural change the exact guard does not see (a parameter-free submodule, say)
860
+ self._frozen_snapshot = _FrozenSnapshot(self.model)
861
+
862
+ def validate_execution(self) -> None:
863
+ self._verify_frozen_model()
864
+ if (
865
+ digest(_stable_configuration(self.model.config.to_dict()))
866
+ != self._configuration_fingerprint
867
+ ):
868
+ raise ValueError(
869
+ "model configuration changed after adapter identity was frozen; rewrap"
870
+ )
871
+ check_numeric_environment(self.execution["numeric_scope"])
872
+
873
+ # --- external key/value cache -------------------------------------------------------
874
+
875
+ def _foreign_hooks(self, index: int) -> bool:
876
+ """True when a forward or forward-pre hook other than this library's own controllers
877
+ (``core.own_hook``) can run in decoder layer ``index`` (any module of its subtree) or
878
+ is global (``torch.nn.modules.module._global_forward*``). Such a hook could write a K/V
879
+ layer through ``.data``, numpy or dlpack, which bumps no version counter."""
880
+ from torch.nn.modules import module as torch_module
881
+
882
+ for table in (
883
+ torch_module._global_forward_hooks,
884
+ torch_module._global_forward_pre_hooks,
885
+ ):
886
+ if any(not getattr(hook, "_saturn_own_hook", False) for hook in table.values()):
887
+ return True
888
+ for sub in self._layer_modules[index].modules():
889
+ for table in (sub._forward_hooks, sub._forward_pre_hooks):
890
+ if table and any(
891
+ not getattr(hook, "_saturn_own_hook", False) for hook in table.values()
892
+ ):
893
+ return True
894
+ return False
895
+
896
+ def _cache(
897
+ self, keys: Sequence[torch.Tensor], values: Sequence[torch.Tensor], layer_index: int
898
+ ) -> DynamicCache:
899
+ """A native cache over ``keys``/``values``, held by reference when no foreign hook can
900
+ run in layer ``layer_index`` (checked once per call): a plain ``DynamicLayer`` never
901
+ writes its tensors (its ``update`` concatenates into a new tensor), cell edits replace
902
+ a layer tensor by an edited copy, and ``Session._advance_guarded`` refuses
903
+ (``InPlaceWrite``) a transition that wrote a state tensor in place anyway, so the
904
+ native layer gets the state's own K/V without a copy of every layer per transition.
905
+ With a foreign hook registered (it could write through ``.data``/numpy/dlpack, which
906
+ the version counter does not see), and for any other layer kind (sliding window,
907
+ offloaded, lazily appended), the layers are filled through ``DynamicCache.update``,
908
+ which copies."""
909
+ cache = DynamicCache(config=self.model.config)
910
+ offloading = getattr(cache, "offloading", False) or self._foreign_hooks(layer_index)
911
+ for index, (key, value) in enumerate(zip(keys, values)):
912
+ if key.shape[-2]:
913
+ key, value = key.to(self.device), value.to(self.device)
914
+ layer = cache.layers[index] if index < len(cache.layers) else None
915
+ if (
916
+ type(layer) is DynamicLayer
917
+ and not offloading
918
+ and not layer.is_initialized
919
+ and not key.is_inference()
920
+ and not value.is_inference()
921
+ ):
922
+ layer.lazy_initialization(key, value)
923
+ layer.keys, layer.values = key, value
924
+ else:
925
+ cache.update(key, value, index)
926
+ return cache
927
+
928
+ @staticmethod
929
+ def _populated(cache: DynamicCache) -> list[tuple[Any, ...] | None]:
930
+ """Per layer: ``(keys, keys version, values, values version)`` of the tensors ``_cache``
931
+ put in the cache, or None for a layer it left empty (or whose tensors keep no version
932
+ counter, as under inference mode: a write to them could not be told)."""
933
+ out: list[tuple[Any, ...] | None] = []
934
+ for layer in cache.layers:
935
+ key, value = getattr(layer, "keys", None), getattr(layer, "values", None)
936
+ if key is None or value is None or key.is_inference() or value.is_inference():
937
+ out.append(None)
938
+ else:
939
+ out.append((key, key._version, value, value._version))
940
+ return out
941
+
942
+ def _kv_shape(self, length: int) -> tuple[int, int, int, int]:
943
+ return (1, self.num_kv_heads, length, self.head_dim)
944
+
945
+ @staticmethod
946
+ def _same_layout(a: torch.Tensor, b: torch.Tensor) -> bool:
947
+ return (
948
+ a.shape == b.shape
949
+ and a.stride() == b.stride()
950
+ and a.dtype == b.dtype
951
+ and a.device == b.device
952
+ )
953
+
954
+ def _cache_values_shared(
955
+ self,
956
+ cache: DynamicCache,
957
+ populated: Sequence[tuple[Any, ...] | None],
958
+ keys: Sequence[torch.Tensor],
959
+ values: Sequence[torch.Tensor],
960
+ ) -> tuple[list[torch.Tensor], list[torch.Tensor]]:
961
+ """``_cache_values`` with the input's own tensors for every layer the transition left
962
+ alone: the cache still holds the very copy ``_cache`` put there, unwritten (same object,
963
+ same version counter), so it is bitwise the input, which is kept instead (same layout
964
+ required). A layer the native code or a cell edit replaced or wrote is taken over."""
965
+ out_keys, out_values = self._cache_values(cache)
966
+ for index, entry in enumerate(populated):
967
+ layer = cache.layers[index]
968
+ current_key = getattr(layer, "keys", None)
969
+ current_value = getattr(layer, "values", None)
970
+ if entry is None:
971
+ if current_key is None and current_value is None:
972
+ out_keys[index], out_values[index] = keys[index], values[index]
973
+ continue
974
+ key, key_version, value, value_version = entry
975
+ if (
976
+ current_key is key
977
+ and current_value is value
978
+ and key._version == key_version
979
+ and value._version == value_version
980
+ and self._same_layout(key, keys[index])
981
+ and self._same_layout(value, values[index])
982
+ ):
983
+ out_keys[index], out_values[index] = keys[index], values[index]
984
+ for index in range(len(out_keys)):
985
+ for new, old in ((out_keys[index], keys[index]), (out_values[index], values[index])):
986
+ self._declare_append(new, old)
987
+ return out_keys, out_values
988
+
989
+ @staticmethod
990
+ def _declare_append(new: torch.Tensor, old: torch.Tensor) -> None:
991
+ """Declare a layer tensor the transition grew by rows (``seal_append``) when its leading
992
+ rows are bitwise the input's, so a cut holds only the appended rows of it."""
993
+ if new is old or new.dim() != 4 or old.dim() != 4:
994
+ return
995
+ rows = old.shape[2]
996
+ if new.shape[2] <= rows or new.shape[:2] != old.shape[:2] or new.shape[3] != old.shape[3]:
997
+ return
998
+ if new.dtype != old.dtype or new.device != old.device:
999
+ return
1000
+ if rows and not torch.equal(new.narrow(2, 0, rows), old):
1001
+ return # a cell edit rewrote cached rows: the tensor is held whole
1002
+ seal_append(new, old, 2)
1003
+
1004
+ def _cache_values(self, cache: DynamicCache) -> tuple[list[torch.Tensor], list[torch.Tensor]]:
1005
+ """The cache's per-layer tensors, taken over without a copy: every one is a fresh
1006
+ ``torch.cat`` of the cache update (``_cache`` copies the input layers in), contiguous,
1007
+ and the cache object is dropped by every caller."""
1008
+ empty = self._kv_shape(0)
1009
+ keys, values = [], []
1010
+ for layer in cache.layers:
1011
+ keys.append(
1012
+ layer.keys
1013
+ if getattr(layer, "keys", None) is not None
1014
+ else torch.empty(empty, device=self.device, dtype=self.dtype)
1015
+ )
1016
+ values.append(
1017
+ layer.values
1018
+ if getattr(layer, "values", None) is not None
1019
+ else torch.empty(empty, device=self.device, dtype=self.dtype)
1020
+ )
1021
+ return keys, values
1022
+
1023
+ def _embed(self, tokens: torch.Tensor) -> torch.Tensor:
1024
+ run = self._residency.run
1025
+ embed_module = getattr(self.backbone, self.spec.embed)
1026
+ hidden = run(embed_module, tokens[:, -1:].clone()) # modules never see state tensors
1027
+ if self._embed_scale is not None:
1028
+ hidden = hidden * torch.tensor(self._embed_scale, dtype=hidden.dtype)
1029
+ if self.spec.position == "absolute":
1030
+ position = tokens.shape[1] - 1
1031
+ positions = torch.tensor([[position]], device=self.device)
1032
+ hidden = hidden + run(getattr(self.backbone, self.spec.abs_pos), positions)
1033
+ return hidden
1034
+
1035
+ def _layer_kwargs(self, index: int, kwargs: dict[str, Any]) -> dict[str, Any]:
1036
+ if self._layer_forward_kwargs:
1037
+ return kwargs
1038
+ signature = inspect.signature(self._layer_modules[index].forward)
1039
+ return {k: v for k, v in kwargs.items() if k in signature.parameters}
1040
+
1041
+ def _run_layer(
1042
+ self,
1043
+ index: int,
1044
+ hidden: torch.Tensor,
1045
+ cache: DynamicCache,
1046
+ position: int,
1047
+ ports: Any = None,
1048
+ ) -> torch.Tensor:
1049
+ positions = torch.tensor([[position]], device=self.device)
1050
+ kwargs: dict[str, Any] = {self.spec.cache_kwarg: cache, "use_cache": True}
1051
+ if self.spec.position == "rotary":
1052
+ kwargs["position_ids"] = positions
1053
+ kwargs["position_embeddings"] = self._residency.run(self.rotary, hidden, positions)
1054
+ kwargs["attention_mask"] = None
1055
+ else:
1056
+ kwargs["attention_mask"] = None
1057
+ kwargs = self._layer_kwargs(index, kwargs)
1058
+ module = self._layer_modules[index]
1059
+ if ports is None:
1060
+ result = self._residency.run(module, hidden, **kwargs)
1061
+ else:
1062
+ with ports.installed(self, index, module):
1063
+ result = self._residency.run(module, hidden, **kwargs)
1064
+ return result[0] if isinstance(result, tuple) else result
1065
+
1066
+ def _streamed_backbone(self, tokens: torch.Tensor) -> tuple[torch.Tensor, DynamicCache]:
1067
+ """Block-streamed replica of the native backbone forward over a full token span.
1068
+
1069
+ Streams the embedding, rotary, and every decoder layer one module at a time while the
1070
+ model's own ``create_causal_mask`` builds the eager attention mask. Because the copies
1071
+ are byte-preserving and ``functional_call`` substitutes without mutating the module, the
1072
+ returned hidden state and key/value cache are bitwise-identical to a resident
1073
+ ``model(tokens)`` forward on the same device (proven by tests and measured on real
1074
+ weights). Used only in streamed residency, where the whole model cannot fit the device.
1075
+ """
1076
+ from transformers.masking_utils import create_causal_mask
1077
+
1078
+ run = self._residency.run
1079
+ length = tokens.shape[1]
1080
+ hidden = run(getattr(self.backbone, self.spec.embed), tokens)
1081
+ if self._embed_scale is not None:
1082
+ hidden = hidden * torch.tensor(self._embed_scale, dtype=hidden.dtype)
1083
+ position_ids = torch.arange(length, device=self.device).unsqueeze(0)
1084
+ if self.spec.position == "absolute":
1085
+ hidden = hidden + run(getattr(self.backbone, self.spec.abs_pos), position_ids)
1086
+ cache = DynamicCache(config=self.model.config)
1087
+ cache_position = torch.arange(length, device=self.device)
1088
+ mask = create_causal_mask(
1089
+ **_causal_mask_kwargs(
1090
+ create_causal_mask,
1091
+ config=self.model.config,
1092
+ hidden=hidden,
1093
+ cache=cache,
1094
+ position_ids=position_ids,
1095
+ cache_position=cache_position,
1096
+ )
1097
+ )
1098
+ kwargs: dict[str, Any] = {
1099
+ self.spec.cache_kwarg: cache,
1100
+ "use_cache": True,
1101
+ "attention_mask": mask,
1102
+ }
1103
+ if self.spec.position == "rotary":
1104
+ kwargs["position_ids"] = position_ids
1105
+ kwargs["position_embeddings"] = run(self.rotary, hidden, position_ids)
1106
+ for index in range(self.layers):
1107
+ result = run(self._layer_modules[index], hidden, **self._layer_kwargs(index, kwargs))
1108
+ hidden = result[0] if isinstance(result, tuple) else result
1109
+ return hidden, cache
1110
+
1111
+ # --- session / grammar --------------------------------------------------------------
1112
+
1113
+ @torch.no_grad()
1114
+ def session(self, token_ids: Sequence[int], *, prefill: int | None = None) -> Session:
1115
+ """A session over the prompt ``token_ids``: the first ``prefill`` rows are computed in
1116
+ one batched native call (default: all but the last), the next row is pending.
1117
+
1118
+ With ``prefill`` below ``len(token_ids) - 1`` the remaining prompt rows are stepped one
1119
+ row at a time by the same transitions as generated rows: the state then holds the whole
1120
+ prompt in the ``prompt`` slot and the ``sample`` transition of a prompt row writes the
1121
+ prompt's next token (``forced_token``) instead of the argmax. The default procedure has
1122
+ no ``prompt`` slot, so its states, cuts and fingerprints are those of before the slot
1123
+ existed. The split is part of the cut: a batched and a stepped row can differ in their
1124
+ cached K/V bits, and the root cut of each procedure is a different state."""
1125
+ self.validate_execution()
1126
+ tokens = torch.tensor([list(token_ids)], dtype=torch.long, device=self.device)
1127
+ if tokens.shape[-1] < 1:
1128
+ raise ValueError("at least one pending token is required")
1129
+ count = tokens.shape[-1]
1130
+ if prefill is None:
1131
+ prefill = count - 1
1132
+ if isinstance(prefill, bool) or not isinstance(prefill, int) or not 0 <= prefill < count:
1133
+ raise ValueError(f"prefill must be an integer in 0..{count - 1} (the prompt has "
1134
+ f"{count} tokens; the row after the prefilled ones is pending)")
1135
+ self._guard_window(count)
1136
+ prompt = tokens
1137
+ tokens = tokens[:, : prefill + 1].clone()
1138
+ cache = DynamicCache(config=self.model.config)
1139
+ if prefill > 0:
1140
+ if self._residency.mode == "streamed":
1141
+ cache = self._streamed_backbone(tokens[:, :-1])[1]
1142
+ else:
1143
+ cache = self.model(tokens[:, :-1], use_cache=True).past_key_values
1144
+ keys, values = self._cache_values(cache)
1145
+ state = {
1146
+ "tokens": tokens,
1147
+ "keys": keys,
1148
+ "values": values,
1149
+ "layer": 0,
1150
+ "phase": "embed",
1151
+ "hidden": None,
1152
+ "logits": None,
1153
+ "sampled_token": None,
1154
+ }
1155
+ if prefill < count - 1:
1156
+ state["prompt"] = prompt
1157
+ return Session(self, state)
1158
+
1159
+ @staticmethod
1160
+ def _forced(state: Mapping[str, Any]) -> torch.Tensor | None:
1161
+ """The prompt token the pending row's ``sample`` writes (``[1, 1]``), or None when the
1162
+ row is the prompt's last (or past it) and ``sample`` is the native argmax."""
1163
+ prompt = state.get("prompt")
1164
+ if prompt is None:
1165
+ return None
1166
+ row = state["tokens"].shape[1]
1167
+ if row >= prompt.shape[1]:
1168
+ return None
1169
+ return prompt[:, row : row + 1].clone()
1170
+
1171
+ def _guard_window(self, count: int) -> None:
1172
+ if self.sliding_window is not None and count > self.sliding_window:
1173
+ raise ValueError(
1174
+ "context exceeds the sliding-window horizon; windowed attention is not registered"
1175
+ )
1176
+
1177
+ def boundary(self, state: Mapping[str, Any]) -> str:
1178
+ if self.granularity == "layer":
1179
+ if state["hidden"] is None:
1180
+ return "token"
1181
+ return f"layer:{state['layer']}"
1182
+ phase = state["phase"]
1183
+ if phase == "layer":
1184
+ return f"token:{state['tokens'].shape[1] - 1}/layer:{state['layer']}"
1185
+ return f"token:{state['tokens'].shape[1] - 1}/{phase}"
1186
+
1187
+ def point(self, state: Mapping[str, Any]) -> ExecutionPoint:
1188
+ phase = state["phase"]
1189
+ index = state["layer"] if phase == "layer" else None
1190
+ next_operation = {
1191
+ "embed": f"{self.spec.backbone}.{self.spec.embed}",
1192
+ "normalization": f"{self.spec.backbone}.{self.spec.final_norm}",
1193
+ "readout": "lm_head",
1194
+ "sample": "greedy_argmax" if self._forced(state) is None else "forced_token",
1195
+ "commit": "token_commit",
1196
+ }.get(
1197
+ phase,
1198
+ (
1199
+ f"decoder_layer.{state['layer']}"
1200
+ if state["layer"] < self.layers
1201
+ else "normalization_readout_sampler_commit"
1202
+ ),
1203
+ )
1204
+ return ExecutionPoint(
1205
+ family=self.spec.model_type,
1206
+ logical_step=state["tokens"].shape[1] - 1,
1207
+ phase=phase,
1208
+ operator=phase,
1209
+ index=index,
1210
+ edge="before",
1211
+ next_operation=next_operation,
1212
+ local_clock=state["layer"],
1213
+ )
1214
+
1215
+ def transition(self, state: Mapping[str, Any]) -> TransitionSpec:
1216
+ phase = state["phase"]
1217
+ if state["hidden"] is None:
1218
+ reads, writes = ("tokens",), ("hidden", "logits", "phase")
1219
+ elif state["layer"] < self.layers:
1220
+ reads = ("tokens", "hidden", "keys", "values", "layer")
1221
+ writes = ("hidden", "keys", "values", "layer", "phase")
1222
+ elif self.granularity == "operation":
1223
+ reads, writes = {
1224
+ "normalization": (("hidden",), ("hidden", "phase")),
1225
+ "readout": (("hidden",), ("logits", "phase")),
1226
+ "sample": (("logits",) if self._forced(state) is None else ("tokens", "prompt"),
1227
+ ("sampled_token", "phase")),
1228
+ "commit": (
1229
+ ("tokens", "sampled_token"),
1230
+ ("tokens", "hidden", "sampled_token", "layer", "phase"),
1231
+ ),
1232
+ }[phase]
1233
+ else:
1234
+ reads = ("hidden", "tokens") + (("prompt",) if "prompt" in state else ())
1235
+ writes = ("logits", "tokens", "hidden", "layer", "phase")
1236
+ return TransitionSpec(
1237
+ self.point(state).next_operation,
1238
+ reads,
1239
+ writes,
1240
+ consumer=f"native-{self.spec.model_type}-suffix",
1241
+ footprint="declared",
1242
+ )
1243
+
1244
+ def surface(self, state: Mapping[str, Any]) -> SurfaceManifest:
1245
+ def tensor_schema(value: torch.Tensor | None, *, optional: bool = False) -> dict[str, Any]:
1246
+ if value is None:
1247
+ return {"kind": "tensor", "optional": optional}
1248
+ return {
1249
+ "kind": "tensor",
1250
+ "shape": list(value.shape),
1251
+ "stride": list(value.stride()),
1252
+ "dtype": str(value.dtype),
1253
+ "device": str(value.device),
1254
+ "optional": optional,
1255
+ }
1256
+
1257
+ slots = (
1258
+ SlotSpec(
1259
+ "tokens",
1260
+ role="cursor",
1261
+ producer="token_commit",
1262
+ consumer="embed",
1263
+ schema=tensor_schema(state["tokens"]),
1264
+ ),
1265
+ SlotSpec(
1266
+ "keys",
1267
+ role="cache",
1268
+ producer="decoder_layer",
1269
+ consumer="attention",
1270
+ schema={"kind": "tensor_sequence", "length": self.layers},
1271
+ ),
1272
+ SlotSpec(
1273
+ "values",
1274
+ role="cache",
1275
+ producer="decoder_layer",
1276
+ consumer="attention",
1277
+ schema={"kind": "tensor_sequence", "length": self.layers},
1278
+ ),
1279
+ SlotSpec(
1280
+ "hidden",
1281
+ role="carrier",
1282
+ writable=state["hidden"] is not None,
1283
+ persistence="authoritative",
1284
+ producer="embed_or_layer",
1285
+ consumer="native_suffix",
1286
+ schema=tensor_schema(state["hidden"], optional=True),
1287
+ ),
1288
+ SlotSpec(
1289
+ "logits",
1290
+ role="observation",
1291
+ producer="lm_head",
1292
+ consumer="greedy_argmax",
1293
+ schema=tensor_schema(state["logits"], optional=True),
1294
+ ),
1295
+ SlotSpec(
1296
+ "sampled_token",
1297
+ role="decision",
1298
+ producer="greedy_argmax",
1299
+ consumer="token_commit",
1300
+ schema=tensor_schema(state["sampled_token"], optional=True),
1301
+ ),
1302
+ SlotSpec(
1303
+ "layer",
1304
+ role="clock",
1305
+ producer="decoder_layer",
1306
+ consumer="runtime",
1307
+ schema={"kind": "integer", "minimum": 0, "maximum": self.layers},
1308
+ ),
1309
+ SlotSpec(
1310
+ "phase",
1311
+ role="clock",
1312
+ producer="runtime",
1313
+ consumer="runtime",
1314
+ schema={
1315
+ "kind": "enum",
1316
+ "values": ["embed", "layer", "normalization", "readout", "sample", "commit"],
1317
+ },
1318
+ ),
1319
+ )
1320
+ if "prompt" in state: # a stepped prompt: the tokens its sample transitions force
1321
+ slots += (
1322
+ SlotSpec(
1323
+ "prompt",
1324
+ role="decision",
1325
+ producer="prefill",
1326
+ consumer="forced_token",
1327
+ schema=tensor_schema(state["prompt"]),
1328
+ ),
1329
+ )
1330
+ return SurfaceManifest(
1331
+ slots=slots,
1332
+ state_schema=f"saturn-pub-decoder-{self.spec.model_type}-state-v1",
1333
+ consumer=f"native-{self.spec.model_type}-suffix",
1334
+ horizon="native-autoregressive-suffix",
1335
+ )
1336
+
1337
+ def addresses(self, state: Mapping[str, Any]) -> tuple[str, ...]:
1338
+ result = ("tokens",)
1339
+ if state["hidden"] is not None:
1340
+ result += ("hidden",)
1341
+ if state["logits"] is not None:
1342
+ result += ("logits",)
1343
+ return result
1344
+
1345
+ def validate(self, state: Mapping[str, Any]) -> None:
1346
+ self._verify_frozen_model()
1347
+ self.validate_state(state)
1348
+
1349
+ def _all_finite(self, tensors: Sequence[Any]) -> bool | None:
1350
+ """Whether every one of ``tensors`` is finite, with one host sync; None when one is not
1351
+ a tensor on the execution device (the per-tensor checks then decide, and name it)."""
1352
+ if not all(isinstance(t, torch.Tensor) and t.device == self.device for t in tensors):
1353
+ return None
1354
+ # a tensor checked finite before and unwritten since (same object and version counter:
1355
+ # the shares_state guard) is not checked again: a layer transition writes one K/V layer
1356
+ fresh = [t for t in tensors if TENSOR_FACTS.get(t, "finite") is not True]
1357
+ if not fresh:
1358
+ return True
1359
+ finite = bool(torch.stack([torch.isfinite(t).all() for t in fresh]).all())
1360
+ if finite:
1361
+ for t in fresh:
1362
+ TENSOR_FACTS.put(t, "finite", True)
1363
+ return finite
1364
+
1365
+ def validate_state(self, state: Mapping[str, Any]) -> None:
1366
+ """``validate`` without the frozen-model check, which ``validate_execution`` makes.
1367
+
1368
+ Finiteness of the K/V, hidden and logits tensors is one fused check (one host sync);
1369
+ only when it fails do the per-tensor checks run, so the refusal names the same tensor
1370
+ in the same order as before.
1371
+ """
1372
+ expected_keys = {
1373
+ "tokens",
1374
+ "keys",
1375
+ "values",
1376
+ "layer",
1377
+ "phase",
1378
+ "hidden",
1379
+ "logits",
1380
+ "sampled_token",
1381
+ }
1382
+ if "prompt" in state:
1383
+ expected_keys.add("prompt")
1384
+ if set(state) != expected_keys:
1385
+ raise ValueError("decoder state schema keys differ from the execution contract")
1386
+ tokens = state["tokens"]
1387
+ if (
1388
+ tokens.ndim != 2
1389
+ or tokens.shape[0] != 1
1390
+ or tokens.dtype != torch.long
1391
+ or tokens.device != self.device
1392
+ ):
1393
+ raise ValueError("decoder state requires batch-one integer tokens")
1394
+ if not 0 < tokens.shape[1] <= self.max_positions:
1395
+ raise ValueError("token count outside configured context")
1396
+ self._guard_window(tokens.shape[1])
1397
+ if bool(((tokens < 0) | (tokens >= self.vocab_size)).any()):
1398
+ raise ValueError("token ID outside vocabulary")
1399
+ layer = state["layer"]
1400
+ if type(layer) is not int or not 0 <= layer <= self.layers:
1401
+ raise ValueError("invalid layer cursor")
1402
+ phase = state["phase"]
1403
+ allowed_phases = {"embed", "layer"}
1404
+ if self.granularity == "operation":
1405
+ allowed_phases |= {"normalization", "readout", "sample", "commit"}
1406
+ if phase not in allowed_phases:
1407
+ raise ValueError("invalid decoder operation phase")
1408
+ if phase == "embed" and (state["hidden"] is not None or layer != 0):
1409
+ raise ValueError("invalid embedding boundary closure")
1410
+ if phase != "embed" and state["hidden"] is None:
1411
+ raise ValueError("missing hidden carrier")
1412
+ if phase == "layer" and layer > self.layers:
1413
+ raise ValueError("layer phase exceeds the native layer program")
1414
+ if self.granularity == "operation" and phase == "layer" and layer == self.layers:
1415
+ raise ValueError("operation mode must expose the normalization boundary")
1416
+ if phase in {"normalization", "readout", "sample", "commit"} and layer != self.layers:
1417
+ raise ValueError("post-layer phase requires a complete decoder stack")
1418
+ expected = tokens.shape[1] - 1
1419
+ keys, values = state["keys"], state["values"]
1420
+ if len(keys) != self.layers or len(values) != self.layers:
1421
+ raise ValueError("missing layer K/V")
1422
+ finite = self._all_finite(
1423
+ [*keys, *values, *(state[n] for n in ("hidden", "logits") if state[n] is not None)]
1424
+ )
1425
+ for index, (key, value) in enumerate(zip(keys, values)):
1426
+ length = expected + (1 if state["hidden"] is not None and index < layer else 0)
1427
+ shape = self._kv_shape(length)
1428
+ if tuple(key.shape) != shape or tuple(value.shape) != shape:
1429
+ raise ValueError("K/V closure does not match token/layer cursor")
1430
+ if key.dtype != self.dtype or value.dtype != self.dtype:
1431
+ raise ValueError("K/V dtype mismatch")
1432
+ if key.device != self.device or value.device != self.device:
1433
+ raise ValueError("K/V device mismatch")
1434
+ if not finite and (not torch.isfinite(key).all() or not torch.isfinite(value).all()):
1435
+ raise ValueError("non-finite K/V")
1436
+ hidden = state["hidden"]
1437
+ if hidden is not None and (
1438
+ tuple(hidden.shape) != (1, 1, self.hidden_size)
1439
+ or hidden.dtype != self.dtype
1440
+ or hidden.device != self.device
1441
+ or (not finite and not torch.isfinite(hidden).all())
1442
+ ):
1443
+ raise ValueError("invalid hidden carrier")
1444
+ logits = state["logits"]
1445
+ if logits is not None and (
1446
+ tuple(logits.shape) != (1, self.vocab_size)
1447
+ or logits.dtype != self.dtype
1448
+ or logits.device != self.device
1449
+ or (not finite and not torch.isfinite(logits).all())
1450
+ ):
1451
+ raise ValueError("invalid logit observation")
1452
+ if phase in {"sample", "commit"} and logits is None:
1453
+ raise ValueError("sampling requires the native logit observation")
1454
+ sampled = state["sampled_token"]
1455
+ if sampled is not None and (
1456
+ tuple(sampled.shape) != (1, 1)
1457
+ or sampled.dtype != torch.long
1458
+ or sampled.device != self.device
1459
+ or bool(((sampled < 0) | (sampled >= self.vocab_size)).any())
1460
+ ):
1461
+ raise ValueError("invalid sampled token")
1462
+ if (phase == "commit") != (sampled is not None):
1463
+ raise ValueError("sampled token exists only at the commit boundary")
1464
+ prompt = state.get("prompt")
1465
+ if prompt is not None:
1466
+ if (
1467
+ prompt.ndim != 2
1468
+ or prompt.shape[0] != 1
1469
+ or prompt.dtype != torch.long
1470
+ or prompt.device != self.device
1471
+ or prompt.shape[1] < 2
1472
+ ):
1473
+ raise ValueError("a stepped prompt is batch-one integer tokens, two or more")
1474
+ shared = min(tokens.shape[1], prompt.shape[1])
1475
+ if not torch.equal(tokens[:, :shared], prompt[:, :shared]):
1476
+ raise ValueError("the tokens differ from the stepped prompt they follow")
1477
+ forced = self._forced(state)
1478
+ if sampled is not None and forced is not None and not torch.equal(sampled, forced):
1479
+ raise ValueError("a prompt row's sampled token must be the prompt's next token")
1480
+
1481
+ def read(self, state: Mapping[str, Any], address: str) -> Any:
1482
+ """Read a listed address, or one of the cache/decision slots that exist in the state.
1483
+
1484
+ ``keys`` and ``values`` (per-layer cache tensors) are always present; ``sampled_token``
1485
+ only at the operation-granularity commit boundary; ``prompt`` only in a session whose
1486
+ prompt rows are stepped (``session(..., prefill=K)``). They are readable here but are
1487
+ not in ``addresses()``, so frames, cuts and receipts are unchanged.
1488
+ """
1489
+ if address in ("keys", "values"):
1490
+ return clone(state[address])
1491
+ if address == "prompt":
1492
+ if state.get("prompt") is None:
1493
+ raise ValueError(f"unsupported address at {self.boundary(state)}: {address} "
1494
+ "(this session prefilled its prompt)")
1495
+ return clone(state[address])
1496
+ if address == "sampled_token":
1497
+ if state["sampled_token"] is None:
1498
+ raise ValueError(f"unsupported address at {self.boundary(state)}: {address}")
1499
+ return clone(state[address])
1500
+ return super().read(state, address)
1501
+
1502
+ def supply_next_token(self, token_id: int | None) -> None:
1503
+ """Arm (or with None disarm) a supplied token for the next ``sample`` transition only, in
1504
+ place of the greedy argmax: a forced decision, for re-walking a stored sampled chain.
1505
+ The caller records it (mdb ``Run.feed`` keeps it on its trail and replays it)."""
1506
+ if token_id is not None and not (isinstance(token_id, int) and 0 <= token_id < self.vocab_size):
1507
+ raise ValueError(f"supplied token must be an id in 0..{self.vocab_size - 1}")
1508
+ self._supplied_token = token_id
1509
+
1510
+ def read_part(self, state: Mapping[str, Any], address: str, index: Any) -> Any:
1511
+ """One layer of ``keys`` / ``values`` (``index``), copying that layer only."""
1512
+ if address in ("keys", "values"):
1513
+ return clone(state[address][index])
1514
+ return super().read_part(state, address, index)
1515
+
1516
+ def write(
1517
+ self, state: Mapping[str, Any], writes: Mapping[str, Any], invalidates: tuple[str, ...]
1518
+ ) -> Mapping[str, Any]:
1519
+ if "tokens" in writes:
1520
+ raise ValueError("token writes require a new prefill; use adapter.session(new_tokens)")
1521
+ if "logits" in writes:
1522
+ raise ValueError("logits are observations; intervene on hidden before readout")
1523
+ if "sampled_token" in writes:
1524
+ raise ValueError("sampled tokens are decisions; intervene on logits upstream")
1525
+ if invalidates:
1526
+ raise ValueError(
1527
+ "decoder derived state is recomputed automatically; no manual invalidation"
1528
+ )
1529
+ return super().write(state, writes, ())
1530
+
1531
+ def ports(self, state: Mapping[str, Any]) -> tuple[str, ...]:
1532
+ """Qualified module names a port controller may hook in the pending decoder layer."""
1533
+ if state["hidden"] is None or state["phase"] != "layer" or state["layer"] >= self.layers:
1534
+ return ()
1535
+ prefix = f"{self.spec.backbone}.{self.spec.layers}.{state['layer']}"
1536
+ return tuple(
1537
+ f"{prefix}.{name}" if name else prefix
1538
+ for name, _ in self._layer_modules[state["layer"]].named_modules()
1539
+ )
1540
+
1541
+ def ports_ahead(self, state: Mapping[str, Any], steps: int) -> tuple[Any, ...]:
1542
+ """The decoder layer index each of the next ``steps`` transitions runs (``None`` for the
1543
+ embedding and the post-layer operations), derived from the state without running."""
1544
+ bare = state["hidden"] is None
1545
+ layer = state["layer"]
1546
+ post = ("normalization", "readout", "sample", "commit")
1547
+ phase = state["phase"] if state["phase"] in post else None
1548
+ out: list[int | None] = []
1549
+ for _ in range(steps):
1550
+ if bare:
1551
+ out.append(None)
1552
+ bare = False
1553
+ elif layer < self.layers:
1554
+ out.append(layer)
1555
+ layer += 1
1556
+ if layer == self.layers:
1557
+ phase = post[0]
1558
+ else:
1559
+ out.append(None)
1560
+ if self.granularity == "operation" and phase != post[-1]:
1561
+ phase = post[post.index(phase) + 1] if phase in post else post[1]
1562
+ else:
1563
+ bare, layer, phase = True, 0, None
1564
+ return tuple(out)
1565
+
1566
+ @torch.no_grad()
1567
+ def advance(
1568
+ self, state: Mapping[str, Any], *, ports: Any = None, validated: bool = False
1569
+ ) -> Mapping[str, Any]:
1570
+ """The next native transition of ``state``, which is left unchanged.
1571
+
1572
+ The result shares the tensors of the slots the transition does not write with
1573
+ ``state`` (they are never written in place) and holds new tensors for the rest; in a
1574
+ layer transition every K/V layer other than the ones the layer (or a cell edit) wrote
1575
+ is the input's own tensor (``shares_state``).
1576
+ ``validated``: the caller validated ``state`` and the executor (``validate_execution``)
1577
+ in this same call, so the entry validation is not repeated.
1578
+ """
1579
+ if not validated:
1580
+ self.validate(state)
1581
+ out = {**state, "keys": list(state["keys"]), "values": list(state["values"])}
1582
+ tokens = out["tokens"].to(self.device)
1583
+ if out["hidden"] is None:
1584
+ if tokens.shape[1] >= self.max_positions:
1585
+ raise ValueError("context capacity reached")
1586
+ out["hidden"] = self._embed(tokens)
1587
+ out["logits"] = None
1588
+ out["phase"] = "layer"
1589
+ return out
1590
+ # native modules and their hooks get a private copy of the carrier (as they got a copy of
1591
+ # the whole state before shares_state): a hook writing its input cannot reach the state
1592
+ hidden = out["hidden"].to(self.device, copy=True)
1593
+ layer = out["layer"]
1594
+ if layer < self.layers:
1595
+ cache = self._cache(out["keys"], out["values"], layer)
1596
+ populated = self._populated(cache)
1597
+ out["hidden"] = self._run_layer(layer, hidden, cache, tokens.shape[1] - 1, ports)
1598
+ out["keys"], out["values"] = self._cache_values_shared(
1599
+ cache, populated, out["keys"], out["values"]
1600
+ )
1601
+ out["layer"] = layer + 1
1602
+ if self.granularity == "operation" and out["layer"] == self.layers:
1603
+ out["phase"] = "normalization"
1604
+ elif self.granularity == "operation" and out["phase"] == "normalization":
1605
+ out["hidden"] = self._residency.run(
1606
+ getattr(self.backbone, self.spec.final_norm), hidden
1607
+ )
1608
+ out["phase"] = "readout"
1609
+ elif self.granularity == "operation" and out["phase"] == "readout":
1610
+ out["logits"] = self._apply_logit_softcap(
1611
+ self._residency.run(self.model.lm_head, hidden)[:, -1]
1612
+ )
1613
+ out["phase"] = "sample"
1614
+ elif self.granularity == "operation" and out["phase"] == "sample":
1615
+ supplied = getattr(self, "_supplied_token", None)
1616
+ forced = self._forced(out) # a stepped prompt row: the prompt's next token
1617
+ if supplied is not None: # a supplied decision (mdb Run.feed): one transition only
1618
+ self._supplied_token = None
1619
+ out["sampled_token"] = torch.tensor([[supplied]], dtype=torch.long,
1620
+ device=out["logits"].device)
1621
+ elif forced is not None:
1622
+ out["sampled_token"] = forced
1623
+ else:
1624
+ out["sampled_token"] = out["logits"].argmax(-1, keepdim=True)
1625
+ out["phase"] = "commit"
1626
+ elif self.granularity == "operation" and out["phase"] == "commit":
1627
+ out["tokens"] = torch.cat((tokens, out["sampled_token"]), dim=-1)
1628
+ seal_append(out["tokens"], tokens, 1) # cuts hold the new token only
1629
+ out["hidden"] = None
1630
+ out["sampled_token"] = None
1631
+ out["layer"] = 0
1632
+ out["phase"] = "embed"
1633
+ else:
1634
+ final_norm = getattr(self.backbone, self.spec.final_norm)
1635
+ run = self._residency.run
1636
+ logits = self._apply_logit_softcap(
1637
+ run(self.model.lm_head, run(final_norm, hidden))[:, -1]
1638
+ )
1639
+ out["logits"] = logits
1640
+ forced = self._forced(out)
1641
+ chosen = logits.argmax(-1, keepdim=True) if forced is None else forced
1642
+ out["tokens"] = torch.cat((tokens, chosen), dim=-1)
1643
+ seal_append(out["tokens"], tokens, 1) # cuts hold the new token only
1644
+ out["hidden"] = None
1645
+ out["layer"] = 0
1646
+ out["phase"] = "embed"
1647
+ return out
1648
+
1649
+ def generate(self, session: Session, tokens: int = 1) -> None:
1650
+ if tokens < 1:
1651
+ raise ValueError("generation budget must be positive")
1652
+ for _ in range(tokens):
1653
+ initial = session.read("tokens").shape[1]
1654
+ while session.read("tokens").shape[1] == initial:
1655
+ session.continue_()
1656
+
1657
+ @torch.inference_mode()
1658
+ def native_logits(self, tokens: Sequence[int]) -> torch.Tensor:
1659
+ """Uninstrumented full forward used as the numerical comparator.
1660
+
1661
+ In streamed residency the full forward is itself block-streamed (the whole model may
1662
+ not fit the device), reproducing the resident ``model(tokens)`` logits bitwise.
1663
+ """
1664
+ sequence = torch.tensor([list(tokens)], device=self.device)
1665
+ if self._residency.mode == "streamed":
1666
+ hidden, _ = self._streamed_backbone(sequence)
1667
+ final_norm = getattr(self.backbone, self.spec.final_norm)
1668
+ run = self._residency.run
1669
+ return self._apply_logit_softcap(
1670
+ run(self.model.lm_head, run(final_norm, hidden))[:, -1]
1671
+ )
1672
+ return self.model(sequence).logits[:, -1]
1673
+
1674
+
1675
+ def _accepts_kwargs(function: Callable[..., Any]) -> bool:
1676
+ return any(
1677
+ parameter.kind is inspect.Parameter.VAR_KEYWORD
1678
+ for parameter in inspect.signature(function).parameters.values()
1679
+ )