Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aien-protocols-mv/blob/main/crates/aien-probe/src/backend.rs # aien-protocols-mv Canonical specifications, wire protocols, and schemas for the AIEN sovereign ecosystem Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aien-protocols-mv / crates / aien-probe / src / backend.rs` 304 lines ยท 9971 bytes Raw Blame History 1 //! Probe backends. 2 //! 3 //! A backend turns a state and a probe set into calibrated answers. Two backends ship here: a 4 //! deterministic in process reference oracle, and an HTTP client for an AIEN inference service. 5 6 use crate::math; 7 use crate::{ 8 canonicalize, Answer, ChoiceAnswer, NoulAnswer, Probe, ProbeError, ProbeResponse, ProbeSet, 9 ScoreAnswer, 10 }; 11 use async_trait::async_trait; 12 use serde::{Deserialize, Serialize}; 13 use serde_json::Value; 14 use sha2::{Digest, Sha256}; 15 use std::cmp::Ordering; 16 17 /// A source of calibrated probe answers. 18 #[async_trait] 19 pub trait ProbeBackend: Send + Sync { 20 /// A human readable name for the backend. 21 fn name(&self) -> &str; 22 23 /// Evaluates every probe against the state. 24 async fn evaluate(&self, state: &Value, probes: &ProbeSet) 25 -> Result; 26 } 27 28 /// A deterministic, in process reference oracle. 29 /// 30 /// This backend runs no model and opens no socket. It derives a logit for every question from a 31 /// SHA-256 feature hash of the canonical state and the question label, then applies the same 32 /// calibration math the device path uses. Given the same state and probes it always returns the 33 /// same answers, which makes it the conformance oracle for tests and continuous integration. 34 /// 35 /// It is a reference oracle, not a trained calibrator. For calibrated judgments on real content, 36 /// point [`HttpProbeBackend`] at an AIEN inference service on the GB10. 37 pub struct DeterministicReferenceBackend { 38 temperature: f64, 39 } 40 41 impl DeterministicReferenceBackend { 42 /// A reference oracle at the default temperature of one. 43 pub fn new() -> Self { 44 Self { temperature: 1.0 } 45 } 46 47 /// A reference oracle at a chosen temperature. 48 pub fn with_temperature(temperature: f64) -> Self { 49 Self { temperature } 50 } 51 52 /// The temperature in use. 53 pub fn temperature(&self) -> f64 { 54 self.temperature 55 } 56 57 fn logit(seed: &[u8], label: &[u8], temperature: f64) -> f64 { 58 let mut hasher = Sha256::new(); 59 hasher.update(seed); 60 hasher.update([0u8]); 61 hasher.update(label); 62 let digest: [u8; 32] = hasher.finalize().into(); 63 let raw = u64::from_le_bytes(digest[..8].try_into().expect("eight bytes")); 64 let unit = (raw as f64) / ((u64::MAX as f64) + 1.0); 65 let centered = unit * 2.0 - 1.0; 66 math::temperature_scale(centered * 4.0, temperature) 67 } 68 69 fn state_seed(state: &Value) -> Result<[u8; 32], ProbeError> { 70 let canonical = serde_json::to_vec(&canonicalize(state)) 71 .map_err(|e| ProbeError::Serialization(e.to_string()))?; 72 let mut hasher = Sha256::new(); 73 hasher.update(b"aien-probe-state-v1"); 74 hasher.update(canonical); 75 Ok(hasher.finalize().into()) 76 } 77 78 fn probe_seed(state_seed: &[u8; 32], id: &str) -> [u8; 32] { 79 let mut hasher = Sha256::new(); 80 hasher.update(state_seed); 81 hasher.update([0u8]); 82 hasher.update(id.as_bytes()); 83 hasher.finalize().into() 84 } 85 86 fn answer_noul(&self, seed: &[u8; 32]) -> Answer { 87 let z_yes = Self::logit(seed, b"noul:yes", self.temperature); 88 let z_no = Self::logit(seed, b"noul:no", self.temperature); 89 Answer::Noul(NoulAnswer { 90 noul: math::sigmoid(z_yes - z_no), 91 }) 92 } 93 94 fn answer_score(&self, seed: &[u8; 32], criteria: &[String]) -> Answer { 95 let logits: Vec = (0..criteria.len()) 96 .map(|level| { 97 let label = format!("score:{level}"); 98 Self::logit(seed, label.as_bytes(), self.temperature) 99 }) 100 .collect(); 101 let probabilities = math::softmax(&logits); 102 let score = math::expected_value(&probabilities); 103 let confidence = math::confidence(&probabilities); 104 let legend = criteria 105 .iter() 106 .enumerate() 107 .map(|(level, criterion)| (level as u32, criterion.clone())) 108 .collect(); 109 let by_level = probabilities 110 .iter() 111 .enumerate() 112 .map(|(level, probability)| (level as u32, *probability)) 113 .collect(); 114 Answer::Score(ScoreAnswer { 115 score, 116 confidence, 117 legend, 118 probabilities: by_level, 119 }) 120 } 121 122 fn answer_choice(&self, seed: &[u8; 32], options: &[crate::ChoiceOption]) -> Answer { 123 let logits: Vec = options 124 .iter() 125 .map(|option| { 126 let label = format!("choice:{}", option.id); 127 Self::logit(seed, label.as_bytes(), self.temperature) 128 }) 129 .collect(); 130 let probabilities = math::softmax(&logits); 131 let confidence = math::confidence(&probabilities); 132 let best = probabilities 133 .iter() 134 .enumerate() 135 .max_by(|a, b| a.1.partial_cmp(b.1).unwrap_or(Ordering::Equal)) 136 .map(|(index, _)| index) 137 .unwrap_or(0); 138 let choice = options 139 .get(best) 140 .map(|option| option.id.clone()) 141 .unwrap_or_default(); 142 let by_option = options 143 .iter() 144 .enumerate() 145 .map(|(index, option)| (option.id.clone(), probabilities[index])) 146 .collect(); 147 Answer::Choice(ChoiceAnswer { 148 choice, 149 confidence, 150 probabilities: by_option, 151 }) 152 } 153 } 154 155 impl Default for DeterministicReferenceBackend { 156 fn default() -> Self { 157 Self::new() 158 } 159 } 160 161 #[async_trait] 162 impl ProbeBackend for DeterministicReferenceBackend { 163 fn name(&self) -> &str { 164 "deterministic-reference-oracle" 165 } 166 167 async fn evaluate( 168 &self, 169 state: &Value, 170 probes: &ProbeSet, 171 ) -> Result { 172 let state_seed = Self::state_seed(state)?; 173 let mut answers = Vec::with_capacity(probes.len()); 174 175 for (id, probe) in probes.iter() { 176 let seed = Self::probe_seed(&state_seed, id); 177 let answer = match probe { 178 Probe::Noul(_) => self.answer_noul(&seed), 179 Probe::Score(score) => self.answer_score(&seed, &score.criteria), 180 Probe::Choice(choice) => self.answer_choice(&seed, &choice.options), 181 }; 182 answers.push((id.clone(), answer)); 183 } 184 185 Ok(ProbeResponse { 186 model: self.name().to_string(), 187 answers, 188 latency_micros: 0, 189 }) 190 } 191 } 192 193 /// Wire request for the AIEN probe endpoint. 194 #[derive(Serialize)] 195 struct WireRequest<'a> { 196 state: &'a Value, 197 probes: &'a ProbeSet, 198 } 199 200 /// Wire response from the AIEN probe endpoint. 201 #[derive(Deserialize)] 202 struct WireResponse { 203 #[serde(default)] 204 model: String, 205 answers: Vec<(String, Answer)>, 206 } 207 208 /// An HTTP client for an AIEN inference service that taps logits on the device. 209 /// 210 /// The service exposes `POST /v1/probe` taking `{ "state": ..., "probes": ... }` and 211 /// returning `{ "model": ..., "answers": [[id, answer], ...] }`. On the GB10 the service prefills 212 /// the state into the paged KV cache once, forks one copy on write branch per probe, and reads 213 /// the calibrated distribution from a single forward step. 214 pub struct HttpProbeBackend { 215 client: reqwest::Client, 216 endpoint: String, 217 model: String, 218 } 219 220 impl HttpProbeBackend { 221 /// Builds a backend for an endpoint and model name. 222 pub fn with_endpoint(endpoint: impl Into, model: impl Into) -> Self { 223 Self { 224 client: reqwest::Client::new(), 225 endpoint: endpoint.into(), 226 model: model.into(), 227 } 228 } 229 230 /// Builds a backend for an endpoint with the default model name. 231 pub fn new(endpoint: impl Into) -> Self { 232 Self::with_endpoint(endpoint, "aien-sovereign-probe") 233 } 234 235 /// Builds a backend from `AIEN_PROBE_ENDPOINT` and `AIEN_PROBE_MODEL`. 236 pub fn from_env() -> Result { 237 let endpoint = std::env::var("AIEN_PROBE_ENDPOINT") 238 .map_err(|_| ProbeError::Evaluation("AIEN_PROBE_ENDPOINT is not set".to_string()))?; 239 let model = std::env::var("AIEN_PROBE_MODEL") 240 .unwrap_or_else(|_| "aien-sovereign-probe".to_string()); 241 Ok(Self::with_endpoint(endpoint, model)) 242 } 243 244 /// The endpoint in use. 245 pub fn endpoint(&self) -> &str { 246 &self.endpoint 247 } 248 249 fn probe_url(&self) -> String { 250 format!("{}/v1/probe", self.endpoint.trim_end_matches('/')) 251 } 252 } 253 254 #[async_trait] 255 impl ProbeBackend for HttpProbeBackend { 256 fn name(&self) -> &str { 257 "aien-http-probe" 258 } 259 260 async fn evaluate( 261 &self, 262 state: &Value, 263 probes: &ProbeSet, 264 ) -> Result { 265 let body = WireRequest { state, probes }; 266 let response = self 267 .client 268 .post(self.probe_url()) 269 .json(&body) 270 .send() 271 .await 272 .map_err(|e| ProbeError::Transport(e.to_string()))?; 273 274 let status = response.status(); 275 let text = response 276 .text() 277 .await 278 .map_err(|e| ProbeError::Transport(e.to_string()))?; 279 280 if !status.is_success() { 281 return Err(ProbeError::Status { 282 status: status.as_u16(), 283 body: text.chars().take(400).collect(), 284 }); 285 } 286 287 let parsed: WireResponse = serde_json::from_str(&text).map_err(|e| { 288 ProbeError::Malformed(format!( 289 "{e}; body: {}", 290 text.chars().take(200).collect::() 291 )) 292 })?; 293 294 Ok(ProbeResponse { 295 model: if parsed.model.is_empty() { 296 self.model.clone() 297 } else { 298 parsed.model 299 }, 300 answers: parsed.answers, 301 latency_micros: 0, 302 }) 303 } 304 }