interplane.Get Omega
Read in your language

spark-rsi-mv

Native Rust recursive self-improvement engine with paired bootstrap evaluation and cryptographic ledger

Brought by drakestapleton

branch main Branches Tags History

spark-rsi-mv / src / measure / profile.rs

268 lines · 8924 bytes Raw Blame History
1//! Workload key and execution-profile fingerprint.
2//!
3//! Effective execution configuration: the `RsiConfig` fields that change what the stages do or
4//! which services they call, so two cycles with different values are not comparable:
5//! - `model_url` (the inference endpoint Propose calls)
6//! - the effective holdouts directory (the judge's workload)
7//! - `canary_target` (how many canary observations the canary stage needs)
8//! - `cortex_url` and `cortex_space` (what CortexCommit writes to)
9//! - `ratify_roots` (sorted; the scope of candidates that reach the stages)
10//!
11//! Left out on purpose: secrets (signing and operator keys), `require_latency_improvement`,
12//! `non_inferiority_margin` and the judge policy fields (evaluation policy, not execution
13//! mode), `loop_interval_secs` (scheduling), `sandbox_root` and `rsi_root` (locations), the
14//! `measure_*` fields (how to read samples) and `dual_price_vector_dir` (diagnostic only).
15
16use crate::models::RsiConfig;
17use serde::{Deserialize, Serialize};
18use sha2::{Digest, Sha256};
19use std::io::Read;
20use std::path::Path;
21use std::process::{Command, Stdio};
22use std::time::{Duration, Instant};
23
24#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
25#[serde(deny_unknown_fields)]
26pub struct ExecutionConfig {
27 pub model_url: String,
28 pub holdouts_dir: String,
29 pub canary_target: u64,
30 pub cortex_url: String,
31 pub cortex_space: String,
32 pub ratify_roots: Vec<String>,
33}
34
35impl ExecutionConfig {
36 pub fn from_config(config: &RsiConfig) -> Self {
37 let mut ratify_roots = config.ratify_roots.clone();
38 ratify_roots.sort();
39 ratify_roots.dedup();
40 Self {
41 model_url: config.model_url.clone(),
42 holdouts_dir: config
43 .holdouts_dir
44 .clone()
45 .unwrap_or_else(|| format!("{}/holdouts", config.rsi_root)),
46 canary_target: config.canary_target,
47 cortex_url: config.cortex_url.clone(),
48 cortex_space: config.cortex_space.clone(),
49 ratify_roots,
50 }
51 }
52
53 fn canonical(&self) -> String {
54 format!(
55 "model_url={}\nholdouts_dir={}\ncanary_target={}\ncortex_url={}\ncortex_space={}\nratify_roots={}\n",
56 self.model_url,
57 self.holdouts_dir,
58 self.canary_target,
59 self.cortex_url,
60 self.cortex_space,
61 self.ratify_roots.join(",")
62 )
63 }
64}
65
66/// Machine and configuration identity stamped on every sample.
67#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
68#[serde(deny_unknown_fields)]
69pub struct ExecutionProfile {
70 pub model: String,
71 pub execution_config: ExecutionConfig,
72 /// None when the platform would not say. Distinct from every real count.
73 pub cpu_count: Option<usize>,
74 pub memory_total_kib: Option<u64>,
75 /// GPU names from nvidia-smi joined with ";", or the literal "none".
76 pub gpu: String,
77}
78
79fn digest_hex(domain: &str, body: &str) -> String {
80 let mut h = Sha256::new();
81 h.update(domain.as_bytes());
82 h.update(b"\n");
83 h.update(body.as_bytes());
84 hex::encode(h.finalize())
85}
86
87fn opt<T: ToString>(v: &Option<T>) -> String {
88 v.as_ref()
89 .map(|x| x.to_string())
90 .unwrap_or_else(|| "unknown".to_string())
91}
92
93impl ExecutionProfile {
94 pub fn fingerprint(&self) -> String {
95 digest_hex(
96 "spark-rsi/measure/execution-profile/v1",
97 &format!(
98 "model={}\n{}cpu_count={}\nmemory_total_kib={}\ngpu={}\n",
99 self.model,
100 self.execution_config.canonical(),
101 opt(&self.cpu_count),
102 opt(&self.memory_total_kib),
103 self.gpu
104 ),
105 )
106 }
107
108 pub fn detect(config: &RsiConfig) -> Self {
109 Self {
110 model: config.model_id.clone(),
111 execution_config: ExecutionConfig::from_config(config),
112 cpu_count: std::thread::available_parallelism().ok().map(|n| n.get()),
113 memory_total_kib: read_mem_total_kib("/proc/meminfo"),
114 gpu: probe_gpu(Duration::from_secs(3)),
115 }
116 }
117}
118
119/// MemTotal in KiB from a meminfo-format file.
120pub fn read_mem_total_kib(path: &str) -> Option<u64> {
121 let text = std::fs::read_to_string(path).ok()?;
122 let line = text.lines().find(|l| l.starts_with("MemTotal:"))?;
123 line.split_whitespace().nth(1)?.parse().ok()
124}
125
126/// GPU identity from nvidia-smi, or "none" when absent, failing or slower than `timeout`.
127pub fn probe_gpu(timeout: Duration) -> String {
128 let Ok(mut child) = Command::new("nvidia-smi")
129 .args(["--query-gpu=name", "--format=csv,noheader"])
130 .stdin(Stdio::null())
131 .stdout(Stdio::piped())
132 .stderr(Stdio::null())
133 .spawn()
134 else {
135 return "none".to_string();
136 };
137 let deadline = Instant::now() + timeout;
138 loop {
139 match child.try_wait() {
140 Ok(Some(status)) => {
141 if !status.success() {
142 return "none".to_string();
143 }
144 let mut out = String::new();
145 if let Some(mut so) = child.stdout.take() {
146 let _ = so.read_to_string(&mut out);
147 }
148 let names: Vec<&str> = out
149 .lines()
150 .map(str::trim)
151 .filter(|l| !l.is_empty())
152 .collect();
153 return if names.is_empty() {
154 "none".to_string()
155 } else {
156 names.join(";")
157 };
158 }
159 Ok(None) if Instant::now() < deadline => std::thread::sleep(Duration::from_millis(20)),
160 _ => {
161 let _ = child.kill();
162 let _ = child.wait();
163 return "none".to_string();
164 }
165 }
166 }
167}
168
169/// Remote URL without credentials or trailing `.git` and `/`, or the canonical absolute path.
170pub fn repo_identity(repo: &Path) -> String {
171 let remote = Command::new("git")
172 .arg("-C")
173 .arg(repo)
174 .args(["config", "--get", "remote.origin.url"])
175 .stdin(Stdio::null())
176 .stderr(Stdio::null())
177 .output()
178 .ok()
179 .filter(|o| o.status.success())
180 .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
181 .filter(|u| !u.is_empty());
182 match remote {
183 Some(url) => format!("remote:{}", normalize_remote(&url)),
184 None => {
185 let abs = std::fs::canonicalize(repo).unwrap_or_else(|_| repo.to_path_buf());
186 format!("path:{}", abs.display())
187 }
188 }
189}
190
191pub fn normalize_remote(url: &str) -> String {
192 let mut u = url.trim().to_string();
193 if let Some(scheme_end) = u.find("://") {
194 let rest_start = scheme_end + 3;
195 let authority_end = u[rest_start..]
196 .find('/')
197 .map(|i| rest_start + i)
198 .unwrap_or(u.len());
199 if let Some(at) = u[rest_start..authority_end].rfind('@') {
200 u.replace_range(rest_start..rest_start + at + 1, "");
201 }
202 }
203 while u.ends_with('/') {
204 u.pop();
205 }
206 if let Some(stripped) = u.strip_suffix(".git") {
207 u = stripped.to_string();
208 }
209 u
210}
211
212pub fn head_commit(repo: &Path) -> Option<String> {
213 Command::new("git")
214 .arg("-C")
215 .arg(repo)
216 .args(["rev-parse", "HEAD"])
217 .stdin(Stdio::null())
218 .stderr(Stdio::null())
219 .output()
220 .ok()
221 .filter(|o| o.status.success())
222 .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
223 .filter(|c| !c.is_empty())
224}
225
226/// What a cycle needs to read prior samples and write its own.
227#[derive(Debug, Clone)]
228pub struct MeasureContext {
229 pub workload_key: String,
230 pub profile: ExecutionProfile,
231 pub fingerprint: String,
232 pub source_commit: Option<String>,
233}
234
235impl MeasureContext {
236 pub fn for_config(config: &RsiConfig, repo: &Path) -> Self {
237 Self::from_parts(
238 &repo_identity(repo),
239 ExecutionProfile::detect(config),
240 head_commit(repo),
241 )
242 }
243
244 /// Workload key: repository identity, effective execution configuration, model name.
245 /// The target commit is deliberately absent.
246 pub fn from_parts(
247 repo_identity: &str,
248 profile: ExecutionProfile,
249 source_commit: Option<String>,
250 ) -> Self {
251 let workload_key = digest_hex(
252 "spark-rsi/measure/workload-key/v1",
253 &format!(
254 "repo={}\n{}model={}\n",
255 repo_identity,
256 profile.execution_config.canonical(),
257 profile.model
258 ),
259 );
260 let fingerprint = profile.fingerprint();
261 Self {
262 workload_key,
263 profile,
264 fingerprint,
265 source_commit,
266 }
267 }
268}