DAG Multi-Agent Orchestration and Native Multimodal Visual Encoding in Practice
This article examines native multimodal model design and DAG-based multi-agent orchestration. It compares late visual adaptation with native multimodal pretraining, describes a three-layer unified architecture, and discusses native-resolution visual encoding with patchification and sequence packing. It also covers shared image-video encoding, token budgets, and a DAG scheduler with dependency resolution, concurrency control, timeouts, retries, compensation, and result aggregation.
1. Why Native Multimodality Is Needed
Common multimodal large models use a “late visual adaptation” construction approach: first train a text-only language model, then attach a visual encoder and align the two modalities with a small amount of image-text data. This route has low cost and a short cycle, but it has two inherent problems.
First, language capability and visual capability compete for capacity at the parameter level. Late in training, text performance may decline, and visual understanding may remain superficial. For example, the model can recognize objects but cannot read quantitative relationships in a chart.
Second, alignment between visual features and language representations occurs only in the projection layer. It is difficult for the model to form a unified semantic representation in deep layers, and image-text reasoning may show the two kinds of information acting independently.
The native multimodal idea is to let text data and visual data participate jointly in optimization during pretraining, so that the two modalities reinforce each other within the same parameter space. The cost is more complex training, requiring more refined data ratios and training scheduling. The benefit is more consistent performance on image-text reasoning, chart understanding, video question answering, and similar tasks.
The following table summarizes the main differences between the two routes:
| Dimension | Late visual adaptation | Native multimodality |
|---|---|---|
| Training cost | Low; mainly trains the projection layer and limited fine-tuning | High; requires large-scale joint image-text pretraining |
| Data mixture | Text-dominant; small image-text volume | Needs fine-grained mixture by modality, task, and resolution |
| Capability risk | Text capability may degrade; visual understanding may remain shallow | Training scheduling is harder; debugging cost is high |
| Applicable boundary | Limited resources; only basic image-text QA | Deep image-text reasoning, document understanding, video analysis |
Whether to choose native multimodality depends on training resources, target tasks, and acceptable risk. If the goal is only to add simple image question answering to a text model, late visual adaptation is usually more cost-effective.
2. Three-Layer Structure of a Unified Multimodal Architecture
A typical unified multimodal model can be divided into three modules:
- Visual encoder: converts images or video frames into a set of visual feature vectors.
- Cross-modal projection layer: usually a small MLP that maps visual features into the embedding space of the language model.
- Language backbone: receives a unified sequence composed of visual tokens and text tokens and performs end-to-end modeling.
The data flow among the three modules can be represented by the following pseudocode:
# Illustration: construction flow for a unified sequencevisual_feats = vision_encoder(image_or_video) # [N_v, D_v]visual_tokens = projector(visual_feats) # [N_v, D_lm]text_tokens = tokenizer.encode(prompt) # [N_t, D_lm]sequence = concat(visual_tokens, text_tokens) # [N_v + N_t, D_lm]output = language_backbone(sequence)
The key to this design is that visual tokens and text tokens enter the same attention mechanism. The model can therefore make a text instruction attend to specific regions in an image at any layer, and visual content can also be constrained by the language context.
When constructing a unified sequence, several boundary conditions need to be determined in advance:
- Visual token upper limit. The number of tokens that each image or video segment can occupy must have an upper limit; otherwise, a single sample may fill the entire context window.
- Truncation strategy. When the limit is exceeded, should resolution be reduced, frame count be decreased, or an error be reported directly? This must be specified uniformly in the data pipeline.
- Image-text order. Whether images come before or after text affects how the model follows instructions. Training and inference should keep this order consistent.
- Attention masks. When multiple images are packed into the same sequence, the mask must ensure that different samples are invisible to each other.
- Memory impact. As sequence length increases, attention computation and memory overhead both rise, usually approaching quadratic growth.
At the training level, engineering practice often adopts a decoupled strategy: first train the representation capability of the visual encoder separately, then let it participate in joint training with frozen parameters or a low learning rate, and finally perform unified instruction fine-tuning. Decoupling reduces instability in each stage and makes it easier to troubleshoot problems in a single module.
3. Native-Resolution Visual Encoding
3.1 Information Loss from Fixed Cropping
Many visual models require input at a fixed size, such as 224×224. During preprocessing, long images are cropped and lose edge content, while wide images are resized and cause text and details to deform. For images with high information density, such as documents, tables, and UI screenshots, this loss is especially noticeable.
Take a table screenshot with a large height-to-width ratio as an example. If it is compressed into a square input, small cell text may become unrecognizable. Even if the language backbone is strong, it cannot recover the lost information from visual features. The specific affected resolution and crop ratio should be determined by measuring your own data; do not directly apply empirical values.
3.2 Patchification and Sequence Packing
A common approach to native-resolution encoding is to split an image into fixed-size patches, flatten the patches into a one-dimensional sequence, and then pass the sequence to a Transformer. The following code can be run directly, provided that numpy is installed:
import numpy as npdef patchify(image, patch_size=14):"""Split an [h, w, c] image into a patch sequence [N, p, p, c]."""h, w, c = image.shapeassert h % patch_size == 0 and w % patch_size == 0, \"h and w must be multiples of patch_size; align dimensions first"gh, gw = h // patch_size, w // patch_sizepatches = image.reshape(gh, patch_size, gw, patch_size, c)patches = patches.transpose(0, 2, 1, 3, 4) # [gh, gw, p, p, c]patches = patches.reshape(gh * gw, patch_size, patch_size, c) # [N, p, p, c]return patchesimg = np.random.rand(224, 448, 3)seq = patchify(img, patch_size=14)print(seq.shape) # (512, 14, 14, 3)flat = seq.reshape(seq.shape[0], -1) # flatten to [N, p*p*c], one vector per patchprint(flat.shape) # (512, 588)
The key here is to align dimensions to integer multiples of the patch size before splitting. Alignment can be done by resizing to the nearest valid size or by padding at the edges. Both approaches change the pixel distribution of the original image and should be compared with cropping during evaluation.
Patch sequences from different images can be packed into the same batch, with attention masks distinguishing their boundaries, thereby avoiding uniform resizing just for batching. The following example shows how to construct a block-diagonal mask:
import numpy as npdef pack_sequences(seqs, max_tokens):"""seqs: several [N_i, D] arrays. Return packed sequence, block-diagonal mask, and segment bounds."""total = sum(len(s) for s in seqs)assert total <= max_tokens, f"total token count {total} exceeds budget {max_tokens}"packed = np.concatenate(seqs, axis=0)seg_ids = np.concatenate([np.full(len(s), i) for i, s in enumerate(seqs)])mask = seg_ids[:, None] == seg_ids[None, :] # visible within the same sample, invisible across samplesbounds = np.cumsum([0] + [len(s) for s in seqs])return packed, mask, boundsa = np.random.rand(4, 8)b = np.random.rand(6, 8)packed, mask, bounds = pack_sequences([a, b], max_tokens=32)print(packed.shape, mask.shape, bounds) # (10, 8) (10, 10) [ 0 4 10]
If the language backbone uses causal attention, the mask must be intersected with a lower-triangular matrix. Practical frameworks usually provide variable-length sequence interfaces, such as splitting attention by a cumulative length array. In engineering, prefer native framework capabilities rather than implementing masks yourself.
3.3 Common Errors and Handling
In practice, the following situations are most likely to cause problems:
- Height and width are not integer multiples of the patch size. Direct splitting discards trailing pixels or reports a shape error. Align dimensions uniformly in the preprocessing stage and log the dimensions before and after alignment.
- Extremely long images. When the aspect ratio is too large, the number of patches increases sharply. Set a maximum side length or maximum patch count, and scale down proportionally when exceeded.
- Too many video frames. Frame count directly determines the number of visual tokens and must be controlled during sampling, as discussed in the next section.
- Large differences in sequence length within a batch. Samples with very different lengths packed together cause substantial padding and memory waste. It is recommended to bucket by length before packing.
4. Shared Encoding for Images and Video
Images and video can share the same visual encoder inside the model. An image can be regarded as a video with only one frame, so training data can complement each other, and the model can more easily learn general visual representations.
Video processing usually includes three steps.
The first step is frame sampling. A common approach is to sample uniformly by a fixed frame rate or a fixed number of frames. The fixed-frame-count approach makes it easier to control the token budget, but short videos may repeat frames and long videos may lose key actions. Frame-rate sampling preserves duration information more completely, but the cost is that the number of tokens for long videos is uncontrollable.
The second step is temporal positional encoding. The patches of each frame need to carry both spatial position and temporal position. One approach is to encode space and time separately and then add them; another is to treat time as an independent dimension for attention. In either case, the model should be able to distinguish both the positional relationships of patches within the same frame and the temporal order between different frames.
The third step is the token budget. Assuming each frame produces a fixed number of patches, the total number of video tokens equals the frame count multiplied by the number of patches per frame. This number must be planned together with the context window of the language backbone. A common approach is to set a frame cap and trade off resolution against frame count within the cap: fewer frames at high resolution, more frames at low resolution.
This tradeoff has no universal optimum. Document understanding tasks rely more on resolution, while action recognition tasks rely more on frame count. When evaluating a solution, test by task type separately rather than looking only at a single aggregate metric.
5. DAG-Based Parallel Multi-Agent Orchestration
When a task requires multiple agents to collaborate—for example, one agent reads documents, another parses charts, and a third summarizes conclusions—there are often dependencies among these steps. Steps with dependencies must run in order, while steps without dependencies can run in parallel. A directed acyclic graph (DAG) describes exactly this structure.
In this model, each node is an agent call or a piece of processing logic, and each directed edge indicates that a downstream node depends on the output of an upstream node. The orchestrator needs to perform the following work.
Dependency resolution. The orchestrator computes a topological order based on the edge relationships and confirms which nodes are ready to execute. If the graph contains a cycle, it should report an error before startup rather than getting stuck halfway through execution.
Concurrency control. Ready nodes can execute in parallel, but the concurrency level should have an upper limit. The limit depends on model service throughput, rate limits, and GPU memory; it cannot be scaled without bound.
Timeouts and retries. Each node should have a timeout. After a timeout or failure, it can be retried a limited number of times; once the limit is exceeded, it is marked as failed.
Rollback and compensation. If a node produces external side effects, such as writing to a database or sending a message, compensation operations need to be performed after failure. Compensation should proceed in reverse topological order to ensure that completed side effects are correctly undone. Read-only nodes usually do not need compensation.
Result aggregation. Results from all terminal nodes need to be aggregated into the final output. Before aggregation, check whether any upstream node failed to avoid returning incomplete results as a complete conclusion.
The following code provides a runnable scheduling skeleton that relies on graphlib from the standard library:
import asynciofrom graphlib import TopologicalSorterasync def run_dag(nodes, deps, max_concurrency=4, timeout=60):"""nodes: {name: async function(results) -> result}deps: {name: set of upstream node names}Returns (results, failed)."""sorter = TopologicalSorter(deps)sorter.prepare() # raises CycleError if the graph has a cyclesem = asyncio.Semaphore(max_concurrency)results, failed = {}, set()async def run_node(name):if deps.get(name, set()) & failed:failed.add(name) # upstream failed, skip this nodereturn nameasync with sem:try:results[name] = await asyncio.wait_for(nodes[name](results), timeout)except Exception:failed.add(name)return namepending = set()while sorter.is_active():for name in sorter.get_ready():pending.add(asyncio.create_task(run_node(name)))done, pending = await asyncio.wait(pending, return_when=asyncio.FIRST_COMPLETED)for t in done:sorter.done(t.result())return results, failedasync def read_doc(results):await asyncio.sleep(0.1)return "document summary"async def parse_chart(results):await asyncio.sleep(0.2)return "chart data"async def summarize(results):return f"{results['read']} + {results['chart']}"nodes = {"read": read_doc, "chart": parse_chart, "sum": summarize}deps = {"read": set(), "chart": set(), "sum": {"read", "chart"}}out, bad = asyncio.run
