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-runtime / src / model.rs

276 lines · 9016 bytes Raw Blame History
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Drake Stapleton (AIEN / aien-dev)
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16use aien_inference_abi::backend::{ReferenceCpuBackend, TensorBackend};
17use aien_inference_abi::tokenizer::TinyLlamaTokenizer;
18use aien_inference_abi::transformer_backend::NativeTransformerBackend;
19use aien_inference_abi::weights::TransformerWeights;
20use aien_inference_abi::ModelConfig;
21use aien_kv_cache::SharedKvManager;
22use aien_scheduler::AienScheduler;
23use parking_lot::RwLock;
24use std::path::{Path, PathBuf};
25use std::sync::atomic::{AtomicU64, Ordering};
26use std::sync::Arc;
27use tracing::{info, warn};
28
29static SEQUENCE_COUNTER: AtomicU64 = AtomicU64::new(1);
30
31fn generate_sequence_id() -> u64 {
32 SEQUENCE_COUNTER.fetch_add(1, Ordering::Relaxed)
33}
34
35pub struct EmbeddedModel {
36 pub tokenizer: TinyLlamaTokenizer,
37 pub transformer: NativeTransformerBackend,
38 pub scheduler: Option<Arc<RwLock<AienScheduler>>>,
39 pub kv_cache: Option<SharedKvManager>,
40 pub config: ModelConfig,
41}
42
43impl EmbeddedModel {
44 pub fn new(
45 tokenizer: TinyLlamaTokenizer,
46 transformer: NativeTransformerBackend,
47 scheduler: Option<Arc<RwLock<AienScheduler>>>,
48 kv_cache: Option<SharedKvManager>,
49 config: ModelConfig,
50 ) -> Self {
51 Self {
52 tokenizer,
53 transformer,
54 scheduler,
55 kv_cache,
56 config,
57 }
58 }
59
60 pub fn with_reference_weights(config: &ModelConfig) -> Result<Self, String> {
61 let transformer = NativeTransformerBackend::with_reference_weights(config);
62 let tokenizer_path = find_tokenizer_path()
63 .ok_or_else(|| "No valid tokenizer.json found on filesystem".to_string())?;
64
65 let tokenizer = TinyLlamaTokenizer::from_file(&tokenizer_path).map_err(|e| {
66 format!(
67 "Failed to load tokenizer from {}: {}",
68 tokenizer_path.display(),
69 e
70 )
71 })?;
72
73 Ok(Self {
74 tokenizer,
75 transformer,
76 scheduler: None,
77 kv_cache: None,
78 config: config.clone(),
79 })
80 }
81
82 pub fn load_checkpoint<P: AsRef<Path>>(
83 checkpoint_path: P,
84 tokenizer_path: P,
85 use_gpu: bool,
86 paged_kv: bool,
87 ) -> Result<Self, String> {
88 let config = ModelConfig::tinyllama_1_1b();
89 let weights = TransformerWeights::load_from_safetensors(checkpoint_path.as_ref(), &config)
90 .map_err(|e| format!("Failed to load safetensors checkpoint: {}", e))?;
91
92 // FB-1 cut 6: the native Omega engine is the only GPU backend (no CUDA).
93 let tensor_backend: Arc<dyn TensorBackend> = if use_gpu {
94 let omega = aien_inference_abi::OmegaGb10Backend::new();
95 if omega.is_available() {
96 info!("Binding EmbeddedModel to the native Omega GPU engine");
97 Arc::new(omega)
98 } else if aien_inference_abi::strict::production_strict() {
99 return Err(aien_inference_abi::strict::violation(
100 "GPU backend requested but the Omega GPU engine is not linked (stub build)",
101 ));
102 } else {
103 info!("Omega GPU engine not linked, falling back to CPU reference execution");
104 Arc::new(ReferenceCpuBackend::new())
105 }
106 } else {
107 Arc::new(ReferenceCpuBackend::new())
108 };
109
110 let transformer = if paged_kv {
111 NativeTransformerBackend::with_paged_kv_backend(
112 weights,
113 tensor_backend,
114 2048,
115 config.block_size,
116 )?
117 } else {
118 NativeTransformerBackend::with_backend(weights, tensor_backend)
119 };
120
121 let kv_cache = transformer.kv_manager.clone();
122 let tokenizer = TinyLlamaTokenizer::from_file(tokenizer_path.as_ref()).map_err(|e| {
123 format!(
124 "Failed to load tokenizer from {}: {}",
125 tokenizer_path.as_ref().display(),
126 e
127 )
128 })?;
129
130 Ok(Self {
131 tokenizer,
132 transformer,
133 scheduler: None,
134 kv_cache,
135 config,
136 })
137 }
138
139 pub fn load_default_or_fallback() -> Result<Self, String> {
140 let model_path = find_checkpoint_path();
141 let tokenizer_path = find_tokenizer_path();
142
143 if let (Some(mp), Some(tp)) = (model_path, tokenizer_path) {
144 info!("Loading real TinyLlama checkpoint from {}", mp.display());
145 Self::load_checkpoint(&mp, &tp, true, true)
146 } else {
147 if aien_inference_abi::strict::production_strict() {
148 return Err(aien_inference_abi::strict::violation(
149 "no real checkpoint and tokenizer found on disk",
150 ));
151 }
152 warn!("Real model checkpoint not found on disk, using reference test weights");
153 Self::with_reference_weights(&ModelConfig::tinyllama_1_1b())
154 }
155 }
156
157 pub fn generate_stream<F>(
158 &mut self,
159 prompt: &str,
160 max_tokens: usize,
161 temperature: f32,
162 mut on_token: F,
163 ) -> Result<(), String>
164 where
165 F: FnMut(&str) -> bool,
166 {
167 let prompt_tokens = self
168 .tokenizer
169 .encode(prompt)
170 .map_err(|e| format!("Encoding failed: {}", e))?;
171
172 let seq_id = generate_sequence_id();
173 let stop_tokens = [
174 TinyLlamaTokenizer::EOS_TOKEN_ID,
175 TinyLlamaTokenizer::UNK_TOKEN_ID,
176 ];
177
178 self.transformer.generate_tokens_streaming(
179 seq_id,
180 &prompt_tokens,
181 max_tokens,
182 temperature,
183 &stop_tokens,
184 |tok| {
185 if let Ok(piece) = self.tokenizer.decode(&[tok]) {
186 on_token(&piece)
187 } else {
188 true
189 }
190 },
191 )
192 }
193
194 pub fn generate(
195 &mut self,
196 prompt: &str,
197 max_tokens: usize,
198 temperature: f32,
199 ) -> Result<String, String> {
200 let prompt_tokens = self
201 .tokenizer
202 .encode(prompt)
203 .map_err(|e| format!("Encoding failed: {}", e))?;
204
205 let seq_id = generate_sequence_id();
206 let stop_tokens = [
207 TinyLlamaTokenizer::EOS_TOKEN_ID,
208 TinyLlamaTokenizer::UNK_TOKEN_ID,
209 ];
210
211 let generated_ids = self.transformer.generate_tokens(
212 seq_id,
213 &prompt_tokens,
214 max_tokens,
215 temperature,
216 &stop_tokens,
217 )?;
218
219 self.tokenizer
220 .decode(&generated_ids)
221 .map_err(|e| format!("Decoding failed: {}", e))
222 }
223}
224
225/// Pinned TinyLlama snapshot in the Hugging Face cache, located from
226/// HF_HOME or HOME. Returns None when neither is set.
227fn tinyllama_snapshot_dir() -> Option<PathBuf> {
228 let hub = match std::env::var_os("HF_HOME") {
229 Some(h) => PathBuf::from(h).join("hub"),
230 None => PathBuf::from(std::env::var_os("HOME")?).join(".cache/huggingface/hub"),
231 };
232 Some(hub.join("models--TinyLlama--TinyLlama-1.1B-Chat-v1.0/snapshots/fe8a4ea1ffedaf415f4da2f062534de366a451e6"))
233}
234
235fn find_checkpoint_path() -> Option<PathBuf> {
236 if let Ok(p) = std::env::var("TINYLLAMA_MODEL_PATH") {
237 let path = PathBuf::from(p);
238 if path.exists() {
239 return Some(path);
240 }
241 }
242
243 if let Some(base) = tinyllama_snapshot_dir() {
244 let default_snap = base.join("model.safetensors");
245 if default_snap.exists() {
246 return Some(default_snap);
247 }
248 }
249
250 None
251}
252
253fn find_tokenizer_path() -> Option<PathBuf> {
254 if let Ok(p) = std::env::var("TINYLLAMA_TOKENIZER_PATH") {
255 let path = PathBuf::from(p);
256 if path.exists() {
257 return Some(path);
258 }
259 }
260
261 let manifest_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
262 let candidates = [
263 manifest_dir.join("../aien-inference-abi/fixtures/tokenizer.json"),
264 manifest_dir.join("fixtures/tokenizer.json"),
265 PathBuf::from("crates/aien-inference-abi/fixtures/tokenizer.json"),
266 ];
267 let hf_tok = tinyllama_snapshot_dir().map(|d| d.join("tokenizer.json"));
268
269 for c in candidates.iter().chain(hf_tok.iter()) {
270 if c.exists() {
271 return Some(c.clone());
272 }
273 }
274
275 None
276}