Mixture-of-Experts (MoE) models and agentic AI systems (AAIs) share one idea: each input uses only a few selected units. This post derives the latency of each system, and implements an orchestrator in PyTorch. The following picture shows an MoE and the two kinds of AAIs, static and dynamic:

The units that each system selects, and when. Orange arrows are network transfers.

From left to right, the units become coarser, more independent and more heterogeneous, and their latency becomes longer and more variable.

Mixture-of-Experts

An MoE layer runs in three steps. A gate picks the top-k experts of each token. A dispatch (all-to-all) sends each token to the accelerators that hold its experts. A combine sends the weighted outputs back, where they are summed. The following picture gives the prefill and decode latency of \(L_{\text{moe}}\) layers, for \(n_{\text{in}}\) input and \(n_{\text{out}}\) output tokens, and what bounds each term:

The latency \(t_{\text{layer}}(m, c)\) of one layer, for \(m\) new tokens on a KV cache of \(c\) tokens, is given by:

\[t_{\text{layer}}(m, c) = t_{\text{attn}}(m, c) + t_{\text{gate}}(m) + \mathbf{t}_{\textbf{dispatch}}(m) + t_{\text{expert}}(m) + \mathbf{t}_{\textbf{combine}}(m) \tag{1}\]

The terms in bold cross the network, in every layer and at every decode step. The following picture illustrates Eq. 1 on two accelerators:

One MoE layer on two accelerators, with two experts each, and the terms of Eq. 1 under its steps. The orange arrows are network transfers: at the dispatch, each gate keeps the tokens of its local experts and sends the other tokens to the other accelerator; at the combine, each accelerator sends the partial sums of the tokens of the other accelerator back to it, where they are added up.

Agentic AI systems

An AAI is like an MoE whose experts, the agents, are separate programs, e.g. web APIs, database queries, RAG pipelines or other ML models specialized in a task. They bring what a larger model cannot, such as recent data, exact results and actions on other systems. However, they differ in compute time and location, and they can fail.

In a static AAI, a router picks \(K\) agents once, from the query alone. The agents run in parallel as a hedged fan-out: the system keeps the first \(k \le K\) results, or what has arrived by the Time-To-Last-Token (TTLT) deadline, like the hedged requests of The Tail at Scale. A synthesizer then writes the answer. With the agents sorted by completion time, the following picture gives the latency of a static AAI, and what makes each term grow:

The following picture illustrates these terms on a static AAI:

A static AAI with \(K = 3\) agents, of which the first \(k = 2\) results are used. The result of the third agent comes too late and is dropped. The orange arrows are network transfers.

In a dynamic AAI, a central LLM, the orchestrator, picks the agents at every step, after reading the previous results, as in ReAct. At step \(s\), it prefills \(p_s\) new tokens on a KV cache of \(c_s\) tokens, decodes \(n_s\) tokens that may call \(K_s\) agents, and waits for the first \(k_s\) results. The following picture illustrates this loop:

A dynamic AAI. At each step, the orchestrator decodes calls to agents, and their outputs are appended to its context, until it decodes the final answer. The context (bottom) grows by the decoded tokens \(d_s\) and the agent outputs \(a_s\).

At the first step, the cache is empty (\(c_1 = 0\)), and each later step prefills only the last decoded token and the agent outputs. The following picture gives the latency of \(S\) steps, and what makes each term grow:

Note the KV cache: it sits idle in accelerator memory while the agents run. Keeping it limits the batch size of the server; evicting it, or moving to another replica, means a prefill of the whole context at the next step (InferCept).

The orchestrator is implemented in PyTorch in three parts. First, the hedged fan-out runs the calls with asyncio and keeps the first \(k\) results within TTLT:

import asyncio, re
import torch

async def hedged_fanout(calls, k, ttlt):
  tasks = [asyncio.create_task(call) for call in calls]
  results = []
  try:
    async with asyncio.timeout(ttlt):  # the TTLT deadline
      for next_done in asyncio.as_completed(tasks):
        try:
          results.append(await next_done)
        except Exception:
          continue                     # skip a failed call
        if len(results) == k:
          break
  except TimeoutError:
    pass                               # keep the results that arrived in time
  for task in tasks:
    task.cancel()                      # stop the calls that are still running
  return results

Then, one step of the orchestrator computes the first two terms of \(T_{\text{dynamic}}\). It prefills the new tokens on the KV cache of llm, a GPT that takes the cache as input and returns it updated, and decodes until a stop token:

@torch.no_grad()
def orchestrator_step(llm, new_tokens, kv_cache, stop_ids, n_max):
  logits, kv_cache = llm(new_tokens, kv_cache)  # prefill of p_s tokens
  out = [logits[:, -1:].argmax(dim=-1)]
  while out[-1].item() not in stop_ids and len(out) < n_max:
    logits, kv_cache = llm(out[-1], kv_cache)   # decode: one token
    out.append(logits[:, -1:].argmax(dim=-1))
  return torch.cat(out, dim=1), kv_cache  # the last token is not cached yet

Finally, the loop parses the calls, such as <call rag>input</call>, runs them, and prefills the outputs at the next step, with encode and decode the tokenizer:

CALL = re.compile(r"<call (\w+)>(.*?)</call>", re.S)

async def orchestrate(llm, encode, decode, agents, prompt, stop_ids, ttlt, s_max, n_max=512):
  new, kv_cache = encode(prompt), None
  for s in range(s_max):
    tokens, kv_cache = orchestrator_step(llm, new, kv_cache, stop_ids, n_max)
    text = decode(tokens)
    calls = [agents[name](arg) for name, arg in CALL.findall(text)]
    if not calls:                       # no calls: final answer
      return text
    outputs = await hedged_fanout(calls, k=len(calls), ttlt=ttlt)
    new = torch.cat([tokens[:, -1:], encode("".join(outputs))], dim=1)
  return text

And that is all: each entry of agents is an asynchronous function from a text to a text, e.g. a call to a web API, a database query or a RAG pipeline.

Limits in production

The network adds two crossings per agent call, a round trip that takes from tens of microseconds in one data center to hundreds of milliseconds across continents. Agent messages are small, so latency matters, not bandwidth. The main costs are:

  • Queueing: shared agents serve many orchestrators, so under load \(t_{\text{agent}}\) is mostly waiting.
  • Stragglers: a fan-out waits for its \(k\)-th fastest agent, and an agent that misses TTLT wastes its compute.
  • Context growth: every agent output stays in the context, and makes every later prefill and decode step slower.