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 / spark-adapters / src / distill.rs

487 lines · 17132 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 crate::models::{ChatMessage, DistillTask, DistillationRecord, Rollout};
17use crate::providers::call_provider_unary;
18use crate::router::AdapterRouter;
19use crate::verifier::Verifier;
20use chrono::Utc;
21use reqwest::Client;
22use serde_json::json;
23use std::fs::{create_dir_all, OpenOptions};
24use std::io::Write;
25use std::path::{Path, PathBuf};
26use std::time::{Duration, Instant};
27
28pub struct DistillationEngine {
29 pub client: Client,
30 pub router: AdapterRouter,
31 pub dataset_dir: PathBuf,
32 pub cortex_endpoint: String,
33}
34
35impl Default for DistillationEngine {
36 fn default() -> Self {
37 Self::new()
38 }
39}
40
41impl DistillationEngine {
42 pub const CORTEX_QUALIFICATION_THRESHOLD: f32 = 0.85;
43
44 pub fn new() -> Self {
45 let home = std::env::var("HOME")
46 .or_else(|_| std::env::var("USERPROFILE"))
47 .map(PathBuf::from)
48 .unwrap_or_else(|_| PathBuf::from("."));
49 let default_dir = home.join("workspace/distillation-data");
50 let _ = create_dir_all(&default_dir);
51
52 let client = Client::builder()
53 .connect_timeout(Duration::from_secs(5))
54 .timeout(Duration::from_secs(30))
55 .build()
56 .unwrap_or_default();
57
58 Self {
59 client,
60 router: AdapterRouter::new(),
61 dataset_dir: default_dir,
62 cortex_endpoint: "http://127.0.0.1:18080".to_string(),
63 }
64 }
65
66 pub fn with_client(mut self, client: Client) -> Self {
67 self.client = client;
68 self
69 }
70
71 pub fn with_timeout(mut self, timeout: Duration) -> Self {
72 self.client = Client::builder()
73 .connect_timeout(Duration::from_secs(5))
74 .timeout(timeout)
75 .build()
76 .unwrap_or_default();
77 self
78 }
79
80 pub fn with_dataset_dir<P: AsRef<Path>>(mut self, dir: P) -> Self {
81 self.dataset_dir = dir.as_ref().to_path_buf();
82 let _ = create_dir_all(&self.dataset_dir);
83 self
84 }
85
86 pub fn qualifies_for_cortex(commit_to_cortex: bool, passed: bool, score: f32) -> bool {
87 commit_to_cortex && passed && score >= Self::CORTEX_QUALIFICATION_THRESHOLD
88 }
89
90 pub fn build_cortex_payload(
91 name: &str,
92 canonical_name: &str,
93 content: &str,
94 task_id: &str,
95 confidence: f64,
96 ) -> serde_json::Value {
97 serde_json::json!({
98 "kind": "entity",
99 "value": {
100 "space": "atlas-memory",
101 "canonicalName": canonical_name,
102 "entityType": "learned_procedure",
103 "content": content,
104 "aliases": [name],
105 "confidence": confidence,
106 "metadata": {
107 "source": "spark-distill",
108 "taskId": task_id
109 }
110 }
111 })
112 }
113
114 pub fn parse_cortex_receipt(body: &serde_json::Value, fallback: &str) -> String {
115 body.pointer("/receipt/targetId")
116 .or_else(|| body.pointer("/receipt/id"))
117 .or_else(|| body.pointer("/receipt/target_id"))
118 .and_then(|v| v.as_str())
119 .unwrap_or(fallback)
120 .to_string()
121 }
122
123 pub fn filter_dpo_candidate<'a>(
124 chosen: &'a str,
125 rejected: Option<&'a str>,
126 preference_delta: f32,
127 ) -> Option<&'a str> {
128 rejected.filter(|rej| preference_delta > 0.0 && *rej != chosen)
129 }
130
131 pub async fn distill(&self, mut task: DistillTask) -> Result<DistillationRecord, String> {
132 task.prompt = crate::vault::sanitize_outbound_prompt(&task.prompt);
133 if let Some(ref sys) = task.system_prompt {
134 task.system_prompt = Some(crate::vault::sanitize_outbound_prompt(sys));
135 }
136
137 let mut messages = Vec::new();
138 if let Some(ref sys) = task.system_prompt {
139 messages.push(ChatMessage {
140 role: "system".to_string(),
141 content: crate::vault::sanitize_outbound_prompt(sys),
142 reasoning: None,
143 });
144 }
145 messages.push(ChatMessage {
146 role: "user".to_string(),
147 content: crate::vault::sanitize_outbound_prompt(&task.prompt),
148 reasoning: None,
149 });
150
151 // 1. Query Teacher Oracle
152 let (teacher_provider, teacher_endpoint, teacher_model_id, teacher_key) =
153 self.router.resolve_route(&task.teacher_model);
154
155 let t0 = Instant::now();
156 let (teacher_content, teacher_reasoning, teacher_tokens) = call_provider_unary(
157 &self.client,
158 teacher_provider,
159 &teacher_endpoint,
160 &teacher_model_id,
161 teacher_key.as_deref(),
162 &messages,
163 Some(0.7),
164 )
165 .await
166 .map_err(|e| format!("Teacher query failed ({}): {}", task.teacher_model, e))?;
167 let teacher_duration = t0.elapsed().as_millis() as u64;
168
169 let teacher_verif = Verifier::verify(&teacher_content, task.verification_strategy);
170
171 let teacher_rollout = Rollout {
172 provider: teacher_provider,
173 model_id: task.teacher_model.clone(),
174 content: teacher_content.clone(),
175 reasoning: teacher_reasoning.clone(),
176 duration_ms: teacher_duration,
177 token_count: teacher_tokens,
178 verification: teacher_verif.clone(),
179 };
180
181 // 2. Query Student (Local Open-Weight Resident Model)
182 let mut student_rollout = None;
183 let student_target = task
184 .student_model
185 .clone()
186 .unwrap_or_else(|| "atlas-lightning-omni".to_string());
187
188 let (student_provider, student_endpoint, student_model_id, student_key) =
189 self.router.resolve_route(&student_target);
190
191 let s0 = Instant::now();
192 match call_provider_unary(
193 &self.client,
194 student_provider,
195 &student_endpoint,
196 &student_model_id,
197 student_key.as_deref(),
198 &messages,
199 Some(0.7),
200 )
201 .await
202 {
203 Ok((student_content, student_reasoning, student_tokens)) => {
204 let student_duration = s0.elapsed().as_millis() as u64;
205 let student_verif = Verifier::verify(&student_content, task.verification_strategy);
206
207 student_rollout = Some(Rollout {
208 provider: student_provider,
209 model_id: student_target.clone(),
210 content: student_content,
211 reasoning: student_reasoning,
212 duration_ms: student_duration,
213 token_count: student_tokens,
214 verification: student_verif,
215 });
216 }
217 Err(e) => {
218 eprintln!(
219 "Warning: Student rollout failed ({}): {}",
220 student_target, e
221 );
222 }
223 }
224
225 // 3. Selection and Preference Logic
226 #[derive(Copy, Clone, PartialEq)]
227 enum ChosenSeat {
228 Teacher,
229 Student,
230 }
231
232 let mut chosen_seat = ChosenSeat::Teacher;
233 let mut chosen = teacher_content.clone();
234 let mut chosen_reasoning = teacher_reasoning.clone();
235 let mut chosen_score = teacher_rollout.verification.score;
236 let mut chosen_passed = teacher_rollout.verification.passed;
237 let mut rejected = None;
238 let mut rejected_reasoning = None;
239 let mut preference_delta = 0.0;
240
241 if let Some(ref s_roll) = student_rollout {
242 let t_pass = teacher_rollout.verification.passed;
243 let s_pass = s_roll.verification.passed;
244 let t_score = teacher_rollout.verification.score;
245 let s_score = s_roll.verification.score;
246
247 if s_pass && (!t_pass || s_score > t_score) {
248 // Student strictly outperformed teacher
249 chosen_seat = ChosenSeat::Student;
250 chosen = s_roll.content.clone();
251 chosen_reasoning = s_roll.reasoning.clone();
252 chosen_score = s_score;
253 chosen_passed = s_pass;
254 rejected = Some(teacher_content.clone());
255 rejected_reasoning = teacher_reasoning.clone();
256 preference_delta = s_score - t_score;
257 } else if t_pass && (!s_pass || t_score > s_score) {
258 // Teacher strictly outperformed student
259 chosen_seat = ChosenSeat::Teacher;
260 chosen = teacher_content.clone();
261 chosen_reasoning = teacher_reasoning.clone();
262 chosen_score = t_score;
263 chosen_passed = t_pass;
264 rejected = Some(s_roll.content.clone());
265 rejected_reasoning = s_roll.reasoning.clone();
266 preference_delta = t_score - s_score;
267 } else {
268 // Tie or both failed: default to teacher solution, record exact delta
269 chosen_seat = ChosenSeat::Teacher;
270 chosen = teacher_content.clone();
271 chosen_reasoning = teacher_reasoning.clone();
272 chosen_score = t_score;
273 chosen_passed = t_pass;
274 rejected = Some(s_roll.content.clone());
275 rejected_reasoning = s_roll.reasoning.clone();
276 preference_delta = (t_score - s_score).abs();
277 }
278 }
279
280 // 4. Persist to SFT and DPO Datasets
281 let valid_dpo_rejected =
282 Self::filter_dpo_candidate(&chosen, rejected.as_deref(), preference_delta);
283
284 self.persist_training_pair(
285 &task,
286 &chosen,
287 chosen_reasoning.as_deref(),
288 valid_dpo_rejected,
289 )?;
290
291 // 5. Commit Durable Knowledge to Spark Cortex if Verified
292 let mut durable_committed = false;
293 let mut cortex_id = None;
294
295 if Self::qualifies_for_cortex(task.commit_to_cortex, chosen_passed, chosen_score) {
296 let entity_name = format!("distill_lesson:{}_{}", task.id, Utc::now().timestamp());
297 let canonical = format!("distill_{}", task.id.replace('-', "_"));
298 let source_label = match chosen_seat {
299 ChosenSeat::Teacher => format!("Teacher Oracle ({})", task.teacher_model),
300 ChosenSeat::Student => format!("Student Model ({})", student_target),
301 };
302 let content_summary = format!(
303 "Distilled from {}. Task: {}. Reasoning: {}. Verified Solution: {}",
304 source_label,
305 task.prompt,
306 chosen_reasoning.as_deref().unwrap_or("<direct>"),
307 chosen
308 );
309
310 match self
311 .commit_to_cortex(
312 &entity_name,
313 &canonical,
314 &content_summary,
315 &task.id,
316 chosen_score as f64,
317 )
318 .await
319 {
320 Ok(id) => {
321 durable_committed = true;
322 cortex_id = Some(id);
323 }
324 Err(e) => {
325 eprintln!("Warning: Cortex commit failed: {}", e);
326 }
327 }
328 }
329
330 Ok(DistillationRecord {
331 task_id: task.id,
332 task_type: task.task_type,
333 prompt: task.prompt,
334 system_prompt: task.system_prompt,
335 teacher_rollout,
336 student_rollout,
337 chosen,
338 chosen_reasoning,
339 rejected,
340 rejected_reasoning,
341 preference_delta,
342 durable_memory_committed: durable_committed,
343 cortex_entity_id: cortex_id,
344 created_at: Utc::now().to_rfc3339(),
345 })
346 }
347
348 pub fn persist_training_pair(
349 &self,
350 task: &DistillTask,
351 chosen: &str,
352 chosen_reasoning: Option<&str>,
353 rejected: Option<&str>,
354 ) -> Result<bool, String> {
355 let _ = create_dir_all(&self.dataset_dir);
356
357 // Append SFT JSONL (ChatML format)
358 let sft_file = self.dataset_dir.join("sft.jsonl");
359 let mut sft_entry = json!({
360 "task_id": task.id,
361 "timestamp": Utc::now().to_rfc3339(),
362 "messages": [
363 { "role": "user", "content": task.prompt }
364 ]
365 });
366
367 if let Some(ref sys) = task.system_prompt {
368 if let Some(arr) = sft_entry.get_mut("messages").and_then(|m| m.as_array_mut()) {
369 arr.insert(0, json!({ "role": "system", "content": sys }));
370 }
371 }
372
373 let mut assistant_obj = json!({
374 "role": "assistant",
375 "content": chosen
376 });
377 if let Some(r) = chosen_reasoning {
378 assistant_obj["reasoning"] = json!(r);
379 }
380 if let Some(arr) = sft_entry.get_mut("messages").and_then(|m| m.as_array_mut()) {
381 arr.push(assistant_obj);
382 }
383
384 let mut file = OpenOptions::new()
385 .create(true)
386 .append(true)
387 .open(&sft_file)
388 .map_err(|e| format!("Failed to open sft.jsonl: {}", e))?;
389 writeln!(file, "{}", serde_json::to_string(&sft_entry).unwrap())
390 .map_err(|e| format!("Failed to write to sft.jsonl: {}", e))?;
391
392 // Append DPO JSONL if rejected pair exists
393 let mut dpo_written = false;
394 if let Some(rej) = rejected {
395 let dpo_file = self.dataset_dir.join("dpo.jsonl");
396 let dpo_entry = json!({
397 "task_id": task.id,
398 "prompt": task.prompt,
399 "system": task.system_prompt,
400 "chosen": chosen,
401 "rejected": rej,
402 "timestamp": Utc::now().to_rfc3339()
403 });
404
405 let mut d_file = OpenOptions::new()
406 .create(true)
407 .append(true)
408 .open(&dpo_file)
409 .map_err(|e| format!("Failed to open dpo.jsonl: {}", e))?;
410 writeln!(d_file, "{}", serde_json::to_string(&dpo_entry).unwrap())
411 .map_err(|e| format!("Failed to write to dpo.jsonl: {}", e))?;
412 dpo_written = true;
413 }
414
415 Ok(dpo_written)
416 }
417
418 pub async fn commit_to_cortex(
419 &self,
420 name: &str,
421 canonical_name: &str,
422 content: &str,
423 task_id: &str,
424 confidence: f64,
425 ) -> Result<String, String> {
426 let token = match crate::vault::resolve_secret("CORTEX_TOKEN") {
427 Some(tok) if !tok.is_empty() => tok,
428 _ => {
429 return Err(
430 "CORTEX_TOKEN not found: configure CORTEX_TOKEN in environment or register in atlas-vault"
431 .to_string(),
432 );
433 }
434 };
435
436 let endpoint =
437 std::env::var("CORTEX_ENDPOINT").unwrap_or_else(|_| self.cortex_endpoint.clone());
438 let url = format!("{}/api/cortex/write", endpoint);
439
440 let payload =
441 Self::build_cortex_payload(name, canonical_name, content, task_id, confidence);
442
443 let res = self
444 .client
445 .post(&url)
446 .header("Authorization", format!("Bearer {}", token))
447 .json(&payload)
448 .send()
449 .await
450 .map_err(|e| format!("Cortex request error: {}", e))?;
451
452 if !res.status().is_success() {
453 let status = res.status();
454 let body = res.text().await.unwrap_or_default();
455 return Err(format!("Cortex returned status {}: {}", status, body));
456 }
457
458 let body: serde_json::Value = res
459 .json()
460 .await
461 .map_err(|e| format!("Failed to parse Cortex response JSON: {}", e))?;
462
463 let entity_id = Self::parse_cortex_receipt(&body, canonical_name);
464
465 Ok(entity_id)
466 }
467}
468
469#[cfg(test)]
470mod tests {
471 use super::*;
472
473 #[tokio::test]
474 async fn test_commit_to_cortex_requires_token() {
475 let engine = DistillationEngine::new();
476 let res = engine
477 .commit_to_cortex("test", "test_canonical", "content", "task-1", 0.9)
478 .await;
479 if let Err(e) = res {
480 assert!(
481 e.contains("CORTEX_TOKEN not found")
482 || e.contains("Cortex request error")
483 || e.contains("Cortex returned status")
484 );
485 }
486 }
487}