FullStack AI Hub
Studio
lesson depth
Mastery
not started · 0%

Local LLM Orchestration in the Browser

Browser LLM orchestration coordinates WebGPU support, model loading and caching, KV memory, generation, cancellation, and release within client budgets.

Freshness: current•12 min read•Deep Learning and Specialized AI
Full Technical Reference Document

Mental model

Browser-local LLM inference loads a versioned model into a client-side runtime, then repeatedly applies its decoder to tokens without sending prompts to a server. The orchestrator must manage model download and cache revisions, WebGPU capability, context and KV-cache growth, progressive output, cancellation, and explicit unload. Keeping the prompt on-device improves data locality, but it does not make model files or device memory free.

Learning outcomes

  • Estimate the KV-cache size in bytes for a selected layer count, context length, head layout, and cache precision.
  • Separate cold-load and time-to-first-token measurements from steady-state decode throughput, and report both by device class.
  • Specify a local-session lifecycle with an immutable model revision, bounded context, user-visible load progress, and explicit teardown.

Theory

A local session has a cold path and a hot path. The cold path checks for a WebGPU-capable browser and an adapter, selects a model artifact compatible with the runtime, downloads missing shards, initializes GPU pipelines, and reports progress while weights are copied or compiled. A warm path may reuse cached files, but a cache hit still needs device initialization and should be keyed by model revision and tokenizer metadata. IndexedDB storage can be evicted by the browser, so the application must recover from a missing or partially written cache entry.

At inference time, the tokenizer converts the conversation into token IDs. The model first performs prefill over the prompt, producing key and value tensors for every attention layer. During autoregressive decode, each new token attends to that KV cache and appends another position. This avoids recomputing all earlier keys and values, but the cache grows with context length. Generation therefore has two separate latency signals: time to first token measures loading plus prompt prefill, while tokens per second mostly measures the repeated decode loop after warmup.

A WebGPU adapter is not a promise that an arbitrary model will fit. Querying adapter or engine limits catches some unsupported buffer shapes, but it does not report all memory already used by the page, model weights, KV cache, or temporary kernels. The real admission decision needs a model-specific memory estimate and a bounded context window. For a production UI, run engine initialization and tokenization in a worker so downloads and JavaScript work do not stall input or scroll rendering. Report progress and allow cancellation during load; unload the engine when the user leaves the local session or when a memory-pressure policy evicts it.

Revision-pinned model manifest
WebGPU adapter check and model load
Prompt prefill with KV-cache allocation
Autoregressive token decode
Cancel or unload the session
Conceptual teaching model synthesized from:webllm-user-get-started-docs,webllm-api-reference-docs,w3c-webgpu-spec

Calculate KV-cache growth

For batch size one, a decoder with full attention stores a key and value per layer, context position, key-value head, and head dimension:

MKV=2LTHKVDHBM_{KV} = 2 L T H_{KV} D_H B

Here, L is transformer layers, T is live context tokens, H_KV is key-value heads, D_H is head width, and B is bytes per cached element. The leading two accounts for key and value. Multiply by batch size for concurrent conversations; quantized caches use a smaller B only when that runtime supports the cache format.

For 32 layers, 8 key-value heads, head width 128, a 4,096-token context, and FP16 cache values at 2 bytes, the KV cache is 536,870,912 bytes, or 512 MiB, before allocator padding. An eight-billion-parameter model at four bits has roughly 4.0 GB of packed weights before scales and metadata. The combined lower bound is already more than 4.5 GB decimal; prefill activations, shader workspaces, tokenizer buffers, and the browser tab increase the peak. Reducing the context from 4,096 to 2,048 tokens roughly halves this KV component, while it does not shrink the fixed weight payload.

Trade-offs

DecisionResource effectUser-visible cost
Use a four-bit instead of an eight-bit weight artifactRoughly halves raw weight bytes before scale metadataCalibration may expose task-specific quality loss
Cap context at 2,048 instead of 4,096 tokensRoughly halves the full-attention KV componentOlder conversation turns no longer fit in one request
Keep one engine warm between turnsAvoids repeating model initializationRetains GPU buffers and cache memory while idle

