Concepts / Autoregressive Decoding and Token Generation

Autoregressive Decoding and Token Generation

A token is one piece of the output, and the model does not emit a whole response in a single step.

  • Programming

Two Ways to Send a Model a Request

Once a model has been trained, applications send it inputs and wait for outputs. Many model providers expose this work through two kinds of inference API: an online API and a batch API. Both accept requests and both return predictions, so from the outside they can look alike. The difference lies in what the provider is trying to optimize. That choice shapes how requests are scheduled, how the hardware is used, and what the person waiting on the result experiences.

What do you think happens?

A chatbot user sends one message, and in the same period a separate job submits a large set of document summaries that nobody is waiting on. Which API style should answer the chatbot message sooner?

  • The online API

  • The batch API

  • Both answer at the same speed

Reveal answer
Answer:

The online API

An online API is tuned for latency, which is the time a single caller waits for an answer, and each request is handled as soon as it arrives. A batch API is tuned for cost. Its requests do not need an immediate answer, so the provider can delay them and group them together.

Generating a Response One Token at a Time

Language models often produce their output one token at a time through autoregressive decoding. A token is one piece of the output, and the model does not emit a whole response in a single step. Each step produces the next token, and that token becomes part of what the model works from when it produces the step after it. The loop repeats until the response is complete.

Because the response is built this way, generating a full answer can take a long time. The diagram below traces the loop: the text so far is used to predict the next token, that token is appended, and the extended text becomes the input for the next prediction.

Text so farPredict next tokenNew tokenToken appended totextinputone stepaddedfed back as input
How does the model produce a sequence one token at a time, with each new token fed back in as input for the next step?

What Online and Batch APIs Optimize

An online API is tuned for latency, meaning the time a single caller waits for an answer. Each request is handled as soon as it arrives. A batch API is tuned for cost. Its requests do not need to be answered immediately, and that slack gives the provider room to use cheaper hardware and to group many requests together so they are processed as one unit of work.

A useful way to hold this distinction is to ask what the provider is allowed to delay. An online API cannot delay much, so it gives up some efficiency in order to answer quickly. A batch API may delay, so it can spend that time on efficiency. The source describes the batch trade-off concretely: when turnaround stretches from seconds or minutes to hours, the provider can apply a wider range of optimization techniques. When the source was written, Google Gemini and OpenAI both offered batch APIs at a 50% cost reduction in exchange for that longer turnaround.

AspectOnline APIBatch API
Optimization goalLatency: the wait of a single callerCost
When requests are processedAs soon as they arriveNot immediately; the provider can schedule them within a longer turnaround
Acceptable turnaroundSeconds, since callers are waitingCan stretch from seconds or minutes to hours
What the provider can doGives up some efficiency to answer quicklyUses cheaper hardware and groups many requests into one unit of work

Online and batch inference APIs differ in what they prioritize and in when they process work.

Tracing Three Requests Through Each Style

The clearest way to see the difference is to follow requests through the system. Suppose three requests arrive close together: a chatbot message, a code-generation request, and a request to summarize a day's support tickets. Each request is a separate job for the provider. The timeline below shows how an online API and a batch API might handle them. Each lane is read from left to right in order of time.

A processingA heldA answeredB processingB heldB answeredC processingC heldC answeredA, B, C processed asone unitA, B, C returnedthenthenthenqueuedqueuedgroupedthen
When requests A, B, and C arrive close together, when does each one start processing and finish under an online API versus a batch API?
Worked example

Following the three requests

A chatbot message, a code-generation request, and a request to summarize a day's support tickets arrive close together. Trace how each is handled under an online API and under a batch API.

  1. 1
    Online API: handle on arrival

    Each request is treated as a separate job and is handled as soon as it arrives. The chatbot message is answered without waiting for the other two, because waiting would raise its latency.

  2. 2
    Online API: the other two requests

    The code-generation request and the support-ticket summary are also handled on arrival. Any grouping the online API does is allowed only if it does not significantly hurt latency.

  3. 3
    Batch API: accept and hold

    The batch API accepts all three requests but does not need to answer any of them immediately. Nobody in this batch is waiting in real time, so the provider has room to delay.

  4. 4
    Batch API: process together

    The provider groups the submitted requests into one unit of work and processes them together, which allows cheaper hardware and better efficiency.

  5. 5
    Batch API: return results

    Results come back after the grouped processing finishes. The turnaround may be much longer than seconds, which the batch style accepts in exchange for lower cost.

Result

The online API answers each request as it arrives and keeps each caller's wait short. The batch API defers all three, processes them as one group, and returns results later at a lower cost.

Batch Inference in Traditional Machine Learning

