Architecture Design and Implementation of On-Device Multimodal Large Models

    This article explores the architecture design and practical implementation of on-device multimodal large models. It examines the trade-offs between latency, privacy, and cost against strict hardware constraints, as well as the selection logic for model specifications (Dense, MoE, and small edge models). Furthermore, it details the unified processing of multimodal inputs, handling long contexts with positional encoding, and layer-wise conditional embedding for efficient information injection. The article concludes with deployment best practices, including memory estimation, agent task validation, and evaluation methodologies.

    1. Why On-Device Multimodal Models Matter

    Over the past two years, discussions around large models have primarily focused on cloud-side parameter scales and benchmark scores. As we move into the application phase, more teams are paying attention to another route: running models directly on smartphones, embedded devices, and small workstations. There are three main driving forces behind this route.

    First is latency. Scenarios like voice assistants, UI operations, and on-site quality inspection are sensitive to response time. A single network round-trip can easily exceed the user’s acceptable wait time.

    Second is privacy and compliance. Processing images, audio recordings, and screen content locally reduces the risk of data breaches associated with uploading raw data.

    Third is cost. When call volumes are high, token-based cloud inference costs can escalate rapidly. Local inference has a lower marginal cost, though it requires an upfront investment in hardware procurement and maintenance.

    The constraints of on-device devices are also clear: memory capacity, memory bandwidth, power consumption, and thermal limits are significantly tighter than in data centers. Therefore, architecture design usually requires balancing capability, size, and speed, rather than pursuing a single metric.

    2. Model Specification Selection Logic

    The same generation of models typically offers multiple specifications. When selecting a model, you can start by evaluating the following three structural types.

    1. Dense Models: Activates all parameters during every forward pass. The structure is simple, inference behavior is stable, and it is suitable as a quality baseline. The computational load is proportional to the parameter count, meaning larger scales result in higher latency and energy consumption per inference.
    2. Mixture of Experts (MoE): The model contains multiple expert sub-networks, and a router selects a few experts for each token to participate in the computation. The total parameter count can be very large, while the actually activated parameters per token are few, offering the potential for higher capacity under similar compute power. However, memory usage is still calculated based on total parameters, so sufficient memory must be reserved during deployment, and load balancing among experts should be monitored.
    3. Small Parameter Edge Models: These models have a smaller parameter scale and rely primarily on structural optimization and training data quality to ensure usability, making them suitable for smartphones and embedded devices. These models are typically weaker than large models in complex reasoning, so their task scope should be limited to simple, well-defined scenarios.

    For practical selection, you can refer to the following decision table:

    Constraint Condition Recommended Direction
    Mobile devices with limited memory, requiring offline operation Small parameter edge model, deployed with quantization
    Workstation-level GPU, requiring strong complex reasoning capabilities Dense model or large-scale MoE model
    High request volume, sensitive to per-inference cost MoE model, with evaluation of routing load balancing

    The selection logic can be solidified into a function to facilitate reuse across different device configurations:

    1. def choose_variant(device_mem_gb, offline_required, latency_budget_ms):
    2. if device_mem_gb < 8 or offline_required:
    3. return "small_edge" # Small parameter edge model
    4. if latency_budget_ms < 500:
    5. return "moe_medium" # MoE, balancing throughput and quality
    6. return "dense_large" # Dense large model, quality first

    The thresholds above are for illustration only; actual values should be determined by benchmark testing on target devices.

    3. Unified Processing of Multimodal Inputs

    The core of unifying multimodal inputs is mapping different modalities into the same token sequence, allowing a single attention mechanism to process all information. Mainstream approaches include: text is tokenized and mapped to vocabulary indices; images are split into patches by a vision encoder and then projected into the model’s hidden dimension; audio is converted into spectral features and output as a sequence by an audio encoder; and video is sampled by frames over time, encoding either frame-by-frame or by segments.

    3.1 Image and Variable Resolution

    Fixed resolutions cause two types of waste. Small images are over-scaled, increasing computation without adding new information; large images are forcibly compressed, resulting in detail loss. Variable resolution schemes determine the number of patches based on the actual size of the image, with the number of visual tokens growing approximately proportionally to the pixel area.

    Given an image size of H×W and a patch side length of p, the number of visual tokens is approximately (H/p)×(W/p). For example, a 448×448 image with a patch side length of 14 yields 32×32=1024 tokens. In engineering, a maximum token budget should be set for each image to balance recognition accuracy and inference latency.

    3.2 Temporal Sampling of Video

    Video is essentially an image sequence with a time dimension. Common sampling strategies include uniform frame extraction, keyframe detection, and temporal downsampling. More frames yield more complete temporal information, but token consumption and memory usage grow linearly with the number of frames. In practice, a frame rate upper limit is usually set first, and then the sampling density is increased if the task relies on fine-grained motion changes.

    3.3 Audio: Cascaded Pipeline vs. End-to-End Input

    Traditional voice interactions typically use a cascaded structure: an independent speech recognition module transcribes the audio first, and the text is then passed to the language model. This structure offers clear modules for individual debugging but suffers from error propagation. Recognition errors directly enter subsequent reasoning, and information like intonation, pauses, and ambient sounds is lost during transcription.

    End-to-end audio input allows the model to directly receive audio encodings, saving a model call and a segment of transcription latency, while preserving more acoustic features. The trade-off is that the model must handle more perception tasks, requiring more edge computing power, and the length of a single audio segment usually has an upper limit, requiring chunking for long recordings.

    A comparison of the two approaches is as follows:

    Dimension Cascaded Pipeline End-to-End Audio Input
    Number of modules Multiple models, numerous interfaces Single model
    Latency Serial accumulation across stages Eliminates one intermediate step
    Information retention Loses prosody and other info post-transcription Preserves more acoustic features
    Long audio Can be processed after sentence segmentation Often limited by single input length

    The chunking logic for extra-long audio can be implemented as follows:

    1. def split_audio(samples, sample_rate, max_seconds=30):
    2. chunk = max_seconds * sample_rate
    3. return [samples[i:i + chunk] for i in range(0, len(samples), chunk)]

    During actual splitting, try to break at silent points to avoid splitting a single word across two segments.

    4. Long Context and Positional Encoding

    4.1 Basic Principles of Rotary Position Embedding (RoPE)

    Rotary Position Embedding (RoPE) injects positional information by rotating vectors. For a vector of dimension d, adjacent dimensions are paired, and the rotation angle of the i-th group at position m is m·θᵢ, where θᵢ = base^(−2i/d).

    Its core property is that the inner product of the rotated query and key vectors depends only on their relative position m−n, not on absolute positions. This allows the model to utilize relative distance relationships, which is why it is widely adopted.

    4.2 Two Challenges of Long Context

    First, positions during inference may exceed the range seen during training. The rotation angles fall into intervals the model hasn’t learned, causing attention distributions to easily distort.

    Second, the computational and memory overhead of global attention grows quadratically with the sequence length. Expanding a sequence from 4K to 32K increases the attention matrix size by about 64 times.

    4.3 Hierarchical Attention and Differentiated Positional Encoding

    A common approach is to mix two types of attention layers. In sliding window layers, each token only attends to the most recent W tokens, making the computational load linearly related to the sequence length. Global attention layers can see the entire history and are responsible for capturing long-range dependencies.

    The two types of layers can employ different positional encoding configurations. Sliding window layers can use standard rotary encoding, as relative distances within the window always stay within the training range. Global layers can use a variant that scales the position index proportionally, replacing position m with m/s, where s is the scaling factor. This maintains a stable distribution of rotation angles over longer sequences.

    The following schematic code illustrates the difference between the two angle calculation methods:

    1. import math
    2. def rope_angles(pos, dim, base=10000.0, scale=1.0):
    3. # When scale > 1, the position index is proportionally compressed for global attention layers
    4. angles = []
    5. for i in range(dim // 2):
    6. theta = base ** (-2 * i / dim)
    7. angles.append((pos / scale) * theta)
    8. return angles
    9. def apply_rope(vec, pos, base=10000.0, scale=1.0):
    10. out = [0.0] * len(vec)
    11. for i, a in enumerate(rope_angles(pos, len(vec), base, scale)):
    12. x0, x1 = vec[2 * i], vec[2 * i + 1]
    13. out[2 * i] = x0 * math.cos(a) - x1 * math.sin(a)
    14. out[2 * i + 1] = x0 * math.sin(a) + x1 * math.cos(a)
    15. return out

    This code is only for illustrating the calculation logic; production environments should use optimized low-level operators.

    4.4 Nominal Window Does Not Equal Effective Capability

    The context length declared by a model is a structural limit, not a guarantee of actual performance. Validation should use tasks like long-document retrieval, cross-paragraph QA, and long multi-turn conversations. Information in the middle positions is easily overlooked, so test samples should be specifically designed to place “key information in the middle” to observe whether the model can consistently retrieve it.

    5. Layer-wise Conditional Embedding: Injecting Information on Demand

    5.1 Information Bottleneck of Standard Transformers

    A standard Transformer assigns an embedding vector to each token at the input. This vector must carry semantic meaning, grammatical roles, and contextual clues through all subsequent layers, updating incrementally via residual connections. The more information packed at the input, the greater the pressure on the vector. However, what deep computation actually needs is often information relevant to the current context, which may not match the content packed at the very beginning.

    5.2 Design Approach

    Layer-wise conditional embedding adds a parallel low-dimensional pathway alongside the main computation path. For each token, it generates a specific small vector for each layer. This vector consists of two parts: one is a token identity signal obtained via low-dimensional lookup; the other is a context-aware signal obtained by linearly projecting the initial embedding. After combination, it is injected into the hidden state at the corresponding layer in an additive manner.

    Expressed in formulas:

    • Conditional vector for the t-th token at the l-th layer: c_{t,l} = E_l[x_t] + P_l(h_t^{(0)})
    • Injected into the hidden state: ht^{(l)} ← h_t^{(l)} + U_l(c{t,l})

    Where x_t is the token’s vocabulary index, E_l is the low-dimensional lookup for the l-th layer, h_t^{(0)} is the initial embedding, and P_l and U_l are linear projections. Through this method, each layer only retrieves token information relevant to itself when needed, rather than receiving all information at the input at once.

    5.3 Engineering Value

    This design offers several practical benefits.

    • The lookup part has a large parameter volume, but only a small number of vectors are read each time. Thus, it can be considered for placement in slower-access storage and read on demand. Specific feasibility depends on the inference framework’s implementation.
    • The pathway dimension is low, and the added computation per layer is minimal, having a limited impact on edge computing power.
    • Information is allocated by layer, allowing deep layers to acquire signals that better match the current computation, helping to maintain expressive power at a smaller parameter scale.

    The schematic code below only illustrates the forward process:

    1. def forward_with_layer_injection(tokens, layers, token_tables, proj_in, proj_outs, h):
    2. ctx = proj_in(h) # Context-aware signal derived from initial embedding
    3. for l, layer in enumerate(layers):
    4. ident = token_tables[l][tokens] # Token identity signal, low-dimensional lookup
    5. c = ident + ctx # Combine the two signals
    6. h = layer(h) # Main path computation
    7. h = h + proj_outs[l](c) # Inject conditional information at the l-th layer
    8. return h

    6. Deployment and Engineering Practices

    6.1 Quantization and Memory Estimation

    Inference memory usage primarily comes from model weights and the KV cache. The estimation formula for the KV cache is as follows:

    Memory (bytes) ≈ 2 × number of layers × number of KV heads × head dimension × sequence length × bytes per element

    The factor of 2 corresponds to the two caches for K and V. For example, with 32 layers, 8 KV heads, a head dimension of 128, a sequence length of 4096, and 2 bytes per element (FP16):

    2 × 32 × 8 × 128 × 4096 × 2 = 536,870,912 bytes (approx. 512 MiB)

    This is just the cache for a single sequence. As concurrent requests increase, the cache grows linearly with the number of requests, so long-context services must limit concurrency or set a cache ceiling.

    Weight quantization can significantly reduce model size. 4-bit quantized weights theoretically take about a quarter of FP16, but actual usage must also account for scaling factors, activations, and KV cache overhead. Output quality should be compared on an internal test set before and after quantization to avoid focusing solely on size benefits.

    6.2 Implementation Points for Agent Tasks

    When on-device models call tools, the stability of the output format is the first hurdle. It is recommended to constrain outputs with structured formats and perform strict validation before execution:

    1. def run_tool_call(raw_output, allowed_tools, dispatch, validate_args):
    2. call = parse_json(raw_output) # Reject directly if parsing fails; do not guess or repair
    3. name = call.get("name")
    4. if name not in allowed_tools:
    5. raise PermissionError("Tool not in whitelist")
    6. args = call.get("arguments", {})
    7. validate_args(name, args) # Check parameter types, value ranges, and required fields
    8. return dispatch(name, args)

    In addition, note the following points:

    • Small models are prone to accumulating errors in multi-step planning. Limit the maximum number of steps and make results traceable at key nodes.
    • Irreversible operations like deleting files, sending messages, or making payments should retain a manual confirmation step.
    • Tool whitelists should be designed based on the principle of least privilege to prevent the model from acquiring capabilities beyond the task’s needs.

    6.3 Evaluation Methods

    There is often a significant gap between public leaderboards and business scenarios. It is recommended to build an internal test set of 200 to 500 real samples, covering normal, boundary, and abnormal inputs. During evaluation, record time to first token (TTFT), tokens per second, peak memory, and error types. These metrics better reflect the on-device experience than a single score.

    7. Common Pitfalls

    1. Larger parameters are better suited for the edge. On-device usability is primarily determined by memory, power consumption, and latency. Parameter scale is only one factor.
    2. End-to-end audio input is always better than a cascaded pipeline. The pros and cons of both depend on audio quality, latency budget, and hardware conditions. They should be tested in the target scenario.
    3. The longer the context window, the better. Longer windows mean greater computational and memory overhead, and actual utilization may not increase proportionally. It should be measured jointly by task effectiveness and latency.
    4. Rankings on comparison charts are the final conclusion. Evaluation prompt templates, decoding parameters, and data versions all affect results. Before making a selection decision, try to reproduce key metrics and validate them in your own scenarios.

    8. Conclusion

    The design focus of on-device multimodal models is doing three things well under limited resources: unifying the input representations of different modalities, supporting long contexts with appropriate positional encoding, and reasonably allocating the information received by each layer. During selection, first clarify device, latency, and privacy constraints before deciding on model specifications. During implementation, use reproducible metrics to validate capabilities and set validation and privilege boundaries for tool calling.