Open-Source LLM Architecture Analysis and Edge Inference Adaptation Guide

    This article provides a comprehensive guide to evaluating and adapting open-source large language models (LLMs) for edge inference. It covers architectural cost analysis beyond parameter scale, the impact of layer-wise embeddings, KV cache sharing, hybrid attention, and multimodal deployment. Additionally, it outlines a reproducible workflow for verifying numerical correctness, performance metrics, and business task acceptance to ensure reliable deployment conclusions.

    1. Evaluating Open-Source LLMs: Define the Evaluation Target First

    When facing a newly released open-source LLM, developers typically care most about three questions: Is the capability sufficient? Can the device handle it? Is the integration cost controllable? These three questions correspond to model quality, resource efficiency, and engineering usability, which cannot be simply replaced by parameter scale or a single benchmark score.

    The same model can present completely different user experiences under different devices, quantization precisions, context lengths, and concurrency conditions. For example, smooth short Q&A responses do not mean that long document analysis will remain stable; high text generation speed does not mean that the time-to-first-token latency in an image understanding pipeline is low enough.

    Therefore, the evaluation should form a complete chain:

    Model structure analysis → Runtime adaptation → Numerical correctness verification → Resource and performance testing → Business task acceptance.

    This article discusses this general technical problem. It does not review specific models as products, nor does it treat unverified architectural descriptions as universal facts. When mechanisms like layer-wise embeddings or cross-layer cache sharing are involved, they should always be based on the actual public configurations, weight structures, and implementation explanations of the target model.

    2. From Parameter Scale to Architectural Cost Analysis

    1. Parameter Count Does Not Directly Represent Deployment Cost

    The space required for model weights can be roughly estimated first:

    Weight storage ≈ Number of parameters × Storage bits per parameter ÷ 8.

    However, this only describes the weights themselves. Actual operation also requires KV cache, activation tensors, temporary computation buffers, quantization auxiliary data, and runtime management space. Multimodal models may also need to load visual or audio encoders simultaneously.

    Therefore, deployment feasibility should be based on peak memory, not the weight file size. Especially on edge devices, the application itself, the operating system, and graphics processing will also compete for memory. Judging stable operation solely on “the weights fit” can easily lead to crashes or frequent swapping during long inputs.

    2. Dense vs. Sparse Expert Computation Must Be Evaluated Separately

    Dense models typically use the vast majority of intra-layer parameters in each forward computation. Sparse expert models (MoE), on the other hand, use a routing mechanism to allow each token to enter only a subset of experts.

    This design may reduce the computation per token, but it does not mean that the total model weights can be proportionally reduced according to the activation ratio. Experts not used by the current token still need to reside in memory or be loaded from other storage tiers when needed.

    Therefore, for sparse expert models, at least the following should be examined separately:

    • Total parameter count and its storage cost;
    • Actual activated computation per token;
    • Expert routing and data movement overhead;
    • Load balancing under different inputs.

    For devices with limited memory bandwidth, reducing computation may not bring proportional speedups.

    3. Layer-wise Embeddings: Adding Information Pathways and Adaptation Requirements

    Traditional language models usually first convert token IDs into vectors, and then the multi-layer network continuously updates the hidden states. The layer-wise embedding mechanism provides additional token-related information to some or all network layers, so that intermediate layers do not have to rely entirely on the representations passed down from previous layers.

    A schematic expression is:

    h′ₗ = hₗ + gₗ(hₗ, eₗ(t))

    Where hₗ represents the hidden state of the l-th layer, eₗ(t) represents the token embedding used by that layer, and gₗ represents projection, gating, or other fusion operations. This formula is only used to explain the information flow; not all models adopt the same computational form.

    1. Potential Design Value

    Additional information pathways can provide the network with supplementary signals related to token identity or lexical features, changing the way the model stores and processes information across different layers.

    However, it cannot be directly inferred from this that “the number of layers can be reduced,” “the speed will definitely be faster,” or “the performance will inevitably be better.” These conclusions need to be verified through ablation experiments and real deployment tests.

    2. Main Difficulties in Inference Adaptation

    The first is weight layout. If multiple layers have their own embedding tables or projection matrices, the export process must correctly preserve the mapping between layer IDs, token IDs, and weight shards.

    The second is tensor shape. The prefill phase processes an input sequence, while the decode phase typically processes only one new token at a time. The lookup and broadcasting logic for both must be consistent.

    The last is the quantization strategy. The data distributions of embedding tables and projection matrices may differ, so the same quantization method should not be applied without calibration. Checking the lookup results, fusion outputs, and subsequent hidden states separately makes it easier to locate error sources.

    4. KV Cache Sharing: More Than Just Saving Data Copies

    Autoregressive generation typically caches the keys and values of historical tokens to avoid recalculating all historical states every time a new token is generated.

    For common structures where each layer caches independently and the dimensions of keys and values are the same, the cache capacity can be approximated as:

    Cache bytes ≈ 2 × Number of layers × Batch size × Cached sequence length × Number of KV heads × Dimension per head × Bytes per element.

    The “2” in the formula corresponds to keys and values respectively. If the number of heads, dimensions, or cache precision differ across layers, they should be calculated separately by layer and then summed.

    1. Cross-Layer Sharing Must Originate from Model Design

    Cross-layer cache sharing means that certain attention layers reuse keys and values generated by other layers according to the model’s predefined structure. It is different from multiple requests sharing a common prefix cache, and also different from simply merging cache storage spaces.

    These layers have specific computational dependencies. Independent layers cannot arbitrarily share a copy of the cache just to save memory, otherwise it will alter the model’s behavior.

    2. The Runtime Must Clarify Cache Ownership

    The sharing mechanism requires the runtime to know:

    • Which layer is responsible for generating the cache;
    • Which layers only read the cache;
    • When the cache is written and when it is released;
    • How position IDs and valid sequence lengths are synchronized;
    • How to clean up state when a request is canceled or the batch is adjusted.

    If each consuming layer still copies a copy of the data, it may be functionally correct, but the expected memory savings will not be achieved. Conversely, if the cache is released prematurely or overwritten incorrectly, it may produce output errors that are difficult to reproduce stably.

    3. Memory Savings Do Not Equal Proportional Speedup

    Sharing the cache can reduce some storage or projection computation, but attention reads, position processing, and synchronization operations still exist. The final benefit depends on whether computation, bandwidth, or scheduling overhead is the bottleneck; generation speed cannot be estimated solely based on the number of cache copies.

    5. How Hybrid Attention and Heterogeneous Structures Affect Inference

    1. Local Attention vs. Global Attention

    Local attention allows tokens to primarily focus on historical information within a limited window, while global attention retains a broader context interaction range. Hybrid designs attempt to strike a balance between resource cost and long-range modeling capability.

    It should be noted that the theoretical advantages of local attention can only be fully realized when the runtime genuinely supports windowed computation and windowed cache management. If computation is still executed on the full history and then masking is used to block out-of-window positions, the actual efficiency may be significantly lower than expected.

    2. Different Layers May Have Different Structures

    Some models may use different numbers of KV heads, attention ranges, or positional encoding configurations for different layers. In such cases, the inference engine can no longer assume that all layers have uniform tensor shapes.

    A more robust approach is to read the configuration layer by layer and determine projection dimensions, cache layouts, and execution paths separately. Padding with invalid data to unify shapes during the export phase may negate the original structural optimizations.

    3. Normalization and Positional Encoding Must Be Strictly Aligned

    The normalization position, scaling factors, and positional encoding methods in attention all affect numerical results. Existing implementations should not be directly reused just because the formulas “look similar.”

    In particular, it is necessary to check rotation dimensions, frequency parameters, position offsets, and the positional alignment between prefill and incremental decoding. Such errors may not be obvious in short inputs, but will continuously accumulate in long contexts.

    6. Multimodal Deployment: Inspect the Complete Input Pipeline

    Multimodal models typically involve input preprocessing, modality encoding, feature alignment, language model inference, and output processing. Any inconsistency in one part may manifest as a degradation in final answer quality.

    1. Image Input

    Image scaling, cropping, normalization, patching methods, and visual token arrangement should all be consistent with the model’s requirements. Increasing the resolution may add identifiable details, but it may also increase the number of visual tokens, preprocessing time, and subsequent attention costs.

    Therefore, tests should not only record the speed of the text generation phase, but also the time spent on image reading, preprocessing, and encoding.

    2. Audio Input

    The audio pipeline usually involves resampling, feature extraction, segmentation, and temporal information processing. Long audio also requires considering segment concatenation, repeated content, and boundary truncation issues.

    Having an audio encoder does not inherently mean it supports streaming recognition, real-time interaction, or audio generation capabilities. The specific scope of support must be confirmed separately.

    3. Define Boundaries for Cache Reuse

    When the same image or audio is used repeatedly, it is possible to evaluate whether to reuse the encoding results. However, encoded features and the KV cache in the language model are not the same object and cannot be directly interchanged.

    Before reuse, it is also necessary to confirm whether the preprocessing configuration, model version, and input arrangement are consistent; in enterprise systems, data isolation between users must also be guaranteed.

    7. Establishing a Reproducible Adaptation and Evaluation Workflow

    Step 1: Compile a Structural Checklist

    Before writing operators, first confirm the vocabulary, number of layers, attention type for each layer, cache dependencies, positional encoding, normalization methods, and multimodal input protocols.

    The goal of this step is to eliminate implicit assumptions. For example, assumptions like “all layers have independent value projections” or “all layers have the same number of heads” will lead to incorrect export results once they do not match the actual structure.

    Step 2: Verify Numerical Values Before Optimizing Performance

    It is recommended to verify in the following order:

    1. Align input encoding results;
    2. Compare embedding layers and representative intermediate layer outputs;
    3. Compare attention and feed-forward network outputs;
    4. Check consistency between prefill and token-by-token decoding;
    5. Finally, check complete task performance.

    Verification should prioritize deterministic decoding settings to reduce random sampling interference. Comparing only the final text is insufficient because accidental textual similarity does not prove that intermediate computations are correct.

    Step 3: Introduce Quantization Phased

    First establish a high-precision baseline, then gradually quantize weights, caches, or other tensors to help locate the source of quality loss.

    Quantization acceptance should not only look at average errors but also include long inputs, repetitive generation, structured outputs, and multimodal tasks. Different modules have varying sensitivities to errors; when necessary, higher precision should be retained for certain modules.

    Step 4: Measure Different Runtime Phases Separately

    At least the following should be recorded:

    Phase Key Metrics Main Issues Reflected
    Cold Start Load time, initialization peak memory First-use experience
    Input Processing Prefill time, input throughput Long input processing capability
    First Token Output Time to first token (TTFT) Interactive waiting perception
    Continuous Generation Output throughput, inter-token latency Generation fluency
    Long-term Operation Temperature, power consumption, performance fluctuation Continuous service stability

    Edge devices particularly require continuous runtime testing. Short-term results may benefit from higher transient power, while actual use will be affected by temperature rise and frequency adjustments.

    Step 5: Acceptance via Business Tasks

    General capability tests cannot replace business tests. Knowledge Q&A should check evidence consistency and refusal-to-answer performance; information extraction should check field accuracy and format validity; document analysis should check long-distance information integration; multimodal tasks should check detail recognition and error description.

    Test reports should specify device conditions, model precision, input length, output limits, concurrency, and repetition counts, and report latency distributions rather than just showing a single best result.

    8. How to Form Reliable Deployment Conclusions

    The final conclusion should not be a vague “good performance” or “runs fast,” but should clearly state the applicable conditions.

    Personal offline applications may focus more on peak memory, battery life, and privacy; enterprise knowledge applications focus more on answer reliability, access control, and concurrency stability; image-text interactive applications need to control both preprocessing and generation latency.

    Furthermore, public weights do not automatically mean that all commercial uses are unrestricted. Before formal use, the scope of license, redistribution requirements, and data processing boundaries for inputs and outputs should also be verified.

    The key to evaluating open-source LLMs is translating architectural mechanisms into verifiable engineering results: whether layer-wise embeddings are correctly fused, whether cache sharing genuinely reduces memory footprint, whether hybrid attention is effectively executed, and whether the multimodal pipeline is fully aligned. Only after correctness, quality, resource cost, and stability have all been verified can one determine if a model is suitable for specific devices and business needs, rather than stopping at parameter sheets and demo effects.