Fitting LLMs on Edge Devices: PLE and Peak Memory Estimation

    This article explores the feasibility of running large language models (LLMs) on edge devices by analyzing memory constraints, parameter types, and Per-Layer Embeddings (PLE). It details the implementation steps for 4-bit quantization and embedding table paging, provides a practical formula for peak memory estimation, and outlines a pre-deployment checklist to ensure optimal performance and mitigate operational risks.

    1. Defining Three Core Constraints

    Running large language models (LLMs) on edge devices is primarily constrained by three factors: available memory, memory bandwidth, and power consumption. Available memory determines whether the model can fit. Memory bandwidth determines how much data is transferred to generate each token, often acting as the speed ceiling. Power consumption dictates how long the device can sustain inference.

    During model selection, nominal memory cannot substitute for available memory. Mobile operating systems reclaim memory from background apps. Raspberry Pi is limited by onboard RAM, with the OS and other processes consuming a portion.

    Methods to measure available memory are as follows:

    • iOS: Use os_proc_available_memory() to read the memory available for the current process.
    • Android: Read availMem via ActivityManager.MemoryInfo, and check the lowMemory flag to assess system memory pressure.
    • Linux or Raspberry Pi: Read MemAvailable from /proc/meminfo, or run free -m.

    Measurements should be taken while the app is in the foreground, with background apps normally resident, and sampled multiple times. It is recommended to keep at least a 20% memory margin to prevent the OS from terminating the inference process.

    Data center GPUs typically have significantly higher memory bandwidth than edge devices. A model with the same parameter count may run several times slower on an edge device. Therefore, design must focus on the actual weight data read per token.

    2. Total, Effective, and Active Parameters

    These three concepts are often confused and require clear definitions:

    • Total parameters: The number of all parameters in the model, including weights from all layers and embedding tables. This determines storage usage and the minimum resident memory.
    • Effective parameters: Parameters involved in matrix operations during a single forward pass. This determines computational load.
    • Active parameters: Values actually read per token calculation, including rows fetched from embedding tables. This relates to bandwidth pressure but is not the sole determinant.

    For this article: Total parameters include the token embedding table and output layer. If the output layer shares weights with the embedding table, they are only counted once.

    The relationship among these three differs across architectures:

    • Dense Transformer: All layer weights participate in each token’s calculation. The non-embedding effective and active parameters are essentially identical.
    • Mixture of Experts (MoE): Total parameters include all experts, but only a few experts are activated per token. Storage is based on total parameters, while per-token read volume is based on active experts, creating a large gap.
    • Per-Layer Embeddings (PLE): Most parameters are lookup tables. The total table size is large, but only a small fraction is read per token.

    Consider a magnitude-level example. Assume a vocabulary size of 50,000, an embedding dimension of 64, 24 layers, and an independent embedding table per layer. Total table parameters are 24 × 50,000 × 64 ≈ 76.8 million. During inference, each token reads 24 vectors from the layer tables, totaling 24 × 64 = 1,536 values. If stored in 4-bit, the total table footprint is about 38.4MB, and the per-token read volume is about 768 bytes. Refer to the model configuration file for actual dimensions and layer counts.

    Bandwidth pressure is also affected by other factors, including KV cache reads, random reads from embedding lookups, and actual memory bandwidth utilization. Therefore, speed cannot be accurately estimated by looking at active parameters alone; empirical testing is required.

    3. How Per-Layer Embeddings (PLE) Work

    Per-Layer Embeddings (PLE) equips each layer with a smaller embedding table. The model looks up a vector from each layer’s table based on the input token ID and combines it with that layer’s hidden state. This allows the model’s storage capacity to increase with minimal increase in per-token computation and read volume.

    The PLE read path is as follows:

    1. Look up the corresponding vector in each layer’s table based on the input token ID.
    2. If the implementation includes projection or gating matrices, map the looked-up vector to the hidden dimension. These matrices count as effective parameters and must be tracked separately.
    3. Add or multiply the result with that layer’s hidden state to proceed with subsequent calculations.

    The primary benefit of PLE is storage. When tables are resident in memory, the bandwidth impact of table lookups is minimal. However, if tables must be paged to flash memory, each lookup may trigger a random read, making latency and I/O the primary bottlenecks.

    4. 4-bit Quantization and Embedding Table Paging Steps

    4.1 4-bit Quantization

    1. Choose a group quantization method, commonly with a group size of 32, 64, or 128. Each group requires saving a scale value, such as a 16-bit float. With 4-bit weights plus the scale value, the equivalent bit width is approximately 4 + 16 / group size. With a group size of 32, the equivalent bit width is about 4.5 bits. Memory estimation must use this equivalent bit width, not just 4.
    2. Quantize using a representative calibration dataset covering the text types and lengths of the target scenarios.
    3. Compare results before and after quantization, including task accuracy, output quality, and perplexity. If a specific task degrades significantly, retain higher bit widths for sensitive layers or the output layer, then re-test.
    4. Load the quantized model on the target device, record the actual resident memory, and compare it with the formula estimate.

    4.2 Embedding Table Paging

    1. Split the embedding table by pages. The page size should align with the flash memory read unit, such as a multiple of 4KB. A larger page means more data per read and lower cache utilization.
    2. Set a cache budget, which is the number of bytes in resident memory available for caching embedding pages. This budget is derived from available memory minus other components.
    3. Manage the cache using policies like Least Recently Used (LRU). For each token, check the cache first; if hit, use it directly; if missed, read the page from flash and replace an old page in the cache.
    4. Record the cache hit rate. If the hit rate is low, either increase the cache budget, reduce the page size, or switch to a fully resident approach.
    5. After sampling the current token, prefetch pages that the next token might need to reduce miss wait times.
    6. Measure read latency on misses on the target device, and track tail latency (e.g., 95th or 99th percentile), not just the average.

    4.3 Random Read Risks

    The main risk of the paging scheme comes from flash memory random reads. Latency fluctuations in random reads can be significant, potentially increasing tail latency and making generation speed unstable. Frequent reads consume I/O bandwidth, increasing power consumption and heat. While reads barely consume flash write lifespan, if the app performs heavy writes simultaneously, the overall storage load must be monitored.

    5. Peak Memory Estimation

    Estimate peak memory before deployment using the following formula:

    M_peak ≈ α × ( W_core × b_w / 8 + E_res × b_e / 8 + KV + A )

    All terms are in bytes, and the result is in bytes. The symbols are defined as follows:

    Symbol Meaning Unit Source
    M_peak Peak memory Bytes Formula result
    α Runtime overhead coefficient, covering framework memory pools, fragmentation, and alignment waste Dimensionless Empirically measured on the target device using the target inference framework, as the ratio of actual resident memory to theoretical value; if unmeasured, use 1.1 to 1.3
    W_core Non-embedding layer parameters, including attention, FFN, and projection matrices. For MoE models, include all experts Count Model config or weight file
    b_w Equivalent bit width of weights; 4-bit group quantization must include the scale value Bit Quantization config
    E_res Resident memory embedding parameters. If fully resident, equals total table parameters; if paged, only includes parameters corresponding to cached pages Count Model config and cache budget
    b_e Equivalent bit width of the embedding table Bit Quantization config
    KV KV cache usage, calculated as 2 × L × n_kv × d_head × T × b_kv / 8 Bytes See below
    A Activations and temporary buffers, including intermediate activations per layer, attention score temporary matrices, and output logits buffer Bytes Estimated from framework measurements or empirical values, commonly tens of MB

    For the KV term, the symbols mean: L is the number of layers, n_kv is the number of KV heads, d_head is the dimension per head, T is the context length (number of tokens), and b_kv is the bit width of the KV cache (e.g., 16 for fp16).

    5.1 Worked Example

    Assume a model has the following configuration:

    • Non-embedding parameters W_core = 1.0 × 10^9, 4-bit group quantization with group size 32, equivalent bit width b_w = 4.5.
    • All embedding parameters are resident, E_res = 2.0 × 10^8, b_e = 4.
    • Layers L = 24, KV heads n_kv = 4, dimension per head d_head = 64, context length T = 2048, KV cache is fp16, b_kv = 16.
    • Activations and temporary buffers A = 60,000,000 bytes.
    • Runtime overhead coefficient α = 1.2.

    Calculate term by term:

    • Weights: 1.0 × 10^9 × 4.5 / 8 = 562,500,000 bytes.
    • Embeddings: 2.0 × 10^8 × 4 / 8 = 100,000,000 bytes.
    • KV: 2 × 24 × 4 × 64 × 2048 × 16 / 8 = 50,331,648 bytes (approx. 48 MiB).
    • Total inside parentheses: 562,500,000 + 100,000,000 + 50,331,648 + 60,000,000 = 772,831,648 bytes.
    • Peak memory: 1.2 × 772,831,648 ≈ 927,397,978 bytes (approx. 0.93 GB).

    If the target device’s measured available memory is 1.2 GB, the margin is about 0.27 GB, roughly 22% of available memory, satisfying the 20% margin requirement. If available memory is only 1 GB, the model cannot fit directly; you would need to shorten the context, reduce the cache budget, or select a smaller model.

    5.2 Bandwidth Limit Estimation

    The dense part must read all non-embedding weights per token, about 562.5 MB. As the context approaches 2048, the KV cache also requires reading about 50 MB per token. Combined, this is about 612 MB. If the effective bandwidth measured on the target device is 20 GB/s, the theoretical limit is 20 × 10^9 / (6.12 × 10^8) ≈ 33 token/s. Actual speed is typically lower than the theoretical limit and must be verified empirically.

    6. Pre-Deployment Checklist

    Confirm the following before deployment:

    • Available memory: Measured multiple times on the target device, recording the method and timing.
    • Peak memory margin: Formula result subtracted, margin is at least 20% of available memory.
    • Runtime overhead coefficient: α calibrated with empirical values, not arbitrarily estimated.
    • Bandwidth estimation: Theoretical limit calculated based on actual per-token read volume, and empirically tested.
    • Context length: Maximum T determined, with corresponding KV usage calculated.
    • Quantization precision: Compared with unquantized version, acceptable degradation on key task metrics confirmed.
    • Paging hit rate: Measured on typical inputs, meeting latency requirements.
    • Flash random read latency: Average and tail latency measured, confirmed to be within acceptable application bounds.
    • Power and heat: Tested under sustained inference to ensure no thermal throttling.
    • Fallback plan: Clear degradation strategy (e.g., shorter context, smaller model) if memory or latency limits are exceeded.

    7. Risk List

    • Discrepancy between nominal and available memory; system reclaiming background apps may interrupt inference.
    • The formula only provides an estimate; fragmentation and framework behavior may cause actual peaks to exceed estimates.
    • 4-bit quantization reduces precision; degradation on certain tasks or languages may exceed expectations.
    • With embedding table paging, random reads on misses increase tail latency, affecting UX.
    • Frequent random reads increase power and heat; speed may degrade during prolonged inference.
    • Growing context length simultaneously increases KV usage and bandwidth pressure, raising risks during long conversations.
    • Flash memory performance varies significantly across devices; results from one device cannot be directly applied to another.
    • Parameter counts and memory requirements provided by model vendors may not include runtime overhead and require independent verification.

    8. Conclusion

    Determining if an edge model can fit and run efficiently requires three steps. First, use empirically measured available memory and the formula to estimate peak memory, retaining a sufficient margin. Second, estimate the bandwidth limit using actual per-token read volume, taking empirical speed as the standard. Third, validate precision and latency for quantization and paging schemes. Each step has a clear measurement method. If any step fails to meet criteria, adjust the model size, context length, or cache strategy and re-test.