These choices interact. A smaller checkpoint does not guarantee that a larger context fits, and a warm engine can consume memory even when no generation is running. Choose a per-device profile using measured peak memory and latency rather than treating model-file size as a complete capacity estimate.

Runtime budgets and recovery

StageBudget to observeRecovery action
Model fetchBytes by artifact revision and download durationResume or discard the incomplete cache revision
WebGPU initializationAdapter availability, required limits, pipeline compile timeOffer a smaller model or a non-local route
Prefill and decodePrompt tokens, time to first token, tokens per secondBound context and output tokens
Session teardownLive GPU buffers and unload completionUnload on route change or memory pressure

Failure modes and misconceptions

If navigator.gpu is absent or requestAdapter() returns null, the browser cannot run the selected WebLLM GPU path; surface an alternate route instead of leaving an infinite spinner. Device loss can arrive during decode, so reject the active request, mark the session invalid, and rebuild only after a fresh capability check. A model cache can also be stale after a model or tokenizer update; key it to an immutable revision and validate the manifest before reuse.

Local generation keeps prompt processing on the device, but the downloaded weights still need supply-chain checks and licenses. Do not put private conversation text in progress logs, analytics, crash reports, or model-selection telemetry. A service worker may cache large files, but storage quotas and eviction differ by browser. Show the artifact size before download, separate download progress from prefill latency, cap context and output, and make unload reachable from the UI.

The sample below uses the documented WebLLM engine API to demonstrate a checked load, progress reporting, bounded request, and explicit release. A shipped interface should host engine creation in a module worker so the UI can continue to accept cancellation while initialization or generation is underway.

Decision scenario

A four-bit 8B model finishes downloading on a laptop, but a 4,096-token prompt triggers device loss during prefill. The app has no context limit and leaves the loaded engine resident after the conversation closes. Pause rollout on that device profile, measure peak memory by context size, and reduce the context or select a smaller artifact until the KV cache and workspaces fit with headroom. Resume only after the cold-load, prefill, decode, and unload paths pass on the affected browser and GPU.

Implementation: load, answer, release

typescript
import { CreateMLCEngine } from "@mlc-ai/web-llm";
​
const modelId = "Llama-3.1-8B-Instruct";
let engine: Awaited<ReturnType<typeof CreateMLCEngine>> | undefined;
​
export async function loadLocalModel(reportProgress: (text: string) => void) {
if (!navigator.gpu) throw new Error("WebGPU is unavailable in this browser");
const adapter = await navigator.gpu.requestAdapter();
if (!adapter) throw new Error("No compatible WebGPU adapter was returned");
engine = await CreateMLCEngine(modelId, {
initProgressCallback: (progress) => reportProgress(progress.text),
});
const maxBufferBytes = await engine.getMaxStorageBufferBindingSize();
return { modelId, maxBufferBytes };
}
​
export async function answerLocally(question: string) {
if (!engine) throw new Error("Load the local model before generating");
const prompt = question.trim();
if (!prompt || prompt.length > 6000) throw new RangeError("Prompt exceeds the local input budget");
const result = await engine.chat.completions.create({
messages: [{ role: "user", content: prompt }],
temperature: 0.2,
max_tokens: 160,
stream: false,
});
const text = result.choices[0]?.message.content;
if (typeof text !== "string") throw new Error("The model returned no text content");
return text;
}
​
export async function releaseLocalModel() {
if (!engine) return;
const loaded = engine;
engine = undefined;
await loaded.unload();
}
Reflect before revealing the guide

Prerequisites & Related Concepts (2)

Private notes

0 words
Recommended Free Track
Free · Verifiable Credential

FS-102LLM Systems Foundations

Build a connected mental model from tokens through retrieval evaluation security and operations.

24 concepts~18h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.

Next