Unified Vision Encoding and Parallel Orchestration for Multimodal Agents

    This article explains how unified multimodal architectures combine visual and language representations, preserve image details through native-resolution encoding, and share one encoder across images and video. It also covers staged multimodal training and DAG-based parallel orchestration for reducing agent latency, along with practical engineering considerations for deployment.

    1. Background: The Limitations of Adding Vision After Language Pretraining

    Many early multimodal systems followed a fixed pipeline: first train a text-only large language model, then attach a vision encoder to the model’s input, and finally use a relatively small amount of image-text data for alignment. Although this approach is straightforward to implement, it has two structural limitations.

    First, visual and language capabilities compete for training resources. Language data typically accounts for most of the training budget, leaving the vision branch to learn from less data and compute. As a result, improvements in one modality can come at the expense of the other.

    Second, the two modalities have limited interaction. Visual features are generated outside the language model, and the language model can access them only through a shallow projection layer. This makes it difficult to fully use visual details during reasoning.

    The core idea behind newer designs is early fusion: visual and textual inputs are optimized together from the pretraining stage, allowing both modalities to learn representations in a shared parameter space.

    2. Three Components of a Unified Multimodal Architecture

    A typical unified multimodal architecture consists of three components:

    1. Vision encoder: Splits images or video frames into small patches and produces a sequence of visual features.
    2. Projection layer: Usually an MLP that maps visual features into the language model’s embedding space, aligning their dimensions and distributions.
    3. Language backbone: A Transformer-based large language model that receives a mixed sequence of visual and text embeddings and applies unified self-attention modeling.

    The data flow can be summarized as visual feature extraction, cross-modal projection, and unified language-backbone modeling. Images and video first pass through the vision encoder and projection layer, then are concatenated with text tokens. The entire pipeline is trained end to end. At every layer, the model operates in a shared semantic space instead of combining modalities only at the output stage.

    If the language backbone uses a mixture-of-experts (MoE) architecture, each token activates only a subset of expert parameters. This helps control the computation required for each inference request as the total parameter count grows. However, it also introduces routing and load-balancing challenges. Auxiliary losses or capacity limits are commonly required during training.

    3. Native-Resolution Vision Encoding

    Traditional vision pipelines often resize or crop images to a fixed resolution, such as 224×224. This can remove small text, table lines, and distant objects, while also distorting the original aspect ratio.

    A native-resolution approach avoids fixed resizing. Instead, it divides an image of any size directly into patches and flattens all patches into a one-dimensional sequence. Following the patch-packing idea used in approaches such as NaViT, patches from images with different dimensions can be packed into the same batch, while positional encodings distinguish their spatial coordinates.

    The following simplified example splits an image into patches and uses padding instead of resizing:

    1. import numpy as np
    2. def patchify(img: np.ndarray, p: int = 14) -> np.ndarray:
    3. """Split an H×W×C image into (N, p*p*C) patches with zero padding."""
    4. h, w, c = img.shape
    5. ph, pw = (-h) % p, (-w) % p
    6. img = np.pad(img, ((0, ph), (0, pw), (0, 0)))
    7. H, W = img.shape[:2]
    8. x = img.reshape(H // p, p, W // p, p, c).transpose(0, 2, 1, 3, 4)
    9. return x.reshape(-1, p * p * c)
    10. tokens = patchify(np.random.rand(375, 812, 3))
    11. print(tokens.shape) # For example: (1560, 588)

    This approach provides several benefits:

    • It preserves original visual details, which is particularly useful for documents, charts, and UI screenshots.
    • Images with different aspect ratios do not need to be cropped to a common shape, reducing information loss.
    • Sequence length grows naturally with resolution, and batch-level packing can reduce padding overhead.

    The trade-off is that sequence lengths can vary significantly, while attention cost grows quadratically with the number of tokens. Common mitigations include setting a maximum token limit, processing very large images in tiles, and using more efficient attention implementations.

    4. Shared Encoding for Images and Video

    Video can be viewed as a sequence of images arranged along a temporal dimension. One common approach is to build a separate temporal module for video. However, this introduces additional parameters and makes it harder to transfer image capabilities directly to video understanding.

    An alternative is to group consecutive frames into spatiotemporal units. For example, with four frames, each frame is still divided into spatial patches. Patches from the same spatiotemporal unit are then packed into one sequence, allowing a shared encoder to model both spatial and temporal attention.

    1. def pack_clip(frames: list[np.ndarray], p: int = 14, t_group: int = 4):
    2. """Pack consecutive frames into spatiotemporal sequences with time indices."""
    3. assert len(frames) % t_group == 0
    4. clips = []
    5. for start in range(0, len(frames), t_group):
    6. group = frames[start:start + t_group]
    7. tokens, t_ids = [], []
    8. for t, frame in enumerate(group):
    9. patches = patchify(frame, p)
    10. tokens.append(patches)
    11. t_ids.append(np.full(len(patches), t))
    12. clips.append((np.concatenate(tokens), np.concatenate(t_ids)))
    13. return clips

    This design has several advantages:

    • Images and video share weights, allowing spatial knowledge learned during image pretraining to support video understanding directly.
    • Temporal information enters attention explicitly through time indices, allowing the model to distinguish content at the same spatial location across different frames.
    • There is no separate video branch to maintain, reducing deployment and maintenance complexity.

    The main consideration is sequence length. More frames produce longer sequences. In practice, the sampling rate is selected according to the task, while long videos are handled with keyframe extraction or segmented processing.

    5. Training Pipeline: Decoupling Visual and Language Optimization

    The vision encoder and language backbone generally learn at different speeds and from different data distributions. If both are randomly initialized and updated at the same time, training can become unstable.

    A more reliable approach is to train in stages:

    1. Vision pretraining: Train the encoder on large-scale image-text and video data. Objectives can include image-text alignment and temporal consistency in video.
    2. Alignment: Freeze the encoder or update it with a low learning rate, while training the projection layer so that visual features enter the language representation space.
    3. Joint training: Unfreeze all parameters and perform end-to-end training with a relatively small learning rate. Retain a certain proportion of pure text data to prevent language capability degradation.

    To assess training health, monitor three categories of metrics together: changes in text-only benchmarks, accuracy on visual tasks, and gradient norms for each modality. If one modality consistently has much smaller gradients than the other, the data mixture or learning rates may require adjustment.

    6. Parallel Orchestration for Lower Agent Latency

    Complex agent workflows often follow a loop of planning, tool calls, result processing, and replanning. If every subtask runs sequentially, total latency is approximately the sum of the latency of all steps.

    In practical workloads, many subtasks are independent. For example, an agent may retrieve several web pages, analyze multiple files, or run several test groups at the same time. By representing the workflow as a directed acyclic graph (DAG) and grouping tasks by dependency level, sequential waiting can be replaced with parallel execution.

    Theoretical latency can be estimated as follows:

    • Sequential execution: The sum of the execution time of all subtasks.
    • Layered parallel execution: The sum of the slowest subtask in each dependency layer.

    The more tasks a layer contains, and the closer their execution times are, the greater the potential benefit from parallelism. If the dependency graph is deep and tasks cannot be decomposed effectively, the benefit decreases. The orchestrator should therefore analyze task structure before deciding whether to parallelize.

    The following example executes tasks layer by layer:

    1. import asyncio
    2. from dataclasses import dataclass
    3. @dataclass
    4. class Task:
    5. name: str
    6. deps: list[str]
    7. async def execute(plan: list[list[Task]], run_subtask):
    8. """Run independent tasks concurrently within each dependency layer."""
    9. results: dict[str, object] = {}
    10. for layer in plan:
    11. outputs = await asyncio.gather(
    12. *(run_subtask(task, results) for task in layer)
    13. )
    14. for task, out in zip(layer, outputs):
    15. results[task.name] = out
    16. return results

    Production systems also need to address the following considerations:

    • Limit concurrency to prevent a sudden burst of requests from overwhelming downstream services. A semaphore can be used to enforce a maximum concurrency level.
    • Give every subtask timeout and retry policies so that one blocked task does not stall the entire plan.
    • Store subtask results in a structured format so that later steps can reference and audit them easily.
    • Handle shared-state issues introduced by parallel execution through immutable inputs or locking.

    7. Engineering Checklist

    Before integrating unified multimodal capabilities into a production system, verify the following areas:

    • Input specifications: Define supported image formats, maximum resolution, video duration, and frame-rate limits. Validate inputs at the entry point.
    • Resource budget: Estimate memory usage and latency from the maximum token count, and define fallback strategies for long sequences.
    • Quality evaluation: In addition to general benchmarks, evaluate real business samples, with particular attention to small-text recognition, table extraction, and temporal reasoning.
    • Security and privacy: Review uploaded images and videos for safety issues, and retain data according to data-minimization principles.
    • Observability: Record subtask latency, failure rates, and retry counts to help identify bottlenecks.

    8. Conclusion

    The value of a unified multimodal architecture lies in allowing vision and language to share representations from the training stage, reducing conflicts caused by late-stage modality fusion. Native-resolution encoding preserves visual details, while shared image-and-video encoding makes capability transfer more direct.

    At the agent layer, dependency analysis and layered parallel execution can significantly reduce workflow latency. Combined, these techniques can improve both understanding accuracy and response speed, although their actual impact must still be validated against task-specific data.