Inference Optimization in Auto-Regressive Language Models

In this blog, We will discuss about how inference in LLM works, inference optimization techniques and how we used some of these to increase throughput and number of concurrent requests.

For a more inclusive read of this blog, we will refresh some concepts that will appear more often throughout this writeup.

A. Fundamentals

Training: It is the process of teaching a model patterns through large datasets by adjusting it’s parameters. During this process a model learns language patterns, facts, reasoning etc. It has different stages like Data Preparation, Pre-training, Supervised Fine Tuning, Post-Training (Like RL).

This is typically episodic and computationally heavy.

Inference: It is the process of using the fixed weights during training on live/new inputs. For eg, us using ChatGPT is performing inference on an OpenAI model. It runs continuously, on demand. It prioritizes low latency, and should scale with user traffic.


Now, that we understand these two terms, it’s important to understand why we need inference optimization in LLMs. For this to sink in, we need to realize what happens during inference.

B. Inference in auto-regressive LLMs consists of following stages:

auto-regressive llm is one where model generates one token at a time, using it’s own previously generated tokens as context. Diffusion llm is an alternate architecture.

Stages of inference for the input

1. Tokenization:

It splits a text into tokens. Tokens are equivalent to words of a sentence. Then, the tokenizer maps each token to an Integer ID. In later phases, the computation happens on these numbers. In the example below, each word of the sentence is a token. The word “inference” is formed of two tokens, “infer” and “ence”. Each token has it’s unique number.

Tokenization of the input What is inference?

2. Prefill and Build KV cache:

Prefill is the stage after tokenization. Usually there’s a scheduler which allows server to receive a tokenized request, then, KV cache is allocated which is enqueued for the prefill batch.

If you’ve used these llms via api, this step happens between ( you sending an api request and before llm creating it’s first output token).

In such case, the KV cache stores system prompt + user prompt by the end of prefill stage.

When prefill is performed, KV cache is created.

What’s a KV cache and why do we need it?

During inference, we need to calculate the attention scores of each token with every other token. Since, this is compute heavy operation, we can store results of one calculation in cache and re-use it every time we need it again. The re-use happens quite often.

Most of the inference optimization techniques, are based on KV cache.

Prefill builds the K and V matrices of the KV cache

3.Decode:

Decode is the process of creating the output tokens. During this, every single output token is appended to the earlier prefill sequence. Decode is completed either when context limit is hit, or when and end of sequence operator is encountered. Usually <eos> character is used.

Decode generates one token per step until the end-of-sequence token

4. Detokenization

This is the conversion of generated sequence of numbers into actual word, so it’s readable by the human.

Detokenization joins the decoded tokens into text

C. Why we need inference optimization

Model weights are stored in the GPU. This doesn’t scale with the number of requests and is easy to estimate. But it scales with the size of the model. A model with more parameters is generally better, so higher spec model is more desirable. i.e for eg, a Model with 27B model paramters is more desirable over 14B parameters. Another thing that competes for the GPU memory is the KV cache, which is harder to estimate.

During auto-regressive generation, each new token needs the keys and values of all previous tokens. Instead of re-computing them at every step, the serving engine stores them in the KV cache. With increasing sequence length, the amount of GPU memory required increases. Now, all concurrent requests will also use the same GPU memory. With the above context, hopefully you can now get a sense for how quickly the GPU memory gets consumed.

Goals of memory optimization

While, reducing memory footprint is one of the most important goals of inference optimization, this is not the only one, some are:

  1. Reduce Memory Footprint: Fit larger models or more concurrent requests on given hardware.
  2. Increase throughput: Generate more tokens or serve more requests per second.
  3. Reduce Latency: Get the first token faster and get output quickly.
  4. Reduce Inference Cost: Achieve the same workload with fewer or cheaper resources.
  5. Improve Scalability: Handle increasing concurrenet traffic without degrading service quality.

After being aware of these goals, we can ponder with a few questions. And in an ideal world, during this proceses of finding answers, we would end up discovering novel optimization techniques. But since we don’t live in an ideal world and most of these have already been figured out, let’s think about these questions and then, look at some widely used techniques.

Questions:

  1. Can we run the same model using less memory and cheaper hardware without compromising output quality?
  2. If multiple users send requests with the same system prompt or shared context, can we avoid processing that repeated content?
  3. Can we generate multiple tokens at once instead of generating them one by one?
  4. Can we use a smaller, faster model to help a larger model generate responses faster?
  5. Can we serve more users concurrently without making each user wait for the entire batch to finish?

D. Inference Optimization

In this part, we’ll try to answer above questions. Each question motivates one of the optimization techniques discussed below in order. We’ll also talk about how we implemented each of those techniques and how it improved performance in our case.

Our setup was: Qwen-3.8 27B model in L4 GPU (24GB vRAM). vLLM was the inference framework in use.

1. Quantization

Can we run the same model using less memory and cheaper hardware without compromising output quality?

Yes, but with minimal loss in quality.

In modern LLMs, weights are usually stored in 16-bit floating point numbers (FP16 or BF16) precision. This takes a lot of storage. We can reduce the precision of each weight to 8-bit(INT8), 4-bit(INT4) numbers. This significantly reduces the memory requirement and can help improve inference speed.

