Skip to content

Commit f5a6081

Browse files
committed
Add load balancer example
1 parent 7b2788e commit f5a6081

File tree

1 file changed

+59
-0
lines changed
  • examples/app_server_with_load_balancer

1 file changed

+59
-0
lines changed
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
# !pip install torchvision pydantic
2+
import base64
3+
import io
4+
5+
import torch
6+
import torchvision
7+
from PIL import Image
8+
from pydantic import BaseModel
9+
10+
import lightning as L
11+
from lightning.app.components.serve import Image as InputImage
12+
from lightning.app.components.serve import PythonServer
13+
14+
15+
class PyTorchServer(PythonServer):
16+
def __init__(self):
17+
super().__init__(
18+
input_type=InputImage,
19+
output_type=OutputData,
20+
cloud_compute=L.CloudCompute("gpu"),
21+
)
22+
23+
def setup(self):
24+
self._model = torchvision.models.resnet18(pretrained=True)
25+
self._device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
26+
self._model.to(self._device)
27+
28+
def predict(self, request):
29+
image = base64.b64decode(request.image.encode("utf-8"))
30+
image = Image.open(io.BytesIO(image))
31+
transforms = torchvision.transforms.Compose(
32+
[
33+
torchvision.transforms.Resize(224),
34+
torchvision.transforms.ToTensor(),
35+
torchvision.transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
36+
]
37+
)
38+
image = transforms(image)
39+
image = image.to(self._device)
40+
prediction = self._model(image.unsqueeze(0))
41+
return {"prediction": prediction.argmax().item()}
42+
43+
44+
class OutputData(BaseModel):
45+
prediction: int
46+
47+
48+
app = L.LightningApp(PyTorchServer())
49+
50+
51+
# TODO: name confusion LoadBalancer vs. AutoScaler
52+
# from lightning.app.components import LoadBalancer
53+
# component = LoadBalancer(
54+
# PyTorchServer,
55+
# num_replicas=4,
56+
# balance_function="predict",
57+
# auto_scale=False,
58+
# )
59+
# app = L.LightningApp(component)

0 commit comments

Comments
 (0)