Skip to main content

High-throughput ML inference middleware with dynamic batching

Project description

SmartBatch: High-Throughput Async Inference Middleware

SmartBatch is a production-grade inference serving system designed to maximize GPU utilization and throughput for PyTorch models. It implements Dynamic Batching to group incoming requests on-the-fly, significantly reducing overhead compared to naive request-per-inference processing.

๐Ÿš€ Key Features

  • Dynamic Batching: Automatically groups requests into batches (up to MAX_BATCH_SIZE) or processes them after a timeout (MAX_WAIT_TIME), striking the perfect balance between throughput and latency.
  • Latency-Aware Adaptive Batching: Dynamically adjusts batch sizes based on real-time execution duration to meet SLA targets (target_latency).
  • Hard Backpressure: Protects your system by shedding load with HTTP 429 when queues are full, preventing cascading failures.
  • Per-GPU Queues: Ensures strict isolation between workers, preventing stalls on one GPU from blocking others.
  • Asynchronous API: Built on FastAPI and asyncio to handle thousands of concurrent connections efficiently.
  • Production Robustness: Includes graceful shutdown, proper error handling, and thread-safe metrics.
  • Real-World Load Testing: Benchmarking suite included to simulate high-concurrency traffic with realistic payloads.
  • Observability: /metrics endpoint for real-time monitoring of latency, batch sizes, and throughput.

๐Ÿ“Š Benchmark Results (Stress Test)

We conducted a rigorous 1-hour stress test comparing SmartBatch against a Baseline (no batching) implementation.

Hardware: Single Node (Simulated Production Environment) Load: 200-1000 Concurrent Users Payload: Real-world images (ResNet18 inputs)

Metric Baseline (Sequential) SmartBatch (Batched) Improvement
Throughput (RPS) ~0.67 req/s ~2.22 req/s 3.3x Higher
Median Latency (p50) > 1000s (Collapsed) ~13s (Stable) ~99% Reduction
Tail Latency (p95) Unstable / Timeouts Controlled by Batching Stabilized

๐Ÿ› ๏ธ Installation

  1. Clone the repository:

    git clone https://github.com/yourusername/SmartBatch.git
    cd SmartBatch
    
  2. Create a virtual environment:

    python3.12 -m venv venv
    source venv/bin/activate
    
  3. Install dependencies:

    pip install .
    

๐Ÿƒ Usage

1. The Decorator Pattern (Recommended)

Add @batch to any async function to automatically group requests.

from smartbatch import batch
from typing import List

# 1. Define your batched function (List -> List)
# target_latency=0.05 enables adaptive batching (50ms target)
@batch(max_batch_size=32, max_wait_time=0.01, target_latency=0.05)
async def run_model(batch_inputs: List[float]) -> List[float]:
    # This runs ONLY when a batch is full or timeout matches
    return model.predict(batch_inputs)

# 2. Call it normally (Single Item -> Single Item)
# The decorator handles queueing and waiting!
result = await run_model(single_input) 

2. Binary Transport (MsgPack)

For high-performance clients, send binary packed data instead of JSON to reduce payload size.

Header: Content-Type: application/msgpack Body: MsgPack encoded dict (e.g., {"data": [...]}) or raw list [...].

import msgpack, requests
payload = msgpack.packb([0.1, 0.2, 0.3])
requests.post("http://localhost:8000/predict", data=payload, headers={"Content-Type": "application/msgpack"})

3. Multi-Model Registry

To serve multiple models on dynamic routes (/models/{name}/predict), use @register:

from smartbatch import batch, register

@register(name="yolo")
@batch(max_batch_size=8)
async def run_yolo(batch: List):
    return yolo_model(batch)

# Now available at: POST /models/yolo/predict

4. Input Schema Validation (Recommended)

Protect your workers by enforcing Pydantic schemas. Invalid requests (e.g. string instead of int) will raise an error before queueing.

from pydantic import BaseModel

class ImageInput(BaseModel):
    data: List[float]
    threshold: float = 0.5

@batch(max_batch_size=32, input_schema=ImageInput)
async def safe_inference(batch: List[ImageInput]):
    # 'batch' contains valid Pydantic objects now!
    inputs = [item.data for item in batch]
    return model.predict(inputs)

