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:

    1. 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.
    2. 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.
    3. 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.
    4. 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:

    1. 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.
    2. 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.
    3. 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.
    4. Concurrency gradient. Gradually increase from 1, 2, 4, 8 to the target value, recording throughput and latency inflection points.
    5. Statistical caliber. Report P50, P95, P99, while recording the failure rate and timeout rate. Reporting only averages will mask long-tail problems.
    6. 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.

    1. import math
    2. import os
    3. import time
    4. from concurrent.futures import ThreadPoolExecutor
    5. from openai import OpenAI
    6. client = OpenAI(
    7. base_url=os.environ["MODEL_BASE_URL"],
    8. api_key=os.environ["MODEL_API_KEY"],
    9. timeout=60.0,
    10. max_retries=0,
    11. )
    12. MODEL_NAME = os.environ["MODEL_NAME"]
    13. PROMPT = [{"role": "user", "content": "Introduce the Mixture of Experts model in two sentences."}]
    14. MAX_TOKENS = 64
    15. CONCURRENCY_LEVELS = [1, 2, 4, 8]
    16. REQUESTS_PER_LEVEL = 200
    17. WARMUP_REQUESTS = 20
    18. def percentile(values: list[float], p: float) -> float:
    19. """Calculate percentile using the nearest rank method. Values cannot be empty."""
    20. ordered = sorted(values)
    21. rank = max(1, math.ceil(p / 100 * len(ordered)))
    22. return ordered[rank - 1]
    23. def one_request(messages: list) -> tuple[bool, float | None, float, int]:
    24. """Send a streaming request, returning (is_successful, TTFT_seconds, total_time_seconds, content_block_count)."""
    25. start = time.perf_counter()
    26. ttft = None
    27. blocks = 0
    28. try:
    29. stream = client.chat.completions.create(
    30. model=MODEL_NAME,
    31. messages=messages,
    32. max_tokens=MAX_TOKENS,
    33. stream=True,
    34. )
    35. try:
    36. for chunk in stream:
    37. if chunk.choices and chunk.choices[0].delta.content:
    38. if ttft is None:
    39. ttft = time.perf_counter() - start
    40. blocks += 1
    41. finally:
    42. stream.close()
    43. except Exception:
    44. # Production environments should log exception types; here it's just counted as a failure
    45. return False, None, time.perf_counter() - start, 0
    46. total = time.perf_counter() - start
    47. return ttft is not None, ttft, total, blocks
    48. def run_level(concurrency: int, total: int) -> dict:
    49. wall_start = time.perf_counter()
    50. with ThreadPoolExecutor(max_workers=concurrency) as pool:
    51. results = list(pool.map(one_request, [PROMPT] * total))
    52. wall = time.perf_counter() - wall_start
    53. ok = [r for r in results if r[0]]
    54. ttfts = [r[1] for r in ok]
    55. blocks = sum(r[3] for r in ok)
    56. stats = {
    57. "success_rate": len(ok) / total,
    58. "rps": len(ok) / wall,
    59. "block_rate": blocks / wall,
    60. }
    61. for p in (50, 95, 99):
    62. stats[f"p{p}"] = percentile(ttfts, p) if ttfts else None
    63. return stats
    64. def fmt_ms(seconds: float | None) -> str:
    65. return "-" if seconds is None else f"{seconds * 1000:.0f}ms"
    66. def main() -> None:
    67. for _ in range(WARMUP_REQUESTS):
    68. one_request(PROMPT)
    69. print(f"{'Conc':>4} {'Success':>8} {'P50':>8} {'P95':>8} {'P99':>8} "
    70. f"{'Req/s':>9} {'Blk/s':>9}")
    71. for c in CONCURRENCY_LEVELS:
    72. s = run_level(c, REQUESTS_PER_LEVEL)
    73. print(f"{c:>4} {s['success_rate']:>8.1%} {fmt_ms(s['p50']):>8} "
    74. f"{fmt_ms(s['p95']):>8} {fmt_ms(s['p99']):>8} "
    75. f"{s['rps']:>9.2f} {s['block_rate']:>9.1f}")
    76. if __name__ == "__main__":
    77. main()

    Before running, set the environment variables and install dependencies:

    1. pip install "openai>=1.40,<2"
    2. export MODEL_BASE_URL="https://your-endpoint/v1"
    3. export MODEL_API_KEY="your-key"
    4. export MODEL_NAME="your-multimodal-model"
    5. 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:

    1. import base64
    2. import io
    3. import os
    4. import sys
    5. import time
    6. from openai import APIConnectionError, APIStatusError, OpenAI
    7. from PIL import Image
    8. BASE_URL = os.environ["MODEL_BASE_URL"]
    9. API_KEY = os.environ["MODEL_API_KEY"]
    10. MODEL_NAME = os.environ["MODEL_NAME"]
    11. MAX_SIDE = 1024 # Upper limit for the longest side of the image, controls image token count
    12. MAX_FILE_BYTES = 10 * 1024 * 1024
    13. MAX_RETRIES = 3
    14. RETRYABLE_STATUS = {429, 500, 502, 503, 504}
    15. client = OpenAI(base_url=BASE_URL, api_key=API_KEY, timeout=60.0, max_retries=0)
    16. def encode_image(path: str) -> str:
    17. """Reads the image, scales it so the longest side does not exceed MAX_SIDE, and returns a data URL."""
    18. if os.path.getsize(path) > MAX_FILE_BYTES:
    19. raise ValueError(f"Image exceeds {MAX_FILE_BYTES // 1024 // 1024} MB limit: {path}")
    20. with Image.open(path) as img:
    21. img = img.convert("RGB")
    22. img.thumbnail((MAX_SIDE, MAX_SIDE))
    23. buf = io.BytesIO()
    24. img.save(buf, format="JPEG", quality=90)
    25. b64 = base64.b64encode(buf.getvalue()).decode("ascii")
    26. return f"data:image/jpeg;base64,{b64}"
    27. def ask(image_path: str, question: str) -> str:
    28. data_url = encode_image(image_path)
    29. messages = [{
    30. "role": "user",
    31. "content": [
    32. {"type": "text", "text": question},
    33. {"type": "image_url", "image_url": {"url": data_url}},
    34. ],
    35. }]
    36. for attempt in range(1, MAX_RETRIES + 1):
    37. try:
    38. resp = client.chat.completions.create(
    39. model=MODEL_NAME,
    40. messages=messages,
    41. max_tokens=512,
    42. )
    43. return resp.choices[0].message.content or ""
    44. except APIStatusError as e:
    45. if e.status_code not in RETRYABLE_STATUS or attempt == MAX_RETRIES:
    46. raise
    47. except APIConnectionError:
    48. if attempt == MAX_RETRIES:
    49. raise
    50. time.sleep(2 ** attempt)
    51. raise RuntimeError("Retries exhausted")
    52. if __name__ == "__main__":
    53. if len(sys.argv) != 3:
    54. print("Usage: python mm_qa.py <image_path> <question>", file=sys.stderr)
    55. sys.exit(1)
    56. try:
    57. print(ask(sys.argv[1], sys.argv[2]))
    58. except (OSError, ValueError, APIStatusError, APIConnectionError) as e:
    59. print(f"API call failed: {e}", file=sys.stderr)
    60. sys.exit(1)

    Running example:

    1. 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.