feat(app): performance stages move the LLM between the normal and the game placement
- while the services run, game mode decides the stage (perf.rs): a game means the game stage at once (or pause with game.pauseInGame); its end brings the normal stage back after game.revertSeconds (default 30) - a change tells the voice worker the LLM switches (llm switching, with a notice), waits until the brain has written the answers in progress (llm_idle, at most 2 minutes), restarts the LLM in the stage and tells the worker it is ready or paused - the game stage runs at 16K context, one request at a time, half the engine's CPU threads and the game placement (reserve game.reserveGb, default 8, else 2 GiB, else 0 GiB, else pause), measured once at that context; every placement of a run counts other programs' memory as it was when the services started - the voice worker gates every LLM use: on switching new work waits (at most 180 s), the first spoken request that waits hears the notice once under its own id, on ready all go on, on paused nothing is answered - dashboard: "성능 단계: 게임 중 · 게임에 X GB" / 일시정지; game mode screen: game VRAM, revert wait, pause in game Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -24,7 +24,9 @@ pub struct Services {
|
||||
pub llm: Arc<Llm>,
|
||||
pub browser: BrowserRun,
|
||||
/// Game detection while the services run (admin.spec.md, "Game detection").
|
||||
pub game: crate::game::GameWatch,
|
||||
pub game: Arc<crate::game::GameWatch>,
|
||||
/// Moves the LLM between the performance stages as games come and go.
|
||||
pub perf: std::sync::Mutex<Option<tokio::task::JoinHandle<()>>>,
|
||||
}
|
||||
|
||||
/// The bot browser of a run (admin.spec.md, "Bot browser").
|
||||
@@ -61,6 +63,11 @@ impl BrowserRun {
|
||||
impl Services {
|
||||
/// Stop everything; an error means the LLM's server may still run.
|
||||
pub async fn stop(&self) -> Result<(), String> {
|
||||
let perf = self.perf.lock().unwrap().take();
|
||||
if let Some(p) = perf {
|
||||
p.abort();
|
||||
let _ = p.await;
|
||||
}
|
||||
self.game.stop();
|
||||
self.core.close().await;
|
||||
self.worker.close();
|
||||
@@ -113,6 +120,7 @@ async fn start_browser(data_dir: &Path, settings: &crate::settings::Settings) ->
|
||||
pub async fn start_services(data_dir: &Path, llm: Arc<Llm>) -> Result<Services, Box<dyn std::error::Error + Send + Sync>> {
|
||||
let settings = load_settings(&data_dir.join("config").join("settings.json"))?;
|
||||
let game_settings = settings.game.clone();
|
||||
let perf_settings = settings.clone();
|
||||
// The stored token (the setup wizard keeps it encrypted, admin.spec.md), else the environment.
|
||||
let secrets = crate::secrets::Secrets::new(&data_dir.join("config").join("secrets.dat"));
|
||||
let stored = secrets.get(crate::secrets::DISCORD_TOKEN)?;
|
||||
@@ -193,8 +201,76 @@ pub async fn start_services(data_dir: &Path, llm: Arc<Llm>) -> Result<Services,
|
||||
return Err(after_stop(&llm, &browser, e.to_string()).await.into());
|
||||
}
|
||||
crate::info_log!("app", "services started");
|
||||
let game = crate::game::GameWatch::start(game_settings);
|
||||
Ok(Services { core, events, worker, worker_process, missed, llm, browser, game })
|
||||
let game = Arc::new(crate::game::GameWatch::start(game_settings));
|
||||
let on = { let g = game.clone(); Arc::new(move || g.on()) };
|
||||
let perf = std::sync::Mutex::new(Some(tokio::spawn(perf_loop(perf_settings, llm.clone(), Arc::new(worker.clone()), on))));
|
||||
Ok(Services { core, events, worker, worker_process, missed, llm, browser, game, perf })
|
||||
}
|
||||
|
||||
/// The brain as the performance stages see it: told the LLM's state, and asked to finish what it is
|
||||
/// answering (the worker client; a fake in tests).
|
||||
#[async_trait::async_trait]
|
||||
pub trait LlmBrain: Send + Sync {
|
||||
fn llm_state(&self, state: &str, notice: Option<&str>) -> bool;
|
||||
async fn wait_llm_idle(&self, t: std::time::Duration) -> bool;
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl LlmBrain for WorkerClient {
|
||||
fn llm_state(&self, state: &str, notice: Option<&str>) -> bool {
|
||||
WorkerClient::llm_state(self, state, notice)
|
||||
}
|
||||
async fn wait_llm_idle(&self, t: std::time::Duration) -> bool {
|
||||
WorkerClient::wait_llm_idle(self, t).await
|
||||
}
|
||||
}
|
||||
|
||||
/// What a request that waits for a switch hears once (voice_worker.spec.md, "LLM switches").
|
||||
fn switch_notice(stage: crate::perf::Stage) -> Option<&'static str> {
|
||||
match stage {
|
||||
crate::perf::Stage::Gaming => Some("잠깐만요, 게임 모드로 바꾸는 중이에요"),
|
||||
crate::perf::Stage::Normal => Some("잠깐만요, 평소 모드로 돌아가는 중이에요"),
|
||||
crate::perf::Stage::Paused => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The performance stages (admin.spec.md, "Performance stages"): every second the stage wanted
|
||||
/// from game mode (`perf.rs`); a change tells the brain the LLM switches, waits until the answers
|
||||
/// in progress are written (at most 2 minutes), restarts the LLM in that stage (or stops it to
|
||||
/// pause) and tells the brain it is ready (or paused). With `llm.url` nothing moves.
|
||||
async fn perf_loop(settings: crate::settings::Settings, llm: Arc<Llm>, worker: Arc<dyn LlmBrain>, game: Arc<dyn Fn() -> bool + Send + Sync>) {
|
||||
use crate::perf::{Perf, Stage};
|
||||
if settings.llm.url.is_some() {
|
||||
return;
|
||||
}
|
||||
let mut perf = Perf::new(std::time::Duration::from_secs(settings.game.revert_seconds.into()), settings.game.pause_in_game);
|
||||
let mut applied = Stage::Normal;
|
||||
loop {
|
||||
tokio::time::sleep(std::time::Duration::from_secs(1)).await;
|
||||
let want = perf.target(game(), std::time::Instant::now());
|
||||
if want == applied {
|
||||
continue;
|
||||
}
|
||||
crate::info_log!("perf", "performance stage: {want:?}");
|
||||
worker.llm_state("switching", switch_notice(want));
|
||||
if !worker.wait_llm_idle(std::time::Duration::from_secs(120)).await {
|
||||
crate::warn_log!("perf", "Warning: the brain did not finish its answers in 2 minutes; switching anyway");
|
||||
}
|
||||
// Wanted is what counts as applied: a game stage that ends paused is not tried again.
|
||||
applied = want;
|
||||
match llm.switch(&settings, want).await {
|
||||
Ok(Stage::Paused) => {
|
||||
worker.llm_state("paused", None);
|
||||
}
|
||||
Ok(_) => {
|
||||
worker.llm_state("ready", None);
|
||||
}
|
||||
Err(e) => {
|
||||
crate::error_log!("perf", "the LLM did not come back in the {want:?} stage: {e}");
|
||||
worker.llm_state("ready", None);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The secret values the services get: the bot token and the MCP servers' environment values.
|
||||
@@ -220,6 +296,70 @@ async fn after_llm_stop(llm: &Llm, error: String) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod perf_tests {
|
||||
use super::*;
|
||||
use crate::strata::tests::{card, fake_placed, launches, layout, server_after_launch};
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::Mutex;
|
||||
use std::time::Duration;
|
||||
|
||||
#[derive(Default)]
|
||||
struct FakeBrain(Mutex<Vec<String>>);
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl LlmBrain for FakeBrain {
|
||||
fn llm_state(&self, state: &str, notice: Option<&str>) -> bool {
|
||||
self.0.lock().unwrap().push(format!("{state}{}", notice.map(|n| format!(": {n}")).unwrap_or_default()));
|
||||
true
|
||||
}
|
||||
async fn wait_llm_idle(&self, _t: Duration) -> bool {
|
||||
self.0.lock().unwrap().push("waited".into());
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn a_game_moves_the_llm_to_the_game_stage_and_its_end_moves_it_back() {
|
||||
let l = layout("perf-loop");
|
||||
let port = server_after_launch(&l, "list").await;
|
||||
let llm = Arc::new(Llm::with_exe(l.clone(), fake_placed(&l)).with_gpu(card(&l, "GPU-test", 0)));
|
||||
let s = crate::settings::parse_settings(&serde_json::json!({"llm": {"port": port}, "game": {"revertSeconds": 0}})).unwrap();
|
||||
llm.start(&s).await.unwrap();
|
||||
let brain = Arc::new(FakeBrain::default());
|
||||
let game = Arc::new(AtomicBool::new(false));
|
||||
let g = game.clone();
|
||||
let task = tokio::spawn(perf_loop(s, llm.clone(), brain.clone(), Arc::new(move || g.load(Ordering::SeqCst))));
|
||||
std::fs::remove_file(l.data.join("calls")).unwrap();
|
||||
game.store(true, Ordering::SeqCst);
|
||||
let until = |want: &'static str| {
|
||||
let brain = brain.clone();
|
||||
async move {
|
||||
for _ in 0..200 {
|
||||
if brain.0.lock().unwrap().iter().filter(|m| m.as_str() == want).count() > 0 {
|
||||
return;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
}
|
||||
panic!("never {want}: {:?}", brain.0.lock().unwrap());
|
||||
}
|
||||
};
|
||||
until("ready").await;
|
||||
assert_eq!(*brain.0.lock().unwrap(), ["switching: 잠깐만요, 게임 모드로 바꾸는 중이에요", "waited", "ready"]);
|
||||
assert!(launches(&l).last().unwrap().contains("--context 16384"), "{:?}", launches(&l));
|
||||
assert_eq!(llm.stage_view()["stage"], serde_json::json!("gaming"));
|
||||
// The game ends (no wait set): back to the normal stage.
|
||||
brain.0.lock().unwrap().clear();
|
||||
game.store(false, Ordering::SeqCst);
|
||||
until("ready").await;
|
||||
assert_eq!(brain.0.lock().unwrap()[0], "switching: 잠깐만요, 평소 모드로 돌아가는 중이에요");
|
||||
assert!(launches(&l).last().unwrap().contains("--context 32768"));
|
||||
assert_eq!(llm.stage_view()["stage"], serde_json::json!("normal"));
|
||||
task.abort();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
Reference in New Issue
Block a user