mlflow-modal-deploy 0.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- mlflow_modal/__init__.py +29 -0
- mlflow_modal/deployment.py +779 -0
- mlflow_modal_deploy-0.2.0.dist-info/METADATA +242 -0
- mlflow_modal_deploy-0.2.0.dist-info/RECORD +8 -0
- mlflow_modal_deploy-0.2.0.dist-info/WHEEL +5 -0
- mlflow_modal_deploy-0.2.0.dist-info/entry_points.txt +2 -0
- mlflow_modal_deploy-0.2.0.dist-info/licenses/LICENSE +190 -0
- mlflow_modal_deploy-0.2.0.dist-info/top_level.txt +1 -0
mlflow_modal/__init__.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"""
|
|
2
|
+
MLflow Modal Deployment Plugin
|
|
3
|
+
|
|
4
|
+
Deploy MLflow models to Modal's serverless infrastructure.
|
|
5
|
+
See https://modal.com for more information.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from mlflow_modal.deployment import (
|
|
9
|
+
DEFAULT_CPU,
|
|
10
|
+
DEFAULT_GPU,
|
|
11
|
+
DEFAULT_MEMORY,
|
|
12
|
+
DEFAULT_TIMEOUT,
|
|
13
|
+
SUPPORTED_GPUS,
|
|
14
|
+
ModalDeploymentClient,
|
|
15
|
+
run_local,
|
|
16
|
+
target_help,
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
__version__ = "0.1.0"
|
|
20
|
+
__all__ = [
|
|
21
|
+
"ModalDeploymentClient",
|
|
22
|
+
"run_local",
|
|
23
|
+
"target_help",
|
|
24
|
+
"SUPPORTED_GPUS",
|
|
25
|
+
"DEFAULT_GPU",
|
|
26
|
+
"DEFAULT_MEMORY",
|
|
27
|
+
"DEFAULT_CPU",
|
|
28
|
+
"DEFAULT_TIMEOUT",
|
|
29
|
+
]
|
|
@@ -0,0 +1,779 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Modal Deployment Client for MLflow models.
|
|
3
|
+
|
|
4
|
+
This module provides the ModalDeploymentClient class for deploying
|
|
5
|
+
MLflow models to Modal's serverless infrastructure.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import json
|
|
9
|
+
import logging
|
|
10
|
+
import os
|
|
11
|
+
import re
|
|
12
|
+
import subprocess
|
|
13
|
+
import textwrap
|
|
14
|
+
import urllib.parse
|
|
15
|
+
from typing import Any
|
|
16
|
+
|
|
17
|
+
import requests
|
|
18
|
+
from mlflow.deployments import BaseDeploymentClient, PredictionsResponse
|
|
19
|
+
from mlflow.exceptions import MlflowException
|
|
20
|
+
from mlflow.models import Model
|
|
21
|
+
from mlflow.protos.databricks_pb2 import INVALID_PARAMETER_VALUE, RESOURCE_DOES_NOT_EXIST
|
|
22
|
+
from mlflow.pyfunc import FLAVOR_NAME as PYFUNC_FLAVOR_NAME
|
|
23
|
+
from mlflow.tracking.artifact_utils import _download_artifact_from_uri
|
|
24
|
+
from mlflow.utils.file_utils import TempDir
|
|
25
|
+
|
|
26
|
+
_logger = logging.getLogger(__name__)
|
|
27
|
+
|
|
28
|
+
# Default configuration values
|
|
29
|
+
DEFAULT_GPU = None
|
|
30
|
+
DEFAULT_MEMORY = 512 # MB
|
|
31
|
+
DEFAULT_CPU = 1.0
|
|
32
|
+
DEFAULT_TIMEOUT = 300 # seconds
|
|
33
|
+
DEFAULT_CONTAINER_IDLE_TIMEOUT = 60 # seconds
|
|
34
|
+
DEFAULT_ALLOW_CONCURRENT_INPUTS = 1
|
|
35
|
+
DEFAULT_MIN_CONTAINERS = 0
|
|
36
|
+
DEFAULT_MAX_CONTAINERS = None
|
|
37
|
+
DEFAULT_SCALEDOWN_WINDOW = None
|
|
38
|
+
|
|
39
|
+
# Supported GPU types
|
|
40
|
+
SUPPORTED_GPUS = ["T4", "L4", "A10G", "A100", "A100-80GB", "H100"]
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _get_model_requirements(model_path: str) -> tuple[list[str], list[str]]:
|
|
44
|
+
"""
|
|
45
|
+
Extract Python requirements from an MLflow model.
|
|
46
|
+
|
|
47
|
+
Returns:
|
|
48
|
+
Tuple of (pip_requirements, wheel_files) where wheel_files are paths
|
|
49
|
+
to .whl files in the model's code/ directory.
|
|
50
|
+
"""
|
|
51
|
+
requirements = []
|
|
52
|
+
wheel_files = []
|
|
53
|
+
|
|
54
|
+
# Check for wheel files in code/ directory
|
|
55
|
+
code_dir = os.path.join(model_path, "code")
|
|
56
|
+
if os.path.exists(code_dir):
|
|
57
|
+
for filename in os.listdir(code_dir):
|
|
58
|
+
if filename.endswith(".whl"):
|
|
59
|
+
wheel_files.append(os.path.join(code_dir, filename))
|
|
60
|
+
_logger.info(f"Found wheel dependency: {filename}")
|
|
61
|
+
|
|
62
|
+
req_file = os.path.join(model_path, "requirements.txt")
|
|
63
|
+
if os.path.exists(req_file):
|
|
64
|
+
with open(req_file) as f:
|
|
65
|
+
for line in f:
|
|
66
|
+
line = line.strip()
|
|
67
|
+
if line and not line.startswith("#") and not line.lower().startswith("mlflow"):
|
|
68
|
+
# Skip wheel references - we handle them separately
|
|
69
|
+
if not line.endswith(".whl") and "code/" not in line:
|
|
70
|
+
requirements.append(line)
|
|
71
|
+
return requirements, wheel_files
|
|
72
|
+
|
|
73
|
+
conda_file = os.path.join(model_path, "conda.yaml")
|
|
74
|
+
if os.path.exists(conda_file):
|
|
75
|
+
try:
|
|
76
|
+
import yaml
|
|
77
|
+
|
|
78
|
+
with open(conda_file) as f:
|
|
79
|
+
conda_env = yaml.safe_load(f)
|
|
80
|
+
for dep in conda_env.get("dependencies", []):
|
|
81
|
+
if isinstance(dep, dict) and "pip" in dep:
|
|
82
|
+
requirements.extend(
|
|
83
|
+
pip_dep
|
|
84
|
+
for pip_dep in dep["pip"]
|
|
85
|
+
if not pip_dep.lower().startswith("mlflow") and not pip_dep.endswith(".whl")
|
|
86
|
+
)
|
|
87
|
+
elif isinstance(dep, str) and not dep.startswith("python"):
|
|
88
|
+
if not dep.lower().startswith("mlflow"):
|
|
89
|
+
requirements.append(dep)
|
|
90
|
+
except Exception as e:
|
|
91
|
+
_logger.warning(f"Failed to parse conda.yaml: {e}")
|
|
92
|
+
return requirements, wheel_files
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _get_model_python_version(model_path: str) -> str | None:
|
|
96
|
+
"""Extract Python version from an MLflow model."""
|
|
97
|
+
conda_file = os.path.join(model_path, "conda.yaml")
|
|
98
|
+
if os.path.exists(conda_file):
|
|
99
|
+
try:
|
|
100
|
+
import yaml
|
|
101
|
+
|
|
102
|
+
with open(conda_file) as f:
|
|
103
|
+
conda_env = yaml.safe_load(f)
|
|
104
|
+
for dep in conda_env.get("dependencies", []):
|
|
105
|
+
if isinstance(dep, str) and dep.startswith("python"):
|
|
106
|
+
version = dep.split("=")[-1].split(">")[-1].split("<")[-1]
|
|
107
|
+
parts = version.split(".")
|
|
108
|
+
if len(parts) >= 2:
|
|
109
|
+
return f"{parts[0]}.{parts[1]}"
|
|
110
|
+
except Exception as e:
|
|
111
|
+
_logger.warning(f"Failed to parse Python version: {e}")
|
|
112
|
+
return None
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _clear_volume(modal, volume_name: str) -> None:
|
|
116
|
+
"""Clear Modal volume to allow redeployment."""
|
|
117
|
+
try:
|
|
118
|
+
volume = modal.Volume.from_name(volume_name)
|
|
119
|
+
for entry in volume.listdir("/"):
|
|
120
|
+
try:
|
|
121
|
+
volume.remove_file(f"/{entry.path}")
|
|
122
|
+
except Exception:
|
|
123
|
+
pass
|
|
124
|
+
_logger.info(f"Cleared volume: {volume_name}")
|
|
125
|
+
except Exception as e:
|
|
126
|
+
_logger.debug(f"Could not clear volume {volume_name}: {e}")
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _get_preferred_deployment_flavor(model_config):
|
|
130
|
+
"""Obtain the flavor MLflow prefers for deployment."""
|
|
131
|
+
if PYFUNC_FLAVOR_NAME in model_config.flavors:
|
|
132
|
+
return PYFUNC_FLAVOR_NAME
|
|
133
|
+
raise MlflowException(
|
|
134
|
+
message=(
|
|
135
|
+
"The specified model does not contain the python_function flavor "
|
|
136
|
+
"which is required for Modal deployment. "
|
|
137
|
+
f"The model contains the following flavors: {list(model_config.flavors.keys())}."
|
|
138
|
+
),
|
|
139
|
+
error_code=RESOURCE_DOES_NOT_EXIST,
|
|
140
|
+
)
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def _validate_deployment_flavor(model_config, flavor):
|
|
144
|
+
"""Validate that the specified flavor is supported and present in the model."""
|
|
145
|
+
if flavor != PYFUNC_FLAVOR_NAME:
|
|
146
|
+
raise MlflowException(
|
|
147
|
+
message=f"Flavor '{flavor}' is not supported for Modal deployment. "
|
|
148
|
+
f"Only '{PYFUNC_FLAVOR_NAME}' is supported.",
|
|
149
|
+
error_code=INVALID_PARAMETER_VALUE,
|
|
150
|
+
)
|
|
151
|
+
|
|
152
|
+
if flavor not in model_config.flavors:
|
|
153
|
+
raise MlflowException(
|
|
154
|
+
message=f"The specified model does not contain the '{flavor}' flavor. "
|
|
155
|
+
f"Available flavors: {list(model_config.flavors.keys())}.",
|
|
156
|
+
error_code=RESOURCE_DOES_NOT_EXIST,
|
|
157
|
+
)
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def _import_modal():
|
|
161
|
+
"""Import modal and raise helpful error if not installed."""
|
|
162
|
+
try:
|
|
163
|
+
import modal
|
|
164
|
+
|
|
165
|
+
return modal
|
|
166
|
+
except ImportError as e:
|
|
167
|
+
raise MlflowException(
|
|
168
|
+
"The `modal` package is required for Modal deployments. Please install it with: pip install modal"
|
|
169
|
+
) from e
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def _generate_modal_app_code(
|
|
173
|
+
app_name: str,
|
|
174
|
+
model_path: str,
|
|
175
|
+
config: dict[str, Any],
|
|
176
|
+
model_requirements: list[str] | None = None,
|
|
177
|
+
wheel_filenames: list[str] | None = None,
|
|
178
|
+
) -> str:
|
|
179
|
+
"""
|
|
180
|
+
Generate Modal app Python code for serving an MLflow model.
|
|
181
|
+
|
|
182
|
+
Args:
|
|
183
|
+
app_name: Name of the Modal app
|
|
184
|
+
model_path: Path to the MLflow model directory
|
|
185
|
+
config: Deployment configuration
|
|
186
|
+
model_requirements: List of pip requirements
|
|
187
|
+
wheel_filenames: List of wheel filenames (just names, not paths) to install from volume
|
|
188
|
+
"""
|
|
189
|
+
gpu_config = config.get("gpu")
|
|
190
|
+
memory = config.get("memory", DEFAULT_MEMORY)
|
|
191
|
+
cpu = config.get("cpu", DEFAULT_CPU)
|
|
192
|
+
timeout = config.get("timeout", DEFAULT_TIMEOUT)
|
|
193
|
+
container_idle_timeout = config.get("container_idle_timeout", DEFAULT_CONTAINER_IDLE_TIMEOUT)
|
|
194
|
+
enable_batching = config.get("enable_batching", False)
|
|
195
|
+
max_batch_size = config.get("max_batch_size", 8)
|
|
196
|
+
batch_wait_ms = config.get("batch_wait_ms", 100)
|
|
197
|
+
python_version = config.get("python_version", "3.10")
|
|
198
|
+
|
|
199
|
+
gpu_str = f'"{gpu_config}"' if gpu_config else "None"
|
|
200
|
+
|
|
201
|
+
pip_packages = ["mlflow"]
|
|
202
|
+
if model_requirements:
|
|
203
|
+
pip_packages.extend(model_requirements)
|
|
204
|
+
pip_install_str = ", ".join(f'"{pkg}"' for pkg in pip_packages)
|
|
205
|
+
|
|
206
|
+
scaling_parts = []
|
|
207
|
+
min_containers = config.get("min_containers", DEFAULT_MIN_CONTAINERS)
|
|
208
|
+
max_containers = config.get("max_containers")
|
|
209
|
+
scaledown_window = config.get("scaledown_window")
|
|
210
|
+
allow_concurrent_inputs = config.get("allow_concurrent_inputs", DEFAULT_ALLOW_CONCURRENT_INPUTS)
|
|
211
|
+
|
|
212
|
+
if min_containers is not None and min_containers > 0:
|
|
213
|
+
scaling_parts.append(f"min_containers={min_containers}")
|
|
214
|
+
if max_containers is not None:
|
|
215
|
+
scaling_parts.append(f"max_containers={max_containers}")
|
|
216
|
+
if scaledown_window is not None:
|
|
217
|
+
scaling_parts.append(f"scaledown_window={scaledown_window}")
|
|
218
|
+
if allow_concurrent_inputs != DEFAULT_ALLOW_CONCURRENT_INPUTS:
|
|
219
|
+
scaling_parts.append(f"allow_concurrent_inputs={allow_concurrent_inputs}")
|
|
220
|
+
|
|
221
|
+
scaling_str = "\n ".join(f"{part}," for part in scaling_parts)
|
|
222
|
+
|
|
223
|
+
# Generate wheel installation code if wheels are present
|
|
224
|
+
wheel_install_code = ""
|
|
225
|
+
if wheel_filenames:
|
|
226
|
+
wheel_paths = [f"/model/wheels/{whl}" for whl in wheel_filenames]
|
|
227
|
+
wheel_install_code = textwrap.dedent(f"""
|
|
228
|
+
# Install wheel dependencies from volume
|
|
229
|
+
import subprocess
|
|
230
|
+
import sys
|
|
231
|
+
wheel_files = {wheel_paths}
|
|
232
|
+
for whl in wheel_files:
|
|
233
|
+
subprocess.check_call([sys.executable, "-m", "pip", "install", whl, "--quiet"])
|
|
234
|
+
""")
|
|
235
|
+
|
|
236
|
+
code = textwrap.dedent(f'''
|
|
237
|
+
"""
|
|
238
|
+
Modal app for serving MLflow model: {app_name}
|
|
239
|
+
Auto-generated by mlflow-modal plugin
|
|
240
|
+
"""
|
|
241
|
+
import modal
|
|
242
|
+
import os
|
|
243
|
+
|
|
244
|
+
app = modal.App("{app_name}")
|
|
245
|
+
|
|
246
|
+
model_volume = modal.Volume.from_name("{app_name}-model-volume", create_if_missing=True)
|
|
247
|
+
MODEL_DIR = "/model"
|
|
248
|
+
|
|
249
|
+
image = (
|
|
250
|
+
modal.Image.debian_slim(python_version="{python_version}")
|
|
251
|
+
.pip_install({pip_install_str})
|
|
252
|
+
)
|
|
253
|
+
|
|
254
|
+
@app.cls(
|
|
255
|
+
image=image,
|
|
256
|
+
gpu={gpu_str},
|
|
257
|
+
memory={memory},
|
|
258
|
+
cpu={cpu},
|
|
259
|
+
timeout={timeout},
|
|
260
|
+
container_idle_timeout={container_idle_timeout},
|
|
261
|
+
{scaling_str}
|
|
262
|
+
volumes={{MODEL_DIR: model_volume}},
|
|
263
|
+
)
|
|
264
|
+
class MLflowModel:
|
|
265
|
+
@modal.enter()
|
|
266
|
+
def load_model(self):
|
|
267
|
+
import mlflow.pyfunc
|
|
268
|
+
model_volume.reload()
|
|
269
|
+
{wheel_install_code}
|
|
270
|
+
self.model = mlflow.pyfunc.load_model(MODEL_DIR)
|
|
271
|
+
|
|
272
|
+
''')
|
|
273
|
+
|
|
274
|
+
if enable_batching:
|
|
275
|
+
code += textwrap.dedent(f"""
|
|
276
|
+
@modal.batched(max_batch_size={max_batch_size}, wait_ms={batch_wait_ms})
|
|
277
|
+
def predict_batch(self, inputs: list[dict]) -> list[dict]:
|
|
278
|
+
import pandas as pd
|
|
279
|
+
results = []
|
|
280
|
+
for input_data in inputs:
|
|
281
|
+
df = pd.DataFrame(input_data)
|
|
282
|
+
prediction = self.model.predict(df)
|
|
283
|
+
results.append({{"predictions": prediction.tolist()}})
|
|
284
|
+
return results
|
|
285
|
+
|
|
286
|
+
@modal.web_endpoint(method="POST")
|
|
287
|
+
def predict(self, input_data: dict) -> dict:
|
|
288
|
+
return self.predict_batch.local([input_data])[0]
|
|
289
|
+
""")
|
|
290
|
+
else:
|
|
291
|
+
code += textwrap.dedent("""
|
|
292
|
+
@modal.web_endpoint(method="POST")
|
|
293
|
+
def predict(self, input_data: dict) -> dict:
|
|
294
|
+
import pandas as pd
|
|
295
|
+
df = pd.DataFrame(input_data)
|
|
296
|
+
prediction = self.model.predict(df)
|
|
297
|
+
return {"predictions": prediction.tolist()}
|
|
298
|
+
""")
|
|
299
|
+
|
|
300
|
+
return code
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
class ModalDeploymentClient(BaseDeploymentClient):
|
|
304
|
+
"""
|
|
305
|
+
Client for deploying MLflow models to Modal.
|
|
306
|
+
|
|
307
|
+
Modal is a serverless platform for running Python code in the cloud.
|
|
308
|
+
This client enables deploying MLflow models as Modal web endpoints.
|
|
309
|
+
|
|
310
|
+
Args:
|
|
311
|
+
target_uri: A URI that follows one of the following formats:
|
|
312
|
+
- ``modal``: Uses default Modal workspace from environment
|
|
313
|
+
- ``modal:/workspace-name``: Uses the specified workspace
|
|
314
|
+
|
|
315
|
+
Example:
|
|
316
|
+
.. code-block:: python
|
|
317
|
+
|
|
318
|
+
from mlflow.deployments import get_deploy_client
|
|
319
|
+
|
|
320
|
+
client = get_deploy_client("modal")
|
|
321
|
+
client.create_deployment(
|
|
322
|
+
name="my-model",
|
|
323
|
+
model_uri="runs:/abc123/model",
|
|
324
|
+
config={"gpu": "T4", "enable_batching": True},
|
|
325
|
+
)
|
|
326
|
+
"""
|
|
327
|
+
|
|
328
|
+
def __init__(self, target_uri: str):
|
|
329
|
+
super().__init__(target_uri=target_uri)
|
|
330
|
+
self.workspace = self._parse_workspace_from_uri(target_uri)
|
|
331
|
+
self._validate_modal_auth()
|
|
332
|
+
|
|
333
|
+
def _parse_workspace_from_uri(self, target_uri: str) -> str | None:
|
|
334
|
+
"""Parse workspace name from target URI."""
|
|
335
|
+
parsed = urllib.parse.urlparse(target_uri)
|
|
336
|
+
if parsed.scheme == "modal":
|
|
337
|
+
path = parsed.path.strip("/")
|
|
338
|
+
return path or None
|
|
339
|
+
return None
|
|
340
|
+
|
|
341
|
+
def _validate_modal_auth(self):
|
|
342
|
+
"""Validate that Modal authentication is configured."""
|
|
343
|
+
_import_modal()
|
|
344
|
+
|
|
345
|
+
def _default_deployment_config(self) -> dict[str, Any]:
|
|
346
|
+
"""Return default deployment configuration."""
|
|
347
|
+
return {
|
|
348
|
+
"gpu": DEFAULT_GPU,
|
|
349
|
+
"memory": DEFAULT_MEMORY,
|
|
350
|
+
"cpu": DEFAULT_CPU,
|
|
351
|
+
"timeout": DEFAULT_TIMEOUT,
|
|
352
|
+
"container_idle_timeout": DEFAULT_CONTAINER_IDLE_TIMEOUT,
|
|
353
|
+
"enable_batching": False,
|
|
354
|
+
"max_batch_size": 8,
|
|
355
|
+
"batch_wait_ms": 100,
|
|
356
|
+
"allow_concurrent_inputs": DEFAULT_ALLOW_CONCURRENT_INPUTS,
|
|
357
|
+
"min_containers": DEFAULT_MIN_CONTAINERS,
|
|
358
|
+
"max_containers": DEFAULT_MAX_CONTAINERS,
|
|
359
|
+
"scaledown_window": DEFAULT_SCALEDOWN_WINDOW,
|
|
360
|
+
"python_version": None,
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
def _apply_custom_config(self, config: dict[str, Any], custom_config: dict[str, Any] | None) -> dict[str, Any]:
|
|
364
|
+
"""Apply custom configuration over defaults."""
|
|
365
|
+
if not custom_config:
|
|
366
|
+
return config
|
|
367
|
+
|
|
368
|
+
int_fields = {
|
|
369
|
+
"memory",
|
|
370
|
+
"timeout",
|
|
371
|
+
"container_idle_timeout",
|
|
372
|
+
"max_batch_size",
|
|
373
|
+
"batch_wait_ms",
|
|
374
|
+
"min_containers",
|
|
375
|
+
"max_containers",
|
|
376
|
+
"scaledown_window",
|
|
377
|
+
"allow_concurrent_inputs",
|
|
378
|
+
}
|
|
379
|
+
float_fields = {"cpu"}
|
|
380
|
+
bool_fields = {"enable_batching"}
|
|
381
|
+
|
|
382
|
+
for key, value in custom_config.items():
|
|
383
|
+
if key not in config:
|
|
384
|
+
config[key] = value
|
|
385
|
+
continue
|
|
386
|
+
|
|
387
|
+
if value is None:
|
|
388
|
+
config[key] = value
|
|
389
|
+
elif key in int_fields and not isinstance(value, int):
|
|
390
|
+
config[key] = int(value)
|
|
391
|
+
elif key in float_fields and not isinstance(value, float):
|
|
392
|
+
config[key] = float(value)
|
|
393
|
+
elif key in bool_fields and not isinstance(value, bool):
|
|
394
|
+
config[key] = str(value).lower() == "true"
|
|
395
|
+
else:
|
|
396
|
+
config[key] = value
|
|
397
|
+
|
|
398
|
+
if config.get("gpu") and config["gpu"] not in SUPPORTED_GPUS:
|
|
399
|
+
raise MlflowException(
|
|
400
|
+
f"Unsupported GPU type: {config['gpu']}. Supported types: {SUPPORTED_GPUS}",
|
|
401
|
+
error_code=INVALID_PARAMETER_VALUE,
|
|
402
|
+
)
|
|
403
|
+
|
|
404
|
+
return config
|
|
405
|
+
|
|
406
|
+
def create_deployment(
|
|
407
|
+
self,
|
|
408
|
+
name: str,
|
|
409
|
+
model_uri: str,
|
|
410
|
+
flavor: str | None = None,
|
|
411
|
+
config: dict[str, Any] | None = None,
|
|
412
|
+
endpoint: str | None = None,
|
|
413
|
+
) -> dict[str, Any]:
|
|
414
|
+
"""
|
|
415
|
+
Deploy an MLflow model to Modal.
|
|
416
|
+
|
|
417
|
+
Args:
|
|
418
|
+
name: Name of the deployment (will be used as Modal app name)
|
|
419
|
+
model_uri: URI of the MLflow model to deploy
|
|
420
|
+
flavor: Model flavor (only python_function supported)
|
|
421
|
+
config: Deployment configuration dict with keys:
|
|
422
|
+
- gpu: GPU type (T4, L4, A10G, A100, A100-80GB, H100)
|
|
423
|
+
- memory: Memory in MB (default: 512)
|
|
424
|
+
- cpu: CPU cores (default: 1.0)
|
|
425
|
+
- timeout: Request timeout in seconds (default: 300)
|
|
426
|
+
- container_idle_timeout: Idle timeout in seconds (default: 60)
|
|
427
|
+
- enable_batching: Enable dynamic batching (default: False)
|
|
428
|
+
- max_batch_size: Max batch size (default: 8)
|
|
429
|
+
- batch_wait_ms: Batch wait time in ms (default: 100)
|
|
430
|
+
- min_containers: Minimum containers (default: 0)
|
|
431
|
+
- max_containers: Maximum containers (default: None)
|
|
432
|
+
- python_version: Python version (default: auto-detect)
|
|
433
|
+
endpoint: Unused, kept for API compatibility
|
|
434
|
+
|
|
435
|
+
Returns:
|
|
436
|
+
Dictionary with deployment information including endpoint URL
|
|
437
|
+
"""
|
|
438
|
+
modal = _import_modal()
|
|
439
|
+
|
|
440
|
+
with TempDir() as tmp_dir:
|
|
441
|
+
local_model_path = _download_artifact_from_uri(model_uri, output_path=tmp_dir.path())
|
|
442
|
+
model_config = Model.load(local_model_path)
|
|
443
|
+
|
|
444
|
+
if flavor is None:
|
|
445
|
+
flavor = _get_preferred_deployment_flavor(model_config)
|
|
446
|
+
else:
|
|
447
|
+
_validate_deployment_flavor(model_config, flavor)
|
|
448
|
+
|
|
449
|
+
deployment_config = self._default_deployment_config()
|
|
450
|
+
deployment_config = self._apply_custom_config(deployment_config, config)
|
|
451
|
+
|
|
452
|
+
if deployment_config.get("python_version") is None:
|
|
453
|
+
detected_version = _get_model_python_version(local_model_path)
|
|
454
|
+
deployment_config["python_version"] = detected_version or "3.10"
|
|
455
|
+
|
|
456
|
+
model_requirements, wheel_files = _get_model_requirements(local_model_path)
|
|
457
|
+
if model_requirements:
|
|
458
|
+
_logger.info(f"Detected pip requirements: {model_requirements}")
|
|
459
|
+
if wheel_files:
|
|
460
|
+
_logger.info(f"Detected wheel files: {[os.path.basename(w) for w in wheel_files]}")
|
|
461
|
+
|
|
462
|
+
wheel_filenames = [os.path.basename(w) for w in wheel_files] if wheel_files else None
|
|
463
|
+
app_code = _generate_modal_app_code(
|
|
464
|
+
name, local_model_path, deployment_config, model_requirements, wheel_filenames
|
|
465
|
+
)
|
|
466
|
+
|
|
467
|
+
app_file = os.path.join(tmp_dir.path(), "modal_app.py")
|
|
468
|
+
with open(app_file, "w") as f:
|
|
469
|
+
f.write(app_code)
|
|
470
|
+
|
|
471
|
+
volume_name = f"{name}-model-volume"
|
|
472
|
+
_clear_volume(modal, volume_name)
|
|
473
|
+
|
|
474
|
+
_logger.info(f"Uploading model to Modal volume: {volume_name}")
|
|
475
|
+
volume = modal.Volume.from_name(volume_name, create_if_missing=True)
|
|
476
|
+
volume.batch_upload(local_model_path, "/", force=True)
|
|
477
|
+
|
|
478
|
+
# Upload wheel files to a separate wheels/ directory in the volume
|
|
479
|
+
if wheel_files:
|
|
480
|
+
wheels_dir = os.path.join(tmp_dir.path(), "wheels")
|
|
481
|
+
os.makedirs(wheels_dir, exist_ok=True)
|
|
482
|
+
import shutil
|
|
483
|
+
|
|
484
|
+
for whl in wheel_files:
|
|
485
|
+
shutil.copy(whl, wheels_dir)
|
|
486
|
+
_logger.info(f"Uploading {len(wheel_files)} wheel file(s) to volume")
|
|
487
|
+
volume.batch_upload(wheels_dir, "/wheels", force=True)
|
|
488
|
+
|
|
489
|
+
_logger.info(f"Deploying Modal app: {name}")
|
|
490
|
+
deploy_cmd = ["modal", "deploy", app_file]
|
|
491
|
+
if self.workspace:
|
|
492
|
+
deploy_cmd.extend(["--env", self.workspace])
|
|
493
|
+
|
|
494
|
+
result = subprocess.run(deploy_cmd, capture_output=True, text=True, cwd=tmp_dir.path())
|
|
495
|
+
|
|
496
|
+
# Log deployment output for debugging
|
|
497
|
+
if result.stdout:
|
|
498
|
+
for line in result.stdout.strip().split("\n"):
|
|
499
|
+
_logger.info(f"[modal deploy] {line}")
|
|
500
|
+
if result.stderr:
|
|
501
|
+
for line in result.stderr.strip().split("\n"):
|
|
502
|
+
if result.returncode != 0:
|
|
503
|
+
_logger.error(f"[modal deploy] {line}")
|
|
504
|
+
else:
|
|
505
|
+
_logger.warning(f"[modal deploy] {line}")
|
|
506
|
+
|
|
507
|
+
if result.returncode != 0:
|
|
508
|
+
error_msg = result.stderr or result.stdout or "Unknown error"
|
|
509
|
+
raise MlflowException(
|
|
510
|
+
f"Failed to deploy Modal app. Build logs:\n{error_msg}\n\n"
|
|
511
|
+
"Tip: Run with MLFLOW_LOGGING_LEVEL=DEBUG for more details.",
|
|
512
|
+
error_code=INVALID_PARAMETER_VALUE,
|
|
513
|
+
)
|
|
514
|
+
|
|
515
|
+
endpoint_url = None
|
|
516
|
+
for line in result.stdout.split("\n"):
|
|
517
|
+
if "https://" in line and ".modal.run" in line:
|
|
518
|
+
match = re.search(r"(https://[^\s]+\.modal\.run[^\s]*)", line)
|
|
519
|
+
if match:
|
|
520
|
+
endpoint_url = match.group(1)
|
|
521
|
+
break
|
|
522
|
+
|
|
523
|
+
return {
|
|
524
|
+
"name": name,
|
|
525
|
+
"flavor": flavor,
|
|
526
|
+
"model_uri": model_uri,
|
|
527
|
+
"endpoint_url": endpoint_url,
|
|
528
|
+
"config": deployment_config,
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
def update_deployment(
|
|
532
|
+
self,
|
|
533
|
+
name: str,
|
|
534
|
+
model_uri: str | None = None,
|
|
535
|
+
flavor: str | None = None,
|
|
536
|
+
config: dict[str, Any] | None = None,
|
|
537
|
+
endpoint: str | None = None,
|
|
538
|
+
) -> dict[str, Any]:
|
|
539
|
+
"""Update an existing Modal deployment."""
|
|
540
|
+
if model_uri is None:
|
|
541
|
+
raise MlflowException(
|
|
542
|
+
"model_uri is required for updating a Modal deployment",
|
|
543
|
+
error_code=INVALID_PARAMETER_VALUE,
|
|
544
|
+
)
|
|
545
|
+
return self.create_deployment(name, model_uri, flavor, config, endpoint)
|
|
546
|
+
|
|
547
|
+
def delete_deployment(self, name: str, endpoint: str | None = None) -> dict[str, Any]:
|
|
548
|
+
"""Delete a Modal deployment."""
|
|
549
|
+
modal = _import_modal()
|
|
550
|
+
|
|
551
|
+
stop_cmd = ["modal", "app", "stop", name]
|
|
552
|
+
if self.workspace:
|
|
553
|
+
stop_cmd.extend(["--env", self.workspace])
|
|
554
|
+
|
|
555
|
+
result = subprocess.run(stop_cmd, capture_output=True, text=True)
|
|
556
|
+
|
|
557
|
+
volume_name = f"{name}-model-volume"
|
|
558
|
+
try:
|
|
559
|
+
volume = modal.Volume.from_name(volume_name)
|
|
560
|
+
volume.delete()
|
|
561
|
+
_logger.info(f"Deleted volume: {volume_name}")
|
|
562
|
+
except Exception as e:
|
|
563
|
+
_logger.debug(f"Could not delete volume {volume_name}: {e}")
|
|
564
|
+
|
|
565
|
+
if result.returncode != 0 and "not found" not in result.stderr.lower():
|
|
566
|
+
raise MlflowException(
|
|
567
|
+
f"Failed to delete Modal app: {result.stderr}",
|
|
568
|
+
error_code=INVALID_PARAMETER_VALUE,
|
|
569
|
+
)
|
|
570
|
+
|
|
571
|
+
return {"name": name, "deleted": True}
|
|
572
|
+
|
|
573
|
+
def list_deployments(self, endpoint: str | None = None) -> list[dict[str, Any]]:
|
|
574
|
+
"""List all Modal deployments."""
|
|
575
|
+
list_cmd = ["modal", "app", "list", "--json"]
|
|
576
|
+
if self.workspace:
|
|
577
|
+
list_cmd.extend(["--env", self.workspace])
|
|
578
|
+
|
|
579
|
+
result = subprocess.run(list_cmd, capture_output=True, text=True)
|
|
580
|
+
|
|
581
|
+
if result.returncode != 0:
|
|
582
|
+
raise MlflowException(
|
|
583
|
+
f"Failed to list Modal apps: {result.stderr}",
|
|
584
|
+
error_code=INVALID_PARAMETER_VALUE,
|
|
585
|
+
)
|
|
586
|
+
|
|
587
|
+
try:
|
|
588
|
+
apps = json.loads(result.stdout) if result.stdout.strip() else []
|
|
589
|
+
except json.JSONDecodeError:
|
|
590
|
+
apps = []
|
|
591
|
+
|
|
592
|
+
return [{"name": app.get("name", app.get("app_id", "unknown"))} for app in apps]
|
|
593
|
+
|
|
594
|
+
def get_deployment(self, name: str, endpoint: str | None = None) -> dict[str, Any]:
|
|
595
|
+
"""Get information about a specific Modal deployment."""
|
|
596
|
+
deployments = self.list_deployments()
|
|
597
|
+
for deployment in deployments:
|
|
598
|
+
if deployment.get("name") == name:
|
|
599
|
+
return deployment
|
|
600
|
+
|
|
601
|
+
raise MlflowException(
|
|
602
|
+
f"Deployment '{name}' not found",
|
|
603
|
+
error_code=RESOURCE_DOES_NOT_EXIST,
|
|
604
|
+
)
|
|
605
|
+
|
|
606
|
+
def predict(
|
|
607
|
+
self,
|
|
608
|
+
deployment_name: str | None = None,
|
|
609
|
+
inputs: Any = None,
|
|
610
|
+
endpoint: str | None = None,
|
|
611
|
+
) -> PredictionsResponse:
|
|
612
|
+
"""Make predictions using a deployed Modal model."""
|
|
613
|
+
if deployment_name is None:
|
|
614
|
+
raise MlflowException(
|
|
615
|
+
"deployment_name is required",
|
|
616
|
+
error_code=INVALID_PARAMETER_VALUE,
|
|
617
|
+
)
|
|
618
|
+
|
|
619
|
+
deployment = self.get_deployment(deployment_name)
|
|
620
|
+
endpoint_url = deployment.get("endpoint_url")
|
|
621
|
+
|
|
622
|
+
if not endpoint_url:
|
|
623
|
+
list_cmd = ["modal", "app", "list", "--json"]
|
|
624
|
+
if self.workspace:
|
|
625
|
+
list_cmd.extend(["--env", self.workspace])
|
|
626
|
+
|
|
627
|
+
result = subprocess.run(list_cmd, capture_output=True, text=True)
|
|
628
|
+
if result.returncode == 0:
|
|
629
|
+
try:
|
|
630
|
+
apps = json.loads(result.stdout) if result.stdout.strip() else []
|
|
631
|
+
for app in apps:
|
|
632
|
+
if app.get("name") == deployment_name or app.get("app_id") == deployment_name:
|
|
633
|
+
for func in app.get("functions", []):
|
|
634
|
+
if "predict" in func.get("name", "").lower():
|
|
635
|
+
endpoint_url = func.get("web_url")
|
|
636
|
+
break
|
|
637
|
+
except json.JSONDecodeError:
|
|
638
|
+
pass
|
|
639
|
+
|
|
640
|
+
if not endpoint_url:
|
|
641
|
+
raise MlflowException(
|
|
642
|
+
f"Could not find endpoint URL for deployment '{deployment_name}'. "
|
|
643
|
+
"The deployment may not have a web endpoint configured.",
|
|
644
|
+
error_code=RESOURCE_DOES_NOT_EXIST,
|
|
645
|
+
)
|
|
646
|
+
|
|
647
|
+
response = requests.post(endpoint_url, json=inputs, timeout=300)
|
|
648
|
+
response.raise_for_status()
|
|
649
|
+
|
|
650
|
+
return PredictionsResponse(predictions=response.json())
|
|
651
|
+
|
|
652
|
+
|
|
653
|
+
def run_local(
|
|
654
|
+
target_uri: str,
|
|
655
|
+
name: str,
|
|
656
|
+
model_uri: str,
|
|
657
|
+
flavor: str | None = None,
|
|
658
|
+
config: dict[str, Any] | None = None,
|
|
659
|
+
) -> None:
|
|
660
|
+
"""
|
|
661
|
+
Run a Modal deployment locally using `modal serve`.
|
|
662
|
+
|
|
663
|
+
Args:
|
|
664
|
+
target_uri: Target URI (e.g., "modal")
|
|
665
|
+
name: Name for the local deployment
|
|
666
|
+
model_uri: URI of the MLflow model to deploy
|
|
667
|
+
flavor: Model flavor (only python_function supported)
|
|
668
|
+
config: Deployment configuration
|
|
669
|
+
"""
|
|
670
|
+
_import_modal()
|
|
671
|
+
|
|
672
|
+
with TempDir() as tmp_dir:
|
|
673
|
+
local_model_path = _download_artifact_from_uri(model_uri, output_path=tmp_dir.path())
|
|
674
|
+
|
|
675
|
+
deployment_config = ModalDeploymentClient("modal")._default_deployment_config()
|
|
676
|
+
if config:
|
|
677
|
+
deployment_config.update(config)
|
|
678
|
+
|
|
679
|
+
if deployment_config.get("python_version") is None:
|
|
680
|
+
detected_version = _get_model_python_version(local_model_path)
|
|
681
|
+
deployment_config["python_version"] = detected_version or "3.10"
|
|
682
|
+
|
|
683
|
+
model_requirements, wheel_files = _get_model_requirements(local_model_path)
|
|
684
|
+
if model_requirements:
|
|
685
|
+
_logger.info(f"Detected pip requirements: {model_requirements}")
|
|
686
|
+
if wheel_files:
|
|
687
|
+
_logger.info(f"Detected wheel files: {[os.path.basename(w) for w in wheel_files]}")
|
|
688
|
+
|
|
689
|
+
wheel_filenames = [os.path.basename(w) for w in wheel_files] if wheel_files else None
|
|
690
|
+
app_code = _generate_modal_app_code(
|
|
691
|
+
name, local_model_path, deployment_config, model_requirements, wheel_filenames
|
|
692
|
+
)
|
|
693
|
+
|
|
694
|
+
app_file = os.path.join(tmp_dir.path(), "modal_app.py")
|
|
695
|
+
with open(app_file, "w") as f:
|
|
696
|
+
f.write(app_code)
|
|
697
|
+
|
|
698
|
+
_logger.info(f"Starting local Modal server for {name}...")
|
|
699
|
+
subprocess.run(["modal", "serve", app_file], cwd=tmp_dir.path())
|
|
700
|
+
|
|
701
|
+
|
|
702
|
+
def target_help() -> str:
|
|
703
|
+
"""Return help text for the Modal deployment target."""
|
|
704
|
+
return """
|
|
705
|
+
MLflow Modal Deployment Plugin
|
|
706
|
+
==============================
|
|
707
|
+
|
|
708
|
+
Deploy MLflow models to Modal's serverless platform (https://modal.com).
|
|
709
|
+
|
|
710
|
+
Installation
|
|
711
|
+
------------
|
|
712
|
+
pip install mlflow-modal
|
|
713
|
+
|
|
714
|
+
Target URI Format
|
|
715
|
+
-----------------
|
|
716
|
+
- ``modal``: Use default workspace from Modal authentication
|
|
717
|
+
- ``modal:/workspace-name``: Use a specific Modal environment/workspace
|
|
718
|
+
|
|
719
|
+
Authentication
|
|
720
|
+
--------------
|
|
721
|
+
Modal authentication is handled via the Modal CLI or environment variables:
|
|
722
|
+
- Run ``modal setup`` to configure authentication interactively
|
|
723
|
+
- Or set MODAL_TOKEN_ID and MODAL_TOKEN_SECRET environment variables
|
|
724
|
+
|
|
725
|
+
Configuration Options
|
|
726
|
+
---------------------
|
|
727
|
+
Pass these options via the ``config`` parameter in create_deployment():
|
|
728
|
+
|
|
729
|
+
Resource Configuration:
|
|
730
|
+
- ``gpu``: GPU type (T4, L4, A10G, A100, A100-80GB, H100)
|
|
731
|
+
- ``memory``: Memory allocation in MB (default: 512)
|
|
732
|
+
- ``cpu``: CPU cores (default: 1.0)
|
|
733
|
+
- ``timeout``: Request timeout in seconds (default: 300)
|
|
734
|
+
|
|
735
|
+
Scaling Configuration:
|
|
736
|
+
- ``min_containers``: Minimum containers to keep warm (default: 0)
|
|
737
|
+
- ``max_containers``: Maximum containers to scale to (default: None)
|
|
738
|
+
- ``container_idle_timeout``: Container idle timeout in seconds (default: 60)
|
|
739
|
+
- ``scaledown_window``: Time window for scale-down decisions in seconds
|
|
740
|
+
- ``allow_concurrent_inputs``: Concurrent inputs per container (default: 1)
|
|
741
|
+
|
|
742
|
+
Batching Configuration:
|
|
743
|
+
- ``enable_batching``: Enable dynamic batching (default: False)
|
|
744
|
+
- ``max_batch_size``: Maximum batch size when batching enabled (default: 8)
|
|
745
|
+
- ``batch_wait_ms``: Batch wait time in milliseconds (default: 100)
|
|
746
|
+
|
|
747
|
+
Example
|
|
748
|
+
-------
|
|
749
|
+
.. code-block:: python
|
|
750
|
+
|
|
751
|
+
from mlflow.deployments import get_deploy_client
|
|
752
|
+
|
|
753
|
+
client = get_deploy_client("modal")
|
|
754
|
+
|
|
755
|
+
deployment = client.create_deployment(
|
|
756
|
+
name="my-classifier",
|
|
757
|
+
model_uri="runs:/abc123/model",
|
|
758
|
+
config={
|
|
759
|
+
"gpu": "T4",
|
|
760
|
+
"memory": 2048,
|
|
761
|
+
"min_containers": 1,
|
|
762
|
+
"enable_batching": True,
|
|
763
|
+
}
|
|
764
|
+
)
|
|
765
|
+
|
|
766
|
+
predictions = client.predict(
|
|
767
|
+
deployment_name="my-classifier",
|
|
768
|
+
inputs={"feature1": [1, 2, 3], "feature2": [4, 5, 6]}
|
|
769
|
+
)
|
|
770
|
+
|
|
771
|
+
CLI Usage
|
|
772
|
+
---------
|
|
773
|
+
.. code-block:: bash
|
|
774
|
+
|
|
775
|
+
mlflow deployments create -t modal -m runs:/abc123/model --name my-model
|
|
776
|
+
mlflow deployments list -t modal
|
|
777
|
+
mlflow deployments get -t modal --name my-model
|
|
778
|
+
mlflow deployments delete -t modal --name my-model
|
|
779
|
+
"""
|
|
@@ -0,0 +1,242 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: mlflow-modal-deploy
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: MLflow deployment plugin for Modal serverless GPU infrastructure (actively maintained)
|
|
5
|
+
Home-page: https://github.com/debu-sinha/mlflow-modal
|
|
6
|
+
Author: Debu Sinha
|
|
7
|
+
Author-email: debu.sinha@example.com
|
|
8
|
+
License: Apache-2.0
|
|
9
|
+
Project-URL: Homepage, https://github.com/debu-sinha/mlflow-modal-deploy
|
|
10
|
+
Project-URL: Repository, https://github.com/debu-sinha/mlflow-modal-deploy
|
|
11
|
+
Project-URL: Issues, https://github.com/debu-sinha/mlflow-modal-deploy/issues
|
|
12
|
+
Keywords: mlflow,modal,deployment,serverless,machine-learning
|
|
13
|
+
Classifier: Development Status :: 4 - Beta
|
|
14
|
+
Classifier: Intended Audience :: Developers
|
|
15
|
+
Classifier: Intended Audience :: Science/Research
|
|
16
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
17
|
+
Classifier: Operating System :: OS Independent
|
|
18
|
+
Classifier: Programming Language :: Python :: 3
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
22
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
23
|
+
Requires-Python: >=3.10
|
|
24
|
+
Description-Content-Type: text/markdown
|
|
25
|
+
License-File: LICENSE
|
|
26
|
+
Requires-Dist: mlflow>=2.10.0
|
|
27
|
+
Requires-Dist: modal>=0.64.0
|
|
28
|
+
Provides-Extra: dev
|
|
29
|
+
Requires-Dist: pytest>=7.0.0; extra == "dev"
|
|
30
|
+
Requires-Dist: pytest-cov>=4.0.0; extra == "dev"
|
|
31
|
+
Requires-Dist: ruff>=0.1.0; extra == "dev"
|
|
32
|
+
Requires-Dist: twine>=4.0.0; extra == "dev"
|
|
33
|
+
Requires-Dist: build>=1.0.0; extra == "dev"
|
|
34
|
+
Dynamic: author-email
|
|
35
|
+
Dynamic: home-page
|
|
36
|
+
Dynamic: license-file
|
|
37
|
+
Dynamic: requires-python
|
|
38
|
+
|
|
39
|
+
# mlflow-modal-deploy
|
|
40
|
+
|
|
41
|
+
[](https://github.com/debu-sinha/mlflow-modal-deploy/actions/workflows/ci.yml)
|
|
42
|
+
[](https://badge.fury.io/py/mlflow-modal-deploy)
|
|
43
|
+
[](https://opensource.org/licenses/Apache-2.0)
|
|
44
|
+
[](https://www.python.org/downloads/)
|
|
45
|
+
|
|
46
|
+
Deploy MLflow models to [Modal](https://modal.com)'s serverless GPU infrastructure with a single command.
|
|
47
|
+
|
|
48
|
+
## Installation
|
|
49
|
+
|
|
50
|
+
```bash
|
|
51
|
+
pip install mlflow-modal-deploy
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
## Features
|
|
55
|
+
|
|
56
|
+
- **One-command deployment**: Deploy any MLflow model to Modal's serverless infrastructure
|
|
57
|
+
- **GPU support**: T4, L4, A10G, A100, A100-80GB, H100
|
|
58
|
+
- **Auto-scaling**: Configure min/max containers, scale-down windows
|
|
59
|
+
- **Dynamic batching**: Built-in request batching for high-throughput workloads
|
|
60
|
+
- **Automatic dependency detection**: Extracts requirements from model artifacts
|
|
61
|
+
- **Wheel file support**: Handles private dependencies packaged as wheel files
|
|
62
|
+
- **MLflow CLI integration**: Use familiar `mlflow deployments` commands
|
|
63
|
+
|
|
64
|
+
## Quick Start
|
|
65
|
+
|
|
66
|
+
### Python API
|
|
67
|
+
|
|
68
|
+
```python
|
|
69
|
+
from mlflow.deployments import get_deploy_client
|
|
70
|
+
|
|
71
|
+
# Get the Modal deployment client
|
|
72
|
+
client = get_deploy_client("modal")
|
|
73
|
+
|
|
74
|
+
# Deploy a model
|
|
75
|
+
deployment = client.create_deployment(
|
|
76
|
+
name="my-classifier",
|
|
77
|
+
model_uri="runs:/abc123/model",
|
|
78
|
+
config={
|
|
79
|
+
"gpu": "T4",
|
|
80
|
+
"memory": 2048,
|
|
81
|
+
"min_containers": 1,
|
|
82
|
+
}
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
print(f"Deployed to: {deployment['endpoint_url']}")
|
|
86
|
+
|
|
87
|
+
# Make predictions
|
|
88
|
+
predictions = client.predict(
|
|
89
|
+
deployment_name="my-classifier",
|
|
90
|
+
inputs={"feature1": [1, 2, 3], "feature2": [4, 5, 6]}
|
|
91
|
+
)
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
### CLI
|
|
95
|
+
|
|
96
|
+
```bash
|
|
97
|
+
# Deploy a model
|
|
98
|
+
mlflow deployments create -t modal -m runs:/abc123/model --name my-model
|
|
99
|
+
|
|
100
|
+
# Deploy with GPU
|
|
101
|
+
mlflow deployments create -t modal -m runs:/abc123/model --name gpu-model \
|
|
102
|
+
-C gpu=T4 -C memory=4096
|
|
103
|
+
|
|
104
|
+
# List deployments
|
|
105
|
+
mlflow deployments list -t modal
|
|
106
|
+
|
|
107
|
+
# Get deployment info
|
|
108
|
+
mlflow deployments get -t modal --name my-model
|
|
109
|
+
|
|
110
|
+
# Delete deployment
|
|
111
|
+
mlflow deployments delete -t modal --name my-model
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
## Configuration Options
|
|
115
|
+
|
|
116
|
+
| Option | Type | Default | Description |
|
|
117
|
+
|--------|------|---------|-------------|
|
|
118
|
+
| `gpu` | str | None | GPU type: T4, L4, A10G, A100, A100-80GB, H100 |
|
|
119
|
+
| `memory` | int | 512 | Memory allocation in MB |
|
|
120
|
+
| `cpu` | float | 1.0 | CPU cores |
|
|
121
|
+
| `timeout` | int | 300 | Request timeout in seconds |
|
|
122
|
+
| `container_idle_timeout` | int | 60 | Container idle timeout in seconds |
|
|
123
|
+
| `min_containers` | int | 0 | Minimum warm containers |
|
|
124
|
+
| `max_containers` | int | None | Maximum containers |
|
|
125
|
+
| `enable_batching` | bool | False | Enable dynamic batching |
|
|
126
|
+
| `max_batch_size` | int | 8 | Max batch size when batching enabled |
|
|
127
|
+
| `batch_wait_ms` | int | 100 | Batch wait time in milliseconds |
|
|
128
|
+
| `python_version` | str | auto | Python version (auto-detected from model) |
|
|
129
|
+
|
|
130
|
+
## Authentication
|
|
131
|
+
|
|
132
|
+
Configure Modal authentication before deploying:
|
|
133
|
+
|
|
134
|
+
```bash
|
|
135
|
+
# Interactive setup
|
|
136
|
+
modal setup
|
|
137
|
+
|
|
138
|
+
# Or use environment variables
|
|
139
|
+
export MODAL_TOKEN_ID=your-token-id
|
|
140
|
+
export MODAL_TOKEN_SECRET=your-token-secret
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
## Advanced Usage
|
|
144
|
+
|
|
145
|
+
### Deploy to Specific Workspace
|
|
146
|
+
|
|
147
|
+
```python
|
|
148
|
+
# Use workspace-specific URI
|
|
149
|
+
client = get_deploy_client("modal:/production")
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
Or via CLI:
|
|
153
|
+
|
|
154
|
+
```bash
|
|
155
|
+
mlflow deployments create -t modal:/production -m runs:/abc123/model --name my-model
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
### High-Throughput Deployment with Batching
|
|
159
|
+
|
|
160
|
+
```python
|
|
161
|
+
client.create_deployment(
|
|
162
|
+
name="batch-classifier",
|
|
163
|
+
model_uri="runs:/abc123/model",
|
|
164
|
+
config={
|
|
165
|
+
"gpu": "A100",
|
|
166
|
+
"enable_batching": True,
|
|
167
|
+
"max_batch_size": 32,
|
|
168
|
+
"batch_wait_ms": 50,
|
|
169
|
+
"min_containers": 2,
|
|
170
|
+
"max_containers": 20,
|
|
171
|
+
}
|
|
172
|
+
)
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
### Models with Private Dependencies
|
|
176
|
+
|
|
177
|
+
If your model includes wheel files in the `code/` directory, they are automatically detected and installed:
|
|
178
|
+
|
|
179
|
+
```
|
|
180
|
+
model/
|
|
181
|
+
├── MLmodel
|
|
182
|
+
├── requirements.txt
|
|
183
|
+
├── code/
|
|
184
|
+
│ └── my_private_package-1.0.0-py3-none-any.whl # Auto-detected
|
|
185
|
+
└── ...
|
|
186
|
+
```
|
|
187
|
+
|
|
188
|
+
### Local Development
|
|
189
|
+
|
|
190
|
+
Test your deployment locally before deploying to Modal:
|
|
191
|
+
|
|
192
|
+
```python
|
|
193
|
+
from mlflow_modal import run_local
|
|
194
|
+
|
|
195
|
+
run_local(
|
|
196
|
+
target_uri="modal",
|
|
197
|
+
name="test-model",
|
|
198
|
+
model_uri="runs:/abc123/model",
|
|
199
|
+
config={"gpu": "T4"}
|
|
200
|
+
)
|
|
201
|
+
```
|
|
202
|
+
|
|
203
|
+
## Requirements
|
|
204
|
+
|
|
205
|
+
- Python 3.10+
|
|
206
|
+
- MLflow 2.10.0+
|
|
207
|
+
- Modal 0.64.0+
|
|
208
|
+
|
|
209
|
+
## Contributing
|
|
210
|
+
|
|
211
|
+
Contributions welcome! Please see [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines.
|
|
212
|
+
|
|
213
|
+
### Development Setup
|
|
214
|
+
|
|
215
|
+
```bash
|
|
216
|
+
# Clone the repository
|
|
217
|
+
git clone https://github.com/debu-sinha/mlflow-modal-deploy.git
|
|
218
|
+
cd mlflow-modal-deploy
|
|
219
|
+
|
|
220
|
+
# Install with dev dependencies
|
|
221
|
+
uv sync --extra dev
|
|
222
|
+
|
|
223
|
+
# Install pre-commit hooks
|
|
224
|
+
uv run pre-commit install
|
|
225
|
+
|
|
226
|
+
# Run tests
|
|
227
|
+
uv run pytest tests/ -v
|
|
228
|
+
```
|
|
229
|
+
|
|
230
|
+
## License
|
|
231
|
+
|
|
232
|
+
Apache License 2.0
|
|
233
|
+
|
|
234
|
+
## Acknowledgments
|
|
235
|
+
|
|
236
|
+
- [MLflow](https://mlflow.org/) - Open source platform for the ML lifecycle
|
|
237
|
+
- [Modal](https://modal.com/) - Serverless cloud for AI/ML
|
|
238
|
+
|
|
239
|
+
## Support
|
|
240
|
+
|
|
241
|
+
- [GitHub Issues](https://github.com/debu-sinha/mlflow-modal-deploy/issues) - Bug reports and feature requests
|
|
242
|
+
- [MLflow Slack](https://mlflow.org/slack) - Community discussion
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
mlflow_modal/__init__.py,sha256=AirbpCl81V1qpEt8t6vP2sdMrxCmhWCiXZw9Xc24f_E,545
|
|
2
|
+
mlflow_modal/deployment.py,sha256=iameFi9sc_BJVmMU6BNYAmgdFk1qlS_1Ulk9V42Zyl0,29484
|
|
3
|
+
mlflow_modal_deploy-0.2.0.dist-info/licenses/LICENSE,sha256=2rWZc3jxeOoY5vVVgr7oI-oJJoTBNat6vchfwzPK8pQ,10759
|
|
4
|
+
mlflow_modal_deploy-0.2.0.dist-info/METADATA,sha256=gnnNqAEP4wQNUKG22YuEb1h5DcpbLcGXhvkjlEFizEU,6848
|
|
5
|
+
mlflow_modal_deploy-0.2.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
|
|
6
|
+
mlflow_modal_deploy-0.2.0.dist-info/entry_points.txt,sha256=EzJMKb71JNQlHMnU__zFqfNhQh6w8XEuGko54SSroow,75
|
|
7
|
+
mlflow_modal_deploy-0.2.0.dist-info/top_level.txt,sha256=pZaQEqSmi6kuM89dAA953A3qb6DswJRUmWgOfK4OyH0,13
|
|
8
|
+
mlflow_modal_deploy-0.2.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to the Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
Copyright 2025 Debu Sinha
|
|
179
|
+
|
|
180
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
181
|
+
you may not use this file except in compliance with the License.
|
|
182
|
+
You may obtain a copy of the License at
|
|
183
|
+
|
|
184
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
185
|
+
|
|
186
|
+
Unless required by applicable law or agreed to in writing, software
|
|
187
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
188
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
189
|
+
See the License for the specific language governing permissions and
|
|
190
|
+
limitations under the License.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
mlflow_modal
|