TorchServe: Panduan Lengkap Deployment Model PyTorch ke Production
Penulis: Ruby Abdullah Kategori: Tutorial Tags: PyTorch, TorchServe, MLOps, Model Serving, Production MLPendahuluan
Melatih model machine learning yang akurat hanyalah separuh dari pekerjaan seorang ML engineer. Tantangan sesungguhnya dimulai ketika model tersebut harus di-deploy ke production dan melayani ribuan hingga jutaan request dari pengguna nyata. Di sinilah TorchServe hadir sebagai solusi resmi dari PyTorch.
TorchServe adalah framework open-source untuk serving model PyTorch yang dikembangkan bersama oleh Facebook (Meta) dan AWS. Framework ini dirancang khusus untuk mengatasi kebutuhan deployment model PyTorch di lingkungan production: dari model sederhana untuk klasifikasi gambar hingga model NLP berskala besar. TorchServe menyediakan REST API yang siap pakai, mendukung multi-model serving, batch inference, dan dilengkapi dengan sistem monitoring serta manajemen model yang komprehensif.
Artikel ini akan membahas TorchServe secara menyeluruh, mulai dari instalasi, penggunaan dasar, hingga konfigurasi production-grade yang meliputi custom handler, batching, dan scaling. Semua contoh kode dapat langsung dijalankan dan diuji di lingkungan Anda.
Mengapa TorchServe?
Sebelum TorchServe, tim ML yang menggunakan PyTorch harus membangun sistem serving sendiri menggunakan Flask, FastAPI, atau framework web generik lainnya. Pendekatan ini memiliki beberapa kelemahan:
- Tidak ada standar untuk model packaging dan versioning
- Harus menulis boilerplate code untuk preprocessing dan postprocessing
- Tidak ada built-in support untuk batching dan concurrency
- Monitoring dan metrics harus diimplementasikan secara manual
- Sulit untuk melakukan hot reload model tanpa downtime
TorchServe menyelesaikan semua masalah tersebut dengan menyediakan infrastruktur serving yang sudah matang dan teruji, sehingga ML engineer dapat fokus pada logika model dan bisnis, bukan pada infrastruktur serving.
Instalasi dan Setup
Prasyarat
Sebelum memulai, pastikan sistem Anda memiliki:
- Python 3.8 atau lebih baru
- Java 11 atau lebih baru (diperlukan oleh TorchServe)
- PyTorch 1.9 atau lebih baru
- pip package manager
Verifikasi instalasi Java:
java -version
Harus menampilkan versi 11 atau lebih baru
Instalasi TorchServe
Instalasi TorchServe terdiri dari dua komponen utama: torchserve (runtime server) dan torch-model-archiver (tool untuk packaging model).
# Instalasi untuk CPU
pip install torchserve torch-model-archiver torch-workflow-archiver
Instalasi untuk GPU (pastikan CUDA sudah terinstal)
pip install torchserve torch-model-archiver torch-workflow-archiver
Verifikasi instalasi
torchserve --version
torch-model-archiver --version
Untuk lingkungan production, disarankan menggunakan virtual environment atau Docker:
# Menggunakan virtual environment
python -m venv torchserve-env
source torchserve-env/bin/activate # Linux/Mac
torchserve-env\Scripts\activate # Windows
pip install torchserve torch-model-archiver torch-workflow-archiver
Menggunakan Docker (Rekomendasi untuk Production)
Docker image resmi TorchServe tersedia di Docker Hub:
# Pull image dengan dukungan GPU (CUDA 11.6)
docker pull pytorch/torchserve:latest-gpu
Pull image untuk CPU
docker pull pytorch/torchserve:latest
Jalankan container
docker run --rm -it \
-p 8080:8080 \
-p 8081:8081 \
-p 8082:8082 \
-v $(pwd)/model-store:/home/model-server/model-store \
pytorch/torchserve:latest
Struktur Direktori
Buat struktur direktori berikut untuk proyek TorchServe Anda:
project/
├── model-store/ # Direktori untuk menyimpan file .mar
├── config/
│ └── config.properties # File konfigurasi TorchServe
├── handlers/ # Custom handler scripts
├── models/ # File model (.pt, .pth)
└── logs/ # Output log
mkdir -p project/{model-store,config,handlers,models,logs}
cd project
Model Archiving dengan torch-model-archiver
Sebelum model dapat di-serve oleh TorchServe, model harus dikemas ke dalam format .mar (Model Archive) menggunakan torch-model-archiver. File .mar berisi model weights, handler script, dan semua dependensi yang diperlukan.
Contoh: Menyiapkan Model ResNet untuk Image Classification
Pertama, simpan model yang sudah dilatih:
# savemodel.py
import torch
import torchvision.models as models
Load pre-trained ResNet50
model = models.resnet50(pretrained=True)
model.eval()
Simpan model ke format TorchScript untuk portabilitas yang lebih baik
example
input = torch.rand(1, 3, 224, 224)
tracedmodel = torch.jit.trace(model, exampleinput)
tracedmodel.save("models/resnet50traced.pt")
print("Model berhasil disimpan ke models/resnet50traced.pt")
Jalankan script tersebut:
python savemodel.py
Selanjutnya, siapkan file mapping untuk label ImageNet:
# Download file indextoname.json untuk ImageNet
wget https://raw.githubusercontent.com/pytorch/serve/master/examples/imageclassifier/indextoname.json \
-O models/indextoname.json
Membuat Model Archive
torch-model-archiver \
--model-name resnet50 \
--version 1.0 \
--serialized-file models/resnet50traced.pt \
--export-path model-store \
--extra-files models/indextoname.json \
--handler imageclassifier
ls model-store/
Output: resnet50.mar
Penjelasan parameter:
--model-name: Nama model yang akan digunakan sebagai endpoint--version: Versi model untuk manajemen versioning--serialized-file: File model yang sudah disimpan (.pt,.pth, atau.bin)--export-path: Direktori output untuk file.mar--extra-files: File tambahan yang dibutuhkan model (label mapping, config, dll)--handler: Handler yang akan memproses request (bawaan atau custom)
Built-in Handlers
TorchServe menyediakan beberapa built-in handler yang siap digunakan:
| Handler | Kegunaan |
|---|---|
| imageclassifier | Klasifikasi gambar, output top-5 class |
| objectdetector | Deteksi objek dengan bounding box |
| imagesegmenter | Segmentasi gambar |
| textclassifier | Klasifikasi teks |
Menjalankan TorchServe
File Konfigurasi
Buat file config/config.properties:
# config/config.properties
inferenceaddress=http://0.0.0.0:8080
managementaddress=http://0.0.0.0:8081
metricsaddress=http://0.0.0.0:8082
modelstore=/home/user/project/model-store
loadmodels=resnet50.mar
numberofnettythreads=32
jobqueuesize=1000
defaultworkerspermodel=1
defaultresponsetimeout=120
unregistermodeltimeout=180
maxresponsesize=6553500
Menjalankan Server
# Jalankan TorchServe
torchserve \
--start \
--model-store model-store \
--models resnet50=resnet50.mar \
--ts-config config/config.properties \
--log-config config/log4j2.xml
Cek status server
curl http://localhost:8080/ping
Output: {"status": "Healthy"}
Untuk menghentikan server:
torchserve --stop
Melakukan Inference
Setelah server berjalan, Anda dapat mengirim request inference:
# Download gambar test
wget https://raw.githubusercontent.com/pytorch/serve/master/docs/images/kittensmall.jpg
Kirim request inference
curl -X POST \
http://localhost:8080/predictions/resnet50 \
-T kittensmall.jpg
Output contoh:
{
"tabby": 0.4087,
"tigercat": 0.3372,
"Egyptiancat": 0.1620,
...
}
Menggunakan Python requests:
# inferenceclient.py
import requests
import json
def predict
image(imagepath: str, modelname: str = "resnet50") -> dict:
url = f"http://localhost:8080/predictions/{modelname}"
with open(imagepath, "rb") as f:
response = requests.post(url, data=f)
if response.statuscode == 200:
return response.json()
else:
raise RuntimeError(f"Inference gagal: {response.statuscode} - {response.text}")
Contoh penggunaan
result = predictimage("kittensmall.jpg")
print(json.dumps(result, indent=2))
Management API
TorchServe menyediakan Management API yang berjalan di port 8081 (default) untuk mengelola model yang sedang berjalan tanpa perlu restart server.
Mendaftarkan Model Baru
# Register model dari URL
curl -X POST "http://localhost:8081/models" \
-d "url=resnet50.mar" \
-d "initialworkers=2" \
-d "synchronous=true"
Register model dari local file
curl -X POST "http://localhost:8081/models?url=resnet50.mar&initialworkers=2"
Melihat Model yang Terdaftar
# List semua model
curl http://localhost:8081/models
Detail model tertentu
curl http://localhost:8081/models/resnet50
Detail versi spesifik
curl http://localhost:8081/models/resnet50/1.0
Scaling Workers
# Update jumlah workers untuk model resnet50
curl -X PUT "http://localhost:8081/models/resnet50" \
-d "minworker=2" \
-d "maxworker=8"
Update versi spesifik
curl -X PUT "http://localhost:8081/models/resnet50/1.0" \
-d "minworker=4" \
-d "maxworker=10"
Unregister Model
# Unregister model
curl -X DELETE http://localhost:8081/models/resnet50/1.0
Custom Handler
Salah satu fitur terkuat TorchServe adalah kemampuan untuk menulis custom handler. Handler bertanggung jawab untuk preprocessing input, menjalankan inference, dan postprocessing output.
Struktur Custom Handler
# handlers/customhandler.py
import torch
import json
import logging
from torchvision import transforms
from PIL import Image
import io
import base64
logger = logging.getLogger(name)
class CustomImageClassifier:
"""
Custom handler untuk image classification dengan preprocessing khusus.
"""
def init(self):
self.model = None
self.device = None
self.mapping = None
self.initialized = False
def initialize(self, context):
"""
Dipanggil sekali saat model dimuat ke worker.
Gunakan untuk inisialisasi model dan resource lainnya.
"""
self.manifest = context.manifest
properties = context.system
properties
# Tentukan device
self.device = torch.device(
"cuda" if torch.cuda.isavailable() else "cpu"
)
logger.info(f"Menggunakan device: {self.device}")
# Load model
modeldir = properties.get("modeldir")
serializedfile = self.manifest["model"]["serializedFile"]
modelpath = f"{modeldir}/{serializedfile}"
self.model = torch.jit.load(modelpath, maplocation=self.device)
self.model.eval()
# Load label mapping jika tersedia
mappingfile = f"{modeldir}/indextoname.json"
try:
with open(mappingfile) as f:
self.mapping = json.load(f)
except FileNotFoundError:
logger.warning("File indextoname.json tidak ditemukan")
# Definisikan transform
self.transform = transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize(
mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225]
),
])
self.initialized = True
logger.info("Handler berhasil diinisialisasi")
def preprocess(self, data):
"""
Preprocess input data menjadi tensor yang siap untuk inference.
Mendukung input berupa raw bytes atau base64 encoded string.
"""
images = []
for row in data:
# Ambil data dari request
imagedata = row.get("data") or row.get("body")
if isinstance(imagedata, str):
# Base64 encoded
imagedata = base64.b64decode(imagedata)
# Konversi bytes ke PIL Image
image = Image.open(io.BytesIO(imagedata)).convert("RGB")
# Apply transform
tensor = self.transform(image)
images.append(tensor)
# Stack menjadi batch
return torch.stack(images).to(self.device)
def inference(self, data):
"""
Jalankan model inference pada batch tensor.
"""
with torch.nograd():
outputs = self.model(data)
return outputs
def postprocess(self, data):
"""
Konversi output tensor menjadi format JSON yang dapat dibaca.
Mengembalikan top-5 predictions dengan label dan confidence score.
"""
probabilities = torch.nn.functional.softmax(data, dim=1)
top5prob, top5idx = torch.topk(probabilities, 5, dim=1)
results = []
for probs, indices in zip(top5prob, top5idx):
predictions = {}
for prob, idx in zip(probs.tolist(), indices.tolist()):
label = str(idx)
if self.mapping and str(idx) in self.mapping:
label = self.mapping[str(idx)]
predictions[label] = round(prob, 4)
results.append(predictions)
return results
def handle(self, data, context):
"""
Entry point utama yang dipanggil oleh TorchServe untuk setiap request.
Mengorkestrasi pipeline: preprocess -> inference -> postprocess.
"""
if not self.initialized:
self.initialize(context)
if data is None:
return None
try:
preprocessed = self.preprocess(data)
output = self.inference(preprocessed)
result = self.postprocess(output)
return result
except Exception as e:
logger.error(f"Error saat memproses request: {str(e)}")
raise
Instansiasi handler (diperlukan oleh TorchServe)
service = CustomImageClassifier()
def handle(data, context):
return
service.handle(data, context)
Packaging dengan Custom Handler
torch-model-archiver \
--model-name customresnet50 \
--version 2.0 \
--serialized-file models/resnet50traced.pt \
--handler handlers/customhandler.py \
--extra-files models/indextoname.json \
--export-path model-store
Register model baru
curl -X POST "http://localhost:8081/models" \
-d "url=customresnet50.mar" \
-d "modelname=customresnet50" \
-d "initialworkers=2"
Batch Inference
Batch inference adalah salah satu teknik penting untuk meningkatkan throughput TorchServe. Dengan batching, server dapat menggabungkan beberapa request yang datang hampir bersamaan dan memprosesnya sekaligus.
Konfigurasi Batching
Aktifkan batching melalui Management API:
# Register model dengan batch support
curl -X POST "http://localhost:8081/models" \
-d "url=resnet50.mar" \
-d "batchsize=8" \
-d "maxbatchdelay=50" \
-d "initialworkers=4"
Parameter batching:
batchsize: Jumlah request maksimum dalam satu batch (default: 1)maxbatchdelay: Waktu tunggu maksimum dalam milidetik untuk mengumpulkan batch (default: 100ms)
Handler yang Mendukung Batching
Handler yang sudah dibuat sebelumnya sudah mendukung batching karena menggunakan torch.stack untuk memproses beberapa gambar sekaligus. Berikut contoh handler yang lebih eksplisit mendukung batch:
# handlers/batchhandler.py
import torch
import logging
from typing import List, Dict, Any
logger = logging.getLogger(name)
class BatchAwareHandler:
"""
Handler yang dioptimalkan untuk batch inference.
"""
def init(self):
self.model = None
self.device = None
self.initialized = False
def initialize(self, context):
properties = context.system
properties
self.device = torch.device(
"cuda" if torch.cuda.isavailable() else "cpu"
)
modeldir = properties.get("modeldir")
modelfile = context.manifest["model"]["serializedFile"]
self.model = torch.jit.load(
f"{modeldir}/{modelfile}",
maplocation=self.device
)
self.model.eval()
self.initialized = True
logger.info(
f"BatchAwareHandler diinisialisasi, device: {self.device}"
)
def preprocess(self, requests: List[Dict]) -> torch.Tensor:
"""
Preprocess batch of requests.
Parameter requests adalah list dengan panjang = batchsize aktual.
"""
batchtensors = []
for request in requests:
data = request.get("body", request.get("data", b""))
# Parse dan preprocess setiap item
tensor = self.parseinput(data)
batchtensors.append(tensor)
return torch.stack(batchtensors).to(self.device)
def parseinput(self, rawdata: bytes) -> torch.Tensor:
"""Parse single input item."""
# Implementasi parsing sesuai format input Anda
# Contoh: deserialize numpy array
import numpy as np
array = np.frombuffer(rawdata, dtype=np.float32).reshape(3, 224, 224)
return torch.fromnumpy(array.copy())
def inference(self, batchtensor: torch.Tensor) -> torch.Tensor:
"""
Jalankan inference untuk seluruh batch sekaligus.
Ini lebih efisien daripada menjalankan satu per satu.
"""
with torch.nograd():
return self.model(batchtensor)
def postprocess(self, output: torch.Tensor) -> List[Dict]:
"""
Pisahkan output batch menjadi respons individual.
Panjang output list harus sama dengan panjang input batch.
"""
probabilities = torch.softmax(output, dim=1)
results = []
for prob in probabilities:
topprob, topidx = prob.topk(5)
result = {
str(idx.item()): round(p.item(), 4)
for p, idx in zip(topprob, topidx)
}
results.append(result)
return results
def handle(self, data, context):
if not self.initialized:
self.initialize(context)
batchinput = self.preprocess(data)
batchoutput = self.inference(batchinput)
return self.postprocess(batchoutput)
Menguji Batch Inference
# testbatch.py
import requests
import concurrent.futures
import time
def sendrequest(imagepath: str) -> dict:
with open(imagepath, "rb") as f:
response = requests.post(
"http://localhost:8080/predictions/resnet50",
data=f
)
return response.json()
Kirim 10 request bersamaan untuk menguji batching
imagepaths = ["kittensmall.jpg"] 10
start = time.time()
with concurrent.futures.ThreadPoolExecutor(maxworkers=10) as executor:
futures = [executor.submit(sendrequest, p) for p in imagepaths]
results = [f.result() for f in concurrent.futures.ascompleted(futures)]
elapsed = time.time() - start
print(f"10 request selesai dalam {elapsed:.2f} detik")
print(f"Throughput: {10/elapsed:.1f} req/s")
Logging dan Metrics
Konfigurasi Logging
Buat file config/log4j2.xml untuk konfigurasi logging yang lebih detail:
fileName="logs/torchserve.log"
filePattern="logs/torchserve-%d{MM-dd-yyyy}-%i.log.gz">
%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n
Metrics API
TorchServe mengekspos metrics melalui port 8082 dalam format yang kompatibel dengan Prometheus:
# Ambil semua metrics
curl http://localhost:8082/metrics
Contoh output:
tsinferencerequeststotal{modelname="resnet50",host="hostname"} 1234.0
tsinferencelatencymicroseconds{modelname="resnet50",host="hostname"} 45678.9
tsqueuelatencymicroseconds{modelname="resnet50",host="hostname"} 1234.5
Custom Metrics dalam Handler
# Tambahkan custom metrics dalam handler
from ts.metrics.metricsstore import MetricsStore
class HandlerWithMetrics:
def initialize(self, context):
self.context = context
# Akses metrics store
self.metrics = context.metrics
def handle(self, data, context):
import time
start = time.time()
result = self.runinference(data)
# Catat custom metric
elapsedms = (time.time() - start) 1000
self.metrics.addtime(
"CustomInferenceTime",
elapsedms,
None,
"ms"
)
self.metrics.addcounter(
"CustomRequestCount",
len(data)
)
return result
Integrasi dengan Prometheus dan Grafana
Untuk monitoring production, integrasikan TorchServe dengan Prometheus:
# prometheus.yml
scrapeconfigs:
- jobname: 'torchserve'
staticconfigs:
- targets: ['localhost:8082']
metricspath: '/metrics'
scrape
interval: 15s
Versioning dan Model Management
TorchServe mendukung multiple versi model secara bersamaan, berguna untuk A/B testing dan rollback:
# Daftarkan versi kedua dari model
torch-model-archiver \
--model-name resnet50 \
--version 2.0 \
--serialized-file models/resnet50v2traced.pt \
--handler handlers/customhandler.py \
--extra-files models/indextoname.json \
--export-path model-store
Register versi baru
curl -X POST "http://localhost:8081/models" \
-d "url=resnet50.mar" \
-d "modelversion=2.0" \
-d "initialworkers=2"
Set versi default
curl -X PUT "http://localhost:8081/models/resnet50/2.0/set-default"
Inference ke versi spesifik
curl -X POST http://localhost:8080/predictions/resnet50/1.0 \
-T kittensmall.jpg
Inference ke versi default
curl -X POST http://localhost:8080/predictions/resnet50 \
-T kittensmall.jpg
Best Practices untuk Production
1. Optimasi Model Sebelum Deployment
Selalu optimalkan model sebelum di-deploy untuk mendapatkan performa terbaik:
# optimizemodel.py
import torch
import torch.quantization as quant
def optimizeforinference(model, exampleinput):
"""
Terapkan beberapa teknik optimasi untuk model production.
"""
model.eval()
# 1. TorchScript tracing untuk menghilangkan overhead Python
traced = torch.jit.trace(model, exampleinput)
traced = torch.jit.optimizeforinference(traced)
return traced
def quantizemodel(model, calibrationdata):
"""
Terapkan dynamic quantization untuk mengurangi ukuran model
dan meningkatkan inference speed di CPU.
"""
quantized = quant.quantizedynamic(
model,
{torch.nn.Linear, torch.nn.Conv2d},
dtype=torch.qint8
)
return quantized
Contoh penggunaan
model = loadtrainedmodel()
exampleinput = torch.rand(1, 3, 224, 224)
optimized = optimizeforinference(model, exampleinput)
optimized.save("models/resnet50optimized.pt")
print(f"Ukuran model asli: {getmodelsize(model):.1f} MB")
print(f"Ukuran model optimized: {getmodelsize(optimized):.1f} MB")
2. Konfigurasi Worker yang Tepat
Jumlah worker optimal bergantung pada hardware dan karakteristik model:
# config/config.properties untuk production
Untuk server dengan 8 CPU cores
defaultworkerspermodel=4
numberofnettythreads=16
jobqueuesize=2000
Timeout settings
defaultresponsetimeout=120
unregistermodeltimeout=180
Memory management
loadmodels=all
maxresponsesize=6553500
Untuk GPU inference
defaultworkerspermodel=1 # Biasanya 1 worker per GPU cukup
numberofgpu=4 # Jumlah GPU yang tersedia
3. Health Check dan Graceful Shutdown
Implementasikan health check endpoint dalam sistem Anda:
# healthcheck.py
import requests
import sys
import time
def check
torchservehealth(
host: str = "localhost",
port: int = 8080,
max
retries: int = 10,
retrydelay: float = 2.0
) -> bool:
"""
Cek apakah TorchServe sudah siap menerima request.
Berguna untuk readiness probe di Kubernetes.
"""
url = f"http://{host}:{port}/ping"
for attempt in range(maxretries):
try:
response = requests.get(url, timeout=5)
if response.statuscode == 200:
data = response.json()
if data.get("status") == "Healthy":
print(f"TorchServe healthy setelah {attempt + 1} percobaan")
return True
except requests.exceptions.ConnectionError:
pass
print(f"Percobaan {attempt + 1}/{maxretries}, menunggu...")
time.sleep(retrydelay)
return False
if name == "main":
if not checktorchservehealth():
print("TorchServe tidak responsive!")
sys.exit(1)
print("TorchServe siap menerima traffic")
4. Deployment dengan Docker Compose
Untuk deployment yang lebih terstruktur di production:
# docker-compose.yml
version: "3.8"
services:
torchserve:
image: pytorch/torchserve:latest-gpu
ports:
- "8080:8080"
- "8081:8081"
- "8082:8082"
volumes:
- ./model-store:/home/model-server/model-store
- ./config:/home/model-server/config
- ./logs:/home/model-server/logs
environment:
- TSCONFIGFILE=/home/model-server/config/config.properties
deploy:
resources:
reservations:
devices:
- driver: nvidia
count: 1
capabilities: [gpu]
restart: unless-stopped
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:8080/ping"]
interval: 30s
timeout: 10s
retries: 3
startperiod: 60s
prometheus:
image: prom/prometheus:latest
ports:
- "9090:9090"
volumes:
- ./config/prometheus.yml:/etc/prometheus/prometheus.yml
dependson:
- torchserve
5. Keamanan
Untuk deployment production yang aman:
# Batasi akses Management API hanya dari localhost atau jaringan internal
managementaddress=http://127.0.0.1:8081
Aktifkan SSL untuk Inference API (memerlukan sertifikat)
keystore=/path/to/keystore.p12
keystorepass=yourpassword
keystoretype=PKCS12
Batasi ukuran request untuk mencegah abuse
maxrequestsize=6553500
maxresponsesize=6553500
6. Monitoring Throughput dan Latency
Gunakan script sederhana untuk load testing sebelum deploy ke production:
# loadtest.py
import requests
import time
import statistics
import concurrent.futures
def singlerequest(imagepath: str) -> float:
"""Return latency dalam milidetik."""
start = time.time()
with open(imagepath, "rb") as f:
response = requests.post(
"http://localhost:8080/predictions/resnet50",
data=f,
timeout=10
)
response.raiseforstatus()
return (time.time() - start) 1000
def runloadtest(
imagepath: str,
totalrequests: int = 100,
concurrentworkers: int = 10
):
latencies = []
with concurrent.futures.ThreadPoolExecutor(
maxworkers=concurrentworkers
) as executor:
futures = [
executor.submit(singlerequest, imagepath)
for in range(totalrequests)
]
for future in concurrent.futures.ascompleted(futures):
try:
latency = future.result()
latencies.append(latency)
except Exception as e:
print(f"Request gagal: {e}")
if latencies:
print(f"Total requests: {totalrequests}")
print(f"Sukses: {len(latencies)}")
print(f"Rata-rata latency: {statistics.mean(latencies):.1f} ms")
print(f"Median latency: {statistics.median(latencies):.1f} ms")
print(f"P95 latency: {sorted(latencies)[int(len(latencies)0.95)]:.1f} ms")
print(f"P99 latency: {sorted(latencies)[int(len(latencies)*0.99)]:.1f} ms")
print(f"Min: {min(latencies):.1f} ms, Max: {max(latencies):.1f} ms")
if name == "main":
runloadtest("kittensmall.jpg", totalrequests=200, concurrentworkers=20)
7. Scaling Horizontal
Untuk traffic yang sangat tinggi, gunakan load balancer di depan beberapa instance TorchServe:
# nginx.conf untuk load balancing
upstream torchserveinference {
leastconn;
server torchserve-1:8080;
server torchserve-2:8080;
server torchserve-3:8080;
keepalive 32;
}
server {
listen 80;
location /predictions/ {
proxypass http://torchserveinference;
proxysetheader Connection "";
proxyhttpversion 1.1;
proxyreadtimeout 120s;
proxyconnect_timeout 10s;
}
}
Kesimpulan
TorchServe adalah solusi production-grade yang komprehensif untuk serving model PyTorch. Dalam artikel ini, kita telah membahas semua aspek penting yang perlu diketahui oleh ML engineer:
- Model Archiving: Mengemas model dengan
torch-model-archiverke format.maryang portable dan self-contained - Deployment: Menjalankan TorchServe dengan konfigurasi yang tepat untuk berbagai lingkungan
- Management API: Mendaftarkan, mengupdate, dan mengelola model secara dinamis tanpa downtime
- Custom Handlers: Menulis logika preprocessing dan postprocessing khusus sesuai kebutuhan model
- Batch Inference: Mengoptimalkan throughput dengan menggabungkan beberapa request menjadi satu batch
- Monitoring: Mengumpulkan metrics dan log untuk observability di production
- Best Practices: Optimasi model, konfigurasi worker, keamanan, dan scaling horizontal
TorchServe bukan hanya sebuah web server sederhana. Ia adalah platform serving yang dirancang untuk menangani kompleksitas deployment model ML di production: dari versioning dan A/B testing hingga auto-scaling dan monitoring. Dengan mengikuti panduan ini, Anda sudah memiliki fondasi yang kuat untuk men-deploy model PyTorch Anda ke production dengan andal dan efisien.
Langkah selanjutnya yang dapat Anda eksplorasi adalah integrasi TorchServe dengan Kubernetes untuk orchestration skala besar, penggunaan ONNX Runtime sebagai backend alternatif untuk performa yang lebih tinggi, dan implementasi model caching untuk mengurangi cold start latency.