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-inference-abi / src / transformer_backend.rs

3158 lines · 127063 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
16//! Pure native Rust transformer inference backend executing real forward passes.
17//! Dispatches tensor math through the decoupled TensorBackend trait for CPU and Omega GB10 execution.
18
19use crate::backend::{ReferenceCpuBackend, TensorBackend};
20use crate::tensor::{sample_argmax, sample_temperature};
21use crate::weights::{LayerKvCache, SequenceState, TransformerWeights};
22use crate::{
23 AienInferenceBackend, AienUsageReceipt, BranchHandle, ContextHandle, DecodeObservation,
24 DecodeOutput, FinishReason, ModelConfig, SamplingParams, ScheduledBatch, StepMetrics,
25};
26use aien_kv_cache::{
27 create_shared_kv_manager_with_pool, round_to_dtype_in_place, AienKvManager, KvDType,
28 KvPoolConfig, SharedKvManager,
29};
30use async_trait::async_trait;
31use std::collections::HashMap;
32use std::sync::atomic::{AtomicU64, Ordering};
33use std::sync::Arc;
34
35static NEXT_HANDLE_ID: AtomicU64 = AtomicU64::new(1);
36
37/// Stable prefix of every error returned when the paged KV pool cannot supply
38/// the blocks a prefill append or a single-token decode step needs
39/// (PREFILL-I25). The rest of the message says how many new blocks were needed
40/// and how many were free. Callers and tests may match on this prefix.
41pub const KV_POOL_EXHAUSTED_PREFIX: &str = "KV pool exhausted:";
42
43/// splitmix64 mixing step (the generator behind java.util.SplittableRandom):
44/// a bijective 64-bit mixer, in-house, no outside crate.
45fn splitmix64(mut z: u64) -> u64 {
46 z = z.wrapping_add(0x9E37_79B9_7F4A_7C15);
47 z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
48 z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
49 z ^ (z >> 31)
50}
51
52/// Deterministic seed for sampling the token at `position` (the sequence's
53/// token count before the new token) of request `request_id` (PREFILL-E2E
54/// C6). Swarm branches get distinct request ids from the runtime arena
55/// (`AienRuntimeSpine::launch_swarm` submits each branch with
56/// `request_id: child_seq.as_u64()`), so sibling branches forked from one
57/// root draw different streams; the same request replays the same stream.
58pub fn decode_sampling_seed(request_id: u64, position: usize) -> u64 {
59 splitmix64(request_id ^ splitmix64(position as u64))
60}
61
62/// Samples one token from `logits` under `params` with the given seed.
63/// - `temperature <= 0.001`: argmax (unchanged greedy path).
64/// - otherwise softmax(logits / temperature) in f64; if `0 < top_p < 1`
65/// only the smallest highest-probability set whose mass reaches `top_p`
66/// is kept (ties broken by lower token id); one uniform draw from the
67/// seed picks a token from the kept mass. (`SamplingParams` has no top-k
68/// field, so there is no top-k.)
69///
70/// Returns the token and its log-probability under the kept distribution.
71pub fn sample_with_params(logits: &[f32], params: &SamplingParams, seed: u64) -> (u32, f32) {
72 sample_with_params_observed(logits, params, seed, &mut DecodeObservation::default())
73}
74
75/// `sample_with_params` that also counts, inside the branch it takes, how the
76/// token was chosen (sc#294): greedy, or a draw at `temperature` (with
77/// `top_p` when nucleus filtering ran). The seed's request id is the caller's
78/// to record. The chosen token is identical to `sample_with_params`.
79pub fn sample_with_params_observed(
80 logits: &[f32],
81 params: &SamplingParams,
82 seed: u64,
83 obs: &mut DecodeObservation,
84) -> (u32, f32) {
85 let (token, logprob, _) = sample_with_params_traced(logits, params, seed, obs);
86 (token, logprob)
87}
88
89/// What one draw had to choose from (OWN-8B stage S): the kept set after the
90/// temperature softmax and the nucleus cut, counted inside the sampler, so a
91/// confident model and a sampler that ignores its seed can be told apart.
92#[derive(Debug, Clone, Copy, PartialEq)]
93pub struct DrawTrace {
94 /// Tokens with non-zero probability in the set the draw chose from. 1 for a
95 /// greedy pick; 1 for a sampled draw means the seed had nothing to choose.
96 pub kept: usize,
97 /// Probability of the most likely token after temperature, before the
98 /// nucleus cut. 1.0 for a greedy pick.
99 pub top_prob: f64,
100}
101
102/// `sample_with_params_observed` that also returns the [`DrawTrace`]. This is
103/// the one implementation of the sampling math; the other two call it.
104pub fn sample_with_params_traced(
105 logits: &[f32],
106 params: &SamplingParams,
107 seed: u64,
108 obs: &mut DecodeObservation,
109) -> (u32, f32, DrawTrace) {
110 if params.temperature <= 0.001 {
111 obs.greedy_tokens += 1;
112 let (token, logprob) = sample_argmax(logits);
113 let trace = DrawTrace {
114 kept: 1,
115 top_prob: 1.0,
116 };
117 return (token, logprob, trace);
118 }
119 obs.sampled_tokens += 1;
120 obs.temperature = Some(params.temperature);
121 assert!(!logits.is_empty(), "Logits cannot be empty");
122 let inv_t = 1.0f64 / params.temperature as f64;
123 let max = logits.iter().fold(f32::NEG_INFINITY, |m, &v| m.max(v)) as f64;
124 let mut probs: Vec<f64> = logits
125 .iter()
126 .map(|&v| ((v as f64 - max) * inv_t).exp())
127 .collect();
128 let sum: f64 = probs.iter().sum();
129 for p in probs.iter_mut() {
130 *p /= sum;
131 }
132
133 let mut kept: Vec<usize> = (0..probs.len()).collect();
134 let top_p = params.top_p as f64;
135 if top_p > 0.0 && top_p < 1.0 {
136 obs.top_p = Some(params.top_p);
137 kept.sort_by(|&a, &b| {
138 probs[b]
139 .partial_cmp(&probs[a])
140 .unwrap_or(std::cmp::Ordering::Equal)
141 .then(a.cmp(&b))
142 });
143 let mut cum = 0.0f64;
144 let mut keep = 0usize;
145 for &i in &kept {
146 cum += probs[i];
147 keep += 1;
148 if cum >= top_p {
149 break;
150 }
151 }
152 kept.truncate(keep);
153 }
154
155 let mass: f64 = kept.iter().map(|&i| probs[i]).sum();
156 let trace = DrawTrace {
157 kept: kept.iter().filter(|&&i| probs[i] > 0.0).count(),
158 // The largest logit contributed exp(0) = 1 to `sum`.
159 top_prob: 1.0 / sum,
160 };
161 // 53 random bits -> uniform in [0, 1), scaled to the kept mass.
162 let r = ((seed >> 11) as f64 / (1u64 << 53) as f64) * mass;
163 let mut cum = 0.0f64;
164 for &i in &kept {
165 cum += probs[i];
166 if r < cum {
167 return (i as u32, (probs[i] / mass).max(1e-300).ln() as f32, trace);
168 }
169 }
170 let last = *kept.last().expect("kept set is never empty");
171 let logprob = (probs[last] / mass).max(1e-300).ln() as f32;
172 (last as u32, logprob, trace)
173}
174
175/// Fully native Rust transformer backend executing real tensor forward computation.
176/// Decouples execution orchestration from compute hardware via the TensorBackend trait.
177pub struct NativeTransformerBackend {
178 pub weights: TransformerWeights,
179 pub sequences: HashMap<u64, SequenceState>,
180 pub tensor_backend: Arc<dyn TensorBackend>,
181 pub kv_manager: Option<SharedKvManager>,
182 /// Element type K/V are rounded to at birth when no physical pool is attached
183 /// (a pool's own dtype wins; see `storage_dtype`). `Fp32` = no rounding. A dense
184 /// control backend sets this to the pool dtype it is the reference for.
185 pub kv_dtype: KvDType,
186 /// Per-request sampling params used by decode (PREFILL-E2E C6). Recorded
187 /// from the prefill request (`execute_step`) and from the fork hook
188 /// (`fork_sequence_with_sampling`; a plain `fork_sequence` child inherits
189 /// its parent's entry). A request with no entry decodes with argmax.
190 sampling: HashMap<u64, SamplingParams>,
191 /// Token sampled after the most recent `execute_step` prefill chunk of a request,
192 /// not yet appended to `sequences[id].tokens`. A prefill request does not say
193 /// whether it is the final chunk of its prompt, so the sample is held here:
194 /// a following prefill chunk discards it (it was mid-prefill), and the first
195 /// decode (or fork) commits it. While a request is prefilling, `tokens.len()`
196 /// therefore always equals the number of positions whose K/V is cached.
197 pub pending_prefill_token: HashMap<u64, u32>,
198 /// How each request's tokens were actually chosen (sc#294), filled inside the
199 /// branch that chose them and taken once by the scheduler when the request
200 /// finishes (`take_decode_observation`).
201 decode_observed: HashMap<u64, DecodeTally>,
202}
203
204/// Per-request tally behind `DecodeObservation` (sc#294). The pick after a
205/// prefill chunk is held apart and replaced by the next chunk's, like
206/// `pending_prefill_token`, so a mid-prompt pick that is discarded is not counted.
207#[derive(Debug, Default)]
208struct DecodeTally {
209 prefill_pick: DecodeObservation,
210 decode: DecodeObservation,
211}
212
213impl DecodeTally {
214 fn merged(self) -> DecodeObservation {
215 let (p, d) = (self.prefill_pick, self.decode);
216 DecodeObservation {
217 greedy_tokens: p.greedy_tokens + d.greedy_tokens,
218 sampled_tokens: p.sampled_tokens + d.sampled_tokens,
219 temperature: d.temperature.or(p.temperature),
220 top_p: d.top_p.or(p.top_p),
221 seed_request_id: d.seed_request_id.or(p.seed_request_id),
222 }
223 }
224}
225
226impl NativeTransformerBackend {
227 /// Creates a new backend with default ReferenceCpuBackend oracle.
228 pub fn new(weights: TransformerWeights) -> Self {
229 Self {
230 weights,
231 sequences: HashMap::new(),
232 sampling: HashMap::new(),
233 decode_observed: HashMap::new(),
234 tensor_backend: Arc::new(ReferenceCpuBackend::new()),
235 kv_manager: None,
236 pending_prefill_token: HashMap::new(),
237 kv_dtype: KvDType::Fp32,
238 }
239 }
240
241 /// Creates a backend with an explicit TensorBackend implementation.
242 pub fn with_backend(
243 weights: TransformerWeights,
244 tensor_backend: Arc<dyn TensorBackend>,
245 ) -> Self {
246 Self {
247 weights,
248 sequences: HashMap::new(),
249 sampling: HashMap::new(),
250 decode_observed: HashMap::new(),
251 tensor_backend,
252 kv_manager: None,
253 pending_prefill_token: HashMap::new(),
254 kv_dtype: KvDType::Fp32,
255 }
256 }
257
258 /// Explicit constructor for ReferenceCpuBackend golden oracle.
259 pub fn new_reference(weights: TransformerWeights) -> Self {
260 Self::new(weights)
261 }
262
263 /// Convenience constructor with deterministic reference weights and ReferenceCpuBackend.
264 pub fn with_reference_weights(config: &ModelConfig) -> Self {
265 let weights = TransformerWeights::reference_test_weights(config);
266 Self::new(weights)
267 }
268
269 /// Explicit constructor for the GB10 GPU backend (Omega native kernels, no CUDA).
270 pub fn new_blackwell(weights: TransformerWeights) -> Self {
271 Self::with_backend(weights, Arc::new(crate::OmegaGb10Backend::new()))
272 }
273
274 /// Convenience constructor with deterministic reference weights and OmegaGb10Backend.
275 pub fn with_blackwell_backend(config: &ModelConfig) -> Self {
276 let weights = TransformerWeights::reference_test_weights(config);
277 Self::new_blackwell(weights)
278 }
279
280 /// Constructor attaching a physical reference-counted KV page pool for Copy-on-Write branching.
281 pub fn with_paged_kv(
282 weights: TransformerWeights,
283 total_blocks: usize,
284 block_size: usize,
285 ) -> Result<Self, String> {
286 let pool_cfg = KvPoolConfig::for_model(
287 total_blocks,
288 block_size,
289 weights.config.num_layers,
290 weights.config.num_kv_heads,
291 weights.config.head_dim,
292 KvDType::Fp32,
293 );
294 let kv_mgr = create_shared_kv_manager_with_pool(total_blocks, block_size, pool_cfg)?;
295 Ok(Self {
296 weights,
297 sequences: HashMap::new(),
298 sampling: HashMap::new(),
299 decode_observed: HashMap::new(),
300 tensor_backend: Arc::new(ReferenceCpuBackend::new()),
301 kv_manager: Some(kv_mgr),
302 pending_prefill_token: HashMap::new(),
303 kv_dtype: KvDType::Fp32,
304 })
305 }
306
307 /// Constructor attaching physical paged KV cache with explicit TensorBackend compute hardware.
308 pub fn with_paged_kv_backend(
309 weights: TransformerWeights,
310 tensor_backend: Arc<dyn TensorBackend>,
311 total_blocks: usize,
312 block_size: usize,
313 ) -> Result<Self, String> {
314 let pool_cfg = KvPoolConfig::for_model(
315 total_blocks,
316 block_size,
317 weights.config.num_layers,
318 weights.config.num_kv_heads,
319 weights.config.head_dim,
320 KvDType::Fp32,
321 );
322 let kv_mgr = create_shared_kv_manager_with_pool(total_blocks, block_size, pool_cfg)?;
323 Ok(Self {
324 weights,
325 sequences: HashMap::new(),
326 sampling: HashMap::new(),
327 decode_observed: HashMap::new(),
328 tensor_backend,
329 kv_manager: Some(kv_mgr),
330 pending_prefill_token: HashMap::new(),
331 kv_dtype: KvDType::Fp32,
332 })
333 }
334
335 /// Constructor attaching an existing shared KV manager and explicit TensorBackend compute hardware.
336 pub fn with_shared_kv_and_backend(
337 weights: TransformerWeights,
338 tensor_backend: Arc<dyn TensorBackend>,
339 kv_manager: SharedKvManager,
340 ) -> Self {
341 Self {
342 weights,
343 sequences: HashMap::new(),
344 sampling: HashMap::new(),
345 decode_observed: HashMap::new(),
346 tensor_backend,
347 kv_manager: Some(kv_manager),
348 pending_prefill_token: HashMap::new(),
349 kv_dtype: KvDType::Fp32,
350 }
351 }
352
353 /// Sampling params decode will use for `request_id`, if any were recorded
354 /// (PREFILL-E2E C6). `None` means decode takes the argmax.
355 pub fn sampling_params(&self, request_id: u64) -> Option<&SamplingParams> {
356 self.sampling.get(&request_id)
357 }
358
359 /// Creates a new immutable root context from prompt tokens.
360 pub fn prefill_sequence(
361 &mut self,
362 seq_id: u64,
363 prompt_tokens: &[u32],
364 ) -> Result<Vec<f32>, String> {
365 if prompt_tokens.is_empty() {
366 return Err("Cannot prefill empty prompt".to_string());
367 }
368
369 if let Some(kv_mgr) = &self.kv_manager {
370 kv_mgr.write().allocate_sequence(seq_id, prompt_tokens)?;
371 }
372
373 let num_layers = self.weights.config.num_layers;
374 let kv_dtype = self.storage_dtype();
375 let seq = self
376 .sequences
377 .entry(seq_id)
378 .or_insert_with(|| SequenceState {
379 tokens: Vec::new(),
380 layers: vec![LayerKvCache::default(); num_layers],
381 kv_dtype,
382 });
383
384 let last_hidden = Self::prefill_prompt_layer_by_layer_paged(
385 &self.weights,
386 &*self.tensor_backend,
387 prompt_tokens,
388 seq,
389 seq_id,
390 self.kv_manager.as_ref(),
391 )?;
392
393 let logits = Self::compute_logits_impl(&self.weights, &*self.tensor_backend, &last_hidden);
394 Ok(logits)
395 }
396
397 pub fn create_context(&mut self, prompt_tokens: &[u32]) -> Result<ContextHandle, String> {
398 if prompt_tokens.is_empty() {
399 return Err("Cannot create context with empty prompt".to_string());
400 }
401 let id = NEXT_HANDLE_ID.fetch_add(1, Ordering::SeqCst);
402 let handle = ContextHandle(id);
403
404 if let Some(kv_mgr) = &self.kv_manager {
405 kv_mgr.write().allocate_sequence(handle.0, prompt_tokens)?;
406 }
407
408 let num_layers = self.weights.config.num_layers;
409 let kv_dtype = self.storage_dtype();
410 let seq = self
411 .sequences
412 .entry(handle.0)
413 .or_insert_with(|| SequenceState {
414 tokens: Vec::new(),
415 layers: vec![LayerKvCache::default(); num_layers],
416 kv_dtype,
417 });
418
419 Self::prefill_prompt_layer_by_layer_paged(
420 &self.weights,
421 &*self.tensor_backend,
422 prompt_tokens,
423 seq,
424 handle.0,
425 self.kv_manager.as_ref(),
426 )?;
427
428 Ok(handle)
429 }
430
431 /// Appends the token sampled after a completed `execute_step` prefill (if any)
432 /// to the sequence, so the next decode feeds it at position `prompt_len`.
433 fn commit_pending_prefill_token(&mut self, seq_id: u64) {
434 if let Some(tok) = self.pending_prefill_token.remove(&seq_id) {
435 if let Some(seq) = self.sequences.get_mut(&seq_id) {
436 seq.tokens.push(tok);
437 }
438 }
439 }
440
441 /// Forks an existing context into an independently decoding branch with zero KV copying.
442 ///
443 /// Handle-API helper for library tests (`paged_transformer_parity.rs`,
444 /// `branch_client_harness.rs`, the unit tests below). It is NOT on the
445 /// runtime path: the spine forks backend state only through the trait hook
446 /// `AienInferenceBackend::fork_sequence`, which is gated on PrefillReady and
447 /// never copies K/V. This method is ungated and, without a KV manager,
448 /// copies the parent's dense K/V per branch; no code in aien-runtime or
449 /// aien-cli calls it (grep `fork_context`, PREFILL-E2E C4).
450 pub fn fork_context(&mut self, parent: ContextHandle) -> Result<BranchHandle, String> {
451 self.commit_pending_prefill_token(parent.0);
452 let parent_seq = self
453 .sequences
454 .get(&parent.0)
455 .ok_or_else(|| format!("Parent context {} not found", parent.0))?;
456
457 let child_id = NEXT_HANDLE_ID.fetch_add(1, Ordering::SeqCst);
458 let child = BranchHandle(child_id);
459
460 let child_seq = if self.kv_manager.is_some() {
461 SequenceState {
462 tokens: parent_seq.tokens.clone(),
463 layers: Vec::new(),
464 kv_dtype: parent_seq.kv_dtype,
465 }
466 } else {
467 parent_seq.clone()
468 };
469
470 if let Some(kv_mgr) = &self.kv_manager {
471 kv_mgr.write().fork_context(parent.0, child.0)?;
472 }
473
474 self.sequences.insert(child.0, child_seq);
475 Ok(child)
476 }
477
478 /// Releases a branch and immediately reclaims its private COW pages.
479 pub fn release_branch(&mut self, branch: BranchHandle) -> Result<(), String> {
480 self.sequences.remove(&branch.0);
481 self.pending_prefill_token.remove(&branch.0);
482 if let Some(kv_mgr) = &self.kv_manager {
483 let _ = kv_mgr.write().release_branch(branch.0);
484 }
485 Ok(())
486 }
487
488 /// Executes one autoregressive decode step for a branch, triggering COW if tail page is shared.
489 pub fn decode_branch_step(&mut self, branch: BranchHandle) -> Result<(u32, Vec<f32>), String> {
490 self.commit_pending_prefill_token(branch.0);
491 let seq = self
492 .sequences
493 .get_mut(&branch.0)
494 .ok_or_else(|| format!("Branch {} not found", branch.0))?;
495
496 let pos = seq.tokens.len().saturating_sub(1);
497 let last_token = *seq.tokens.last().unwrap_or(&1);
498
499 let hidden = Self::try_forward_token_impl_paged(
500 &self.weights,
501 &*self.tensor_backend,
502 last_token,
503 pos,
504 seq,
505 branch.0,
506 self.kv_manager.as_ref(),
507 )?;
508
509 let logits = Self::compute_logits_impl(&self.weights, &*self.tensor_backend, &hidden);
510 let (sampled_tok, _) = sample_argmax(&logits);
511 seq.tokens.push(sampled_tok);
512
513 Ok((sampled_tok, logits))
514 }
515
516 /// Ingests branch-specific prompt/delta tokens into the physical paged KV cache, triggering COW on shared blocks.
517 pub fn append_branch_token(&mut self, branch: BranchHandle, token: u32) -> Result<(), String> {
518 // An explicitly supplied token replaces any sample held from a prefill chunk.
519 self.pending_prefill_token.remove(&branch.0);
520 let seq = self
521 .sequences
522 .get_mut(&branch.0)
523 .ok_or_else(|| format!("Branch {} not found", branch.0))?;
524
525 let pos = seq.tokens.len();
526 let _hidden = Self::try_forward_token_impl_paged(
527 &self.weights,
528 &*self.tensor_backend,
529 token,
530 pos,
531 seq,
532 branch.0,
533 self.kv_manager.as_ref(),
534 )?;
535 seq.tokens.push(token);
536 Ok(())
537 }
538
539 /// Ingests multiple branch-specific delta tokens sequentially.
540 pub fn append_branch_tokens(
541 &mut self,
542 branch: BranchHandle,
543 tokens: &[u32],
544 ) -> Result<(), String> {
545 for &tok in tokens {
546 self.append_branch_token(branch, tok)?;
547 }
548 Ok(())
549 }
550
551 /// Generates tokens autoregressively, invoking a callback for each generated token.
552 pub fn generate_tokens_streaming<F>(
553 &mut self,
554 seq_id: u64,
555 prompt_tokens: &[u32],
556 max_tokens: usize,
557 temperature: f32,
558 stop_tokens: &[u32],
559 mut on_token: F,
560 ) -> Result<(), String>
561 where
562 F: FnMut(u32) -> bool,
563 {
564 if prompt_tokens.is_empty() {
565 return Err("Cannot generate from empty prompt".to_string());
566 }
567
568 let logits = self.prefill_sequence(seq_id, prompt_tokens)?;
569
570 let (first_tok, _) = if temperature <= 0.001 {
571 sample_argmax(&logits)
572 } else {
573 sample_temperature(&logits, temperature, seq_id)
574 };
575
576 if stop_tokens.contains(&first_tok) {
577 self.release_sequence(seq_id);
578 return Ok(());
579 }
580
581 if !on_token(first_tok) {
582 self.release_sequence(seq_id);
583 return Ok(());
584 }
585
586 if let Some(seq) = self.sequences.get_mut(&seq_id) {
587 seq.tokens.push(first_tok);
588 }
589
590 for step in 1..max_tokens {
591 let seq = match self.sequences.get_mut(&seq_id) {
592 Some(s) => s,
593 None => break,
594 };
595
596 let pos = seq.tokens.len().saturating_sub(1);
597 let last_token = *seq.tokens.last().unwrap_or(&1);
598
599 let hidden = match Self::try_forward_token_impl_paged(
600 &self.weights,
601 &*self.tensor_backend,
602 last_token,
603 pos,
604 seq,
605 seq_id,
606 self.kv_manager.as_ref(),
607 ) {
608 Ok(hidden) => hidden,
609 Err(e) => {
610 // This standalone generator owns its KV: do not leak the
611 // sequence when a decode step cannot get a block.
612 self.release_sequence(seq_id);
613 return Err(e);
614 }
615 };
616
617 let next_logits =
618 Self::compute_logits_impl(&self.weights, &*self.tensor_backend, &hidden);
619 let (next_tok, _) = if temperature <= 0.001 {
620 sample_argmax(&next_logits)
621 } else {
622 sample_temperature(&next_logits, temperature, seq_id.wrapping_add(step as u64))
623 };
624
625 if stop_tokens.contains(&next_tok) {
626 break;
627 }
628
629 if !on_token(next_tok) {
630 break;
631 }
632
633 if let Some(seq) = self.sequences.get_mut(&seq_id) {
634 seq.tokens.push(next_tok);
635 }
636 }
637
638 self.release_sequence(seq_id);
639 Ok(())
640 }
641
642 /// Generates tokens autoregressively from a sequence of prompt tokens.
643 pub fn generate_tokens(
644 &mut self,
645 seq_id: u64,
646 prompt_tokens: &[u32],
647 max_tokens: usize,
648 temperature: f32,
649 stop_tokens: &[u32],
650 ) -> Result<Vec<u32>, String> {
651 let mut generated = Vec::with_capacity(max_tokens);
652 self.generate_tokens_streaming(
653 seq_id,
654 prompt_tokens,
655 max_tokens,
656 temperature,
657 stop_tokens,
658 |tok| {
659 generated.push(tok);
660 true
661 },
662 )?;
663 Ok(generated)
664 }
665
666 /// Releases a sequence from memory and frees associated KV cache resources.
667 pub fn release_sequence(&mut self, seq_id: u64) {
668 self.sequences.remove(&seq_id);
669 self.pending_prefill_token.remove(&seq_id);
670 self.decode_observed.remove(&seq_id);
671 if let Some(kv_mgr) = &self.kv_manager {
672 let _ = kv_mgr.write().release_branch(seq_id);
673 }
674 }
675
676 /// Loads TinyLlama weights from safetensors with optional paged KV cache and compute backend.
677 pub fn load_tinyllama_safetensors<P: AsRef<std::path::Path>>(
678 checkpoint_path: P,
679 tensor_backend: Option<Arc<dyn TensorBackend>>,
680 total_blocks: Option<usize>,
681 ) -> Result<Self, String> {
682 let config = ModelConfig::tinyllama_1_1b();
683 let weights = TransformerWeights::load_from_safetensors(checkpoint_path.as_ref(), &config)
684 .map_err(|e| format!("Failed to load safetensors: {}", e))?;
685
686 let backend = tensor_backend.unwrap_or_else(|| {
687 let surface = crate::ExecutionSurface::detect();
688 if surface.is_accelerated_gpu() {
689 Arc::new(crate::OmegaGb10Backend::new())
690 } else {
691 Arc::new(ReferenceCpuBackend::new())
692 }
693 });
694
695 if let Some(blocks) = total_blocks {
696 Self::with_paged_kv_backend(weights, backend, blocks, config.block_size)
697 } else {
698 Ok(Self::with_backend(weights, backend))
699 }
700 }
701
702 /// Returns a telemetry receipt for a branch, calculating shared pages and physical bytes saved.
703 pub fn get_usage_receipt(&self, branch: BranchHandle) -> Result<AienUsageReceipt, String> {
704 let kv_mgr = self
705 .kv_manager
706 .as_ref()
707 .ok_or_else(|| "KV manager not initialized on backend".to_string())?
708 .read();
709
710 let table = kv_mgr
711 .get_block_table(branch.0)
712 .ok_or_else(|| format!("Branch {} not found in KV cache", branch.0))?;
713 let metrics = kv_mgr.metrics();
714 let total_tokens = table.total_tokens;
715
716 let mut shared_pages = 0;
717 let mut private_pages = 0;
718 for &b in &table.block_ids {
719 if let Some(block) = kv_mgr.get_block(b) {
720 if block.is_shared {
721 shared_pages += 1;
722 } else {
723 private_pages += 1;
724 }
725 }
726 }
727
728 let bytes_per_block = kv_mgr.tensor_pool().map(|p| p.block_bytes()).unwrap_or(0);
729 let physical_kv_bytes = (shared_pages + private_pages) * bytes_per_block;
730
731 Ok(AienUsageReceipt {
732 prefix_tokens: shared_pages * kv_mgr.block_size(),
733 private_tokens: total_tokens.saturating_sub(shared_pages * kv_mgr.block_size()),
734 logical_pages: table.block_ids.len(),
735 physical_pages: metrics.physical_pages,
736 shared_pages,
737 private_pages,
738 cow_faults: metrics.cow_faults,
739 physical_kv_bytes,
740 bytes_saved_vs_full_copy: shared_pages * bytes_per_block,
741 })
742 }
743
744 /// Internal forward pass executing one token forward pass through the transformer.
745 /// sc draft-verify (2026-10-12): the speculative-verification primitive.
746 /// Forwards `block` (block[0] = the sequence's pending token, the one whose
747 /// K/V is not computed yet; block[1..] = draft tokens) at positions
748 /// offset..offset+n, offset = the K/V length of `seq_id` in the paged pool,
749 /// in ONE row-batched pass per layer: the matmuls take all n rows (as the
750 /// prompt read does), attention is the existing paged batch call with the
751 /// sequence's block table n times and context lengths offset+1..offset+n
752 /// (causal, pool read in place, no staging), the lm_head runs on every row.
753 /// Returns the greedy argmax of each row: row t predicts position
754 /// offset+t+1, so draft token block[t+1] is accepted while it equals row t.
755 /// The K/V of every row is left in the pool: the caller truncates to
756 /// offset + accepted + 1 (`truncate_kv`) and keeps its own token list
757 /// (`sequences[seq].tokens` is NOT touched here). On any error after the
758 /// slots were appended the pool is truncated back to `offset`. Needs the
759 /// paged pool (the GB10 serving construction); refused otherwise.
760 pub fn verify_block(&mut self, seq_id: u64, block: &[u32]) -> Result<Vec<u32>, String> {
761 let n = block.len();
762 let vocab = self.weights.config.vocab_size();
763 let logits = self.verify_block_logits(seq_id, block)?;
764 Ok((0..n)
765 .map(|t| sample_argmax(&logits[t * vocab..(t + 1) * vocab]).0)
766 .collect())
767 }
768
769 /// `verify_block` before the argmax: the full logits of every row, `n * vocab` f32.
770 pub fn verify_block_logits(&mut self, seq_id: u64, block: &[u32]) -> Result<Vec<f32>, String> {
771 let n = block.len();
772 if n == 0 || n > 64 {
773 return Err(format!("verify_block: {n} rows (1 to 64)"));
774 }
775 let mgr = self
776 .kv_manager
777 .clone()
778 .ok_or_else(|| "verify_block needs the paged KV pool".to_string())?;
779 let weights = &self.weights;
780 let backend: &dyn TensorBackend = &*self.tensor_backend;
781 let geom = weights
782 .config
783 .attention_geometry()
784 .map_err(|e| e.to_string())?;
785 backend.check_model(&weights.config)?;
786 let (num_heads, num_kv_heads, head_dim) =
787 (geom.num_q_heads(), geom.num_kv_heads(), geom.head_dim());
788 let (q_dim, kv_dim) = (geom.q_dim(), geom.kv_dim());
789 let hidden_dim = weights.config.hidden_dim();
790 let intermediate_dim = weights.config.intermediate_dim();
791 let vocab = weights.config.vocab_size();
792 let eps = weights.config.rms_norm_eps;
793 let rope = weights.config.rope();
794 // Slots for the n positions, appended up front (as the prompt read does).
795 let (offset, slots, block_ids) = {
796 let mut w = mgr.write();
797 if w.tensor_pool().is_none() {
798 return Err("verify_block needs the paged KV pool (tensor pool)".into());
799 }
800 let tbl = w
801 .get_block_table(seq_id)
802 .cloned()
803 .ok_or_else(|| format!("verify_block: sequence {seq_id} has no block table"))?;
804 let offset = tbl.total_tokens;
805 if let Some((needed, available)) = Self::kv_pool_shortfall(&w, seq_id, n) {
806 return Err(Self::kv_pool_exhausted_error(
807 &format!("verify block of {n} tokens at position {offset}"),
808 seq_id,
809 needed,
810 available,
811 ));
812 }
813 let mut slots = Vec::with_capacity(n);
814 for t in 0..n {
815 slots.push(w.append_token_with_slot(seq_id).map_err(|e| {
816 format!(
817 "{KV_POOL_EXHAUSTED_PREFIX} verify append of position {} failed: {e}",
818 offset + t
819 )
820 })?);
821 }
822 let ids = w
823 .get_block_table(seq_id)
824 .map(|t| t.block_ids.clone())
825 .unwrap_or_default();
826 (offset, slots, ids)
827 };
828 let run = || -> Result<Vec<f32>, String> {
829 let mut states: Vec<Vec<f32>> = block
830 .iter()
831 .map(|&tok| {
832 let i = (tok as usize) % vocab;
833 weights.embed_tokens[i * hidden_dim..(i + 1) * hidden_dim].to_vec()
834 })
835 .collect();
836 let mut x_flat = vec![0.0f32; n * hidden_dim];
837 let flatten = |x_flat: &mut [f32], states: &[Vec<f32>]| {
838 for (t, s) in states.iter().enumerate() {
839 x_flat[t * hidden_dim..(t + 1) * hidden_dim].copy_from_slice(s);
840 }
841 };
842 let mut x_norm = vec![0.0f32; n * hidden_dim];
843 let mut q_b = vec![0.0f32; n * q_dim];
844 let mut k_b = vec![0.0f32; n * kv_dim];
845 let mut v_b = vec![0.0f32; n * kv_dim];
846 let qkv_dim = q_dim + 2 * kv_dim;
847 let mut qkv_b = vec![0.0f32; n * qkv_dim];
848 let mut attn_b = vec![0.0f32; n * q_dim];
849 let mut proj_b = vec![0.0f32; n * hidden_dim];
850 let mut post_b = vec![0.0f32; n * hidden_dim];
851 let mut gate_b = vec![0.0f32; n * intermediate_dim];
852 let mut up_b = vec![0.0f32; n * intermediate_dim];
853 let mut act_b = vec![0.0f32; n * intermediate_dim];
854 let mut gu_b = vec![0.0f32; n * 2 * intermediate_dim];
855 let mut mlp_b = vec![0.0f32; n * hidden_dim];
856 let max_blocks = block_ids.len().max(1);
857 let mut tables = vec![-1i32; n * max_blocks];
858 let mut ctx = vec![0i32; n];
859 for t in 0..n {
860 for (j, &b) in block_ids.iter().enumerate() {
861 tables[t * max_blocks + j] =
862 i32::try_from(b).map_err(|_| "block id past i32")?;
863 }
864 ctx[t] = i32::try_from(offset + t + 1).map_err(|_| "context past i32")?;
865 }
866 for (layer_idx, layer_w) in weights.layers.iter().enumerate() {
867 flatten(&mut x_flat, &states);
868 backend.rmsnorm_rows(&mut x_norm, &x_flat, &layer_w.input_layernorm, n, eps);
869 if let Some(w) = layer_w.qkv_proj.as_ref() {
870 backend.matmul_batch_w(&mut qkv_b, &x_norm, w.as_ref(), n, hidden_dim, qkv_dim);
871 for t in 0..n {
872 let row = &qkv_b[t * qkv_dim..(t + 1) * qkv_dim];
873 q_b[t * q_dim..(t + 1) * q_dim].copy_from_slice(&row[..q_dim]);
874 k_b[t * kv_dim..(t + 1) * kv_dim]
875 .copy_from_slice(&row[q_dim..q_dim + kv_dim]);
876 v_b[t * kv_dim..(t + 1) * kv_dim].copy_from_slice(&row[q_dim + kv_dim..]);
877 }
878 } else {
879 backend.matmul_batch_w(
880 &mut q_b,
881 &x_norm,
882 layer_w.q_proj.as_ref(),
883 n,
884 hidden_dim,
885 q_dim,
886 );
887 backend.matmul_batch_w(
888 &mut k_b,
889 &x_norm,
890 layer_w.k_proj.as_ref(),
891 n,
892 hidden_dim,
893 kv_dim,
894 );
895 backend.matmul_batch_w(
896 &mut v_b,
897 &x_norm,
898 layer_w.v_proj.as_ref(),
899 n,
900 hidden_dim,
901 kv_dim,
902 );
903 }
904 layer_w.apply_qk_norm_on(backend, &mut q_b, &mut k_b, head_dim, eps);
905 for t in 0..n {
906 let q_t = &mut q_b[t * q_dim..(t + 1) * q_dim];
907 let k_t = &mut k_b[t * kv_dim..(t + 1) * kv_dim];
908 let v_t = &v_b[t * kv_dim..(t + 1) * kv_dim];
909 backend.apply_rope(
910 q_t,
911 k_t,
912 offset + t,
913 head_dim,
914 num_heads,
915 num_kv_heads,
916 &rope,
917 );
918 let (block_id, slot) = slots[t];
919 mgr.write()
920 .write_explicit_token_kv(block_id, layer_idx, slot, k_t, v_t)
921 .map_err(|e| {
922 format!(
923 "verify KV write layer {layer_idx} position {}: {e}",
924 offset + t
925 )
926 })?;
927 }
928 {
929 let r = mgr.read();
930 let pool = r.tensor_pool().ok_or("pool vanished")?;
931 backend.paged_attention_batch(
932 &mut attn_b,
933 &q_b,
934 pool,
935 &tables,
936 &ctx,
937 max_blocks,
938 n,
939 layer_idx,
940 num_heads,
941 num_kv_heads,
942 head_dim,
943 );
944 }
945 backend.matmul_batch_w(
946 &mut proj_b,
947 &attn_b,
948 layer_w.o_proj.as_ref(),
949 n,
950 q_dim,
951 hidden_dim,
952 );
953 for t in 0..n {
954 let p = &proj_b[t * hidden_dim..(t + 1) * hidden_dim];
955 for i in 0..hidden_dim {
956 states[t][i] += p[i];
957 }
958 }
959 flatten(&mut x_flat, &states);
960 backend.rmsnorm_rows(
961 &mut post_b,
962 &x_flat,
963 &layer_w.post_attention_layernorm,
964 n,
965 eps,
966 );
967 if let Some(w) = layer_w.gate_up_proj.as_ref() {
968 let gu = 2 * intermediate_dim;
969 backend.matmul_batch_w(&mut gu_b, &post_b, w.as_ref(), n, hidden_dim, gu);
970 for t in 0..n {
971 let row = &gu_b[t * gu..(t + 1) * gu];
972 gate_b[t * intermediate_dim..(t + 1) * intermediate_dim]
973 .copy_from_slice(&row[..intermediate_dim]);
974 up_b[t * intermediate_dim..(t + 1) * intermediate_dim]
975 .copy_from_slice(&row[intermediate_dim..]);
976 }
977 } else {
978 backend.matmul_batch_w(
979 &mut gate_b,
980 &post_b,
981 layer_w.gate_proj.as_ref(),
982 n,
983 hidden_dim,
984 intermediate_dim,
985 );
986 backend.matmul_batch_w(
987 &mut up_b,
988 &post_b,
989 layer_w.up_proj.as_ref(),
990 n,
991 hidden_dim,
992 intermediate_dim,
993 );
994 }
995 backend.swiglu(&mut act_b, &gate_b, &up_b);
996 backend.matmul_batch_w(
997 &mut mlp_b,
998 &act_b,
999 layer_w.down_proj.as_ref(),
1000 n,
1001 intermediate_dim,
1002 hidden_dim,
1003 );
1004 for t in 0..n {
1005 let m = &mlp_b[t * hidden_dim..(t + 1) * hidden_dim];
1006 for i in 0..hidden_dim {
1007 states[t][i] += m[i];
1008 }
1009 }
1010 }
1011 flatten(&mut x_flat, &states);
1012 let mut final_b = vec![0.0f32; n * hidden_dim];
1013 backend.rmsnorm_rows(&mut final_b, &x_flat, &weights.final_norm, n, eps);
1014 let mut logits = vec![0.0f32; n * vocab];
1015 backend.matmul_batch_w(
1016 &mut logits,
1017 &final_b,
1018 weights.output_matrix(),
1019 n,
1020 hidden_dim,
1021 vocab,
1022 );
1023 Ok(logits)
1024 };
1025 let out = run();
1026 if out.is_err() {
1027 let _ = mgr.write().truncate_sequence(seq_id, offset);
1028 }
1029 out
1030 }
1031
1032 /// Drops the K/V at or past `new_total` (pool and dense copies). The token
1033 /// list is the caller's.
1034 pub fn truncate_kv(&mut self, seq_id: u64, new_total: usize) -> Result<(), String> {
1035 if let Some(m) = &self.kv_manager {
1036 m.write().truncate_sequence(seq_id, new_total)?;
1037 }
1038 if let Some(seq) = self.sequences.get_mut(&seq_id) {
1039 for l in &mut seq.layers {
1040 let kvd = l.cached_k.first().map_or(0, |r| r.len());
1041 l.cached_k.truncate(new_total);
1042 l.cached_v.truncate(new_total);
1043 l.flat_k.truncate(new_total * kvd);
1044 l.flat_v.truncate(new_total * kvd);
1045 }
1046 }
1047 Ok(())
1048 }
1049
1050 /// Forwards the sequence's last token (the pending one) at its position and
1051 /// returns the logits of the next position; the token list is untouched.
1052 pub fn decode_pending(&mut self, seq_id: u64) -> Result<Vec<f32>, String> {
1053 let seq = self
1054 .sequences
1055 .get_mut(&seq_id)
1056 .ok_or_else(|| format!("decode_pending: sequence {seq_id} not found"))?;
1057 let pos = seq
1058 .tokens
1059 .len()
1060 .checked_sub(1)
1061 .ok_or_else(|| "decode_pending: empty sequence".to_string())?;
1062 let tok = seq.tokens[pos];
1063 let hidden = Self::try_forward_token_impl_paged(
1064 &self.weights,
1065 &*self.tensor_backend,
1066 tok,
1067 pos,
1068 seq,
1069 seq_id,
1070 self.kv_manager.as_ref(),
1071 )?;
1072 Ok(Self::compute_logits_impl(
1073 &self.weights,
1074 &*self.tensor_backend,
1075 &hidden,
1076 ))
1077 }
1078
1079 pub fn forward_token_impl(
1080 weights: &TransformerWeights,
1081 backend: &dyn TensorBackend,
1082 token_id: u32,
1083 pos: usize,
1084 seq_state: &mut SequenceState,
1085 ) -> Vec<f32> {
1086 Self::forward_token_impl_paged(weights, backend, token_id, pos, seq_state, 0, None)
1087 }
1088
1089 /// Fresh physical blocks `appends` consecutive appends on `seq_id` would
1090 /// allocate. The rule lives in one place, `AienKvManager::
1091 /// blocks_needed_for_appends`; this only forwards to it.
1092 fn kv_blocks_needed_for_appends(kv: &AienKvManager, seq_id: u64, appends: usize) -> usize {
1093 kv.blocks_needed_for_appends(seq_id, appends)
1094 }
1095
1096 /// `Some((needed, available))` when `appends` appends to `seq_id` need more
1097 /// new blocks than the pool has free, `None` when they fit. Read-only.
1098 fn kv_pool_shortfall(
1099 kv: &AienKvManager,
1100 seq_id: u64,
1101 appends: usize,
1102 ) -> Option<(usize, usize)> {
1103 let needed = Self::kv_blocks_needed_for_appends(kv, seq_id, appends);
1104 let available = kv.available_blocks();
1105 (needed > available).then_some((needed, available))
1106 }
1107
1108 /// Message for a capacity failure; always starts with `KV_POOL_EXHAUSTED_PREFIX`.
1109 fn kv_pool_exhausted_error(what: &str, seq_id: u64, needed: usize, available: usize) -> String {
1110 format!(
1111 "{KV_POOL_EXHAUSTED_PREFIX} {what} for sequence {seq_id} needs {needed} new KV blocks \
1112 but only {available} are free; the block table, the pool and the sequence state are unchanged"
1113 )
1114 }
1115
1116 /// Element type every new sequence's K/V are rounded to the moment they are
1117 /// produced: the attached pool's dtype (what `write_token_kv` stores), else
1118 /// `kv_dtype`. One rounding point keeps dense cache, pool and attention on the
1119 /// same bits (PREFILL-E2E-2).
1120 pub fn storage_dtype(&self) -> KvDType {
1121 self.kv_manager
1122 .as_ref()
1123 .and_then(|m| m.read().tensor_pool().map(|p| p.config().dtype))
1124 .unwrap_or(self.kv_dtype)
1125 }
1126
1127 /// Forward pass executing one token forward pass through the transformer with optional paged COW KV.
1128 ///
1129 /// Panics when the paged KV pool cannot supply the block this token needs
1130 /// (see `try_forward_token_impl_paged`, which returns the error instead).
1131 pub fn forward_token_impl_paged(
1132 weights: &TransformerWeights,
1133 backend: &dyn TensorBackend,
1134 token_id: u32,
1135 pos: usize,
1136 seq_state: &mut SequenceState,
1137 seq_id: u64,
1138 kv_manager: Option<&SharedKvManager>,
1139 ) -> Vec<f32> {
1140 Self::try_forward_token_impl_paged(
1141 weights, backend, token_id, pos, seq_state, seq_id, kv_manager,
1142 )
1143 .unwrap_or_else(|e| panic!("forward_token_impl_paged: {e}"))
1144 }
1145
1146 /// Same as `forward_token_impl_paged`, but returns a loud `Err` (message
1147 /// starting with `KV_POOL_EXHAUSTED_PREFIX`) when the paged KV pool has no
1148 /// block for this token, instead of continuing with no stored K/V
1149 /// (PREFILL-I25). The capacity check runs before anything is mutated, so a
1150 /// failed call leaves the block table, the pool and `seq_state` unchanged.
1151 /// A sequence with no block table in the manager still takes the dense
1152 /// per-layer cache path, as before.
1153 pub fn try_forward_token_impl_paged(
1154 weights: &TransformerWeights,
1155 backend: &dyn TensorBackend,
1156 token_id: u32,
1157 pos: usize,
1158 seq_state: &mut SequenceState,
1159 seq_id: u64,
1160 kv_manager: Option<&SharedKvManager>,
1161 ) -> Result<Vec<f32>, String> {
1162 let hidden_dim = weights.config.hidden_dim();
1163 // Checked once per forward: zero heads, non-divisible heads or an overflowing width
1164 // are refused here instead of becoming a wrong slice later.
1165 let geom = weights
1166 .config
1167 .attention_geometry()
1168 .map_err(|e| e.to_string())?;
1169 backend.check_model(&weights.config)?;
1170 let num_heads = geom.num_q_heads();
1171 let num_kv_heads = geom.num_kv_heads();
1172 let head_dim = geom.head_dim();
1173 let q_dim = geom.q_dim();
1174 let kv_dim = geom.kv_dim();
1175 let intermediate_dim = weights.config.intermediate_dim();
1176 let eps = weights.config.rms_norm_eps;
1177 let rope = weights.config.rope();
1178
1179 let token_idx = (token_id as usize) % weights.config.vocab_size();
1180 let mut x =
1181 weights.embed_tokens[token_idx * hidden_dim..(token_idx + 1) * hidden_dim].to_vec();
1182
1183 let mut x_norm = vec![0.0f32; hidden_dim];
1184 let mut q = vec![0.0f32; q_dim];
1185 let mut k = vec![0.0f32; kv_dim];
1186 let mut v = vec![0.0f32; kv_dim];
1187 let qkv_dim = q_dim + 2 * kv_dim;
1188 let mut qkv = vec![0.0f32; qkv_dim];
1189 let mut attn_out = vec![0.0f32; q_dim];
1190 let mut attn_proj = vec![0.0f32; hidden_dim];
1191 let mut post_norm = vec![0.0f32; hidden_dim];
1192 let mut gate = vec![0.0f32; intermediate_dim];
1193 let mut up = vec![0.0f32; intermediate_dim];
1194 let mut activated = vec![0.0f32; intermediate_dim];
1195 let mut gate_up = vec![0.0f32; 2 * intermediate_dim];
1196 let mut mlp_out = vec![0.0f32; hidden_dim];
1197
1198 // Reserve this token's slot. A full pool is a loud error (checked before
1199 // anything is mutated), never a silent fall back to "no stored K/V".
1200 // A sequence with no block table in the manager keeps the dense
1201 // per-layer cache path, as before.
1202 let block_slot = match kv_manager {
1203 Some(mgr) => {
1204 let mut w = mgr.write();
1205 if w.get_block_table(seq_id).is_some() {
1206 if let Some((needed, available)) = Self::kv_pool_shortfall(&w, seq_id, 1) {
1207 return Err(Self::kv_pool_exhausted_error(
1208 &format!("decode step at position {pos}"),
1209 seq_id,
1210 needed,
1211 available,
1212 ));
1213 }
1214 let slot = w.append_token_with_slot(seq_id).map_err(|e| {
1215 format!(
1216 "{KV_POOL_EXHAUSTED_PREFIX} append of position {pos} for sequence \
1217 {seq_id} failed after the capacity check: {e}"
1218 )
1219 })?;
1220 Some(slot)
1221 } else {
1222 None
1223 }
1224 }
1225 None => None,
1226 };
1227
1228 for (layer_idx, layer_w) in weights.layers.iter().enumerate() {
1229 backend.rmsnorm(&mut x_norm, &x, &layer_w.input_layernorm, eps);
1230 if let Some(w) = layer_w.qkv_proj.as_ref() {
1231 backend.matmul_vec_w(&mut qkv, &x_norm, w.as_ref(), qkv_dim, hidden_dim);
1232 q.copy_from_slice(&qkv[..q_dim]);
1233 k.copy_from_slice(&qkv[q_dim..q_dim + kv_dim]);
1234 v.copy_from_slice(&qkv[q_dim + kv_dim..]);
1235 } else {
1236 backend.matmul_vec_w(&mut q, &x_norm, layer_w.q_proj.as_ref(), q_dim, hidden_dim);
1237 backend.matmul_vec_w(&mut k, &x_norm, layer_w.k_proj.as_ref(), kv_dim, hidden_dim);
1238 backend.matmul_vec_w(&mut v, &x_norm, layer_w.v_proj.as_ref(), kv_dim, hidden_dim);
1239 }
1240
1241 layer_w.apply_qk_norm_on(backend, &mut q, &mut k, head_dim, eps);
1242 backend.apply_rope(
1243 &mut q,
1244 &mut k,
1245 pos,
1246 head_dim,
1247 num_heads,
1248 num_kv_heads,
1249 &rope,
1250 );
1251 // Round once, at birth: pool write, dense cache and attention all see
1252 // the same bits (PREFILL-E2E-2).
1253 round_to_dtype_in_place(seq_state.kv_dtype, &mut k);
1254 round_to_dtype_in_place(seq_state.kv_dtype, &mut v);
1255
1256 if let (Some((block_id, slot)), Some(mgr)) = (block_slot, kv_manager) {
1257 {
1258 let mut w = mgr.write();
1259 // A manager with no physical pool has nowhere to store K/V;
1260 // that case is skipped, as before. With a pool the write
1261 // cannot fail silently any more.
1262 if w.tensor_pool().is_some() {
1263 w.write_explicit_token_kv(block_id, layer_idx, slot, &k, &v)
1264 .map_err(|e| {
1265 format!(
1266 "KV write failed for sequence {seq_id} layer {layer_idx} \
1267 position {pos}: {e}"
1268 )
1269 })?;
1270 }
1271 }
1272
1273 let mgr_read = mgr.read();
1274 if let (Some(pool), Some(table)) =
1275 (mgr_read.tensor_pool(), mgr_read.get_block_table(seq_id))
1276 {
1277 let total_tokens = table.total_tokens;
1278 backend.paged_attention(
1279 &mut attn_out,
1280 &q,
1281 pool,
1282 &table.block_ids,
1283 total_tokens,
1284 layer_idx,
1285 num_heads,
1286 num_kv_heads,
1287 head_dim,
1288 );
1289 }
1290 } else {
1291 let kv_cache = &mut seq_state.layers[layer_idx];
1292 kv_cache.cached_k.push(k.clone());
1293 kv_cache.cached_v.push(v.clone());
1294 kv_cache.flat_k.extend_from_slice(&k);
1295 kv_cache.flat_v.extend_from_slice(&v);
1296
1297 let seq_len = kv_cache.cached_k.len();
1298 backend.gqa_attention(
1299 &mut attn_out,
1300 &q,
1301 &kv_cache.flat_k,
1302 &kv_cache.flat_v,
1303 seq_len,
1304 num_heads,
1305 num_kv_heads,
1306 head_dim,
1307 );
1308 }
1309
1310 backend.matmul_vec_w(
1311 &mut attn_proj,
1312 &attn_out,
1313 layer_w.o_proj.as_ref(),
1314 hidden_dim,
1315 q_dim,
1316 );
1317 for i in 0..hidden_dim {
1318 x[i] += attn_proj[i];
1319 }
1320
1321 backend.rmsnorm(&mut post_norm, &x, &layer_w.post_attention_layernorm, eps);
1322 if let Some(w) = layer_w.gate_up_proj.as_ref() {
1323 backend.matmul_vec_w(
1324 &mut gate_up,
1325 &post_norm,
1326 w.as_ref(),
1327 2 * intermediate_dim,
1328 hidden_dim,
1329 );
1330 backend.swiglu(
1331 &mut activated,
1332 &gate_up[..intermediate_dim],
1333 &gate_up[intermediate_dim..],
1334 );
1335 } else {
1336 backend.matmul_vec_w(
1337 &mut gate,
1338 &post_norm,
1339 layer_w.gate_proj.as_ref(),
1340 intermediate_dim,
1341 hidden_dim,
1342 );
1343 backend.matmul_vec_w(
1344 &mut up,
1345 &post_norm,
1346 layer_w.up_proj.as_ref(),
1347 intermediate_dim,
1348 hidden_dim,
1349 );
1350 backend.swiglu(&mut activated, &gate, &up);
1351 }
1352 backend.matmul_vec_w(
1353 &mut mlp_out,
1354 &activated,
1355 layer_w.down_proj.as_ref(),
1356 hidden_dim,
1357 intermediate_dim,
1358 );
1359
1360 for i in 0..hidden_dim {
1361 x[i] += mlp_out[i];
1362 }
1363 }
1364
1365 let mut x_final = vec![0.0f32; hidden_dim];
1366 backend.rmsnorm(&mut x_final, &x, &weights.final_norm, eps);
1367 Ok(x_final)
1368 }
1369
1370 pub fn compute_logits_impl(
1371 weights: &TransformerWeights,
1372 backend: &dyn TensorBackend,
1373 hidden_state: &[f32],
1374 ) -> Vec<f32> {
1375 let vocab_size = weights.config.vocab_size();
1376 let hidden_dim = weights.config.hidden_dim();
1377 let mut logits = vec![0.0f32; vocab_size];
1378 backend.compute_logits_w(
1379 &mut logits,
1380 hidden_state,
1381 weights.output_matrix(),
1382 vocab_size,
1383 hidden_dim,
1384 );
1385 logits
1386 }
1387
1388 /// Prefill all prompt tokens layer-by-layer rather than token-by-token.
1389 pub fn prefill_prompt_layer_by_layer(
1390 weights: &TransformerWeights,
1391 backend: &dyn TensorBackend,
1392 prompt_tokens: &[u32],
1393 seq_state: &mut SequenceState,
1394 ) -> Vec<f32> {
1395 Self::prefill_prompt_layer_by_layer_paged(
1396 weights,
1397 backend,
1398 prompt_tokens,
1399 seq_state,
1400 0,
1401 None,
1402 )
1403 .unwrap_or_else(|e| panic!("prefill without a KV manager cannot hit the KV pool: {e}"))
1404 }
1405
1406 /// Prefill all prompt tokens layer-by-layer with optional paged COW KV registration.
1407 ///
1408 /// In paged mode, positions beyond the block table's allocated length are
1409 /// appended to the table. If the pool cannot supply the blocks those
1410 /// appends need, the call fails with an `Err` starting with
1411 /// `KV_POOL_EXHAUSTED_PREFIX` BEFORE anything is mutated: the block table,
1412 /// the free-block count and `seq_state` stay exactly as they were, so the
1413 /// same call can be retried once blocks are freed (PREFILL-I25).
1414 pub fn prefill_prompt_layer_by_layer_paged(
1415 weights: &TransformerWeights,
1416 backend: &dyn TensorBackend,
1417 prompt_tokens: &[u32],
1418 seq_state: &mut SequenceState,
1419 seq_id: u64,
1420 kv_manager: Option<&SharedKvManager>,
1421 ) -> Result<Vec<f32>, String> {
1422 let n = prompt_tokens.len();
1423 if n == 0 {
1424 return Ok(Vec::new());
1425 }
1426 // Tokens already in this sequence (earlier prefill chunks). This chunk's
1427 // token t sits at absolute position `offset + t`: that position drives RoPE,
1428 // the paged block/slot, and the causal attention length.
1429 let offset = seq_state.tokens.len();
1430 let kv_dtype = seq_state.kv_dtype;
1431 if n == 1 && offset == 0 {
1432 // The token is recorded only after the forward pass succeeded, so a
1433 // loud KV failure leaves `seq_state` untouched.
1434 let hidden = Self::try_forward_token_impl_paged(
1435 weights,
1436 backend,
1437 prompt_tokens[0],
1438 0,
1439 seq_state,
1440 seq_id,
1441 kv_manager,
1442 )?;
1443 seq_state.tokens.push(prompt_tokens[0]);
1444 return Ok(hidden);
1445 }
1446
1447 let hidden_dim = weights.config.hidden_dim();
1448 // Checked once per forward: zero heads, non-divisible heads or an overflowing width
1449 // are refused here instead of becoming a wrong slice later.
1450 let geom = weights
1451 .config
1452 .attention_geometry()
1453 .map_err(|e| e.to_string())?;
1454 backend.check_model(&weights.config)?;
1455 let num_heads = geom.num_q_heads();
1456 let num_kv_heads = geom.num_kv_heads();
1457 let head_dim = geom.head_dim();
1458 let q_dim = geom.q_dim();
1459 let kv_dim = geom.kv_dim();
1460 let intermediate_dim = weights.config.intermediate_dim();
1461 let eps = weights.config.rms_norm_eps;
1462 let rope = weights.config.rope();
1463
1464 // Paged mode: one physical (block, slot) per absolute position, resolved once
1465 // (not per layer). Positions inside the table's allocated length (the
1466 // scheduler allocates the whole prompt up front) use the existing blocks;
1467 // positions beyond it are appended to the table. Resolved first, before
1468 // `seq_state` is touched, so a pool that cannot hold the appends fails the
1469 // whole call cleanly (PREFILL-I25).
1470 let num_layers = weights.config.num_layers;
1471 let mut paged_slots: Vec<Option<(usize, usize)>> = vec![None; n];
1472 if let Some(mgr) = kv_manager {
1473 let mut w = mgr.write();
1474 if w.tensor_pool().is_some() {
1475 let block_size = w.block_size();
1476 if let Some(tbl) = w.get_block_table(seq_id).cloned() {
1477 let covered =
1478 |p: usize| p < tbl.total_tokens && p / block_size < tbl.block_ids.len();
1479 let appends = (0..n).filter(|&t| !covered(offset + t)).count();
1480 if let Some((needed, available)) = Self::kv_pool_shortfall(&w, seq_id, appends)
1481 {
1482 return Err(Self::kv_pool_exhausted_error(
1483 &format!("prefill of {n} tokens at position {offset}"),
1484 seq_id,
1485 needed,
1486 available,
1487 ));
1488 }
1489 for (t, slot_out) in paged_slots.iter_mut().enumerate() {
1490 let p = offset + t;
1491 *slot_out = if covered(p) {
1492 Some((tbl.block_ids[p / block_size], p % block_size))
1493 } else {
1494 let slot = w.append_token_with_slot(seq_id).map_err(|e| {
1495 format!(
1496 "{KV_POOL_EXHAUSTED_PREFIX} append of position {p} for \
1497 sequence {seq_id} failed after the capacity check: {e}"
1498 )
1499 })?;
1500 Some(slot)
1501 };
1502 }
1503 }
1504 }
1505 }
1506
1507 seq_state.tokens.extend_from_slice(prompt_tokens);
1508
1509 let mut states: Vec<Vec<f32>> = prompt_tokens
1510 .iter()
1511 .map(|&tok| {
1512 let token_idx = (tok as usize) % weights.config.vocab_size();
1513 let slice =
1514 &weights.embed_tokens[token_idx * hidden_dim..(token_idx + 1) * hidden_dim];
1515 slice.to_vec()
1516 })
1517 .collect();
1518
1519 let mut x_norm_batch = vec![0.0f32; n * hidden_dim];
1520 let mut q_batch = vec![0.0f32; n * q_dim];
1521 let mut k_batch = vec![0.0f32; n * kv_dim];
1522 let mut v_batch = vec![0.0f32; n * kv_dim];
1523 let qkv_dim = q_dim + 2 * kv_dim;
1524 let mut qkv_batch = vec![0.0f32; n * qkv_dim];
1525 let mut attn_out_batch = vec![0.0f32; n * q_dim];
1526 let mut attn_proj_batch = vec![0.0f32; n * hidden_dim];
1527 let mut post_norm_batch = vec![0.0f32; n * hidden_dim];
1528 let mut gate_batch = vec![0.0f32; n * intermediate_dim];
1529 let mut up_batch = vec![0.0f32; n * intermediate_dim];
1530 let mut act_batch = vec![0.0f32; n * intermediate_dim];
1531 let mut gate_up_batch = vec![0.0f32; n * 2 * intermediate_dim];
1532 let mut mlp_out_batch = vec![0.0f32; n * hidden_dim];
1533
1534 // The dense per-layer cache must hold K/V for positions 0..offset before this
1535 // chunk's attention runs. Paged mode clears it after each prefill, so rebuild
1536 // it from the physical pool.
1537 if seq_state.layers.len() != num_layers {
1538 seq_state.layers = vec![LayerKvCache::default(); num_layers];
1539 if offset > 0 {
1540 if let Some(mgr) = kv_manager {
1541 let r = mgr.read();
1542 if let (Some(pool), Some(tbl)) = (r.tensor_pool(), r.get_block_table(seq_id)) {
1543 for (layer_idx, cache) in seq_state.layers.iter_mut().enumerate() {
1544 let (k, v) = pool.gather_layer_kv(&tbl.block_ids, offset, layer_idx);
1545 for (k_t, v_t) in k.chunks(kv_dim).zip(v.chunks(kv_dim)) {
1546 cache.cached_k.push(k_t.to_vec());
1547 cache.cached_v.push(v_t.to_vec());
1548 }
1549 cache.flat_k = k;
1550 cache.flat_v = v;
1551 }
1552 }
1553 }
1554 }
1555 }
1556
1557 // Contiguous copy of the residual rows for the row-batched norms (one launch per
1558 // chunk and layer instead of one per token).
1559 let mut x_flat = vec![0.0f32; n * hidden_dim];
1560 let flatten = |x_flat: &mut [f32], states: &[Vec<f32>]| {
1561 for (t, s) in states.iter().enumerate() {
1562 x_flat[t * hidden_dim..(t + 1) * hidden_dim].copy_from_slice(s);
1563 }
1564 };
1565
1566 for (layer_idx, layer_w) in weights.layers.iter().enumerate() {
1567 let kv_cache = &mut seq_state.layers[layer_idx];
1568
1569 flatten(&mut x_flat, &states);
1570 backend.rmsnorm_rows(&mut x_norm_batch, &x_flat, &layer_w.input_layernorm, n, eps);
1571
1572 if let Some(w) = layer_w.qkv_proj.as_ref() {
1573 backend.matmul_batch_w(
1574 &mut qkv_batch,
1575 &x_norm_batch,
1576 w.as_ref(),
1577 n,
1578 hidden_dim,
1579 qkv_dim,
1580 );
1581 for t in 0..n {
1582 let row = &qkv_batch[t * qkv_dim..(t + 1) * qkv_dim];
1583 q_batch[t * q_dim..(t + 1) * q_dim].copy_from_slice(&row[..q_dim]);
1584 k_batch[t * kv_dim..(t + 1) * kv_dim]
1585 .copy_from_slice(&row[q_dim..q_dim + kv_dim]);
1586 v_batch[t * kv_dim..(t + 1) * kv_dim].copy_from_slice(&row[q_dim + kv_dim..]);
1587 }
1588 } else {
1589 backend.matmul_batch_w(
1590 &mut q_batch,
1591 &x_norm_batch,
1592 layer_w.q_proj.as_ref(),
1593 n,
1594 hidden_dim,
1595 q_dim,
1596 );
1597 backend.matmul_batch_w(
1598 &mut k_batch,
1599 &x_norm_batch,
1600 layer_w.k_proj.as_ref(),
1601 n,
1602 hidden_dim,
1603 kv_dim,
1604 );
1605 backend.matmul_batch_w(
1606 &mut v_batch,
1607 &x_norm_batch,
1608 layer_w.v_proj.as_ref(),
1609 n,
1610 hidden_dim,
1611 kv_dim,
1612 );
1613 }
1614
1615 // q/k norm is per head with one weight, so the whole chunk is one `heads` run
1616 // per tensor (n * num_heads rows for q, n * num_kv_heads for k).
1617 layer_w.apply_qk_norm_on(backend, &mut q_batch, &mut k_batch, head_dim, eps);
1618
1619 for t in 0..n {
1620 let q_t = &mut q_batch[t * q_dim..(t + 1) * q_dim];
1621 let k_t = &mut k_batch[t * kv_dim..(t + 1) * kv_dim];
1622 let v_t = &mut v_batch[t * kv_dim..(t + 1) * kv_dim];
1623
1624 let pos = offset + t;
1625 backend.apply_rope(q_t, k_t, pos, head_dim, num_heads, num_kv_heads, &rope);
1626 // Round once, at birth, so this chunk's in-flight K/V and the earlier
1627 // chunks gathered back from the pool carry the same bits (PREFILL-E2E-2).
1628 round_to_dtype_in_place(kv_dtype, k_t);
1629 round_to_dtype_in_place(kv_dtype, v_t);
1630
1631 if let (Some((block_id, slot)), Some(mgr)) = (paged_slots[t], kv_manager) {
1632 // Slots exist only when a physical pool is attached, so this
1633 // write has nowhere to fail silently; any error is loud.
1634 mgr.write()
1635 .write_explicit_token_kv(block_id, layer_idx, slot, k_t, v_t)
1636 .map_err(|e| {
1637 format!(
1638 "KV write failed for sequence {seq_id} layer {layer_idx} \
1639 position {pos}: {e}"
1640 )
1641 })?;
1642 }
1643
1644 kv_cache.cached_k.push(k_t.to_vec());
1645 kv_cache.cached_v.push(v_t.to_vec());
1646 kv_cache.flat_k.extend_from_slice(k_t);
1647 kv_cache.flat_v.extend_from_slice(v_t);
1648 }
1649 // The chunk's attention in one call: the cache now holds offset + n tokens and row
1650 // t attends over the first offset + t + 1 of them (omega stages the KV once and
1651 // sends the rows in a few launches, omega#406, instead of one launch per token).
1652 backend.gqa_attention_rows(
1653 &mut attn_out_batch,
1654 &q_batch,
1655 &kv_cache.flat_k,
1656 &kv_cache.flat_v,
1657 offset,
1658 n,
1659 num_heads,
1660 num_kv_heads,
1661 head_dim,
1662 );
1663
1664 backend.matmul_batch_w(
1665 &mut attn_proj_batch,
1666 &attn_out_batch,
1667 layer_w.o_proj.as_ref(),
1668 n,
1669 q_dim,
1670 hidden_dim,
1671 );
1672 for t in 0..n {
1673 let proj_t = &attn_proj_batch[t * hidden_dim..(t + 1) * hidden_dim];
1674 for i in 0..hidden_dim {
1675 states[t][i] += proj_t[i];
1676 }
1677 }
1678
1679 flatten(&mut x_flat, &states);
1680 backend.rmsnorm_rows(
1681 &mut post_norm_batch,
1682 &x_flat,
1683 &layer_w.post_attention_layernorm,
1684 n,
1685 eps,
1686 );
1687
1688 if let Some(w) = layer_w.gate_up_proj.as_ref() {
1689 let gu = 2 * intermediate_dim;
1690 backend.matmul_batch_w(
1691 &mut gate_up_batch,
1692 &post_norm_batch,
1693 w.as_ref(),
1694 n,
1695 hidden_dim,
1696 gu,
1697 );
1698 // Un-interleave the fused rows into the gate and up planes so the whole
1699 // chunk is one elementwise launch.
1700 for t in 0..n {
1701 let row = &gate_up_batch[t * gu..(t + 1) * gu];
1702 gate_batch[t * intermediate_dim..(t + 1) * intermediate_dim]
1703 .copy_from_slice(&row[..intermediate_dim]);
1704 up_batch[t * intermediate_dim..(t + 1) * intermediate_dim]
1705 .copy_from_slice(&row[intermediate_dim..]);
1706 }
1707 backend.swiglu(&mut act_batch, &gate_batch, &up_batch);
1708 } else {
1709 backend.matmul_batch_w(
1710 &mut gate_batch,
1711 &post_norm_batch,
1712 layer_w.gate_proj.as_ref(),
1713 n,
1714 hidden_dim,
1715 intermediate_dim,
1716 );
1717 backend.matmul_batch_w(
1718 &mut up_batch,
1719 &post_norm_batch,
1720 layer_w.up_proj.as_ref(),
1721 n,
1722 hidden_dim,
1723 intermediate_dim,
1724 );
1725 backend.swiglu(&mut act_batch, &gate_batch, &up_batch);
1726 }
1727
1728 backend.matmul_batch_w(
1729 &mut mlp_out_batch,
1730 &act_batch,
1731 layer_w.down_proj.as_ref(),
1732 n,
1733 intermediate_dim,
1734 hidden_dim,
1735 );
1736 for t in 0..n {
1737 let mlp_t = &mlp_out_batch[t * hidden_dim..(t + 1) * hidden_dim];
1738 for i in 0..hidden_dim {
1739 states[t][i] += mlp_t[i];
1740 }
1741 }
1742 }
1743
1744 // Drop the dense copy only when the physical pool holds the K/V (it is rebuilt
1745 // from the pool if a later chunk continues this sequence).
1746 if kv_manager.is_some_and(|m| m.read().tensor_pool().is_some()) {
1747 seq_state.layers.clear();
1748 }
1749
1750 let last_x = &states[n - 1];
1751 let mut x_final = vec![0.0f32; hidden_dim];
1752 backend.rmsnorm(&mut x_final, last_x, &weights.final_norm, eps);
1753 Ok(x_final)
1754 }
1755
1756 /// Single-token forward pass executing through the configured TensorBackend trait.
1757 pub fn forward_token(
1758 &self,
1759 token_id: u32,
1760 pos: usize,
1761 seq_state: &mut SequenceState,
1762 ) -> Vec<f32> {
1763 Self::forward_token_impl(
1764 &self.weights,
1765 &*self.tensor_backend,
1766 token_id,
1767 pos,
1768 seq_state,
1769 )
1770 }
1771
1772 /// Computes logits projection executing through the configured TensorBackend trait.
1773 pub fn compute_logits(&self, hidden_state: &[f32]) -> Vec<f32> {
1774 Self::compute_logits_impl(&self.weights, &*self.tensor_backend, hidden_state)
1775 }
1776
1777 /// Forward pass executing one token decode step across a batch of D sequences concurrently.
1778 /// Employs batched GEMM (M=D) for all linear projections and batched paged attention.
1779 ///
1780 /// Every id must already have backend state (from a prefill or from
1781 /// `fork_sequence`). An unknown id, or one with no tokens, is an error and
1782 /// nothing is computed: decoding it would start from token 1 at position 0
1783 /// over an empty cache (PREFILL-E2E C4).
1784 pub fn forward_decode_batch(
1785 &mut self,
1786 decode_req_ids: &[u64],
1787 ) -> Result<Vec<DecodeOutput>, String> {
1788 self.forward_decode_batch_impl(decode_req_ids)
1789 .map(|(outputs, _logits, _vocab)| outputs)
1790 }
1791
1792 /// Same as `forward_decode_batch`, also returning each sequence's logits
1793 /// (in `decode_req_ids` order, minus any sequence ended as Preempted for
1794 /// lack of a KV slot, which gets no logits) for parity checks.
1795 pub fn forward_decode_batch_with_logits(
1796 &mut self,
1797 decode_req_ids: &[u64],
1798 ) -> Result<(Vec<DecodeOutput>, Vec<Vec<f32>>), String> {
1799 let (outputs, logits_batch, vocab_size) = self.forward_decode_batch_impl(decode_req_ids)?;
1800 let logits = if vocab_size == 0 {
1801 Vec::new()
1802 } else {
1803 logits_batch
1804 .chunks(vocab_size)
1805 .map(|row| row.to_vec())
1806 .collect()
1807 };
1808 Ok((outputs, logits))
1809 }
1810
1811 fn forward_decode_batch_impl(
1812 &mut self,
1813 decode_req_ids: &[u64],
1814 ) -> Result<(Vec<DecodeOutput>, Vec<f32>, usize), String> {
1815 if decode_req_ids.is_empty() {
1816 return Ok((Vec::new(), Vec::new(), 0));
1817 }
1818
1819 let hidden_dim = self.weights.config.hidden_dim();
1820 // Checked once per forward: zero heads, non-divisible heads or an overflowing width
1821 // are refused here instead of becoming a wrong slice later.
1822 let geom = self
1823 .weights
1824 .config
1825 .attention_geometry()
1826 .map_err(|e| e.to_string())?;
1827 self.tensor_backend.check_model(&self.weights.config)?;
1828 let num_heads = geom.num_q_heads();
1829 let num_kv_heads = geom.num_kv_heads();
1830 let head_dim = geom.head_dim();
1831 let q_dim = geom.q_dim();
1832 let kv_dim = geom.kv_dim();
1833 let intermediate_dim = self.weights.config.intermediate_dim();
1834 let eps = self.weights.config.rms_norm_eps;
1835 let rope = self.weights.config.rope();
1836 let vocab_size = self.weights.config.vocab_size();
1837
1838 // 1. Gather active sequence requests and their current positions / last tokens
1839 // Validated before anything is written, so a refused batch leaves no state behind.
1840 let mut valid_reqs = Vec::with_capacity(decode_req_ids.len());
1841 for &req_id in decode_req_ids {
1842 self.commit_pending_prefill_token(req_id);
1843 let seq = self.sequences.get(&req_id).ok_or_else(|| {
1844 format!(
1845 "decode refused: request {} has no backend sequence state \
1846 (never prefilled and never forked via fork_sequence)",
1847 req_id
1848 )
1849 })?;
1850 let last_token = *seq.tokens.last().ok_or_else(|| {
1851 format!(
1852 "decode refused: request {} has no tokens (no prefilled prompt)",
1853 req_id
1854 )
1855 })?;
1856 let pos = seq.tokens.len() - 1;
1857 valid_reqs.push((req_id, last_token, pos));
1858 }
1859
1860 // 1b. Reserve append slots in KV cache for this decode step. A sequence
1861 // whose slot cannot be reserved (pool exhausted) has nowhere to put this
1862 // step's K/V, so it is not computed and gets no token: it is ended as
1863 // Preempted and the scheduler frees its KV. Before the backend owned
1864 // decode K/V, the scheduler's append check did the same
1865 // (aien-scheduler/src/lib.rs, `!backend.manages_kv_cache()` branch).
1866 let mut slot_failures: Vec<DecodeOutput> = Vec::new();
1867 let block_slots: Vec<Option<(usize, usize)>> = if let Some(mgr) = &self.kv_manager {
1868 let mut write_mgr = mgr.write();
1869 let mut kept_reqs = Vec::with_capacity(valid_reqs.len());
1870 let mut kept_slots = Vec::with_capacity(valid_reqs.len());
1871 for req in valid_reqs.drain(..) {
1872 match write_mgr.append_token_with_slot(req.0) {
1873 Ok(slot) => {
1874 kept_reqs.push(req);
1875 kept_slots.push(Some(slot));
1876 }
1877 Err(_) => {
1878 let total_tokens = self.sequences.get(&req.0).map_or(0, |s| s.tokens.len());
1879 slot_failures.push(DecodeOutput::Finished {
1880 request_id: req.0,
1881 reason: FinishReason::Preempted,
1882 total_tokens,
1883 });
1884 }
1885 }
1886 }
1887 valid_reqs = kept_reqs;
1888 kept_slots
1889 } else {
1890 vec![None; valid_reqs.len()]
1891 };
1892
1893 let d = valid_reqs.len();
1894 if d == 0 {
1895 return Ok((slot_failures, Vec::new(), 0));
1896 }
1897
1898 // 2. Allocate batch activations
1899 let mut x = vec![0.0f32; d * hidden_dim];
1900 let mut x_norm = vec![0.0f32; d * hidden_dim];
1901 let mut q_batch = vec![0.0f32; d * q_dim];
1902 let mut k_batch = vec![0.0f32; d * kv_dim];
1903 let mut v_batch = vec![0.0f32; d * kv_dim];
1904 let qkv_dim = q_dim + 2 * kv_dim;
1905 let mut qkv_batch = vec![0.0f32; d * qkv_dim];
1906 let mut attn_out_batch = vec![0.0f32; d * q_dim];
1907 let mut attn_proj_batch = vec![0.0f32; d * hidden_dim];
1908 let mut post_norm_batch = vec![0.0f32; d * hidden_dim];
1909 let mut gate_batch = vec![0.0f32; d * intermediate_dim];
1910 let mut up_batch = vec![0.0f32; d * intermediate_dim];
1911 let mut act_batch = vec![0.0f32; d * intermediate_dim];
1912 let mut gate_up_batch = vec![0.0f32; d * 2 * intermediate_dim];
1913 let mut mlp_out_batch = vec![0.0f32; d * hidden_dim];
1914 let mut logits_batch = vec![0.0f32; d * vocab_size];
1915
1916 // 3. Populate initial embeddings
1917 for (i, &(_seq_id, last_token, _pos)) in valid_reqs.iter().enumerate() {
1918 self.weights
1919 .embed_token(last_token, &mut x[i * hidden_dim..(i + 1) * hidden_dim]);
1920 }
1921
1922 // 4. (Decode slots were reserved in step 1b.)
1923
1924 // 5. Transformer layer loop
1925 for (layer_idx, layer_w) in self.weights.layers.iter().enumerate() {
1926 // a. Pre-attention RMSNorm
1927 for i in 0..d {
1928 self.tensor_backend.rmsnorm(
1929 &mut x_norm[i * hidden_dim..(i + 1) * hidden_dim],
1930 &x[i * hidden_dim..(i + 1) * hidden_dim],
1931 &layer_w.input_layernorm,
1932 eps,
1933 );
1934 }
1935
1936 // b. Batched Q, K, V projections (M = D)
1937 if let Some(w) = layer_w.qkv_proj.as_ref() {
1938 self.tensor_backend.matmul_batch_w(
1939 &mut qkv_batch,
1940 &x_norm,
1941 w.as_ref(),
1942 d,
1943 hidden_dim,
1944 qkv_dim,
1945 );
1946 for t in 0..d {
1947 let row = &qkv_batch[t * qkv_dim..(t + 1) * qkv_dim];
1948 q_batch[t * q_dim..(t + 1) * q_dim].copy_from_slice(&row[..q_dim]);
1949 k_batch[t * kv_dim..(t + 1) * kv_dim]
1950 .copy_from_slice(&row[q_dim..q_dim + kv_dim]);
1951 v_batch[t * kv_dim..(t + 1) * kv_dim].copy_from_slice(&row[q_dim + kv_dim..]);
1952 }
1953 } else {
1954 self.tensor_backend.matmul_batch_w(
1955 &mut q_batch,
1956 &x_norm,
1957 layer_w.q_proj.as_ref(),
1958 d,
1959 hidden_dim,
1960 q_dim,
1961 );
1962 self.tensor_backend.matmul_batch_w(
1963 &mut k_batch,
1964 &x_norm,
1965 layer_w.k_proj.as_ref(),
1966 d,
1967 hidden_dim,
1968 kv_dim,
1969 );
1970 self.tensor_backend.matmul_batch_w(
1971 &mut v_batch,
1972 &x_norm,
1973 layer_w.v_proj.as_ref(),
1974 d,
1975 hidden_dim,
1976 kv_dim,
1977 );
1978 }
1979
1980 // c. RoPE across all D sequences at their respective positions, then
1981 // round K/V once at birth (PREFILL-E2E-2).
1982 for (i, &(seq_id, _tok, pos)) in valid_reqs.iter().enumerate() {
1983 let kv_dtype = self
1984 .sequences
1985 .get(&seq_id)
1986 .map(|s| s.kv_dtype)
1987 .unwrap_or_else(|| self.storage_dtype());
1988 layer_w.apply_qk_norm_on(
1989 self.tensor_backend.as_ref(),
1990 &mut q_batch[i * q_dim..(i + 1) * q_dim],
1991 &mut k_batch[i * kv_dim..(i + 1) * kv_dim],
1992 head_dim,
1993 eps,
1994 );
1995 self.tensor_backend.apply_rope(
1996 &mut q_batch[i * q_dim..(i + 1) * q_dim],
1997 &mut k_batch[i * kv_dim..(i + 1) * kv_dim],
1998 pos,
1999 head_dim,
2000 num_heads,
2001 num_kv_heads,
2002 &rope,
2003 );
2004 round_to_dtype_in_place(kv_dtype, &mut k_batch[i * kv_dim..(i + 1) * kv_dim]);
2005 round_to_dtype_in_place(kv_dtype, &mut v_batch[i * kv_dim..(i + 1) * kv_dim]);
2006 }
2007
2008 // d. Write K & V into KV cache
2009 if let Some(mgr) = &self.kv_manager {
2010 let mut write_mgr = mgr.write();
2011 for (i, slot_opt) in block_slots.iter().enumerate() {
2012 if let Some((block_id, slot)) = *slot_opt {
2013 let k_slice = &k_batch[i * kv_dim..(i + 1) * kv_dim];
2014 let v_slice = &v_batch[i * kv_dim..(i + 1) * kv_dim];
2015 let _ = write_mgr
2016 .write_explicit_token_kv(block_id, layer_idx, slot, k_slice, v_slice);
2017 }
2018 }
2019 } else {
2020 for (i, &(seq_id, _, _)) in valid_reqs.iter().enumerate() {
2021 if let Some(seq) = self.sequences.get_mut(&seq_id) {
2022 let kv_cache = &mut seq.layers[layer_idx];
2023 let k_slice = &k_batch[i * kv_dim..(i + 1) * kv_dim];
2024 let v_slice = &v_batch[i * kv_dim..(i + 1) * kv_dim];
2025 kv_cache.cached_k.push(k_slice.to_vec());
2026 kv_cache.cached_v.push(v_slice.to_vec());
2027 kv_cache.flat_k.extend_from_slice(k_slice);
2028 kv_cache.flat_v.extend_from_slice(v_slice);
2029 }
2030 }
2031 }
2032
2033 // e. Attention execution
2034 let paged_computed = if let Some(mgr) = &self.kv_manager {
2035 let read_mgr = mgr.read();
2036 if let Some(pool) = read_mgr.tensor_pool() {
2037 let mut block_tables = Vec::with_capacity(d);
2038 let mut context_lens = Vec::with_capacity(d);
2039 let mut max_blocks = 1;
2040 for &(seq_id, _, _pos) in &valid_reqs {
2041 if let Some(table) = read_mgr.get_block_table(seq_id) {
2042 if table.block_ids.len() > max_blocks {
2043 max_blocks = table.block_ids.len();
2044 }
2045 block_tables.push(table.block_ids.clone());
2046 context_lens.push(table.total_tokens as i32);
2047 } else {
2048 block_tables.push(Vec::new());
2049 context_lens.push(0);
2050 }
2051 }
2052
2053 let mut flat_block_tables = vec![-1i32; d * max_blocks];
2054 for (i, bt) in block_tables.iter().enumerate() {
2055 for (j, &blk) in bt.iter().enumerate() {
2056 flat_block_tables[i * max_blocks + j] = blk as i32;
2057 }
2058 }
2059
2060 self.tensor_backend.paged_attention_batch(
2061 &mut attn_out_batch,
2062 &q_batch,
2063 pool,
2064 &flat_block_tables,
2065 &context_lens,
2066 max_blocks,
2067 d,
2068 layer_idx,
2069 num_heads,
2070 num_kv_heads,
2071 head_dim,
2072 );
2073 true
2074 } else {
2075 false
2076 }
2077 } else {
2078 false
2079 };
2080
2081 if !paged_computed {
2082 for (i, &(seq_id, _, _pos)) in valid_reqs.iter().enumerate() {
2083 let q_slice = &q_batch[i * q_dim..(i + 1) * q_dim];
2084 let out_slice = &mut attn_out_batch[i * q_dim..(i + 1) * q_dim];
2085 if let Some(seq) = self.sequences.get(&seq_id) {
2086 let kv_cache = &seq.layers[layer_idx];
2087 let seq_len = kv_cache.cached_k.len();
2088 self.tensor_backend.gqa_attention(
2089 out_slice,
2090 q_slice,
2091 &kv_cache.flat_k,
2092 &kv_cache.flat_v,
2093 seq_len,
2094 num_heads,
2095 num_kv_heads,
2096 head_dim,
2097 );
2098 }
2099 }
2100 }
2101
2102 // f. Attention output projection (M = D)
2103 self.tensor_backend.matmul_batch_w(
2104 &mut attn_proj_batch,
2105 &attn_out_batch,
2106 layer_w.o_proj.as_ref(),
2107 d,
2108 q_dim,
2109 hidden_dim,
2110 );
2111
2112 // g. Residual connection
2113 for idx in 0..x.len() {
2114 x[idx] += attn_proj_batch[idx];
2115 }
2116
2117 // h. Post-attention RMSNorm
2118 for i in 0..d {
2119 self.tensor_backend.rmsnorm(
2120 &mut post_norm_batch[i * hidden_dim..(i + 1) * hidden_dim],
2121 &x[i * hidden_dim..(i + 1) * hidden_dim],
2122 &layer_w.post_attention_layernorm,
2123 eps,
2124 );
2125 }
2126
2127 // i. MLP Gate & Up projections (M = D)
2128 if let Some(w) = layer_w.gate_up_proj.as_ref() {
2129 let gu = 2 * intermediate_dim;
2130 self.tensor_backend.matmul_batch_w(
2131 &mut gate_up_batch,
2132 &post_norm_batch,
2133 w.as_ref(),
2134 d,
2135 hidden_dim,
2136 gu,
2137 );
2138 // j. SwiGLU activation on the fused rows
2139 for i in 0..d {
2140 let row = &gate_up_batch[i * gu..(i + 1) * gu];
2141 self.tensor_backend.swiglu(
2142 &mut act_batch[i * intermediate_dim..(i + 1) * intermediate_dim],
2143 &row[..intermediate_dim],
2144 &row[intermediate_dim..],
2145 );
2146 }
2147 } else {
2148 self.tensor_backend.matmul_batch_w(
2149 &mut gate_batch,
2150 &post_norm_batch,
2151 layer_w.gate_proj.as_ref(),
2152 d,
2153 hidden_dim,
2154 intermediate_dim,
2155 );
2156 self.tensor_backend.matmul_batch_w(
2157 &mut up_batch,
2158 &post_norm_batch,
2159 layer_w.up_proj.as_ref(),
2160 d,
2161 hidden_dim,
2162 intermediate_dim,
2163 );
2164 // j. SwiGLU activation
2165 for i in 0..d {
2166 self.tensor_backend.swiglu(
2167 &mut act_batch[i * intermediate_dim..(i + 1) * intermediate_dim],
2168 &gate_batch[i * intermediate_dim..(i + 1) * intermediate_dim],
2169 &up_batch[i * intermediate_dim..(i + 1) * intermediate_dim],
2170 );
2171 }
2172 }
2173
2174 // k. MLP Down projection (M = D)
2175 self.tensor_backend.matmul_batch_w(
2176 &mut mlp_out_batch,
2177 &act_batch,
2178 layer_w.down_proj.as_ref(),
2179 d,
2180 intermediate_dim,
2181 hidden_dim,
2182 );
2183
2184 // l. Residual connection
2185 for idx in 0..x.len() {
2186 x[idx] += mlp_out_batch[idx];
2187 }
2188 }
2189
2190 // 6. Final RMSNorm
2191 for i in 0..d {
2192 self.tensor_backend.rmsnorm(
2193 &mut x_norm[i * hidden_dim..(i + 1) * hidden_dim],
2194 &x[i * hidden_dim..(i + 1) * hidden_dim],
2195 &self.weights.final_norm,
2196 eps,
2197 );
2198 }
2199
2200 // 7. Batched Vocabulary Logits Projection (M = D)
2201 self.tensor_backend.matmul_batch_w(
2202 &mut logits_batch,
2203 &x_norm,
2204 self.weights.output_matrix(),
2205 d,
2206 hidden_dim,
2207 vocab_size,
2208 );
2209
2210 // 8. Sampling and output emission (slot failures from step 1b first)
2211 let mut outputs = slot_failures;
2212 outputs.reserve(d);
2213 // The model's end-of-sequence set (legacy TinyLlama UNK/BOS/EOS when the config
2214 // names none): a Llama 3 vocabulary has ordinary text at ids 0..=2.
2215 let stop_tokens = self.weights.config.stop_token_ids().to_vec();
2216
2217 for (i, &(seq_id, _, pos)) in valid_reqs.iter().enumerate() {
2218 let logits = &logits_batch[i * vocab_size..(i + 1) * vocab_size];
2219 // PREFILL-E2E C6: the request's own sampling params (recorded at
2220 // prefill or by the fork hook), seeded per request and position.
2221 // No params, or temperature 0: argmax as before.
2222 // sc#294: counted inside the branch taken.
2223 let obs = &mut self.decode_observed.entry(seq_id).or_default().decode;
2224 let (sampled_tok, logprob) = match self.sampling.get(&seq_id) {
2225 Some(params) => {
2226 let seed = decode_sampling_seed(seq_id, pos + 1);
2227 let picked = sample_with_params_observed(logits, params, seed, obs);
2228 if obs.sampled_tokens > 0 {
2229 obs.seed_request_id = Some(seq_id);
2230 }
2231 picked
2232 }
2233 None => {
2234 obs.greedy_tokens += 1;
2235 sample_argmax(logits)
2236 }
2237 };
2238
2239 if let Some(seq) = self.sequences.get_mut(&seq_id) {
2240 seq.tokens.push(sampled_tok);
2241
2242 if stop_tokens.contains(&sampled_tok) {
2243 outputs.push(DecodeOutput::Finished {
2244 request_id: seq_id,
2245 reason: FinishReason::StopToken,
2246 total_tokens: seq.tokens.len(),
2247 });
2248 } else {
2249 outputs.push(DecodeOutput::Token {
2250 request_id: seq_id,
2251 token_id: sampled_tok,
2252 logprob: Some(logprob),
2253 });
2254 }
2255 }
2256 }
2257
2258 Ok((outputs, logits_batch, vocab_size))
2259 }
2260}
2261
2262#[async_trait]
2263impl AienInferenceBackend for NativeTransformerBackend {
2264 async fn load_model(&mut self, config: &ModelConfig) -> Result<(), String> {
2265 self.weights = TransformerWeights::reference_test_weights(config);
2266 self.sequences.clear();
2267 self.sampling.clear();
2268 self.pending_prefill_token.clear();
2269 self.decode_observed.clear();
2270 Ok(())
2271 }
2272
2273 fn manages_kv_cache(&self) -> bool {
2274 self.kv_manager.is_some()
2275 }
2276
2277 /// Forks per-sequence backend state (tokens, hence position and last
2278 /// token) from a prefilled parent into a child whose physical KV the
2279 /// shared KV manager has already forked (`fork_prefilled`). Never copies
2280 /// or re-forks K/V. Refuses when:
2281 /// - there is no KV manager, or it has no physical tensor pool: the K/V
2282 /// would live in the backend's dense per-sequence cache and a fork
2283 /// would have to copy it per branch (bullet 10);
2284 /// - the parent is not PrefillReady/SharedFrozen in the KV manager
2285 /// (bullet 6: no fork before the completion fence);
2286 /// - the child has no KV block table yet (the KV fork must come first);
2287 /// - the parent is unknown to the backend, or the child already exists.
2288 fn fork_sequence(&mut self, parent_id: u64, child_id: u64) -> Result<(), String> {
2289 let kv_mgr = self.kv_manager.as_ref().ok_or_else(|| {
2290 format!(
2291 "fork_sequence {} -> {} refused: backend has no shared KV manager \
2292 (unpaged fork would copy dense K/V)",
2293 parent_id, child_id
2294 )
2295 })?;
2296 {
2297 let kv = kv_mgr.read();
2298 if kv.tensor_pool().is_none() {
2299 return Err(format!(
2300 "fork_sequence {} -> {} refused: KV manager has no physical tensor pool",
2301 parent_id, child_id
2302 ));
2303 }
2304 match kv.prefill_state(parent_id) {
2305 Some(state) if state.is_ready() => {}
2306 Some(state) => {
2307 return Err(format!(
2308 "fork_sequence {} -> {} refused: parent prefill state {:?} is not ready \
2309 (completion fence not passed)",
2310 parent_id, child_id, state
2311 ))
2312 }
2313 None => {
2314 return Err(format!(
2315 "fork_sequence {} -> {} refused: parent has no KV block table",
2316 parent_id, child_id
2317 ))
2318 }
2319 }
2320 if kv.get_block_table(child_id).is_none() {
2321 return Err(format!(
2322 "fork_sequence {} -> {} refused: child has no KV block table \
2323 (physical KV fork must precede the backend fork)",
2324 parent_id, child_id
2325 ));
2326 }
2327 }
2328 if self.sequences.contains_key(&child_id) {
2329 return Err(format!(
2330 "fork_sequence {} -> {} refused: child already has backend state",
2331 parent_id, child_id
2332 ));
2333 }
2334 // The token prefill sampled but did not append yet (`pending_prefill_token`)
2335 // belongs to the parent's stream. The child gets it appended to its own copy
2336 // of the tokens; the parent is NOT mutated (its tokens stay prompt-only and
2337 // its pending token stays pending, so the parent's own next decode commits it).
2338 let mut parent_tokens = self
2339 .sequences
2340 .get(&parent_id)
2341 .ok_or_else(|| {
2342 format!(
2343 "fork_sequence {} -> {} refused: parent unknown to the backend",
2344 parent_id, child_id
2345 )
2346 })?
2347 .tokens
2348 .clone();
2349 if let Some(&pending) = self.pending_prefill_token.get(&parent_id) {
2350 parent_tokens.push(pending);
2351 }
2352 let kv_dtype = self.storage_dtype();
2353 self.sequences.insert(
2354 child_id,
2355 SequenceState {
2356 tokens: parent_tokens,
2357 // Paged mode: K/V lives in the shared pool, never in per-sequence layers.
2358 layers: Vec::new(),
2359 kv_dtype,
2360 },
2361 );
2362 // PREFILL-E2E C6: a plain fork inherits the parent's sampling params
2363 // (seeded by the child's own id at decode, so streams still differ).
2364 if let Some(params) = self.sampling.get(&parent_id).cloned() {
2365 self.sampling.insert(child_id, params);
2366 }
2367 Ok(())
2368 }
2369
2370 /// PREFILL-E2E C6: same checks and state fork as `fork_sequence`, then
2371 /// records the branch's own sampling params for decode.
2372 fn fork_sequence_with_sampling(
2373 &mut self,
2374 parent_id: u64,
2375 child_id: u64,
2376 sampling: &SamplingParams,
2377 ) -> Result<(), String> {
2378 self.fork_sequence(parent_id, child_id)?;
2379 self.sampling.insert(child_id, sampling.clone());
2380 Ok(())
2381 }
2382
2383 /// ADR 0003 section 6.2 (review finding 3): the tokens whose K/V is written
2384 /// in the shared pool. VERIFIED rule, from the decode and prefill code above:
2385 /// prefill leaves `tokens` holding exactly the cached positions and the
2386 /// sampled token apart in `pending_prefill_token`, so `computed = tokens`;
2387 /// every decode step first commits the pending token (or feeds the last
2388 /// token), computes K/V for the LAST entry of `tokens`, then appends the
2389 /// newly sampled token, which has no K/V, so `computed = tokens[..len - 1]`.
2390 /// The answer is also capped at the block table's `total_tokens`, so it can
2391 /// never claim a position the table does not cover. `None` for an unknown
2392 /// sequence, without a shared manager and pool (K/V is then in the dense
2393 /// per-sequence cache, which no holder can pin), or without a block table.
2394 fn computed_prefix(&self, seq_id: u64) -> Option<Vec<u32>> {
2395 let mgr = self.kv_manager.as_ref()?;
2396 let table_tokens = {
2397 let kv = mgr.read();
2398 kv.tensor_pool()?;
2399 kv.total_tokens(seq_id)?
2400 };
2401 let seq = self.sequences.get(&seq_id)?;
2402 let computed = if self.pending_prefill_token.contains_key(&seq_id) {
2403 seq.tokens.len()
2404 } else {
2405 seq.tokens.len().checked_sub(1)?
2406 };
2407 Some(seq.tokens[..computed.min(table_tokens)].to_vec())
2408 }
2409
2410 /// ADR 0003 section 6.3: backend state for a prefix whose K/V a restore put
2411 /// in `seq_id`'s block table. Same refusals as `fork_sequence` where they
2412 /// apply, nothing changed on any refusal:
2413 /// - no shared KV manager, or one with no physical tensor pool;
2414 /// - no block table for `seq_id` (the restored table is assembled first);
2415 /// - the table is not `PrefillPending` (DOCS SILENT: `fork_sequence` demands
2416 /// a ready parent because it shares finished K/V; here the table is the
2417 /// request's own and the suffix prefill must still run, so the narrowest
2418 /// rule is the exact state `assemble_table` leaves, and a ready table is
2419 /// refused because decode could start on it);
2420 /// - empty `tokens`, or a count different from the table's `total_tokens`;
2421 /// - `seq_id` already has backend state.
2422 ///
2423 /// On success `tokens` is the restored prefix, so the next prefill chunk
2424 /// sits at position `tokens.len()`. No pending sampled token exists.
2425 fn restore_sequence(&mut self, seq_id: u64, tokens: &[u32]) -> Result<(), String> {
2426 let kv_mgr = self.kv_manager.as_ref().ok_or_else(|| {
2427 format!(
2428 "restore_sequence {seq_id} refused: backend has no shared KV manager \
2429 (unpaged restore would copy dense K/V)"
2430 )
2431 })?;
2432 {
2433 let kv = kv_mgr.read();
2434 if kv.tensor_pool().is_none() {
2435 return Err(format!(
2436 "restore_sequence {seq_id} refused: KV manager has no physical tensor pool"
2437 ));
2438 }
2439 let table = kv.get_block_table(seq_id).ok_or_else(|| {
2440 format!(
2441 "restore_sequence {seq_id} refused: sequence has no KV block table \
2442 (the restored table must be assembled first)"
2443 )
2444 })?;
2445 if table.prefill_state != aien_kv_cache::PrefillState::PrefillPending {
2446 return Err(format!(
2447 "restore_sequence {seq_id} refused: prefill state {:?} is not PrefillPending",
2448 table.prefill_state
2449 ));
2450 }
2451 if tokens.is_empty() {
2452 return Err(format!(
2453 "restore_sequence {seq_id} refused: empty token list"
2454 ));
2455 }
2456 if tokens.len() != table.total_tokens {
2457 return Err(format!(
2458 "restore_sequence {seq_id} refused: block table covers {} tokens, \
2459 {} were given",
2460 table.total_tokens,
2461 tokens.len()
2462 ));
2463 }
2464 }
2465 if self.sequences.contains_key(&seq_id) {
2466 return Err(format!(
2467 "restore_sequence {seq_id} refused: sequence already has backend state"
2468 ));
2469 }
2470 let kv_dtype = self.storage_dtype();
2471 self.sequences.insert(
2472 seq_id,
2473 SequenceState {
2474 tokens: tokens.to_vec(),
2475 // Paged mode: K/V lives in the shared pool, never in per-sequence layers.
2476 layers: Vec::new(),
2477 kv_dtype,
2478 },
2479 );
2480 Ok(())
2481 }
2482
2483 /// PREFILL-E2E C5 (bullet 12): removes this request's entry from the
2484 /// per-sequence map (tokens and, unpaged, dense K/V layers) and any pending
2485 /// prefill token (C3). The map is the
2486 /// backend's only per-request state. Unlike the inherent
2487 /// `NativeTransformerBackend::release_sequence` (standalone generation,
2488 /// which owns its KV), this never touches the KV manager: in the runtime
2489 /// the scheduler and swarm manager free the block tables, and freeing here
2490 /// too would race their accounting. Unknown ids are a no-op.
2491 fn release_sequence(&mut self, seq_id: u64) -> Result<(), String> {
2492 self.sequences.remove(&seq_id);
2493 self.pending_prefill_token.remove(&seq_id);
2494 // PREFILL-E2E C6: the per-request sampling params entry goes too.
2495 self.sampling.remove(&seq_id);
2496 self.decode_observed.remove(&seq_id);
2497 Ok(())
2498 }
2499
2500 /// sc#294: how this request's tokens were chosen, counted inside the
2501 /// sampling branch taken (`sample_with_params_observed` and the prefill
2502 /// pick); removed once taken.
2503 fn take_decode_observation(&mut self, request_id: u64) -> Option<DecodeObservation> {
2504 self.decode_observed
2505 .remove(&request_id)
2506 .map(DecodeTally::merged)
2507 }
2508
2509 /// sc#337: the tensor backend's name and op counters so far.
2510 fn op_evidence(&self) -> Option<crate::OpEvidence> {
2511 let mut e = self
2512 .tensor_backend
2513 .op_report()
2514 .evidence(self.tensor_backend.name());
2515 e.gpu_executions = self.tensor_backend.gpu_executions(); // sc#402
2516 Some(e)
2517 }
2518
2519 async fn execute_step(
2520 &mut self,
2521 batch: &ScheduledBatch,
2522 ) -> Result<(Vec<DecodeOutput>, StepMetrics), String> {
2523 let t0 = std::time::Instant::now();
2524 let mut outputs = Vec::new();
2525 let mut prefill_tokens = 0;
2526 let num_layers = self.weights.config.num_layers;
2527
2528 // 1. Prefill Requests
2529 for req in &batch.prefill_requests {
2530 prefill_tokens += req.prompt_tokens.len();
2531 // PREFILL-E2E C6: decode of this request uses its sampling params.
2532 self.sampling
2533 .insert(req.request_id, req.sampling_params.clone());
2534
2535 if let Some(kv_mgr) = &self.kv_manager {
2536 let mut mgr = kv_mgr.write();
2537 if mgr.get_block_table(req.request_id).is_none() {
2538 let _ = mgr.allocate_sequence(req.request_id, &req.prompt_tokens);
2539 }
2540 }
2541
2542 let kv_dtype = self.storage_dtype();
2543 let seq = self
2544 .sequences
2545 .entry(req.request_id)
2546 .or_insert_with(|| SequenceState {
2547 tokens: Vec::new(),
2548 layers: vec![LayerKvCache::default(); num_layers],
2549 kv_dtype,
2550 });
2551
2552 let last_hidden = Self::prefill_prompt_layer_by_layer_paged(
2553 &self.weights,
2554 &*self.tensor_backend,
2555 &req.prompt_tokens,
2556 seq,
2557 req.request_id,
2558 self.kv_manager.as_ref(),
2559 )?;
2560 // A further prefill chunk: the sample held from the previous chunk was
2561 // mid-prompt and is discarded. Done only after this chunk succeeded, so a
2562 // chunk that fails loudly (KV pool exhausted) keeps the held sample and
2563 // can be retried against unchanged state (PREFILL-I25).
2564 self.pending_prefill_token.remove(&req.request_id);
2565
2566 let logits =
2567 Self::compute_logits_impl(&self.weights, &*self.tensor_backend, &last_hidden);
2568 // sc#294: this chunk's pick replaces the previous chunk's (only the
2569 // final chunk's pick is kept, like `pending_prefill_token`).
2570 let mut pick = DecodeObservation::default();
2571 let (sampled_tok, logprob) = if req.sampling_params.temperature <= 0.001 {
2572 pick.greedy_tokens = 1;
2573 sample_argmax(&logits)
2574 } else {
2575 pick.sampled_tokens = 1;
2576 pick.temperature = Some(req.sampling_params.temperature);
2577 pick.seed_request_id = Some(req.request_id);
2578 sample_temperature(&logits, req.sampling_params.temperature, req.request_id)
2579 };
2580 self.decode_observed
2581 .entry(req.request_id)
2582 .or_default()
2583 .prefill_pick = pick;
2584
2585 // Not pushed to `seq.tokens`: if another chunk of this prompt follows, the
2586 // next prefill call replaces this sample; otherwise the first decode
2587 // commits it. Pushing here would put a sampled token between prompt chunks.
2588 self.pending_prefill_token
2589 .insert(req.request_id, sampled_tok);
2590
2591 outputs.push(DecodeOutput::Token {
2592 request_id: req.request_id,
2593 token_id: sampled_tok,
2594 logprob: Some(logprob),
2595 });
2596 }
2597
2598 // 2. Decode Requests (Batched across D active sequences)
2599 if !batch.decode_requests.is_empty() {
2600 let decode_outputs = self.forward_decode_batch(&batch.decode_requests)?;
2601 outputs.extend(decode_outputs);
2602 }
2603
2604 let elapsed_us = t0.elapsed().as_micros() as u64;
2605 let metrics = StepMetrics {
2606 prefill_tokens_processed: prefill_tokens,
2607 decode_tokens_emitted: batch.decode_requests.len() + batch.prefill_requests.len(),
2608 step_latency_us: elapsed_us,
2609 active_kv_blocks: batch.block_tables.values().map(|v| v.len()).sum(),
2610 };
2611
2612 Ok((outputs, metrics))
2613 }
2614}
2615
2616#[cfg(test)]
2617mod tests {
2618 use super::*;
2619
2620 #[test]
2621 fn test_backend_constructors() {
2622 let config = ModelConfig {
2623 num_layers: 2,
2624 num_heads: 4,
2625 num_kv_heads: 2,
2626 head_dim: 16,
2627 hidden_dim: 64,
2628 intermediate_dim: 128,
2629 vocab_size: 256,
2630 ..Default::default()
2631 };
2632
2633 let cpu_backend = NativeTransformerBackend::with_reference_weights(&config);
2634 assert_eq!(cpu_backend.tensor_backend.name(), "ReferenceCpuBackend");
2635
2636 let blackwell_backend = NativeTransformerBackend::with_blackwell_backend(&config);
2637 assert!(blackwell_backend
2638 .tensor_backend
2639 .name()
2640 .starts_with("OmegaGb10Backend"));
2641 }
2642
2643 #[test]
2644 fn test_forward_token_and_logits_execution() {
2645 let config = ModelConfig {
2646 num_layers: 2,
2647 num_heads: 4,
2648 num_kv_heads: 2,
2649 head_dim: 16,
2650 hidden_dim: 64,
2651 intermediate_dim: 128,
2652 vocab_size: 256,
2653 ..Default::default()
2654 };
2655
2656 let backend = NativeTransformerBackend::with_reference_weights(&config);
2657 let mut seq_state = SequenceState {
2658 tokens: vec![1],
2659 layers: vec![LayerKvCache::default(); config.num_layers],
2660 kv_dtype: KvDType::Fp32,
2661 };
2662
2663 let hidden = backend.forward_token(1, 0, &mut seq_state);
2664 assert_eq!(hidden.len(), config.hidden_dim());
2665
2666 let logits = backend.compute_logits(&hidden);
2667 assert_eq!(logits.len(), config.vocab_size());
2668 }
2669
2670 #[test]
2671 fn test_paged_cow_context_and_branch_fork() {
2672 let config = ModelConfig {
2673 num_layers: 2,
2674 num_heads: 4,
2675 num_kv_heads: 2,
2676 head_dim: 16,
2677 hidden_dim: 64,
2678 intermediate_dim: 128,
2679 vocab_size: 256,
2680 block_size: 16,
2681 ..Default::default()
2682 };
2683
2684 let weights = TransformerWeights::reference_test_weights(&config);
2685 let mut backend = NativeTransformerBackend::with_paged_kv(weights, 200, 16).unwrap();
2686
2687 // 1. Create parent context with 30 prompt tokens (2 blocks)
2688 let prompt: Vec<u32> = (0..30).collect();
2689 let parent = backend.create_context(&prompt).unwrap();
2690
2691 // 2. Fork 4 branches
2692 let b1 = backend.fork_context(parent).unwrap();
2693 let b2 = backend.fork_context(parent).unwrap();
2694 let b3 = backend.fork_context(parent).unwrap();
2695 let b4 = backend.fork_context(parent).unwrap();
2696
2697 // Initial receipt before decode: 2 shared pages
2698 let r_init = backend.get_usage_receipt(b1).unwrap();
2699 assert_eq!(r_init.shared_pages, 2);
2700 assert_eq!(r_init.private_pages, 0);
2701
2702 // 3. Decode step for each branch -> triggers COW divergence on partial block 1
2703 let (t1, _) = backend.decode_branch_step(b1).unwrap();
2704 let (t2, _) = backend.decode_branch_step(b2).unwrap();
2705 let (t3, _) = backend.decode_branch_step(b3).unwrap();
2706 let (t4, _) = backend.decode_branch_step(b4).unwrap();
2707
2708 // Tokens generated
2709 assert_eq!(t1, t2); // Same deterministic greedy choice initially
2710 assert_eq!(t3, t4);
2711
2712 let r_after = backend.get_usage_receipt(b1).unwrap();
2713 assert_eq!(r_after.cow_faults, 4); // All 4 branches COWed tail page
2714 assert_eq!(r_after.shared_pages, 1); // Prefix block 0 remains shared
2715 assert_eq!(r_after.private_pages, 1); // Divergent block 1 is private
2716
2717 // 4. Release branches
2718 backend.release_branch(b1).unwrap();
2719 backend.release_branch(b2).unwrap();
2720 backend.release_branch(b3).unwrap();
2721 backend.release_branch(b4).unwrap();
2722 }
2723
2724 #[test]
2725 fn test_native_transformer_generate_tokens() {
2726 let config = ModelConfig {
2727 num_layers: 2,
2728 num_heads: 4,
2729 num_kv_heads: 2,
2730 head_dim: 16,
2731 hidden_dim: 64,
2732 intermediate_dim: 128,
2733 vocab_size: 256,
2734 block_size: 16,
2735 ..Default::default()
2736 };
2737 let mut backend = NativeTransformerBackend::with_reference_weights(&config);
2738 let prompt = vec![1, 5, 9];
2739 let stop_tokens = vec![0];
2740 let generated = backend
2741 .generate_tokens(555, &prompt, 4, 0.0, &stop_tokens)
2742 .unwrap();
2743 assert_eq!(generated.len(), 4);
2744 assert!(!generated.contains(&0));
2745 assert_eq!(backend.sequences.len(), 0);
2746 }
2747
2748 #[test]
2749 fn test_native_transformer_generate_tokens_streaming() {
2750 let config = ModelConfig {
2751 num_layers: 2,
2752 num_heads: 4,
2753 num_kv_heads: 2,
2754 head_dim: 16,
2755 hidden_dim: 64,
2756 intermediate_dim: 128,
2757 vocab_size: 256,
2758 block_size: 16,
2759 ..Default::default()
2760 };
2761 let mut backend = NativeTransformerBackend::with_reference_weights(&config);
2762 let prompt = vec![1, 5, 9];
2763 let stop_tokens = vec![0];
2764 let mut streamed = Vec::new();
2765 backend
2766 .generate_tokens_streaming(777, &prompt, 4, 0.0, &stop_tokens, |tok| {
2767 streamed.push(tok);
2768 true
2769 })
2770 .unwrap();
2771 assert_eq!(streamed.len(), 4);
2772 assert!(!streamed.contains(&0));
2773 assert_eq!(backend.sequences.len(), 0);
2774 }
2775
2776 // PREFILL-E2E-0 bullet 4, cut C3: a prompt longer than one prefill chunk must
2777 // give the same result as a one-shot prefill. Chunk 128 matches the daemon's
2778 // scheduler chunk size; 300 tokens = 128 + 128 + 44.
2779 const C3_PROMPT_LEN: usize = 300;
2780 const C3_CHUNK: usize = 128;
2781 const C3_ABS_TOL: f32 = 1e-4;
2782
2783 fn c3_config() -> ModelConfig {
2784 ModelConfig {
2785 num_layers: 2,
2786 num_heads: 4,
2787 num_kv_heads: 2,
2788 head_dim: 16,
2789 hidden_dim: 64,
2790 intermediate_dim: 128,
2791 vocab_size: 256,
2792 block_size: 16,
2793 ..Default::default()
2794 }
2795 }
2796
2797 /// Deterministic prompt avoiding token ids 0..=2 (UNK/BOS/EOS).
2798 fn c3_prompt() -> Vec<u32> {
2799 (0..C3_PROMPT_LEN)
2800 .map(|i| ((i * 37 + 11) % 253 + 3) as u32)
2801 .collect()
2802 }
2803
2804 fn c3_backend(paged: bool) -> NativeTransformerBackend {
2805 let weights = TransformerWeights::reference_test_weights(&c3_config());
2806 if paged {
2807 NativeTransformerBackend::with_paged_kv(weights, 64, 16).unwrap()
2808 } else {
2809 NativeTransformerBackend::new(weights)
2810 }
2811 }
2812
2813 fn c3_max_abs_diff(a: &[f32], b: &[f32]) -> f32 {
2814 assert_eq!(a.len(), b.len());
2815 a.iter()
2816 .zip(b.iter())
2817 .map(|(x, y)| (x - y).abs())
2818 .fold(0.0f32, f32::max)
2819 }
2820
2821 /// Last-position logits of a 300-token prompt prefilled in chunks of 128 equal
2822 /// the one-shot prefill within abs 1e-4, and the sequence holds exactly the
2823 /// prompt after every chunk. In paged mode the first chunk allocates only its
2824 /// own blocks, so later chunks exercise the append path and the pool rebuild.
2825 fn c3_logits_parity(paged: bool) {
2826 let prompt = c3_prompt();
2827 let id = 7u64;
2828
2829 let mut one_shot = c3_backend(paged);
2830 let reference = one_shot.prefill_sequence(id, &prompt).unwrap();
2831
2832 let mut chunked = c3_backend(paged);
2833 let mut fed = 0usize;
2834 let mut last = Vec::new();
2835 for chunk in prompt.chunks(C3_CHUNK) {
2836 last = chunked.prefill_sequence(id, chunk).unwrap();
2837 fed += chunk.len();
2838 assert_eq!(
2839 chunked.sequences[&id].tokens,
2840 prompt[..fed],
2841 "sequence must hold exactly the prompt tokens fed so far"
2842 );
2843 }
2844 assert_eq!(fed, C3_PROMPT_LEN);
2845
2846 let diff = c3_max_abs_diff(&reference, &last);
2847 assert!(
2848 diff <= C3_ABS_TOL,
2849 "chunked vs one-shot last-position logits differ by {} (> {}), paged={}",
2850 diff,
2851 C3_ABS_TOL,
2852 paged
2853 );
2854
2855 if paged {
2856 let kv = chunked.kv_manager.as_ref().unwrap().read();
2857 assert_eq!(kv.total_tokens(id), Some(C3_PROMPT_LEN));
2858 } else {
2859 for layer in &chunked.sequences[&id].layers {
2860 assert_eq!(layer.cached_k.len(), C3_PROMPT_LEN);
2861 assert_eq!(
2862 layer.flat_k.len(),
2863 one_shot.sequences[&id].layers[0].flat_k.len()
2864 );
2865 }
2866 }
2867 }
2868
2869 #[test]
2870 fn c3_chunked_prefill_logits_match_one_shot_unpaged() {
2871 c3_logits_parity(false);
2872 }
2873
2874 #[test]
2875 fn c3_chunked_prefill_logits_match_one_shot_paged() {
2876 c3_logits_parity(true);
2877 }
2878
2879 /// Through `execute_step` (the scheduler path): no sampled token is pushed
2880 /// between prompt chunks, the sequence holds exactly prompt_len tokens before
2881 /// the first decode, and prefill + one decode match the one-shot control.
2882 /// Paged mode pre-allocates the whole prompt, as `prefill_detached` does.
2883 async fn c3_execute_step_chunked(paged: bool) {
2884 use crate::{SamplingParams, SequenceRequest};
2885 let prompt = c3_prompt();
2886 let id = 9u64;
2887 let req = |toks: &[u32]| SequenceRequest {
2888 request_id: id,
2889 prompt_tokens: toks.to_vec(),
2890 sampling_params: SamplingParams {
2891 temperature: 0.0,
2892 ..Default::default()
2893 },
2894 arrival_time_ns: 0,
2895 priority: 0,
2896 };
2897 let batch = |prefill: Vec<SequenceRequest>, decode: Vec<u64>| ScheduledBatch {
2898 prefill_requests: prefill,
2899 decode_requests: decode,
2900 block_tables: HashMap::new(),
2901 step_id: 0,
2902 };
2903
2904 let mut one_shot = c3_backend(paged);
2905 if let Some(kv) = &one_shot.kv_manager {
2906 kv.write().allocate_sequence(id, &prompt).unwrap();
2907 }
2908 let (out_one, _) = one_shot
2909 .execute_step(&batch(vec![req(&prompt)], vec![]))
2910 .await
2911 .unwrap();
2912 one_shot
2913 .execute_step(&batch(vec![], vec![id]))
2914 .await
2915 .unwrap();
2916
2917 let mut chunked = c3_backend(paged);
2918 if let Some(kv) = &chunked.kv_manager {
2919 kv.write().allocate_sequence(id, &prompt).unwrap();
2920 }
2921 let mut fed = 0usize;
2922 let mut last_out = Vec::new();
2923 for chunk in prompt.chunks(C3_CHUNK) {
2924 let (out, metrics) = chunked
2925 .execute_step(&batch(vec![req(chunk)], vec![]))
2926 .await
2927 .unwrap();
2928 fed += chunk.len();
2929 assert_eq!(metrics.prefill_tokens_processed, chunk.len());
2930 assert_eq!(
2931 chunked.sequences[&id].tokens,
2932 prompt[..fed],
2933 "no sampled token may be pushed between prompt chunks"
2934 );
2935 last_out = out;
2936 }
2937 assert_eq!(chunked.sequences[&id].tokens.len(), C3_PROMPT_LEN);
2938
2939 let first_token = |out: &[DecodeOutput]| match out.first() {
2940 Some(DecodeOutput::Token { token_id, .. }) => *token_id,
2941 other => panic!("expected a sampled token after prefill, got {:?}", other),
2942 };
2943 let first_chunked = first_token(&last_out[..]);
2944 assert_eq!(first_chunked, first_token(&out_one[..]));
2945
2946 chunked
2947 .execute_step(&batch(vec![], vec![id]))
2948 .await
2949 .unwrap();
2950 let toks = &chunked.sequences[&id].tokens;
2951 assert_eq!(toks.len(), C3_PROMPT_LEN + 2);
2952 assert_eq!(toks[..C3_PROMPT_LEN], prompt[..]);
2953 assert_eq!(toks[C3_PROMPT_LEN], first_chunked);
2954 assert_eq!(*toks, one_shot.sequences[&id].tokens);
2955 }
2956
2957 #[tokio::test]
2958 async fn c3_chunked_prefill_execute_step_unpaged() {
2959 c3_execute_step_chunked(false).await;
2960 }
2961
2962 #[tokio::test]
2963 async fn c3_chunked_prefill_execute_step_paged() {
2964 c3_execute_step_chunked(true).await;
2965 }
2966
2967 /// sc#294: prefill in chunks, then `decodes` decode steps, through
2968 /// `execute_step` (the scheduler path). Returns the observation the
2969 /// scheduler would take at finish and the chosen tokens after the prompt.
2970 async fn sc294_run(params: SamplingParams, decodes: usize) -> (DecodeObservation, Vec<u32>) {
2971 use crate::SequenceRequest;
2972 let prompt = c3_prompt();
2973 let id = 11u64;
2974 let batch = |prefill: Vec<SequenceRequest>, decode: Vec<u64>| ScheduledBatch {
2975 prefill_requests: prefill,
2976 decode_requests: decode,
2977 block_tables: HashMap::new(),
2978 step_id: 0,
2979 };
2980 let mut b = c3_backend(false);
2981 for chunk in prompt.chunks(C3_CHUNK) {
2982 let req = SequenceRequest {
2983 request_id: id,
2984 prompt_tokens: chunk.to_vec(),
2985 sampling_params: params.clone(),
2986 arrival_time_ns: 0,
2987 priority: 0,
2988 };
2989 b.execute_step(&batch(vec![req], vec![])).await.unwrap();
2990 }
2991 for _ in 0..decodes {
2992 b.execute_step(&batch(vec![], vec![id])).await.unwrap();
2993 }
2994 let chosen = b.sequences[&id].tokens[C3_PROMPT_LEN..].to_vec();
2995 let obs = b.take_decode_observation(id).expect("observed");
2996 assert_eq!(b.take_decode_observation(id), None, "taken once");
2997 (obs, chosen)
2998 }
2999
3000 /// Greedy request: every chosen token is counted as greedy, the
3001 /// discarded mid-prompt picks are not, and nothing claims sampling.
3002 #[tokio::test]
3003 async fn sc294_greedy_request_is_observed_greedy() {
3004 const {
3005 assert!(
3006 C3_PROMPT_LEN > C3_CHUNK,
3007 "prompt must take more than one chunk"
3008 )
3009 };
3010 let greedy = SamplingParams {
3011 temperature: 0.0,
3012 ..Default::default()
3013 };
3014 let (obs, chosen) = sc294_run(greedy, 3).await;
3015 // 1 pick after the final prefill chunk (committed by the first decode)
3016 // plus 3 decode picks; the last decode's pick is pushed too.
3017 assert_eq!(chosen.len(), 4);
3018 assert_eq!(obs.greedy_tokens, 4);
3019 assert_eq!(obs.sampled_tokens, 0);
3020 assert_eq!(obs.mode(), "greedy");
3021 assert_eq!(
3022 (obs.temperature, obs.top_p, obs.seed_request_id),
3023 (None, None, None)
3024 );
3025 }
3026
3027 /// Sampling request: every token is counted as drawn, with the
3028 /// temperature, the top_p the decode draws applied, and the seed's request id.
3029 #[tokio::test]
3030 async fn sc294_sampled_request_is_observed_sampled() {
3031 let sampled = SamplingParams {
3032 temperature: 0.7,
3033 top_p: 0.95,
3034 ..Default::default()
3035 };
3036 let (obs, _) = sc294_run(sampled, 3).await;
3037 assert_eq!(obs.sampled_tokens, 4);
3038 assert_eq!(obs.greedy_tokens, 0);
3039 assert_eq!(obs.mode(), "sampled");
3040 assert_eq!(obs.temperature, Some(0.7));
3041 assert_eq!(obs.top_p, Some(0.95));
3042 assert_eq!(obs.seed_request_id, Some(11));
3043 }
3044
3045 /// Observing never changes the chosen token: the same token and logprob
3046 /// as `sample_with_params`, greedy and sampled, over many seeds.
3047 #[test]
3048 fn sc294_observing_does_not_change_the_choice() {
3049 let logits: Vec<f32> = (0..64).map(|i| ((i * 37 % 64) as f32) * 0.1).collect();
3050 for temperature in [0.0f32, 0.0005, 0.3, 0.7, 1.5] {
3051 for top_p in [0.0f32, 0.5, 0.95, 1.0] {
3052 let p = SamplingParams {
3053 temperature,
3054 top_p,
3055 ..Default::default()
3056 };
3057 for seed in 0..50u64 {
3058 let seed = decode_sampling_seed(seed, 3);
3059 let mut o = DecodeObservation::default();
3060 assert_eq!(
3061 sample_with_params(&logits, &p, seed),
3062 sample_with_params_observed(&logits, &p, seed, &mut o)
3063 );
3064 let (t, lp, _) = sample_with_params_traced(&logits, &p, seed, &mut o);
3065 assert_eq!(sample_with_params(&logits, &p, seed), (t, lp));
3066 }
3067 }
3068 }
3069 }
3070
3071 /// OWN-8B stage S: the kept set is counted where the draw happens.
3072 #[test]
3073 fn stage_s_trace_counts_the_kept_set() {
3074 let mut o = DecodeObservation::default();
3075 let p = |temperature: f32, top_p: f32| SamplingParams {
3076 temperature,
3077 top_p,
3078 ..Default::default()
3079 };
3080 // Flat 4-way: everything is kept, top probability 1/4.
3081 let flat = [0.0f32; 4];
3082 let (_, _, tr) = sample_with_params_traced(&flat, &p(1.0, 1.0), 9, &mut o);
3083 assert_eq!(tr.kept, 4);
3084 assert!((tr.top_prob - 0.25).abs() < 1e-12, "{tr:?}");
3085 // One token holds more than top_p of the mass: the nucleus keeps it alone.
3086 let peaked = [10.0f32, 0.0, 0.0, 0.0];
3087 let (t, _, tr) = sample_with_params_traced(&peaked, &p(0.7, 0.8), 9, &mut o);
3088 assert_eq!((t, tr.kept), (0, 1));
3089 assert!(tr.top_prob > 0.8, "{tr:?}");
3090 // Masked (-inf) logits are not counted as kept.
3091 let masked = [1.0f32, 1.0, f32::NEG_INFINITY, f32::NEG_INFINITY];
3092 let (_, _, tr) = sample_with_params_traced(&masked, &p(1.0, 1.0), 9, &mut o);
3093 assert_eq!(tr.kept, 2);
3094 // Greedy: one candidate.
3095 let (t, _, tr) = sample_with_params_traced(&flat, &p(0.0, 1.0), 9, &mut o);
3096 assert_eq!((t, tr.kept, tr.top_prob), (0, 1, 1.0));
3097 }
3098
3099 /// A decoding request with no recorded sampling params takes the argmax
3100 /// arm of decode; those picks are counted as greedy too.
3101 #[tokio::test]
3102 async fn sc294_decode_without_params_is_observed_greedy() {
3103 use crate::SequenceRequest;
3104 let id = 7u64;
3105 let mut b = c3_backend(false);
3106 let req = SequenceRequest {
3107 request_id: id,
3108 prompt_tokens: c3_prompt()[..4].to_vec(),
3109 sampling_params: SamplingParams {
3110 temperature: 0.0,
3111 ..Default::default()
3112 },
3113 arrival_time_ns: 0,
3114 priority: 0,
3115 };
3116 let batch = |prefill: Vec<SequenceRequest>, decode: Vec<u64>| ScheduledBatch {
3117 prefill_requests: prefill,
3118 decode_requests: decode,
3119 block_tables: HashMap::new(),
3120 step_id: 0,
3121 };
3122 b.execute_step(&batch(vec![req], vec![])).await.unwrap();
3123 b.sampling.remove(&id);
3124 for _ in 0..2 {
3125 b.execute_step(&batch(vec![], vec![id])).await.unwrap();
3126 }
3127 let obs = b.take_decode_observation(id).expect("observed");
3128 assert_eq!((obs.greedy_tokens, obs.sampled_tokens), (3, 0));
3129 assert_eq!(obs.mode(), "greedy");
3130 }
3131
3132 /// A released or never-seen request has no observation.
3133 #[tokio::test]
3134 async fn sc294_release_drops_the_observation() {
3135 use crate::SequenceRequest;
3136 let mut b = c3_backend(false);
3137 let req = SequenceRequest {
3138 request_id: 5,
3139 prompt_tokens: c3_prompt()[..4].to_vec(),
3140 sampling_params: SamplingParams {
3141 temperature: 0.0,
3142 ..Default::default()
3143 },
3144 arrival_time_ns: 0,
3145 priority: 0,
3146 };
3147 let batch = ScheduledBatch {
3148 prefill_requests: vec![req],
3149 decode_requests: vec![],
3150 block_tables: HashMap::new(),
3151 step_id: 0,
3152 };
3153 b.execute_step(&batch).await.unwrap();
3154 AienInferenceBackend::release_sequence(&mut b, 5).unwrap();
3155 assert_eq!(b.take_decode_observation(5), None);
3156 assert_eq!(b.take_decode_observation(6), None);
3157 }
3158}