Compare commits
5 Commits
app-v0.1.2
...
app-v0.1.2
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d02092662b | ||
|
|
4adc6a8d72 | ||
|
|
4993942040 | ||
|
|
ff78c0ac41 | ||
|
|
8c61d7a821 |
2
app/Cargo.lock
generated
2
app/Cargo.lock
generated
@@ -1520,7 +1520,7 @@ checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4"
|
||||
|
||||
[[package]]
|
||||
name = "jarvis-app"
|
||||
version = "0.1.21"
|
||||
version = "0.1.23"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"base64 0.22.1",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "jarvis-app"
|
||||
version = "0.1.21"
|
||||
version = "0.1.23"
|
||||
edition = "2021"
|
||||
rust-version = "1.85"
|
||||
description = "Jarvis v2 Windows app core: Discord voice, voice worker supervisor, chat channels"
|
||||
|
||||
4
app/shell/Cargo.lock
generated
4
app/shell/Cargo.lock
generated
@@ -2637,7 +2637,7 @@ checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4"
|
||||
|
||||
[[package]]
|
||||
name = "jarvis-app"
|
||||
version = "0.1.21"
|
||||
version = "0.1.23"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"base64 0.22.1",
|
||||
@@ -2666,7 +2666,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "jarvis-shell"
|
||||
version = "0.1.21"
|
||||
version = "0.1.23"
|
||||
dependencies = [
|
||||
"jarvis-app",
|
||||
"serde_json",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "jarvis-shell"
|
||||
version = "0.1.21"
|
||||
version = "0.1.23"
|
||||
edition = "2021"
|
||||
rust-version = "1.85"
|
||||
description = "Jarvis v2 management app window (Tauri 2 over the app core's AdminApi)"
|
||||
|
||||
@@ -582,8 +582,8 @@ between the normal placement and the game placement as games come and go (not wi
|
||||
engine's CPU threads (read from its log at the normal start, else a quarter of the logical CPUs),
|
||||
and the game placement (`placement.rs`: the reserve beside more than 2 GiB of experts, else
|
||||
2 GiB, else 0 GiB, else pause), measured once at that context like the normal one. Other
|
||||
programs' memory is what the card holds after the LLM stopped, less the STT worker's model while
|
||||
it is loaded (1300 MiB), read afresh at every placement. A normal placement made with no game
|
||||
programs' memory is what the card holds after the LLM stopped, less the voice worker's models
|
||||
while they are loaded (the STT model 1300 MiB, the TTS 1005 MiB), read afresh at every placement. A normal placement made with no game
|
||||
running keeps its reading; one made while a game runs (the way back from a failed game stage)
|
||||
keeps the earlier one. The game stage counts other programs as that kept reading and leaves
|
||||
a reserve of at least what has grown since (the game and any program opened after that
|
||||
@@ -591,7 +591,7 @@ between the normal placement and the game placement as games come and go (not wi
|
||||
as the services started, there is no such reading: game detection looks once before the LLM
|
||||
starts, at the window in front and at every running program (one in a launcher's game folder or
|
||||
the person's games list counts, also behind other windows; how a window looks is not known
|
||||
there). Then the game stage counts what the card holds now, the game included, and leaves only
|
||||
there; the `game` log tab gets "a game runs as the services start: program"). Then the game stage counts what the card holds now, the game included, and leaves only
|
||||
the room for other programs. The dashboard shows the stage that runs, also on a fallback
|
||||
placement without experts.
|
||||
- Pause: the LLM stops (`llm` off, "게임 중 일시정지"); the brain answers nothing until the stage
|
||||
@@ -599,7 +599,10 @@ between the normal placement and the game placement as games come and go (not wi
|
||||
- The foreground program is a game, in this order: in `notGames`: no; in `games`: yes
|
||||
(`registered`); a browser (also the bot's Chrome), video player, the desktop, Discord, a
|
||||
launcher's own window or this app: no; under a launcher's game folder (the folder after
|
||||
`steamapps\common`, `Epic Games` or `Riot Games`) or inside a Battle.net game's install folder:
|
||||
`steamapps\common`, `Epic Games` or `Riot Games`), unless that folder is the launcher's own or a
|
||||
program that is not a game (`Steamworks Shared` and `wallpaper_engine` (Wallpaper Engine, which
|
||||
runs all the time) under Steam, `Launcher` and `Epic Online Services` under Epic, `Riot Client`
|
||||
under Riot), or inside a Battle.net game's install folder:
|
||||
yes (`launcher`, with the launcher's name). Battle.net installs anywhere, so its games come from
|
||||
the machine's uninstall entries (64- and 32-bit), read when the watch starts: entries removed by
|
||||
its "Blizzard Uninstaller" or published by Blizzard Entertainment, with an install folder, not
|
||||
@@ -624,9 +627,9 @@ start it first, so nothing answers before the brain can, and stop it last.
|
||||
environment, `runtime/strata` as the working folder, one process group, lines to the `llm` log
|
||||
tab). It downloads the model on the first start, starts the engine and returns; the app then
|
||||
waits (up to 30 minutes) until `/v1/models` lists the model and takes its id. `--restart`
|
||||
replaces a server left with other choices; the same choices are reused. `--parallel` is 1 (faster
|
||||
on a 16 GB card, M0) and 2 when a chat channel answers every message, so its answers do not wait
|
||||
behind voice answers. Pictures (`--vision`) are off unless screen viewing is available ("Screen viewing"): then `gpu`
|
||||
replaces a server left with other choices; the same choices are reused. `--parallel` is always 1 (faster
|
||||
on a 16 GB card, M0; with 2 the answers were up to 3 times slower), also when a chat channel
|
||||
answers every message: its answers take turns with the voice answers. Pictures (`--vision`) are off unless screen viewing is available ("Screen viewing"): then `gpu`
|
||||
in the normal stage and `cpu` in the game stage (M0). Stopping the services
|
||||
runs `strata launch --stop` (ended after 2 minutes, with everything it started) and then checks
|
||||
that the port refuses connections; so does a failed or cancelled start, so nothing half-started
|
||||
@@ -644,7 +647,8 @@ start it first, so nothing answers before the brain can, and stop it last.
|
||||
and leaves the speech-to-text worker no room, and its qwen36 engine takes no reserve. Experts get
|
||||
what is left of the card after what it holds before the start (other programs), the model without
|
||||
experts, the STT worker's share (2740 MiB: its model and ten speakers at once, M0 `stt`), the
|
||||
engine's margin (768 MiB) and the room for programs opened later (`game.otherRoomGb`, default
|
||||
TTS's share (1005 MiB, MeloTTS after its warm-up sentence, M0 `tts_melo`; it loads after the LLM,
|
||||
so a start and a switch with the same programs open place the same), the engine's margin (768 MiB) and the room for programs opened later (`game.otherRoomGb`, default
|
||||
1 GB); the budget first holds the long-prompt staging, rounded down to 0.1 GiB, 0 when nothing is
|
||||
left. What the model holds without experts is measured once per context, number of requests at
|
||||
once and card (its NVIDIA UUID): the first-run self-check, a start with `expert-vram=0`, one
|
||||
@@ -994,7 +998,8 @@ back. Performance stages (on every system, with a fake
|
||||
Strata and card): a game moves the LLM to the game placement (measured once at 16K and one request,
|
||||
2 GiB on the game PC's numbers, half the 16 engine threads) and back after the wait, pause stops
|
||||
it, a card with no room for a game pauses, the normal stage counts a program opened since, the game
|
||||
stage does not count the game twice and counts what grew since the normal reading, a game running
|
||||
stage does not count the game twice and counts what grew since the normal reading, the voice
|
||||
worker's models loaded after the start leave the normal placement as it started, a game running
|
||||
as the services start does not pause the LLM, the way back to normal from a failed game stage while
|
||||
the game runs keeps the reading from before the game, a game program behind other windows is found
|
||||
at the start (win-ci VM: a minimised program in a Steam game folder), a fallback game placement still shows as the game
|
||||
@@ -1004,7 +1009,8 @@ is tried three times; after that a new game tries again, and the next try waits
|
||||
failed switch was over. The worker client ignores a late idle of an earlier switch and sends the
|
||||
latest LLM state first when a worker connects again. On every system: game detection's rules
|
||||
(a borderless game, a maximised program, a browser's full-screen video, exclusive full screen,
|
||||
launcher folders and their own windows, Battle.net games by install folder and their uninstall
|
||||
launcher folders, their own windows and own folders (Wallpaper Engine, the Riot client's crash
|
||||
handler), Battle.net games by install folder and their uninstall
|
||||
entries, non-ASCII paths, the person's lists first, staying on until the game ends,
|
||||
detection off) and its settings. A removal forgets the driver only when no device is left and the package
|
||||
is gone or was not in the store; a failed install forgets it only under the same rule (and never
|
||||
|
||||
@@ -89,7 +89,7 @@ Settings (section `response`):
|
||||
|
||||
| Key | Default | Meaning |
|
||||
|---|---|---|
|
||||
| `response.policy` | `"first"` | `first` (처음 대화만), `inOrder` (들어온 순서대로), `latest` (마지막 대화만), `important` (제일 중요한 대화만). |
|
||||
| `response.policy` | `"latest"` | `first` (처음 대화만), `inOrder` (들어온 순서대로), `latest` (마지막 대화만), `important` (제일 중요한 대화만). |
|
||||
| `response.queueMax` | `5` | `inOrder`: most waiting requests; past it the oldest is dropped. 1-20. |
|
||||
| `response.collectMs` | `700` | `important`: how long candidates are collected before choosing. 0-3000. |
|
||||
| `response.settleMs` | `800` | Longest wait for an earlier-ended utterance that is still being transcribed. 0-3000. |
|
||||
@@ -167,10 +167,9 @@ never takes the voice turn and never goes through the response policy.
|
||||
(`reply_delivered`).
|
||||
- The worker writes voice and chat answers in separate lanes (`voice_worker.spec.md`), so a voice
|
||||
answer never waits behind another person's chat answer; one person's answers are written one at a
|
||||
time, in the order they asked. For the two to run at the same time the LLM must take two
|
||||
requests at once (`docs/v2/conversation.md`, "LLM 동시 요청 수"): until the app starts Strata itself
|
||||
(M5), Strata is started with `--parallel 2` when some channel answers everything; with
|
||||
`--parallel 1` the two lanes' LLM calls take turns at Strata.
|
||||
time, in the order they asked. The LLM takes one request at a time (`docs/v2/conversation.md`,
|
||||
"LLM 동시 요청 수"; `--parallel 1`, also when a channel answers everything), so the two lanes' LLM
|
||||
calls take turns at Strata.
|
||||
|
||||
## The conversation loop
|
||||
|
||||
|
||||
@@ -28,12 +28,14 @@ const NOT_GAMES: &[&str] = &[
|
||||
];
|
||||
|
||||
/// Launcher game folders, as the path parts before the game's own folder: a program under one
|
||||
/// counts as a game whatever its window looks like. Battle.net installs anywhere, so its games come
|
||||
/// from their install folders (`InstalledGame`).
|
||||
const LAUNCHERS: &[(&[&str], &str)] = &[
|
||||
(&["steamapps", "common"], "Steam"),
|
||||
(&["epic games"], "Epic"),
|
||||
(&["riot games"], "Riot"),
|
||||
/// counts as a game whatever its window looks like, unless that folder is one of the launcher's
|
||||
/// own (its client, shared runtimes, or a non-game app such as Wallpaper Engine, which runs all
|
||||
/// the time). Battle.net installs anywhere, so its games come from their install folders
|
||||
/// (`InstalledGame`).
|
||||
const LAUNCHERS: &[(&[&str], &str, &[&str])] = &[
|
||||
(&["steamapps", "common"], "Steam", &["steamworks shared", "wallpaper_engine"]),
|
||||
(&["epic games"], "Epic", &["launcher", "epic online services"]),
|
||||
(&["riot games"], "Riot", &["riot client"]),
|
||||
];
|
||||
|
||||
/// A game a launcher installed somewhere of its own choosing.
|
||||
@@ -71,10 +73,11 @@ fn launcher_game(path: &str, installed: &[InstalledGame]) -> Option<(&'static st
|
||||
return Some((g.launcher, g.name.clone()));
|
||||
}
|
||||
}
|
||||
for (marker, launcher) in LAUNCHERS {
|
||||
for (marker, launcher, own) in LAUNCHERS {
|
||||
// The game's folder follows the marker, and the program is inside it.
|
||||
if let Some(i) = (0..p.len().saturating_sub(marker.len() + 1)).find(|&i| same(&p[i..i + marker.len()], marker)) {
|
||||
return Some((launcher, p[i + marker.len()].to_owned()));
|
||||
let folder = p[i + marker.len()];
|
||||
return (!own.iter().any(|o| folder.eq_ignore_ascii_case(o))).then(|| (*launcher, folder.to_owned()));
|
||||
}
|
||||
}
|
||||
None
|
||||
@@ -150,14 +153,14 @@ pub fn classify(fg: &Foreground, d3d_fullscreen: bool, s: &GameSettings, install
|
||||
(fg.covers_monitor && fg.no_frame && fg.gpu_3d >= MIN_GPU_3D).then_some(Reason::Borderless)
|
||||
}
|
||||
|
||||
/// Whether one of these programs (full paths) is a game by what it is: the person's list or a
|
||||
/// The first of these programs (full paths) that is a game by what it is: the person's list or a
|
||||
/// launcher's game folder. Used once as the services start, for games behind other windows (how a
|
||||
/// window looks is not known there, so those rules do not apply).
|
||||
pub fn game_running_among(paths: &[String], s: &GameSettings, installed: &[InstalledGame]) -> bool {
|
||||
paths.iter().any(|p| {
|
||||
let fg = Foreground { pid: 0, path: p.clone(), covers_monitor: false, no_frame: false, gpu_3d: 0.0 };
|
||||
pub fn game_running_among(paths: &[String], s: &GameSettings, installed: &[InstalledGame]) -> Option<String> {
|
||||
paths.iter().find(|p| {
|
||||
let fg = Foreground { pid: 0, path: (*p).clone(), covers_monitor: false, no_frame: false, gpu_3d: 0.0 };
|
||||
classify(&fg, false, s, installed).is_some()
|
||||
})
|
||||
}).cloned()
|
||||
}
|
||||
|
||||
/// A game's name for the dashboard: its name from the launcher (the folder under a launcher's game
|
||||
@@ -225,7 +228,11 @@ impl GameWatch {
|
||||
if cfg!(windows) && settings.detect {
|
||||
let snap = probe::Probe::new().snapshot();
|
||||
state.lock().unwrap().update(&snap, &settings, probe::alive);
|
||||
background = game_running_among(&probe::process_paths(), &settings, &snap.installed);
|
||||
if let Some(path) = game_running_among(&probe::process_paths(), &settings, &snap.installed) {
|
||||
// Which program, so a wrong one can be put on the "not games" list.
|
||||
crate::info_log!("game", "a game runs as the services start: {}", file_name(&path));
|
||||
background = true;
|
||||
}
|
||||
}
|
||||
let thread = (cfg!(windows) && settings.detect).then(|| {
|
||||
let (state, stop) = (state.clone(), stop.clone());
|
||||
@@ -622,15 +629,35 @@ mod tests {
|
||||
let s = settings();
|
||||
let wow = InstalledGame { dir: r"D:\Games\World of Warcraft".into(), name: "World of Warcraft".into(), launcher: "Battle.net" };
|
||||
// Behind other windows: only what the program is (where it lives, or the person's list).
|
||||
assert!(game_running_among(&[r"C:\Windows\explorer.exe".into(), r"C:\Riot Games\VALORANT\live\VALORANT.exe".into()], &s, &[]));
|
||||
assert!(game_running_among(&[r"D:\Games\World of Warcraft\_retail_\Wow.exe".into()], &s, &[wow]));
|
||||
assert!(!game_running_among(&[r"C:\Windows\explorer.exe".into(), r"C:\Riot Games\Riot Client\RiotClientServices.exe".into(),
|
||||
r"C:\Program Files\Google\Chrome\Application\chrome.exe".into()], &s, &[]), "launchers and browsers are not games");
|
||||
assert_eq!(game_running_among(&[r"C:\Windows\explorer.exe".into(), r"C:\Riot Games\VALORANT\live\VALORANT.exe".into()], &s, &[]),
|
||||
Some(r"C:\Riot Games\VALORANT\live\VALORANT.exe".into()), "the program found, for the log");
|
||||
assert!(game_running_among(&[r"D:\Games\World of Warcraft\_retail_\Wow.exe".into()], &s, &[wow]).is_some());
|
||||
assert!(game_running_among(&[r"C:\Windows\explorer.exe".into(), r"C:\Riot Games\Riot Client\RiotClientServices.exe".into(),
|
||||
r"C:\Program Files\Google\Chrome\Application\chrome.exe".into()], &s, &[]).is_none(), "launchers and browsers are not games");
|
||||
let mut mine = settings();
|
||||
mine.games = vec!["mygame".into()];
|
||||
assert!(game_running_among(&[r"D:\x\MyGame.exe".into()], &mine, &[]));
|
||||
assert!(game_running_among(&[r"D:\x\MyGame.exe".into()], &mine, &[]).is_some());
|
||||
mine.not_games = vec!["VALORANT.exe".into()];
|
||||
assert!(!game_running_among(&[r"C:\Riot Games\VALORANT\live\VALORANT.exe".into()], &mine, &[]));
|
||||
assert!(game_running_among(&[r"C:\Riot Games\VALORANT\live\VALORANT.exe".into()], &mine, &[]).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn programs_in_a_launchers_own_folders_are_not_games() {
|
||||
let s = settings();
|
||||
// Always running on the game PC (2026-11-17): Wallpaper Engine is a Steam app, and the Riot
|
||||
// client's crash handler sits in the client's folder.
|
||||
for p in [r"C:\Program Files (x86)\Steam\steamapps\common\wallpaper_engine\wallpaper64.exe",
|
||||
r"C:\Program Files (x86)\Steam\steamapps\common\Steamworks Shared\_CommonRedist\vcredist\x.exe",
|
||||
r"C:\Riot Games\Riot Client\RiotClientCrashHandler.exe",
|
||||
r"C:\Program Files\Epic Games\Launcher\Portal\Binaries\Win64\EpicGamesLauncher.exe",
|
||||
r"C:\Program Files (x86)\Epic Games\Epic Online Services\service\EpicOnlineServices.exe"] {
|
||||
assert_eq!(classify(&fg(p, false, false, 0.0), false, &s, &[]), None, "{p}");
|
||||
}
|
||||
assert_eq!(game_running_among(&[r"C:\Riot Games\Riot Client\RiotClientCrashHandler.exe".into(),
|
||||
r"C:\Program Files (x86)\Steam\steamapps\common\wallpaper_engine\wallpaper64.exe".into()], &s, &[]), None);
|
||||
// The games beside them still are.
|
||||
assert_eq!(classify(&fg(r"C:\Program Files\Epic Games\Fortnite\FortniteClient.exe", false, false, 0.0), false, &s, &[]),
|
||||
Some(Reason::Launcher("Epic")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -13,6 +13,15 @@ pub const MARGIN_MIB: i64 = 768;
|
||||
pub const STT_MIB: i64 = STT_MODEL_MIB + 1440;
|
||||
/// The STT worker's model alone (M0 `stt`).
|
||||
pub const STT_MODEL_MIB: i64 = 1300;
|
||||
/// The TTS (MeloTTS, Korean) on the card after its warm-up sentence, measured on the game PC
|
||||
/// (M0 `tts_melo`). It loads after the LLM starts, so it is kept beside like the STT's share.
|
||||
pub const TTS_MIB: i64 = 1005;
|
||||
|
||||
/// What the voice worker's models hold on the card now: the STT model and the TTS once loaded.
|
||||
/// Taken off what the card holds, so they are not counted again as other programs.
|
||||
pub fn worker_models_mib(stt_loaded: bool, tts_loaded: bool) -> i64 {
|
||||
(if stt_loaded { STT_MODEL_MIB } else { 0 }) + if tts_loaded { TTS_MIB } else { 0 }
|
||||
}
|
||||
/// The smallest expert budget in a game: it holds the long-prompt staging (about 1.1 GiB) first,
|
||||
/// so 2 GiB is the least that loads experts, and it was 1.5-2.1 times faster than none in a real
|
||||
/// game (user decision, 2026-11-10).
|
||||
@@ -36,10 +45,10 @@ pub struct Probe {
|
||||
}
|
||||
|
||||
/// The expert budget (GiB, down to 0.1) that leaves `room_mib` free besides what the card already
|
||||
/// holds (`used_mib`), the LLM without experts, the STT's share and the engine's margin. The budget
|
||||
/// holds (`used_mib`), the LLM without experts, the STT's and TTS's shares and the engine's margin. The budget
|
||||
/// first holds the staging, which the start without experts already has (M0 `expert_budget_gib`).
|
||||
pub fn expert_budget_gib(total_mib: i64, used_mib: i64, p: &Probe, room_mib: i64) -> f64 {
|
||||
let spare = total_mib - used_mib - p.model_mib - STT_MIB - MARGIN_MIB - room_mib;
|
||||
let spare = total_mib - used_mib - p.model_mib - STT_MIB - TTS_MIB - MARGIN_MIB - room_mib;
|
||||
if spare <= 0 {
|
||||
return 0.0;
|
||||
}
|
||||
@@ -71,7 +80,7 @@ pub fn game(total_mib: i64, used_mib: i64, p: &Probe, reserve_mib: i64) -> GameP
|
||||
return GamePlacement { expert_gib: expert, game_room_mib: reserve_mib, paused: false };
|
||||
}
|
||||
// Beside the model without experts (which already holds the staging): what 2 GiB adds.
|
||||
let free = total_mib - used_mib - p.model_mib - STT_MIB - MARGIN_MIB;
|
||||
let free = total_mib - used_mib - p.model_mib - STT_MIB - TTS_MIB - MARGIN_MIB;
|
||||
let extra = ((MIN_GAME_EXPERT_GIB - p.staging_gib) * 1024.0).max(0.0) as i64;
|
||||
if free - extra > 0 {
|
||||
return GamePlacement { expert_gib: MIN_GAME_EXPERT_GIB, game_room_mib: free - extra, paused: false };
|
||||
@@ -93,7 +102,7 @@ mod tests {
|
||||
use super::*;
|
||||
|
||||
/// The game PC in M0 `gamemode_tune` (RTX 5070 Ti 16 GB): 2760 MiB held before the LLM there
|
||||
/// included the STT model (1300 MiB), which the app starts after the LLM.
|
||||
/// included the STT model (1300 MiB), which the app starts after the LLM. M0 ran no TTS.
|
||||
const TOTAL: i64 = 16303;
|
||||
const OTHERS: i64 = 2760 - 1300;
|
||||
fn probe32() -> Probe {
|
||||
@@ -103,7 +112,8 @@ mod tests {
|
||||
#[test]
|
||||
fn the_normal_placement_is_the_one_m0_measured_with_room_for_the_stt() {
|
||||
// M0 got 1.5 GiB (the STT model counted as already held); the app counts it in the STT share.
|
||||
assert_eq!(normal(TOTAL, OTHERS, &probe32(), 1024), 1.5);
|
||||
// M0 ran no TTS: the app keeps its share too, so the same 1.5 GiB needs that much less held.
|
||||
assert_eq!(normal(TOTAL, OTHERS - TTS_MIB, &probe32(), 1024), 1.5);
|
||||
// More room for other programs, fewer experts; no room at all, none.
|
||||
assert!(normal(TOTAL, OTHERS, &probe32(), 2048) < 1.5);
|
||||
assert_eq!(normal(TOTAL, OTHERS + 8000, &probe32(), 1024), 0.0);
|
||||
@@ -116,7 +126,7 @@ mod tests {
|
||||
// 8 GB does not fit on 16 GB: the smallest placement, and the game gets what is left.
|
||||
let g = game(TOTAL, OTHERS, &probe16, 8192);
|
||||
assert_eq!((g.expert_gib, g.paused), (MIN_GAME_EXPERT_GIB, false));
|
||||
let expected = TOTAL - OTHERS - probe16.model_mib - STT_MIB - MARGIN_MIB - ((2.0 - 1.1) * 1024.0) as i64;
|
||||
let expected = TOTAL - OTHERS - probe16.model_mib - STT_MIB - TTS_MIB - MARGIN_MIB - ((2.0 - 1.1) * 1024.0) as i64;
|
||||
assert_eq!(g.game_room_mib, expected);
|
||||
assert!(g.game_room_mib > 0 && g.game_room_mib < 8192);
|
||||
// A bigger card keeps the whole reserve, with more experts than the minimum.
|
||||
@@ -124,9 +134,9 @@ mod tests {
|
||||
assert_eq!(big.game_room_mib, 8192);
|
||||
assert!(big.expert_gib > MIN_GAME_EXPERT_GIB && !big.paused);
|
||||
// No room beside 2 GiB but some beside none: the 0 GiB placement, before pausing.
|
||||
let tight = game(TOTAL, 2960, &Probe { model_mib: 9124, ..probe16.clone() }, 8192);
|
||||
let tight = game(TOTAL, 1955, &Probe { model_mib: 9124, ..probe16.clone() }, 8192);
|
||||
assert_eq!((tight.expert_gib, tight.paused), (0.0, false));
|
||||
assert_eq!(tight.game_room_mib, TOTAL - 2960 - 9124 - STT_MIB - MARGIN_MIB);
|
||||
assert_eq!(tight.game_room_mib, TOTAL - 1955 - 9124 - STT_MIB - TTS_MIB - MARGIN_MIB);
|
||||
// Other programs already hold the card: no room for a game, the LLM pauses in one.
|
||||
let full = game(TOTAL, OTHERS + 4000, &probe16, 8192);
|
||||
assert!(full.paused);
|
||||
|
||||
@@ -36,7 +36,7 @@ pub struct PolicySettings {
|
||||
impl Default for PolicySettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
kind: PolicyKind::First,
|
||||
kind: PolicyKind::Latest,
|
||||
queue_max: 5,
|
||||
collect: Duration::from_millis(700),
|
||||
settle: Duration::from_millis(800),
|
||||
|
||||
@@ -253,8 +253,8 @@ pub trait LlmBrain: Send + Sync {
|
||||
/// `ready` (with whether a game runs) or `paused`.
|
||||
fn llm_state(&self, state: &str, game: bool) -> bool;
|
||||
async fn wait_llm_idle(&self, id: u64, t: std::time::Duration) -> bool;
|
||||
/// The STT worker's model is loaded (on the graphics card).
|
||||
fn stt_on_card(&self) -> bool;
|
||||
/// What the worker's loaded models (STT, TTS) hold on the graphics card, in MiB.
|
||||
fn worker_models_mib(&self) -> i64;
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
@@ -268,8 +268,8 @@ impl LlmBrain for WorkerClient {
|
||||
async fn wait_llm_idle(&self, id: u64, t: std::time::Duration) -> bool {
|
||||
WorkerClient::wait_llm_idle(self, id, t).await
|
||||
}
|
||||
fn stt_on_card(&self) -> bool {
|
||||
self.hello().is_some_and(|h| h.stt_ready)
|
||||
fn worker_models_mib(&self) -> i64 {
|
||||
self.hello().map_or(0, |h| crate::placement::worker_models_mib(h.stt_ready, h.tts_ready))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -320,7 +320,7 @@ async fn perf_loop(settings: crate::settings::Settings, llm: Arc<Llm>, brain: Ar
|
||||
if !brain.wait_llm_idle(id, std::time::Duration::from_secs(120)).await {
|
||||
crate::warn_log!("perf", "Warning: the brain did not finish its answers in 2 minutes; switching anyway");
|
||||
}
|
||||
let ended = match llm.switch(&settings, want, brain.stt_on_card(), game()).await {
|
||||
let ended = match llm.switch(&settings, want, brain.worker_models_mib(), game()).await {
|
||||
Ok(ended) => {
|
||||
retry.succeeded();
|
||||
actual = want;
|
||||
@@ -328,7 +328,7 @@ async fn perf_loop(settings: crate::settings::Settings, llm: Arc<Llm>, brain: Ar
|
||||
}
|
||||
Err(e) => {
|
||||
crate::error_log!("perf", "the LLM did not start in the {want:?} stage: {e}; going back to {actual:?}");
|
||||
let back = match llm.switch(&settings, actual, brain.stt_on_card(), game()).await {
|
||||
let back = match llm.switch(&settings, actual, brain.worker_models_mib(), game()).await {
|
||||
Ok(ended) => ended,
|
||||
Err(e) => {
|
||||
crate::error_log!("perf", "the LLM did not come back in the {actual:?} stage either: {e}");
|
||||
@@ -396,8 +396,8 @@ mod perf_tests {
|
||||
self.0.lock().unwrap().push("waited".into());
|
||||
true
|
||||
}
|
||||
fn stt_on_card(&self) -> bool {
|
||||
false
|
||||
fn worker_models_mib(&self) -> i64 {
|
||||
0
|
||||
}
|
||||
}
|
||||
|
||||
@@ -497,7 +497,7 @@ mod perf_tests {
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn going_back_to_normal_while_the_game_runs_keeps_the_reading_from_before_the_game() {
|
||||
// 24 GB card; other programs 1460 MiB at the start. A game (2500 MiB) starts; the first
|
||||
// 24 GB card; other programs `OTHERS` at the start. A game (2500 MiB) starts; the first
|
||||
// game start fails and the normal stage comes back while the game still runs; the second
|
||||
// try works. It must count other programs from the reading before the game, not one that
|
||||
// has the game in it.
|
||||
@@ -508,7 +508,7 @@ mod perf_tests {
|
||||
let exe = crate::strata::tests::fake_strata(&l, &format!(
|
||||
"case \"$*\" in *'--context 16384'*'expert-vram=0'*) ;; *'--context 16384'*) if [ ! -e '{fo}' ]; then touch '{fo}'; exit 4; fi;; esac; rm -f '{g}'; echo 'strata-q36: (1.10 GiB staging) on 16 CPU threads' >> '{log}'; echo 'Strata is serving.'",
|
||||
fo = failed_once.display(), g = l.data.join("gone").display(), log = log.display()));
|
||||
let others = Arc::new(std::sync::atomic::AtomicI64::new(1460));
|
||||
let others = Arc::new(std::sync::atomic::AtomicI64::new(crate::strata::tests::OTHERS));
|
||||
let calls = l.data.join("calls");
|
||||
let o2 = others.clone();
|
||||
let llm = Arc::new(Llm::with_exe(l.clone(), exe).with_gpu(Arc::new(move || {
|
||||
@@ -518,7 +518,7 @@ mod perf_tests {
|
||||
})));
|
||||
let s = crate::settings::parse_settings(&serde_json::json!({"llm": {"port": port}})).unwrap();
|
||||
llm.start(&s).await.unwrap();
|
||||
others.store(1460 + 2500, Ordering::SeqCst);
|
||||
others.store(crate::strata::tests::OTHERS + 2500, Ordering::SeqCst);
|
||||
let brain = Arc::new(FakeBrain::default());
|
||||
let task = tokio::spawn(perf_loop(s, llm.clone(), brain.clone(), Arc::new(|| true), Duration::from_millis(300)));
|
||||
for _ in 0..100 {
|
||||
@@ -529,8 +529,8 @@ mod perf_tests {
|
||||
assert!(failed_once.exists(), "the first game start failed");
|
||||
assert_eq!(llm.stage_view()["stage"], serde_json::json!("gaming"));
|
||||
let probe16 = crate::placement::Probe { context: 16384, parallel: 1, gpu: "GPU-test".into(), model_mib: 9874, staging_gib: 1.1 };
|
||||
let right = crate::placement::game(24576, 1460, &probe16, 8192).expert_gib;
|
||||
let wrong = crate::placement::game(24576, 1460 + 2500, &probe16, 8192).expert_gib;
|
||||
let right = crate::placement::game(24576, crate::strata::tests::OTHERS, &probe16, 8192).expert_gib;
|
||||
let wrong = crate::placement::game(24576, crate::strata::tests::OTHERS + 2500, &probe16, 8192).expert_gib;
|
||||
assert_ne!(right, wrong);
|
||||
assert!(launches(&l).last().unwrap().contains(&format!("--set expert-vram={right} ")), "{:?}", launches(&l));
|
||||
}
|
||||
@@ -551,8 +551,8 @@ mod perf_tests {
|
||||
async fn wait_llm_idle(&self, _id: u64, _t: Duration) -> bool {
|
||||
true
|
||||
}
|
||||
fn stt_on_card(&self) -> bool {
|
||||
false
|
||||
fn worker_models_mib(&self) -> i64 {
|
||||
0
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -447,7 +447,7 @@ fn parse_call(raw: &Map<String, Value>, wake_words: &[String], d: &CallSettings)
|
||||
|
||||
fn parse_response(raw: &Map<String, Value>, d: &PolicySettings) -> Result<PolicySettings, SettingsError> {
|
||||
let r = section(raw, "response")?;
|
||||
let kind = match get_str(r, "policy", "response", "first")?.as_str() {
|
||||
let kind = match get_str(r, "policy", "response", "latest")?.as_str() {
|
||||
"first" => PolicyKind::First,
|
||||
"inOrder" => PolicyKind::InOrder,
|
||||
"latest" => PolicyKind::Latest,
|
||||
@@ -914,6 +914,11 @@ mod tests {
|
||||
assert_eq!(load_settings(&dir.join("nope.json")).unwrap(), Settings::default());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn by_default_only_the_latest_call_is_answered() {
|
||||
assert_eq!(parse_settings(&json!({})).unwrap().response.kind, PolicyKind::Latest);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_a_full_file_with_bom() {
|
||||
let dir = std::env::temp_dir().join(format!("jarvis-settings-full-{}", std::process::id()));
|
||||
|
||||
@@ -94,7 +94,7 @@ pub fn fields() -> Vec<Field> {
|
||||
f("call.followUpMs", Channels, Int { min: 0, max: 5000 }, json!(1500), "호출어 뒤 이어 말하기 대기(ms)"),
|
||||
f("call.earcon", Channels, Bool, json!(true), "부르면 효과음"),
|
||||
f("response.policy", Channels, Choice { values: &["first", "inOrder", "latest", "important"] },
|
||||
json!("first"), "동시 대화 응답 정책"),
|
||||
json!("latest"), "동시 대화 응답 정책"),
|
||||
f("response.queueMax", Channels, Int { min: 1, max: 20 }, json!(5), "기다리는 요청 최대 개수"),
|
||||
f("response.collectMs", Channels, Int { min: 0, max: 3000 }, json!(700), "중요도 비교 대기(ms)"),
|
||||
f("response.settleMs", Channels, Int { min: 0, max: 3000 }, json!(800), "먼저 끝난 말 전사 대기(ms)"),
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
//! shows how far it got. With `llm.url` the app uses that server instead and starts nothing.
|
||||
|
||||
use std::path::Path;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::atomic::{AtomicBool, AtomicI64, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
@@ -41,12 +41,6 @@ pub struct LlmStatus {
|
||||
pub note: Option<String>,
|
||||
}
|
||||
|
||||
/// Requests answered at once: one is faster on a 16 GB card (M0), two only when a chat channel
|
||||
/// answers every message (so its answers do not wait behind the voice answers).
|
||||
pub fn parallel(settings: &Settings) -> u32 {
|
||||
if settings.chat_channels.iter().any(|c| c.answer_all) { 2 } else { 1 }
|
||||
}
|
||||
|
||||
/// `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.
|
||||
@@ -68,8 +62,9 @@ pub fn launch_args(layout: &Layout, settings: &Settings, conf: &Conf, sets: &[St
|
||||
a
|
||||
}
|
||||
|
||||
/// The context and requests at once of a stage: the settings' in the normal stage; in a game 16K
|
||||
/// (or less when the settings ask for less) and one request at a time.
|
||||
/// The context and requests at once of a stage: the settings' context in the normal stage, in a
|
||||
/// game 16K (or less when the settings ask for less); always one request at a time (faster on a
|
||||
/// 16 GB card, M0; chat answers take turns with the voice answers).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct Conf {
|
||||
pub context: u32,
|
||||
@@ -82,7 +77,7 @@ pub fn conf(settings: &Settings, stage: Stage) -> Conf {
|
||||
let vision = vision(stage, crate::screen::available(settings));
|
||||
match stage {
|
||||
Stage::Gaming => Conf { context: crate::placement::GAME_CONTEXT.min(settings.llm.context), parallel: 1, vision },
|
||||
_ => Conf { context: settings.llm.context, parallel: parallel(settings), vision },
|
||||
_ => Conf { context: settings.llm.context, parallel: 1, vision },
|
||||
}
|
||||
}
|
||||
|
||||
@@ -279,9 +274,9 @@ pub struct Llm {
|
||||
/// A game runs (or may run) as the LLM is placed: set before `start` and at every `switch`.
|
||||
/// Only a normal placement made while none runs keeps its reading.
|
||||
game_running: AtomicBool,
|
||||
/// 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,
|
||||
/// What the voice worker's models (STT, TTS) hold on the card (set at switches while the worker
|
||||
/// runs), so it is not taken for another program's memory.
|
||||
worker_models_mib: AtomicI64,
|
||||
/// 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.
|
||||
@@ -307,7 +302,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), game_running: AtomicBool::new(false), stt_on_card: AtomicBool::new(false), room: Mutex::new(None), threads: Mutex::new(None),
|
||||
stop_timeout: Duration::from_secs(120), gpu: None, baseline: Mutex::new(None), game_running: AtomicBool::new(false), worker_models_mib: AtomicI64::new(0), room: Mutex::new(None), threads: Mutex::new(None),
|
||||
stage: Mutex::new((Stage::Normal, None)) }
|
||||
}
|
||||
|
||||
@@ -367,11 +362,10 @@ impl Llm {
|
||||
return Ok(Some(sets));
|
||||
}
|
||||
let Some(card) = self.read_gpu().await else { return Ok(Some(vec![])) };
|
||||
// Other programs: what the card holds without this LLM and without the STT worker's model.
|
||||
// Other programs: what the card holds without this LLM and without the voice worker's models.
|
||||
// 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 now_others = (card.used_mib - self.worker_models_mib.load(Ordering::SeqCst)).max(0);
|
||||
// Only a normal placement made while no game runs keeps its reading (a game's memory would be
|
||||
// taken for other programs'; also on the way back from a failed game stage).
|
||||
if stage != Stage::Gaming && !self.game_running.load(Ordering::SeqCst) {
|
||||
@@ -470,19 +464,20 @@ 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.worker_models_mib.store(0, 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.
|
||||
/// `stt_on_card`: the STT worker's model is loaded on the card; `game_running`: a game runs now.
|
||||
pub async fn switch(&self, settings: &Settings, stage: Stage, stt_on_card: bool, game_running: bool) -> Result<Stage, String> {
|
||||
/// `worker_models_mib`: what the voice worker's loaded models hold on the card
|
||||
/// (`placement::worker_models_mib`); `game_running`: a game runs now.
|
||||
pub async fn switch(&self, settings: &Settings, stage: Stage, worker_models_mib: i64, game_running: bool) -> Result<Stage, String> {
|
||||
if settings.llm.url.is_some() {
|
||||
return Ok(Stage::Normal);
|
||||
}
|
||||
self.stt_on_card.store(stt_on_card, Ordering::SeqCst);
|
||||
self.worker_models_mib.store(worker_models_mib, Ordering::SeqCst);
|
||||
self.game_running.store(game_running, Ordering::SeqCst);
|
||||
if stage != Stage::Paused && self.start_stage(settings, stage).await?.is_some() {
|
||||
return Ok(stage);
|
||||
@@ -654,6 +649,10 @@ pub(crate) mod tests {
|
||||
use crate::datadir::temp_dir;
|
||||
use crate::settings::{parse_settings, ChatChannelSettings};
|
||||
|
||||
/// Other programs on the fake cards: the game PC's 1460 MiB in M0 less the TTS's share, which
|
||||
/// the app keeps beside and M0 did not run, so M0's placements come out.
|
||||
pub(crate) const OTHERS: i64 = 1460 - crate::placement::TTS_MIB;
|
||||
|
||||
pub(crate) fn layout(tag: &str) -> Layout {
|
||||
Layout { data: temp_dir(tag), src: std::path::PathBuf::from("src") }
|
||||
}
|
||||
@@ -687,12 +686,12 @@ pub(crate) mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_chat_channel_answering_everything_gets_a_second_request_slot() {
|
||||
fn the_llm_takes_one_request_at_a_time_also_with_a_chat_channel_answering_everything() {
|
||||
let mut s = Settings::default();
|
||||
assert_eq!(parallel(&s), 1);
|
||||
s.chat_channels.push(ChatChannelSettings { id: 1, name: String::new(), description: String::new(), read: true,
|
||||
send: true, edit: true, react: true, delete: false, pin: false, answer_all: true, sync_discord: true });
|
||||
assert_eq!(parallel(&s), 2);
|
||||
let a = launch_args(&layout("llm-one"), &s, &conf(&s, Stage::Normal), &[]);
|
||||
assert_eq!(a[a.iter().position(|x| x == "--parallel").unwrap() + 1], "1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -886,7 +885,7 @@ pub(crate) mod tests {
|
||||
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
|
||||
// The game PC in M0 (16303 MiB card, `OTHERS` held by other programs); the LLM without
|
||||
// experts held 9874 MiB.
|
||||
let llm = Llm::with_exe(l.clone(), exe).with_gpu(card(&l, "GPU-test", 0));
|
||||
let s = parse_settings(&json!({"llm": {"port": port}})).unwrap();
|
||||
@@ -909,7 +908,7 @@ pub(crate) mod tests {
|
||||
assert!(launches[0].ends_with("--set expert-vram=1.5 --set prefill=2048"), "{}", launches[0]);
|
||||
}
|
||||
|
||||
/// A fake card for `fake_placed`: 16303 MiB, 1460 MiB held by other programs (and by any
|
||||
/// A fake card for `fake_placed`: 16303 MiB, `OTHERS` held by other programs (and by any
|
||||
/// server still left over, `leftover` MiB, until a `launch --stop`), and 9874 MiB more while a
|
||||
/// Strata server runs (the calls file shows the last launch and stop).
|
||||
#[cfg(unix)]
|
||||
@@ -919,7 +918,7 @@ pub(crate) mod tests {
|
||||
let c = std::fs::read_to_string(&calls).unwrap_or_default();
|
||||
let stopped = c.contains("launch --stop");
|
||||
let running = c.lines().last().is_some_and(|x| x.starts_with("launch --family"));
|
||||
let used = 1460 + if running { 9874 } else if stopped { 0 } else { leftover };
|
||||
let used = OTHERS + if running { 9874 } else if stopped { 0 } else { leftover };
|
||||
Some(Gpu { id: id.into(), used_mib: used, total_mib: 16303 })
|
||||
})
|
||||
}
|
||||
@@ -954,7 +953,7 @@ pub(crate) mod tests {
|
||||
let reads = Arc::new(std::sync::atomic::AtomicU32::new(0));
|
||||
let r2 = reads.clone();
|
||||
let llm = Llm::with_exe(l.clone(), fake_placed(&l)).with_gpu(Arc::new(move || {
|
||||
(r2.fetch_add(1, Ordering::SeqCst) == 0).then(|| Gpu { id: "GPU-test".into(), used_mib: 1460, total_mib: 16303 })
|
||||
(r2.fetch_add(1, Ordering::SeqCst) == 0).then(|| Gpu { id: "GPU-test".into(), used_mib: OTHERS, total_mib: 16303 })
|
||||
}));
|
||||
let s = parse_settings(&json!({"llm": {"port": port}})).unwrap();
|
||||
tokio::time::timeout(Duration::from_secs(20), llm.start(&s)).await.expect("starts").unwrap();
|
||||
@@ -975,7 +974,7 @@ pub(crate) mod tests {
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn the_measurement_is_kept_per_requests_at_once_and_per_card() {
|
||||
async fn the_measurement_is_kept_per_context_and_per_card() {
|
||||
let l = layout("llm-place-keys");
|
||||
let llm = Llm::with_exe(l.clone(), fake_placed(&l)).with_gpu(card(&l, "GPU-a", 0));
|
||||
let port = server_after_launch(&l, "list").await;
|
||||
@@ -983,13 +982,11 @@ pub(crate) mod tests {
|
||||
llm.start(&one).await.unwrap();
|
||||
assert_eq!(launches(&l).len(), 2, "measured once");
|
||||
llm.stop().await.unwrap();
|
||||
// A chat channel that answers everything: two requests at once, measured again.
|
||||
// Another context: measured again.
|
||||
std::fs::remove_file(l.data.join("calls")).unwrap();
|
||||
let two = parse_settings(&json!({"llm": {"port": port}, "chatChannels": [{"id": "123456789012345678", "answer": "everything"}]})).unwrap();
|
||||
assert_eq!(parallel(&two), 2);
|
||||
llm.start(&two).await.unwrap();
|
||||
assert_eq!(launches(&l).len(), 2, "measured for two at once");
|
||||
assert!(launches(&l)[0].contains("--parallel 2"));
|
||||
let short = parse_settings(&json!({"llm": {"port": port, "context": 16384}})).unwrap();
|
||||
llm.start(&short).await.unwrap();
|
||||
assert_eq!(launches(&l).len(), 2, "measured for the other context");
|
||||
llm.stop().await.unwrap();
|
||||
// Another card (same size): measured again.
|
||||
std::fs::remove_file(l.data.join("calls")).unwrap();
|
||||
@@ -997,7 +994,7 @@ pub(crate) mod tests {
|
||||
llm.start(&one).await.unwrap();
|
||||
assert_eq!(launches(&l).len(), 2, "measured for the new card");
|
||||
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/1"]["gpu"].clone(), probe["32768/2"]["gpu"].clone()), (json!("GPU-b"), json!("GPU-a")));
|
||||
assert_eq!((probe["32768/1"]["gpu"].clone(), probe["16384/1"]["gpu"].clone()), (json!("GPU-b"), json!("GPU-a")));
|
||||
llm.stop().await.unwrap();
|
||||
}
|
||||
|
||||
@@ -1030,38 +1027,38 @@ 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, false, true)).await.unwrap().unwrap(), Stage::Gaming);
|
||||
assert_eq!(tokio::time::timeout(Duration::from_secs(30), llm.switch(&s, Stage::Gaming, 0, true)).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.
|
||||
assert_eq!(g.len(), 2, "{g:?}");
|
||||
assert!(g[0].contains("--context 16384") && g[0].contains("--parallel 1") && g[0].contains("--set expert-vram=0"), "{}", g[0]);
|
||||
assert!(g[1].ends_with("--set expert-vram=2 --set prefill=2048 --set pool-workers=8"), "{}", g[1]);
|
||||
let room = 16303 - 1460 - 9874 - crate::placement::STT_MIB - crate::placement::MARGIN_MIB - 921;
|
||||
let room = 16303 - OTHERS - 9874 - crate::placement::STT_MIB - crate::placement::TTS_MIB - crate::placement::MARGIN_MIB - 921;
|
||||
assert_eq!(llm.stage_view(), json!({"stage": "gaming", "gameRoomMib": room}));
|
||||
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, false, false).await.unwrap(), Stage::Normal);
|
||||
assert_eq!(llm.switch(&s, Stage::Normal, 0, 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, false, true).await.unwrap(), Stage::Paused);
|
||||
assert_eq!(llm.switch(&s, Stage::Paused, 0, true).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.
|
||||
/// A card whose other programs hold `others` MiB (changeable), plus the voice worker's models
|
||||
/// (`worker` MiB), plus 9874 MiB while a Strata server runs.
|
||||
#[cfg(unix)]
|
||||
fn live_card(l: &Layout, others: Arc<std::sync::atomic::AtomicI64>, stt: bool) -> GpuReader {
|
||||
fn live_card(l: &Layout, others: Arc<std::sync::atomic::AtomicI64>, worker: i64) -> 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 };
|
||||
let used = others.load(Ordering::SeqCst) + worker + if running { 9874 } else { 0 };
|
||||
Some(Gpu { id: "GPU-test".into(), used_mib: used, total_mib: 16303 })
|
||||
})
|
||||
}
|
||||
@@ -1071,25 +1068,48 @@ pub(crate) mod tests {
|
||||
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));
|
||||
let others = Arc::new(std::sync::atomic::AtomicI64::new(OTHERS));
|
||||
// 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 llm = Llm::with_exe(l.clone(), fake_placed(&l)).with_gpu(live_card(&l, others.clone(), 0));
|
||||
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));
|
||||
let stt = crate::placement::worker_models_mib(true, false);
|
||||
let llm = llm.with_gpu(live_card(&l, others.clone(), stt));
|
||||
// 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, true).await.unwrap();
|
||||
others.store(OTHERS + 2500, Ordering::SeqCst);
|
||||
llm.switch(&s, Stage::Gaming, stt, 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, false).await.unwrap();
|
||||
let expected = crate::placement::normal(16303, 1460 + 1000, &crate::placement::Probe { context: 32768, parallel: 1,
|
||||
others.store(OTHERS + 1000, Ordering::SeqCst);
|
||||
llm.switch(&s, Stage::Normal, stt, false).await.unwrap();
|
||||
let expected = crate::placement::normal(16303, OTHERS + 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 the_voice_models_loaded_after_the_start_change_nothing_on_the_way_back() {
|
||||
// At the start neither the STT nor the TTS has loaded; at the switches both hold the card.
|
||||
// With nothing else changed, the normal stage comes back with the placement it started with.
|
||||
let l = layout("llm-stage-voice");
|
||||
let port = server_after_launch(&l, "list").await;
|
||||
let others = Arc::new(std::sync::atomic::AtomicI64::new(460));
|
||||
let llm = Llm::with_exe(l.clone(), fake_placed(&l)).with_gpu(live_card(&l, others.clone(), 0));
|
||||
let s = parse_settings(&json!({"llm": {"port": port}})).unwrap();
|
||||
llm.start(&s).await.unwrap();
|
||||
let first = launches(&l).last().unwrap().clone();
|
||||
let voice = crate::placement::worker_models_mib(true, true);
|
||||
let held = crate::placement::STT_MODEL_MIB + crate::placement::TTS_MIB;
|
||||
let llm = llm.with_gpu(live_card(&l, others.clone(), held));
|
||||
llm.switch(&s, Stage::Gaming, voice, true).await.unwrap();
|
||||
llm.switch(&s, Stage::Normal, voice, false).await.unwrap();
|
||||
let back = launches(&l).last().unwrap().clone();
|
||||
assert!(!first.contains("--set expert-vram=0 "), "the test has room for experts: {first}");
|
||||
assert_eq!(back, first);
|
||||
}
|
||||
|
||||
/// `live_card` on a card of `total` MiB.
|
||||
#[cfg(unix)]
|
||||
fn live_card_of(l: &Layout, others: Arc<std::sync::atomic::AtomicI64>, total: i64) -> GpuReader {
|
||||
@@ -1107,33 +1127,33 @@ pub(crate) mod tests {
|
||||
// A game holds 2500 MiB already: it is in what the card holds, so no reserve on top.
|
||||
let l = layout("llm-stage-game-at-start");
|
||||
let port = server_after_launch(&l, "list").await;
|
||||
let others = Arc::new(std::sync::atomic::AtomicI64::new(1460 + 2500));
|
||||
let others = Arc::new(std::sync::atomic::AtomicI64::new(OTHERS + 2500));
|
||||
let llm = Llm::with_exe(l.clone(), fake_placed(&l)).with_gpu(live_card_of(&l, others.clone(), 16303));
|
||||
llm.game_at_start(true);
|
||||
let s = parse_settings(&json!({"llm": {"port": port}})).unwrap();
|
||||
llm.start(&s).await.unwrap();
|
||||
assert_eq!(llm.switch(&s, Stage::Gaming, false, true).await.unwrap(), Stage::Gaming, "not paused");
|
||||
assert_eq!(llm.switch(&s, Stage::Gaming, 0, true).await.unwrap(), Stage::Gaming, "not paused");
|
||||
let probe16 = crate::placement::Probe { context: 16384, parallel: 1, gpu: "GPU-test".into(), model_mib: 9874, staging_gib: 1.1 };
|
||||
let expected = crate::placement::normal(16303, 1460 + 2500, &probe16, 1024);
|
||||
let expected = crate::placement::normal(16303, OTHERS + 2500, &probe16, 1024);
|
||||
assert!(launches(&l).last().unwrap().contains(&format!("--set expert-vram={expected} ")), "{:?}", launches(&l));
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn the_game_stage_reads_the_card_again_and_counts_what_grew_since_the_normal_reading() {
|
||||
// Normal reading: 1460 MiB. Then a program takes 4000 MiB and the game 4500 MiB: together
|
||||
// Normal reading: OTHERS. Then a program takes 4000 MiB and the game 4500 MiB: together
|
||||
// more than the 8 GB reserve, so the placement leaves that much, not just 8 GB.
|
||||
let l = layout("llm-stage-grew");
|
||||
let port = server_after_launch(&l, "list").await;
|
||||
let others = Arc::new(std::sync::atomic::AtomicI64::new(1460));
|
||||
let others = Arc::new(std::sync::atomic::AtomicI64::new(OTHERS));
|
||||
let llm = Llm::with_exe(l.clone(), fake_placed(&l)).with_gpu(live_card_of(&l, others.clone(), 24576));
|
||||
let s = parse_settings(&json!({"llm": {"port": port}})).unwrap();
|
||||
llm.start(&s).await.unwrap();
|
||||
others.store(1460 + 4000 + 4500, Ordering::SeqCst);
|
||||
llm.switch(&s, Stage::Gaming, false, true).await.unwrap();
|
||||
others.store(OTHERS + 4000 + 4500, Ordering::SeqCst);
|
||||
llm.switch(&s, Stage::Gaming, 0, true).await.unwrap();
|
||||
let probe16 = crate::placement::Probe { context: 16384, parallel: 1, gpu: "GPU-test".into(), model_mib: 9874, staging_gib: 1.1 };
|
||||
let expected = crate::placement::game(24576, 1460, &probe16, 8500).expert_gib;
|
||||
assert_ne!(expected, crate::placement::game(24576, 1460, &probe16, 8192).expert_gib, "the test tells them apart");
|
||||
let expected = crate::placement::game(24576, OTHERS, &probe16, 8500).expert_gib;
|
||||
assert_ne!(expected, crate::placement::game(24576, OTHERS, &probe16, 8192).expert_gib, "the test tells them apart");
|
||||
assert!(launches(&l).last().unwrap().contains(&format!("--set expert-vram={expected} ")), "{:?}", launches(&l));
|
||||
}
|
||||
|
||||
@@ -1150,9 +1170,9 @@ pub(crate) mod tests {
|
||||
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 })
|
||||
(r2.fetch_add(1, Ordering::SeqCst) == 0).then(|| Gpu { id: "GPU-test".into(), used_mib: OTHERS, total_mib: 16303 })
|
||||
}));
|
||||
assert_eq!(llm.switch(&s, Stage::Gaming, false, true).await.unwrap(), Stage::Gaming);
|
||||
assert_eq!(llm.switch(&s, Stage::Gaming, 0, true).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}));
|
||||
}
|
||||
@@ -1167,11 +1187,11 @@ pub(crate) mod tests {
|
||||
let llm = Llm::with_exe(l.clone(), fake_placed(&l)).with_gpu(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"));
|
||||
Some(Gpu { id: "GPU-small".into(), used_mib: 1460 + if running { 9874 } else { 0 }, total_mib: 12288 })
|
||||
Some(Gpu { id: "GPU-small".into(), used_mib: OTHERS + if running { 9874 } else { 0 }, total_mib: 12288 })
|
||||
}));
|
||||
let s = parse_settings(&json!({"llm": {"port": port}})).unwrap();
|
||||
llm.start(&s).await.unwrap();
|
||||
assert_eq!(llm.switch(&s, Stage::Gaming, false, true).await.unwrap(), Stage::Paused);
|
||||
assert_eq!(llm.switch(&s, Stage::Gaming, 0, true).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();
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
Every distinct LLM call in Jarvis, what feeds it, what consumes it, and how it is gated. This is the reference for optimising the app's main bottleneck (LLM latency). Keep it in sync with the code — see the note at the bottom.
|
||||
|
||||
**Transport (all contexts below).** `ollama_base_url` selects the API. A URL that ends in `/v1` (v2: Strata at `http://127.0.0.1:8080/v1`, which the app starts and writes with the model id Strata lists into the brain's `config/brain.json`, `app/src/strata.rs`; also llama.cpp or Ollama's own `/v1`) uses the OpenAI-compatible API: chat goes to `/chat/completions`, embeddings to `/embeddings`, and the warm-up is a one-token chat completion. Any other URL uses Ollama's `/api/chat`, `/api/generate` and `/api/embeddings`. The conversion lives in `src/jarvis/llm.py` only: callers keep sending Ollama-shaped messages and reading Ollama-shaped responses (`message.content`, `message.tool_calls` with dict arguments, `message.thinking` from `reasoning_content`). On the OpenAI path `num_ctx` and `keep_alive` are not sent (the server owns its context size and residency), `num_predict` becomes `max_tokens`, and the thinking switch becomes `chat_template_kwargs.enable_thinking`. The `num_ctx: 8192` limits listed below apply to the Ollama path. Ollama's own `/v1` ignores `num_ctx` and runs at its default context (2,048 tokens here), which cuts the system prompt; to test the OpenAI path on Ollama use a model tag created with a larger `num_ctx`. A server with no embedding model (Strata) answers `/embeddings` with an error and every embedding consumer fails open to its text path. In v2 the app also sets Strata's context per performance stage (`app/src/admin.spec.md`, "Performance stages"): the settings' `llm.context` (default 32,768 tokens) normally and 16,384 tokens with one request at a time while a game runs; while it switches the voice worker starts no LLM call (requests wait, at most 180 s, `voice_worker.spec.md` "LLM switches"), and while paused (a game with no room for the model) every brain call fails at once.
|
||||
**Transport (all contexts below).** `ollama_base_url` selects the API. A URL that ends in `/v1` (v2: Strata at `http://127.0.0.1:8080/v1`, which the app starts and writes with the model id Strata lists into the brain's `config/brain.json`, `app/src/strata.rs`; also llama.cpp or Ollama's own `/v1`) uses the OpenAI-compatible API: chat goes to `/chat/completions`, embeddings to `/embeddings`, and the warm-up is a one-token chat completion. Any other URL uses Ollama's `/api/chat`, `/api/generate` and `/api/embeddings`. The conversion lives in `src/jarvis/llm.py` only: callers keep sending Ollama-shaped messages and reading Ollama-shaped responses (`message.content`, `message.tool_calls` with dict arguments, `message.thinking` from `reasoning_content`). On the OpenAI path `num_ctx` and `keep_alive` are not sent (the server owns its context size and residency), `num_predict` becomes `max_tokens`, and the thinking switch becomes `chat_template_kwargs.enable_thinking`. Every call that no later request continues (all `call_llm_direct` and `call_llm_streaming` calls, the warm-up and the v1 intent judge; not the reply loop's `chat_with_messages`, whose next step continues it) carries `"strata_checkpoint": false`: Strata's Qwen3.6 engine then gives that call's session away first, so with two or more requests at once a reply's tool turn keeps its session through the short calls made between its steps (with one request at once nothing changes, and Strata releases up to 0.1.59 ignore the field on this engine); other servers ignore it. The `num_ctx: 8192` limits listed below apply to the Ollama path. Ollama's own `/v1` ignores `num_ctx` and runs at its default context (2,048 tokens here), which cuts the system prompt; to test the OpenAI path on Ollama use a model tag created with a larger `num_ctx`. A server with no embedding model (Strata) answers `/embeddings` with an error and every embedding consumer fails open to its text path. In v2 the app also sets Strata's context per performance stage (`app/src/admin.spec.md`, "Performance stages"): the settings' `llm.context` (default 32,768 tokens) normally and 16,384 tokens with one request at a time while a game runs; while it switches the voice worker starts no LLM call (requests wait, at most 180 s, `voice_worker.spec.md` "LLM switches"), and while paused (a game with no room for the model) every brain call fails at once.
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -40,12 +40,12 @@
|
||||
|
||||
| 정책 | 새 요청 처리 | 봇이 말하는 중에 새 요청이 오면 |
|
||||
|---|---|---|
|
||||
| **처음 대화만 (기본값)** | 봇이 답을 준비하거나 말하는 동안 들어온 새 요청은 버립니다. 지금 답이 끝나야 다음 요청을 받습니다. 여러 명이 거의 동시에 부르면 **말이 먼저 끝난 사람** 하나에 답합니다. 먼저 끝난 말이 아직 전사 중이면 호출인지 확인될 때까지 잠깐 기다립니다. | 지금 답을 끝까지 재생하고, 새 요청은 버립니다. |
|
||||
| **처음 대화만** | 봇이 답을 준비하거나 말하는 동안 들어온 새 요청은 버립니다. 지금 답이 끝나야 다음 요청을 받습니다. 여러 명이 거의 동시에 부르면 **말이 먼저 끝난 사람** 하나에 답합니다. 먼저 끝난 말이 아직 전사 중이면 호출인지 확인될 때까지 잠깐 기다립니다. | 지금 답을 끝까지 재생하고, 새 요청은 버립니다. |
|
||||
| 들어온 순서대로 | 요청마다 **말이 끝난 시각**으로 순번을 붙여 그 순서대로 답합니다. 전사가 끝난 순서가 아니므로 길게 말한 사람이 뒤로 밀리지 않습니다. 대기열 최대 길이를 넘으면 가장 오래된 요청부터 버립니다. | 지금 답을 끝까지 재생하고, 새 요청은 대기열에 넣습니다. |
|
||||
| 마지막 대화만 | 대기열에 가장 최근 요청 하나만 남깁니다. | 지금 답을 멈추고 가장 최근 요청에 바로 답합니다. 멈춘 답은 다시 재생하지 않습니다. |
|
||||
| **마지막 대화만 (기본값)** | 대기열에 가장 최근 요청 하나만 남깁니다. | 지금 답을 멈추고 가장 최근 요청에 바로 답합니다. 멈춘 답은 다시 재생하지 않습니다. |
|
||||
| 제일 중요한 대화만 | 짧은 수집 시간(기본 0.7초)과 봇이 말하는 동안 들어온 요청을 모아 점수를 매기고, 가장 높은 하나에만 답합니다. 판단 기준은 (1) 사람별 우선순위, (2) 호출어로 직접 불렀는지, (3) LLM이 판단한 중요도 순입니다. 후보가 2개 이상일 때만 LLM 판단을 하므로 평소에는 지연이 늘지 않습니다. | 새 요청의 점수가 더 높으면 멈추고 새 요청에 답합니다. 낮거나 같으면 끝까지 재생하고, 그 뒤 남은 후보 중 가장 높은 것에 답합니다. |
|
||||
|
||||
LLM이 동시에 처리하는 요청 수는 이 정책과 상관없이 채팅 채널 설정을 따릅니다([LLM 동시 요청 수](#llm-동시-요청-수)). 음성 답은 어느 정책이든 한 번에 하나씩 준비하고, 한 답의 글은 말하기보다 훨씬 빨리 끝나므로 다음 답 준비가 밀리지 않습니다.
|
||||
LLM은 이 정책과 상관없이 요청을 하나씩 처리합니다([LLM 동시 요청 수](#llm-동시-요청-수)). 음성 답은 어느 정책이든 한 번에 하나씩 준비하고, 한 답의 글은 말하기보다 훨씬 빨리 끝나므로 다음 답 준비가 밀리지 않습니다.
|
||||
|
||||
버려진 요청과 중간에 멈춘 답은 대시보드의 "놓친 요청" 목록에 남아서, 무엇이 왜 빠졌는지 볼 수 있습니다.
|
||||
|
||||
@@ -62,7 +62,7 @@ LLM이 동시에 처리하는 요청 수는 이 정책과 상관없이 채팅
|
||||
|
||||
### LLM 동시 요청 수
|
||||
|
||||
채팅 채널 중 하나라도 "모든 메시지에 대답"이면 LLM이 요청을 2개 이상(그래픽카드에 맞는 수, 최소 2개) 동시에 처리합니다. 그 채널에서는 사람마다 메시지가 따로 들어오고 각자 글로 답을 받으므로, 한 답이 끝나기를 기다리지 않고 함께 준비해야 하고 음성 답도 채팅 답 뒤로 밀리지 않습니다. 그런 채널이 없으면 음성 응답 정책과 상관없이 1개입니다. 16GB 카드에서는 1개일 때 답이 더 빠릅니다(출력 97 대 70~75 tok/s). 이 수는 LLM을 다시 시작해야 바뀌므로, 첫 "모든 메시지에 대답" 채널을 켜거나 마지막 하나를 끄면 지금 답이 끝난 뒤 다시 시작합니다(약 30초). 게임 중에는 1개입니다([pc-features.md](pc-features.md#자동-성능-조절)).
|
||||
LLM은 요청을 항상 하나씩 처리합니다. 채팅 채널이 "모든 메시지에 대답"이어도 같아서, 채팅 답과 음성 답은 LLM에서 차례를 기다립니다. 16GB 카드에서는 1개일 때 답이 더 빠르고(출력 97 대 70~75 tok/s), 2개로 둔 날(2026-11-16)에는 프롬프트 읽기가 약 3배 느려져 답이 10~20초 걸렸습니다(사용자 결정, 2026-11-17). 게임 중에도 1개입니다([pc-features.md](pc-features.md#자동-성능-조절)).
|
||||
|
||||
- **음성과 연결**: 음성으로 "자비스, 채팅 채널에 오늘 할 일 올려 줘", "채팅에 방금 뭐 올라왔어?"처럼 시킬 수 있습니다.
|
||||
- **디스코드 제약**: 봇은 자기가 쓴 메시지만 수정할 수 있습니다. 다른 사람 메시지는 삭제·고정만 되고, 서버에서 메시지 관리 권한을 줘야 합니다.
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
| 관리 앱 언어 | Rust. 화면(M5)은 Tauri 2로 Windows 기본 WebView2에 그림(2026-11-11, 사용자가 맡긴 판단). 같은 M2 음성 코어를 Electron과 Rust로 둘 다 만들어 실제 디스코드에서 비교함: 받아 적기·말하기·정지 결과는 같았고, Rust는 실행 파일 하나에 메모리 약 16MB(Electron은 프로세스 5개, 크로미움 GPU 프로세스 포함)라 게임과 함께 돌리는 이 앱에 맞음. 게임 감지, 화면 캡처, 입력, 프로세스 우선순위(M7)도 Windows API를 바로 부를 수 있음. 약점은 Rust 디스코드 음성 라이브러리(songbird)가 덜 검증된 점: DAVE 수신 해독 버그는 앱이 직접 해독해 피했고, 그룹이 바뀐 뒤 받기가 멈춘다는 보고(#310)는 들어왔다 나가기 3번 시험에서 재현되지 않음. 몇 시간짜리 시험에서 멈추면 그 부분만 discord.js 보조 프로세스로 돌리는 것을 예비안으로 둠 ([architecture.md](architecture.md#기술-선택과-이유)) |
|
||||
| 호출 방식 기본값 | 호출어로 부를 때만 응답 |
|
||||
| 지정한 사람 설정 | "지정한 사람만 응답"과 "지정한 사람은 호출어 없이 대답"을 각각 켜기/끄기. 기본은 둘 다 꺼짐 ([conversation.md](conversation.md#호출어와-호출-방식)) |
|
||||
| 동시 대화 응답 정책 기본값 | 처음 대화만 |
|
||||
| 동시 대화 응답 정책 기본값 | 마지막 대화만(사용자 결정, 2026-11-17. 처음에는 처음 대화만) |
|
||||
| "제일 중요한 대화" 판단 기준 | 사람별 우선순위 → 호출어로 직접 불렀는지 → LLM이 판단한 중요도 |
|
||||
| 대화 기억 범위 기본값 | 본인 기록 + 등록한 채팅 채널 + 같은 음성 채널에 함께 있던 다른 사람 말. 채팅 채널과 다른 사람 말은 각각 켜기/끄기, 기본은 둘 다 켜짐 ([memory.md](memory.md)) |
|
||||
| 가상 디스플레이 드라이버 | 필요해지면 설치. 설치 때 관리자 권한 1회. 우리 설치 파일 하나로 어느 PC에서나 돼야 하므로 Parsec 드라이버는 제품에 쓰지 않음(M0 개념 확인용으로만 사용). 대상은 x64 Windows 10/11(S 모드 제외). ARM64는 WHQL 서명이 필요해 범위 밖. 배포할 드라이버는 오픈소스 Virtual Display Driver(MIT, SignPath 재단 서명, IddCx)를 설치 파일에 함께 넣음(사용자 선택). 자체 드라이버는 만들지 않음 |
|
||||
@@ -35,7 +35,7 @@
|
||||
|---|---|
|
||||
| TTS | MeloTTS만 기본 제공. CosyVoice2/3는 첫 소리까지 중앙값 3.4~3.6초라 뺌. 앱 시작 때 한 번 미리 합성(첫 합성 30초) |
|
||||
| STT | large-v3-turbo, `int8_float16`(모델 1.3GB, 10명 동시 전사 때 1.44GB 더 늘어 최대 약 2.7GB). `float16`과 정확도가 같았음 |
|
||||
| LLM | Qwen3.6-35B-A3B 하나(위 표). 동시 요청은 채팅 채널 설정을 따름: "모든 메시지에 대답" 채널이 하나라도 있으면 2개 이상(카드에 맞는 수, 최소 2개), 없으면 음성 응답 정책과 상관없이 1개(사용자 결정, 2026-11-10. 16GB 카드에서 1개가 출력 97 tok/s로 2개의 70~75 tok/s보다 빠름). 게임 중에는 채널 설정과 상관없이 1개. 이미지는 GPU 처리, 화질 1280x720, 음성 답변은 생각 모드 끔. 함께 잰 Qwen3.8-Flash-Next(Q2_0, MTP 보조 모델)는 출력 131 tok/s로 82 tok/s보다 빨랐지만 음성 답변 첫 문장(0.58초 대 0.36초), 맥락 8천 토큰 첫 토큰(2.1초 대 1.6초), 이미지 1장 답변 시작(1.3초 대 0.6초)이 모두 느리고, 한국어 답에 한자(礼貌)가 한 번 섞였고, 아래 도구 호출 문제가 있어 뺌 |
|
||||
| LLM | Qwen3.6-35B-A3B 하나(위 표). 동시 요청은 항상 1개(사용자 결정, 2026-11-17. 16GB 카드에서 1개가 출력 97 tok/s로 2개의 70~75 tok/s보다 빠르고, 2개로 쓴 날 프롬프트 읽기가 약 3배 느려짐. 2026-11-10에는 "모든 메시지에 대답" 채팅 채널이 있으면 2개로 정했었음). 이미지는 GPU 처리, 화질 1280x720, 음성 답변은 생각 모드 끔. 함께 잰 Qwen3.8-Flash-Next(Q2_0, MTP 보조 모델)는 출력 131 tok/s로 82 tok/s보다 빨랐지만 음성 답변 첫 문장(0.58초 대 0.36초), 맥락 8천 토큰 첫 토큰(2.1초 대 1.6초), 이미지 1장 답변 시작(1.3초 대 0.6초)이 모두 느리고, 한국어 답에 한자(礼貌)가 한 번 섞였고, 아래 도구 호출 문제가 있어 뺌 |
|
||||
| 지난 대화 맥락 | 약 8천 토큰에서 시작(텍스트 첫 문장 1.8초). 상한은 M4에서 왕복 지연을 실측해 정함 |
|
||||
| 도구 호출 | Strata에서 동작(빠름 12번 중 9번, 권장 12번 중 8번). 둘 다 도구를 부르지 않고 한 척하는 경우가 있음: 빠름 모델은 "5분 타이머 맞춰 줘"에서 "설정했습니다"라고만 답하고(3번 모두), 권장 모델은 "서울 날씨 어때?"에서 날씨를 지어내 답함(3번 모두). 두뇌 코드에서 고침(2026-11-10): (1) 지시문에 "바뀌는 정보(날씨·뉴스·가격·화면)는 이번 턴 도구 결과로만 말하고, 동작은 도구가 성공했을 때만 했다고 말한다"는 규칙을 넣고, 지시문 끝에 이번 턴에 쓸 수 있는 도구 이름을 다시 적음. (2) 모델이 계획 단계가 고른 도구를 건너뛰고 답하면 그 답을 버리고 계획에 적힌 호출을 직접 실행한 뒤 결과로 다시 답하게 함(인자가 도구 형식에 맞을 때만, 아니면 원래 답 유지). (3) 계획 단계에 도구 인자 이름을 보여 줌. 측정 키트 `tools_fast`/`tools_recommended` 단계로 두 모델에서 다시 확인. 수정 후에도 틀리면 모델을 바꿈(사용자 결정): 키트가 같은 계열의 덜 압축된 모델(빠름: UD-Q6_K_XL, Q8_0 / 권장: IQ3_XXS, IQ3_S)을 차례로 재고, 처음 통과한 모델을 기본값으로 함. 재측정 결과(2026-11-10): 빠름 모델 UD-Q4_K_XL이 27번 모두 통과해 기본값 그대로 둠. 도구를 모두 모델이 직접 불렀고 "건너뛴 도구 직접 실행" 장치는 한 번도 돌지 않음. (처음 채점에서는 "할 수 있는 도구는 없습니다/준비되어 있지 않습니다"를 거절로 읽지 못해 6번을 실패로 잘못 매겼고, 그래서 Q6_K_XL과 Q8_0까지 받아 잼. 채점을 고친 뒤 세 모델 모두 27번 통과.) 권장 모델은 Q2_0, IQ3_XXS, IQ3_S 모두 27번 중 24번: "거실 불 꺼 줘"에서 계획 단계는 도구가 필요 없다고 했는데 상관없는 도구(화면 보기, 날씨, 한 번은 0분 타이머)를 부름. 압축 정도와 상관없는 모델 성질이라 권장 모델은 뺌 |
|
||||
| 분리된 화면공유 창 | 분리 창은 하나뿐이고 그 안에서 볼 화면공유를 고름. 창 제목에는 음성 채널 이름만 있어 누구 화면인지 모름. 누가 공유 중인지는 음성 채널 상태로 확인. 물어본 사람이 공유 중이 아니면 그렇다고 답함. 공유 중이면 공유자가 여러 명이어도 따로 묻지 않고 분리 창을 바로 캡처(사용자가 이미 그 사람 화면을 보고 있음). 가려져도 영상은 계속 그려짐 |
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
|---|---|
|
||||
| 독점 전체화면 | Windows가 알려 주는 "전체화면 D3D 앱 실행 중" 상태로 감지합니다. |
|
||||
| 테두리 없는 창 모드 (borderless) | 앞에 있는 창이 아래 세 조건을 모두 만족하면 게임으로 봅니다. 셋 다 맞아야 하므로 일반 프로그램을 최대화한 것과 구분됩니다. (1) 모니터 한 장을 빈틈없이 덮습니다. (2) 제목 표시줄·테두리가 없습니다. (3) 그 프로세스가 GPU 3D 엔진을 일정 수준 이상 씁니다. |
|
||||
| 게임 폴더·목록 | Steam, Epic, Riot, Battle.net 게임 폴더에서 실행된 프로그램과 GUI에서 직접 등록한 게임은 창 모양과 상관없이 게임으로 봅니다. Battle.net 게임은 아무 폴더에나 설치되므로 Windows에 등록된 설치 정보(프로그램 제거 목록)에서 설치 폴더를 찾습니다. |
|
||||
| 게임 폴더·목록 | Steam, Epic, Riot, Battle.net 게임 폴더에서 실행된 프로그램과 GUI에서 직접 등록한 게임은 창 모양과 상관없이 게임으로 봅니다. 단, 런처 자신의 폴더와 게임이 아닌 앱의 폴더(Steam의 `Steamworks Shared`·`wallpaper_engine`, Epic의 `Launcher`·`Epic Online Services`, Riot의 `Riot Client`)는 빼서, 늘 켜져 있는 Wallpaper Engine이나 Riot 클라이언트 크래시 핸들러를 게임으로 잡지 않습니다(2026-11-17). Battle.net 게임은 아무 폴더에나 설치되므로 Windows에 등록된 설치 정보(프로그램 제거 목록)에서 설치 폴더를 찾습니다. |
|
||||
| 게임이 아닌 것 | 브라우저 전체화면 영상, 동영상 플레이어, 바탕화면, 디스코드, 봇용 크롬은 제외합니다. 잘못 잡히는 프로그램은 "게임 아님" 목록에 넣습니다. |
|
||||
|
||||
한 번 게임으로 감지되면 게임 프로세스가 끝날 때까지 게임 모드를 유지합니다. Alt+Tab으로 다른 창을 봐도 마찬가지입니다. 게임이 뒤에 있어도 VRAM은 계속 쓰기 때문입니다. 대시보드에는 "게임 모드: 켜짐 (게임 이름, 감지 이유)"를 표시합니다.
|
||||
@@ -25,16 +25,16 @@
|
||||
|
||||
| 단계 | 언제 | LLM 배치 (다시 시작 필요) | 다시 시작 없이 바꾸는 것 |
|
||||
|---|---|---|---|
|
||||
| 평소 | 게임이 없고 VRAM이 넉넉함 | 전문가 층의 VRAM 몫(`--expert-vram`)을 STT 몫과 다른 프로그램용 여유(기본 1GB)를 남기고 계산해서 정함(아래 식, 게임용으로 비울 VRAM은 0). Strata 자동 배치는 STT 자리를 남기지 않아 쓰지 않음(아래 측정 결과). 이미지는 GPU로 읽기. 동시 요청 수는 [채팅 채널 설정](conversation.md#llm-동시-요청-수)을 따름: "모든 메시지에 대답" 채널이 하나라도 있으면 2개 이상(이 카드에 맞는 수, 최소 2개), 없으면 1개(하나씩 보면 더 빠름) | 화면 캡처 미리 준비(말하는 중), 화질 보통, 지난 대화 약 8천 토큰 |
|
||||
| 게임 중 | 게임을 감지했거나, 다른 프로그램이 VRAM을 써서 남은 VRAM이 "게임용으로 비울 VRAM"보다 적음 | 전문가 층의 VRAM 몫(`--expert-vram`)을 줄여 "게임용으로 비울 VRAM"(기본 8GB)을 비움. 나머지 전문가 층은 RAM에서 CPU로 계산. 동시 요청 1개(채팅 채널 설정과 상관없이), 이미지는 CPU로 읽기, 엔진 CPU 작업자는 절반(16코어 PC에서 8개), 맥락 16K. 대화 메모리 형식(`--kv`)과 MTP 끄기는 이 엔진에서 VRAM을 줄이지 않아 쓰지 않음(아래 측정 결과) | 캡처 미리 준비 끔, 화질 빠름(긴 변 768px), 지난 대화 약 4천 토큰 |
|
||||
| 평소 | 게임이 없고 VRAM이 넉넉함 | 전문가 층의 VRAM 몫(`--expert-vram`)을 STT 몫과 다른 프로그램용 여유(기본 1GB)를 남기고 계산해서 정함(아래 식, 게임용으로 비울 VRAM은 0). Strata 자동 배치는 STT 자리를 남기지 않아 쓰지 않음(아래 측정 결과). 이미지는 GPU로 읽기. 동시 요청 1개([LLM 동시 요청 수](conversation.md#llm-동시-요청-수), 하나씩 보면 더 빠름) | 화면 캡처 미리 준비(말하는 중), 화질 보통, 지난 대화 약 8천 토큰 |
|
||||
| 게임 중 | 게임을 감지했거나, 다른 프로그램이 VRAM을 써서 남은 VRAM이 "게임용으로 비울 VRAM"보다 적음 | 전문가 층의 VRAM 몫(`--expert-vram`)을 줄여 "게임용으로 비울 VRAM"(기본 8GB)을 비움. 나머지 전문가 층은 RAM에서 CPU로 계산. 동시 요청 1개, 이미지는 CPU로 읽기, 엔진 CPU 작업자는 절반(16코어 PC에서 8개), 맥락 16K. 대화 메모리 형식(`--kv`)과 MTP 끄기는 이 엔진에서 VRAM을 줄이지 않아 쓰지 않음(아래 측정 결과) | 캡처 미리 준비 끔, 화질 빠름(긴 변 768px), 지난 대화 약 4천 토큰 |
|
||||
| 일시정지 | 사용자가 켠 경우(기본 꺼짐), 또는 이 PC에서 최소 배치로도 게임 몫을 비울 수 없을 때 | LLM을 멈춤 | 게임 중에는 대답하지 않음 |
|
||||
|
||||
### PC마다 값을 계산
|
||||
|
||||
- **배치는 계산해서 정함**: 전문가 층 VRAM 몫 = 그래픽카드 VRAM − 게임용으로 비울 VRAM − 다른 프로그램이 이미 쓰는 VRAM − STT 몫(약 2.7GB: 모델 1.3GB와 10명 동시 전사 때 늘어나는 1.44GB, M0 `stt` 실측) − 엔진 기본 버퍼 − 여유분(768MiB, 엔진이 스스로 남기는 양과 같음). 평소 배치도 같은 식이고, 게임용으로 비울 VRAM 대신 다른 프로그램용 여유(기본 1GB)를 뺍니다(사용자 결정, 2026-11-10). 이 여유는 나중에 켜는 브라우저 영상 같은 프로그램 몫이고, 이미 켜져 있는 프로그램은 "다른 프로그램이 이미 쓰는 VRAM"으로 따로 빠집니다. 게임 중에는 게임용으로 비울 VRAM이 이 역할을 하므로 다른 프로그램용 여유를 따로 빼지 않습니다. 엔진 기본 버퍼는 첫 실행 자가 점검에서 전문가 층 없이 한 번 켜서 잽니다. 정해 둔 숫자가 아니라 이 식으로 구하므로 VRAM이 작은 PC에도 같은 규칙이 맞습니다.
|
||||
- **배치는 계산해서 정함**: 전문가 층 VRAM 몫 = 그래픽카드 VRAM − 게임용으로 비울 VRAM − 다른 프로그램이 이미 쓰는 VRAM − STT 몫(약 2.7GB: 모델 1.3GB와 10명 동시 전사 때 늘어나는 1.44GB, M0 `stt` 실측) − TTS 몫(1005MiB, MeloTTS 워밍업 합성 뒤, M0 `tts_melo` 실측; LLM보다 늦게 올라오므로 미리 남겨야 처음 켤 때와 전환할 때 값이 같음, 2026-11-17) − 엔진 기본 버퍼 − 여유분(768MiB, 엔진이 스스로 남기는 양과 같음). 평소 배치도 같은 식이고, 게임용으로 비울 VRAM 대신 다른 프로그램용 여유(기본 1GB)를 뺍니다(사용자 결정, 2026-11-10). 이 여유는 나중에 켜는 브라우저 영상 같은 프로그램 몫이고, 이미 켜져 있는 프로그램은 "다른 프로그램이 이미 쓰는 VRAM"으로 따로 빠집니다. 게임 중에는 게임용으로 비울 VRAM이 이 역할을 하므로 다른 프로그램용 여유를 따로 빼지 않습니다. 엔진 기본 버퍼는 첫 실행 자가 점검에서 전문가 층 없이 한 번 켜서 잽니다. 정해 둔 숫자가 아니라 이 식으로 구하므로 VRAM이 작은 PC에도 같은 규칙이 맞습니다.
|
||||
- **게임 중 최소 배치는 전문가 2GB입니다**(사용자 결정, 2026-11-10). 전문가 몫에는 긴 프롬프트용 버퍼 1.1GiB가 먼저 들어가므로 2GB는 전문가를 실제로 올리는 가장 작은 값이고, 실제 게임 중에는 0GB보다 출력이 1.5~2.1배 빨랐습니다(아래 측정 결과). 0GB는 2GB로는 게임 몫이 0 이하가 되는 PC에서만 일시정지 전 마지막 단계로 씁니다.
|
||||
- **몫이 최소 배치보다 작을 때**: 계산한 몫이 최소 배치(전문가 2GB)보다 작으면, 몫을 늘려 게임 몫을 침범하지 않습니다. 대신 게임용으로 비울 VRAM을 "그래픽카드 VRAM − 다른 프로그램 − STT 몫 − 엔진 기본 버퍼 − 최소 배치"까지 줄이고, 대시보드와 게임 모드 설정 화면에 "이 PC에서는 게임에 X GB까지만 비울 수 있음"을 표시합니다. 이렇게 줄인 값이 0 이하이면(예: 8GB 그래픽카드에서 다른 프로그램이 이미 많이 씀) 게임 중에는 LLM을 멈추고 일시정지 단계로 갑니다. 게임 중 일시정지를 꺼 두었어도 마찬가지이고, 그 이유를 대시보드에 표시합니다. 게임이 끝나면 되돌리기 규칙대로 돌아옵니다.
|
||||
- **첫 실행 자가 점검**: 설치가 끝나면 평소·게임 중 배치로 각각 30초씩 출력 속도와 음성 첫 문장 시간을 잽니다. 평소 배치가 기준(출력 30 tok/s, 음성 첫 문장 0.7초)에 못 미치는 PC는 평소에도 동시 요청 1개, 이미지 CPU 읽기, 지난 대화 약 4천 토큰으로 시작합니다. 게임 중 배치가 기준에 못 미치면 대시보드와 설정 화면에 "게임 중에는 답이 느릴 수 있음"을 표시합니다.
|
||||
- **첫 실행 자가 점검**: 설치가 끝나면 평소·게임 중 배치로 각각 30초씩 출력 속도와 음성 첫 문장 시간을 잽니다. 평소 배치가 기준(출력 30 tok/s, 음성 첫 문장 0.7초)에 못 미치는 PC는 평소에도 이미지 CPU 읽기, 지난 대화 약 4천 토큰으로 시작합니다. 게임 중 배치가 기준에 못 미치면 대시보드와 설정 화면에 "게임 중에는 답이 느릴 수 있음"을 표시합니다.
|
||||
- **GPU 사용률 제한은 두지 않습니다**: Jarvis 옆에서 보는 영상이 끊기지 않도록 LLM 엔진과 음성·두뇌 워커를 200ms마다 함께 10ms씩 멈추는 제한(Windows 프로세스 일시정지)을 검토했지만 뺐습니다(2026-11-11). M0 `gamemode_tune`에서는 멈춘 시간이 정한 대로 5.2%였는데도 nvidia-smi 사용률이 내려가지 않았고(STT를 쉬지 않고 돌릴 때 중앙값 96→98%, LLM만 40→39%) 출력만 6~10% 느려졌습니다([측정 결과](#자동-조절-측정-m0-gamemode_tune-2026-11-11)). M0 `video_drops`에서는 제한이 없어도 Jarvis가 GPU를 98%까지 쓰는 동안 유튜브 1080p 60fps 영상이 끊기지 않았고, 95% 제한은 끊긴 프레임을 줄이지 못했습니다([측정 결과](#영상-끊김-측정-m0-video_drops-2026-11-11)). 미리 정한 기준(제한이 끊김을 줄이지 못하면 설정을 뺌)대로 설정에서 뺐습니다. 게임 화면 프레임에 주는 영향은 아래 `game_frames`로 따로 잽니다.
|
||||
- **대신 게임 화면의 프레임을 직접 봤고, 양보는 넣지 않습니다(M0 `game_frames`, 2026-11-11)**: 사용률 제한은 GPU 전체 사용률을 보고 Jarvis를 일정 시간씩 멈추는 방식이라, 게임이 GPU를 원하지 않을 때도 Jarvis를 느리게 했고 정작 막으려던 것(화면이 끊기는 것)은 보지 않았습니다. 그래서 게임 화면의 프레임을 기준으로 삼고, 멈추는 대신 우선순위로 양보하는 방법을 후보로 함께 쟀습니다. 실제 게임 중 Jarvis가 바쁠 때 평균 fps는 0.2%, 1% low는 3.3% 떨어졌고 50ms 넘는 프레임은 늘지 않아서(0개), 아래 미리 정한 기준대로 양보는 넣지 않습니다([측정 결과](#게임-프레임-측정-m0-game_frames-2026-11-11)).
|
||||
- **기준은 게임 화면의 프레임 시간입니다**: 평균 fps, 1% low(가장 느린 1% 프레임), 50ms·100ms를 넘는 프레임 수를 봅니다. 게임이 프레임을 만든 간격이 아니라 화면이 실제로 바뀐 간격으로 셉니다. 게임은 60fps로 프레임을 내도 화면에는 일부만 나갈 수 있기 때문입니다. 화면에 나가지 못한 프레임 수도 따로 셉니다. Windows가 기록하는 프레임 시각만 읽고 게임 화면은 보지 않습니다.
|
||||
@@ -45,7 +45,6 @@
|
||||
### 전환 규칙
|
||||
|
||||
- **게임 시작**: 지금 하던 답이 끝나면 바로 게임 중 배치로 다시 시작합니다. 다시 시작하는 동안(게임PC 측정 31~36초, 컴퓨터를 켠 뒤 첫 시작은 47초) 들어온 요청은 대기열에 두고, 한 번만 "잠깐만요, 게임 모드로 바꾸는 중이에요"라고 말한 뒤 준비되면 답합니다.
|
||||
- **채팅 채널 설정을 바꿀 때**: 동시 요청 수가 바뀌는 변경(첫 "모든 메시지에 대답" 채널을 켜거나 마지막 하나를 끔)은 LLM을 다시 시작해야 합니다. 게임 시작과 같이 지금 하던 답이 끝난 뒤 다시 시작하고, 그동안 들어온 요청은 대기열에 둡니다. 게임 중에는 다시 시작하지 않고 게임이 끝나 평소 배치로 돌아갈 때 함께 반영합니다.
|
||||
- **되돌리기**: 게임이 끝나고 30초 뒤(설정에서 조절), VRAM 부족은 해소된 상태가 60초 이어진 뒤 평소 배치로 돌아갑니다. 게임을 껐다 바로 다시 켤 때 모델을 반복해서 옮기지 않기 위해서입니다.
|
||||
- **표시**: 대시보드에 "성능 단계: 게임 중 (발로란트 감지)", 전환 중에는 "모델 배치 바꾸는 중"을 표시합니다.
|
||||
- **설정**: GUI에서 바꾸는 것은 게임 감지 켜기/끄기, 게임용으로 비울 VRAM, 다른 프로그램용 여유 VRAM(평소, 기본 1GB), 되돌리기 대기 시간, 게임 중 일시정지 켜기/끄기뿐입니다.
|
||||
@@ -83,7 +82,7 @@
|
||||
- **이 PC의 게임 중 배치**: 기본값 8GB는 비울 수 없으므로 [몫이 최소 배치보다 작을 때](#pc마다-값을-계산) 규칙대로 최소 배치(전문가 2GB, 맥락 16K)로 갑니다. LLM과 STT(GPU, 10명 동시 전사)를 함께 켜고 잰 게임 몫은 2.6GB여서(아래 LLM과 STT를 함께 켠 측정) "이 PC에서는 게임에 약 2.6GB까지만 비울 수 있음"을 표시합니다. 0GB 배치(게임 몫 3.6GB)는 실제 게임에서 출력이 2GB의 절반 정도라 쓰지 않습니다(사용자 결정, 2026-11-10).
|
||||
- **CPU 작업자**를 16개에서 8개로 줄여도 출력 속도가 줄지 않았습니다(73.8 대 75.8 tok/s). 게임 중에는 8개로 둡니다.
|
||||
- **STT는 게임 중에도 GPU에 둡니다.** CPU로 옮기면 게임 몫이 약 2.7GB 늘고 LLM도 빨라지지만, 4~5초짜리 말 한 마디를 받아 적는 데 3.0~3.8초(GPU 0.11~0.19초), 10명 동시 전사 한 번에 32~37초(GPU 1.1~3.0초)가 걸려 0.3~0.5초마다 하는 부분 전사를 따라가지 못합니다. 실제 게임 중 전문가 2GB 배치에서 한 사람 전사와 짧은 프롬프트의 음성 첫 문장 중앙값(서로 다른 측정)을 단순히 더하면 CPU 약 4.3초, GPU 약 1.2초입니다. TTS와 전사 대기는 빠진 추정이라 실제 음성 시작 시간은 이보다 깁니다.
|
||||
- **평소 동시 요청 수**: 동시 2개는 Strata가 "16GB 카드에는 1개가 맞음"이라고 경고하고, 전문가 층을 덜 올려서 동시 1개 배치(전문가 6GB)보다 출력이 느렸습니다(69.6~74.7 대 97.1 tok/s). 그래서 평소에는 1개로 두고, 채팅 채널 중 하나라도 "모든 메시지에 대답"일 때만 2개 이상으로 합니다(사용자 결정, 2026-11-10).
|
||||
- **평소 동시 요청 수**: 동시 2개는 Strata가 "16GB 카드에는 1개가 맞음"이라고 경고하고, 전문가 층을 덜 올려서 동시 1개 배치(전문가 6GB)보다 출력이 느렸습니다(69.6~74.7 대 97.1 tok/s). 그래서 평소에도 1개로 둡니다. 처음에는 채팅 채널 중 하나라도 "모든 메시지에 대답"이면 2개로 했지만(2026-11-10), 그렇게 쓴 날 프롬프트 읽기가 약 3배 느려져 항상 1개로 바꿨습니다(사용자 결정, 2026-11-17).
|
||||
|
||||
세 번째 실행(LLM만, 게임 중 후보는 모두 동시 1개, 이미지 CPU, CPU 작업자 8개):
|
||||
|
||||
|
||||
@@ -36,7 +36,7 @@ def warm_up_ollama_model(base_url: str, model: str, timeout: float) -> bool:
|
||||
if is_openai_compatible(base_url):
|
||||
# The server loads its model at launch; one token checks it answers.
|
||||
body = openai_chat_body(model, [{"role": "user", "content": "hi"}], stream=False,
|
||||
thinking=False, max_tokens=1)
|
||||
thinking=False, max_tokens=1, one_shot=True)
|
||||
try:
|
||||
response = post_chat_completion(base_url, body, timeout)
|
||||
ok = response.status_code == 200
|
||||
@@ -438,6 +438,7 @@ Examples:
|
||||
self.config.model,
|
||||
[{"role": "system", "content": system_prompt}, {"role": "user", "content": user_prompt}],
|
||||
stream=False, thinking=self.config.thinking, max_tokens=200, temperature=0.0,
|
||||
one_shot=True,
|
||||
),
|
||||
self.config.timeout_sec,
|
||||
)
|
||||
|
||||
@@ -110,7 +110,11 @@ def openai_chat_body(
|
||||
max_tokens: Optional[int] = None,
|
||||
temperature: Optional[float] = None,
|
||||
tools: Optional[List[Dict[str, Any]]] = None,
|
||||
one_shot: bool = False,
|
||||
) -> Dict[str, Any]:
|
||||
"""``one_shot``: no later request continues this one (a classification, an extraction, a
|
||||
warm-up). Strata then gives its session away first, so a reply's tool turn keeps its own
|
||||
session through the short calls made between its steps; other servers ignore the field."""
|
||||
body: Dict[str, Any] = {
|
||||
"model": chat_model,
|
||||
"messages": _openai_messages(messages),
|
||||
@@ -124,6 +128,8 @@ def openai_chat_body(
|
||||
body["temperature"] = temperature
|
||||
if tools:
|
||||
body["tools"] = tools
|
||||
if one_shot:
|
||||
body["strata_checkpoint"] = False
|
||||
return body
|
||||
|
||||
|
||||
@@ -246,7 +252,8 @@ def call_llm_direct(base_url: str, chat_model: str, system_prompt: str, user_con
|
||||
|
||||
if is_openai_compatible(base_url):
|
||||
caller = _caller_name()
|
||||
body = openai_chat_body(chat_model, messages, stream=False, thinking=thinking, temperature=temperature)
|
||||
body = openai_chat_body(chat_model, messages, stream=False, thinking=thinking, temperature=temperature,
|
||||
one_shot=True)
|
||||
try:
|
||||
content = _openai_chat(base_url, body, timeout_sec, caller)["message"]["content"]
|
||||
if content.strip():
|
||||
@@ -386,7 +393,7 @@ def _openai_stream(
|
||||
thinking: bool,
|
||||
) -> Optional[str]:
|
||||
"""Server-sent-events stream from ``/chat/completions``; answer text only (no reasoning)."""
|
||||
body = openai_chat_body(chat_model, messages, stream=True, thinking=thinking)
|
||||
body = openai_chat_body(chat_model, messages, stream=True, thinking=thinking, one_shot=True)
|
||||
try:
|
||||
with post_chat_completion(base_url, body, timeout_sec, stream=True) as resp:
|
||||
resp.raise_for_status()
|
||||
|
||||
@@ -231,3 +231,41 @@ def test_dictation_clean_up_uses_chat_completions():
|
||||
out = _llm_clean_dictation("um hello there", V1, model="qwen")
|
||||
assert out == "hello there"
|
||||
assert post.call_args.args[0] == f"{V1}/chat/completions"
|
||||
|
||||
|
||||
# One-shot calls (docs/llm_contexts.md, transport note): a call no later request continues says so
|
||||
# ("strata_checkpoint": false), so Strata gives its session away first and a reply's tool turn keeps
|
||||
# its own session through the short calls made between its steps.
|
||||
|
||||
|
||||
def test_short_calls_are_marked_one_shot():
|
||||
from jarvis.listening.intent_judge import IntentJudge, IntentJudgeConfig, warm_up_ollama_model
|
||||
from jarvis.listening.transcript_buffer import TranscriptSegment
|
||||
|
||||
answer = json.dumps({"directed": True, "query": "q", "stop": False, "confidence": "high", "reasoning": "r"})
|
||||
seg = TranscriptSegment(text="jarvis q", start_time=1.0, end_time=2.0)
|
||||
calls = {
|
||||
"direct": lambda: call_llm_direct(V1, "qwen", "s", "u"),
|
||||
"streaming": lambda: call_llm_streaming(V1, "qwen", "s", "u"),
|
||||
"warm-up": lambda: warm_up_ollama_model(V1, "qwen", timeout=5),
|
||||
"intent judge": lambda: IntentJudge(IntentJudgeConfig(ollama_base_url=V1, model="qwen")).judge([seg], wake_timestamp=1.0),
|
||||
}
|
||||
for name, call in calls.items():
|
||||
resp = _sse({"choices": [{"delta": {"content": "x"}}]}) if name == "streaming" else _response(_completion(answer))
|
||||
with patch("jarvis.llm.requests.post", return_value=resp) as post:
|
||||
call()
|
||||
assert post.call_args.kwargs["json"].get("strata_checkpoint") is False, name
|
||||
|
||||
|
||||
def test_the_reply_loop_is_not_marked_one_shot():
|
||||
# its next step continues this one, so its session must be kept
|
||||
with patch("jarvis.llm.requests.post", return_value=_response(_completion("ok"))) as post:
|
||||
chat_with_messages(V1, "qwen", [{"role": "user", "content": "hi"}],
|
||||
tools=[{"type": "function", "function": {"name": "getWeather"}}])
|
||||
assert "strata_checkpoint" not in post.call_args.kwargs["json"]
|
||||
|
||||
|
||||
def test_ollama_api_gets_no_one_shot_field():
|
||||
with patch("jarvis.llm.requests.post", return_value=_response({"message": {"content": "ok"}})) as post:
|
||||
call_llm_direct("http://127.0.0.1:11434", "m", "s", "u")
|
||||
assert "strata_checkpoint" not in post.call_args.kwargs["json"]
|
||||
|
||||
Reference in New Issue
Block a user