A local inference operating system for unified-memory APUs. It runs 5+ large models (26B–35B params) simultaneously on a single consumer box with no cloud, no NVIDIA tax, and no datacenter complexity.
The router owns mechanism — slots, memory, context profiles, scheduling, batching, caching. The agents own policy — what to do, in what order, with what handoffs. They communicate via OpenAI-compatible chat completions plus a small set of hint extensions.
This is the OS kernel/userspace split, applied to local inference.
What this system actually is (no fluff)
This is systems integration engineering at the edge of consumer hardware, not fundamental research. None of the individual algorithms are novel:
- Intent classification is keyword matching, not ML research.
- Context profiling is heuristic estimation with Bayesian smoothing.
- Continuous batching is llama.cpp’s existing
-npfeature exposed through a semaphore. - Prefix caching is a HashMap lookup, not SGLang’s radix tree.
- Predictive preloading is a first-order Markov chain.
The novelty, such as it is, lies in the combination and the hardware target:
| What exists elsewhere | What does NOT exist |
|---|---|
| vLLM: continuous batching, prefix caching | On a single 128GB consumer APU with unified memory |
| Ollama: simple local inference | 5+ 26B–35B models resident simultaneously |
| LiteLLM: model routing | Intent classification + dynamic context sizing + predictive preloading + pipeline orchestration in one binary |
| SGLang: radix attention | On a Strix Halo with Mesa Vulkan drivers |
The breakthrough is not an algorithm. It is that the whole stack runs on a Strix Halo without falling over.
Guiding principle: tokens per byte
The APU has a fixed memory bandwidth budget (~273 GB/s on Strix Halo). You cannot increase it. The only lever is how many useful tokens you extract per byte transferred.
time_per_token ≈ model_size_bytes / effective_bandwidth
You cannot change effective_bandwidth (silicon). You can change model_size_bytes per useful token. This is the frame that drives all optimization decisions:
- Batching — read weights once, apply to N sequences. Already validated: +110% effective throughput at 4× concurrency.
- Prefix caching — stop recomputing shared document/system-prompt prefixes.
- Speculative decoding — draft model verifies N tokens in one forward pass. Pending.
- KV quantization — already applied (Fast q4_0, Reason q8_0).
- Distillation / MoE conversion — model-level bandwidth reduction. Future research.
Deprecated frames: “avoid concurrent GPU usage,” “CPU offload to eliminate contention,” “temporal multiplexing to serialize access.” All of these treat bandwidth as an enemy to avoid rather than a budget to optimize.
What lives in the Router
Slot lifecycle — spawn, evict, OOM-aware respawn, idle timeout. No agent ever decides to spawn or kill a llama-server process. Why: spawning costs seconds and locks memory; one component must own that decision globally.
Context profile selection (C′ + C″ + C‴) — token estimation, output prediction, history blending. Agents send raw prompts; the router decides whether they get Chat/Standard/Extended/Maximal. Why: agents will systematically over-request context “to be safe” and starve other workloads.
Intent classification — keyword-only classifier (98.4% curated). Why: it’s the cheapest possible routing signal and lives at the only point that sees all traffic. Agents can override with explicit X-Gateway-Intent headers.
Per-slot resource policy — HashMap<Slot, Arc<Semaphore>> keyed by slot, permits = config.parallel for LlamaCpp slots. Different slots run concurrently; same slot batches up to parallel requests via llama-server’s continuous batching. Why: on a memory-bound APU, reading weights once and applying to N hidden states is the highest-ROI throughput win.
Request collation — when queue depth > 1, hold requests for a 20 ms window before releasing to the semaphore. Realtime priority bypasses entirely. Why: staggered arrivals (5–15 ms apart) otherwise miss the batching window.
Memory ceiling enforcement — 112GB ceiling, free-RAM floor. Why: the agents have no visibility into total system memory; the router must refuse spawns that would OOM.
Priority lanes — X-Gateway-Priority: interactive | batch | realtime. Interactive requests skip batch_only slots and get shorter queue timeouts (5s vs 30s). Realtime bypasses the collation window. Why: foreground chat latency degrading because a background research agent is hogging Reason is the single most common failure mode.
Automatic prefix cache — gateway tokenizes the messages array per tokenizer family (Gemma, Qwen) and maintains a prefix cache. Routes to the slot that already holds the longest matching prefix in its KV cache. Evicted on slot standby. LRU eviction at capacity. Why: multi-turn conversations and document analysis recompute the same prefix tokens repeatedly; this stops that waste without agents managing slot affinity.
Manual KV cache reuse — prompt_cache_id as an optional body parameter for agent-managed cache affinity. Why: some workloads (chunked document processing) benefit from explicit cache control.
Backpressure / queueing — requests wait on per-slot semaphores with timeout. Returns 503 on timeout. Why: llama-server’s internal queue is opaque; you can’t prioritize within it.
Fallback chain — explicit → classifier → loaded-with-overlap → cloud (unwired). Why: agents shouldn’t know what’s loaded; if Reason is OOM-evicted, the router silently degrades to Fast.
Metrics & observability — Prometheus, dashboard. Why: observability is a property of the boundary.
Streaming — SSE pass-through, owned permit per stream. Why: streams are inference state; router owns inference state.
What the router explicitly does NOT do:
- Decide which agents exist, when to spawn them, or how to coordinate them.
- Hold conversation history. (Each request is stateless from the router’s view.)
- Manage tool/function definitions.
- Decide what gets stored where (Supabase vs. LanceDB).
- Synthesize results across multiple inference calls.
- Run ML research. (Keyword classifier, heuristic profiling, Markov preloading — all good enough, not cutting edge.)
What lives in the Agents
Topology — which agents exist for a given task, who hands off to whom, when to fan out, when to converge. Why: topology is the actual problem; the router is just the engine.
Tool / function definitions — each agent declares its own tools. Tool execution happens in the agent’s process. The router only sees the model’s tool-call output as text. Why: tools have side effects; side effects must be locally owned.
Memory layers — three tiers:
- Working memory (chunking agent’s temporal store) — LanceDB, embedded, in-process.
- Durable knowledge (research outputs) — Supabase + pgvector.
- Conversation state (chat agent’s session) — wherever the chat agent keeps it.
Why: memory is policy. Different agents have different retention, freshness, and access patterns.
Prompts, personas, system messages — agent-owned. The router never injects system prompts. Why: routing is content-agnostic.
Conversation history & multi-turn state — agent-owned. Each request to the gateway is self-contained. Why: this makes the router stateless and horizontally trivial.
Result synthesis — when parallel agents return, the agent layer reconciles. The router never sees “result A vs result B.”
Priority assignment — the agent stamps X-Gateway-Priority based on its own role. The router enforces; the agent classifies. Why: only the agent knows whether it’s user-facing or background.
What the agents explicitly do NOT do:
- Pick which slot to use, except as a hint (
model: "Reason"). - Spawn or kill llama-server processes.
- Manage
parallel,ctx_size, or any llama.cpp flag. - Hold a global semaphore or implement their own request queue across agents.
- Read
slots.toml. Ever.
The contract between them
Tiny. Three things:
-
OpenAI-compatible chat completions —
/v1/chat/completions, streaming and non-streaming. -
Hint headers — small, optional, ignorable:
X-Gateway-Priority: interactive | batch | realtimeX-Gateway-Intent: summarize | list | explain | write | code | analyze | chat | trivialX-Gateway-Lease: foreground
-
Response metadata — the router tells the agent what actually happened: which slot, which profile, fallback or not, queue wait.
That’s it. No bidirectional state. No agent registration. The router has no idea what agents exist; agents have no idea what slots.toml looks like.
Completed experiments
These validated the core architecture. Their conclusions are now part of the system.
- Per-slot GPU semaphores — Replaced global semaphore. Same slot batches; different slots run concurrently. Continuous batching validated at +110% throughput (4× concurrency).
- Cache thrashing diagnosis — Asymmetric degradation (Fast -68%, Reason -12%) with 96% DRAM traffic collapse at 100% GPU utilization confirmed L2 cache thrashing, not bandwidth saturation. Reframed optimization strategy to tokens-per-byte.
- Priority lanes —
interactive | batch | realtimeimplemented. Interactive skipsbatch_only; realtime bypasses collation. - KV cache reuse —
--cache-reuse 256+prompt_cache_idrouting + automatic prefix cache. - Request collation — 20 ms window, queue-depth-gated. Validated throughput scaling.
Open research (do when needed, not before):
- Speculative decoding acceptance-rate measurement
- LanceDB integration spike for agent working memory
- Cold-start tax measurement (spawn latency end-to-end)
- Model distillation or sparse upcycling for permanent bandwidth reduction
The one-page summary
The router is your kernel. It owns slots, memory, context profiles, scheduling, batching, caching, and resource policy. It is stateless from the agent’s perspective and never reasons about tasks.
The agents are your processes. They own topology, conversations, tools, memory, personas, and result synthesis. They never touch llama.cpp directly.
The contract is OpenAI-compatible HTTP plus three hint headers. Nothing else crosses the boundary.
The target is not datacenter scale. It is not edge-tiny inference. It is desktop AI at model scale — 5+ large models on one consumer APU, no cloud required.