spark-adapters
Hardware abstraction adapters for local AI accelerators
Brought by drakestapleton
spark-adapters / src / distill.rs
| 1 | use crate::models::{ |
| 2 | ChatMessage, DistillTask, DistillationRecord, Rollout, |
| 3 | }; |
| 4 | use crate::providers::call_provider_unary; |
| 5 | use crate::router::AdapterRouter; |
| 6 | use crate::verifier::Verifier; |
| 7 | use chrono::Utc; |
| 8 | use reqwest::Client; |
| 9 | use serde_json::json; |
| 10 | use std::fs::{create_dir_all, OpenOptions}; |
| 11 | use std::io::Write; |
| 12 | use std::path::{Path, PathBuf}; |
| 13 | use std::time::Instant; |
| 14 | |
| 15 | pub struct DistillationEngine { |
| 16 | pub client: Client, |
| 17 | pub router: AdapterRouter, |
| 18 | pub dataset_dir: PathBuf, |
| 19 | pub cortex_endpoint: String, |
| 20 | } |
| 21 | |
| 22 | impl DistillationEngine { |
| 23 | pub fn new() -> Self { |
| 24 | let default_dir = PathBuf::from("/home/drakestapleton/workspace/distillation-data"); |
| 25 | let _ = create_dir_all(&default_dir); |
| 26 | |
| 27 | Self { |
| 28 | client: Client::builder().build().unwrap_or_default(), |
| 29 | router: AdapterRouter::new(), |
| 30 | dataset_dir: default_dir, |
| 31 | cortex_endpoint: "http://127.0.0.1:18080".to_string(), |
| 32 | } |
| 33 | } |
| 34 | |
| 35 | pub fn with_dataset_dir<P: AsRef<Path>>(mut self, dir: P) -> Self { |
| 36 | self.dataset_dir = dir.as_ref().to_path_buf(); |
| 37 | let _ = create_dir_all(&self.dataset_dir); |
| 38 | self |
| 39 | } |
| 40 | |
| 41 | pub async fn distill(&self, task: DistillTask) -> Result<DistillationRecord, String> { |
| 42 | let mut messages = Vec::new(); |
| 43 | if let Some(ref sys) = task.system_prompt { |
| 44 | messages.push(ChatMessage { |
| 45 | role: "system".to_string(), |
| 46 | content: sys.clone(), |
| 47 | reasoning: None, |
| 48 | }); |
| 49 | } |
| 50 | messages.push(ChatMessage { |
| 51 | role: "user".to_string(), |
| 52 | content: task.prompt.clone(), |
| 53 | reasoning: None, |
| 54 | }); |
| 55 | |
| 56 | // 1. Query Teacher Oracle |
| 57 | let (teacher_provider, teacher_endpoint, teacher_model_id, teacher_key) = |
| 58 | self.router.resolve_route(&task.teacher_model); |
| 59 | |
| 60 | let t0 = Instant::now(); |
| 61 | let (teacher_content, teacher_reasoning, teacher_tokens) = call_provider_unary( |
| 62 | &self.client, |
| 63 | teacher_provider, |
| 64 | &teacher_endpoint, |
| 65 | &teacher_model_id, |
| 66 | teacher_key.as_deref(), |
| 67 | &messages, |
| 68 | Some(0.7), |
| 69 | ) |
| 70 | .await |
| 71 | .map_err(|e| format!("Teacher query failed ({}): {}", task.teacher_model, e))?; |
| 72 | let teacher_duration = t0.elapsed().as_millis() as u64; |
| 73 | |
| 74 | let teacher_verif = Verifier::verify(&teacher_content, task.verification_strategy); |
| 75 | |
| 76 | let teacher_rollout = Rollout { |
| 77 | provider: teacher_provider, |
| 78 | model_id: task.teacher_model.clone(), |
| 79 | content: teacher_content.clone(), |
| 80 | reasoning: teacher_reasoning.clone(), |
| 81 | duration_ms: teacher_duration, |
| 82 | token_count: teacher_tokens, |
| 83 | verification: teacher_verif.clone(), |
| 84 | }; |
| 85 | |
| 86 | // 2. Query Student (Local Open-Weight Resident Model) |
| 87 | let mut student_rollout = None; |
| 88 | let student_target = task.student_model.clone().unwrap_or_else(|| "atlas-lightning-omni".to_string()); |
| 89 | |
| 90 | let (student_provider, student_endpoint, student_model_id, student_key) = |
| 91 | self.router.resolve_route(&student_target); |
| 92 | |
| 93 | let s0 = Instant::now(); |
| 94 | if let Ok((student_content, student_reasoning, student_tokens)) = call_provider_unary( |
| 95 | &self.client, |
| 96 | student_provider, |
| 97 | &student_endpoint, |
| 98 | &student_model_id, |
| 99 | student_key.as_deref(), |
| 100 | &messages, |
| 101 | Some(0.7), |
| 102 | ) |
| 103 | .await |
| 104 | { |
| 105 | let student_duration = s0.elapsed().as_millis() as u64; |
| 106 | let student_verif = Verifier::verify(&student_content, task.verification_strategy); |
| 107 | |
| 108 | student_rollout = Some(Rollout { |
| 109 | provider: student_provider, |
| 110 | model_id: student_target.clone(), |
| 111 | content: student_content, |
| 112 | reasoning: student_reasoning, |
| 113 | duration_ms: student_duration, |
| 114 | token_count: student_tokens, |
| 115 | verification: student_verif, |
| 116 | }); |
| 117 | } |
| 118 | |
| 119 | // 3. Selection & Preference Logic |
| 120 | let mut chosen = teacher_content.clone(); |
| 121 | let mut chosen_reasoning = teacher_reasoning.clone(); |
| 122 | let mut rejected = None; |
| 123 | let mut rejected_reasoning = None; |
| 124 | let mut preference_delta = 0.0; |
| 125 | |
| 126 | if let Some(ref s_roll) = student_rollout { |
| 127 | preference_delta = teacher_rollout.verification.score - s_roll.verification.score; |
| 128 | if teacher_rollout.verification.passed && (!s_roll.verification.passed || teacher_rollout.verification.score >= s_roll.verification.score) { |
| 129 | chosen = teacher_content.clone(); |
| 130 | chosen_reasoning = teacher_reasoning.clone(); |
| 131 | rejected = Some(s_roll.content.clone()); |
| 132 | rejected_reasoning = s_roll.reasoning.clone(); |
| 133 | } else if s_roll.verification.passed && !teacher_rollout.verification.passed { |
| 134 | chosen = s_roll.content.clone(); |
| 135 | chosen_reasoning = s_roll.reasoning.clone(); |
| 136 | rejected = Some(teacher_content.clone()); |
| 137 | rejected_reasoning = teacher_reasoning.clone(); |
| 138 | } else { |
| 139 | chosen = teacher_content.clone(); |
| 140 | rejected = Some(s_roll.content.clone()); |
| 141 | } |
| 142 | } |
| 143 | |
| 144 | // 4. Persist to SFT and DPO Datasets |
| 145 | self.persist_training_pair(&task, &chosen, chosen_reasoning.as_deref(), rejected.as_deref())?; |
| 146 | |
| 147 | // 5. Commit Durable Knowledge to Spark Cortex if Verified |
| 148 | let mut durable_committed = false; |
| 149 | let mut cortex_id = None; |
| 150 | |
| 151 | if task.commit_to_cortex && teacher_rollout.verification.passed && teacher_rollout.verification.score >= 0.85 { |
| 152 | let entity_name = format!("distill_lesson:{}_{}", task.id, Utc::now().timestamp()); |
| 153 | let canonical = format!("distill_{}", task.id.replace('-', "_")); |
| 154 | let content_summary = format!( |
| 155 | "Distilled from Teacher Oracle {}. Task: {}. Reasoning: {}. Verified Solution: {}", |
| 156 | task.teacher_model, |
| 157 | task.prompt, |
| 158 | teacher_reasoning.as_deref().unwrap_or("<direct>"), |
| 159 | chosen |
| 160 | ); |
| 161 | |
| 162 | if let Ok(id) = self.commit_to_cortex(&entity_name, &canonical, &content_summary).await { |
| 163 | durable_committed = true; |
| 164 | cortex_id = Some(id); |
| 165 | } |
| 166 | } |
| 167 | |
| 168 | Ok(DistillationRecord { |
| 169 | task_id: task.id, |
| 170 | task_type: task.task_type, |
| 171 | prompt: task.prompt, |
| 172 | system_prompt: task.system_prompt, |
| 173 | teacher_rollout, |
| 174 | student_rollout, |
| 175 | chosen, |
| 176 | chosen_reasoning, |
| 177 | rejected, |
| 178 | rejected_reasoning, |
| 179 | preference_delta, |
| 180 | durable_memory_committed: durable_committed, |
| 181 | cortex_entity_id: cortex_id, |
| 182 | created_at: Utc::now().to_rfc3339(), |
| 183 | }) |
| 184 | } |
| 185 | |
| 186 | fn persist_training_pair( |
| 187 | &self, |
| 188 | task: &DistillTask, |
| 189 | chosen: &str, |
| 190 | chosen_reasoning: Option<&str>, |
| 191 | rejected: Option<&str>, |
| 192 | ) -> Result<(), String> { |
| 193 | let _ = create_dir_all(&self.dataset_dir); |
| 194 | |
| 195 | // Append SFT JSONL (ChatML format) |
| 196 | let sft_file = self.dataset_dir.join("sft.jsonl"); |
| 197 | let mut sft_entry = json!({ |
| 198 | "task_id": task.id, |
| 199 | "timestamp": Utc::now().to_rfc3339(), |
| 200 | "messages": [ |
| 201 | { "role": "user", "content": task.prompt } |
| 202 | ] |
| 203 | }); |
| 204 | |
| 205 | if let Some(ref sys) = task.system_prompt { |
| 206 | if let Some(arr) = sft_entry.get_mut("messages").and_then(|m| m.as_array_mut()) { |
| 207 | arr.insert(0, json!({ "role": "system", "content": sys })); |
| 208 | } |
| 209 | } |
| 210 | |
| 211 | let mut assistant_obj = json!({ |
| 212 | "role": "assistant", |
| 213 | "content": chosen |
| 214 | }); |
| 215 | if let Some(r) = chosen_reasoning { |
| 216 | assistant_obj["reasoning"] = json!(r); |
| 217 | } |
| 218 | sft_entry.get_mut("messages").and_then(|m| m.as_array_mut()).map(|arr| arr.push(assistant_obj)); |
| 219 | |
| 220 | let mut file = OpenOptions::new() |
| 221 | .create(true) |
| 222 | .append(true) |
| 223 | .open(&sft_file) |
| 224 | .map_err(|e| format!("Failed to open sft.jsonl: {}", e))?; |
| 225 | writeln!(file, "{}", serde_json::to_string(&sft_entry).unwrap()) |
| 226 | .map_err(|e| format!("Failed to write to sft.jsonl: {}", e))?; |
| 227 | |
| 228 | // Append DPO JSONL if rejected pair exists |
| 229 | if let Some(rej) = rejected { |
| 230 | let dpo_file = self.dataset_dir.join("dpo.jsonl"); |
| 231 | let dpo_entry = json!({ |
| 232 | "task_id": task.id, |
| 233 | "prompt": task.prompt, |
| 234 | "system": task.system_prompt, |
| 235 | "chosen": chosen, |
| 236 | "rejected": rej, |
| 237 | "timestamp": Utc::now().to_rfc3339() |
| 238 | }); |
| 239 | |
| 240 | let mut d_file = OpenOptions::new() |
| 241 | .create(true) |
| 242 | .append(true) |
| 243 | .open(&dpo_file) |
| 244 | .map_err(|e| format!("Failed to open dpo.jsonl: {}", e))?; |
| 245 | writeln!(d_file, "{}", serde_json::to_string(&dpo_entry).unwrap()) |
| 246 | .map_err(|e| format!("Failed to write to dpo.jsonl: {}", e))?; |
| 247 | } |
| 248 | |
| 249 | Ok(()) |
| 250 | } |
| 251 | |
| 252 | async fn commit_to_cortex( |
| 253 | &self, |
| 254 | name: &str, |
| 255 | canonical_name: &str, |
| 256 | content: &str, |
| 257 | ) -> Result<String, String> { |
| 258 | let token_path = PathBuf::from("/home/drakestapleton/.config/cortex/token"); |
| 259 | let token = std::fs::read_to_string(token_path) |
| 260 | .map(|s| s.trim().to_string()) |
| 261 | .unwrap_or_default(); |
| 262 | |
| 263 | let url = format!("{}/spaces/atlas-memory/entities", self.cortex_endpoint); |
| 264 | let payload = json!({ |
| 265 | "name": name, |
| 266 | "type": "learned_procedure", |
| 267 | "canonicalName": canonical_name, |
| 268 | "content": content |
| 269 | }); |
| 270 | |
| 271 | let res = self.client |
| 272 | .post(&url) |
| 273 | .header("Authorization", format!("Bearer {}", token)) |
| 274 | .json(&payload) |
| 275 | .send() |
| 276 | .await |
| 277 | .map_err(|e| format!("Cortex request error: {}", e))?; |
| 278 | |
| 279 | if !res.status().is_success() { |
| 280 | return Err(format!("Cortex returned status {}", res.status())); |
| 281 | } |
| 282 | |
| 283 | let body: serde_json::Value = res.json().await.unwrap_or_default(); |
| 284 | let entity_id = body.get("id").and_then(|v| v.as_str()).unwrap_or(name).to_string(); |
| 285 | Ok(entity_id) |
| 286 | } |
| 287 | } |