Architectural Analysis and Inference Adaptation Practices for On-Device Multimodal Large Models

    Evaluating large models requires looking beyond parameter size, focusing on architectural, engineering, and user experience perspectives. This article explores how to establish a resource budget for inference, analyze mechanisms like layer-wise embedding and cross-layer KV cache sharing, and adapt multimodal data pipelines. It also provides a methodical approach to model export, deployment, and performance evaluation to ensure correct and efficient inference on edge and server devices.

    I. Evaluating Large Models Beyond Parameter Size

    When evaluating large models for mobile phones, personal computing devices, and servers, developers typically care about direct questions: Can it run? Is the response fast enough? Is there sufficient memory? Can the response quality meet business requirements?

    These questions cannot be answered by parameter count alone. Models of the same scale may adopt different attention structures, cache organizations, and multimodal encoding paths, leading to significantly different actual resource overheads. Even if the weights fit into memory, it does not guarantee stable operation for long contexts, multi-turn dialogues, or image inputs.

    Therefore, evaluating such models should be based on three interconnected perspectives:

    • Architectural Perspective: What mechanisms does the model use to reduce computation or storage costs, and what additional operators and dependencies does it introduce?
    • Engineering Perspective: Can the inference engine accurately express these mechanisms? Are there operator fallbacks, redundant computations, or unnecessary data movements?
    • Experience Perspective: Under real devices and business inputs, do the first-token latency, continuous generation speed, response quality, and stability meet the standards?

    This article does not review a specific model, nor does it treat unverified architectural descriptions as established facts. Instead, it discusses general adaptation and evaluation methods focusing on layer-wise embedding, KV cache sharing, and multimodal support.

    II. Establishing a Resource Budget Before Optimization

    The peak memory of large model inference can be approximately decomposed into:

    Total Memory ≈ Weight Memory + KV Cache + Intermediate Activations + Temporary Workspace + Runtime Overhead

    For multimodal systems, the weights of visual or audio encoders, input preprocessing buffers, and the space occupied by modality features should also be included. The peaks of these items do not necessarily occur simultaneously, so accurate results still require runtime sampling.

    Weight quantization primarily reduces weight memory and does not automatically solve all memory issues. With long contexts, the KV cache might become the main increment; when processing high-resolution images, intermediate features and temporary workspaces may also trigger transient peaks.

    Therefore, “model file size” can only serve as a preliminary screening criterion and cannot replace runtime resource measurement.

    1. Parameter Count is Not Equivalent to Computation Per Step

    Sparse expert structures typically only allow a subset of experts to participate in a single forward pass, meaning the total parameter count differs from the activated parameter count per step. However, experts not selected by the current input may still need to be kept in device memory or participate in subsequent computations through dynamic loading.

    This implies:

    • Computation costs may decrease, but weight storage requirements may not drop proportionally.
    • Expert switching may increase memory access and scheduling costs.
    • In multi-device deployments, data exchange overhead must be considered.
    • Single-request latency and batch throughput may exhibit different trends.

    Therefore, “fewer activated parameters” should not be directly interpreted as “low memory, low latency.”

    2. Hybrid Attention Requires Layer-by-Layer Analysis

    Some models alternate between local window attention and global attention. Local layers only attend to historical positions within a limited range, helping to control long-sequence overhead; global layers handle broader information integration.

    During adaptation, you need to verify the window range, mask semantics, and positional encoding layer by layer. Notably: adopting local attention does not mean the implementation will automatically release the cache outside the window. Only when the runtime genuinely supports the corresponding cache management strategy can theoretical savings translate into actual benefits.

    III. Layer-wise Embedding: Injecting Input Information Deeper

    1. Differences from Standard Input Embedding

    Conventional language models typically map tokens to vectors first, and then let these representations pass through attention and feed-forward networks layer by layer. Layer-wise embedding allows some or multiple network layers to obtain additional representations associated with input tokens.

    The general concept can be summarized as:

    Current Layer Output = Fusion of Intra-Layer Computation Results and Input-Related Representations for That Layer

    However, this description is merely a conceptual framework. Specific implementations may involve table lookups, projections, normalization, gating, or scaling. You cannot assume all models using layer-wise embedding follow the same formula.

    2. Where Engineering Costs Mainly Manifest

    Layer-wise embedding seems to merely add an information pathway, but it can affect:

    • Weight Layout: Layer-by-layer storage vs. centralized storage changes loading methods and access locality.
    • Lookup Granularity: The prefill stage allows batch lookups, while the token-by-token generation stage is more prone to small-granularity memory accesses.
    • Projection Computation: Additional projections may introduce operator launch overhead.
    • Quantization Strategy: The numerical distribution of embedding tables differs from standard linear weights, so the same quantization scheme should not be adopted without verification.
    • Graph Optimization: Incorrect fusion or constant folding may alter inter-layer data dependencies.

    If layer-wise embedding relies solely on input tokens and fixed weights, the feasibility of precomputation and reuse can be evaluated; if it also depends on the current layer’s hidden states, it cannot be treated as a static lookup path.

    3. How to Verify Implementation Correctness

    Verification should not stop at “eventually generating text.” A more robust method is staged comparison:

    1. Are the input embeddings consistent?
    2. Are the lookup results for additional embeddings in each layer consistent?
    3. Are the tensors after projection, normalization, and fusion consistent?
    4. Is the difference in the final output distribution within an acceptable range?

    When deviations occur, prioritize checking dimensional arrangement, scaling order, normalization positions, and quantization/de-quantization paths. Layer-by-layer localization is typically more effective than directly comparing the entire generated response.

    IV. Cross-Layer KV Cache Sharing: Saving Memory but Adding Constraints

    1. Why KV Cache Becomes a Bottleneck

    During autoregressive generation, models usually save keys and values from historical positions to avoid recomputing all historical information for every new token generated.

    Under simplified conditions where cache shapes are consistent across layers, the cache capacity can be approximated as:

    Cache Capacity ≈ 2 × Number of Layers × Batch Size × Sequence Length × Number of KV Heads × Head Dimension × Bytes per Element

    The coefficient 2 represents storing keys and values separately. If different layers use different windows, different numbers of heads, different precisions, or if sharing relationships exist, you must calculate and sum them layer by layer.

    2. Cross-Layer Sharing is Not Simple Memory Reuse

    Cross-layer cache sharing means that certain layers, by model design, use key-value representations produced by other layers. This is fundamentally different from “two tensors have non-overlapping lifetimes, so they can occupy the same memory block”:

    • Memory reuse changes storage arrangements.
    • Cross-layer sharing alters model computation dependencies.

    Therefore, it is not a universal optimization that can be arbitrarily added to existing models. If the model was not trained with the corresponding structure, forcing different layers to share caches will typically alter model behavior.

    3. Inference Engines Must Express Sharing Relationships

    Traditional cache managers often allocate space independently per layer. When supporting cross-layer sharing, it is more appropriate to introduce a “cache group” concept, where multiple consumers reference the same cache.

    Cache metadata should at least include:

    • The network layer or compute node that produces this cache.
    • The set of consumers using it.
    • Number of KV heads, head dimension, and data type.
    • Valid sequence length and position mapping.
    • Local window range.
    • Cache lifecycle and release conditions.

    If multi-layer caches are mechanically mapped to the same address without handling write order and lifecycles, issues like overwriting historical data or reading incomplete results can easily occur.

    4. Checking Shared Caches and Positional Encoding Together

    If different attention layers use different positional encoding parameters, rotation dimensions, or scaling methods, you cannot determine that caches can be shared solely based on identical tensor shapes.

    During adaptation, it must be clear whether the cache stores representations before or after positional transformation, and whether consumers need to perform additional transformations. In incremental decoding, position indices must remain consistent with the prefill stage; otherwise, short inputs may appear normal while long contexts gradually distort.

    V. Multimodal Support: The Complete Data Pipeline Beyond the Language Decoder

    Multimodal models do not simply add a file input next to text. They typically involve multiple stages: preprocessing, modality encoding, feature mapping, sequence concatenation, and language generation.

    1. Image Inputs Affect Sequence Organization First

    A typical image processing pipeline includes resizing or cropping, numerical normalization, visual feature extraction, and mapping features into a representation space acceptable to the language model.

    Key aspects to verify include:

    • Whether changes in image size cause changes in feature count.
    • Whether the order of multiple images is preserved.
    • Whether image placeholders match the number of features.
    • How text position numbering spans across visual features.
    • Whether high-resolution inputs introduce additional cropping or tiling.

    More visual features usually mean the subsequent language processing faces a longer effective input. Fast image encoding does not necessarily mean fast overall first-token latency.

    2. Audio Inputs Rely on Strict Temporal Semantics

    Audio processing often involves resampling, framing, feature extraction, and temporal encoding. Deviations in sample rate, frame shift, padding masks, or effective length handling can lead to significant degradation in recognition quality.

    Furthermore, supporting whole-segment audio input is not equivalent to supporting low-latency streaming input. Streaming capability also depends on chunking strategies, cross-chunk states, and whether the encoder uses future information. These two capabilities must be evaluated separately.

    3. Record Multimodal Performance by Stages

    The latency of a single request should be decomposed into at least:

    Input Preprocessing → Modality Encoding → Feature Mapping and Concatenation → Language Prefill → Token-by-Token Generation

    Only by measuring stage by stage can you determine whether the bottleneck comes from image processing, audio encoding, context length, or the language decoder itself.

    VI. From Export to Deployment: Correctness Before Efficiency

    1. Build an Architecture Checklist

    Before export, organize the attention type, number of KV heads, positional encoding configuration, sharing relationships, normalization positions for each layer, and the input/output conventions of modality branches.

    You cannot simply apply existing adaptation templates based solely on model name or size. Networks that look similar may have critical differences in a single scaling coefficient or the position of a normalization step.

    2. Start with an Unquantized Baseline

    It is recommended to proceed in the following order:

    1. Verify a single layer or module.
    2. Verify complete prefill.
    3. Verify single-step incremental decoding.
    4. Verify multi-step cache accumulation.
    5. Verify multimodal inputs.
    6. Finally, introduce quantization and operator fusion.

    This prevents mistaking architectural implementation errors for quantization errors.

    3. Compare Full and Incremental Inference

    Under the same context and position definitions, full computation and incremental computation using caches should remain consistent within a reasonable floating-point error range.

    If differences continue to expand, check:

    • Whether cache append positions are correct.
    • Whether the attention mask covers areas that should not be accessed.
    • Whether local window truncation is consistent.
    • Whether the shared cache is written to repeatedly.
    • Whether positional encoding uses the same rules in both paths.

    4. Establish Automated Regression Suites

    Regression tests should not only consist of fixed short sentences. They should also cover empty inputs, inputs near the length limit, multi-turn dialogues, different image sizes, different audio durations, request cancellations, and session resets.

    For dynamic shapes and shared caches, correctness issues are often more easily exposed under boundary conditions.

    VII. How to Draw Reliable User Experience Conclusions

    “Runs smoothly” lacks reproducibility. A complete evaluation should simultaneously report quality, latency, and resource usage.

    Dimension Recommended Observation Description
    Response First-token latency Distinguish between cold start and warm start
    Generation Continuous generation speed Fixed input and output length range
    Capacity Peak memory Cover long contexts and multimodal scenarios
    Stability Long-term continuous operation Observe temperature, throttling, and resource release
    Quality Task completion rate Establish evaluation criteria based on business tasks
    Consistency Pre- and post-quantization differences Evaluate both text and multimodal tasks

    During testing, fix hardware, power mode, thread configuration, inference precision, concurrency level, and generation parameters. After repeating experiments, report at least the median and high-percentile latencies, rather than just showcasing the optimal result.

    This article does not provide real-world measurements on specific devices, so no specific speed, memory saving ratios, or model quality rankings are derived.

    VIII. Deployment Selection: Focus on Business Constraints, Not Model Labels

    Mobile devices should prioritize peak memory, continuous power consumption, and thermal stability. Good performance in a single short request does not guarantee that continuous interactions can maintain the same speed.

    Personal computing devices can handle more complex local tasks, but it is necessary to prevent memory paging, frequent data movement, and cache bloat caused by long contexts.

    Server deployments focus more on concurrency, throughput, cache utilization, and tail latency. The configuration with the fastest single request may not have the best overall resource efficiency.

    Ultimately, a reasonable selection process should be:

    Define task quality baseline → Measure resource boundaries → Verify architectural correctness → Optimize actual bottlenecks → Re-test under target workloads.

    Layer-wise embedding, cross-layer cache sharing, and multimodal encoding provide new efficiency design spaces but also increase the implementation complexity of inference systems. A truly reliable evaluation is not about listing architectural buzzwords, but explaining how these mechanisms affect computation and storage, and using reproducible tests to verify whether they translate into actual benefits.