feat(app): place the LLM's experts so the speech-to-text worker keeps its room

- with an NVIDIA card the app sets --expert-vram itself by the M0 kit's formula: what the card
  holds before the start, the model without experts, the STT worker's share (2740 MiB), the
  engine's margin (768 MiB) and room for programs opened later (game.otherRoomGb, default 1 GB)
  are left free; Strata's own placement filled the card and left the STT no room
- the model without experts is measured once per context and card (a start with
  expert-vram=0, one short answer, the card's memory and the engine log's staging), kept in
  config/llm-probe.json; the real start replaces that server
- placement.rs also works out the game placement (the reserve, else the 2 GiB minimum and the
  room a game really gets, else pause) for the switching that comes next
- with the game PC's M0 numbers the normal placement comes out at 1.5 GiB, as M0 measured

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
javis-bot
2026-11-14 09:53:20 +09:00
parent 7e83b09dd5
commit af6f2c855d
9 changed files with 333 additions and 21 deletions

View File

@@ -49,7 +49,7 @@ pub fn parallel(settings: &Settings) -> u32 {
/// `strata launch` for the services: the M0 kit's normal placement, models in `models/llm`, this
/// computer only. No pictures yet (nothing in v2 sends one; reading them takes graphics memory).
/// `--restart` replaces a server started with other choices; the same choices are reused.
pub fn launch_args(layout: &Layout, settings: &Settings) -> Vec<String> {
pub fn launch_args(layout: &Layout, settings: &Settings, sets: &[String]) -> Vec<String> {
let models = layout.data.join("models").join("llm").to_string_lossy().into_owned();
let mut a: Vec<String> = ["launch", "--family", FAMILY, "--model", MODEL, "--data-dir"].map(String::from).into();
a.push(models);
@@ -60,9 +60,59 @@ pub fn launch_args(layout: &Layout, settings: &Settings) -> Vec<String> {
a.push(v);
}
a.extend(["--no-api-key", "--restart", "--yes", "--no-tui"].map(String::from));
for s in sets {
a.push("--set".into());
a.push(s.clone());
}
a
}
/// The engine settings for an expert budget (`placement.rs`) and the M0 kit's prompt chunk.
fn placement_sets(expert_gib: f64) -> Vec<String> {
vec![format!("expert-vram={expert_gib}"), "prefill=2048".into()]
}
/// Graphics memory `(used, total)` in MiB of the first NVIDIA card, from `nvidia-smi`; None without one.
pub type GpuReader = Arc<dyn Fn() -> Option<(i64, i64)> + Send + Sync>;
fn nvidia_memory() -> Option<(i64, i64)> {
let mut cmd = std::process::Command::new("nvidia-smi");
cmd.args(["--query-gpu=memory.used,memory.total", "--format=csv,noheader,nounits"]);
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
cmd.creation_flags(0x0800_0000);
}
let out = cmd.output().ok()?;
let line = String::from_utf8_lossy(&out.stdout).lines().next()?.to_owned();
let (used, total) = line.split_once(',')?;
Some((used.trim().parse().ok()?, total.trim().parse().ok()?))
}
/// The newest engine log under Strata's folder, its end only (the placement lines of the last start).
fn engine_log(home: &Path) -> String {
fn walk(dir: &Path, depth: u32, best: &mut Option<(std::time::SystemTime, std::path::PathBuf)>) {
let Ok(entries) = std::fs::read_dir(dir) else { return };
for e in entries.flatten() {
let p = e.path();
if p.is_dir() && depth > 0 {
walk(&p, depth - 1, best);
} else if p.to_string_lossy().ends_with(".engine.log") {
if let Ok(t) = e.metadata().and_then(|m| m.modified()) {
if best.as_ref().is_none_or(|(b, _)| t > *b) {
*best = Some((t, p));
}
}
}
}
}
let mut best = None;
walk(home, 5, &mut best);
let Some((_, p)) = best else { return String::new() };
let bytes = std::fs::read(p).unwrap_or_default();
String::from_utf8_lossy(&bytes[bytes.len().saturating_sub(400_000)..]).into_owned()
}
/// How far a line says Strata got: its last `NN%` or `NN.N%`, else `X of Y GB` (or MB), which is
/// how Strata 0.1.59 reports the model download.
pub fn percent(line: &str) -> Option<f64> {
@@ -117,6 +167,18 @@ pub async fn wait_ready(base: &str, timeout: Duration, cancel: &AtomicBool) -> R
}
}
/// One short answer, so the engine has made its buffers before its memory is read (M0 kit).
async fn warm_up(base: &str) {
let Ok(client) = reqwest::Client::builder().timeout(Duration::from_secs(60)).build() else { return };
let model = match client.get(format!("{base}/models")).send().await {
Ok(r) => r.text().await.ok().and_then(|t| serde_json::from_str::<Value>(&t).ok())
.and_then(|v| v["data"][0]["id"].as_str().map(str::to_owned)),
Err(_) => None,
};
let body = json!({"model": model, "messages": [{"role": "user", "content": "안녕"}], "max_tokens": 8});
let _ = client.post(format!("{base}/chat/completions")).header("content-type", "application/json").body(body.to_string()).send().await;
}
/// The brain's settings (`config/brain.json`, the worker's `JARVIS_CONFIG_PATH`): the LLM, the
/// memory database inside the data folder, the tools of the features that are off and the enabled
/// MCP servers (without their environment values, `features.rs`). The app owns this file and writes
@@ -149,6 +211,8 @@ pub struct Llm {
/// The port the managed server was started on (to confirm it is gone after a stop).
port: Mutex<u16>,
stop_timeout: Duration,
/// The graphics card's memory (none: Strata places the model itself).
gpu: Option<GpuReader>,
}
/// How long the model may take to answer after `strata launch` returned (it loads in about 15 s
@@ -162,13 +226,68 @@ impl Llm {
// Only the data folder matters here (the Python sources are the install's business).
let layout = Layout { data: data.to_path_buf(), src: std::path::PathBuf::new() };
let exe = layout.strata_exe();
Self::with_exe(layout, exe)
Self::with_exe(layout, exe).with_gpu(Arc::new(nvidia_memory))
}
pub fn with_exe(layout: Layout, exe: std::path::PathBuf) -> Self {
Self { layout, exe, status: Mutex::new(LlmStatus { state: LlmState::Off, managed: false, percent: None, note: None }),
active: Mutex::new(None), cancel: Arc::new(AtomicBool::new(false)), port: Mutex::new(0),
stop_timeout: Duration::from_secs(120) }
stop_timeout: Duration::from_secs(120), gpu: None }
}
/// Place the model by the card's memory (`placement.rs`), read with `gpu`.
pub fn with_gpu(mut self, gpu: GpuReader) -> Self {
self.gpu = Some(gpu);
self
}
async fn read_gpu(&self) -> Option<(i64, i64)> {
let gpu = self.gpu.clone()?;
tokio::task::spawn_blocking(move || gpu()).await.ok().flatten()
}
fn probe_file(&self) -> std::path::PathBuf {
self.layout.data.join("config").join("llm-probe.json")
}
/// The expert budget's engine settings (none without a card): the normal placement from what
/// the card holds now and this PC's measurement without experts at this context, which the
/// first start makes once (a start without experts, then the real start replaces it).
async fn placement(&self, settings: &Settings, ctx: &Ctx, base: &str) -> Result<Vec<String>, String> {
let Some((used, total)) = self.read_gpu().await else { return Ok(vec![]) };
let context = settings.llm.context;
let file = self.probe_file();
let mut all: serde_json::Map<String, Value> = std::fs::read_to_string(&file).ok()
.and_then(|t| serde_json::from_str(&t).ok()).unwrap_or_default();
let known = all.get(&context.to_string()).and_then(|v| serde_json::from_value::<crate::placement::Probe>(v.clone()).ok())
.filter(|p| p.total_mib == total);
let probe = match known {
Some(p) => p,
None => {
crate::info_log!("llm", "measuring the model without experts once (context {context})");
self.launch(settings, ctx, base, &placement_sets(0.0)).await?;
warm_up(base).await;
let after = self.read_gpu().await.map(|(u, _)| u).unwrap_or(used);
let p = crate::placement::Probe { context, total_mib: total, model_mib: (after - used).max(0),
staging_gib: crate::placement::staging_gib(&engine_log(&self.layout.strata_home())) };
all.insert(context.to_string(), json!(p));
crate::datadir::write_atomic(&file, Value::Object(all).to_string().as_bytes())
.map_err(|e| format!("배치 측정값을 저장하지 못했습니다: {e}"))?;
p
}
};
let expert = crate::placement::normal(total, used, &probe, settings.game.other_room_mib());
crate::info_log!("llm", "placement: experts {expert} GiB (card {total} MiB, held by others {used} MiB, model without experts {} MiB)",
probe.model_mib);
Ok(placement_sets(expert))
}
/// `strata launch` with `sets`, then wait until the model answers.
async fn launch(&self, settings: &Settings, ctx: &Ctx, base: &str, sets: &[String]) -> Result<String, String> {
let args = launch_args(&self.layout, settings, sets);
let refs: Vec<&str> = args.iter().map(String::as_str).collect();
ctx.run_in(&self.exe, &refs, Some(&self.layout.strata_home())).await?;
wait_ready(base, READY_TIMEOUT, &self.cancel).await
}
/// How long `strata launch --stop` may take before it is ended and the stop reported as failed.
@@ -229,13 +348,9 @@ impl Llm {
let ctx = Arc::new(Ctx::standalone(self.layout.clone(), "llm", self.cancel.clone()));
*self.active.lock().unwrap() = Some(ctx.clone());
*self.port.lock().unwrap() = settings.llm.port;
let args = launch_args(&self.layout, settings);
let refs: Vec<&str> = args.iter().map(String::as_str).collect();
let home = self.layout.strata_home();
let ran = ctx.run_in(&self.exe, &refs, Some(&home)).await;
let base = format!("http://127.0.0.1:{}/v1", settings.llm.port);
let ready = match ran {
Ok(()) => wait_ready(&base, READY_TIMEOUT, &self.cancel).await,
let ready = match self.placement(settings, &ctx, &base).await {
Ok(sets) => self.launch(settings, &ctx, &base, &sets).await,
Err(e) => Err(e),
};
*self.active.lock().unwrap() = None;
@@ -350,7 +465,7 @@ mod tests {
fn the_launch_keeps_the_model_in_the_data_folder_and_follows_the_settings() {
let l = layout("llm1");
let s = parse_settings(&json!({"llm": {"context": 16384, "port": 8099}})).unwrap();
let a = launch_args(&l, &s);
let a = launch_args(&l, &s, &[]);
let after = |k: &str| a[a.iter().position(|x| x == k).unwrap() + 1].clone();
assert!(Path::new(&after("--data-dir")).starts_with(&l.data));
assert_eq!((after("--context"), after("--port"), after("--parallel")), ("16384".into(), "8099".into(), "1".into()));
@@ -526,6 +641,46 @@ mod tests {
assert_eq!(llm.status().state, LlmState::Off);
}
#[cfg(unix)]
#[tokio::test]
async fn with_a_graphics_card_the_first_start_measures_the_llm_without_experts_then_places_them() {
let l = layout("llm-place");
let port = models_server_until("qwen-test", Duration::from_millis(0), Some(l.data.join("gone"))).await;
// The engine log, as Strata 0.1.59's qwen36 engine writes it.
let log = l.strata_home().join("x.engine.log");
let exe = fake_strata(&l, &format!("rm -f '{}'; echo 'strata-q36: hybrid experts: 0 of 256 per layer in VRAM, bigger prompt chunks streamed (1.10 GiB staging); 7.1 s' >> '{}'; echo 'Strata is serving.'",
l.data.join("gone").display(), log.display()));
// The game PC in M0 (16303 MiB card, 1460 MiB held by other programs); the LLM without
// experts held 9874 MiB.
let reads = Arc::new(std::sync::atomic::AtomicU32::new(0));
let r2 = reads.clone();
let llm = Llm::with_exe(l.clone(), exe).with_gpu(Arc::new(move || {
let n = r2.fetch_add(1, Ordering::SeqCst);
Some((if n == 1 { 1460 + 9874 } else { 1460 }, 16303))
}));
let s = parse_settings(&json!({"llm": {"port": port}})).unwrap();
tokio::time::timeout(Duration::from_secs(20), llm.start(&s)).await.expect("starts").unwrap();
let calls = std::fs::read_to_string(l.data.join("calls")).unwrap();
let launches: Vec<&str> = calls.lines().filter(|c| c.starts_with("launch --family")).collect();
assert_eq!(launches.len(), 2, "{calls}");
assert!(launches[0].ends_with("--set expert-vram=0 --set prefill=2048"), "{}", launches[0]);
// The M0 kit's normal placement on that PC: 1.5 GiB of experts.
assert!(launches[1].ends_with("--set expert-vram=1.5 --set prefill=2048"), "{}", launches[1]);
let probe: Value = serde_json::from_str(&std::fs::read_to_string(l.data.join("config").join("llm-probe.json")).unwrap()).unwrap();
assert_eq!(probe["32768"], json!({"context": 32768, "totalMib": 16303, "modelMib": 9874, "stagingGib": 1.1}));
llm.stop().await.unwrap();
// The next start reuses the measurement: one launch, placed at once (a new server, as the
// fake one does not come back after a stop).
std::fs::remove_file(l.data.join("calls")).unwrap();
let port2 = models_server_until("qwen-test", Duration::from_millis(0), None).await;
let s2 = parse_settings(&json!({"llm": {"port": port2}})).unwrap();
tokio::time::timeout(Duration::from_secs(20), llm.start(&s2)).await.expect("starts").unwrap();
let calls = std::fs::read_to_string(l.data.join("calls")).unwrap();
let launches: Vec<&str> = calls.lines().filter(|c| c.starts_with("launch --family")).collect();
assert_eq!(launches.len(), 1, "{calls}");
assert!(launches[0].ends_with("--set expert-vram=1.5 --set prefill=2048"), "{}", launches[0]);
}
#[cfg(unix)]
#[tokio::test]
async fn a_cancel_during_the_download_stops_it_and_clears_the_server() {