Abstract / Overview
Deploying AI models requires scalability and user accessibility. Ray Serve provides distributed serving for machine learning models, while Gradio creates simple, interactive web UIs. When combined, they enable scalable backend deployments with intuitive frontends. This article explains how to integrate Ray Serve and Gradio, includes runnable code, and demonstrates a full real-world example of deploying an image classifier.

Conceptual Background
Ray Serve: A scalable serving library for machine learning and Python applications. Supports microservices, multi-model pipelines, and dynamic scaling.
Gradio: A Python library for instantly creating web-based interfaces for ML models. Ideal for demonstrations and rapid prototyping.
Integration Benefits: Ray ensures reliable model serving at scale, while Gradio makes models accessible through an interactive browser interface.
Step-by-Step Walkthrough
1. Install Dependencies
pip install "ray[serve]" gradio fastapi torch torchvision2. Start Ray Serve
from ray import serve
serve.start()3. Create a Deployment with PyTorch Image Classifier
import torch
import torchvision.models as models
import torchvision.transforms as transforms
from PIL import Image
import requests
from io import BytesIO
# Preprocessing pipeline
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]),
])
# Load pretrained model
model = models.resnet18(pretrained=True)
model.eval()
# Labels
LABELS_URL = "https://raw.githubusercontent.com/pytorch/hub/master/imagenet_classes.txt"
labels = requests.get(LABELS_URL).text.splitlines()
@serve.deployment
class ImageClassifier:
def __call__(self, image: bytes) -> str:
img = Image.open(BytesIO(image)).convert("RGB")
tensor = transform(img).unsqueeze(0)
with torch.no_grad():
outputs = model(tensor)
_, predicted = outputs.max(1)
return labels[predicted.item()]
ImageClassifier.deploy()This deployment loads a pretrained ResNet-18 model and classifies input images.
4. Expose Deployment via FastAPI
from fastapi import FastAPI, UploadFile
app = FastAPI()
@serve.deployment
@serve.ingress(app)
class ImageAPI:
@app.post("/classify")
async def classify(self, file: UploadFile):
image_bytes = await file.read()
classifier = await ImageClassifier.get_handle().remote()
result = await classifier.remote(image_bytes)
return {"prediction": result}
ImageAPI.deploy()

Join the conversation! Your thoughts help the community grow.