# LLM inference service: latency metrics, measurement aur engine selection

> Inference service ko first-token latency, token interval aur throughput ek saath manage karna hota hai. Yeh page llama.cpp se naapta hai ek request ka time kahan jaata hai, warm-up kyun zaroori hai, aur llama.cpp, Ollama, vLLM, SGLang ki positioning aur metrics compare karta hai।

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

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

- TTFT, TPOT, end-to-end latency aur throughput ki definitions batayein, aur ek formula se jodein।
- Samjhayein prefill compute-bound hai aur decode memory-bandwidth-bound, measured numbers se verify karein।
- Laptop par reproducible benchmark banayein: warm-up, alternating comparison, steady-state reporting।
- llama.cpp, Ollama, vLLM, SGLang ki positioning alag karein, aur inke expose kiye metrics padhein।
- Little's law se kitne concurrent slots aur kitni machines chahiye, estimate karein।

Inference service ka kaam ek hi hardware par kai requests ek saath serve karna hai: har user ko chahiye "kab se words aane lage" (TTFT) aur "words smooth aate hain ya nahi" (TPOT); operations ko dekhna hai per second total kitne tokens ban rahe hain (throughput). Yeh metrics ek-doosre ko kheenchte hain: batch jitna bada, throughput utna high, har user ka TPOT utna lamba. Yeh page pehle naapta hai ek request ka time kahan jaata hai, phir batata hai kaise naapein, engine kaise chunein, kaun se metrics dekhein; kai requests ko efficiently ek saath jodna [continuous batching aur PagedAttention](https://dmxsf.com/hi/wiki/inference/continuous-batching/) page par hai।

Is vishay se pehla sampark hai to pehle [pehla inference service](https://dmxsf.com/hi/wiki/inference/first-inference-service/) chalayein।

> [!NOTE] Experiment environment
> Is page aur [agle page](https://dmxsf.com/hi/wiki/inference/continuous-batching/) ke numbers ek hi machine se hain: MacBook Pro (Apple M2 Max, 12 CPU cores, 38 GPU cores, 64 GB unified memory, power se juda), llama.cpp ka `llama-server` (build 11146, commit 7fe450e19), model Qwen2.5-7B-Instruct ka Q4_K_M quantization (4.68 GB, Hugging Face `Qwen/Qwen2.5-7B-Instruct-GGUF` se). Alag hardware par absolute numbers alag honge; jo saath le jaana hai woh trend aur method hai. vLLM ko GPU chahiye, yeh machine chala nahi sakti - page ka vLLM content official docs aur papers se hai, is machine par run nahi kiya gaya।

## Ek request ka time kahan jaata hai

Ek generation request server mein teen phases se guzarti hai: **queue** (khaali slot ka intezaar), **prefill** (poora prompt ek saath parallel compute, pehla token banta hai), **decode** (har step ek token, jab tak khatam na ho)।

*Figure: Diagram ki lambai sirf illustrative hai. Prefill jitna lamba, TTFT utna bada; jitne zyada decode tokens, end-to-end latency utni badi।*

Isse chaar metrics bante hain:

| Metric | Matlab | Mainly kis se tay | User ka feel |
| --- | --- | --- | --- |
| TTFT (Time To First Token) | Request se pehla token milne tak | Queue time + prefill time | Kab se words aane lage |
| TPOT (Time Per Output Token), aka ITL (Inter-Token Latency) | Do paas wale output tokens ka gap | Ek decode step ka time: batch size, weights aur KV cache padhna | Words smooth hain ya nahi |
| End-to-end latency | Request se aakhri token tak | TTFT + N-1 TPOT | Poora jawab kitna intezaar |
| Throughput | Server ke per-second total tokens | Batch size aur scheduling | Per-unit cost |

Pehle teen ko formula likhein; output $N$ tokens:

$$
T_{\text{e2e}} = \underbrace{T_{\text{queue}} + T_{\text{prefill}}}_{\text{TTFT}} + (N-1)\,T_{\text{tpot}}
$$

TPOT strictly har step ka interval (ITL) hai; poore request ka average $T_{\text{tpot}}$ hai; vLLM ki monitoring mein dono alag metrics hain. Pehla token prefill ke ant mein banta hai, isliye baaki $N-1$ intervals hain।

## Experiment: ek request ko naapo

Pehle server up karein. Hugging Face se Q4_K_M ke do shards local download karein, pehle shard ka path `-m` ko dein; llama.cpp baaki shards khud padh leta hai:

```bash
llama-server -m qwen2.5-7b-instruct-q4_k_m-00001-of-00002.gguf \
  -c 8192 -np 1 --metrics --port 8089
```

`-c` context length hai, `-np` slots (ek saath process hone wali requests; agla page detail karega), `--metrics` Prometheus format `/metrics` on karta hai. Server OpenAI-compatible endpoint deta hai; `curl` se ek request:

```bash
curl -s http://127.0.0.1:8089/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{"messages": [{"role": "user", "content": "Please introduce the Great Wall in three sentences."}],
       "max_tokens": 80, "temperature": 0}'
```

Return hue JSON mein `usage` aur `timings` fields (excerpt, values 2 decimals tak) saare needed time de dete hain:

```json
"usage": {"prompt_tokens": 36, "completion_tokens": 68, "total_tokens": 104},
"timings": {
  "cache_n": 0,
  "prompt_n": 36,
  "prompt_ms": 124.41,
  "predicted_n": 68,
  "predicted_ms": 1034.66,
  "predicted_per_token_ms": 15.44,
  "predicted_per_second": 64.76
}
```

Note: yeh output original (Chinese-run) experiment se hai; misaal ke prompt text ko Hindi ke bajaye English sample mein badla gaya hai, numbers wahi hain।

`prompt_n` isi baar waqai compute hue prompt tokens, `cache_n` cache se reuse hue tokens (agle page par prefix caching). Prefill ne 36 tokens ko 124 ms liye - yehi TTFT ka main hissa hai; 68 output tokens 1035 ms, per token 15.44 ms, to end-to-end lagbhag $0.124 + 67 \times 0.0154 \approx 1.16$ seconds।

Dhyan: yeh decode speed 64.8 token/s hai. Aage ki steady measurement sirf 42 token/s ke aaspaas hai: abhi-abhi shuru hue "thande" machine par tez, sustained load par gir jaata hai. Yeh laptop ki khaasiyat hai - iska dedicated test thodi der baad।

Systematic measurement ke liye haath se `curl` kaafi nahi. Neeche wala client `aiohttp` se `/completion` ko streaming padhta hai aur client-side TTFT, TPOT plus server ke `timings` record karta hai; text WikiText-2 se hai, taaki har request ka prompt alag ho (accidental cache hit na ho). Yeh agle page ke sab experiments ka client bhi hai:

```python
import asyncio
import json
import statistics as st
import time

import aiohttp
import pandas as pd
from huggingface_hub import hf_hub_download

URL = "http://127.0.0.1:8089"
path = hf_hub_download("Salesforce/wikitext",
                       "wikitext-2-raw-v1/train-00000-of-00001.parquet",
                       repo_type="dataset")
text = "".join(pd.read_parquet(path)["text"])[:600_000]

async def post(s, route, body):
    async with s.post(URL + route, json=body) as r:
        return r.status, await r.json()

async def request(s, tokens, n_predict, t0, cache=False):
    # stream ek completion; client aur server dono ke times record karo
    body = {"prompt": tokens, "n_predict": n_predict, "temperature": 0,
            "ignore_eos": True, "stream": True, "cache_prompt": cache}
    sent = time.perf_counter()
    first = last = None
    async with s.post(URL + "/completion", json=body) as r:
        async for raw in r.content:
            line = raw.decode().strip()
            if not line.startswith("data:"):
                continue
            d = json.loads(line[5:])
            if d.get("content"):
                last = time.perf_counter()
                first = first or last
            if d.get("stop"):
                srv = d["timings"]
    n = srv["predicted_n"]
    return {"sent": sent - t0, "ttft": first - sent, "done": last - t0,
            "n": n, "tpot": (last - first) / max(n - 1, 1), "srv": srv}

async def start():
    # har request naya connection: server streaming response ka connection band karta hai
    s = aiohttp.ClientSession(
        connector=aiohttp.TCPConnector(force_close=True),
        timeout=aiohttp.ClientTimeout(total=3600))
    _, d = await post(s, "/tokenize", {"content": text})
    return s, d["tokens"]

def piece(toks, i, n):  # i-th length-n piece; sab pieces ke starts alag
    return toks[i * 2500: i * 2500 + n]

async def warm_up(s, toks, seconds):
    # laptop GPU shuru ke seconds mein sustained load se zyada fast:
    # pehle pressure daalo, speed stable hone do, phir naapo
    t0, i = time.perf_counter(), 0
    while time.perf_counter() - t0 < seconds:
        await request(s, piece(toks, i, 1024), 32, t0)
        i += 1
```

Isse alag prompt lengths naapein: har length par 3 requests ka median, har request 64 tokens generate karti hai।

```python
async def anatomy():
    s, toks = await start()
    seconds = {}  # prompt length -> prefill time (seconds)
    print("prompt  TTFT(s)  prefill(tok/s)  decode(tok/s)")
    for L in (32, 128, 512, 1024, 2048, 4096):
        rs = [await request(s, piece(toks, i, L), 64, time.perf_counter())
              for i in range(3)]
        med = lambda f: st.median(f(r) for r in rs)
        seconds[L] = med(lambda r: r["srv"]["prompt_ms"]) / 1000
        print(f"{L:>6} {med(lambda r: r['ttft']):8.2f} "
              f"{med(lambda r: r['srv']['prompt_per_second']):15.0f} "
              f"{med(lambda r: r['srv']['predicted_per_second']):14.1f}")
    await s.close()
    return seconds

PROMPT_SECONDS = asyncio.run(anatomy())
```

Output:

```text
prompt  TTFT(s)  prefill(tok/s)  decode(tok/s)
    32     0.13             256           40.9
   128     0.35             373           40.6
   512     1.10             469           42.3
  1024     2.18             470           42.3
  2048     4.16             495           40.8
  4096     8.50             484           38.7
```

नीचे का कंपोनेंट इस टेबल को खिंचने योग्य बनाता है: prompt length (log axis) खींचें और TTFT, prefill, decode speed का हिलना देखें; TTFT की डैश्ड लाइन हर row की अपनी prefill speed से L/v फिर गणना करती है——printed seconds से rounding में मेल।

Teen observations:

1. **TTFT lagbhag prompt length ke proportional hai.** 2048 tokens ko 4.16 s, 4096 tokens ko 8.50 s; TTFT lagbhag $L / v_{\text{prefill}}$ ($v_{\text{prefill}}$ prefill speed): $2048 / 495 \approx 4.14$ s - measurement se match. User lamba document upload karke poochta hai, to yehi kuch seconds ka intezaar hai।
2. **Prefill speed 470-495 token/s ke aaspaas saturate** hoti hai; 32 tokens ka chhota prompt sirf 256 token/s: prompt itna chhota hai ki compute bhar nahi paata, fixed overhead ka hissa bada ho jaata hai।
3. **Decode speed prompt lambe hone se lagbhag nahi badalti, sirf 4096 tokens par thodi girti hai** (42.3 se 38.7 token/s, lagbhag 9%). Decode har step weights ke saath existing tokens ki KV cache bhi padhta hai: 4096 tokens ki KV cache 224 MiB (algorithm agle page par), weights (4.68 GB) ka lagbhag 5% - direction aur magnitude dono match।

## Prefill aur decode: compute-bound vs bandwidth-bound

Prefill decode se dus guna zyada fast hai (lagbhag 470 vs 42 token/s) - wajah: dono alag resources se seemit hain:

- **Prefill** ek baar $L$ tokens process karta hai: weights ek baar padh kar $L$ tokens ke liye compute karta hai - kaam zyada, compute-bound. Prompt jitna bhi lamba, speed saturate - upar wala 470-495 token/s।
- **Decode** ek baar sirf 1 token process karta hai: weights phir bhi poore padhne padte hain, par sirf 1 token ka compute - memory-bound. Speed ceiling lagbhag bandwidth / weight size; poora derivation [GPU aur roofline model](https://dmxsf.com/hi/wiki/systems/gpu-and-roofline/) mein।

Is machine se verify: M2 Max ki memory bandwidth 400 GB/s (Apple ki numairee figure), model 4.68 GB, ceiling $400 / 4.68 \approx 85$ token/s. Measured steady speed 42 token/s - per second $4.68 \times 42 \approx 198$ GB padha, bandwidth ka lagbhag aadha; shuruati 64.8 token/s lagbhag 76%. Ceiling se door kyunki decode ko weights ke alawa attention, normalization aur sampling bhi karna hota hai, aur chhote batch ka kernel bandwidth poora kha nahi sakta।

Yeh rule kai cheezein explain karta hai: quantization (4-bit weights) se speed badhti hai mainly kyunki weights chhote - har step kam bytes (dekhein [model quantization](https://dmxsf.com/hi/wiki/inference/quantization/)); requests ko batch karna throughput badhata hai kyunki ek weight-read kai requests serve karta hai (dekhein [agle page](https://dmxsf.com/hi/wiki/inference/continuous-batching/)); speculative decoding "ek weight-read par kai tokens verify" karke bandwidth ka kharcha phailata hai (dekhein [speculative decoding](https://dmxsf.com/hi/wiki/inference/speculative-decoding/))।

## Laptop par benchmark: pehle warm-up

Laptop GPU ka power aur thermal limit hai; shuruati load par fast, thodi der sustained load par slow. Isse sirf kuch seconds ka benchmark optimistic ho jaata hai; aur bura yeh ki **jo config pehle chali woh "cold machine" ka fayda utha leti hai**. Neeche wala experiment client ko 90 seconds lagatar requests bhejne deta hai, har 15 seconds par summary:

```python
async def drift():
    s, toks = await start()
    t0 = time.perf_counter()
    rows, i = [], 0
    while time.perf_counter() - t0 < 90:  # ek request ke baad ek request
        r = await request(s, piece(toks, i, 1024), 64, t0)
        rows.append((r["sent"], r["srv"]["prompt_per_second"],
                     r["srv"]["predicted_per_second"]))
        i += 1
    print("seconds  prefill(tok/s)  decode(tok/s)  requests")
    for w in range(0, 90, 15):
        win = [r for r in rows if w <= r[0] < w + 15]
        print(f"{w:>3}-{w + 15:<3} {st.mean(r[1] for r in win):14.0f} "
              f"{st.mean(r[2] for r in win):14.1f} {len(win):9d}")
    await s.close()

asyncio.run(drift())
```

```text
seconds  prefill(tok/s)  decode(tok/s)  requests
  0-15             580           50.0         5
 15-30             508           43.7         5
 30-45             497           42.8         4
 45-60             495           42.5         4
 60-75             501           43.1         4
 75-90             498           42.2         5
```

Pehle 15 seconds: prefill 580 token/s, decode 50.0 token/s; 30 seconds tak lagbhag 495 aur 42.5 par stable - lagbhag 15% kam, phir nahi badalta. Maine yeh bhi naapa: 45-60 seconds ya zyada idle ke baad speed initial level par wapas; `-t` (CPU threads) default se 2 karne par koi farq nahi (model ka compute sab GPU par hai)।

Iske aadhar par, is page (aur agle page) ke sab experiments yeh rules maante hain:

1. **Pehle warm-up.** Har measurement se pehle client ke `warm_up` se 40+ seconds lagatar load, phir timing shuru।
2. **Alternating comparison.** A, B configs compare karte waqt A, B, A, B order mein do-do baar, pehle A poora phir B nahi।
3. **Steady-state numbers report karein.** Ya dono states report karein aur kaun sa kaun sa hai likhein।
4. **Environment record karein.** Machine model, power, model aur quantization, engine version (commit), prompt aur output length distribution, aur concurrency।

Doosre hardware par bhi similar problems (GPU downclocking, shared machines par doosre tasks ka interference, cloud burstable instances), sirf magnitude alag. Inference engines ke benchmark articles compare karte waqt pehle dekhein ki in conditions ka zikr hai: same model aur quantization, prompt length distribution, concurrency, sampling parameters; conditions alag to numbers comparable nahi।

## Engine kaise chunein

Aam open-source inference services yeh hain; table November 2026 mein padhe gaye official docs ke aadhar par:

| Engine | Positioning | Hardware | Concurrency aur cache | Quantization aur formats |
| --- | --- | --- | --- | --- |
| llama.cpp (`llama-server`) | Lightweight, portable; personal computers aur edge | CPU, Apple Metal, CUDA, Vulkan waghera; CPU+GPU mix ho sakta hai | Continuous batching (default), slots (`-np`), per-slot prefix reuse | GGUF, kai low-bit quantizations |
| Ollama | Out-of-the-box local model management aur serving | macOS, Windows, Linux; CPU aur GPU | `OLLAMA_NUM_PARALLEL` (default 1), queue limit `OLLAMA_MAX_QUEUE` (default 512) | Library mein mostly GGUF quantized |
| vLLM | GPU server par high-throughput online serving | NVIDIA, AMD, Intel GPUs aur kai CPUs; TPU, Gaudi hardware plugins bhi | PagedAttention, continuous batching, chunked prefill, prefix cache | FP8, INT8, INT4, GPTQ, AWQ, GGUF waghera |
| SGLang | High-throughput serving; prefix reuse aur structured output mein strong | GPU, TPU, NPU, CPU, Apple silicon | RadixAttention (radix-tree prefix cache), continuous batching (doni SGLang paper mein) | Official docs dekhein |
| TGI | Maintenance mode; naye projects ke liye nahi | Mostly GPU | Continuous batching | bitsandbytes, GPTQ, AWQ, FP8 waghera |

Kuch notes:

- **llama.cpp aur Ollama ka farq packaging ka hai**: Ollama llama.cpp ecosystem ke upar model library, auto load/unload aur REST API deta hai - easy use ke badle kuch low-level control chhota. Ollama mein parallel requests context ko parallel count se multiply kar deti hain (official FAQ misaal: 2K context, 4 parallel - actually 8K context); required memory `OLLAMA_NUM_PARALLEL x OLLAMA_CONTEXT_LENGTH` se badhti hai।
- **vLLM** upar wali mechanisms ko default behavior banata hai aur OpenAI-compatible server (`vllm serve <model>`) plus Prometheus metrics deta hai. Server start:

  ```bash
  vllm serve Qwen/Qwen2.5-7B-Instruct --max-model-len 8192
  ```

  Aam tuned parameters: `--max-model-len` (max context), `--max-num-seqs` (concurrent requests), `--max-num-batched-tokens` (per-step token budget), `--gpu-memory-utilization` (memory fraction); matlab [agle page](https://dmxsf.com/hi/wiki/inference/continuous-batching/) par. Yeh command is machine par run nahi kiya gaya; apne version ke docs ko final maanein।
- **SGLang** paper RadixAttention aur compressed finite state machine (structured output decoding ko tez karta hai) deta hai; vLLM se functionality overlap hai - dono ko apne workload par compare karne layak hai।
- **TGI**: Hugging Face ke README ke mutabiq maintenance mode mein - sirf chhote fixes aur docs; vLLM, SGLang, llama.cpp, MLX recommend।

Selection ko scene-wise karein:

| Scene | Pehle sochein |
| --- | --- |
| Personal computer, laptop, edge | llama.cpp ya Ollama |
| Chhoti team, kam concurrency, jaldi public API | Ollama, ya single-GPU vLLM |
| GPU server par multi-user online service | vLLM ya SGLang |
| Bahut repeated prompt prefixes (Agent, RAG, multi-turn), structured output chahiye | SGLang, ya prefix-caching-on vLLM |

Jo bhi chuno, launch se pehle apne workload par ek baar test karein - **model version, quantization format, prompt aur output length distribution, concurrency, sampling parameters sab same rakhein, aur tokenizer aur chat template identical hona chahiye**; same model template badalne par output achanak bura ho sakta hai - woh engine ki galti nahi hai।

## Kya monitor karein

Service live hone ke baad metrics chaar categories mein hain. Do engines ke naam alag, matlab same jaise:

| Category | vLLM (Prometheus) | llama-server (`--metrics`) |
| --- | --- | --- |
| Latency | `vllm:time_to_first_token_seconds`, `vllm:inter_token_latency_seconds`, `vllm:e2e_request_latency_seconds`; breakdown: `vllm:request_queue_time_seconds`, `vllm:request_prefill_time_seconds`, `vllm:request_decode_time_seconds` | Har response ka `timings`; aggregate: `llamacpp:prompt_tokens_seconds`, `llamacpp:predicted_tokens_seconds` |
| Load | `vllm:num_requests_running`, `vllm:num_requests_waiting` | `llamacpp:requests_processing`, `llamacpp:requests_deferred` |
| KV cache | `vllm:kv_cache_usage_perc`, `vllm:num_preemptions`, `vllm:prefix_cache_hits` aur `vllm:prefix_cache_queries` | `llamacpp:prompt_tokens_cached_total` (reused prompt tokens) |
| Throughput | `vllm:prompt_tokens`, `vllm:generation_tokens`, `vllm:request_success` (finish reason ke hisaab se) | `llamacpp:prompt_tokens_total`, `llamacpp:tokens_predicted_total` |

vLLM ke metric names November 2026 ke latest docs ke mutabiq; versions mein farq ho sakta hai - apne version ke `/metrics` output ko final maanein. Latency metrics mein averages nahi, percentiles (p50, p95, p99) dekhein: kuch bahut lambi requests tail ko bahut upar le jaati hain, average mein dikhta nahi।

Problem aaye to neeche wali table se type karke troubleshoot karein (TTFT slow, throughput low, tail bura aur memory kam - aksar ek hi problem nahi):

| Symptom | Pehle dekhein | Aam kaaran | Action |
| --- | --- | --- | --- |
| First token slow | TTFT ko queue aur prefill mein todo | Queue: concurrency > slots; prefill: prompt lamba, prefix cache miss | Input length limit; stable content pehle rakho (prefix hit ke liye); scale out ya rate limit |
| Output stutter (TPOT bada, jitter) | Token interval percentiles; same batch mein lambi prompt ka prefill? | Batch bada; prefill chunk bada, decode kar rahi requests ko interrupt karta hai | Concurrency cap kam, per-step token budget chhota (chunked prefill) |
| Throughput kam, machine khaali | Running requests, batch size | Concurrency kam; length variance bada par static batching | Continuous batching on, concurrency cap badhao |
| Queueing zyada, KV cache usage high, preemptions baar-baar | `kv_cache_usage_perc`, `num_preemptions` | KV cache kaafi nahi | Max context aur concurrency kam, memory fraction badhao, quantize, parallelism badhao |
| p99 bura par average normal | Request length distribution, e2e latency percentiles | Kuch bahut lambi requests queue drag karti hain | Input/output length limit, timeout aur cancellation, lambi requests ko alag route |

## Request traces se goodput nikaalna

[CMU ML Systems ki do LLM serving lectures](https://mlsyscourse.org/schedule) batching+cache aur speculative decoding cover karte hain. In optimizations ko compare karte waqt [DistServe](https://arxiv.org/abs/2401.09670) se le sakte hain: pehle first-token latency aur average per-output-token time ke liye alag-alag SLO define karein. Fixed time window ke liye **goodput** = successful requests jo dono SLO satisfy karte hain, divided by window length. Max load stress test karte waqt acceptable goodput ratio bhi agree karna padta hai, aur arrival rate tier-by-tier badhana hota hai।

Neeche is site ki khud banayi do traces hain. Assume: same window mein same requests bheji, sab complete ya timeout; har completed request ke kam se kam 2 output tokens. Apple M2 Max aur Python 3.14.3 par run; sirf standard Python।

```python
# har row (completed?, TTFT ms, TPOT ms).
traces = {
    "baseline": [(True, 90, 15)] * 5 + [(True, 130, 25)] * 3
        + [(False, None, None)] * 2,
    "candidate": [(True, 80, 15)] * 4 + [(True, 95, 25)] * 6,
}
window_seconds = 2
ttft_limit, tpot_limit = 100, 20

def rates(requests):
    completed = sum(ok for ok, _, _ in requests)
    within_slo = sum(
        ok and ttft <= ttft_limit and tpot <= tpot_limit
        for ok, ttft, tpot in requests
    )
    return completed / window_seconds, within_slo / window_seconds

baseline, candidate = map(rates, traces.values())
assert candidate[0] > baseline[0] and candidate[1] < baseline[1]
for name, requests in traces.items():
    throughput, goodput = rates(requests)
    print(f"{name}: {throughput:.1f} req/s, {goodput:.1f} good req/s")
```

```text
baseline: 4.0 req/s, 2.5 good req/s
candidate: 5.0 req/s, 2.0 good req/s
```

Note: numbers original run se hain; print labels Latin transliteration mein likhe gaye hain।

Candidate config zyada requests complete karti hai, par SLO-within requests kam - kyunki zyada-tar completed requests TPOT limit paar karti hain. Real comparison mein arrival times, input/output length distributions, sampling config aur model quality standard fix karein; alag se goodput ratio, timeouts aur per-length slices report karein. [Prefix caching aur PD separation](https://dmxsf.com/hi/wiki/inference/prefix-caching/) ka research karte waqt cold/warm cache aur cross-node transfer alag naapein।

## Capacity planning: concurrency, latency aur machines

"Kitni machines" ka estimate **Little's law** se: steady state mein system mein maujood requests $L$ = per-second arrivals $\lambda$ x average dwell time $W$:

$$
L = \lambda W
$$

Dwell time $W$ upar wali end-to-end latency hai, aur woh concurrency par nirbhar hai: concurrency zyada, per-request speed kam, dwell lamba. Isliye iterative calculate: pehle product per-user minimum speed tay kare (jaise kam se kam 17 token/s - sirf misaal ko aasaan banane ke liye), phir measured "concurrency vs per-request speed" curve (agle page ka concurrency experiment) se ek machine kitne requests ek saath serve karti hai dekhein, $W$ nikaalein, aakhir mein total concurrency aur machine count. Yeh misaal neeche exercises ke liye chhoda; data agle page ke measured curve se।

## Alerts se ek live degradation locate karna

[CMU Machine Learning in Production ki operations planning chapter](https://mlip-cmu.github.io/book/13-planning-for-operations.html) observability aur updatability ko system design mein rakhta hai. Deployment checklist, request traces aur user-task metrics ko jodkar alert ke baad phenomenon se specific phase tak trace kiya ja sakta hai।

Maan lo ek knowledge-base assistant ne naya index launch kiya, aur customer-support resolution rate gir gaya. Pehle deployment version aur question type ke hisaab se dekhein failures kahan concentrate hain, phir same requests replay karein. Agar evidence-wale sawaal bade paimane par evidence nahi pa rahe, to document freshness, index version aur retrieval results dekhein. Evidence maujood ho par final citations galat hon, to prompt assembly, context truncation aur generation dekhein. Agar requests incomplete hain, to queue, first-token aur decode time alag karein, timeouts aur rejected requests ki ginti bhi dekhein. Sirf completed responses ginne se sabse serious failures ka hissa hi chhut jaata hai।

| Dekha hua signal | Kis evidence se scope chhota karein | Recovery ke baad kaise confirm |
| --- | --- | --- |
| Tool-call timeouts badhe | Same trace ID ke upstream latency, retries aur final state | Fixed tasks replay karke success rate aur duplicate side-effects check |
| Naye version ki retrieval coverage giri | Same queries par naye/purane index ke evidence farq, doc time aur language se group | Compatible index/config restore karke independent samples se coverage re-test |
| First token slow, generation speed stable | Input length, queue, prefill aur cache-hit tokens saath compare | Same arrival distribution se har load tier ka goodput naapo |

Yahan ke signals hypothesis banane ke liye hain. Agar candidate version aur traffic distribution ek saath badle, to pehle fixed-traffic replay ya controlled rollout se do changes alag karein, phir rollback, scale-out ya data-fix decide karein. Cause-differentiating failure samples ko [eval set](https://dmxsf.com/hi/wiki/evaluation/building-eval-sets/) mein le jaayein, aage ke fixes verify karne ke liye।

## Launch se pehle ki checklist

"Chal raha hai" aur "launch-layak" ke beech ek engineered set of work hota hai. Pehli baar LLM service doosron ko dene se pehle kam se kam:

- Model version, quantization format aur config fix, plus ek fixed regression sample set (launch aur rollback par output quality compare karne ke liye)।
- Standard input/output protocol (jaise OpenAI-compatible), ek unified chat template।
- Health check endpoint; kharab instances ko traffic se nikaalna।
- Request timeout aur cancellation, input length limit, rate limit ya queue limit (limit paar par fast-fail, infinite queue nahi)।
- Request logs aur error logs - kisi slow request ko trace kiya ja sake; upar wali table ke metrics monitoring aur alerts mein।
- Rollback plan: naya model, naya quantization format, naya engine launch par purane version par jaldi switch ho sake।

## Summary aur exercises

**Is page ke mukhya points:**

1. Ek request ka time queue + prefill + decode: $T_{\text{e2e}} = \text{TTFT} + (N-1)\,T_{\text{tpot}}$; TTFT = queue + prefill।
2. Prefill compute-bound, speed lagbhag 470-495 token/s, TTFT prompt length ke proportional; decode bandwidth-bound, har token par weights padhe, ceiling lagbhag bandwidth / weight size।
3. Laptop sustained load par shuru se lagbhag 15% dheema: measure se pehle 40+ seconds warm-up, alternate comparison, steady-state report।
4. Personal/edge: llama.cpp ya Ollama; GPU server online: vLLM ya SGLang; TGI maintenance mode mein।
5. Chaar metric categories monitor: latency (queue/prefill alag, percentiles), load, KV cache, throughput; capacity Little's law se।

### Quick self-test

**1. First-token latency (TTFT) mainly kis se banta hai?**

- [ ] Decode phase ke har token ke times ka sum
- [x] Queue time + prefill time
- [ ] Network round-trip time
- [ ] Model load time

> Pehla token prefill ke ant mein banta hai, isliye TTFT = queue + prefill।

**2. Prompt 512 se 4096 tokens karne par, is page ke experiment mein TTFT lagbhag kaise badla?**

- [ ] Lagbhag same
- [x] Lagbhag 8x, 1.10 s se 8.50 s
- [ ] Lagbhag 2x
- [ ] Chhota ho gaya

> Prefill speed 470-495 token/s par saturate hai; TTFT prompt length ke lagbhag proportional hai।

**3. Decode phase bandwidth-bound kyun kehte hain?**

- [ ] Kyunki decode mein bahut zyada matrix multiplications hote hain
- [x] Har generated token ke liye saare weights memory se padhne padte hain, par compute sirf ek token ka hota hai
- [ ] Kyunki decode CPU par chalta hai
- [ ] Kyunki decode ko internet chahiye

> Compute chhota, reading badi - speed ceiling lagbhag bandwidth / weight size।

**4. Laptop par do configs ki speed compare karne ka sabse reasonable tareeka?**

- [ ] Har ek 5 seconds, average le lo
- [ ] Pehle A poora, phir B poora
- [x] Pehle warm-up, phir A, B, A, B order mein alternate, steady-state numbers report karo
- [ ] Sirf sabse tez wala run gin lo

> Shuruati load par machine fast hoti hai; pehle chalane wala config fayda leta hai; alternate + warm-up se hi yeh bias khatam hota hai।

**5. Har request system mein average 12 seconds rehti hai, per second 0.5 requests aati hain; steady state mein average kitne requests ek saath?**

- [ ] 0.5
- [ ] 12
- [x] 6
- [ ] 24

> Little's law: $L = \lambda W = 0.5 \times 12 = 6$।

**Exercises:**

1. Is page ke data se estimate: 3000-token prompt, prefill speed 485 token/s, output 200 tokens, decode speed 42 token/s, koi queue nahi. TTFT aur end-to-end latency kitne?
2. User kehta hai "shuru mein bahut intezaar ke baad words aaye" aur doosra kehta hai "words beech-beech mein atakte hain" - dono ke liye pehle kaun sa metric dekhna chahiye? Har ek ka ek common kaaran aur ek upay batayein।
3. Ek GPU jiski memory bandwidth 3.35 TB/s, Qwen2.5-7B (7.616B parameters) chalata hai. Weights FP16 mein, aur is page ke Q4_K_M (4.68 GB) mein - single request ki decode speed ceiling kitni? Yeh ceiling sirf ceiling kyun hai?
4. Requirement: har user ko kam se kam 17 token/s; har request average 200 output tokens; peak par per second 0.8 requests. [Agle page](https://dmxsf.com/hi/wiki/inference/continuous-batching/) ke measured concurrency experiment (concurrency 4 par per-request 17.3 token/s, average TTFT 0.47 s; concurrency 6 par 12.2 token/s) se estimate: ek machine max kitni requests ek saath? Har request kitni der rehti hai? Kitni machines chahiye?
5. Ek article kehta hai "engine X engine Y se 30% faster hai". Yeh number trustworthy hai ya nahi - kam se kam chaar sawaal poochhiye।

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

1. TTFT $= 3000 / 485 \approx 6.19$ s; end-to-end $= 6.19 + 199 / 42 \approx 10.9$ s. Prefill aadhe se zyada leta hai; lambe prompts par optimization ka focus TTFT (prefix caching, prompt chhota karna)।
2. "Bahut intezaar ke baad words" - TTFT dekhein, aur queue vs prefill mein todo: queue lamba = concurrency > slots, scale out ya rate limit; prefill lamba = prompt lamba ya prefix miss, input chhota karein, stable content pehle. "Beech-beech atakte" - token interval (TPOT/ITL) percentiles: aam kaaran batch bada ya prefill chunk bada jo decode interrupt karta hai; upay concurrency cap kam ya per-step token budget chhota।
3. Decode har token par weights padhta hai; ceiling lagbhag bandwidth / weight size. FP16: $7.616 \times 10^9 \times 2 = 15.2$ GB, $3350 / 15.2 \approx 220$ token/s; Q4_K_M: $3350 / 4.68 \approx 715$ token/s, lagbhag 3.3x. Sirf ceiling: actually attention (KV cache padhna), normalization aur sampling bhi, aur kernel bandwidth poora nahi khaata; is page ka M2 Max bandwidth ceiling ka lagbhag aadha hi nikla।
4. Concurrency 4 par per-request 17.3 token/s - abhi bhi 17 se kam nahi; concurrency 6 par 12.2 - fail, isliye ek machine max 4 requests. Dwell $W \approx 0.47 + 200 / 17.3 \approx 12.0$ s. Total concurrency $L = \lambda W = 0.8 \times 12.0 \approx 9.6$; har machine 4, chahiye $\lceil 9.6 / 4 \rceil = 3$ (do machines sirf 8 concurrency slots, kam). Ek machine ka handle karne wala arrival rate $4 / 12.0 \approx 0.33$ requests/second।
5. Misal ke liye: (1) model, quantization, hardware, engine version same hain? (2) prompt/output length distribution aur concurrency same hain; single-request speed compare ho rahi hai ya total throughput? (3) warm-up hua tha; steady-state numbers hain; alternating run kiya? (4) average dekha ya percentiles (p95, p99); sampling parameters aur chat template same hain?

</details>

## Aage padhein

- Is page ka experiment environment, client aur measurement method [continuous batching aur PagedAttention](https://dmxsf.com/hi/wiki/inference/continuous-batching/) mein bhi use hote hain: concurrency scan, continuous batching comparison, KV cache paging aur prefix caching।
- vLLM docs: [Production Metrics](https://docs.vllm.ai/en/latest/usage/metrics.html) (metric names aur matlab), [Optimization and Tuning](https://docs.vllm.ai/en/latest/configuration/optimization.html)।
- Kwon adi, [Efficient Memory Management for Large Language Model Serving with PagedAttention](https://arxiv.org/abs/2309.06180)।
- Zheng adi, [SGLang: Efficient Execution of Structured Language Model Programs](https://arxiv.org/abs/2312.07104)।
- Official repo notes: [llama.cpp llama-server](https://github.com/ggml-org/llama.cpp/tree/master/tools/server), [Ollama FAQ](https://github.com/ollama/ollama/blob/main/docs/faq.mdx), [TGI README](https://github.com/huggingface/text-generation-inference)।
- Related pages: [KV cache aur inference performance](https://dmxsf.com/hi/wiki/inference/kv-cache/), [model quantization](https://dmxsf.com/hi/wiki/inference/quantization/), [speculative decoding](https://dmxsf.com/hi/wiki/inference/speculative-decoding/); MoE deployment ki khaasiyat (total params memory tay karte hain, active params per-token compute): [Mixtral of Experts paper](https://arxiv.org/abs/2401.04088)।

- Wu adi, [FastServe](https://arxiv.org/abs/2305.05920) (2023) aur Sun adi, [Llumnix](https://arxiv.org/abs/2406.03243) (2024): skip-join scheduling aur dynamic request migration - queue ki head-of-line blocking kam।
- Ong adi, [RouteLLM](https://arxiv.org/abs/2406.18665) (2024): strong aur weak models ke beech query routing - acceptable quality loss ke badle cost bachat।
- Aage ka cache reuse aur prefill/decode separation: [prefix caching aur PD separation](https://dmxsf.com/hi/wiki/inference/prefix-caching/)।
- [Production evaluation](https://dmxsf.com/hi/wiki/evaluation/production-evaluation/)

## सहायक कोड

[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)

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

### Inference service ki sabse important latency metrics kaun si hain?

Teen: first-token latency TTFT (request se pehla token tak; queue + prefill), token interval TPOT (ITL bhi kehte hain; do paas wale tokens ke beech ka gap; output smooth hai ya nahi), aur end-to-end latency (TTFT + N-1 TPOT, N output tokens). Saath mein server ka total throughput (per-second tokens). TTFT mainly prompt length aur queue se, TPOT mainly batch size aur KV cache reads se - alag dekhein।

### llama.cpp, Ollama, vLLM, SGLang kaise chunein?

Personal computer, laptop, edge devices: llama.cpp ya uske upar bana Ollama - rich quantization formats, CPU+GPU mix, ek command se server. GPU server par multi-user online service: pehle vLLM ya SGLang sochein - continuous batching, paged KV cache, prefix cache, bahut zyada throughput. Yeh sirf pehla round hai; apne prompt-length distribution, concurrency aur hardware ke saath load test karein।

### TGI (Text Generation Inference) abhi bhi use karne layak hai?

Hugging Face TGI repo ke README mein likhta hai ki woh maintenance mode mein hai - sirf chhote bug fixes, docs improvements aur light maintenance; vLLM, SGLang aur llama.cpp, MLX jaise local engines recommend karta hai (November 2026 mein padha gaya). Existing TGI deployments chal sakte hain; naye projects vLLM ya SGLang se shuru karein।

### Laptop par benchmark karte waqt shuru ke seconds ki speed baaki se alag kyun?

Laptop shuruati load par steady load se zyada fast hota hai. Is page ka M2 Max pehle 15 seconds mein prefill 580 token/s, decode 50.0 token/s, phir lagbhag 495 aur 42.5 token/s par stable - lagbhag 15% kam; lagbhag ek minute idle ke baad wapas recover. Isliye har measurement se pehle kam se kam 40 seconds warm-up, configs compare karte waqt alternate run (A, B, A, B), aur steady-state numbers report karein।

### Kitne concurrent slots ya kitni machines chahiye, kaise estimate karein?

Little's law: steady state mein system mein maujood requests = per-second arrivals x average time ek request system mein rehti hai. Dwell time = queue + prefill + output tokens / per-request speed. Pehle per-user minimum token/s tay karein, phir measured "concurrency vs per-request speed" curve se ek machine kitne requests serve kar sakti hai dekhein, aakhir mein dwell time se total concurrency nikaalein।

### Inference service launch ke baad kaun se metrics monitor karna zaroori?

Kam se kam chaar categories: latency (TTFT, token interval, e2e latency ke p50/p95/p99; queue aur prefill time alag), load (running vs queued requests), KV cache (usage, preemptions, prefix cache hit rate), throughput aur errors (tokens/s, timeout aur failure ratio). Inke bina queue, prefill, oversized batch ya memory shortage alag nahi ho sakta।
