update(BLOG): Update the documentation with in depth technical aspect
Browse files
BLOG.md
CHANGED
|
@@ -28,8 +28,12 @@ tags:
|
|
| 28 |
4. [The "model proposes, code disposes" pattern](#pattern)
|
| 29 |
5. [Features that emerged naturally](#features)
|
| 30 |
6. [The journey from local to Modal](#local-to-modal)
|
| 31 |
-
7. [
|
| 32 |
-
8. [
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
|
| 34 |
---
|
| 35 |
|
|
@@ -53,9 +57,11 @@ We defined three distinct **roles**, each handled by a different model family:
|
|
| 53 |
|
| 54 |
> **🎭 The Voices** - the actor. It speaks *as* the active character - their speech quirks, their current mood, their secrets. One to three sentences, anime style, never breaking the fourth wall.
|
| 55 |
|
| 56 |
-
> **🎨 The Painter** - it generates backdrops and character sprites.
|
| 57 |
|
| 58 |
-
> **👂 The Ear** - voice transcription. Whisper-
|
|
|
|
|
|
|
| 59 |
|
| 60 |
The key subtlety: **The Weaver and The Voices share a single LLM** (Qwen3-14B). Same weights, two system prompts, one grammar-constrained call per turn. They write the stage directions and the dialogue lines simultaneously. A second LLM call per turn would have doubled perceived latency - and the two roles are so tightly coupled that sharing context is actually an advantage.
|
| 61 |
|
|
@@ -131,8 +137,9 @@ The key subtlety: **The Weaver and The Voices share a single LLM** (Qwen3-14B).
|
|
| 131 |
| Role | Model | Params |
|
| 132 |
|---|---|---|
|
| 133 |
| The Weaver + The Voices (shared) | Qwen3-14B | ~14B |
|
| 134 |
-
| The Painter | SDXL-
|
| 135 |
-
| The Ear | Whisper-
|
|
|
|
| 136 |
| **Total** | | **≈18B** |
|
| 137 |
|
| 138 |
---
|
|
@@ -145,7 +152,7 @@ We already had experience with LLMs and HuggingFace. But this project pushed us
|
|
| 145 |
|
| 146 |
This is clearly what surprised us the most. We knew image generation existed, we had played with online demos, but actually integrating it into a real pipeline - managing prompts, seeds, caching, negative prompts, and visual consistency - is a genuine craft in itself.
|
| 147 |
|
| 148 |
-
Choosing
|
| 149 |
|
| 150 |
What we had never done before: **LoRA fine-tuning**. We trained an anime LoRA on SDXL-Turbo to lock in the visual style - color palette, character rendering, line quality. The result: even as prompts vary wildly from scene to scene, the style stays consistent. That is exactly what a VN needs. The LoRA is published on the Hub (`VN_IMAGE_LORA`) and loads automatically at startup.
|
| 151 |
|
|
@@ -195,29 +202,233 @@ Once the directive pattern was solid, features fell out almost on their own.
|
|
| 195 |
|
| 196 |
**Generated ending screens.** When a relationship hits +100 (romantic confession) or -100 (a falling-out that empties the stage), the model emits an `ending` directive with a poetic 2-4 sentence epilogue. The Painter generates a dedicated illustration - cherry blossoms at golden hour for the warm ending, a rain-soaked empty park bench at night for defeat. No pre-authored cutscenes. The ending art is improvised just like everything else.
|
| 197 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 198 |
---
|
| 199 |
|
| 200 |
## The journey from local to Modal <a name="local-to-modal"></a>
|
| 201 |
|
| 202 |
We started on our two machines: an Apple M3 Max (Metal backend) and an AMD RX 7900 XTX (ROCm). First surprising fact: ROCm reports itself as `"cuda"` to PyTorch - so our device detection works on both machines without any special-casing. Second surprise: CTranslate2 has no ROCm backend, so Whisper runs on CPU on the AMD machine regardless.
|
| 203 |
|
| 204 |
-
For the HF Space we needed GPU inference without going through ZeroGPU (llama.cpp + ZeroGPU is notoriously unreliable). The solution: Modal for heavy model calls, Gradio for the UI. The Space stays CPU, GPU compute goes to on-demand Modal containers.
|
| 205 |
|
| 206 |
One unexpected practical problem: HF Spaces now uses Xet storage and refuses binary files pushed through git. We had to soft-reset the commit that included the music MP3 files, add them to `.gitignore`, push the clean code, then upload the audio files via `HfApi().upload_file()`. Lesson learned the hard way: code goes through git, binary assets go through the Hub API.
|
| 207 |
|
| 208 |
---
|
| 209 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 210 |
## Stack <a name="stack"></a>
|
| 211 |
|
| 212 |
| Layer | Tool |
|
| 213 |
|---|---|
|
| 214 |
-
| App framework | Gradio (`gradio.Server` + custom frontend) |
|
| 215 |
-
| LLM | Qwen3-14B
|
| 216 |
-
| Image generation | SDXL-
|
| 217 |
-
| Voice | Whisper-
|
| 218 |
-
|
|
|
|
|
| 219 |
| Package management | `uv` |
|
| 220 |
-
| Deployment | HF Spaces
|
| 221 |
|
| 222 |
---
|
| 223 |
|
|
|
|
| 28 |
4. [The "model proposes, code disposes" pattern](#pattern)
|
| 29 |
5. [Features that emerged naturally](#features)
|
| 30 |
6. [The journey from local to Modal](#local-to-modal)
|
| 31 |
+
7. [One codebase, three runtimes: local, Modal, Space](#three-runtimes)
|
| 32 |
+
8. [llama.cpp vs transformers vs ZeroGPU: what actually changes](#backends)
|
| 33 |
+
9. [Architecture, in depth](#architecture)
|
| 34 |
+
10. [Field notes: the problems we hit and how we fixed them](#field-notes)
|
| 35 |
+
11. [Stack](#stack)
|
| 36 |
+
12. [What this could become](#vision)
|
| 37 |
|
| 38 |
---
|
| 39 |
|
|
|
|
| 57 |
|
| 58 |
> **🎭 The Voices** - the actor. It speaks *as* the active character - their speech quirks, their current mood, their secrets. One to three sentences, anime style, never breaking the fourth wall.
|
| 59 |
|
| 60 |
+
> **🎨 The Painter** - it generates backdrops and character sprites. Default backend: SDXL-base-1.0 distilled down to 4 inference steps with the ByteDance SDXL-Lightning LoRA (an SDXL-Turbo backend exists as an alternative, and `VN_IMAGE_LORA` accepts a custom style LoRA on top).
|
| 61 |
|
| 62 |
+
> **👂 The Ear** - voice transcription. Whisper (large-v3-turbo by default), CPU via faster-whisper, good enough for short clips.
|
| 63 |
+
|
| 64 |
+
> **🔊 The Larynx** - speech synthesis. Kokoro-82M via ONNX gives every character a voice, picked once at creation from their written voice description and frozen forever (same character = same voice).
|
| 65 |
|
| 66 |
The key subtlety: **The Weaver and The Voices share a single LLM** (Qwen3-14B). Same weights, two system prompts, one grammar-constrained call per turn. They write the stage directions and the dialogue lines simultaneously. A second LLM call per turn would have doubled perceived latency - and the two roles are so tightly coupled that sharing context is actually an advantage.
|
| 67 |
|
|
|
|
| 137 |
| Role | Model | Params |
|
| 138 |
|---|---|---|
|
| 139 |
| The Weaver + The Voices (shared) | Qwen3-14B | ~14B |
|
| 140 |
+
| The Painter | SDXL-base-1.0 + Lightning LoRA | ~3.5B |
|
| 141 |
+
| The Ear | Whisper large-v3-turbo | ~0.8B |
|
| 142 |
+
| The Larynx | Kokoro-82M (TTS) | ~0.08B |
|
| 143 |
| **Total** | | **≈18B** |
|
| 144 |
|
| 145 |
---
|
|
|
|
| 152 |
|
| 153 |
This is clearly what surprised us the most. We knew image generation existed, we had played with online demos, but actually integrating it into a real pipeline - managing prompts, seeds, caching, negative prompts, and visual consistency - is a genuine craft in itself.
|
| 154 |
|
| 155 |
+
Choosing a few-step distilled model over a full diffusion pipeline was deliberate: 1 to 4 inference steps instead of 50. Slightly lower quality, but in a VN where the image arrives *while* the player is reading the dialogue, "fast and impressionistic" beats "slow and polished" every single time. We started with SDXL-Turbo and eventually settled on SDXL-base-1.0 + the ByteDance Lightning LoRA as the default - same philosophy, noticeably better quality at 4 steps (both backends remain in the code).
|
| 156 |
|
| 157 |
What we had never done before: **LoRA fine-tuning**. We trained an anime LoRA on SDXL-Turbo to lock in the visual style - color palette, character rendering, line quality. The result: even as prompts vary wildly from scene to scene, the style stays consistent. That is exactly what a VN needs. The LoRA is published on the Hub (`VN_IMAGE_LORA`) and loads automatically at startup.
|
| 158 |
|
|
|
|
| 202 |
|
| 203 |
**Generated ending screens.** When a relationship hits +100 (romantic confession) or -100 (a falling-out that empties the stage), the model emits an `ending` directive with a poetic 2-4 sentence epilogue. The Painter generates a dedicated illustration - cherry blossoms at golden hour for the warm ending, a rain-soaked empty park bench at night for defeat. No pre-authored cutscenes. The ending art is improvised just like everything else.
|
| 204 |
|
| 205 |
+
**Characters that remember you.** A `remember_fact` directive lets the speaker store one short note when the player reveals something personal ("the player plays violin", "the player is named Lorenzo"). Facts are capped at 8 per character and re-injected into their sheet every turn they are on stage - so a character you met ten scenes ago still knows your name. The same progression system unlocks personality traits at affection thresholds (20/40/60), reveals the secret goal at 80, and stages a one-shot "growing close" moment at 50 - all deterministic, all driven by the relationship value the model proposes.
|
| 206 |
+
|
| 207 |
+
**Quality-of-life.** The player can set their name in the setup form (characters address them by it), and a session persisted server-side after every turn powers a "Continue last story" button - including a rebuilt journal with a condensed recap of everything that got compacted away.
|
| 208 |
+
|
| 209 |
---
|
| 210 |
|
| 211 |
## The journey from local to Modal <a name="local-to-modal"></a>
|
| 212 |
|
| 213 |
We started on our two machines: an Apple M3 Max (Metal backend) and an AMD RX 7900 XTX (ROCm). First surprising fact: ROCm reports itself as `"cuda"` to PyTorch - so our device detection works on both machines without any special-casing. Second surprise: CTranslate2 has no ROCm backend, so Whisper runs on CPU on the AMD machine regardless.
|
| 214 |
|
| 215 |
+
For the HF Space we first needed GPU inference without going through ZeroGPU (llama.cpp + ZeroGPU is notoriously unreliable). The solution: Modal for heavy model calls, Gradio for the UI. The Space stays CPU, GPU compute goes to on-demand Modal containers. We later added a third path - running the models directly on ZeroGPU with `transformers` - which turned out to have its own fascinating constraints (see the next two sections).
|
| 216 |
|
| 217 |
One unexpected practical problem: HF Spaces now uses Xet storage and refuses binary files pushed through git. We had to soft-reset the commit that included the music MP3 files, add them to `.gitignore`, push the clean code, then upload the audio files via `HfApi().upload_file()`. Lesson learned the hard way: code goes through git, binary assets go through the Hub API.
|
| 218 |
|
| 219 |
---
|
| 220 |
|
| 221 |
+
## One codebase, three runtimes: local, Modal, Space <a name="three-runtimes"></a>
|
| 222 |
+
|
| 223 |
+
The same `visualnovel/` package runs in three very different places. Nothing in the game logic knows which one it is in - the backends are selected by `config.py` from environment variables, and every backend implements the same two-method interface (`complete` / `complete_json` for the LLM, `_render` for the Painter).
|
| 224 |
+
|
| 225 |
+
| | **local** | **modal** | **space (ZeroGPU)** |
|
| 226 |
+
|---|---|---|---|
|
| 227 |
+
| Where the app runs | your machine | your machine (UI) + Modal (GPU) | HF Space |
|
| 228 |
+
| LLM engine | llama.cpp, GGUF Q4_K_M, Metal/ROCm | llama.cpp, GGUF Q8_0, A10G container | transformers, full bf16 weights |
|
| 229 |
+
| Painter | diffusers in-process | A10G container (RPC) | diffusers in-process |
|
| 230 |
+
| Selected by | default | `VN_LLM_BACKEND=modal` | `SPACE_ID` env var (auto-detected) |
|
| 231 |
+
| Game state | in-process | in-process | `/tmp` JSON file (workers are stateless) |
|
| 232 |
+
| Cold start cost | model load at launch | ~15-30 s container spin-up, then kept warm 10 min | per-worker lazy load inside the first GPU call |
|
| 233 |
+
|
| 234 |
+
A few design decisions make this work:
|
| 235 |
+
|
| 236 |
+
- **Auto-detection over configuration.** HF injects `SPACE_ID` into every Space, so `config.py` flips the LLM backend to `transformers` automatically when deployed - a fresh clone needs zero setup in any environment. Setting `VN_LLM_BACKEND=modal` also chains the Painter to Modal by default, because if you don't have a local GPU for the LLM you don't have one for SDXL either.
|
| 237 |
+
- **Modal calls are plain RPC.** `ModalLLM` is a ~20-line proxy: it looks up the deployed class with `modal.Cls.from_name(...)` and calls `.remote()`. The JSON schema travels with every call, which has a lovely property: changing prompts, schemas, or game logic never requires a redeploy - only changes to the container code itself do.
|
| 238 |
+
- **Keep-warm matters more than raw speed.** Reloading a 15 GB GGUF mid-conversation is a worse experience than any per-token slowness, so the Modal LLM container keeps a 10-minute `scaledown_window` and the app fires a fire-and-forget warmup ping at server start.
|
| 239 |
+
|
| 240 |
+
---
|
| 241 |
+
|
| 242 |
+
## llama.cpp vs transformers vs ZeroGPU: what actually changes <a name="backends"></a>
|
| 243 |
+
|
| 244 |
+
These three names live at different levels - two are inference engines, one is a runtime - and each one reshaped a different part of the code.
|
| 245 |
+
|
| 246 |
+
### llama.cpp: the grammar is the contract
|
| 247 |
+
|
| 248 |
+
The killer feature for this project: `llama-cpp-python` compiles a JSON schema into a **GBNF grammar** that constrains decoding token by token. The model *physically cannot* emit malformed JSON, invent keys, or put a string where an integer belongs. Our whole "model proposes, code disposes" pattern leans on this.
|
| 249 |
+
|
| 250 |
+
It also exposes full sampling control (`temperature`, `top_p`, `presence_penalty` - the latter became our anti-repetition weapon). Two sharp edges, though:
|
| 251 |
+
|
| 252 |
+
- The grammar cannot *finish* a document when `max_tokens` runs out mid-string. You get perfectly-shaped-but-truncated JSON, and `json.loads` explodes. We wrote a small `close_truncated_json()` repair (close the open string, drop the dangling comma, balance the brackets) so a runaway generation costs a few default-valued fields instead of a crashed turn.
|
| 253 |
+
- Qwen3's thinking mode is baked into the GGUF chat template and there is no API switch - the only control is the `/no_think` soft switch appended to the user message.
|
| 254 |
+
|
| 255 |
+
### transformers: no grammar, so trust but verify
|
| 256 |
+
|
| 257 |
+
On the Space there is no grammar constraint. Instead we derive a **JSON skeleton from the same Pydantic schema** and inject it into the system prompt ("Respond with ONLY a valid JSON object. Required structure: ..."), then parse with up to 3 retries and a regex extraction that tolerates markdown fences and stray prose.
|
| 258 |
+
|
| 259 |
+
Two gotchas that cost us real debugging time:
|
| 260 |
+
|
| 261 |
+
- `model.generate()` **silently ignores** `temperature` and `top_p` unless you also pass `do_sample=True`. For weeks the Space was running greedy decoding while we thought we were sampling at 0.7 - and the 3 retries were deterministic, so they retried into the exact same failure.
|
| 262 |
+
- Qwen3 sometimes puts its entire answer *inside* the `<think>` block and emits nothing after it. `apply_chat_template(..., enable_thinking=False)` suppresses thinking for structured output, with a fallback that searches inside the think block if nothing comes after it.
|
| 263 |
+
|
| 264 |
+
### ZeroGPU: a runtime, not a backend
|
| 265 |
+
|
| 266 |
+
ZeroGPU is the part that changes your *architecture* rather than your inference code. Each `@spaces.GPU` call can be dispatched to a **different worker subprocess** - in-memory state simply does not survive between two HTTP calls. Three consequences:
|
| 267 |
+
|
| 268 |
+
1. **State lives on disk.** After every mutation, `GameState` is serialized to `/tmp/vn_game_state.json` with an atomic write-then-rename. Every endpoint starts by rehydrating from that file if its own memory is empty. (Bonus: this is exactly the mechanism that later powered the "Continue last story" button.)
|
| 269 |
+
2. **Models load lazily.** Loading a 14B model at import time would happen on a CPU-only web worker; instead every backend loads inside the first GPU-decorated call.
|
| 270 |
+
3. **Turns are split in two phases** (`/turn_text` then `/turn_images`) so the dialogue can be displayed while the slower image phase runs - and the pending `DirectorOutput` rides along in the state file, because phase 2 might run on a different worker than phase 1.
|
| 271 |
+
|
| 272 |
+
---
|
| 273 |
+
|
| 274 |
+
## Architecture, in depth <a name="architecture"></a>
|
| 275 |
+
|
| 276 |
+
The package is a strict one-way dependency graph - schemas at the bottom, the engine façade at the top, `app.py` as a thin HTTP shell. The golden rule sits in the middle: the LLM returns a typed `DirectorOutput`, and `state.apply_directives` is the **only** function in the codebase allowed to mutate `GameState`.
|
| 277 |
+
|
| 278 |
+
```mermaid
|
| 279 |
+
flowchart TD
|
| 280 |
+
UI["frontend/index.html<br/>(custom VN UI, Gradio JS client)"]
|
| 281 |
+
APP["app.py - gradio.Server<br/>thin endpoints: /start_text /start_images<br/>/turn_text /turn_images /transcribe /resume"]
|
| 282 |
+
ENG["engine.py<br/>the façade - owns the session"]
|
| 283 |
+
|
| 284 |
+
subgraph CORE["visualnovel/ - testable without a server"]
|
| 285 |
+
ORC["orchestrator.py<br/>the Weaver: init / direct_turn / compact"]
|
| 286 |
+
MEM["memory.py<br/>context budget + trimming"]
|
| 287 |
+
CH["characters.py<br/>present-character sheets"]
|
| 288 |
+
PRM["prompts.py<br/>all prompts + JSON schemas"]
|
| 289 |
+
LLM["llm.py<br/>Mock / LlamaCpp / Transformers / Modal"]
|
| 290 |
+
ST["state.py<br/>apply_directives - THE ONLY MUTATOR"]
|
| 291 |
+
PAINT["painter.py<br/>prompt compose + cache + render"]
|
| 292 |
+
STT["stt.py - Whisper"]
|
| 293 |
+
TTS["tts.py - Kokoro"]
|
| 294 |
+
end
|
| 295 |
+
|
| 296 |
+
UI -->|HTTP| APP --> ENG
|
| 297 |
+
ENG --> ORC
|
| 298 |
+
ORC --> MEM --> CH
|
| 299 |
+
ORC --> PRM
|
| 300 |
+
ORC --> LLM
|
| 301 |
+
ENG --> ST
|
| 302 |
+
ENG --> PAINT
|
| 303 |
+
ENG --> STT
|
| 304 |
+
ENG --> TTS
|
| 305 |
+
```
|
| 306 |
+
|
| 307 |
+
A full turn, with the two-phase split that keeps the dialogue snappy:
|
| 308 |
+
|
| 309 |
+
```mermaid
|
| 310 |
+
sequenceDiagram
|
| 311 |
+
autonumber
|
| 312 |
+
participant P as Player (browser)
|
| 313 |
+
participant A as app.py
|
| 314 |
+
participant E as Engine
|
| 315 |
+
participant W as Weaver (one LLM call)
|
| 316 |
+
participant S as apply_directives
|
| 317 |
+
participant PA as Painter
|
| 318 |
+
participant T as Kokoro TTS
|
| 319 |
+
|
| 320 |
+
P->>A: POST /turn_text ("Hello, you are so pretty today")
|
| 321 |
+
A->>E: play_turn_text()
|
| 322 |
+
Note over E: optional: Whisper if voice input
|
| 323 |
+
E->>W: complete_json(context, directive schema)
|
| 324 |
+
W-->>E: DirectorOutput (dialogue, emotion, directives)
|
| 325 |
+
E->>S: apply_directives - clamps, validates, mutates GameState
|
| 326 |
+
E->>E: save .md views + /tmp state (ZeroGPU workers)
|
| 327 |
+
E-->>P: text-only ViewState - dialogue appears NOW
|
| 328 |
+
|
| 329 |
+
P->>A: POST /turn_images
|
| 330 |
+
A->>E: play_turn_images()
|
| 331 |
+
E->>PA: backdrop(scene) + sprite(char, mood)
|
| 332 |
+
Note over PA: cache hit by (kind, prompt, seed)?<br/>then 0 ms, else 4-step SDXL render
|
| 333 |
+
E->>T: synthesize(dialogue, frozen voice)
|
| 334 |
+
E-->>P: full ViewState - backdrop, sprites, audio
|
| 335 |
+
```
|
| 336 |
+
|
| 337 |
+
And the deployment picture - one engine, three homes:
|
| 338 |
+
|
| 339 |
+
```mermaid
|
| 340 |
+
flowchart LR
|
| 341 |
+
APP["app.py + visualnovel/<br/>(identical code everywhere)"]
|
| 342 |
+
|
| 343 |
+
subgraph L["LOCAL - Mac M3 Max / AMD RX 7900 XTX"]
|
| 344 |
+
L1["llama.cpp - Qwen3-14B Q4_K_M<br/>Metal / ROCm, grammar-constrained"]
|
| 345 |
+
L2["diffusers - SDXL + Lightning LoRA"]
|
| 346 |
+
end
|
| 347 |
+
|
| 348 |
+
subgraph M["MODAL - on-demand A10G"]
|
| 349 |
+
M1["ModalLLMBackend<br/>llama.cpp - Q8_0, kept warm 10 min"]
|
| 350 |
+
M2["ModalPainterBackend<br/>SDXL + Lightning, rembg"]
|
| 351 |
+
end
|
| 352 |
+
|
| 353 |
+
subgraph Z["HF SPACE - ZeroGPU"]
|
| 354 |
+
Z1["TransformersLLM - Qwen3-14B bf16<br/>JSON skeleton + retries"]
|
| 355 |
+
Z2["diffusers in-process"]
|
| 356 |
+
Z3[("/tmp state file<br/>(stateless workers)")]
|
| 357 |
+
end
|
| 358 |
+
|
| 359 |
+
APP -->|"default"| L
|
| 360 |
+
APP -->|"VN_LLM_BACKEND=modal<br/>.remote() RPC"| M
|
| 361 |
+
APP -->|"SPACE_ID detected<br/>@spaces.GPU"| Z
|
| 362 |
+
```
|
| 363 |
+
|
| 364 |
+
Two invariants hold everywhere:
|
| 365 |
+
|
| 366 |
+
- **One LLM call per turn** (a guarded retry is allowed for repetition or a missed mandatory directive - never a loop).
|
| 367 |
+
- **Every Painter render is cached** by `(kind, prompt, seed)`. A character's sprite is generated once per mood and reused forever; seeds are pinned per entity so the same character always has the same face.
|
| 368 |
+
|
| 369 |
+
---
|
| 370 |
+
|
| 371 |
+
## Field notes: the problems we hit and how we fixed them <a name="field-notes"></a>
|
| 372 |
+
|
| 373 |
+
This is the section we wish we had read before starting. Almost every bug below was invisible in the code and obvious in a **saved game file** - our best debugging tool turned out to be exporting the save JSON after each playtest and actually reading it.
|
| 374 |
+
|
| 375 |
+
### 1. Anything optional in the grammar is something the model will skip
|
| 376 |
+
|
| 377 |
+
The single biggest lesson of the project. Our `DirectorOutput` schema had `emotion`, `relationship_delta`, and `new_character` as optional fields with defaults - and the grammar therefore allowed the model to omit them. So it did. Systematically. The symptoms looked like three unrelated gameplay bugs:
|
| 378 |
+
|
| 379 |
+
- every character stayed `"neutral"` forever (so the mood-keyed sprite system never showed a second expression),
|
| 380 |
+
- affection stayed at 0 no matter how hard the player flirted (or insulted),
|
| 381 |
+
- the "look around" action politely refused to introduce anyone.
|
| 382 |
+
|
| 383 |
+
We tried prompt rules ("you MUST emit new_character"), then an explicit retry quoting the instruction. The model ignored both often enough to ruin the demo. The fix that actually worked: **promote the fields to `required` in the JSON schema** handed to the grammar. For "look around" we went further and built a dedicated schema variant where `new_character` is required *and non-nullable* - introduction guaranteed by construction. Prompt engineering is a suggestion; grammar is a constraint.
|
| 384 |
+
|
| 385 |
+
### 2. Instructions inside quoted player speech get read as... player speech
|
| 386 |
+
|
| 387 |
+
Our action hints ("*the wanderer looks around...*") were concatenated with the player's text and injected as `THE WANDERER NOW SAYS: "<hint> <text>"`. Inside the quotes, the model treated our stage directions as something the player said out loud - and ignored them. Moving the hints to a separate `DIRECTOR NOTE (mandatory):` block outside the quotes changed compliance dramatically. Placement in the context is as important as wording.
|
| 388 |
+
|
| 389 |
+
### 3. Qwen3's thinking mode ate our memory summarizer
|
| 390 |
+
|
| 391 |
+
The rolling summary ("THE TALE SO FAR") is rewritten every ~12 turns by a small free-text LLM call with a 320-token budget. On llama.cpp, Qwen3's chat template enables thinking by default - and the model happily spent the *entire* budget inside an unclosed `<think>` block. Our summary was an empty string for whole sessions, silently replaced by a raw-dialogue fallback, and we only noticed by reading a save file where the "summary" was a concatenation cut mid-sentence. Fix: the `/no_think` soft switch appended to the message, `strip_think()` on every free-text output, and a fallback that never degrades the existing summary.
|
| 392 |
+
|
| 393 |
+
### 4. Truncated JSON should cost fields, not turns
|
| 394 |
+
|
| 395 |
+
One playtest produced a character whose `goals` field was a 5,000-character runaway sentence - which blew past `max_tokens` and crashed the turn with `json.decoder.JSONDecodeError: Unterminated string`. Three layers later: generated character fields are word-capped at creation *and* at context-injection time, `close_truncated_json()` repairs cut-off output, and `direct_turn` has a last-resort fallback line ("Hm? Sorry - I lost my train of thought...") so the worst possible outcome of a bad sample is one bland reply.
|
| 396 |
+
|
| 397 |
+
### 5. Small models loop, and they loop harder once a loop is in the context
|
| 398 |
+
|
| 399 |
+
A character repeated the same line verbatim three turns in a row - despite a prompt rule forbidding exactly that. Once one repeat lands in the RECENT EXCHANGE window, it biases the next generation toward repeating again. Code-side guard: normalize and compare the new dialogue against the last 3 turns (`difflib` ratio >= 0.95), and on a hit, retry once at higher temperature with the forbidden line quoted back and `presence_penalty=0.8`.
|
| 400 |
+
|
| 401 |
+
### 6. Pacing has to be enforced in both directions
|
| 402 |
+
|
| 403 |
+
Story beats (`opening -> rising -> turn -> resolution`) failed both ways. First the beat never advanced - because the prompt never mentioned the `advance_beat` field existed. After we documented it, the model sprinted from opening to resolution in 8 turns. Final design: the prompt explains the arc, a deterministic nudge fires after 7 stagnant turns ("consider advance_beat"), and `apply_directives` rate-limits beats to a minimum of 4 turns each. Suggest with the prompt, pace with the code.
|
| 404 |
+
|
| 405 |
+
### 7. The performance pass: death by a thousand reloads
|
| 406 |
+
|
| 407 |
+
Profiling a real session surfaced waste that no benchmark would show:
|
| 408 |
+
|
| 409 |
+
- **rembg reloaded a ~170 MB ONNX model for every sprite.** `rembg.remove(img)` without an explicit session creates one each call. One reused session per painter: 1-3 s saved per generated sprite.
|
| 410 |
+
- **SDXL's stock VAE forced an fp32 upcast on every render** (plus a deprecation warning per image). Swapping in the `sdxl-vae-fp16-fix` VAE removed the per-render upcast on every backend.
|
| 411 |
+
- **The turn blocked on image generation.** Splitting `/turn` into a text phase and an image phase made the perceived latency drop from "the whole pipeline" to "one LLM call" - the player reads the reply while SDXL paints.
|
| 412 |
+
- Smaller wins: Pydantic JSON schemas cached instead of regenerated per turn, memory compaction retuned from every ~4 turns to every ~12 (one LLM call saved per cycle), context trimming fixed to drop the *oldest* exchanges instead of accidentally beheading the style guide and character sheets.
|
| 413 |
+
|
| 414 |
+
### 8. Test the loop, not the models
|
| 415 |
+
|
| 416 |
+
None of the above needed a GPU to verify. The mock-first design (`VN_MOCK=1`) plus a test suite that grew from 6 to 51 tests during the optimization pass meant every fix shipped with a regression test that runs in seconds - including simulated ZeroGPU worker restarts (build a fresh `Engine`, rehydrate from the state file, finish the turn).
|
| 417 |
+
|
| 418 |
+
---
|
| 419 |
+
|
| 420 |
## Stack <a name="stack"></a>
|
| 421 |
|
| 422 |
| Layer | Tool |
|
| 423 |
|---|---|
|
| 424 |
+
| App framework | Gradio (`gradio.Server` + custom HTML/JS frontend) |
|
| 425 |
+
| LLM | Qwen3-14B - `llama-cpp-python` (local + Modal A10G) or `transformers` (ZeroGPU Space) |
|
| 426 |
+
| Image generation | SDXL-base-1.0 + SDXL-Lightning LoRA (4 steps) via `diffusers`, fp16-fix VAE, `rembg` sprites |
|
| 427 |
+
| Voice input | Whisper large-v3-turbo via `faster-whisper` (CPU) |
|
| 428 |
+
| Voice output | Kokoro-82M via `kokoro-onnx` |
|
| 429 |
+
| Data contracts | Pydantic v2 everywhere (schemas drive the LLM grammar) |
|
| 430 |
| Package management | `uv` |
|
| 431 |
+
| Deployment | local, Modal (on-demand A10G), HF Spaces (ZeroGPU) |
|
| 432 |
|
| 433 |
---
|
| 434 |
|