5.3.10 · HinglishMLOps & Deployment

Model serving frameworks (TorchServe, Triton)

2,256 words10 min readRead in English

5.3.10 · AI-ML › MLOps & Deployment


WHY kyu chahiye ek dedicated serving framework?

WHY sirf Flask + model.predict() kyun nahi? Ek naive Flask app:

  • inference ek request at a time chalata hai → GPU 95% time idle rehta hai,
  • no batching → aap per-request overhead baar baar pay karte ho,
  • reload / crash hone par model chala jaata hai; koi versioning ya A/B nahi,
  • koi metrics nahi deta (latency p99, throughput, GPU util) out of the box,
  • easily CPU/GPU, multiple models, ya multiple frameworks mix nahi kar sakta.

Serving frameworks exactly yahi solve karte hain. Do dominant ones:

TorchServe NVIDIA Triton
Origin PyTorch (Meta+AWS) NVIDIA
Native models PyTorch (.mar) Framework-agnostic: TensorRT, ONNX, PyTorch, TF, Python, custom
Killer feature Simple PyTorch handlers Dynamic batching, multi-model, concurrent model instances, GPU-optimal
Protocols HTTP + gRPC HTTP + gRPC (Triton ka v2 inference protocol, jo KServe adopt karta hai)
Best when Pure-PyTorch shop Heterogeneous / max GPU utilization

Woh core idea jo serving ko fast banati hai: DYNAMIC BATCHING

Batching kyun help karta hai — first principles se derive karna

Model ki total latency per request ke do parts hain:

  • Fixed overhead (kernel launch, data transfer, framework glue) — per batch pay hota hai.
  • Marginal compute per sample.

requests one-by-one serve karo:

Unhe ek batch of size ke roop mein serve karo:

Kyun? Fixed cost poori batch ke liye ek baar pay hoti hai, baar ki jagah. Speedup:

Dynamic batching actually kaise kaam karta hai (Triton aur TorchServe dono yahi karte hain):

  1. Requests asynchronously arrive hoti hain.
  2. Server unhe ek queue mein hold karta hai max_batch_size tak YA jab tak max_queue_delay (jaise 5 ms) expire na ho jaye.
  3. Jo pehle ho → pad/stack karke batch banao → single forward pass → results wapas split karo.

Ek single model instance ka throughput

Figure — Model serving frameworks (TorchServe, Triton)

TorchServe: yeh kaise bana hai

# my_handler.py  — the 3 lifecycle steps you override
class MyHandler(BaseHandler):
    def preprocess(self, data):        # bytes/JSON -> tensor
        return torch.tensor(...)
    def inference(self, x):            # forward pass (batched!)
        return self.model(x)
    def postprocess(self, y):          # tensor -> JSON response
        return y.argmax(1).tolist()

Batching config per model rehti hai: batch_size, max_batch_delay (ms). Multiple worker processes concurrency dete hain; har ek ek model copy hold karta hai.


Triton: yeh kaise bana hai

# config.pbtxt (sketch)
max_batch_size: 32
dynamic_batching { max_queue_delay_microseconds: 5000 }
instance_group [ { count: 2, kind: KIND_GPU } ]

Triton kai backends chalata hai (peak GPU speed ke liye TensorRT, ONNX Runtime, PyTorch, Python) ek unified server ke peeche. Iska HTTP/gRPC API v2 inference protocol follow karta hai jo Triton define karta hai (baad mein KServe aur dusre serving stacks ne adopt kiya) — na ki ulta.


Worked Examples


Common Mistakes (Steel-manned)


Flashcards

