interplane.Get Omega
Read in your language

aien-sovereign-core-mv

AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.

Brought by drakestapleton

branch main Branches Tags History

aien-sovereign-core-mv / crates / aien-abi-core / src / lib.rs

695 lines · 25805 bytes Raw Blame History
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Drake Stapleton (AIEN / aien-dev)
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16use async_trait::async_trait;
17use serde::{Deserialize, Serialize};
18use std::collections::HashMap;
19
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
21pub struct ModelHandle(pub u64);
22
23#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
24pub struct ContextHandle(pub u64);
25
26#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
27pub struct BranchHandle(pub u64);
28
29#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
30pub struct AienUsageReceipt {
31 pub prefix_tokens: usize,
32 pub private_tokens: usize,
33 pub logical_pages: usize,
34 pub physical_pages: usize,
35 pub shared_pages: usize,
36 pub private_pages: usize,
37 pub cow_faults: usize,
38 pub physical_kv_bytes: usize,
39 pub bytes_saved_vs_full_copy: usize,
40}
41
42fn default_num_kv_heads() -> usize {
43 8
44}
45fn default_vocab_size() -> usize {
46 151936
47}
48fn default_rms_norm_eps() -> f32 {
49 1e-6
50}
51fn default_rope_theta() -> f32 {
52 10000.0
53}
54
55/// Llama 3 rotary frequency smoothing (`rope_scaling` with `rope_type: "llama3"` in a
56/// Hugging Face `config.json`). Long wavelengths are divided by `factor`, short ones kept,
57/// the band between `high_freq_factor` and `low_freq_factor` is interpolated
58/// (transformers `_compute_llama3_parameters`).
59#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
60pub struct Llama3RopeScaling {
61 pub factor: f64,
62 pub low_freq_factor: f64,
63 pub high_freq_factor: f64,
64 pub original_max_position_embeddings: usize,
65}
66
67impl Llama3RopeScaling {
68 /// Applies the llama3 smoothing to one unscaled inverse frequency.
69 pub fn scale_inv_freq(&self, inv_freq: f64) -> f64 {
70 let old_context = self.original_max_position_embeddings as f64;
71 let low_freq_wavelen = old_context / self.low_freq_factor;
72 let high_freq_wavelen = old_context / self.high_freq_factor;
73 let wavelen = 2.0 * std::f64::consts::PI / inv_freq;
74 if wavelen < high_freq_wavelen {
75 inv_freq
76 } else if wavelen > low_freq_wavelen {
77 inv_freq / self.factor
78 } else {
79 let smooth = (old_context / wavelen - self.low_freq_factor)
80 / (self.high_freq_factor - self.low_freq_factor);
81 (1.0 - smooth) * inv_freq / self.factor + smooth * inv_freq
82 }
83 }
84}
85
86/// Rotary position embedding parameters of one model: the base `theta` and, for the
87/// Llama 3 family, the llama3 frequency smoothing.
88#[derive(Debug, Clone, Copy, PartialEq)]
89pub struct RopeParams {
90 pub theta: f32,
91 pub llama3: Option<Llama3RopeScaling>,
92}
93
94impl RopeParams {
95 /// Unscaled rope: inverse frequency `theta^(-2i/d)`.
96 pub const fn plain(theta: f32) -> Self {
97 Self {
98 theta,
99 llama3: None,
100 }
101 }
102
103 /// Inverse frequency of rotary pair `i` (`0 <= i < head_dim / 2`), in f64.
104 /// The unscaled expression is exactly the one the reference rope has always used,
105 /// so models without scaling get bit-identical tables.
106 pub fn inv_freq(&self, i: usize, head_dim: usize) -> f64 {
107 let exponent = (2 * i) as f64 / (head_dim as f64);
108 let base = 1.0 / (self.theta as f64).powf(exponent);
109 match &self.llama3 {
110 None => base,
111 Some(scaling) => scaling.scale_inv_freq(base),
112 }
113 }
114
115 /// All `head_dim / 2` inverse frequencies.
116 pub fn inv_freqs(&self, head_dim: usize) -> Vec<f64> {
117 (0..head_dim / 2)
118 .map(|i| self.inv_freq(i, head_dim))
119 .collect()
120 }
121
122 /// Bit pattern identifying these parameters (for table caches).
123 pub fn cache_key(&self) -> [u64; 5] {
124 match &self.llama3 {
125 None => [self.theta.to_bits() as u64, 0, 0, 0, 0],
126 Some(s) => [
127 self.theta.to_bits() as u64 | (1 << 32),
128 s.factor.to_bits(),
129 s.low_freq_factor.to_bits(),
130 s.high_freq_factor.to_bits(),
131 s.original_max_position_embeddings as u64,
132 ],
133 }
134 }
135}
136
137#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
138pub struct ModelConfig {
139 pub model_id: String,
140 pub max_sequence_length: usize,
141 pub block_size: usize,
142 pub num_layers: usize,
143 pub num_heads: usize,
144 pub head_dim: usize,
145 #[serde(default = "default_num_kv_heads")]
146 pub num_kv_heads: usize,
147 #[serde(default)]
148 pub hidden_dim: usize,
149 #[serde(default)]
150 pub intermediate_dim: usize,
151 #[serde(default = "default_vocab_size")]
152 pub vocab_size: usize,
153 #[serde(default = "default_rms_norm_eps")]
154 pub rms_norm_eps: f32,
155 #[serde(default = "default_rope_theta")]
156 pub rope_theta: f32,
157 /// Llama 3 rope smoothing; `None` is plain rope.
158 #[serde(default)]
159 pub rope_scaling: Option<Llama3RopeScaling>,
160 /// True when the output projection reuses `model.embed_tokens.weight`
161 /// (the checkpoint has no `lm_head.weight`).
162 #[serde(default)]
163 pub tie_word_embeddings: bool,
164 /// Token ids that end a sequence (`eos_token_id` of `generation_config.json`).
165 /// Empty means the legacy TinyLlama set, see [`ModelConfig::stop_token_ids`].
166 #[serde(default)]
167 pub eos_token_ids: Vec<u32>,
168 /// True for Qwen3 (`Qwen3ForCausalLM`): every attention layer carries per-head RMSNorm
169 /// weights `self_attn.q_norm.weight` and `self_attn.k_norm.weight` (length `head_dim`),
170 /// applied to Q and K per head before RoPE. `head_dim` is then read from `config.json`
171 /// and `num_heads * head_dim` may differ from `hidden_dim`. Not serialized when false, so
172 /// every other model's serialized config is unchanged.
173 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
174 pub qk_norm: bool,
175}
176
177/// Why an [`AttentionGeometry`] was refused. Every variant names the offending numbers so a
178/// refusal in a log says what to fix.
179#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
180pub enum AttentionGeometryError {
181 ZeroQueryHeads,
182 ZeroKvHeads,
183 ZeroHeadDim,
184 /// `num_q_heads` is not a whole multiple of `num_kv_heads` (every kv head must serve the
185 /// same number of query heads).
186 QueryHeadsNotDivisible {
187 num_q_heads: usize,
188 num_kv_heads: usize,
189 },
190 /// `num_q_heads * head_dim` or `num_kv_heads * head_dim` does not fit in `usize`.
191 Overflow {
192 heads: usize,
193 head_dim: usize,
194 },
195 /// A KV pool (or any KV buffer) is laid out for a different kv-head count or head width
196 /// than this geometry.
197 KvPoolMismatch {
198 geometry_kv_heads: usize,
199 geometry_head_dim: usize,
200 pool_kv_heads: usize,
201 pool_head_dim: usize,
202 },
203}
204
205impl std::fmt::Display for AttentionGeometryError {
206 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
207 match self {
208 Self::ZeroQueryHeads => write!(f, "attention geometry: num_q_heads is 0"),
209 Self::ZeroKvHeads => write!(f, "attention geometry: num_kv_heads is 0"),
210 Self::ZeroHeadDim => write!(f, "attention geometry: head_dim is 0"),
211 Self::QueryHeadsNotDivisible {
212 num_q_heads,
213 num_kv_heads,
214 } => write!(
215 f,
216 "attention geometry: num_q_heads {num_q_heads} is not a multiple of num_kv_heads {num_kv_heads}"
217 ),
218 Self::Overflow { heads, head_dim } => write!(
219 f,
220 "attention geometry: {heads} heads x head_dim {head_dim} overflows usize"
221 ),
222 Self::KvPoolMismatch {
223 geometry_kv_heads,
224 geometry_head_dim,
225 pool_kv_heads,
226 pool_head_dim,
227 } => write!(
228 f,
229 "attention geometry: model has {geometry_kv_heads} kv heads x head_dim {geometry_head_dim} but the KV pool is laid out for {pool_kv_heads} kv heads x head_dim {pool_head_dim}"
230 ),
231 }
232 }
233}
234
235impl std::error::Error for AttentionGeometryError {}
236
237/// The checked head geometry of one attention layer: `num_q_heads` query heads sharing
238/// `num_kv_heads` key/value heads, every head `head_dim` wide.
239///
240/// Construction is the only way to get a value, so a geometry in hand always satisfies:
241/// no zero count, `num_q_heads` divisible by `num_kv_heads`, and both `q_dim` and `kv_dim`
242/// fit in `usize`. The contract deliberately does NOT require a power-of-two GQA ratio,
243/// `q_dim == hidden_dim` (Qwen3-Coder: q_dim 4096, hidden 2048) or `num_q_heads ==
244/// num_kv_heads`; a kernel with a narrower envelope refuses on its own and says so.
245///
246/// Flattened layouts the geometry describes:
247/// - q and attention output: `[num_q_heads][head_dim]` (`q_dim` values), head h at
248/// `h * head_dim`;
249/// - one token of K or V: `[num_kv_heads][head_dim]` (`kv_dim` values);
250/// - query head h reads kv head `h / gqa_ratio` ([`Self::kv_head_of`]).
251#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
252#[serde(try_from = "AttentionGeometryRaw", into = "AttentionGeometryRaw")]
253pub struct AttentionGeometry {
254 num_q_heads: usize,
255 num_kv_heads: usize,
256 head_dim: usize,
257}
258
259/// Serde shape of [`AttentionGeometry`]; deserialising re-runs the checks.
260#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
261pub struct AttentionGeometryRaw {
262 pub num_q_heads: usize,
263 pub num_kv_heads: usize,
264 pub head_dim: usize,
265}
266
267impl TryFrom<AttentionGeometryRaw> for AttentionGeometry {
268 type Error = AttentionGeometryError;
269 fn try_from(r: AttentionGeometryRaw) -> Result<Self, Self::Error> {
270 Self::new(r.num_q_heads, r.num_kv_heads, r.head_dim)
271 }
272}
273
274impl From<AttentionGeometry> for AttentionGeometryRaw {
275 fn from(g: AttentionGeometry) -> Self {
276 Self {
277 num_q_heads: g.num_q_heads,
278 num_kv_heads: g.num_kv_heads,
279 head_dim: g.head_dim,
280 }
281 }
282}
283
284impl AttentionGeometry {
285 /// Checks and builds the geometry. See the type docs for the exact rules.
286 pub fn new(
287 num_q_heads: usize,
288 num_kv_heads: usize,
289 head_dim: usize,
290 ) -> Result<Self, AttentionGeometryError> {
291 if num_q_heads == 0 {
292 return Err(AttentionGeometryError::ZeroQueryHeads);
293 }
294 if num_kv_heads == 0 {
295 return Err(AttentionGeometryError::ZeroKvHeads);
296 }
297 if head_dim == 0 {
298 return Err(AttentionGeometryError::ZeroHeadDim);
299 }
300 if !num_q_heads.is_multiple_of(num_kv_heads) {
301 return Err(AttentionGeometryError::QueryHeadsNotDivisible {
302 num_q_heads,
303 num_kv_heads,
304 });
305 }
306 if num_q_heads.checked_mul(head_dim).is_none() {
307 return Err(AttentionGeometryError::Overflow {
308 heads: num_q_heads,
309 head_dim,
310 });
311 }
312 // num_kv_heads <= num_q_heads here, so kv_dim fits whenever q_dim does.
313 Ok(Self {
314 num_q_heads,
315 num_kv_heads,
316 head_dim,
317 })
318 }
319
320 pub fn num_q_heads(&self) -> usize {
321 self.num_q_heads
322 }
323
324 pub fn num_kv_heads(&self) -> usize {
325 self.num_kv_heads
326 }
327
328 pub fn head_dim(&self) -> usize {
329 self.head_dim
330 }
331
332 /// Width of one flattened query (and of one attention output): `num_q_heads * head_dim`.
333 pub fn q_dim(&self) -> usize {
334 self.num_q_heads * self.head_dim
335 }
336
337 /// Width of one token's K (or V) row: `num_kv_heads * head_dim`.
338 pub fn kv_dim(&self) -> usize {
339 self.num_kv_heads * self.head_dim
340 }
341
342 /// Query heads per kv head (1 for multi-head attention).
343 pub fn gqa_ratio(&self) -> usize {
344 self.num_q_heads / self.num_kv_heads
345 }
346
347 /// The kv head query head `q_head` reads. `None` when `q_head >= num_q_heads`.
348 pub fn kv_head_of(&self, q_head: usize) -> Option<usize> {
349 (q_head < self.num_q_heads).then(|| q_head / self.gqa_ratio())
350 }
351
352 /// Refuses a KV pool or buffer laid out for a different kv-head count or head width.
353 /// Call it before any native (chip) code reads the pool with this geometry.
354 pub fn check_kv_pool(
355 &self,
356 pool_kv_heads: usize,
357 pool_head_dim: usize,
358 ) -> Result<(), AttentionGeometryError> {
359 if pool_kv_heads != self.num_kv_heads || pool_head_dim != self.head_dim {
360 return Err(AttentionGeometryError::KvPoolMismatch {
361 geometry_kv_heads: self.num_kv_heads,
362 geometry_head_dim: self.head_dim,
363 pool_kv_heads,
364 pool_head_dim,
365 });
366 }
367 Ok(())
368 }
369}
370
371impl ModelConfig {
372 pub fn tinyllama_1_1b() -> Self {
373 Self {
374 model_id: "TinyLlama/TinyLlama-1.1B-Chat-v1.0".to_string(),
375 max_sequence_length: 2048,
376 block_size: 16,
377 num_layers: 22,
378 num_heads: 32,
379 head_dim: 64,
380 num_kv_heads: 4,
381 hidden_dim: 2048,
382 intermediate_dim: 5632,
383 vocab_size: 32000,
384 rms_norm_eps: 1e-5,
385 rope_theta: 10000.0,
386 rope_scaling: None,
387 tie_word_embeddings: false,
388 eos_token_ids: Vec::new(),
389 qk_norm: false,
390 }
391 }
392
393 /// Stop set the backend ends a sequence on before the scheduler sees the token:
394 /// UNK 0, BOS 1 and EOS 2 of the TinyLlama vocabulary.
395 pub const LEGACY_STOP_TOKEN_IDS: [u32; 3] = [0, 1, 2];
396
397 /// The backend's end-of-sequence set: `eos_token_ids` when the model description
398 /// names them, else [`ModelConfig::LEGACY_STOP_TOKEN_IDS`].
399 pub fn stop_token_ids(&self) -> &[u32] {
400 if self.eos_token_ids.is_empty() {
401 &Self::LEGACY_STOP_TOKEN_IDS
402 } else {
403 &self.eos_token_ids
404 }
405 }
406
407 /// Rotary embedding parameters of this model.
408 pub fn rope(&self) -> RopeParams {
409 RopeParams {
410 theta: self.rope_theta,
411 llama3: self.rope_scaling,
412 }
413 }
414
415 /// The checked head geometry of this model's attention layers
416 /// (`num_heads` query heads, `num_kv_heads` kv heads, `head_dim`).
417 pub fn attention_geometry(&self) -> Result<AttentionGeometry, AttentionGeometryError> {
418 AttentionGeometry::new(self.num_heads, self.num_kv_heads, self.head_dim)
419 }
420
421 pub fn hidden_dim(&self) -> usize {
422 if self.hidden_dim > 0 {
423 self.hidden_dim
424 } else {
425 self.num_heads * self.head_dim
426 }
427 }
428
429 pub fn intermediate_dim(&self) -> usize {
430 if self.intermediate_dim > 0 {
431 self.intermediate_dim
432 } else {
433 self.hidden_dim() * 4
434 }
435 }
436
437 pub fn vocab_size(&self) -> usize {
438 if self.vocab_size > 0 {
439 self.vocab_size
440 } else {
441 151936
442 }
443 }
444}
445
446impl Default for ModelConfig {
447 fn default() -> Self {
448 Self {
449 model_id: "nvidia/NVIDIA-Nemotron-3.5-Lightning-30B-A3B-BF16".to_string(),
450 max_sequence_length: 32768,
451 block_size: 16,
452 num_layers: 48,
453 num_heads: 32,
454 head_dim: 128,
455 num_kv_heads: 8,
456 hidden_dim: 4096,
457 intermediate_dim: 14336,
458 vocab_size: 151936,
459 rms_norm_eps: 1e-6,
460 rope_theta: 10000.0,
461 rope_scaling: None,
462 tie_word_embeddings: false,
463 eos_token_ids: Vec::new(),
464 qk_norm: false,
465 }
466 }
467}
468
469#[derive(Debug, Clone, Serialize, Deserialize)]
470pub struct SamplingParams {
471 pub temperature: f32,
472 pub top_p: f32,
473 pub max_tokens: usize,
474 pub stop_token_ids: Vec<u32>,
475}
476
477impl Default for SamplingParams {
478 fn default() -> Self {
479 Self {
480 temperature: 0.7,
481 top_p: 0.95,
482 max_tokens: 512,
483 stop_token_ids: vec![0, 1, 2],
484 }
485 }
486}
487
488/// How a backend actually chose the tokens of one request, counted at the
489/// point of choice, never read back from the request's `SamplingParams`
490/// (Qwen3 v4 review, sc#294: greedy decoding must be observed, not only
491/// documented). Evidence only: no scheduling or decoding decision reads it.
492///
493/// Counts every token the backend chose for the request: the token after the
494/// final prefill chunk (a mid-prompt chunk's discarded pick is not counted)
495/// and every decode token, the stop token included.
496#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
497pub struct DecodeObservation {
498 /// Tokens taken as the argmax of the logits (greedy).
499 pub greedy_tokens: u64,
500 /// Tokens drawn at random from the temperature-scaled distribution.
501 pub sampled_tokens: u64,
502 /// Temperature of the sampled draws (the last draw's). None when no draw sampled.
503 pub temperature: Option<f32>,
504 /// top_p of the sampled decode draws when nucleus filtering was applied
505 /// (`0 < top_p < 1`). None when no draw applied it.
506 pub top_p: Option<f32>,
507 /// The request id the sampled draws were seeded from (the stream is a
508 /// pure function of it and the position). None when no draw sampled.
509 pub seed_request_id: Option<u64>,
510}
511
512// Temperatures recorded here passed through the sampler, which never sees a
513// NaN from the runtime; equality is used only to compare records.
514impl Eq for DecodeObservation {}
515
516/// Which tensor backend ran the model and how many operations it ran on the
517/// reference CPU path, as process totals since the backend was built (sc#337:
518/// "no silent fallback" must be shown, not inferred from the absence of a
519/// crash). Evidence only: nothing decides on it.
520#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
521pub struct OpEvidence {
522 /// The tensor backend's name (`TensorBackend::name`).
523 pub backend: String,
524 /// Runs of ops the backend claims native that fell back to the reference
525 /// CPU path. A production build panics on the first one, so a finished
526 /// strict call always records 0.
527 pub native_fallbacks: u64,
528 /// Runs of ops on the reference CPU path by design (outside the native mask).
529 pub reference_runs: u64,
530 /// The full `OP_REPORT native=[..] reference=[..] native_fallbacks=[..]
531 /// reference_runs=[..]` line.
532 pub report: String,
533 /// Operations the backend ran on its chip, as a process total (sc#402: the
534 /// Omega GB10 engine's `chip_calls`). ABSENT, not zero, for a backend that
535 /// has no chip or does not count its chip calls; serialized only when present,
536 /// so records of such backends are unchanged.
537 #[serde(default, skip_serializing_if = "Option::is_none")]
538 pub gpu_executions: Option<u64>,
539}
540
541impl DecodeObservation {
542 /// "greedy" (every chosen token was the argmax), "sampled" (every one was
543 /// drawn), "mixed", or "none" (no token was chosen).
544 pub fn mode(&self) -> &'static str {
545 match (self.greedy_tokens > 0, self.sampled_tokens > 0) {
546 (true, false) => "greedy",
547 (false, true) => "sampled",
548 (true, true) => "mixed",
549 (false, false) => "none",
550 }
551 }
552}
553
554#[derive(Debug, Clone, Serialize, Deserialize)]
555pub struct SequenceRequest {
556 pub request_id: u64,
557 pub prompt_tokens: Vec<u32>,
558 pub sampling_params: SamplingParams,
559 pub arrival_time_ns: u64,
560 pub priority: u8,
561}
562
563#[derive(Debug, Clone, Serialize, Deserialize)]
564pub struct ScheduledBatch {
565 pub prefill_requests: Vec<SequenceRequest>,
566 pub decode_requests: Vec<u64>,
567 pub block_tables: HashMap<u64, Vec<usize>>,
568 pub step_id: u64,
569}
570
571#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
572pub enum FinishReason {
573 StopToken,
574 LengthLimit,
575 Aborted,
576 Preempted,
577}
578
579#[derive(Debug, Clone, Serialize, Deserialize)]
580pub enum DecodeOutput {
581 Token {
582 request_id: u64,
583 token_id: u32,
584 logprob: Option<f32>,
585 },
586 Finished {
587 request_id: u64,
588 reason: FinishReason,
589 total_tokens: usize,
590 },
591}
592
593#[derive(Debug, Clone, Default, Serialize, Deserialize)]
594pub struct StepMetrics {
595 pub prefill_tokens_processed: usize,
596 pub decode_tokens_emitted: usize,
597 pub step_latency_us: u64,
598 pub active_kv_blocks: usize,
599}
600
601#[async_trait]
602pub trait AienInferenceBackend: Send + Sync {
603 async fn load_model(&mut self, config: &ModelConfig) -> Result<(), String>;
604 async fn execute_step(
605 &mut self,
606 batch: &ScheduledBatch,
607 ) -> Result<(Vec<DecodeOutput>, StepMetrics), String>;
608
609 /// Indicates whether the backend directly manages and appends tokens into the KV cache.
610 /// When true, the scheduler avoids redundant secondary append operations during decode steps.
611 fn manages_kv_cache(&self) -> bool {
612 false
613 }
614
615 /// PREFILL-E2E-0 bullets 6-8: forks the backend's per-sequence state
616 /// (tokens, position, last token) from a prefilled parent into a child.
617 /// Called by the runtime spine once per branch AFTER the root passed the
618 /// prefill completion fence and the KV manager shared the root blocks
619 /// (`fork_branches_from_ready_root`), and BEFORE any branch is decoded.
620 /// Must never copy or re-fork K/V: the physical KV fork is already done.
621 /// Default: no-op, for backends that keep no per-sequence state.
622 fn fork_sequence(&mut self, _parent_id: u64, _child_id: u64) -> Result<(), String> {
623 Ok(())
624 }
625
626 /// PREFILL-E2E C6 (bullet 11): `fork_sequence` that also hands the
627 /// backend the child's own sampling params, so a branch decodes with its
628 /// request's temperature/top_p instead of argmax. Decode batches carry
629 /// only request ids (`ScheduledBatch::decode_requests`), so the fork hook
630 /// is where a branch's params reach the backend.
631 /// Default: plain `fork_sequence` (params ignored).
632 fn fork_sequence_with_sampling(
633 &mut self,
634 parent_id: u64,
635 child_id: u64,
636 _sampling: &SamplingParams,
637 ) -> Result<(), String> {
638 self.fork_sequence(parent_id, child_id)
639 }
640
641 /// Drops the backend's per-sequence state for `seq_id` (PREFILL-E2E
642 /// bullet 12). The runtime spine calls it for every finished branch, for
643 /// the swarm root once its last branch finished, and for every sequence of
644 /// a cancelled swarm, always after the runtime freed the KV blocks and
645 /// never while a step is executing. Must not free KV: the runtime owns the
646 /// block tables. Unknown ids are a no-op (a cancelled branch may already
647 /// have finished). Default: no-op.
648 fn release_sequence(&mut self, _seq_id: u64) -> Result<(), String> {
649 Ok(())
650 }
651
652 /// Persistent KV (ADR 0003 section 6.2, review finding 3): the tokens of
653 /// `seq_id` whose K/V is actually written in the KV pool, in order. This is
654 /// never the whole token list: after a decode step the last token has been
655 /// sampled but not yet run through the model, so it has no K/V. `None` for
656 /// an unknown sequence or a backend that does not keep its K/V in the shared
657 /// pool. Read-only; the scheduler calls it at the finish transaction while
658 /// the backend still holds the sequence, before the KV lock is taken.
659 /// Default: `None` (no claim, so nothing is ever parked from this backend).
660 fn computed_prefix(&self, _seq_id: u64) -> Option<Vec<u32>> {
661 None
662 }
663
664 /// Persistent KV (ADR 0003 section 6.3): gives `seq_id` backend state for a
665 /// prefix whose K/V a restore already placed in its KV block table, so the
666 /// next prefill chunk starts at position `tokens.len()`. `tokens` is the
667 /// restored prefix. Never copies or computes K/V. Called by the runtime
668 /// after the restored table was assembled and before the scheduler admits
669 /// the remaining prompt. Default: `Err`, because a backend that does not
670 /// override this cannot continue from restored K/V and the caller must fall
671 /// back to a plain prefill.
672 fn restore_sequence(&mut self, seq_id: u64, tokens: &[u32]) -> Result<(), String> {
673 Err(format!(
674 "restore_sequence {} ({} tokens) refused: this backend does not support restoring a persisted KV prefix",
675 seq_id,
676 tokens.len()
677 ))
678 }
679
680 /// Takes (and forgets) how the backend chose `request_id`'s tokens so
681 /// far. The scheduler calls it once, when the request finishes, and
682 /// attaches it to `CompletionEvent::Finished`. Default: None, for a
683 /// backend that does not observe its decoding (an absent claim, not greedy).
684 fn take_decode_observation(&mut self, _request_id: u64) -> Option<DecodeObservation> {
685 None
686 }
687
688 /// The tensor backend and its op counters so far (sc#337). The scheduler
689 /// reads it when a request finishes and attaches it to
690 /// `CompletionEvent::Finished`. Default: None, for a backend that does not
691 /// account its ops (an absent claim, not zero fallbacks).
692 fn op_evidence(&self) -> Option<OpEvidence> {
693 None
694 }
695}