Quantization affects us twice.

  1. When each parameter requires less space, a larger model can fit in a smaller GPU. This applies to both model weight and KV cache.
  2. Decode is limited by how fast the GPU can read weights from memory for eveery token. So, fewer bytes to read per weight means faster generation.

At 8-bit, quality loss is small, At 4-bit, quantization methods like(GPTQ or AWQ) keep most of the quality. But de-gradation is expected, specially on harder reasoning tasks.

For eg: A 27B paramter model requires 54GB in FP16, 27GB in INT8 and 13.5GB in INT4 quantization.

We ended up using RedHatAI/Qwen3.8-27B-INT4 model from RedHatAI. Official BF16 was 54 GB and FP8 was 28GB which didn’t fit in our GPU. KV cache was stored in FP8. vLLM also allows storing kV cache in a different dtype than model weight.

Since, there wasn’t a good multi-modal LLM fitting our requirements, we stuck with INT4 quantization of the same model. However, such aggressive quantization should only be carried out accompanied by an eval set.

2. Prefix Caching

If multiple users send requests with the same system prompt or shared context, can we avoid processing that repeated content?

Yes.

During the prefill stage, model computes the keys and values for the input tokens and stores them in KV cache. If two requests start with the same prefix, we can re-use the same values. Because, each token, only attends to tokens before it. So, the longest prefix that has already been computed becomes free for a different request, only the remaining part of the request has to be prefilled. This reduces redundant computation, improves time-to-first token (TTFT) and saves compute resources.

Inference Frameworks like vLLM expose different tunable configs like, whether to turn on prefix caching or not. What block size to use, which algo to use for hashing, algo to use for invalidating cache, etc.

For example: The requests sharing same system prompt can reuse it’s cached prefix. Harnesses like claude code are engineered around prefix caching.

In our experiment, we were using Qwen with Opencode. For agents, prefix caching becomes important. The same system prompt and tool definitions are passed again and again. A high cache hit rate, reduces both cost and latency.

3. Multi-Token Prediction (MTP)

Can we generate multiple tokens at once instead of generating them one by one?

Partly, yes.

In standard auto-regressive model, generation is sequential.
MTP allows a model to predict multiple future tokens in a single forward pass. A model has to be specifically trained with additional prediction heads. A prediction head predicts next 1, 2 or 3 tokens in a single forward pass. The main model verifies in a single pass. If all are correct we get 3 tokens at the cost of 1 pass.

For eg: given “The sky is”, the model might predict “blue”, “today” and “outside” as future tokens. The main model may agree with “blue” and “today” but disagree with “outside”. In that case, at the cost of one forward pass, we got 2 tokens.

The model we were using ships with an MTP head. There was a bug with vLLM itself, that resulted in each prediction head loading embed_tokens and lm_head which stays un-used, this was resulting in OOM. We fixed it on a fork of ours. [ The contributers are already working on it’s fix to main.]

MTP competes for GPU space too, so available space for context size decreases. On our experiments, We saw no significant gain in decode speed as acceptance of tokens by draft decreased significantly when using higher MTP. Based on these results, we opted to go with MTP-1, which is 44% higher than without MTP.

MTP depth Decode speed Draft acceptance Context that fits
off 15.8 tok/s n/a 64k
1 22.8 tok/s 84% 40k
2 25.9 tok/s 74% 32k
3 26.4 tok/s 65% 32k

4. Speculative Decoding

Can we use a smaller, faster model to help a larger model generate responses faster?

Yes, if both models fit in memory.

Speculative Decoding uses a smaller drafter model to predict a sequence of upcoming tokens. A larger model(target model) then verifies these predictions in parallel. Output will be exactly the same as target model would generate, but slow forward passes are reduced. Above MTP is a special case of this idea itself. But here, there’s no separate drafter model.

We didn’t use a separate drafter model as we were already constrained by memory. If you have enough space, you can check DFlash2.

5. Continuous Batching

Can we serve more users concurrently without making each user wait for the entire batch to finish?

Yes.

In traditional static batching, requests are grouped together and processed as a batch. A new request may have to wait for an existing batch to finish before joining. Continuous batching addressees this by dynamically adding new requests as others finish generating their responses. This keeps the GPU better utilized, improves overall throughput, and allows the inference server to handle concurrent requests more efficiently.

vLLM does continuous batching by default. But at first, our server could handle ony 2 requests at a time. The KV cache had only ~2GB. So, only 2 requests of ~40k tokens could fit at a time.

While continuous batching improves how multiple requests are handled, the actual computation is still limited by KV cache. With high active requests, we knew overall throughput would increase. So to get maximum benefit of continuous batching, we freed some GPU memory for KV cache by moving the following to CPU memory:

  • embed_tokens : ~2.4GB, it’s just a lookup table.
  • vision encoder (~1GB), doesn’t need to live on GPU.

This freed up space to allow ~108k tokens.

We then ran 5 agents together. The speed per task decreased to 18 tok/s each. But, the combined decode throughput increased to ~91 tok/s. In this test, prefill is done one request at a time, as all 5 requests were sent exactly at the same time. But in practise, there’s usually some delay between requests, due to which prefix cache is used.


Every technique has it’s tradeoff. It’s important to measure each one against your requirements, rather than relying numbers on paper.

Similarly, in practise, only one technique is not enough. They’re usually used in a combination. There are also many more techniques than what we’ve discussed above.

Thanks for reading it thus far.




Enjoy Reading This Article?

Here are some more articles you might like to read next: