forked from livepeer/ai-worker
-
Notifications
You must be signed in to change notification settings - Fork 0
/
modal_app.py
202 lines (152 loc) · 5.61 KB
/
modal_app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
import logging
import os
from pathlib import Path
from app.main import (config_logging, load_route,
use_route_names_as_operation_ids)
from app.routes import health
from modal import Image, Secret, Stub, Volume, asgi_app, enter, method
stub = Stub("livepeer-ai-runner")
pipeline_image = (
Image.from_registry("livepeer/ai-runner:latest")
.workdir("/app")
.env({"BFLOAT16": "true"})
)
api_image = Image.debian_slim(python_version="3.11").pip_install(
"pydantic==2.6.1", "fastapi==0.109.2", "pillow"
)
downloader_image = (
Image.debian_slim(python_version="3.11")
.pip_install(
"huggingface_hub==0.20.2",
"hf-transfer==0.1.4",
)
.env({"HF_HUB_ENABLE_HF_TRANSFER": "1", "HF_HUB_DISABLE_PROGRESS_BARS": "1"})
)
models_volume = Volume.persisted("models")
models_path = Path("/models")
logger = logging.getLogger(__name__)
SDXL_LIGHTNING_MODEL_ID = "ByteDance/SDXL-Lightning"
@stub.function(
image=downloader_image,
volumes={models_path: models_volume},
timeout=3600,
secrets=[Secret.from_name("huggingface")],
)
def download_model(model_id: str):
from huggingface_hub import snapshot_download
try:
# TODO: Handle case where there are no fp16 safetensors available
allow_patterns = ["*unet.safetensors", "*.fp16.safetensors", "*.json", "*.txt"]
ignore_patterns = [".onnx", ".onnx_data"]
cache_dir = "/models"
snapshot_download(
model_id,
cache_dir=cache_dir,
allow_patterns=allow_patterns,
ignore_patterns=ignore_patterns,
token=os.environ.get("HF_TOKEN"),
)
logger.info(f"Downloaded model {model_id} to volume")
models_volume.commit()
except Exception:
logger.exception(f"Failed to download model {model_id} to volume")
raise
class Pipeline:
def __init__(self, pipeline: str, model_id: str):
self.pipeline = pipeline
self.model_id = model_id
@enter()
def enter(self):
from app.main import load_pipeline
model_id = self.model_id
if SDXL_LIGHTNING_MODEL_ID in self.model_id:
model_id = SDXL_LIGHTNING_MODEL_ID
model_dir = "models--" + model_id.replace("/", "--")
path = models_path / model_dir
if not path.exists():
models_volume.reload()
if not path.exists():
raise Exception(f"No model found at {path}")
self.pipe = load_pipeline(self.pipeline, self.model_id)
@method()
def predict(self, **kwargs):
return self.pipe(**kwargs)
@stub.cls(
gpu="A10G",
image=pipeline_image,
memory=1024,
volumes={models_path: models_volume},
container_idle_timeout=5 * 60,
)
class A10G_Pipeline(Pipeline):
pass
@stub.cls(
gpu="A100",
image=pipeline_image,
memory=1024,
volumes={models_path: models_volume},
container_idle_timeout=5 * 60,
)
class A100_Pipeline(Pipeline):
pass
# Wrap Pipeline for dependency injection in the runner FastAPI route
class RunnerPipeline:
def __init__(self, pipeline: Pipeline):
self.pipeline = pipeline
self.model_id = pipeline.model_id
def __call__(self, **kwargs):
return self.pipeline.predict.remote(**kwargs)
def make_api(pipeline: str, model_id: str, gpu: str = "A10G"):
from fastapi import FastAPI
config_logging()
app = FastAPI()
app.include_router(health.router)
if gpu == "A10G":
app.pipeline = RunnerPipeline(A10G_Pipeline(pipeline, model_id))
elif gpu == "A100":
app.pipeline = RunnerPipeline(A100_Pipeline(pipeline, model_id))
else:
raise Exception(f"invalid gpu value {gpu}")
app.include_router(load_route(pipeline))
use_route_names_as_operation_ids(app)
return app
@stub.function(image=api_image, secrets=[Secret.from_name("api-auth-token")])
@asgi_app()
def text_to_image_sdxl_lightning_api():
return make_api("text-to-image", "ByteDance/SDXL-Lightning")
@stub.function(image=api_image, secrets=[Secret.from_name("api-auth-token")])
@asgi_app()
def text_to_image_sdxl_lightning_4step_api():
return make_api("text-to-image", "ByteDance/SDXL-Lightning-4step")
@stub.function(image=api_image, secrets=[Secret.from_name("api-auth-token")])
@asgi_app()
def text_to_image_sdxl_lightning_8step_api():
return make_api("text-to-image", "ByteDance/SDXL-Lightning-8step")
@stub.function(image=api_image, secrets=[Secret.from_name("api-auth-token")])
@asgi_app()
def image_to_image_sdxl_lightning_api():
return make_api("image-to-image", "ByteDance/SDXL-Lightning")
@stub.function(image=api_image, secrets=[Secret.from_name("api-auth-token")])
@asgi_app()
def image_to_image_sdxl_lightning_4step_api():
return make_api("image-to-image", "ByteDance/SDXL-Lightning-4step")
@stub.function(image=api_image, secrets=[Secret.from_name("api-auth-token")])
@asgi_app()
def image_to_image_sdxl_lightning_8step_api():
return make_api("image-to-image", "ByteDance/SDXL-Lightning-8step")
@stub.function(image=api_image, secrets=[Secret.from_name("api-auth-token")])
@asgi_app()
def text_to_image_sdxl_turbo_api():
return make_api("text-to-image", "stabilityai/sdxl-turbo")
# @stub.function(image=api_image, secrets=[Secret.from_name("api-auth-token")])
# @asgi_app()
# def image_to_video_svd_api():
# return make_api(
# "image-to-video", "stabilityai/stable-video-diffusion-img2vid-xt", "A100"
# )
@stub.function(image=api_image, secrets=[Secret.from_name("api-auth-token")])
@asgi_app()
def image_to_video_svd_1_1_api():
return make_api(
"image-to-video", "stabilityai/stable-video-diffusion-img2vid-xt-1-1", "A100"
)