# Continuous batching aur PagedAttention: service kai requests ek saath kaise

> Decode har step saare weights padhta hai; batching throughput lagbhag free badhata hai. Yeh page llama.cpp se concurrency, continuous batching, KV cache paging aur prefix caching naapta hai, aur dikhata hai service kai requests kaise serve karti hai।

- URL: https://dmxsf.com/hi/wiki/inference/continuous-batching/
- [DMXSF](https://dmxsf.com/hi/about/)
- मध्यम
- अपडेट किया गया: 2026-11-18
- Tags: Serving, Inference, KV cache

## यह पृष्ठ पूरा करने पर आप

- Samjhayein decode phase mein batch karna throughput lagbhag free kyun badhata hai, aur yeh "lagbhag" kab fail hota hai।
- Static aur continuous batching alag karein, aur uneven-length requests par doosra kitna time bachata hai, estimate karein।
- Ek request ki KV cache kitni badi hai nikaalein, "max-length reservation" waste kyun hai aur PagedAttention ki paging yeh kaise solve karti hai, batayein।
- Prefix cache ki hit condition batayein, aur uske aadhar par prompt structure adjust karein।
- llama.cpp aur vLLM ke concurrency-related parameters padhna seekhein।

Inference service ka throughput batching se aata hai: decode ka har step saare weights memory se padhta hai, aur ek hi read batch ke saare requests serve kar sakta hai - batch jitna bada, per-token cost utna kam. **Continuous batching** se ek request khatam hote hi turant naya request ghus jaata hai; **PagedAttention** KV cache ko fixed-size blocks mein kaat kar memory waste bachata hai; **prefix caching** same shuruat ko sirf ek baar compute karata hai. Teenon milkar vLLM aur llama.cpp jaise servers ka common skeleton hain।

> [!NOTE] Experiment environment
> Is page ke numbers ek hi machine, ek hi client code se hain: MacBook Pro (Apple M2 Max, 64 GB unified memory), llama.cpp ka `llama-server` (build 11146), Qwen2.5-7B-Instruct ka Q4_K_M quantization (4.68 GB), 16 slots. Client aur measurement method [LLM inference service](https://dmxsf.com/hi/wiki/inference/serving/) page par hain; wahan yeh bhi hai ki har experiment se pehle warm-up kyun zaroori hai. Alag hardware par absolute numbers alag; saath le jaane wali cheez trend aur method hai।

## Batch banaane par throughput kyun chadhta hai

Ek token generate karne ke liye saari layers se guzarna padta hai - matlab saare weights ek baar padhne padte hain. Weights padhne ka kharcha "is step mein kitne tokens bane" se nahi badalta: ek saath $B$ requests decode ho rahi hon to ek hi read $B$ requests serve karta hai; per-token read $1/B$ ho jaata hai. Yehi batching throughput badhane ki wajah hai।

Roofline ke soch se estimate kiya ja sakta hai ki yeh fayda kitne bade batch tak chalta hai. Ek linear layer $B$ tokens process karne mein $2BN$ floating-point operations ($N$ is layer ke weights) aur $N$ weights padhta hai; BF16 storage mein $2N$ bytes, isliye per byte $B$ operations - arithmetic intensity = batch size. H100 SXM ki memory bandwidth 3.35 TB/s, BF16 dense compute lagbhag 989 TFLOPS (NVIDIA site par listed 1,979 TFLOPS sparsity sahit hai; dense uska aadha), ratio lagbhag 295 FLOP/B: batch 295 se bahut chhota ho to step ka time weights padhne se tay hota hai, kuch sequences aur judne se time lagbhag nahi badalta।

KV cache aise share nahi hota: har sequence ki apni K aur V hain, har step uski apni copy padhi jaati hai. Batch bada, context lamba - yeh reads badhte hain. Aage ke numbers se: Qwen2.5-7B ke FP16 weights 14.2 GiB; har 4096-token sequence har step 224 MiB KV cache padhti hai; lagbhag 65 sequences par KV reads weights reads ke barabar. Isliye "batch bada = sasta" ki ek limit hai, jo compute, KV reads aur memory capacity milkar tay karte hain।

Is M2 Max par naapo. Neeche $C$ requests ek saath aati hain (prompt 64 tokens, har ek 128 generate), aur total throughput, per-request speed, TTFT, aur server `/metrics` se slot occupancy record hoti hai. [LLM inference service](https://dmxsf.com/hi/wiki/inference/serving/) wala `client.py`:

```python
async def watch(s, stop, peak):  # /metrics poll; slot occupancy ka peak record
    while not stop.is_set():
        async with s.get(URL + "/metrics") as r:
            for line in (await r.text()).splitlines():
                name, _, val = line.partition(" ")
                if name.startswith("llamacpp:requests_"):
                    peak[name] = max(peak.get(name, 0), float(val))
        await asyncio.sleep(0.2)

async def sweep():
    s, toks = await start()
    step = {}  # concurrency -> per-token decode time (seconds)
    print("  C  total tok/s  per-req tok/s  TTFT mean/max(s)  busy  queued")
    for C in (1, 2, 3, 4, 6, 8, 12, 16, 24, 32):
        runs = []
        for rep in range(2):
            stop, peak = asyncio.Event(), {}
            w = asyncio.create_task(watch(s, stop, peak))
            t0 = time.perf_counter()
            rs = await asyncio.gather(*[
                request(s, piece(toks, i, 64), 128, t0) for i in range(C)])
            stop.set()
            await w
            runs.append((
                sum(r["n"] for r in rs) / max(r["done"] for r in rs),
                st.mean(r["tpot"] for r in rs),
                st.mean(r["ttft"] for r in rs), max(r["ttft"] for r in rs),
                peak.get("llamacpp:requests_processing", 0),
                peak.get("llamacpp:requests_deferred", 0)))
        m = [st.mean(x) for x in zip(*runs)]
        step[C] = m[1]
        print(f"{C:>3} {m[0]:11.1f} {1 / m[1]:14.1f} {m[2]:9.2f} /{m[3]:6.2f} "
              f"{max(r[4] for r in runs):5.0f} {max(r[5] for r in runs):7.0f}")
    await s.close()
    return step

STEP = asyncio.run(sweep())
```

Output:

```text
  C  total tok/s  per-req tok/s  TTFT mean/max(s)  busy  queued
  1        38.1           40.1      0.19 /  0.19     1       0
  2        47.0           24.8      0.31 /  0.31     2       0
  3        51.1           17.8      0.39 /  0.39     3       0
  4        65.4           17.3      0.47 /  0.47     4       0
  6        68.6           12.2      0.76 /  0.76     6       0
  8        76.2           10.2      0.94 /  0.94     8       0
 12       111.6           10.4      1.50 /  1.50    12       0
 16       139.0           10.0      1.99 /  2.00    16       0
 24       106.7            9.8      6.66 / 16.02    16       8
 32       133.8            9.7      9.84 / 17.61    16      16
```

*Figure: Har concurrency do baar repeat karke average; har request ka prompt 64 tokens, output 128 tokens. Hollow points ka matlab requests 16 slots se zyada - extra requests pichhli khatam hone ka intezaar karti hain, total throughput isliye girta hai।*

Is table ko padhne ke chaar points:

1. **Throughput 3.6x badha, har request chauthai speed par.** Concurrency 1 se 16: total throughput 38.1 se 139.0 token/s; per-request speed 40.1 se 10.0 token/s. 16x zyada requests serve hui, har request sirf 4x dheemi hui।
2. **Curve na flat hai na smooth.** Per-step time (per-request speed ka inverse) concurrency 1, 2, 3 par 24.9, 40.4, 56.2 ms - har nayi sequence lagbhag 15 ms; concurrency 4 par 57.9 ms - lagbhag nahi badha; 8+ par lagbhag 96-100 ms flat. Roofline model kehta tha "kuch sequences aur = time same"; yeh machine 1-8 range mein aisa nahi karti. Yeh llama.cpp ke Metal kernel choice se match karta hai: `ggml-metal-ops.cpp` ke comments kehte hain small-batch matrix-vector kernels "batch size 2-8 ke liye valid" hain; Q4_K, Q6_K type K-quantizations ke liye yeh sirf batch 4-8 par enable hote hain (batch 2, 3 abhi bhi per-row matrix-vector; har nayi sequence ek aur weight read), batch 8 se bade par hi matrix-multiply kernel. Steps in boundaries se match karte hain, par maine har kernel profile nahi kiya - yeh source-consistent explanation hai, verified conclusion nahi. Is curve ko doosre hardware ki expectation na banayein; launch se pehle apne hardware aur engine par naapein।
3. **Slots bhar gaye to queue.** Concurrency 24, 32 par `busy` 16 par rukta hai, `queued` 8 aur 16: extra requests pichhli khatam hone ka intezaar karti hain; TTFT max 16-18 seconds tak chala jaata hai. Concurrency 24 ka total throughput bhi 106.7 par gir jaata hai: doosri batch sirf 8 requests - batch bhar nahi; concurrency 32 do full batches - wapas 133.8 token/s।
4. **TTFT concurrency ke saath badhta hai.** 16 requests ek saath aayein to pehle $16 \times 64 = 1024$ prompt tokens ka prefill - isliye average TTFT concurrency 1 ke 0.19 s se 1.99 s।

## Static batching aur continuous batching

Batching doosri problem laata hai: ek batch ke requests ki output length alag hoti hai. **Static batching** mein ek batch saath shuru, saath khatam: chhoti request pehle likh deti hai, uska slot khaali, sabse lambi ke intezaar mein, tabhi agla batch. **Continuous batching**, aka iteration-level scheduling, "ek decode step" ko scheduling unit banata hai: har step ke baad check kaun likh chuke, queue se naye requests turant khaali slots mein. Yeh idea Orca (OSDI 2022) se aaya. vLLM paper iska summary: iteration-level kaam karte hain - har iteration ke baad complete requests batch se nikal jaati hain, naye aati hain।

Real server se verify. 48 requests ek saath, har prompt 128 tokens, output lengths log-normal distribution se random (fixed seed, har baar same):

```python
import random

def make_lengths(n=48, seed=7):  # skewed (log-normal) output lengths
    rng = random.Random(seed)
    return [min(512, max(8, round(100 * rng.lognormvariate(0, 0.9))))
            for _ in range(n)]

lengths = make_lengths()
print(f"{len(lengths)} requests, output tokens: min {min(lengths)}, "
      f"median {st.median(lengths):.0f}, mean {st.mean(lengths):.0f}, "
      f"max {max(lengths)}, total {sum(lengths)}")
```

```text
48 requests, output tokens: min 15, median 61, mean 97, max 453, total 4656
```

Server ke paas 16 slots. `llama-server` mein continuous batching default on; `-nocb` (`--no-cont-batching`) lagaane par static batching. Har mode do baar, har baar server restart, aur pehle 40 s warm-up:

```python
import os

async def batching(label):
    s, toks = await start()
    await warm_up(s, toks, 40)
    t0 = time.perf_counter()  # 48 requests sab t = 0 par aati hain
    rs = await asyncio.gather(*[request(s, piece(toks, i, 128), n, t0)
                                for i, n in enumerate(lengths)])
    done = sorted(r["done"] for r in rs)
    print(f"{'server':>8} {'total(s)':>8} {'tok/s':>7} {'mean(s)':>8} "
          f"{'p90(s)':>7} {'TTFT(s)':>8}")
    print(f"{label:>8} {done[-1]:8.1f} {sum(lengths) / done[-1]:7.1f} "
          f"{st.mean(done):8.1f} {done[int(0.9 * len(done))]:7.1f} "
          f"{st.mean(r['ttft'] for r in rs):8.1f}")
    await s.close()

# MODE "default" ya "-nocb", server ke start mode ke mutabiq
asyncio.run(batching(os.environ.get("MODE", "default")))
```

Chaar runs ek table mein (`default` = continuous, `-nocb` = static; `mean` aur `p90` completion times ke mean aur 90th percentile; `TTFT` mein queue time bhi):

```text
  server total(s)   tok/s  mean(s)  p90(s)  TTFT(s)
 default     51.3    90.8     27.4    44.2     15.2
   -nocb     68.6    67.9     36.3    64.2     27.5
 default     51.0    91.2     28.4    45.6     15.9
   -nocb     67.9    68.6     38.1    63.7     30.0
```

Dono repeats kaafi paas. Continuous batching ka total 51 s, static 68 s - lagbhag ek chauthai kam; throughput 68 se 91 token/s; average completion 37 s se 28 s; p90 64 s se 45 s. Static mode mein har batch ka time uski sabse lambi request se tay hota hai. Yeh workload teen batches mein banta hai, har batch 16 requests, longest outputs kram se 218, 453 aur 192 tokens: chhoti requests likh kar khatam, unke slots baaki batch ke time tak khaali - batch chhota hota jaata hai, GPU aur kam bharta hai।

Continuous batching ne aur zyada kyun nahi bachaya? Pehle total kaam dekhein: 48 requests, total 4656 output tokens. Agar hamesha 16 sequences ek saath decode hoti (per step lagbhag 100 ms), to sirf $4656 / 16 \times 0.1 \approx 29$ s chahiye. Plus har request ka prefill: 128-token prompt 0.343 s, aur us dauran saare slots wait karte hain; 48 requests = $48 \times 0.343 \approx 16.5$ s - dono scheduling mein same. To 51 s mein teesra hissa prefill hai, lagbhag 35 s decode. 29 s ideal se zyada wala hissa mainly queue khaali hone ke baad ka "drain" phase hai: neeche ke simulation ke mutabiq aakhri request 38th second par hi generate shuru karti hai, uske baad ke 14.6 seconds mein batch sirf chhota hota jaata hai; aakhri seconds mein sirf woh 453-token request server akeli rakhti hai।

Yeh phenomenon 30 lines mein: har step "current batch size" se pichhle section ke measured step table se time leta hai; naya request aane par poora batch ek prefill ke liye rukta hai. `STEP` pichhle section ke `sweep` se, `PROMPT_SECONDS` LLM inference service page ke `anatomy` se:

```python
def step(b):  # b sequences ek saath decode; per-step time (seconds)
    ks = sorted(STEP)
    if b <= ks[0]:
        return STEP[ks[0]]
    for lo, hi in zip(ks, ks[1:]):
        if b <= hi:
            return STEP[lo] + (STEP[hi] - STEP[lo]) * (b - lo) / (hi - lo)
    return STEP[ks[-1]]

def simulate(lengths, slots, continuous, stall):
    todo, run, t, done = list(lengths), [], 0.0, []
    while todo or run:
        if continuous or not run:  # static batching sirf slots khaali hone par bhar-ta hai
            while todo and len(run) < slots:
                run.append(todo.pop(0))
                t += stall  # naye prompt ka prefill sab sequences rok deta hai
        t += step(len(run))
        run = [n - 1 for n in run]
        done += [t] * sum(n == 0 for n in run)
        run = [n for n in run if n > 0]
    return done

print("batch    " + " ".join(f"{b:5d}" for b in STEP))
print("step(ms) " + " ".join(f"{1000 * v:5.1f}" for v in STEP.values()))

lengths = make_lengths()
stall = PROMPT_SECONDS[128]  # 128-token prompt poore batch ko jitne seconds rokta hai
print(f"prefill of a 128-token prompt: {stall:.3f} s")
print("mode         makespan  tok/s  mean_done  p90_done")
for name, cont in (("continuous", True), ("static", False)):
    d = simulate(lengths, 16, cont, stall)
    print(f"{name:<12} {d[-1]:7.1f} {sum(lengths) / d[-1]:7.1f} "
          f"{st.mean(d):9.1f} {d[int(0.9 * len(d))]:8.1f}")
```

```text
batch        1     2     3     4     6     8    12    16    24    32
step(ms)  24.9  40.4  56.2  57.9  82.2  98.4  96.5 100.3 101.6 103.5
prefill of a 128-token prompt: 0.343 s
mode         makespan  tok/s  mean_done  p90_done
continuous      52.5    88.6      29.9     47.0
static          68.6    67.9      37.7     64.0
```

Simulation ka total measured se sirf kuch percent alag: continuous 52.5 s vs measured 51.0-51.3 s; static 68.6 s vs 67.9-68.6 s. Model mein koi fitted parameter nahi; inputs sirf do measured tables: per-step time aur prefill time. Matlab is machine par **scheduling policy ka total time par asar basically do cheezon se explain hota hai: batch size step length tay karta hai, aur slots kab barte hain.** Is model se todo: dono ka prefill 16.5 s; decode continuous lagbhag 36 s, static lagbhag 52 s; 29 s ideal se comparison - pehla 81%, doosra sirf 56%।

Neeche wala widget same simulator use karta hai. Default settings (16 slots, is page ke 48 requests, prompt 128 tokens, measured curve) = upar ka experiment - 52.5 s vs 68.6 s dikhna chahiye. Controls ghumayein:

- Output length "fully same": dono ka time same (dono 46.6 s), kyunki ek batch saath khatam hoti hai, static ke paas khaali slots nahi. "Long tail": continuous 27% kam time - length distributions mein sabse zyada।
- Per-step time "ideal: batch-independent": batching ka fayda maximum; continuous throughput 89 se 164 token/s, static 68 se 123; pehla abhi bhi 25% kam time. "Proportional to batch": har nayi sequence = extra time; batching ka throughput fayda zero, dono ka time same।
- Prompt length 1024: prefill zyada-tar time kha jaata hai (48 requests total 105 s, makespan 141 s), dono mein sirf 10% farq. Bahut lambe prompts ka scenario prefill-bound hai, decode scheduling ka nahi।
- Slots 2: dono sirf 7% farq; batch khud chhota, static ka slot waste bhi kam।

> [!TIP] Online service mein farq bada hai ya chhota
> Is experiment mein 48 requests ek saath aayein, aakhir mein ek "drain" phase hai: aakhri lambi requests server akeli rakhti hain, batch chhota. Online service mein requests lagatar aati hain, batch zyada-tar full rehta hai; continuous batching ka fayda: naya request current batch ke khatam hone ka intezaar nahi karta, agla step mein ghus jaata hai. Static mein naya request poore batch ka intezaar karta hai - TTFT "ek batch ke length" se bura ho jaata hai।

## Scheduling details: prefill aur decode ek hi step mein kaise

Naye request pehle prefill chahti hai. Prefill poora prompt ek saath process karta hai, compute-bound, time lagbhag prompt length ke proportional (pichhle page: 1024 tokens lagbhag 2.2 s). Agar saari decoding requests ruk jaayein, unka token interval ek lambi stall dikhega - upar ka simulation "poora batch rukna" isi ko dikhata hai।

**Chunked prefill** lambe prompt ko chunks mein kaat-ta hai, har step sirf ek chunk, aur decoding requests ko piggyback karta hai. SARATHI paper ise "decode-maximal batching" kehta hai: ek prefill chunk compute bharta hai, decode requests piggyback mein jaati hain; piggybacked decode ki keemat separate pure-decode batch se ek order of magnitude tak kam. vLLM V1 feasible hone par chunked prefill default on; scheduling mein pehle saare pending decode requests, phir bache `max_num_batched_tokens` budget se prefill chunks. vLLM docs ka trade-off: value chhota - decode token interval zyada stable; value bada - first token zyada fast; throughput ke liye chhote models par 8192 se bada suggest. llama.cpp server mein corresponding `-b` (logical batch, default 2048) aur `-ub` (physical batch, default 512)।

## KV cache: concurrency ki ceiling

Ek request kitni memory leti hai aur ek saath kitni requests fit - dono KV cache se tay hote hain. Har token ki KV cache $2 \times$ layers $\times$ KV heads $\times$ head dim $\times$ bytes per number. Neeche Qwen2.5-7B ke `config.json` se hisaab, aur estimate ki 80 GiB card par kitni requests fit (assume: 90% memory available, 4 GiB activations ke liye - dono numbers assumptions hain):

```python
import glob
import json
import math
import os

cfg = json.load(open(glob.glob(os.path.expanduser(
    "~/.cache/huggingface/hub/models--Qwen--Qwen2.5-7B/snapshots/*/"
    "config.json"))[0]))
d, ff, v = cfg["hidden_size"], cfg["intermediate_size"], cfg["vocab_size"]
L, kv = cfg["num_hidden_layers"], cfg["num_key_value_heads"]
hd = d // cfg["num_attention_heads"]

per_token = 2 * L * kv * hd * 2  # K aur V, har ek 2 bytes (FP16)
attn = 2 * d * d + 2 * d * kv * hd + d + 2 * kv * hd  # q,k,v,o (biases sahit)
params = 2 * v * d + L * (attn + 3 * d * ff + 2 * d) + d
GiB = 2 ** 30
print(f"layers {L}, KV heads {kv}, head dim {hd}")
print(f"KV cache per token: {per_token:,} bytes")
print(f"  4096-token slot: {4096 * per_token / 2**20:.0f} MiB, "
      f"65536-token pool: {65536 * per_token / GiB:.2f} GiB")
print(f"parameters: {params / 1e9:.3f} B -> FP16 weights "
      f"{2 * params / GiB:.1f} GiB")
print(f"KV reads per step equal weight reads at "
      f"{2 * params / (4096 * per_token):.0f} sequences of 4096 tokens")

# 80 GiB GPU, 90% available, 4 GiB activations ke liye (assumption)
pool = 0.9 * 80 * GiB - 2 * params - 4 * GiB
tokens = pool / per_token
print(f"KV pool: {pool / GiB:.1f} GiB = {tokens / 1e6:.2f} M tokens")
fixed = int(tokens // 8192)  # har request max_model_len = 8192 reserve
paged = int(tokens // (math.ceil(1000 / 16) * 16))  # average 1000 tokens
print(f"sequences, reserve 8192 tokens each: {fixed}")
print(f"sequences, 16-token blocks, 1000 tokens avg: {paged}")
```

Output:

```text
layers 28, KV heads 4, head dim 128
KV cache per token: 57,344 bytes
  4096-token slot: 224 MiB, 65536-token pool: 3.50 GiB
parameters: 7.616 B -> FP16 weights 14.2 GiB
KV reads per step equal weight reads at 65 sequences of 4096 tokens
KV pool: 53.8 GiB = 1.01 M tokens
sequences, reserve 8192 tokens each: 123
sequences, 16-token blocks, 1000 tokens avg: 999
```

Qwen2.5-7B grouped-query attention (GQA, 4 KV heads) use karta hai - har token sirf 57,344 bytes; vLLM paper ke OPT-13B se compare: har token 800 KB ($2 \times 5120 \times 40 \times 2$ bytes) - 14 guna farq. KV heads jitne kam, context jitna chhota - same memory mein utni zyada requests।

### Max-length reservation vs paging

Memory har request ko kaise do - yeh utna hi matter karta hai. Sabse seedha: request aate hi max length (jaise `max_model_len = 8192`) ka continuous block reserve, kyunki pehle nahi pata kitna likhegi. Upar ke estimate mein is tareeke se sirf 123 requests; actual length (average 1000 tokens, 16 ka multiple upar) ke hisaab se allocation par 999 - 8x farq।

*Figure: Har block 16 tokens ki KV cache; numbers illustrative hain. PagedAttention ka block table request ki logical position ko non-adjacent physical blocks mein map karta hai।*

**PagedAttention** OS ki virtual memory paging se idea leta hai: KV cache fixed-size blocks (vLLM paper default 16 tokens per block); har request ki ek block table jo logical position ko physical blocks mein map karti hai; physical blocks adjacent hone zaroori nahi; jahan zaroorat wahan allocation. Request sirf aakhri block ke unused hisse ko waste karti hai. vLLM paper ne naapa: purane systems mein KV cache memory ka sirf 20.4%-38.2% real tokens mein tha, vLLM lagbhag 96.3%; same latency par throughput FasterTransformer aur Orca se 2-4x. Kai parallel sampling sequences ek hi prompt ke blocks share kar sakti hain, write par copy (copy-on-write) - prefix caching isi par khadi hai।

Memory waqai kam padne par vLLM kuch requests ko preempt karta hai, unke blocks release; space aane par preempted requests recompute. V1 ka default recompute (RECOMPUTE) hai, memory swap nahi, kyunki V1 architecture mein recompute ka kharcha kam (vLLM docs). Preemption warnings baar-baar = KV cache tight: docs suggest `gpu_memory_utilization` badhana, `max_num_seqs` ya `max_num_batched_tokens` kam karna, ya parallelism badha kar memory khali karna।

### llama.cpp mein wahi baat

llama.cpp server ko bhi "ek KV cache 16 slots mein kaise bat jaye" jawab dena hai. `--kv-unified` ke bina total context `-c` har slot ko barabar bat jaata hai, har request apni hi hisse tak seemit; `--kv-unified` ke saath sab slots ek cache share karte hain. Same 6000-token request se try, dono start modes (`-c 65536 -np 16`):

```python
import textwrap

async def slots():
    s, toks = await start()
    async with s.get(URL + "/props") as r:
        n_ctx = (await r.json())["default_generation_settings"]["n_ctx"]
    print("context available to one request:", n_ctx, "tokens")
    status, d = await post(s, "/completion", {
        "prompt": toks[:6000], "n_predict": 8, "temperature": 0})
    if status == 200:
        print(f"HTTP 200: {d['tokens_evaluated']} prompt tokens processed")
    else:
        print(f"HTTP {status}:")
        print(textwrap.fill(d["error"]["message"], 72))
    await s.close()

asyncio.run(slots())
```

`--kv-unified` ke saath:

```text
context available to one request: 65536 tokens
HTTP 200: 6000 prompt tokens processed
```

Bina:

```text
context available to one request: 4096 tokens
HTTP 400:
request (6000 tokens) exceeds the available context size (4096 tokens),
try increasing it
```

Pehle mein har request poora 65536-token pool use karti hai; doosre mein har slot sirf $65536 / 16 = 4096$, aur 6000-token request reject. Yehi "reserve" aur "share" ka farq hai - scale vLLM se bahut chhota: Ollama context length ko parallel count se multiply karta hai (official FAQ misaal: 2K context, 4 parallel - actually 8K, memory bhi saath badhti hai)।

## Prefix caching: same shuruat sirf ek baar

Kai requests ka shuruat same hota hai: system prompt, tool definitions, RAG ka same document, multi-turn chat ke pichhle saare turns. In tokens ki KV cache sirf unki khud aur unse pehle ke tokens par nirbhar hai, isliye ek baar compute karke aage wali requests ko diya ja sakta hai. Yehi prefix caching hai - koi output nahi badalta।

Experiment: ek 2000-token document + 20-token sawaal, 4 baar bheja, har baar alag sawaal. Teen cases: A document pehle, cache on; B document ke pehle 8 har-baar-badalne wale tokens (jaise timestamp), cache on; C document pehle, cache off (request mein `cache_prompt` = `false`)।

```python
async def prefix():
    s, toks = await start()
    await warm_up(s, toks, 40)
    doc = toks[120_000:122_000]  # 2000-token "system prompt / document"
    ask = lambda i: toks[125_000 + 50 * i:][:20]  # 20-token sawaal
    head = lambda i: toks[127_000 + 10 * i:][:8]  # 8 har-baar-badalne wale tokens
    cases = [("A doc first, cache on", True, lambda i: doc + ask(i)),
             ("B header first, cache on", True,
              lambda i: head(i) + doc + ask(i)),
             ("C doc first, cache off", False, lambda i: doc + ask(i))]
    print("case                       req  reused  computed  TTFT(s)")
    for name, cache, build in cases:
        for i in range(4):
            r = await request(s, build(i), 16, time.perf_counter(), cache)
            print(f"{name:<26} {i + 1:>3} {r['srv']['cache_n']:7d} "
                  f"{r['srv']['prompt_n']:9d} {r['ttft']:8.2f}")
    async with s.get(URL + "/metrics") as r:
        for line in (await r.text()).splitlines():
            if line.startswith("llamacpp:prompt_tokens"):
                print(line)
    await s.close()

asyncio.run(prefix())
```

Output (`reused` = reuse hue tokens, `computed` = recompute hue tokens):

```text
case                       req  reused  computed  TTFT(s)
A doc first, cache on        1       0      2020     4.10
A doc first, cache on        2    2000        20     0.10
A doc first, cache on        3    2000        20     0.13
A doc first, cache on        4    2000        20     0.13
B header first, cache on     1       0      2028     4.09
B header first, cache on     2       0      2028     4.07
B header first, cache on     3       0      2028     4.09
B header first, cache on     4       0      2028     4.11
C doc first, cache off       1       0      2020     4.40
C doc first, cache off       2       0      2020     4.37
C doc first, cache off       3       0      2020     4.36
C doc first, cache off       4       0      2020     4.37
llamacpp:prompt_tokens_total 34656
llamacpp:prompt_tokens_cached_total 6000
llamacpp:prompt_tokens_seconds 496.955
```

Table padhein:

- **A: document pehle**: request 1 ne poora document compute (2020 tokens, 4.10 s); agle teen requests ne 2000 tokens reuse kiye, sirf 20 naye compute; TTFT 0.10-0.13 s par - lagbhag 30x fast।
- **B: shuruat badalti hai**: pehle 8 tokens har baar alag - pehle token se hi pichhli request se different; cache ek baar bhi hit nahi; har request 2028 tokens recompute, 4.1 s. Yeh 8 tokens khud kuch nahi kharch karte, par unke peeche wale 2000 tokens ka poora cache invalidate kar dete hain।
- **C: cache off**: `cache_prompt` = `false` - har baar recompute, 4.4 s. A ki request 1 se lagbhag 7% dheema - yeh scale sustained load par machine state ka drift hai, cache ka asar nahi; compare karne layak cheez 4 s vs 0.1 s hai।

Aakhri teen lines server ke `/metrics` se: is run mein total 34656 prompt tokens process hue, jismein se 6000 cache se (A ki teen requests har ek 2000 reuse)।

vLLM hash-based block caching se wahi karta hai: har block ka hash uske saare pichhle blocks ke hashes (parent hash), is block ke tokens aur extra info (LoRA id, multimodal input hash, cache salt) se banta hai - isliye hit tabhi jab prefix poora same ho; sirf full blocks cache hote hain, khaali blocks LRU (least-recently-used) se evict. SGLang ka RadixAttention prefix cache ko radix tree se manage karta hai; paper report karta hai SGLang ne agent control, few-shot learning, JSON decoding, RAG aur multi-turn chat jaise tasks par throughput max 6.4x diya tab-ke SOTA inference systems se (RadixAttention inme se ek optimization hai). Multi-tenant mein dhyan: hit/miss latency alag banata hai, attacker isse doosre ke prompt infer kar sakta hai; vLLM ka `cache_salt` parameter salt ko pehle block ke hash mein mila deta hai - sirf same salt wali requests cache share karti hain।

Isse prompt likhne ke kuch rules:

- **Stable content pehle, changing content baad**: system prompt, tool definitions, few-shot examples, documents pehle; user ka sawaal aakhir mein।
- **Shuruat mein badalne wali cheez mat rakho**: timestamp, request id, random session id - chahe kuch hi tokens hon, peeche ka poora cache invalid kar dete hain।
- **Multi-turn chat aur Agent har turn append karein, history rewrite nahi**: pichhle turns word-for-word same rakhein - har turn sirf naya hissa compute hoga।
- **RAG mein same document sawaal se pehle rakhein** - usi document ke kai Q&A reuse kar lenge।

## Summary aur exercises

**Is page ke mukhya points:**

1. Decode har step weights padhta hai; batching se kai requests isi read ko share karti hain - total throughput batch ke saath badhta hai; per-request saath hi dheemi hoti hai - throughput aur per-request speed ka trade-off. Is page measured: concurrency 1-16, throughput 3.6x, per-request speed chauthai।
2. Static batching sabse lambi ka intezaar karta hai, chhoti requests ke slots khaali; continuous batching har step bhar-ta hai. Measured 48 uneven requests: continuous lagbhag chauthai kam time; measured step table se banaya simulation measured se kuch percent alag।
3. KV cache concurrency ki ceiling tay karta hai. Max-length reservation zyada-tar memory waste karta hai; PagedAttention fixed-size blocks on-demand allocate karke waste ko aakhri block tak seemit karta hai।
4. Prefix cache sirf tab hit hota hai jab prefix token-by-token same ho: stable pehle, changing baad।
5. Parameters: llama.cpp mein `-np`, `-c`, `--kv-unified`, `-b`, `-ub`; vLLM mein `--max-num-seqs`, `--max-num-batched-tokens`, `--max-model-len`, `--gpu-memory-utilization`।

### Quick self-test

**1. Ideal roofline model mein decode phase batch size 1 se 8 karne par per-step time kaisa hota hai?**

- [ ] Lagbhag 8x
- [x] Lagbhag same
- [ ] Lagbhag 1/8
- [ ] Sampling temperature par nirbhar

> Per-step time "weights ek baar padhna" se tay hota hai; extra sequences isi read ko share karte hain, isliye batch roofline ke turning point se neeche ho to time lagbhag same. Is page ke measured numbers 1-8 range mein flat nahi (25-98 ms) - yeh is machine ke kernel implementation ki khaasiyat hai।

**2. Static batching ka mukhya waste kahan se aata hai?**

- [ ] Har step weights dobara padhne se
- [x] Chhoti request likh kar khatam hone ke baad uska slot sabse lambi request khatam hone tak agle request ko nahi milta
- [ ] KV cache bada
- [ ] Prefill dheema

> Static batching poore batch ke saath shuru aur khatam hoti hai; batch ki sabse lambi request batch ka time tay karti hai।

**3. PagedAttention KV cache ko blocks mein kaatne ka mukhya fayda?**

- [ ] Attention compute zyada precise
- [x] On-demand allocation - over-reservation aur fragmentation ka waste kam; same memory mein zyada requests ek saath fit
- [ ] Weights chhote
- [ ] Prefill compute kam

> Blocks adjacent hone zaroori nahi; request sirf aakhri block ke unused hisse ko waste karti hai।

**4. Prefix cache hit hone ke liye kya condition?**

- [ ] Pichhli request se semantically similar
- [x] Pehle token se hi, kisi pehle-process hue request ke saath same prefix
- [ ] Same sampling temperature
- [ ] Same HTTP connection

> Cache token sequence se match hota hai. Pehla different token aate hi baaki sab recompute।

**5. `-c 65536 -np 16` se llama-server start kiya, `--kv-unified` nahi - ek request ka max context kitna?**

- [ ] 65536 tokens
- [x] 4096 tokens
- [ ] 16 tokens
- [ ] Unlimited

> Total context 16 slots mein barabar banta hai: $65536 / 16 = 4096$।

**Exercises:**

1. 32 layers, 8 KV heads, head dim 128 wala model (Llama 3 8B ka config), FP16 KV cache - har token kitne bytes? Ek 8192-token request kitni memory? 24 GiB card FP16 weights (lagbhag 8.03B params) fit karne ke baad, activations ignore - max kitni aisi requests ek saath?
2. 4 slots, per-step time fixed (batch-independent). 10 requests ke output lengths kram se 100, 10, 10, 10, 10, 10, 10, 10, 10, 10. Static aur continuous batching har ek kitne steps lete hain?
3. vLLM-style prefix cache, block size 16, sirf full blocks cache. Request 1: 1000-token system prompt + 50-token sawaal; request 2: same system prompt + doosra 50-token sawaal; request 3: system prompt ke pehle 1 extra token ka timestamp, baaki request 2 jaisa. Request 2 aur request 3 har ek kitne tokens reuse karte hain?
4. `-c 32768 -np 8` se llama-server start, `--kv-unified` nahi. Kya 20000-token request accept hogi? Do tareeke likhein jisse accept ho jaaye।
5. Online chat ke liye service vLLM ka `max_num_batched_tokens` offline batch inference se chhota kyun rakhti hai?

<details>
<summary>Reference answers</summary>

1. Har token ki KV cache $2 \times 32 \times 8 \times 128 \times 2 = 131072$ bytes (128 KiB); 8192 tokens exactly 1 GiB. Weights lagbhag 14.96 GiB ($8.03 \times 10^9 \times 2$ bytes); 24 GiB card par lagbhag 9.04 GiB bachta hai - max 9 requests. Actually activations aur runtime ke liye bhi jagah chahiye, isliye aur kam।
2. Static: pehli batch [100, 10, 10, 10] = 100 steps, doosri [10, 10, 10, 10] = 10, teesri [10, 10] = 10 - total 120. Continuous: lambi request ek slot par 100 steps rakhti hai; baaki teen slots bache 9 chhoti requests process karte: $9 / 3 \times 10 = 30$ steps, sab un 100 ke andar - total 100. Static 20% zyada; lambi request chhoti requests ko batch mein "daba" deti hai - yehi waste ka srot hai।
3. Request 2 request 1 ke pehle 1000 tokens share karti hai; sirf full blocks hit: $\lfloor 1000 / 16 \rfloor = 62$ blocks, yaani 992 tokens; bache 58 (63rd block ke request-1-jaise 8 tokens sahit) recompute. Request 3 ka pehla token hi alag - pehle block ka hash alag, aage sab blocks ke hashes us par nirbhar - ek bhi hit nahi, reuse 0।
4. Har slot ke paas sirf $32768 / 8 = 4096$ tokens; 20000-token request reject hogi. Upay: `--kv-unified` lagao, sab slots poora cache share; ya `-np` kam karo (jaise `-np 1` par single request 32768 use karti hai); ya `-c` kam se kam $20000 \times 8 = 160000$ badhao - keemat: KV cache ki memory bhi utni badhti hai।
5. Chunked prefill mein har step pehle saari decode requests ghuste hain, phir bache budget se prefill chunks. Budget chhota - per step kam prefill chhipakta hai, already-generating requests ka token interval zyada smooth; interactive-latency-sensitive online chat ke liye. Budget bada - per step zyada prompt tokens, first token fast, throughput high; sirf total throughput dekhne wale offline tasks ke liye (vLLM docs: throughput ke liye bada, chhote models par 8192 se bada)।

</details>

## Aage padhein

- Kwon adi, [Efficient Memory Management for Large Language Model Serving with PagedAttention](https://arxiv.org/abs/2309.06180) (SOSP 2023): vLLM aur PagedAttention ka original paper; is page ke 20.4%-38.2%, 96.3% aur 2-4x sab yahin se।
- Yu adi, [Orca: A Distributed Serving System for Transformer-Based Generative Models](https://www.usenix.org/conference/osdi22/presentation/yu) (OSDI 2022): iteration-level scheduling ka srot।
- Agrawal adi, [SARATHI: Efficient LLM Inference by Piggybacking Decodes with Chunked Prefills](https://arxiv.org/abs/2308.16369): chunked prefill aur decode-maximal batching।
- Holmes adi, [DeepSpeed-FastGen](https://arxiv.org/abs/2401.08671): Dynamic SplitFuse - lambe prompts ko tod kar decode ke saath fixed-size per-step batches।
- Zheng adi, [SGLang: Efficient Execution of Structured Language Model Programs](https://arxiv.org/abs/2312.07104): RadixAttention aur prefix reuse।
- vLLM docs: [Optimization and Tuning](https://docs.vllm.ai/en/latest/configuration/optimization.html) (preemption aur chunked prefill), [Automatic Prefix Caching](https://docs.vllm.ai/en/latest/design/prefix_caching.html), [Production Metrics](https://docs.vllm.ai/en/latest/usage/metrics.html)।
- Related pages: [LLM inference service](https://dmxsf.com/hi/wiki/inference/serving/), [KV cache aur inference performance](https://dmxsf.com/hi/wiki/inference/kv-cache/)।

- Agrawal adi, [Sarathi-Serve](https://arxiv.org/abs/2403.02310) (OSDI 2024): lambe prefill ko chhote chunks mein decode steps ke beech daal kar mixed-deployment blocking khatam; is page ke measured continuous batching aur prefix caching ke complementary - detail [prefix caching aur PD separation](https://dmxsf.com/hi/wiki/inference/prefix-caching/) mein।

## सहायक कोड

[Serving: continuous batching, paged KV memory, prefix cache, TTFT, capacity](https://github.com/dmxsf/dmxsf/tree/main/labs/inference/continuous-batching): Roofline and exact batched decoding, static against continuous scheduling on paper and on a real model, a paged KV pool with copy-on-write, a hash-based prefix cache, and what a request costs (TTFT, TPOT, capacity). Read the ratios, not the milliseconds.

- सहायक रिपॉज़िटरी में चलाएँ (--quick से तेज़ जाँच): `uv run dmxsf run inference/continuous-batching`
- [प्रयोग स्क्रिप्ट देखें](https://github.com/dmxsf/dmxsf/blob/main/labs/inference/continuous-batching/run.py)
- [प्रयोग विवरण](https://github.com/dmxsf/dmxsf/blob/main/labs/inference/continuous-batching/README.en.md)
- [`serving.py`](https://github.com/dmxsf/dmxsf/blob/main/src/dmxsf/inference/serving.py)
- [सूची में देखें](https://dmxsf.com/hi/code/#continuous-batching)

## अक्सर पूछे जाने वाले सवाल

### Continuous batching kya hai? Static batching se kya farq?

Continuous batching ek decode iteration ko scheduling unit banata hai: har step ke baad complete hue requests batch se bahar, aur wait kar rahe naye requests turant khaali slots mein - iteration-level scheduling bhi kehte hain. Static batching mein agla batch tab shuru hota hai jab batch ka sabse lamba request khatam ho; us dauran chhoti requests ke slots khaali. Is page ne Qwen2.5-7B (Q4_K_M, M2 Max, 16 slots) par 48 different-length requests ek saath bheje: continuous batching total lagbhag 51 s, off (-nocb) lagbhag 68 s; throughput 68 se 91 token/s; average completion time lagbhag ek chauthai kam।

### PagedAttention kya hai, kaun si problem solve karti hai?

PagedAttention har request ki KV cache ko fixed-size blocks mein kaat-ta hai (vLLM paper mein default 16 tokens per block), block table logical position ko non-adjacent physical blocks mein map karta hai, aur on-demand allocate karta hai. Purane systems max length ke hisaab se continuous space reserve karte the - over-reservation aur fragmentation se bahut memory waste: vLLM paper ke measurement mein purane systems ki KV cache memory ka sirf 20.4%-38.2% hissa real tokens rakh raha tha, vLLM lagbhag 96.3%; throughput FasterTransformer aur Orca se 2-4x।

### Prefix cache kab hit hota hai?

Prefix cache token sequence se match karta hai: naya request pehle token se hi kisi processed request se exactly same hona chahiye, tabhi us segment ki KV cache reuse hoti hai; pehla different token aate hi baaki sab recompute hota hai. vLLM fixed-size blocks par kaam karta hai, sirf full blocks cache hote hain. Is page ne 2000-token document naapa: document pehle hone par request 1 ne 2020 tokens compute kiye, TTFT 4.1 s; baaki requests sirf 20 naye tokens, lagbhag 0.1 s; document ke pehle 8 har-baar-badalne wale tokens lagaane par cache ek baar bhi hit nahi, har baar 4.1 s।

### Concurrency badhane par single request dheemi kyun ho jaati hai?

Decode har step batch ki har sequence ke liye ek token compute karta hai; batch bada, step dheema. Is page ke measurement mein concurrency 1 se 16: per-step time lagbhag 25 ms se lagbhag 100 ms, per-request speed 40 se 10 token/s, total throughput 38 se 139 token/s. Throughput aur per-request speed ka trade-off hai: pehle per-user minimum token/s tay karein, phir concurrency cap nikaalein।

### llama.cpp server ke -np aur --kv-unified ka matlab?

-np slots (ek saath process hone wali requests) set karta hai, -c total context. --kv-unified ke bina total context har slot ko barabar bat jaata hai: -c 65536 -np 16 par har request max 4096 tokens, lambi requests reject (measured HTTP 400); --kv-unified ke saath sab slots ek hi KV cache share karte hain, wahi 6000-token request process ho gayi. CLI help kehta hai: -np specify na ho (auto) to unified KV default on hai।
