+1 (415) 366-1364

Serving Gemma Economically: KV Cache, Quantization, Continuous Batching, and Cost per Million Tokens

Everyone budgets for the fine-tune. Almost nobody budgets for the serving bill, and that is the one that recurs every month. A 2B-class Gemma model that cost forty dollars of GPU time to tune can easily cost several thousand a month to serve badly - and a tenth of that to serve well. This tutorial is about the gap between those two numbers.

It picks up where Fine-Tuning Gemma with KerasHub stops and where Serving TensorFlow Models in Production does not apply cleanly: TF Serving is excellent for fixed-shape predictors, but an autoregressive language model is a different workload. One request is not one forward pass; it is hundreds of them, each depending on the last.

Why LLM serving is a different problem

A ResNet request is a single matmul-bound forward pass with a fixed cost. A Gemma request is two distinct phases:

  • Prefill - run the whole prompt through the model once, building the key/value cache. This is compute-bound: lots of tokens, one pass, the GPU's matrix units are saturated.
  • Decode - generate one token at a time, each step reading the entire set of model weights and the growing KV cache out of memory. This is memory-bandwidth-bound. The arithmetic per step is trivial; you are paying for data movement.

Two consequences that drive every decision below:

  1. During decode, batching is nearly free. The weights get read from HBM whether you are serving one request or thirty-two. Running a batch of 32 costs barely more wall-clock per step than a batch of 1, so throughput scales almost linearly until you run out of memory for KV cache.
  2. Quantization helps decode more than you'd guess, because it shrinks the number of bytes you must stream per step - not just the footprint on disk.

If you take nothing else away: measure prefill and decode separately. A single "latency" number hides which half of your system is broken.

Step 1: measure before you optimize

Start with an honest baseline using the model exactly as it came out of fine-tuning.

import os
os.environ["KERAS_BACKEND"] = "jax"

import time, statistics
import keras, keras_hub

gemma = keras_hub.models.GemmaCausalLM.from_preset("./gemma2_2b_domain")
gemma.preprocessor.sequence_length = 1024

def timed_generate(prompt, max_length=256):
    t0 = time.perf_counter()
    out = gemma.generate(prompt, max_length=max_length)
    dt = time.perf_counter() - t0
    n_out = len(gemma.preprocessor.tokenizer(out)) - len(gemma.preprocessor.tokenizer(prompt))
    return out, dt, n_out

# warm up first - the first call pays XLA compilation
timed_generate("warmup", max_length=32)

samples = [timed_generate(p) for p in eval_prompts[:20]]
latencies = [dt for _, dt, _ in samples]
tok_per_s = [n / dt for _, dt, n in samples]

print(f"p50 latency {statistics.median(latencies):.2f}s")
print(f"p95 latency {sorted(latencies)[int(0.95 * len(latencies))]:.2f}s")
print(f"median output tok/s {statistics.median(tok_per_s):.1f}")

Record four numbers, not one:

MetricWhat it tells youWho cares
TTFT (time to first token)prefill costusers watching a stream
TPOT (time per output token)decode speedusers reading the stream
Throughput (tokens/s across all concurrent requests)capacityfinance
KV cache bytes per requesthow many concurrent requests fitcapacity planning

TTFT and throughput pull in opposite directions. Deciding which one your product is actually optimizing is a product decision, and it is worth having that argument before you tune the server.

Step 2: compile the generation loop

An uncompiled Python decode loop will be the dominant cost. On the JAX backend, Keras compiles generate for you, but only if the shapes are stable - every distinct sequence length triggers a fresh XLA compilation.

Bucket your inputs so you compile a handful of shapes rather than hundreds:

BUCKETS = [256, 512, 1024, 2048]

def bucket_for(prompt_len):
    for b in BUCKETS:
        if prompt_len <= b:
            return b
    raise ValueError("prompt too long; truncate or chunk upstream")

Then warm each bucket at startup, before you accept traffic, so no user eats a compile:

for b in BUCKETS:
    gemma.preprocessor.sequence_length = b
    gemma.generate("warm " * (b // 4), max_length=b + 16)

Persist the XLA compilation cache across restarts so a rolling deploy does not re-pay it on every pod:

import jax
jax.config.update("jax_compilation_cache_dir", "/var/cache/jax")

This one line has saved clients more cold-start pain than any other change on this page.

Step 3: understand your KV cache budget

The KV cache is the thing that actually limits concurrency. Rough size:

bytes = 2 (K and V) x layers x kv_heads x head_dim x seq_len x dtype_bytes

For a 2B-class model with grouped-query attention, that lands in the low tens of megabytes per 1k tokens of context in bfloat16. Multiply by your concurrency target and by your maximum context, not your average, then check it against what is left of HBM after the weights:

def kv_bytes(layers, kv_heads, head_dim, seq_len, dtype_bytes=2):
    return 2 * layers * kv_heads * head_dim * seq_len * dtype_bytes

per_req = kv_bytes(layers=26, kv_heads=4, head_dim=256, seq_len=2048)
print(f"{per_req / 1e6:.0f} MB per request at 2k context")

weights_bytes = 2.6e9 * 2          # bf16 weights
hbm = 24e9
headroom = 0.85 * hbm - weights_bytes
print(f"max concurrent requests ~= {int(headroom // per_req)}")

If that number is embarrassing, you have three levers, in order of how much we recommend them: cap the context length, quantize the weights (frees HBM for cache), and only then reach for a bigger instance.

Capping context is undervalued. Teams routinely pass a 4k-token prompt where 800 tokens of retrieved context does the same job - see the chunking discussion in our RAG on TensorFlow tutorial. Trimming the prompt cuts prefill cost and cache pressure at once.

Step 4: quantize for serving

Decode is bandwidth-bound, so halving the bytes of the weights roughly halves per-step time. KerasHub exposes post-training quantization directly:

gemma.quantize("int8")                     # weights int8, activations dynamic
gemma.save_to_preset("./gemma2_2b_domain_int8")

Then re-run the Step 1 harness and compare quality as well as speed. The process is the same discipline as our post-training quantization and QAT tutorial, with one language-model-specific wrinkle: perplexity barely moves while instruction-following and JSON-formatting quietly degrade. Score the quantized model on the same held-out evaluation set and the same rubric you used to accept the fine-tune. If you have a structured-output path, re-run the schema-validity check from our tool-calling agents tutorial - invalid-JSON rate is the single most sensitive quantization canary we have found.

Typical result for a 2B-class model, int8 weight-only, on one mid-range GPU:

ConfigWeights in HBMMedian TPOTConcurrency at 2k ctx
bf16~5.2 GBbaselinebaseline
int8 weight-only~2.6 GB~1.5-1.9x fasterroughly 1.3-1.5x more

Treat those multipliers as the shape of the answer, not the answer. Measure on your hardware, your prompt lengths, your model.

Step 5: batch continuously, not statically

Static batching - wait 50 ms, collect what arrives, run the batch, return it all - is the wrong fit for generation. Every request in the batch finishes when the longest one finishes, so a 500-token answer holds four 20-token answers hostage.

Continuous (in-flight) batching instead lets finished sequences leave the batch and admits new ones at the next decode step. If you are serving with a dedicated LLM inference server, you get this for free and should use it. If you are serving Gemma from your own Keras process - which is a perfectly reasonable choice for internal and moderate-traffic workloads - the minimum viable version is a single-worker queue that batches admissions by bucket:

import asyncio
from collections import defaultdict

class BatchingServer:
    def __init__(self, model, max_batch=16, window_s=0.01):
        self.model, self.max_batch, self.window_s = model, max_batch, window_s
        self.queues = defaultdict(asyncio.Queue)

    async def submit(self, prompt, max_length):
        fut = asyncio.get_running_loop().create_future()
        await self.queues[bucket_for(len(prompt))].put((prompt, max_length, fut))
        return await fut

    async def run(self, bucket):
        q = self.queues[bucket]
        while True:
            item = await q.get()
            batch = [item]
            deadline = asyncio.get_running_loop().time() + self.window_s
            while len(batch) < self.max_batch:
                timeout = deadline - asyncio.get_running_loop().time()
                if timeout <= 0:
                    break
                try:
                    batch.append(await asyncio.wait_for(q.get(), timeout))
                except asyncio.TimeoutError:
                    break
            prompts = [p for p, _, _ in batch]
            outs = await asyncio.to_thread(
                self.model.generate, prompts, max_length=max(m for _, m, _ in batch)
            )
            for (_, _, fut), out in zip(batch, outs):
                fut.set_result(out)

That is static batching with a short admission window, and it is honest about it: it buys most of the throughput win for a few dozen lines, at the cost of some tail latency. The crucial detail is the asyncio.to_thread - never run a multi-second blocking generate on the event loop, or your health checks time out and the orchestrator kills a perfectly healthy pod.

Tune window_s against your measured TTFT target. A 10 ms window is invisible next to a 300 ms prefill; a 200 ms window is not.

Step 6: cache what you can

Two caches, very different payoffs:

  • Exact-match response cache. Hash the normalized prompt plus the generation parameters plus the model version, store in Redis with a TTL. On internal tools with templated prompts we routinely see 20-40% hit rates. The model version in the key is not optional - stale answers from the previous fine-tune are a support ticket you will not enjoy diagnosing.
  • Prefix / prompt cache. If every request shares a long system prompt, its KV cache is identical every time. Dedicated inference servers reuse it automatically; in a hand-rolled server it is real work, so first try just making the system prompt shorter. Measure the prefill share of TTFT before you invest here.

Semantic (embedding-similarity) caching is tempting and we mostly advise against it in regulated settings: returning a near answer to a different question is a correctness bug that looks like a performance win on your dashboard.

Step 7: do the cost arithmetic

Once you have measured throughput under load, the unit economics are a two-line calculation:

def cost_per_million_output_tokens(gpu_hourly_usd, tokens_per_s, utilization=0.4):
    effective = tokens_per_s * utilization
    return gpu_hourly_usd / (effective * 3600) * 1e6

print(cost_per_million_output_tokens(gpu_hourly_usd=0.85, tokens_per_s=600))

The utilization term is where self-hosting plans go wrong. A GPU reserved 24/7 and busy 15% of the day costs the same as one busy 90% of the day. Before committing to self-hosting, compare three options with real numbers:

  1. Commercial API per token - no idle cost, no ops, highest marginal cost, data leaves your boundary.
  2. Self-hosted always-on - cheapest at high steady utilization; you pay for nights and weekends.
  3. Self-hosted scale-to-zero - good for spiky internal traffic, if you can tolerate cold starts; see our KServe autoscaling tutorial, and note that LLM cold starts are dominated by pulling and loading multi-gigabyte weights, so mount them from a local SSD cache rather than object storage on every start.

In our experience the crossover for a 2B-class model sits somewhere around a few million tokens a day of steady traffic. Below that, self-hosting usually loses on total cost once you price engineering time. The two legitimate reasons to self-host below the crossover are data residency and latency floors - both good reasons, but name them explicitly rather than assuming self-hosting is cheaper.

Step 8: monitor the right things

Dashboard these, and alert on the first three:

  • TTFT p95 and TPOT p95 - separately. An aggregate latency SLO cannot tell you whether prefill or decode regressed.
  • Queue depth and admission wait - the leading indicator of saturation, visible long before latency moves.
  • KV cache utilization / rejected-for-memory count - if you are evicting or rejecting, your concurrency cap is wrong.
  • Output token length distribution - a prompt-template change that quietly doubles answer length doubles your bill with no code deploy.
  • Cache hit rate and truncation rate (requests hitting max_length), which usually means a truncated, useless answer that you paid full price for.

Ship these as structured metrics, not log greps, and keep the model_version label on every one so a canary rollout is readable.

A sensible default stack

For most clients coming to us with a tuned Gemma and no serving plan, the first iteration we recommend is deliberately boring:

  1. int8 weight-only quantized preset, quality-gated against the same eval set as the bf16 model.
  2. Bucketed sequence lengths with a persistent XLA compilation cache and startup warmup per bucket.
  3. A single-process async server with a 10 ms admission window and a hard concurrency cap derived from the KV-cache arithmetic in Step 3.
  4. Redis exact-match cache keyed on prompt plus params plus model version.
  5. TTFT/TPOT/queue-depth metrics with the model version label, plus a load test that reproduces your real prompt-length distribution.

That gets most teams an order of magnitude from the naive baseline. Reach for sharded multi-GPU serving or a dedicated inference server when you have outgrown it and can prove it with the numbers above - not before.

Where we help

The most common engagement here is a two-week benchmark-and-sizing sprint: we instrument your current serving path, measure prefill and decode under your real traffic shape, test quantized variants against your evaluation set, and hand back a sizing model with cost per million tokens for each option - including the option where you don't self-host at all. See Generative AI on the TensorFlow Stack for how we scope that work, or get in touch with your traffic numbers and latency target and we'll tell you which of the three options above fits.