The word batch means something slightly different in traditional machine learning. There, online inference means predictions are computed after a request has arrived, while batch inference means predictions are precomputed before any request arrives. The batch API described above is not the same thing, and the distinction matters for foundation models.

Precomputation works when inputs are finite and predictable. A recommendation system, for example, can generate recommendations for every user in advance, store them, and retrieve them when a user visits the site. Foundation model inputs are open-ended, and it is hard to anticipate every prompt a user might write. Precomputing answers for all of them is therefore impractical, which is why the batch API for foundation models works by processing submitted requests instead.

  • Generating synthetic data
  • Producing periodic reports, such as summaries of Slack messages or analyses of customer support tickets
  • Processing every document uploaded during onboarding of a new customer
  • Reprocessing all data when migrating to a new model
  • Generating personalized recommendations or newsletters for a large customer base
  • Reindexing an organization's data to update a knowledge base

Each workload in that list tolerates delay. What they share is that no individual caller needs an answer right away, and that is the condition under which a batch API's cost advantage is available.

Streaming Mode and Its Trade-Off

APIs usually return a complete response by default. Many online APIs also offer streaming mode, which returns each token as soon as it is generated. Because users are impatient and generating a full response takes time, streaming changes what the user experiences. The diagram shows the client sending one prompt and then receiving a series of messages, each carrying a token, rather than one message containing everything. The client can begin displaying text as soon as the first token arrives.

ClientModel serviceone prompttoken 1token 2token N
How do tokens reach the client progressively while generation is still running, compared with waiting for the full response?

Latency, Throughput, and Utilization

Before optimizing an inference service, it helps to know which measurements matter. The source identifies three: latency, throughput, and utilization. From the user's point of view, latency is the central concern, because it describes how long a single caller waits. Throughput and utilization describe the service in aggregate: how much work it completes and how efficiently it uses its resources.

MetricWhat it describesHow grouping requests tends to affect it
LatencyHow long a single caller waits for an answerWaiting for a group to form adds delay, which is why online APIs limit grouping that hurts latency
ThroughputHow much work the service completes in aggregateGrouping is the lever batch APIs use to maximize throughput
UtilizationHow efficiently the service uses its resourcesShapes how much work the service can do and what it costs to run

The three metrics used to evaluate inference APIs, and how grouping requests affects each.

Response quality is a further consideration, but the source makes a boundary point about it: quality is a property of the model itself, not of the inference service that delivers it. An inference API therefore cannot be judged on quality alone. Latency tells you how one caller experiences the service, while throughput and utilization tell you what the service is doing overall. Both views are needed to decide whether an online or batch design makes sense.

Mistakes Beginners Make with API Styles

  • Common mistake

    Concluding that online APIs never group requests

    Why it fails

    The source notes that online APIs may still group requests, as long as grouping does not significantly hurt latency.

    Do this instead

    Ask how much waiting the grouping adds. The deciding factor is the emphasis on latency, not whether any grouping happens.

  • Common mistake

    Treating the batch API as precomputed predictions

    Why it fails

    In traditional machine learning, batch inference means precomputing predictions before requests arrive. That approach fails for open-ended foundation model inputs.

    Do this instead

    A foundation model batch API processes submitted requests. It does not precompute answers for every possible prompt.

  • Common mistake

    Choosing an inference API by response quality alone

    Why it fails

    Response quality belongs to the model, so it cannot separate one inference service from another on its own.

    Do this instead

    Evaluate latency, throughput, and utilization as well, since these describe how the service behaves and what it costs to run.

  • Common mistake

    Assuming streamed text has been checked

    Why it fails

    With streaming, tokens reach the user before the complete response exists, so the application cannot score the whole response first.

    Do this instead

    Treat streaming as a trade-off. Retrospective updates or removals can respond to risks after the fact, but they do not prevent the exposure.

Choosing an API Style for a Workload

MEDIUM

A team needs two things: a live chat assistant that answers each user as they type, and a nightly report that summarizes every support ticket from the previous day. For each workload, choose an online or batch API style, then explain what the provider is allowed to delay and what the team trades away.

Hints
  • Ask whether any individual caller is waiting in real time.
  • Think about what the provider is allowed to delay under each style.
  • A batch design can accept a longer turnaround, while a chat assistant cannot easily tolerate delay.

Key Takeaways

  • Online APIs optimize for latency and process requests as they arrive, while batch APIs optimize for cost and can accept longer turnaround.
  • Language models often produce output one token at a time, and each step's token feeds into the next, so generating a full response can take a long time.
  • Streaming mode returns tokens as they are generated, which cuts the wait until the first token, but responses cannot be scored before they are shown.
  • Latency, throughput, and utilization are the metrics used to evaluate inference APIs, and both the per-caller view and the aggregate view are needed to judge a design.

More concepts starting with A