1use cortiq_core::CmfModel;
4use cortiq_core::mask::{MaskCatalog, MaskDiff, TaskMask};
5#[cfg(not(target_os = "macos"))]
6use cortiq_core::types::SimdType;
7use cortiq_core::types::{ExecutionMode, LayerStats, PerformanceMetrics};
8use serde::{Deserialize, Serialize};
9use std::sync::Arc;
10use std::time::Instant;
11use tokio::sync::RwLock;
12
13pub struct CortiqRuntime {
15 model: Arc<CmfModel>,
17 state: Arc<RwLock<RuntimeState>>,
19 started_at: Instant,
21}
22
23#[derive(Debug)]
25struct RuntimeState {
26 active_task: String,
27 active_mask: Option<TaskMask>,
28 execution_mode: ExecutionMode,
29 metrics: PerformanceMetrics,
30 layer_stats: Vec<LayerStats>,
31}
32
33#[derive(Debug, Clone, Serialize, Deserialize)]
35pub struct SwitchResult {
36 pub previous_task: String,
37 pub new_task: String,
38 pub switch_mode: String,
39 pub switch_latency_ms: f64,
40 pub new_sparsity: f32,
41 pub new_active_params: String,
42 pub diff: MaskDiff,
43}
44
45#[derive(Debug, Clone, Serialize, Deserialize)]
47pub struct RuntimeStatus {
48 pub model_name: String,
49 pub model_path: String,
50 pub format: String,
51 pub quantization: String,
52 pub execution_mode: ExecutionMode,
53 pub active_task: String,
54 pub active_sparsity: f32,
55 pub active_params: String,
56 pub active_layers: usize,
57 pub total_layers: usize,
58 pub performance: PerformanceMetrics,
59 pub layer_stats: Vec<LayerStats>,
60}
61
62impl CortiqRuntime {
63 pub fn new(model: Arc<CmfModel>) -> Self {
65 let arch = model.arch();
66 let n_layers = arch.num_layers;
67
68 let execution_mode = Self::detect_execution_mode();
70
71 let ffn_neurons = |i: usize| -> usize {
77 model
78 .tensor(&format!("model.layers.{i}.mlp.gate_proj.weight"))
79 .and_then(|t| t.shape.first().copied())
80 .unwrap_or(arch.intermediate_size)
81 };
82 let layer_stats: Vec<LayerStats> = (0..n_layers)
83 .map(|i| LayerStats {
84 layer_idx: i,
85 active_neurons: ffn_neurons(i),
86 total_neurons: ffn_neurons(i),
87 active_heads: arch.num_attention_heads,
88 total_heads: arch.num_attention_heads,
89 is_alive: true,
90 placement: "gpu".to_string(),
91 avg_forward_ms: 0.0,
92 })
93 .collect();
94
95 let state = RuntimeState {
96 active_task: model.masks.default_task.clone(),
97 active_mask: model.masks.fallback().cloned(),
98 execution_mode,
99 metrics: PerformanceMetrics::default(),
100 layer_stats,
101 };
102
103 Self {
104 model,
105 state: Arc::new(RwLock::new(state)),
106 started_at: Instant::now(),
107 }
108 }
109
110 fn detect_execution_mode() -> ExecutionMode {
112 #[cfg(target_os = "macos")]
114 {
115 ExecutionMode::AppleUnified {
116 metal_layers: vec![],
117 }
118 }
119 #[cfg(not(target_os = "macos"))]
120 {
121 ExecutionMode::CpuOnly {
122 simd_type: SimdType::Avx2,
123 threads: num_cpus(),
124 }
125 }
126 }
127
128 pub async fn switch_task(&self, task_name: &str) -> Result<SwitchResult, anyhow::Error> {
130 let new_mask = self
131 .model
132 .masks
133 .get(task_name)
134 .ok_or_else(|| anyhow::anyhow!("Task mask '{}' not found", task_name))?
135 .clone();
136
137 let mut state = self.state.write().await;
138 let previous_task = state.active_task.clone();
139
140 if new_mask.quality.is_none() {
142 tracing::warn!(
143 "task '{task_name}': mask has no measured quality — \
144 treat outputs as unvalidated"
145 );
146 }
147
148 let switch_start = Instant::now();
149
150 let diff = if let Some(ref current) = state.active_mask {
152 current.diff(&new_mask)
153 } else {
154 MaskDiff {
155 changed_layers: (0..self.model.arch().num_layers).collect(),
156 neurons_added: 0,
157 neurons_removed: 0,
158 ffn_delta: vec![],
159 }
160 };
161
162 for ls in &mut state.layer_stats {
164 ls.active_neurons = new_mask.ffn_active_count(ls.layer_idx);
165 ls.active_heads = new_mask.active_head_count(ls.layer_idx);
166 ls.is_alive = new_mask.layer_alive(ls.layer_idx);
167 }
168
169 let switch_latency = switch_start.elapsed().as_secs_f64() * 1000.0;
170
171 state.active_task = task_name.to_string();
172 let sparsity = new_mask.sparsity;
173 state.active_mask = Some(new_mask);
174 state.metrics.last_switch_latency_ms = switch_latency;
175 state.metrics.total_switches += 1;
176
177 let active_params = self.estimate_active_params(&state);
178
179 Ok(SwitchResult {
180 previous_task,
181 new_task: task_name.to_string(),
182 switch_mode: "warm".to_string(),
183 switch_latency_ms: switch_latency,
184 new_sparsity: sparsity,
185 new_active_params: active_params,
186 diff,
187 })
188 }
189
190 pub async fn status(&self) -> RuntimeStatus {
192 let state = self.state.read().await;
193 let mut metrics = state.metrics.clone();
194 metrics.uptime_seconds = self.started_at.elapsed().as_secs();
195
196 let active_sparsity = state
197 .active_mask
198 .as_ref()
199 .map(|m| m.sparsity)
200 .unwrap_or(0.0);
201
202 let active_layers = state.layer_stats.iter().filter(|l| l.is_alive).count();
203
204 RuntimeStatus {
205 model_name: self.model.arch().arch_name.clone(),
206 model_path: self.model.path.display().to_string(),
207 format: format!("CMF v{}", self.model.header.version),
208 quantization: format!("{:?}", self.model.header.quant_type),
209 execution_mode: state.execution_mode.clone(),
210 active_task: state.active_task.clone(),
211 active_sparsity,
212 active_params: self.estimate_active_params(&state),
213 active_layers,
214 total_layers: self.model.arch().num_layers * self.model.arch().num_loops,
215 performance: metrics,
216 layer_stats: state.layer_stats.clone(),
217 }
218 }
219
220 pub fn masks(&self) -> &MaskCatalog {
222 &self.model.masks
223 }
224
225 pub fn model(&self) -> &CmfModel {
227 &self.model
228 }
229
230 pub async fn active_mask(&self) -> Option<TaskMask> {
232 self.state.read().await.active_mask.clone()
233 }
234
235 pub async fn active_selection(&self) -> (String, Option<TaskMask>) {
238 let state = self.state.read().await;
239 (state.active_task.clone(), state.active_mask.clone())
240 }
241
242 pub async fn record_generation(&self, gen_tokens: usize, elapsed_ms: f64, ttft_ms: f64) {
244 let mut state = self.state.write().await;
245 let m = &mut state.metrics;
246 let prev_total = m.tokens_generated as f64;
247 m.tokens_generated += gen_tokens as u64;
248 if elapsed_ms > 0.0 {
249 let tps = gen_tokens as f64 / (elapsed_ms / 1000.0);
250 let total = prev_total + gen_tokens as f64;
252 m.avg_tokens_per_sec = if total > 0.0 {
253 (m.avg_tokens_per_sec * prev_total + tps * gen_tokens as f64) / total
254 } else {
255 tps
256 };
257 }
258 if m.avg_time_to_first_token_ms == 0.0 {
259 m.avg_time_to_first_token_ms = ttft_ms;
260 } else {
261 m.avg_time_to_first_token_ms = m.avg_time_to_first_token_ms * 0.9 + ttft_ms * 0.1;
262 }
263 }
264
265 fn estimate_active_params(&self, state: &RuntimeState) -> String {
267 let total_params = self.model.total_param_count() as f64 / 1e9;
268 let sparsity = state
269 .active_mask
270 .as_ref()
271 .map(|m| m.sparsity as f64)
272 .unwrap_or(0.0);
273 let active = total_params * (1.0 - sparsity);
274 format!("{:.2}B / {:.2}B", active, total_params)
275 }
276}
277
278#[cfg(not(target_os = "macos"))]
279fn num_cpus() -> usize {
280 std::thread::available_parallelism()
281 .map(|n| n.get())
282 .unwrap_or(4)
283}