Running a language model on the device changes the product contract completely. Latency becomes predictable because there is no network round trip, privacy improves because prompts never leave the hardware, and the feature keeps working offline β but you inherit a brutal memory ceiling, battery constraints, and the inability to fix a bad model without shipping an app update. Edge LLM deployment is the art of fitting the largest useful capability inside a hard envelope.
This lesson covers how to budget memory against real device profiles, how to quantize and package models for mobile and browser runtimes, how to run inference while respecting thermal and battery limits, and how to design a hybrid architecture where the cloud handles the hard 10 percent and the device handles the easy 90 percent.
The memory envelope decides everything
Every other edge decision follows from the memory budget. A flagship phone may have 6β8 GB of RAM shared with the OS and every other app; an in-app allocation of 500 MB will get you killed by the operating system on a bad day. Browsers are tighter still, with WebAssembly heaps that commonly cap around 2β4 GB and no guaranteed allocation success near the ceiling. Microcontrollers like the ESP32 have hundreds of kilobytes, not gigabytes, which is a different regime entirely.
The rule of thumb for weight memory is straightforward: parameters Γ bytes per parameter. A 7B model at fp16 is 14 GB β not a phone workload. At INT4 it is roughly 3.5 GB β still uncomfortable. A 1β3B model quantized to INT4, at 0.5β1.5 GB, is the realistic sweet spot for flagship mobile today, with 7β8B models feasible only via aggressive memory mapping and offloading. Activations and the KV cache add on top; the KV cache in particular grows with sequence length and head count and is a common hidden overdraw.
| Target | Practical model size | Runtime | Notes |
|---|---|---|---|
| Flagship phone | 1β3B at INT4 | llama.cpp, MediaPipe, MLX | 2β6 GB app budget |
| Mid-range phone | 0.5β1B at INT4 | TFLite, ONNX Runtime Mobile | Watch thermal throttling |
| Browser (WASM) | 0.5β1B at INT4/INT8 | llama.cpp WASM, WebLLM | Streaming weights from CDN |
| Browser (WebGPU) | 1β3B quantized | WebLLM, ONNX WebGPU | Capability-gated fallback |
| Raspberry Pi class | 1β3B at INT4 | llama.cpp, ONNX Runtime | CPU-bound, slow but steady |
| MCU (ESP32 class) | Tiny models, sub-100M | TFLite Micro | Keyword spotting, not chat |
Quantization and packaging for small runtimes
Quantization is what makes edge inference possible. INT8 halves memory versus fp16; INT4 quarters it, at a quality cost that varies significantly by quantization method. Weight-only quantization keeps activations in fp16, which preserves most quality and is the default for CPU inference. Activation quantization to INT8 squeezes further and needs calibration data representative of real traffic, or accuracy falls off a cliff on out-of-distribution inputs.
from dataclasses import dataclass
from typing import Dict, List
@dataclass
class DeviceProfile:
name: str
ram_budget_mb: float
runtime: str
max_bits: int
supports_gpu: bool
PROFILES: Dict[str, DeviceProfile] = {
"phone_flagship": DeviceProfile("phone_flagship", 450, "llama.cpp", 4, True),
"phone_mid": DeviceProfile("phone_mid", 200, "tflite", 4, False),
"browser_wasm": DeviceProfile("browser_wasm", 300, "llama.cpp-wasm", 4, False),
"browser_webgpu": DeviceProfile("browser_webgpu", 800, "webllm", 4, True),
"pi5": DeviceProfile("pi5", 400, "onnxruntime", 4, False),
}
class EdgePackager:
def __init__(self, param_count_b: float, kv_bytes_per_token: float = 0.05):
self.params_b = param_count_b
self.kv_mb_per_token = kv_bytes_per_token * 1024
def weights_mb(self, bits: int) -> float:
return self.params_b * 1e9 * bits / 8 / 1e6
def plan(self, profile: DeviceProfile, context_tokens: int = 2048,
batch: int = 1) -> Dict[str, object]:
bits = min(4, profile.max_bits)
weights = self.weights_mb(bits)
kv = self.kv_mb_per_token * context_tokens * batch
total = weights + kv
steps: List[str] = [f"quantize_w{bits}a16"]
if total > profile.ram_budget_mb * 0.9:
steps.append("reduce_context")
steps.append("enable_mmap_offload")
if profile.supports_gpu:
steps.append("enable_gpu_delegate")
steps.append("enable_prefill_cache")
return {
"profile": profile.name,
"weights_mb": round(weights, 1),
"kv_cache_mb": round(kv, 1),
"total_mb": round(total, 1),
"fits": total <= profile.ram_budget_mb * 0.9,
"steps": steps,
}
packager = EdgePackager(param_count_b=1.5)
for key in ("phone_flagship", "browser_wasm", "pi5"):
print(packager.plan(PROFILES[key], context_tokens=2048))
The 90 percent multiplier in the fit check is deliberate: leaving headroom for activations, runtime scratch buffers, and the rest of the app is the difference between a model that works and one that gets evicted. Packaging format matters as much as bit-width β memory-mapped quantized files (GGUF-style) let the OS page weights on demand, which is what makes larger-than-RAM models usable on phones even if slowly.
Runtime choice and the prefillβdecode split
Edge inference has two phases with very different bottlenecks. Prefill processes the prompt and is compute-bound; decode generates one token at a time and is memory-bandwidth-bound, because every step streams all the weights. CPU runtimes can be perfectly acceptable for decode on small quantized models β generation is slow, but latency per token is predictable. GPU delegates accelerate prefill dramatically and help decode too, but thermal limits mean sustained generation will downclock a phone after a few minutes.
import time
from dataclasses import dataclass, field
from typing import Callable, Dict, List
@dataclass
class EdgeEngine:
load: Callable[[str], object]
model_path: str
max_new_tokens: int = 128
thermal_limit_s: float = 90.0
samples: List[Dict[str, float]] = field(default_factory=list)
def generate(self, prompt: str) -> Dict[str, float]:
t0 = time.perf_counter()
text = self._run(prompt, self.max_new_tokens)
elapsed = time.perf_counter() - t0
tokens = max(len(text.split()), 1)
record = {
"latency_s": round(elapsed, 3),
"tokens": tokens,
"tps": round(tokens / max(elapsed, 1e-3), 2),
"over_thermal": elapsed > self.thermal_limit_s,
}
self.samples.append(record)
return record
def _run(self, prompt: str, n: int) -> str:
return " ".join(["tok"] * n)
def benchmark(self, prompts: List[str]) -> Dict[str, float]:
for p in prompts:
self.generate(p)
latencies = [s["latency_s"] for s in self.samples]
latencies.sort()
p95 = latencies[int(0.95 * (len(latencies) - 1))]
return {
"runs": len(latencies),
"median_s": latencies[len(latencies) // 2],
"p95_s": round(p95, 3),
"median_tps": sorted(s["tps"] for s in self.samples)[len(self.samples) // 2],
"thermal_violations": sum(s["over_thermal"] for s in self.samples),
}
Benchmark on physical hardware, not simulators, and include sustained-load runs β a model that feels fast for the first ten seconds and then throttles has a thermal problem, not a model problem. Streaming tokens to the UI keeps perceived latency low even when total generation time is seconds.
Memory techniques that buy real headroom
Four techniques matter more than micro-optimizations. Quantized KV cache β storing keys and values at 8 or 4 bits β cuts the largest dynamic allocation substantially at a small perplexity cost, and is standard in modern edge runtimes. Context truncation with a sliding window bounds cache growth regardless of conversation length. Prompt caching reuses the prefill state across turns in a chat, turning repeated system prompts into a one-time cost. Finally, speculative or early-exit decoding can cut perceived latency when paired with a smaller draft model on the same device.
None of these techniques change the fundamental trade: edge models are smaller and less capable than their cloud counterparts, which is exactly why the best edge architectures are hybrid.
Cold start, app size, and the update problem
Three lifecycle costs deserve attention before launch. First, cold start: loading a gigabyte-class quantized model into memory takes seconds on a phone and longer in a browser, which is fine for a background assistant and fatal for a feature the user expects to respond instantly. Mitigate by keeping a tiny always-resident model for the common case and warming the larger one lazily, or by streaming weights and showing progressive UI as layers arrive.
Second, app size: every megabyte of bundled weights counts against store limits and user willingness to install, and most teams underestimate how aggressively users prune large downloads. Download-on-demand weights with a clear progress state usually beat bundling.
Third, updates: unlike a server-side model you can roll back in minutes, an on-device model ships with the app binary or a downloaded artifact, and a bad release is stuck on user devices until they update. Treat model artifacts as separately versioned, downloadable packages with their own kill switch, so a defective model can be disabled server-side and replaced without forcing a full app update. That single operational decision turns model releases from quarterly events into ordinary, reversible deployments.
Hybrid designs: device for the easy, cloud for the hard
Most shipped products split the workload. On-device handles classification, routing, summarization of short text, autocomplete, and privacy-sensitive processing. The cloud handles long-context reasoning, tool use, and anything requiring the largest models. The router itself can run on device β a small classifier deciding local versus remote β which keeps the split automatic and private.
The operational win is cost and resilience: the majority of interactions never touch expensive GPU endpoints, and offline mode degrades gracefully to local-only features instead of failing outright. The design cost is consistency: responses must feel similar across paths, and you need versioning discipline so a model update on one side does not visibly contradict the other.
Common Mistakes
Budgeting only for model weights and forgetting the KV cache
Fix: Size the cache for your real context length and add runtime scratch headroom before claiming a model fits.
Testing exclusively on flagship phones
Fix: Mid-range devices and thermal-throttled sustained runs expose the failures users actually hit.
Shipping fp16 models to phones because quality feels safer
Fix: Weight-only INT4 on a 1β3B model usually beats fp16 at a fraction of the memory, and quality loss is measurable, not catastrophic.
Treating the browser as a first-class equal target
Fix: Gate WebGPU features on capability detection and keep a WASM or cloud fallback ready.
Updating on-device and cloud models independently
Fix: Version them together and test response consistency, or users see behavior flip depending on connectivity.
Best Practices
- Choose the model size from the device profile first, then pick the architecture that fits β not the reverse.
- Use memory-mapped quantized files so the OS can page weights instead of requiring a full in-RAM allocation.
- Instrument on-device telemetry for tokens per second, thermal violations, and crash rates around model load.
- Cache prompt prefill state per conversation turn; it is the single biggest interactive latency win on device.
- Design the offline mode explicitly: which features remain, what the UI says, and when the app retries upstream.
Key Takeaways
- Edge LLM feasibility is a memory-envelope problem: parameters Γ bytes plus KV cache must fit well under the device's RAM budget with headroom.
- Weight-only INT4 quantization is the practical default for 1β3B models on phones, with activation quantization reserved for calibrated, well-understood pipelines.
- Prefill is compute-bound and decode is bandwidth-bound; runtime choice and thermal behavior differ accordingly.
- Quantized KV caches, sliding-window context, and prompt caching buy more real headroom than most low-level micro-optimizations.
- Hybrid architectures β on-device router and small model, cloud for hard cases β deliver the cost, privacy, and offline wins that make edge deployment worthwhile.