अध्याय 7 · Inference aur deployment 7.4
Prefix caching aur PD separation: repeat computation ek hi baar
Prefix caching system prompt, multi-turn history aur shared docs ki KV cache requests ke beech reuse karta hai; RadixAttention aur LMCache reuse ka organization solve karte hain. PD separation prefill aur decode ko alag hardware par rakhta hai - kab faydemand, DistServe batata hai।
यह पृष्ठ पूरा करने पर आप
- Batayein kaun si requests ki KV cache requests ke beech reuse ho sakti hai, aur hit rate kis par nirbhar hai।
- Samjhayein prefix caching prefill ka zyada tar compute kyun bachaata hai, aur parameter count se bachat estimate karein।
- RadixAttention, CacheBlend, Prompt Cache aur LMCache har ek kaun si problem solve karta hai, compare karein।
- Samjhayein prefill aur decode ke resource profiles alag kyun hain, aur PD separation ka fayda aur keemat kya hai।
- Batayein PD separation kab faaydemand nahi, aur chunk prefill jaise madhyam raaste kya hain।
इस पृष्ठ पर
- Problem ka background: requests ke beech computation repeat hoti hai
- Prefix caching ke organization ke tareeke
- RadixAttention: prefix tree se reusable cache manage karna
- CacheBlend: poora reuse nahi, merge
- Prompt Cache aur CacheGen: offline aur transport
- LMCache aur Mooncake: cache cluster-level infrastructure ban jaata hai
- Hit rate schedulable hai: Preble aur AdaServe
- PD separation: do phases, do resource profiles
- Kab faaydemand nahi
- Experiment: cache hit aur queue ki takkar
- Summary aur exercises
- Quick self-test
- Exercises
- Aage padhein
- अक्सर पूछे जाने वाले सवाल
Agar aap samajh chuke hain ki KV cache ek request ke andar repeat computation kaise bachata hai, to yeh page uske do natural extensions hain: cache ko requests ke beech reuse karna (prefix caching), aur cache ke charon or poora inference cluster phir se organize karna (PD separation). 2024 ke baad inference systems ki do sabse badi engineering lines yahi hain।
Problem ka background: requests ke beech computation repeat hoti hai
Asli traffic mein alag requests ka bade prefixes share karna exception nahi, rule hai:
- Ek hi app ke saare requests ek hi system prompt le jaate hain (dazan se hazaar tokens)।
- Multi-turn chat mein har turn saara purana history dobara server ko bhejta hai।
- Customer support, coding assistant jaise scenarios mein ek documents ka set ya wahi few-shot examples baar-baar aate hain।
Prefix cache na ho to har request shared prefix ka prefill shuru se karta hai. Llama 3.1 8B-scale model (lagbhag 8B parameters, 32 layers, 8 KV heads) se estimate: 32 requests, har ek mein 1000-token shared system prompt + 200-token apna sawaal - bina cache prefill lagbhag 616.7 TFLOPs; 1000-token prefix sirf ek baar compute karne par lagbhag 118.8 TFLOPs, 80.7% bachat. Is shared prefix ki KV cache khud sirf lagbhag 125 MiB (FP16) - bahut chhoti memory ke badle bahut badi compute bachat।
Yeh same code ka output hai; koi bhi model config se dobara nikaal sakte hain:
N = 8.03e9 # parameter count (approx 8B)
shared, per_req, B = 1000, 200, 32 # shared prefix / per-request unique / requests
fpt = 2 * N # forward FLOPs per token approx 2N
before = B * (shared + per_req) * fpt
after = (shared + B * per_req) * fpt
print(f"bachat {(1 - after/before)*100:.1f}%") # 80.7%
Neeche widget is hisaab ko khud compute karne layak bana deta hai: shared prefix, har request ka unique hissa aur request count drag karke dekho saving ceiling S/(S+U) kaise paas jati hai, aur cached prefix kitni memory leta hai.
Note: is estimate ki shart - cache hit par prefix ka prefill poora skip hota hai. Kaun se prefixes store karne layak hain, kitne der, kaun hit karega - yehi prefix caching system ke sawaal hain।
Prefix caching ke organization ke tareeke
RadixAttention: prefix tree se reusable cache manage karna
vLLM ka automatic prefix caching block-level hash matching karta hai; sirf wahi prefix hit hota hai jo stored blocks se exactly aligned ho. SGLang ka RadixAttention ek kadam aage: saare requests ke prefixes ko ek radix tree mein organize karta hai - tree ke edges token sequences hain, nodes par corresponding KV cache latki hai. Naya request aaye to tree par longest common prefix match hota hai; hit hua hissa direct reuse, miss wali fork compute hoti hai; request khatam hone par uska prefix tree mein reh jaata hai aage wali requests ke liye, aur LRU jaisi policy cold nodes ko evict karti hai. Multi-turn chat aur shared system prompts jaise complex prefix relations wale workloads par tree structure block-list se bahut zyada hit karta hai।
CacheBlend: poora reuse nahi, merge
Bahut RAG scenarios ka repeat prefix hai “system prompt + documents + sawaal”, jismein documents ka order badal jaata hai ya kuch documents badal jaate hain - poore prefix ka hash match nahi hota. CacheBlend ki observation: KV cache ki position-sensitivity mainly attention output mein hoti hai; kai alag-cached KV ko seedha concatenate karna halke attention bias laata hai. Iska tareeka: concatenate karne ke baad sirf kuch layers, kuch tokens par thoda recompute karke us bias ko theek karna - bahut kam keemat par inexact prefix ka reuse।
Prompt Cache aur CacheGen: offline aur transport
Do aur directions yeh solve karte hain ki “cache kahan se aaye, kaise le jaaye”:
- Prompt Cache (2023): lambe fixed prompts (jaise few-shot examples) ki KV offline precompute karke distribute karo; user sirf badalne wali tail upload kare, cloud poore fixed segment ka prefill skip kare।
- CacheGen KV cache ko ek compressed-transfer data samajhta hai: custom encoder se KV ko bahut chhota karke edge se datacenter jaise bandwidth-limited links par bhejna - “KV cache ek transferable asset hai” yeh idea poora bolta hai।
LMCache aur Mooncake: cache cluster-level infrastructure ban jaata hai
Jab inference cluster mein prefill aur decode alag deploy hue, to cache kisi ek GPU ki memory mein lock nahi rehna chahiye. LMCache KV cache ko ek independent storage layer banata hai jo processes aur nodes ke beech share hoti hai (GPU memory, CPU memory, disk tiering); vLLM, SGLang engines read-write kar sakte hain. Mooncake (Moonshot AI ka production architecture) isko extreme tak le jaata hai: yeh KVCache-centric distributed inference architecture hai, jismein “cache kahan rahe, prefill kahan ho, decode kahan chale” ek unified scheduling problem hai।
Hit rate schedulable hai: Preble aur AdaServe
Prefix caching ka fayda hit rate par hai, aur hit rate sirf workload se nahi aati. Preble cache-aware routing se request us node par bhejta hai jahan uska prefix hit hone ka sabse zyada chance hai; AdaServe “request kaun se GPU par, kaun si parallelism” ko SLO (latency constraints) ke saath jointly optimize karta hai - cache hit aur service level dono ek saath. General lesson: cache system ka aadha kaam storage mein, aadha scheduling mein।
PD separation: do phases, do resource profiles
Prefill aur decode ke resource characteristics lagbhag complementary hain:
| Phase | Compute profile | Limited resource | Latency metric |
|---|---|---|---|
| Prefill | Poora input ek saath, bade matrices, high parallelism | Compute (compute-bound) | TTFT (first token latency) |
| Decode | Token-by-token, chhote matrices, kai steps | Memory bandwidth (bandwidth-bound) | TPOT (per token latency) |
Inko same GPUs par mix karne se do problems aati hain jo ek-doosre ko nuksaan deti hain: lambi request ka prefill us GPU ki saari decode block karta hai (TPOT spikes); decode-optimized low-parallelism config prefill ka compute bharta nahi. PD separation (Prefill/Decode Disaggregation) ka tareeka: dono phases alag instance groups par; request pehle prefill instance par poora input compute karti hai, KV cache network se decode instance ko jaata hai wahan token-by-token generation hoti hai; dono sides apne-apne scale aur tune hote hain।
Representative systems:
- DistServe (2024): separation ka systematic justification; “goodput” - TTFT aur TPOT dono constraints satisfy karne wala request throughput - se dikhaya mixed deployment high load mein ek-doosre ko disturb karta hai, separation ke baad har SLO tier par goodput kaafi badhta hai; separation ki keemat (KV transfer aur memory redundancy) bhi quantify ki।
- Splitwise (2023): cost ke angle se; prefill instances zyada compute/memory ratio wale “compute-type” hardware le sakte hain, decode instances zyada bandwidth wale “memory-type”; separation khud hi paisa bachati hai।
- Mooncake (2024): production-grade separated architecture, KVCache-centric scheduling, bahut lambe context ki high concurrency service।
Kab faaydemand nahi
PD separation free nahi: cross-node KV transfer network khata hai, scheduling ko do instance pools manage karne padte hain, aur prefix cache ki locality separation se kharab ho sakti hai (isliye Mooncake cache layer ko first-class citizen banata hai). Halki load, even-length requests, ya tight network bandwidth par colocate + chunk prefill (Sarathi-Serve: lambe prefill ko chhote chunks mein tod kar decode steps ke beech daal dena; block na ho, separation bhi na karni pade) aksar aasaan aur effective hai. 2026 ka research (jaise “When Does Disaggregation Pay?”) separation ke break-even boundary ko aur refine kar raha hai - separate karna hai ya nahi, apne workload profile se decide karein, architecture fashion se nahi।
Experiment: cache hit aur queue ki takkar
Preble batata hai ki distributed scheduling ko prefix reuse aur compute load spread dono chahiye. Ek chalane-layak simplified model se dekhein kab dono takraate hain. Maan lo do workers har baar ek request lete hain; sirf pehla warm hai; saare requests ek hi prefix share karte hain. Cold request complete karne ke baad woh worker bhi prefix reuse kar sakta hai. Fixed hit aur miss times first token ki service time hain. Simulation decode, cross-node KV transfer aur cache eviction ignore karta hai।
Hamesha warm worker ko bhejne, aur estimated earliest prefill-finish wale worker ko chunne ki tulna. Doosri strategy ki estimate queue time + is baar ka compute time hai. Queue mein pade same prefix is request shuru hone se pehle warm ho jaata hai. Neeche ki trajectories aur times demonstration values hain; Apple M2 Max aur Python 3.14.3 se nikaale gaye।
from statistics import median
requests = [0, 0, 0, 1, 2, 20]
hit_ms, miss_ms = 4, 11
def replay(cache_only):
free_at = [0, 0]
cached = [True, False]
latency = []
hits = 0
for arrive in requests:
finish = [
max(arrive, available) + (hit_ms if have_prefix else miss_ms)
for available, have_prefix in zip(free_at, cached, strict=True)
]
first_to_finish = min(range(len(finish)), key=finish.__getitem__)
worker = 0 if cache_only else first_to_finish
hits += cached[worker]
cached[worker] = True
free_at[worker] = finish[worker]
latency.append(finish[worker] - arrive)
return hits, median(latency), max(latency)
affinity, earliest = replay(True), replay(False)
assert earliest[0] < affinity[0] and earliest[2] < affinity[2]
for name, (hits, p50, worst) in zip(
('sirf hits dekho', 'latency estimate'), (affinity, earliest), strict=True
):
print(f"{name}: hits={hits}, p50={p50:g} ms, max={worst} ms")
sirf hits dekho: hits=6, p50=10 ms, max=18 ms
latency estimate: hits=5, p50=9.5 ms, max=13 ms
Note: yeh output numbers original run se hain; print labels Hindi/Latin transliteration mein likhe gaye hain।
Neeche widget is replay ko timeline ki tarah draw karta hai: dono policies ke beech switch karo aur dekho kaun sa worker har request chalata hai, hit ya miss — hits aur sabse dheemi latency bayen taraf hain.
Is burst mein ek cold compute accept karne se baaki requests bant jaati hain - hits kam, par sabse dheemi request jaldi. Arrival times ko evenly spaced kar dein to warm worker agli arrival se pehle pichhli request nipta deta hai, aur dono strategies warm cache ko pehle chunti hain. Burst aur sparse load ko compare karte waqt pehle queue ke baad ki first-token latency compare karein, phir hit rate. Real scheduling mein miss tokens, pending queue, memory level aur transfer cost estimate karne padte hain; alag loads par hit tokens, TTFT aur goodput alag-alag report karein।
Summary aur exercises
- Prefix caching requests ke beech ki repeat prefill ko “sirf ek baar” banata hai: is page ke bade-shared-prefix misaal mein estimated prefill compute lagbhag 80.7% bacha; keemat cache memory aur scheduling complexity hai।
- Organization ka safar block hash (vLLM) se radix tree (SGLang RadixAttention) phir cross-node cache layer (LMCache, Mooncake) tak - single engine se cluster-level infrastructure ka evolution।
- PD separation prefill aur decode ke complementary resource profiles se aayi hai; fayda goodput aur cost dono se naapo, separation karne ki faisla workload se।
Quick self-test
1. Ek workload jiske saare prefixes lagbhag overlap nahi karte, uske liye prefix caching on karne par sabse pehle kya hoga?
- Hit rate zero ke paas, cache faltu memory ghiregi, prefill compute lagbhag nahi bachega
- Prefill compute aadha bachega
- Decode bandwidth-bound ho jaayega
Prefix caching ka fayda poora hit rate se aata hai. Bina shared prefix ke traffic ke stored blocks kabhi hit nahi honge - sirf eviction aur management ka overhead bachega।
2. 32 requests, 1000-token shared prefix, har ek mein 200-token unique content (8B model); prefix ek baar compute karne se lagbhag kitna prefill bachega?
- Lagbhag 20%
- Lagbhag 80%
- Lagbhag 50%
Is page ka arithmetic: 616.7 TFLOPs se 118.8 TFLOPs, 80.7% bachat. Formula: shared hissa “x requests” se “x 1” ho jaata hai।
3. Block-hash prefix caching ke muqable RadixAttention ka mukhya fayda kya hai?
- KV cache ka size compress karna
- Prefix tree se partially-overlapping prefixes manage karna, longest common prefix match karna - complex sharing relations par hit rate zyada
- Eviction policy ki zaroorat nahi
Radix tree “A, B ka prefix hai; B, C ka prefix hai” jaise relations naturally express karta hai; block list sirf strictly-aligned poore blocks hit karta hai।
4. PD separation ki fundamental motivation kya hai?
- KV cache ke total bytes kam karna
- Prefill compute-intensive hai, decode bandwidth-bound; mixed deployment mein ek-doosre ko disturb karte hain; alag karne par har side apne profile ke hisaab se hardware aur parallelism le sakti hai
- Speculative decoding aasaan banana
Separation bytes nahi, resource misallocation bachata hai: TTFT aur TPOT dono SLO alag instance types se serve hote hain।
5. Kaun sa tareeka bina separation ke lambe prefill ki decode block hone ko kam kar sakta hai?
- Lambe prefill ko chhote chunks mein tod kar decode steps ke beech schedule karna (chunk prefill / Sarathi-Serve)
- Sampling temperature badhana
- KV cache ko CPU par le jaana
Sarathi-Serve ka chunk prefill scheduling se block hone ko khatam karta hai - mixed deployment ka madhyam raasta।
Exercises
- Is page ke formula se apna application estimate karein: system prompt kitna lamba, har turn ki history kitni, din mein kitne turns? Prefix caching lagbhag kitne prefill FLOPs bachayega?
- Ek table banakar vLLM automatic prefix caching, SGLang RadixAttention, CacheBlend aur LMCache ko teen columns mein compare karein: “kya reuse ho sakta hai, kahan store hota hai, kaun use kar sakta hai”।
Reference answer (exercise 1 ka estimation framework):
Expand karein
Shared prefix length S, har request unique U, requests B, model parameters N - bachat ka anupaat:
B jitna bada, S ka U ke relative bada - bachat 100% ke zyada kareeb. Jab S aur U mein bahut antar ho (chhota system prompt, lamba input), bachat 0 ki taraf - tab doosri optimizations sochein।
Aage padhein
- Zheng adi, SGLang / RadixAttention (2023): prefix cache ko radix tree mein organize karna; is page ki tree discussion ka srot।
- Kwon adi, Efficient Memory Management for LLM Serving with PagedAttention (vLLM) (SOSP 2023): block-wise KV management aur automatic prefix caching ka aadhar।
- Zhong adi, DistServe (OSDI 2024): PD separation aur goodput ka systematic justification।
- Patel adi, Splitwise (2023): prefill/decode separation ka cost angle।
- Qin adi, Mooncake (FAST 2025): KVCache-centric production-grade separated architecture।
- Agrawal adi, Sarathi-Serve (OSDI 2024): chunk prefill - mixed deployment mein prefill block khatam।
- Gim adi, Prompt Cache (2023); Liu adi, CacheGen (2023); Liu adi, CacheBlend (2024): offline precompute, compressed transfer aur inexact prefix merge - teen directions।
- Srivatsa adi, Preble (2024); Zhong adi, AdaServe (2025): cache-aware routing aur SLO-aware request placement।
अक्सर पूछे जाने वाले सवाल
- Prefix caching aur KV cache ek hi cheez hai?
- Nahi. KV cache ek request ke andar history tokens ki K/V reuse karta hai; prefix caching ek prefix ki computed KV ko cross-request shared store mein rakhta hai, aur aage wali requests same prefix le aayein to wo prefill skip ho jaata hai. Pehla request-ke-andar ki repeat computation bachata hai, doosra requests ke beech ki।
- Kis tarah ke workload par prefix caching ki hit rate sabse zyada hoti hai?
- Lambe fixed system prompt wale apps, multi-turn chat (har turn poora history dobara bhejna), ek hi documents ke batch par Q&A karne wala RAG traffic, aur fixed few-shot examples wale classification tasks. Ulta, alag-alag prefixes, lagbhag zero sharing wale casual chat traffic par hit rate zero ke paas - cache sirf memory ghirega।
- PD separation prefill aur decode ko alag kyun deploy karta hai?
- Prefill lambe input process karta hai - compute-intensive, high-parallelism phase; decode token-by-token generate karta hai - bandwidth-bound, low-latency chahiye. Mixed deployment mein ek lamba prefill us GPU ke saare requests ki decode block kar deta hai (TPOT spikes), aur resource profiles bhi alag hain. Alag deploy karne par har side apne profile ke hisaab se hardware aur parallelism le sakti hai, phir high-speed link se KV cache transfer hota hai।
- PD separation free lunch hai?
- Nahi. Isme cross-node KV transfer ka network overhead, scheduling complexity aur memory redundancy aati hai; halki load ya even-length requests mein fayda kharch se kam ho sakta hai. DistServe aur Splitwise dono 'goodput' (TTFT aur TPOT dono constraints satisfy karne wala throughput) se batate hain kab separation faydemand hai; Mooncake ek cache-centric large-scale separated architecture dikhata hai. Kam load par colocate + chunk prefill (Sarathi-Serve) aksar aasaan hai।