fix(app): performance stage switches survive failures, reconnects and late signals
- the normal stage reads other programs' memory afresh (the card after the LLM stopped, less the STT worker's model) and keeps it; the game stage counts from the latest normal reading, so the game is not counted against its own reserve - a restart that fails brings back the stage that ran before and tells the brain ready; the failed stage is tried again after 60 s, three times at most; when nothing comes back the brain is told paused so requests fail at once - the worker client keeps the latest llm state and sends it first on every connection - switches are numbered: llm switching carries an id, llm_idle names it, and a late idle of an earlier switch no longer lets a new one through - a request that waited 180 s for a switch fails without calling the brain - the dashboard shows the stage that runs also on a fallback placement without experts Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -252,10 +252,14 @@ pub struct Llm {
|
||||
stop_timeout: Duration,
|
||||
/// The graphics card's memory (none: Strata places the model itself).
|
||||
gpu: Option<GpuReader>,
|
||||
/// What other programs held when the services started (before the LLM and the STT worker):
|
||||
/// every later placement of this run counts from it, not from a card that then also holds the
|
||||
/// STT worker and a game.
|
||||
/// What other programs held at the latest normal placement (no game then): the game stage
|
||||
/// counts other programs from it, as the card then also holds the game, which its reserve is for.
|
||||
baseline: Mutex<Option<i64>>,
|
||||
/// The STT worker's model is on the card (true at switches while the worker runs), so it is not
|
||||
/// taken for another program's memory.
|
||||
stt_on_card: AtomicBool,
|
||||
/// The graphics memory a game gets in the placement being started.
|
||||
room: Mutex<Option<i64>>,
|
||||
/// The engine's CPU threads in the normal stage; a game gets half.
|
||||
threads: Mutex<Option<u32>>,
|
||||
/// The stage it runs in, and in a game the graphics memory the game gets.
|
||||
@@ -279,7 +283,7 @@ impl Llm {
|
||||
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), gpu: None, baseline: Mutex::new(None), threads: Mutex::new(None),
|
||||
stop_timeout: Duration::from_secs(120), gpu: None, baseline: Mutex::new(None), stt_on_card: AtomicBool::new(false), room: Mutex::new(None), threads: Mutex::new(None),
|
||||
stage: Mutex::new((Stage::Normal, None)) }
|
||||
}
|
||||
|
||||
@@ -313,6 +317,7 @@ impl Llm {
|
||||
/// the card.
|
||||
async fn placement(&self, settings: &Settings, ctx: &Ctx, base: &str, stage: Stage) -> Result<Option<Vec<String>>, String> {
|
||||
let c = conf(settings, stage);
|
||||
*self.room.lock().unwrap() = None;
|
||||
let workers = |sets: &mut Vec<String>| if stage == Stage::Gaming {
|
||||
let half = self.threads.lock().unwrap().map(|n| n / 2)
|
||||
.unwrap_or_else(|| std::thread::available_parallelism().map(|n| n.get() as u32 / 4).unwrap_or(1));
|
||||
@@ -332,7 +337,15 @@ impl Llm {
|
||||
return Ok(Some(sets));
|
||||
}
|
||||
let Some(card) = self.read_gpu().await else { return Ok(Some(vec![])) };
|
||||
let others = *self.baseline.lock().unwrap().get_or_insert(card.used_mib);
|
||||
// Other programs: what the card holds without this LLM and without the STT worker's model.
|
||||
// The normal stage reads it afresh (programs opened since count); the game stage takes it
|
||||
// from the latest normal placement, as the card then also holds the game.
|
||||
let stt_model = if self.stt_on_card.load(Ordering::SeqCst) { crate::placement::STT_MODEL_MIB } else { 0 };
|
||||
let now_others = (card.used_mib - stt_model).max(0);
|
||||
let others = match stage {
|
||||
Stage::Gaming => *self.baseline.lock().unwrap().get_or_insert(now_others),
|
||||
_ => *self.baseline.lock().unwrap().insert(now_others),
|
||||
};
|
||||
let key = format!("{}/{}", c.context, c.parallel);
|
||||
let file = self.probe_file();
|
||||
let mut all: serde_json::Map<String, Value> = std::fs::read_to_string(&file).ok()
|
||||
@@ -368,7 +381,7 @@ impl Llm {
|
||||
crate::info_log!("llm", "placement: no room for a game beside the model; paused while the game runs");
|
||||
return Ok(None);
|
||||
}
|
||||
*self.stage.lock().unwrap() = (Stage::Gaming, Some(g.game_room_mib));
|
||||
*self.room.lock().unwrap() = Some(g.game_room_mib);
|
||||
g.expert_gib
|
||||
}
|
||||
_ => crate::placement::normal(card.total_mib, others, &probe, settings.game.other_room_mib()),
|
||||
@@ -418,16 +431,19 @@ impl Llm {
|
||||
// A new run: other programs' memory is read afresh.
|
||||
*self.baseline.lock().unwrap() = None;
|
||||
*self.stage.lock().unwrap() = (Stage::Normal, None);
|
||||
self.stt_on_card.store(false, Ordering::SeqCst);
|
||||
self.start_stage(settings, Stage::Normal).await.map(|r| r.expect("the normal stage never pauses"))
|
||||
}
|
||||
|
||||
/// Move the running LLM to `stage` (`perf.rs`): a restart with that stage's placement, or a stop
|
||||
/// when it pauses (also a game stage with no room for the game). Returns the stage it ended in.
|
||||
/// With `llm.url` nothing moves.
|
||||
pub async fn switch(&self, settings: &Settings, stage: Stage) -> Result<Stage, String> {
|
||||
/// `stt_on_card`: the STT worker's model is loaded on the card.
|
||||
pub async fn switch(&self, settings: &Settings, stage: Stage, stt_on_card: bool) -> Result<Stage, String> {
|
||||
if settings.llm.url.is_some() {
|
||||
return Ok(Stage::Normal);
|
||||
}
|
||||
self.stt_on_card.store(stt_on_card, Ordering::SeqCst);
|
||||
if stage != Stage::Paused && self.start_stage(settings, stage).await?.is_some() {
|
||||
return Ok(stage);
|
||||
}
|
||||
@@ -447,11 +463,9 @@ impl Llm {
|
||||
*self.threads.lock().unwrap() = Some(n);
|
||||
}
|
||||
}
|
||||
// What runs now, also on a fallback placement (no experts), with the game's room if known.
|
||||
if let Ok(Some(_)) = &result {
|
||||
let mut st = self.stage.lock().unwrap();
|
||||
if stage == Stage::Normal {
|
||||
*st = (Stage::Normal, None);
|
||||
}
|
||||
*self.stage.lock().unwrap() = (stage, self.room.lock().unwrap().take());
|
||||
}
|
||||
match &result {
|
||||
Ok(None) => {}
|
||||
@@ -955,7 +969,7 @@ pub(crate) mod tests {
|
||||
llm.start(&s).await.unwrap();
|
||||
assert_eq!(llm.stage_view(), json!({"stage": "normal", "gameRoomMib": null}));
|
||||
std::fs::remove_file(l.data.join("calls")).unwrap();
|
||||
assert_eq!(tokio::time::timeout(Duration::from_secs(30), llm.switch(&s, Stage::Gaming)).await.unwrap().unwrap(), Stage::Gaming);
|
||||
assert_eq!(tokio::time::timeout(Duration::from_secs(30), llm.switch(&s, Stage::Gaming, false)).await.unwrap().unwrap(), Stage::Gaming);
|
||||
let g = launches(&l);
|
||||
// Measured once at the game's context and one request, then the 2 GiB minimum (8 GB does not
|
||||
// fit on 16 GB) with half the engine's 16 CPU threads.
|
||||
@@ -967,17 +981,74 @@ pub(crate) mod tests {
|
||||
assert_eq!(llm.status().state, LlmState::Ready);
|
||||
// Back to normal: the run's first reading of other programs, the normal placement again.
|
||||
std::fs::remove_file(l.data.join("calls")).unwrap();
|
||||
assert_eq!(llm.switch(&s, Stage::Normal).await.unwrap(), Stage::Normal);
|
||||
assert_eq!(llm.switch(&s, Stage::Normal, false).await.unwrap(), Stage::Normal);
|
||||
let n = launches(&l);
|
||||
assert_eq!(n.len(), 1, "{n:?}");
|
||||
assert!(n[0].contains("--context 32768") && n[0].ends_with("--set expert-vram=1.5 --set prefill=2048"), "{}", n[0]);
|
||||
assert_eq!(llm.stage_view(), json!({"stage": "normal", "gameRoomMib": null}));
|
||||
// Pause: the LLM stops.
|
||||
assert_eq!(llm.switch(&s, Stage::Paused).await.unwrap(), Stage::Paused);
|
||||
assert_eq!(llm.switch(&s, Stage::Paused, false).await.unwrap(), Stage::Paused);
|
||||
assert_eq!(llm.status().state, LlmState::Off);
|
||||
assert_eq!(llm.stage_view()["stage"], json!("paused"));
|
||||
}
|
||||
|
||||
/// A card whose other programs hold `others` MiB (changeable), plus the STT model while
|
||||
/// `stt` is set, plus 9874 MiB while a Strata server runs.
|
||||
#[cfg(unix)]
|
||||
fn live_card(l: &Layout, others: Arc<std::sync::atomic::AtomicI64>, stt: bool) -> GpuReader {
|
||||
let calls = l.data.join("calls");
|
||||
Arc::new(move || {
|
||||
let c = std::fs::read_to_string(&calls).unwrap_or_default();
|
||||
let running = c.lines().last().is_some_and(|x| x.starts_with("launch --family"));
|
||||
let used = others.load(Ordering::SeqCst) + if stt { 1300 } else { 0 } + if running { 9874 } else { 0 };
|
||||
Some(Gpu { id: "GPU-test".into(), used_mib: used, total_mib: 16303 })
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn the_normal_placement_reads_other_programs_afresh_and_a_game_is_not_counted_twice() {
|
||||
let l = layout("llm-stage-fresh");
|
||||
let port = server_after_launch(&l, "list").await;
|
||||
let others = Arc::new(std::sync::atomic::AtomicI64::new(1460));
|
||||
// At the start the STT worker has not loaded; at every switch it has.
|
||||
let llm = Llm::with_exe(l.clone(), fake_placed(&l)).with_gpu(live_card(&l, others.clone(), false));
|
||||
let s = parse_settings(&json!({"llm": {"port": port}})).unwrap();
|
||||
llm.start(&s).await.unwrap();
|
||||
let llm = llm.with_gpu(live_card(&l, others.clone(), true));
|
||||
// A game starts and holds 2500 MiB: the game stage counts other programs as before the game.
|
||||
others.store(1460 + 2500, Ordering::SeqCst);
|
||||
llm.switch(&s, Stage::Gaming, true).await.unwrap();
|
||||
assert!(launches(&l).last().unwrap().contains("--set expert-vram=2 "), "{:?}", launches(&l));
|
||||
// The game ends but a video player now holds 1000 MiB more: the normal stage reads that.
|
||||
others.store(1460 + 1000, Ordering::SeqCst);
|
||||
llm.switch(&s, Stage::Normal, true).await.unwrap();
|
||||
let expected = crate::placement::normal(16303, 1460 + 1000, &crate::placement::Probe { context: 32768, parallel: 1,
|
||||
gpu: "GPU-test".into(), model_mib: 9874, staging_gib: 1.1 }, 1024);
|
||||
assert!(expected < 1.5);
|
||||
assert!(launches(&l).last().unwrap().ends_with(&format!("--set expert-vram={expected} --set prefill=2048")), "{:?}", launches(&l));
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn a_game_stage_on_a_fallback_placement_still_shows_as_the_game_stage() {
|
||||
// The game's measurement fails (the card cannot be read the second time): no experts, but
|
||||
// the game stage is what runs.
|
||||
let l = layout("llm-stage-fallback");
|
||||
let port = server_after_launch(&l, "list").await;
|
||||
let llm = Llm::with_exe(l.clone(), fake_placed(&l)).with_gpu(card(&l, "GPU-test", 0));
|
||||
let s = parse_settings(&json!({"llm": {"port": port}})).unwrap();
|
||||
llm.start(&s).await.unwrap();
|
||||
let reads = Arc::new(std::sync::atomic::AtomicU32::new(0));
|
||||
let r2 = reads.clone();
|
||||
let llm = llm.with_gpu(Arc::new(move || {
|
||||
(r2.fetch_add(1, Ordering::SeqCst) == 0).then(|| Gpu { id: "GPU-test".into(), used_mib: 1460, total_mib: 16303 })
|
||||
}));
|
||||
assert_eq!(llm.switch(&s, Stage::Gaming, false).await.unwrap(), Stage::Gaming);
|
||||
assert!(launches(&l).last().unwrap().contains("--set expert-vram=0 "), "{:?}", launches(&l));
|
||||
assert_eq!(llm.stage_view(), json!({"stage": "gaming", "gameRoomMib": null}));
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn a_game_with_no_room_beside_the_model_pauses_the_llm() {
|
||||
@@ -992,7 +1063,7 @@ pub(crate) mod tests {
|
||||
}));
|
||||
let s = parse_settings(&json!({"llm": {"port": port}})).unwrap();
|
||||
llm.start(&s).await.unwrap();
|
||||
assert_eq!(llm.switch(&s, Stage::Gaming).await.unwrap(), Stage::Paused);
|
||||
assert_eq!(llm.switch(&s, Stage::Gaming, false).await.unwrap(), Stage::Paused);
|
||||
assert_eq!(llm.status().state, LlmState::Off);
|
||||
assert_eq!(llm.stage_view(), json!({"stage": "paused", "gameRoomMib": null}));
|
||||
let c = std::fs::read_to_string(l.data.join("calls")).unwrap();
|
||||
|
||||
Reference in New Issue
Block a user