Choosing Native Multimodal MoE: Principles, Measurement, and Deployment
This article explores the selection principles, performance measurement, and deployment of native multimodal Mixture of Experts (MoE) models. It compares MoE with dense architectures and native multimodal approaches with cascaded solutions, highlighting their respective trade-offs. Furthermore, it provides practical guidelines for measuring Time to First Token (TTFT) and concurrent throughput, including runnable Python scripts for benchmarking and multimodal API calls. Finally, it outlines essential cloud-native monitoring metrics to ensure that theoretical performance gains translate effectively into production environments.
1. What Does MoE Save?
Large model capabilities typically grow with the number of parameters, and inference costs rise accordingly. Dense models use all parameters when processing each token, meaning compute consumption is basically proportional to the parameter scale. The Mixture of Experts (MoE) architecture takes a different approach: the model contains numerous expert subnetworks, and each token only passes through a small subset of experts selected by a router.
Let’s illustrate the calculation with a set of hypothetical numbers. Suppose a model has a total of about 320 billion parameters and activates about 18 billion parameters per inference. The activated parameter ratio per token is 180/3200, or about 5.6%. These numbers are purely arithmetic examples and do not represent any specific model. For actual configurations, please refer to the model’s official technical report.
The differences between the two architectures are as follows:
| Dimension | Dense Model | MoE Model |
|---|---|---|
| Parameters involved in computation per token | All parameters | k routed experts, plus dense layers |
| Knowledge capacity | Bound to computation | Carried by all parameters |
| Inter-GPU communication | Mainly tensor parallelism | Adds All-to-All communication from expert parallelism |
| Memory footprint | Proportional to parameter count | Needs to accommodate all expert weights; memory may not decrease |
| Batch size sensitivity | Relatively stable | Low utilization when a single expert processes few tokens in small batches |
To understand the boundaries of MoE, note the following:
- Parameter count is not equivalent to computation. Attention layers, word embeddings, and output layers are usually dense computations, and their overhead is not reduced by expert sparsity.
- Expert parallelism introduces communication overhead. When experts are distributed across multiple GPUs, tokens must be sent and received between cards. Network bandwidth and latency will directly impact end-to-end latency.
- Routing may be imbalanced. When a large number of tokens concentrate on a few popular experts, these experts become bottlenecks while others remain idle. On the inference side, you should monitor expert load entropy, the ratio of maximum load to average load, and the proportion of tokens dropped due to capacity limits. Alerting thresholds need to be determined through testing on your own traffic.
- Batch size changes the returns. At small batch sizes, theoretical savings are hard to realize. At large batch sizes, most experts will be activated, the savings brought by sparsity will be diluted, and communication and scheduling overheads become more prominent.
The conclusion is: MoE reduces the theoretical computation per token. Whether Time To First Token (TTFT) and throughput actually improve depends on the real-world performance of communication, scheduling, memory, and batch size, which requires empirical testing.
2. Differences Between Native Multimodal and Cascaded Solutions
Native multimodal means that images and text are jointly trained in the same model backbone. Images are divided into visual tokens and enter the model together with text tokens. A cascaded solution involves first using an independent visual encoder to extract features, which are then connected to the language model via a projection layer; or, a visual model first generates a text description, which is then handed over to a text model for processing.
| Dimension | Native Multimodal | Cascaded Solution |
|---|---|---|
| Structure | Image and text tokens enter the same backbone for joint pre-training | Visual encoder plus projection layer connected to LLM, or two models in series |
| Cross-modal alignment | Learned during the training phase | Relies on projection layers or intermediate text descriptions; details easily lost |
| TTFT | Single call, but prefill is longer when there are many image tokens | Additional call when in series, causing latency stacking |
| Concurrent throughput | Depends on image token count and batch processing capability | Visual and text components can be scaled independently |
| Cost | Single model deployment; training costs are usually higher | Can reuse existing components; upgrades are more flexible |
| Applicable scenarios | Fine-grained visual reasoning such as charts, UIs, invoices | Primarily text-based; images only require simple descriptions or classification |
| Selection conclusion | Requires fine-grained visual reasoning and can afford deployment costs | Existing systems are primarily text-based and require quick integration |
When selecting an approach, first look at the visual detail required by the business. If high image detail is required, the text description of a cascaded solution will become an information bottleneck. Secondly, consider image resolution and quantity. The number of image tokens directly lengthens the prefill time, thereby affecting TTFT.
3. Measuring TTFT and Concurrent Throughput
TTFT refers to the time from sending a request to receiving the first piece of output. It is primarily determined by the prefill phase; the more image tokens, the longer this phase takes. Concurrent throughput has two metrics: request throughput refers to the number of successfully completed requests per second, and output rate refers to the amount of content output per second.
The calculation formulas are as follows:
- Request throughput (requests/second) = Successful requests / Total wall clock time
- Output rate (blocks/second) = Total output content blocks / Total wall clock time
In streaming interfaces, each content block usually corresponds to one or a few tokens. The script below uses the number of content blocks to approximate the number of tokens. If the server returns a precise usage field, that field should be prioritized.
The measurement checklist is as follows:
- Warmup. Send several requests before formal timing and discard the results to stabilize memory, cache, and compilation processes. The number of warmup requests can increase with concurrency; the script fixes it at 20.
- Sample size. The sample size for each concurrency level should ensure stable P95 and P99 results, generally no less than several hundred requests. If the sample is too small, P99 only reflects individual slow requests.
- Input distribution. Fix the image resolution and question length, or sample according to real traffic. Otherwise, different rounds are incomparable. The script defaults to sending short text, testing the pure text path. For multimodal scenarios, replace the message with content containing an image.
- Concurrency gradient. Gradually increase from 1, 2, 4, 8 to the target value, recording throughput and latency inflection points.
- Statistical caliber. Report P50, P95, P99, while recording the failure rate and timeout rate. Reporting only averages will mask long-tail problems.
- Configuration recording. Record the batch size, expert parallelism, tensor parallelism, model version, and inference framework version to ensure reproducibility. Do not let other tasks share the same service instance during measurement, or the results will interfere with each other.
The following script sends requests for each concurrency level and outputs the P50, P95, P99, success rate, request throughput, and output rate of the TTFT.
import mathimport osimport timefrom concurrent.futures import ThreadPoolExecutorfrom openai import OpenAIclient = OpenAI(base_url=os.environ["MODEL_BASE_URL"],api_key=os.environ["MODEL_API_KEY"],timeout=60.0,max_retries=0,)MODEL_NAME = os.environ["MODEL_NAME"]PROMPT = [{"role": "user", "content": "Introduce the Mixture of Experts model in two sentences."}]MAX_TOKENS = 64CONCURRENCY_LEVELS = [1, 2, 4, 8]REQUESTS_PER_LEVEL = 200WARMUP_REQUESTS = 20def percentile(values: list[float], p: float) -> float:"""Calculate percentile using the nearest rank method. Values cannot be empty."""ordered = sorted(values)rank = max(1, math.ceil(p / 100 * len(ordered)))return ordered[rank - 1]def one_request(messages: list) -> tuple[bool, float | None, float, int]:"""Send a streaming request, returning (is_successful, TTFT_seconds, total_time_seconds, content_block_count)."""start = time.perf_counter()ttft = Noneblocks = 0try:stream = client.chat.completions.create(model=MODEL_NAME,messages=messages,max_tokens=MAX_TOKENS,stream=True,)try:for chunk in stream:if chunk.choices and chunk.choices[0].delta.content:if ttft is None:ttft = time.perf_counter() - startblocks += 1finally:stream.close()except Exception:# Production environments should log exception types; here it's just counted as a failurereturn False, None, time.perf_counter() - start, 0total = time.perf_counter() - startreturn ttft is not None, ttft, total, blocksdef run_level(concurrency: int, total: int) -> dict:wall_start = time.perf_counter()with ThreadPoolExecutor(max_workers=concurrency) as pool:results = list(pool.map(one_request, [PROMPT] * total))wall = time.perf_counter() - wall_startok = [r for r in results if r[0]]ttfts = [r[1] for r in ok]blocks = sum(r[3] for r in ok)stats = {"success_rate": len(ok) / total,"rps": len(ok) / wall,"block_rate": blocks / wall,}for p in (50, 95, 99):stats[f"p{p}"] = percentile(ttfts, p) if ttfts else Nonereturn statsdef fmt_ms(seconds: float | None) -> str:return "-" if seconds is None else f"{seconds * 1000:.0f}ms"def main() -> None:for _ in range(WARMUP_REQUESTS):one_request(PROMPT)print(f"{'Conc':>4} {'Success':>8} {'P50':>8} {'P95':>8} {'P99':>8} "f"{'Req/s':>9} {'Blk/s':>9}")for c in CONCURRENCY_LEVELS:s = run_level(c, REQUESTS_PER_LEVEL)print(f"{c:>4} {s['success_rate']:>8.1%} {fmt_ms(s['p50']):>8} "f"{fmt_ms(s['p95']):>8} {fmt_ms(s['p99']):>8} "f"{s['rps']:>9.2f} {s['block_rate']:>9.1f}")if __name__ == "__main__":main()
Before running, set the environment variables and install dependencies:
pip install "openai>=1.40,<2"export MODEL_BASE_URL="https://your-endpoint/v1"export MODEL_API_KEY="your-key"export MODEL_NAME="your-multimodal-model"python bench_concurrency.py
The script requires Python 3.10 or higher. Before going live, please run it in your own environment first, then replace the example prompt with your actual traffic’s input distribution.
4. Runnable Multimodal API Call Code
The following script reads an image and asks a question. It scales the image so the longest side does not exceed 1024 pixels, converts it to JPEG, and sends it as a data URL to control the number of image tokens. Files exceeding 10 MB will be rejected directly. Upon encountering 429 and 5xx errors, the script retries up to 3 times with exponential backoff. It does not retry on 401, 403, or similar errors; you should check your keys and permissions first.
Dependencies and environment variables are the same as in Section 3. The script mm_qa.py is as follows:
import base64import ioimport osimport sysimport timefrom openai import APIConnectionError, APIStatusError, OpenAIfrom PIL import ImageBASE_URL = os.environ["MODEL_BASE_URL"]API_KEY = os.environ["MODEL_API_KEY"]MODEL_NAME = os.environ["MODEL_NAME"]MAX_SIDE = 1024 # Upper limit for the longest side of the image, controls image token countMAX_FILE_BYTES = 10 * 1024 * 1024MAX_RETRIES = 3RETRYABLE_STATUS = {429, 500, 502, 503, 504}client = OpenAI(base_url=BASE_URL, api_key=API_KEY, timeout=60.0, max_retries=0)def encode_image(path: str) -> str:"""Reads the image, scales it so the longest side does not exceed MAX_SIDE, and returns a data URL."""if os.path.getsize(path) > MAX_FILE_BYTES:raise ValueError(f"Image exceeds {MAX_FILE_BYTES // 1024 // 1024} MB limit: {path}")with Image.open(path) as img:img = img.convert("RGB")img.thumbnail((MAX_SIDE, MAX_SIDE))buf = io.BytesIO()img.save(buf, format="JPEG", quality=90)b64 = base64.b64encode(buf.getvalue()).decode("ascii")return f"data:image/jpeg;base64,{b64}"def ask(image_path: str, question: str) -> str:data_url = encode_image(image_path)messages = [{"role": "user","content": [{"type": "text", "text": question},{"type": "image_url", "image_url": {"url": data_url}},],}]for attempt in range(1, MAX_RETRIES + 1):try:resp = client.chat.completions.create(model=MODEL_NAME,messages=messages,max_tokens=512,)return resp.choices[0].message.content or ""except APIStatusError as e:if e.status_code not in RETRYABLE_STATUS or attempt == MAX_RETRIES:raiseexcept APIConnectionError:if attempt == MAX_RETRIES:raisetime.sleep(2 ** attempt)raise RuntimeError("Retries exhausted")if __name__ == "__main__":if len(sys.argv) != 3:print("Usage: python mm_qa.py <image_path> <question>", file=sys.stderr)sys.exit(1)try:print(ask(sys.argv[1], sys.argv[2]))except (OSError, ValueError, APIStatusError, APIConnectionError) as e:print(f"API call failed: {e}", file=sys.stderr)sys.exit(1)
Running example:
python mm_qa.py ./invoice.jpg "What is the issue date and amount on this invoice?"
This code only implements basic error handling. Production environments also need timeout alerts, request logging, and rate limiting.
Keys are only read through environment variables. Do not print environment variables, request headers, or complete request bodies, and do not log keys in logs. Executing the export command in a shared terminal will leave the key in the shell history. In production environments, environment variables should be injected by a secret management service.
5. Cloud-Native Deployment Monitoring Essentials
Whether theoretical gains can be realized must be confirmed by online metrics. During deployment, it is recommended to monitor the following categories of metrics:
- Latency: P50, P95, P99 for TTFT and time per output token, grouped by model version and input image token count.
- Queuing: Request queue time and current concurrency. A high proportion of queue time usually indicates the need for scaling or adjusting the batch size.
- Expert Load: Expert load entropy, ratio of maximum load to average load, and token drop rate, statistically broken down by layer.
- Communication: Proportion of inter-GPU All-to-All time in total time, and network bandwidth utilization.
- Memory: Memory usage after weight loading, KV cache usage, and OOM count.
- Errors: 429 and 5xx proportions, timeout rate.
Alerting thresholds should be based on your own traffic. Run a baseline for a period of time first, then set trigger conditions.