5. Multi-GPU / Multi-Worker Support

Scale verticaly by running multiple worker loops. Use worker_id to select devices.

# Models loaded on different GPUs
models = {
    0: load_model("cuda:0"),
    1: load_model("cuda:1")
}

@batch(max_batch_size=32, workers=2)
async def infer(batch, worker_id=0):
    # SmartBatch injects 'worker_id' (0 or 1) automatically
    model = models[worker_id]
    return model(batch)

6. Failure Isolation

SmartBatch uses per-worker queues. If Worker 0 is stalled (e.g. GPU hang), Worker 1 continues to process requests from its own queue. Load balancing automatically routes new requests to the shortest queue.

๐Ÿงช Benchmarking

Reproduce the performance results yourself using the included benchmark suite.

1. Run the Comparison Benchark This script runs both Baseline and SmartBatch scenarios sequentially and generates plots.

# usage: --users [NUM] --duration [TIME]
venv/bin/python scripts/production_benchmark.py --users 200 --duration 1h

2. View Results The script will generate these files in your root directory:

  • production_throughput.png
  • production_latency_p50.png
  • production_latency_p95.png

๐Ÿ“‚ Project Structure

SmartBatch/
โ”œโ”€โ”€ smartbatch/          # Core Package
โ”‚   โ”œโ”€โ”€ main.py          # Entry point & App lifecycle
โ”‚   โ”œโ”€โ”€ api.py           # FastAPI endpoints
โ”‚   โ”œโ”€โ”€ decorator.py     # Batching logic & Queue management
โ”‚   โ”œโ”€โ”€ registry.py      # Model registry
โ”‚   โ”œโ”€โ”€ model.py         # PyTorch Model Wrapper
โ”‚   โ””โ”€โ”€ metrics.py       # Thread-safe metrics collection
โ”œโ”€โ”€ scripts/             # Utilities
โ”‚   โ”œโ”€โ”€ production_benchmark.py # A/B Stress Test Script
โ”‚   โ””โ”€โ”€ study_params.py  # Hyperparameter optimization
โ”œโ”€โ”€ tests/               # Testing
โ”‚   โ”œโ”€โ”€ locustfile.py    # Load generator
โ”‚   โ””โ”€โ”€ data/            # Test images (for realistic load)
โ””โ”€โ”€ README.md            # Documentation

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

smartbatch-0.1.2.tar.gz (14.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

smartbatch-0.1.2-py3-none-any.whl (13.0 kB view details)

Uploaded Python 3

File details

Details for the file smartbatch-0.1.2.tar.gz.

File metadata

  • Download URL: smartbatch-0.1.2.tar.gz
  • Upload date:
  • Size: 14.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for smartbatch-0.1.2.tar.gz
Algorithm Hash digest
SHA256 843713194d44df09dac4ee934374c740d9998a95f245262dd5a1640fc2bdb80d
MD5 cb06c1db393b67eda95833407de6998a
BLAKE2b-256 b7cc1a130e47b27611b753d6a4f4882428dffe40532b67d96fec7a661f12601a

See more details on using hashes here.

Provenance

The following attestation bundles were made for smartbatch-0.1.2.tar.gz:

Publisher: publish.yml on VeeraKarthick609/SmartBatch

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file smartbatch-0.1.2-py3-none-any.whl.

File metadata

  • Download URL: smartbatch-0.1.2-py3-none-any.whl
  • Upload date:
  • Size: 13.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for smartbatch-0.1.2-py3-none-any.whl
Algorithm Hash digest
SHA256 c573b37c06ac84bf6f4d27100673af9fb830f28cf466990c0ba2394e485614ee
MD5 5e5f10570aca2713a62c2e0f091842f0
BLAKE2b-256 79cf44fd74e881d18bf7837c7655a7a2c5b3c6be9239fe1bf3cd63cd055d4c6c

See more details on using hashes here.

Provenance

The following attestation bundles were made for smartbatch-0.1.2-py3-none-any.whl:

Publisher: publish.yml on VeeraKarthick609/SmartBatch

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page