GPU par dynamic batching kya problem solve karta hai?
GPU ek request at a time serve karte hue idle rehta hai; batching fixed per-batch overhead ko bahut saare samples mein amortize karta hai, throughput badhata hai.
Batching speedup aur uski ceiling ka formula
, ceiling jab .
Batching kab barely help karta hai?
Jab marginal compute fixed overhead dominate kare (compute-bound models, bade LLMs) → ceiling .
Dynamic batching mein batch flush trigger karne ke do knobs
max_batch_size reach ho YA max_queue_delay timeout expire ho, jo pehle ho.
TorchServe .mar file kya hai?
Ek Model Archive jo serialized weights + ek handler (preprocess/inference/postprocess) + metadata bundle karta hai.
Concurrency vs batching?
Concurrency = multiple model copies parallel mein chalana (zyada memory); batching = ek copy bahut saare inputs ko ek forward pass mein process karna. Orthogonal, combinable.
Triton ka TorchServe se sabse bada differentiator kya hai?
Framework-agnostic backends (TensorRT/ONNX/TF/PyTorch/Python), concurrent model instances, aur ensembles — max GPU utilization ke liye tuned.
Triton ensemble kya hai?
Ek DAG jo multiple models chain karta hai (jaise tokenizer→BERT→classifier) ek hi request mein bina extra network hops ke serve karta hai.
SLAs ke liye konsa latency metric matter karta hai aur kyun?
Tail latency p95/p99, kyunki queueing/batching tail ko mota kar deta hai even jab mean theek lagta ho.
Queue delay aur achievable batch size ka relationship?
Bada max_queue_delay zyada requests accumulate hone deta hai → bada → zyada throughput lekin zyada queue-wait latency .
"v2 inference protocol" jo Triton use karta hai, woh kaun define karta hai?
Triton (NVIDIA) isse define karta hai; KServe aur dusre serving stacks ise adopt/implement karte hain — na ki ulta.
Kya Throughput ≈ B/(c+Bm) Little's Law ka application hai?
Nahi — yeh sirf batch size ÷ batch processing time hai. Little's Law () alag se queue depth, arrival rate, aur mean wait relate karta hai.

Recall Feynman: 12-saal ke bacche ko explain karo

Ek trained model ek super-fast robot chef ki tarah hai. Agar chef ek plate banaye, use table par le jaaye, wapas aaye, aur agla plate banaye — yeh slow hai kyunki chalna (overhead) baar baar hota hai. Ek serving framework smart kitchen manager hai: woh thoda sa wait karta hai, ek tray ke orders gather karta hai, sab ek saath banata hai, phir saath deliver karta hai. TorchServe ek aisi kitchen hai jo sirf pasta (PyTorch) banati hai lekin chalana easy hai. Triton ek badi kitchen hai jo pasta, pizza, aur sushi (koi bhi model type) banati hai aur ek saath kai chefs chalati hai. Manager decide karta hai tray ke liye kitna wait karna hai — zyada wait karo toh bhookhe customers chipchipate hain (high latency); bilkul wait mat karo toh chef trips waste karta hai (low throughput).

Connections

  • Model quantization & TensorRT — asli fix jab batching apni ceiling hit kare.
  • ONNX & model interchange — woh format jo Triton pasand karta hai.
  • Little's Law & queueing theory — queue depth vs arrival rate govern karta hai (yahan ke batch-throughput formula se alag).
  • Latency SLAs & p99 — kyun tail latency serving config govern karti hai.
  • Autoscaling & Kubernetes (KServe) — KServe Triton ka v2 inference protocol implement karta hai; instances ko horizontally scale karta hai.
  • A-B testing & model versioning — TorchServe/Triton version routing ke zariye serve hota hai.
  • GPU architecture & kernel launch overhead — fixed cost ka origin.

Concept Map

naive attempt

no batching, GPU idle

PyTorch native

framework-agnostic

killer feature

also supports

maximizes

quantified by

approaches

overhead c dominates

Model serving = model behind API

Naive Flask app

Serving frameworks

TorchServe

NVIDIA Triton

Dynamic batching

GPU utilization

Speedup S=B(c+m)/(c+Bm)

Limit 1+c/m