Skip to main content

cortiq_engine/
runtime.rs

1//! Runtime state management — model, active task, metrics.
2
3use cortiq_core::mask::{MaskCatalog, MaskDiff, TaskMask};
4#[cfg(not(target_os = "macos"))]
5use cortiq_core::types::SimdType;
6use cortiq_core::types::{ExecutionMode, LayerStats, PerformanceMetrics};
7use cortiq_core::CmfModel;
8use serde::{Deserialize, Serialize};
9use std::sync::Arc;
10use std::time::Instant;
11use tokio::sync::RwLock;
12
13/// Main runtime managing model state, active task, and metrics.
14pub struct CortiqRuntime {
15    /// Loaded CMF model
16    model: Arc<CmfModel>,
17    /// Current state (behind RwLock for concurrent reads)
18    state: Arc<RwLock<RuntimeState>>,
19    /// Start time
20    started_at: Instant,
21}
22
23/// Mutable runtime state.
24#[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/// Response from a task switch operation.
34#[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/// Runtime status snapshot.
46#[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    /// Create a new runtime from a loaded CMF model.
64    pub fn new(model: Arc<CmfModel>) -> Self {
65        let arch = model.arch();
66        let n_layers = arch.num_layers;
67
68        // Detect execution mode
69        let execution_mode = Self::detect_execution_mode();
70
71        // Default layer stats. FFN neuron counts come from the actual
72        // gate_proj shape (the directory is the size authority) so a
73        // physically-defragged layer (spec §11) reports its true reduced
74        // count, not the nominal arch scalar; fall back to the scalar when
75        // no dense gate_proj is present (e.g. MoE router layers).
76        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    /// Detect optimal execution mode for current hardware.
111    fn detect_execution_mode() -> ExecutionMode {
112        // TODO: actual hardware detection (CUDA, Metal, CPU caps)
113        #[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    /// Switch to a different task mask.
129    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        // Spec §5.1: switching onto an unmeasured mask must be loud.
141        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        // Compute diff for efficient swap
151        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        // Update layer stats based on new mask
163        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    /// Get current runtime status.
191    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,
215            performance: metrics,
216            layer_stats: state.layer_stats.clone(),
217        }
218    }
219
220    /// Get mask catalog.
221    pub fn masks(&self) -> &MaskCatalog {
222        &self.model.masks
223    }
224
225    /// Get model reference.
226    pub fn model(&self) -> &CmfModel {
227        &self.model
228    }
229
230    /// Snapshot of the currently active task mask (None = dense).
231    pub async fn active_mask(&self) -> Option<TaskMask> {
232        self.state.read().await.active_mask.clone()
233    }
234
235    /// Record a finished generation into the performance metrics.
236    pub async fn record_generation(&self, gen_tokens: usize, elapsed_ms: f64, ttft_ms: f64) {
237        let mut state = self.state.write().await;
238        let m = &mut state.metrics;
239        let prev_total = m.tokens_generated as f64;
240        m.tokens_generated += gen_tokens as u64;
241        if elapsed_ms > 0.0 {
242            let tps = gen_tokens as f64 / (elapsed_ms / 1000.0);
243            // Running average weighted by token counts.
244            let total = prev_total + gen_tokens as f64;
245            m.avg_tokens_per_sec = if total > 0.0 {
246                (m.avg_tokens_per_sec * prev_total + tps * gen_tokens as f64) / total
247            } else {
248                tps
249            };
250        }
251        if m.avg_time_to_first_token_ms == 0.0 {
252            m.avg_time_to_first_token_ms = ttft_ms;
253        } else {
254            m.avg_time_to_first_token_ms = m.avg_time_to_first_token_ms * 0.9 + ttft_ms * 0.1;
255        }
256    }
257
258    /// Estimate active parameters string (from real tensor shapes).
259    fn estimate_active_params(&self, state: &RuntimeState) -> String {
260        let total_params = self.model.total_param_count() as f64 / 1e9;
261        let sparsity = state
262            .active_mask
263            .as_ref()
264            .map(|m| m.sparsity as f64)
265            .unwrap_or(0.0);
266        let active = total_params * (1.0 - sparsity);
267        format!("{:.2}B / {:.2}B", active, total_params)
268    }
269}
270
271#[cfg(not(target_os = "macos"))]
272fn num_cpus() -> usize {
273    std::thread::available_parallelism()
274        .map(|n| n.get())
275        .unwrap_or(4)
276}