On-Device LLM Selection: Effective Parameters and Per-Layer Embeddings Explained
A practical guide to choosing large language models for on-device deployment. It explains why effective parameters matter more than total parameters, how Per-Layer Embeddings (PLE) trade memory access for compute, the architectural choices behind small models (sliding window attention, GQA/MQA, mixed layer stacks), quantization tradeoffs from FP16 to INT4, and why KV cache becomes the real memory bottleneck for long context. It also covers device-cloud routing, a reproducible benchmarking methodology, and a selection checklist for teams evaluating an on-device model.
1. On-Device Deployment Constraints: Identify the Bottleneck First
Over the past year or two, lightweight on-device language models have moved from “toy” to a shippable product form. Phone assistants, in-car voice, smart hardware, and edge gateways now expect models to deliver usable answers even without a cloud fallback. These models typically ship in several tiers: one targets mobile and dev-board-class edge devices with roughly 4B total parameters (about 8B including the embedding table); another is more aggressive at roughly 2B total parameters (about 5B including embeddings), aimed at phones, IoT, and embedded scenarios. Note the wording here — “effective parameters” and “total parameters including embeddings” are two different numbers, and that gap is central to on-device model design.
The first-order difference between device and cloud is not raw compute but bandwidth, power, and thermals. Memory available to a phone app is typically on the order of a few hundred MB, and even less on edge devices; memory bandwidth is often a fraction of a data center’s, sometimes far less; sustained full-load inference triggers thermal throttling quickly, and frame rate and generation speed drop together. So the key on-device metrics are not “peak compute” but:
- Memory bandwidth: determines per-token generation speed, because decoding reads all activated weights on nearly every step.
- Peak memory: model weights + KV cache + runtime overhead — decides whether it fits at all.
- Time to first token (TTFT): determines whether it feels “laggy” to the user, and is especially sensitive with long prompts.
- Power and sustained performance: decides how long the device lasts and whether it slows down.
Under these constraints, “effective parameters” is a more actionable engineering metric than total parameters: it measures the parameter count that actually participates in matrix multiply-adds per forward pass, and it maps directly to compute load and bandwidth pressure.
2. Effective Parameters and Per-Layer Embeddings (PLE): How Small Models Save Compute
1. What the “E” Stands For
Small-size tiers are often labeled with an E for effective parameter count, e.g., “2.3B effective / ~5B with embeddings” or “4.5B effective / ~8B with embeddings.” Almost the entire difference lives in the vocabulary-related embedding table.
2. How PLE Works
The traditional approach is a single embedding matrix sized to the vocabulary: vocab V (commonly 250K–260K) × hidden dimension d (e.g., 2048). At 250K × 2048 in bf16, the main embedding alone is about 1GB, and the output head often duplicates a weight matrix of the same size to compute logits. The smaller the model and d, the more exaggerated these two blocks become — a 2B-total-parameter model may have embedding-related weights exceeding 2B.
PLE (Per-Layer Embeddings) replaces “one big table” with “one small table per layer”: the main embedding stays relatively small, while each decoder layer gets a small embedding table (possibly only KB-to-MB scale), and the row vector fetched for that layer by input token id is added onto that layer’s hidden state.
The key point: a lookup is a memory-access operation, not a multiply-add. Although the per-layer tables push total parameters up by several GB, each token fetches only one row per layer, so compute is nearly unchanged. This is where “large total parameters, small effective parameters” comes from.
# Pseudocode: layered embedding forward (illustrative, not tied to any specific implementation)hidden = main_embedding[input_ids] # main embedding: the only large matrix lookupfor i, layer in enumerate(decoder_layers):# per-layer embedding: one small table per layer, fetch the row by token idlayer_vec = layer.embed_table[input_ids] # memory access, not matmulx = hidden + layer_vec # element-wise add, negligible costx = layer.attention_and_ffn(x) # the real matmul cost is herehidden = xlogits = output_head(final_norm(hidden))
3. Engineering Gains and Costs of PLE
Gains
- Significantly better parameter efficiency: within a given memory budget, you can allocate more of it to the actual attention/FFN compute rather than one giant lookup matrix.
- Minimal architectural change: attention and FFN structures are untouched; the inference framework only needs “per-layer lookup + add,” far cheaper to implement than changing the structure.
- Multimodal-friendly: vision/audio encoders can reuse the same layered-embedding mechanism, leaving an interface for a unified token space.
Costs
- Total weight size is still substantial; flash footprint, first-load time, and memory-mapping pressure must be re-evaluated.
- The access pattern becomes many small, fine-grained random reads, which is unfriendly to storage and memory subsystems and may raise TTFT rather than lower it.
- The per-layer tables often need to stay at higher precision (lookups are sensitive to quantization error, and quantization yields less than on matmul weights), so the real compression room is limited.
- Vocab size and per-layer table dimension become new tuning dimensions that must be searched jointly rather than in isolation.
An easily overlooked point: don’t judge on-device feasibility by total parameters alone. A 2B-effective model and a 2B-effective + 3B-embedding model are close in compute cost but differ by 2x in storage and bandwidth. During selection, ask three questions: How many active parameters? How many total weight bytes? How many bytes must be moved from memory per token during decoding?
3. Architectural Tradeoffs: Why Small Models Are Still Experimenting
On-device models are commonly doing a few things, and understanding the motivation matters more than memorizing the terms:
- Sliding window attention (SWA) alternating with global layers: most layers are confined to a local window while only a few global layers are kept, trading a tiny loss of long-range capability for a large drop in KV cache. The more layers and the narrower the window, the more obvious the long-context memory benefit.
- Grouped-query attention (GQA/MQA): multiple query heads share one set of K/V heads, directly compressing the KV cache. This is a prerequisite for long conversations to run on device.
- Alternating local/global + sparsified hybrid stacks: with total layers fixed, a ratio like 5:1 balances “local efficiency” against “global modeling.”
- PPLE / parameter-sharing layered embeddings: further compresses the per-layer tables themselves, changing embedding cost from “growing linearly with layers” to “shared across groups.”
- Non-standard attention variants: such as gated attention outputs, QK-norm, etc., used to improve numerical stability under low precision and trainability of small models.
Practical advice: prefer models that can be pruned layer-by-layer. If every layer is homogeneous, you can drop a few layers by importance to get a smaller variant; if local and global layers strictly alternate, dropping layers breaks the 5:1 ratio and must be done in pairs, which raises the engineering effort substantially.
4. Quantization: From FP16 to INT4, Where Accuracy Is Lost
The mainstream configuration for on-device inference is int4/int8 weights with int8 or bf16 activations (W4A8 / W8A8). Be clear about the gains and costs of each tier:
| Configuration | Weight size (vs. bf16) | Main benefit | Main risk |
|---|---|---|---|
| bf16/fp16 | 100% | accuracy baseline | largest size and bandwidth pressure |
| W8A8 | ~50% | ~2x throughput, usually the smallest accuracy loss | needs activation range calibration |
| W4A16 | ~30% | large drop in memory/bandwidth | low-rank and long-tail layers tend to break |
| W4A8 | ~30% | benefits to both size and throughput | two quantization errors stack |
Rules of thumb:
- Keep accuracy-sensitive layers at higher precision. The QK^T and softmax in attention, RMSNorm/LayerNorm, residual adds, and the output head are all extremely quantization-sensitive. The common practice is to leave them in bf16/fp16 and only quantize the FFN linear layers to low bit-widths.
- Activation outliers are harder than weight quantization. Small models tend to produce a few channels with very large values over long sequences, so W8A8 needs mixed precision or per-channel/per-token dynamic scaling.
- Low bit-width + structured sparsity can stack, but measure it. Sparsity gains depend heavily on whether the kernel actually skips zeros; a drop in theoretical FLOPs is not the same as a drop in wall-clock time.
- Quantization requires regression testing. At minimum cover: perplexity, task accuracy, long-context consistency, structured-output (JSON) validity rate, and multilingual performance. Many cases of “runs but nonsense after quantization” surface here.
5. KV Cache and Long Context: The Real Memory Killer on Device
Given total layers L, number of KV heads n_kv, head dimension d_kv, sequence length s, and precision b (bytes):
KV_bytes ≈ 2 × L × n_kv × d_kv × s × b
For example, L=24, n_kv=2, d_kv=128, s=8192, bf16 (2 bytes) is about 200MB — a non-trivial cost on a phone.
On-device techniques, ranked by cost-effectiveness:
- GQA/MQA: solved at the architecture level; prefer models that already have this design.
- Sliding window + global layers: confine most layers’ caches to the window, dropping memory from O(s) to O(w) for long sequences.
- KV quantization: int8 usually loses very little; int4 needs per-channel scaling and regression testing.
- Paging/block management + prefix reuse: multi-turn conversations share the system prompt and history prefix to avoid duplicate storage.
- Eviction policies: sliding windows evict naturally; if the model has no window capability, you can use attention-score-based “important-token retention” methods, but they are complex to implement and their effect must be measured.
Also note: prefill is compute-intensive while decode is bandwidth-intensive. One-shot long-document input is bottlenecked by compute and TTFT; multi-turn short conversations are bottlenecked by per-token bandwidth. The two have different optimization directions — don’t tune them together.
6. Device-Cloud Collaboration: The Right Role for Small Models
Don’t try to make an on-device small model solve every task end to end. A more robust engineering approach is layering:
# Pseudocode: device-cloud layered routing (illustrative)def answer(query, device_state):task = router.classify(query) # lightweight local classifier, few-ms scaleif task in LOCAL_CAPABLE and device_state.can_afford():out = local_model.generate(query, max_tokens=512)if verifier.acceptable(out): # rule/small-model checkreturn out, "on-device"ctx = compressor.summarize(history, budget=2048)return cloud_model.generate(query, context=ctx), "cloud"
Key design points:
- Routing signals: task type, confidence, device battery/temperature/network state, privacy level. Process sensitive data locally by default; upload only summaries or structured results.
- Result verification: JSON validity, length constraints, unit/format rules — use low-cost rules to catch the “format drift” small models commonly exhibit.
- Context compression: the device handles retrieval and compression while the cloud handles inference. This keeps upload size small, latency low, and the privacy exposure surface minimal.
- Fallback chain: local small model → cloud large model → rule-based fallback / human handoff, with an explicit failure signal at each level.
- Version management: tag model version, quantization config, prompt, and vocab alongside each request; otherwise production issues can’t be attributed.
When hosting this kind of service on the cloud side, the common practice is to use a container platform for elastic scaling of the inference service, object storage for model and data versioning, and logging plus monitoring/alerting services to track latency, error rate, and call volume. These are industry-standard cloud capability categories, and Baidu AI Cloud provides corresponding products; combine them as needed during selection.
7. Reproducible Evaluation: How to Test On-Device
The most common mistake in on-device evaluation is reporting only a single “tokens/s” number. At minimum, cover these dimensions:
| Metric | Description | Common pitfall |
|---|---|---|
| TTFT | time to first token | not comparable across input lengths — fix s |
| Decode speed | tokens/s (single request) | whether sampling and dequantization overhead are included |
| Peak memory | weights + KV + runtime | whether mapped flash weights are counted |
| Power/temperature rise | behavior over a sustained 10 minutes | looking at instantaneous values only, ignoring thermal throttling |
| Task accuracy | a downstream metric, not PPL | applying a cloud eval set directly to a small model |
| Structured-output validity | JSON/function calls | huge variance from different temperature settings |
Methodologically: fix the input-length distribution + fix sampling parameters (recommend temperature 0 or a low temperature for the baseline) + report per scenario (short QA / long documents / multi-turn dialogue / multimodal) + run long-duration stability tests. For multimodal, also measure image/audio encoding preprocessing time separately — it’s often missed but accounts for a sizable share.
8. Selection Checklist
- What are the effective parameters and total parameters respectively? How many bytes do embedding-related weights occupy?
- Does it support GQA/MQA? Plug into the KV cache formula — how much memory do 8k/32k contexts each take?
- Which quantization tier is used? Are sensitive layers kept at high precision? Is there measured regression data?
- Does it support layer-by-layer pruning? Does pruning require handling local/global layers in pairs?
- Does the inference framework natively support PLE and sliding window? What’s the extra overhead when it doesn’t?
- Can the available memory on the target device (after deducting the OS and other apps) cover weights + KV + runtime?
- Is there a clear statement of capability boundaries: which tasks run locally and which must go to the cloud?
- Does the license permit your distribution form (especially on-device preinstallation and commercial use)?
9. Conclusion
The design logic of on-device small models has shifted from “shrink the large model” to “redesign the compute path for bandwidth and memory.” The value of PLE is trading memory access for multiply-adds, saving the precious compute budget for the parameters that actually participate in computation; the value of sliding windows and GQA is turning the cost of long context from linear into something controllable; the value of quantization is making every weight outside the sensitive layers a low-bit transfer.
For developers, the pragmatic path is: first use a cloud large model to establish the task baseline, then let the on-device model take over high-frequency, short-output, low-sensitivity subtasks, use a verification layer to contain format and factual risk, and close the loop with continuous optimization via monitoring. An on-device model is not a shrunk-down replacement for a cloud model, but an independent engineering species that re-solves for the optimum under four constraints — bandwidth, power, latency, and privacy. Understanding its constraints matters more than memorizing its parameter table.
