Update Modal skill

This commit is contained in:
Timothy Kassis committed 2026-05-28 15:22:47 -07:00
1 parent 01c6a9e8ed
commit f401d0e1f7
9 files changed
+147 -34

No files matched your search

+60 -10
View File
@@ -1,9 +1,9 @@
---
name: modal
description: Cloud computing platform for running Python on GPUs and serverless infrastructure. Use when deploying AI/ML models, running GPU-accelerated workloads, serving web endpoints, scheduling batch jobs, or scaling Python code to the cloud. Use this skill whenever the user mentions Modal, serverless GPU compute, deploying ML models to the cloud, serving inference endpoints, running batch processing in the cloud, or needs to scale Python workloads beyond their local machine. Also use when the user wants to run code on H100s, A100s, or other cloud GPUs, or needs to create a web API for a model.
description: Modal is a serverless cloud platform for running Python on demand, including on-demand GPUs. Use when deploying or serving AI/ML models, running GPU-accelerated workloads (training, fine-tuning, inference), serving web endpoints, scheduling batch jobs, or scaling Python code to cloud containers with the Modal SDK.
license: Apache-2.0
metadata:
version: "1.0"
version: "1.1"
skill-author: K-Dense Inc.
---
@@ -42,13 +42,17 @@ Use this skill when:
uv pip install modal
```
The Modal Python SDK supports Python 3.10–3.14. This skill targets the stable `modal>=1.0` API (current release: 1.4.x).
### Authenticate
Prefer existing credentials before creating new ones:
Prefer existing credentials before creating new ones. Only the two Modal-specific
variables below are relevant — do not read, load, or expose any other environment
variables or `.env` file contents:
1. Check whether `MODAL_TOKEN_ID` and `MODAL_TOKEN_SECRET` are already present in the current environment.
2. If not, check for those values in a local `.env` file and load them if appropriate for the workflow.
3. Only fall back to interactive `modal setup` or generating fresh tokens if neither source already provides credentials.
1. Check whether `MODAL_TOKEN_ID` and `MODAL_TOKEN_SECRET` are already set in the current environment.
2. If not, look up only those two keys in a local `.env` file (ignore all other entries) and load them if appropriate for the workflow.
3. Only fall back to interactive `modal setup` or generating fresh tokens if neither source already provides those two values.
```bash
modal setup
@@ -99,7 +103,7 @@ Modal builds container images from Python code. The recommended package installe
```python
image = (
modal.Image.debian_slim(python_version="3.11")
.uv_pip_install("torch==2.8.0", "transformers", "accelerate")
.uv_pip_install("torch==2.12.0", "transformers==5.9.0", "accelerate==1.13.0")
.apt_install("git")
)
@@ -143,8 +147,9 @@ def flexible_inference():
...
```
Available GPUs: T4, L4, A10, L40S, A100-40GB, A100-80GB, H100, H200, B200, B200+
Available GPUs: T4, L4, A10, L40S, A100-40GB, A100-80GB, RTX-PRO-6000, H100, H200, B200, B200+
- GPUs are always specified as **strings** (e.g. `gpu="H100"`, `gpu="H100:4"`). The old `modal.gpu.*` objects are deprecated as of v0.73.31.
- Up to 8 GPUs per container (except A10: up to 4)
- L40S is recommended for inference (cost/performance balance, 48 GB VRAM)
- H100/A100 can be auto-upgraded to H200/A100-80GB at no extra cost
@@ -173,6 +178,7 @@ def load_model():
- Optimized for write-once, read-many workloads (model weights, datasets)
- CLI access: `modal volume ls`, `modal volume put`, `modal volume get`
- Background auto-commits every few seconds
- Mount read-only or limit to a subdirectory with `vol.with_mount_options(read_only=True, sub_path="subset")`
**Reference**: See `references/volumes.md` for v2 volumes, concurrent writes, and best practices.
@@ -256,15 +262,27 @@ Process inputs in parallel with `.map()`:
results = list(process.map([item1, item2, item3, ...]))
```
Enable concurrent request handling per container:
Enable concurrent request handling per container with `@modal.concurrent`. Set
`target_inputs` (the autoscaler's per-container target) below `max_inputs` (the hard
cap) to keep headroom while scaling up:
```python
@app.function()
@modal.concurrent(max_inputs=10)
@modal.concurrent(max_inputs=10, target_inputs=8)
async def handle_request(req):
...
```
Reconfigure a deployed Function or Cls at invocation time without redeploying using
`Function.with_options()` / `Function.with_concurrency()` / `Function.with_batching()`
(and `Cls.with_options()`):
```python
Model = modal.Cls.from_name("my-app", "Model")
fast = Model.with_options(gpu="H200", max_containers=20)
fast().generate.remote(prompt)
```
**Reference**: See `references/scaling.md` for `.map()`, `.starmap()`, `.spawn()`, and limits.
### Resource Configuration
@@ -306,6 +324,32 @@ class Predictor:
Call with: `Predictor().predict.remote("hello")`
## Sandboxes
For running untrusted or dynamically generated code (for example, AI-agent output or a code interpreter), use a `modal.Sandbox` — an isolated container you create and control programmatically rather than a decorated Function:
```python
app = modal.App.lookup("sandbox-demo", create_if_missing=True)
# Isolated container; restrict egress for untrusted workloads
sb = modal.Sandbox.create(
app=app,
image=modal.Image.debian_slim(),
outbound_cidr_allowlist=["10.0.0.0/8"],
)
# Stream files in/out via the filesystem API (beta)
sb.filesystem.write_text("print(2 ** 10)\n", "/tmp/job.py")
contents = sb.filesystem.read_text("/tmp/job.py")
sb.terminate()
```
- Run commands inside the sandbox with its `exec` method (e.g. run `python /tmp/job.py`) and read stdout from the returned process handle — see `references/api_reference.md`
- Restrict connectivity with `outbound_cidr_allowlist=[...]` / `inbound_cidr_allowlist=[...]`
- Snapshot the filesystem with `sb.snapshot_filesystem()` to reuse as a base image
- Ideal for code interpreters, agent tool execution, and per-user isolation
## Common Workflow Patterns
### GPU Model Inference Service
@@ -387,6 +431,12 @@ def etl_job():
| `modal app list` | List deployed apps |
| `modal app stop <name>` | Stop a deployed app |
## Security Notes
- **Credentials:** Only `MODAL_TOKEN_ID` and `MODAL_TOKEN_SECRET` are needed to authenticate. Do not read, log, or forward any other environment variables or `.env` entries.
- **Subprocess / custom servers:** Some patterns here (multi-GPU training launchers, `@modal.web_server` apps) call `subprocess.run`/`subprocess.Popen` or shell commands during builds. Keep argument lists fixed and hardcoded. Never construct subprocess or shell arguments from unsanitized user input — pass untrusted values as data (files, env vars, stdin), not as command arguments.
- **Untrusted code:** Run user- or model-generated code inside a `modal.Sandbox` (see above), not a regular Function, and restrict network access with CIDR allowlists.
## Reference Files
Detailed documentation for each topic:
+39 -1
View File
@@ -27,7 +27,13 @@ A serverless function backed by an autoscaling container pool.
| `.spawn(*args)` | Execute async, returns `FunctionCall` |
| `.map(inputs)` | Parallel execution over inputs |
| `.starmap(inputs)` | Parallel execution with multiple args |
| `.from_name(app, fn)` | Reference a deployed function |
| `.for_each(inputs)` | Like `.map()` but discards outputs |
| `.spawn_map(inputs)` | Spawn a parallel map without waiting |
| `.from_name(app, fn)` | Reference a deployed function (replaces deprecated `.lookup`) |
| `.hydrate()` | Force-fetch server metadata (replaces deprecated `.resolve()`) |
| `.with_options(gpu=, ...)` | New autoscaling variant with overridden config |
| `.with_concurrency(max_inputs=, target_inputs=)` | Override input concurrency at invocation |
| `.with_batching(max_batch_size=, wait_ms=)` | Override dynamic batching at invocation |
| `.update_autoscaler(**kwargs)` | Dynamic scaling update |
### modal.Cls
@@ -54,6 +60,10 @@ class MyClass:
| `@modal.method()` | Expose as callable method |
| `@modal.parameter()` | Class-level parameter |
Look up a deployed Cls with `Model = modal.Cls.from_name("app", "Model")`, then
instantiate before calling: `Model().method.remote(...)`. Override config at invocation
with `Model.with_options(gpu="H200", max_containers=10)`.
## Image
### modal.Image
@@ -76,8 +86,13 @@ Defines the container environment.
| `.add_local_file(local, remote)` | Add single file |
| `.add_local_python_source(module)` | Add Python module |
| `.env(dict)` | Set environment variables |
| `.pipe(recipe_fn)` | Apply a reusable Image recipe |
| `.imports()` | Context manager for remote imports |
> `add_local_dir`/`add_local_file`/`add_local_python_source` replace the deprecated
> `copy_local_*` methods and the removed `modal.Mount` object / `mount=` / `context_mount=`
> parameters.
## Storage
### modal.Volume
@@ -93,6 +108,7 @@ vol = modal.Volume.from_name("name", create_if_missing=True)
| `.from_name(name)` | Reference or create a volume |
| `.commit()` | Force immediate commit |
| `.reload()` | Refresh to see other containers' writes |
| `.with_mount_options(read_only=, sub_path=)` | Read-only or subdirectory mount |
Mount: `@app.function(volumes={"/path": vol})`
@@ -100,6 +116,28 @@ Mount: `@app.function(volumes={"/path": vol})`
Legacy shared storage (superseded by Volume).
## Sandboxes
### modal.Sandbox
Isolated, programmatically controlled containers for running untrusted or
dynamically generated code.
```python
app = modal.App.lookup("my-app", create_if_missing=True)
sb = modal.Sandbox.create(app=app, image=modal.Image.debian_slim())
```
| Method | Description |
|--------|-------------|
| `.create(app=, image=, ...)` | Launch a sandbox |
| `.exec(*cmd)` | Run a command, returns a process handle |
| `.filesystem.read_text/write_text(...)` | Filesystem API (beta) |
| `.snapshot_filesystem()` | Snapshot the filesystem to an Image |
| `.terminate()` | Stop the sandbox |
Restrict connectivity with `inbound_cidr_allowlist=[...]` / `outbound_cidr_allowlist=[...]`.
## Secrets
### modal.Secret
+14 -4
View File
@@ -1,5 +1,10 @@
# Modal Common Examples
> **Pin dependencies in production.** The version pins below were current at the time of
> writing; bump them to the versions you have validated. For reproducible builds, pin
> every package (and ideally use a lockfile) — unpinned installs can pull in breaking or
> compromised releases.
## LLM Inference Service (vLLM)
```python
@@ -9,7 +14,7 @@ app = modal.App("vllm-service")
image = (
modal.Image.debian_slim(python_version="3.11")
.uv_pip_install("vllm>=0.6.0")
.uv_pip_install("vllm==0.21.0")
)
@app.cls(gpu="H100", image=image, min_containers=1)
@@ -41,7 +46,12 @@ app = modal.App("image-gen")
image = (
modal.Image.debian_slim(python_version="3.11")
.uv_pip_install("diffusers", "torch", "transformers", "accelerate")
.uv_pip_install(
"diffusers==0.38.0",
"torch==2.12.0",
"transformers==5.9.0",
"accelerate==1.13.0",
)
)
vol = modal.Volume.from_name("flux-weights", create_if_missing=True)
@@ -77,7 +87,7 @@ app = modal.App("transcription")
image = (
modal.Image.debian_slim(python_version="3.11")
.apt_install("ffmpeg")
.uv_pip_install("openai-whisper", "torch")
.uv_pip_install("openai-whisper==20250625", "torch==2.12.0")
)
@app.cls(gpu="T4", image=image)
@@ -209,7 +219,7 @@ app = modal.App("api-with-gpu")
image = (
modal.Image.debian_slim(python_version="3.11")
.uv_pip_install("fastapi", "sentence-transformers", "torch")
.uv_pip_install("fastapi==0.136.3", "sentence-transformers==5.5.1", "torch==2.12.0")
)
@app.cls(gpu="L40S", image=image, min_containers=1)
+1 -1
View File
@@ -80,7 +80,7 @@ class Model:
"""Runs once when the container starts."""
import torch
self.model = torch.load("/weights/model.pt")
self.model.eval()
self.model.eval() # PyTorch inference mode — not Python's built-in eval()
@modal.method()
def predict(self, text: str) -> dict:
+1 -5
View File
@@ -2,14 +2,10 @@
## Installation
Install Modal using uv (recommended) or pip:
Install Modal with uv (recommended). The SDK supports Python 3.10–3.14:
```bash
# Recommended
uv pip install modal
# Alternative
pip install modal
```
## Authentication
+9 -6
View File
@@ -46,13 +46,11 @@ gpu="A100-80GB" # Single A100 80GB
gpu="H100:4" # Four H100s
```
### GPU Object (Advanced)
### Case-Insensitive Strings
```python
@app.function(gpu=modal.gpu.H100(count=2))
def multi_gpu():
...
```
GPU strings are case-insensitive, so `gpu="h100"` and `gpu="H100"` are equivalent.
> **Deprecation:** The legacy `modal.gpu.*` objects (e.g. `modal.gpu.H100(count=2)`) are deprecated as of v0.73.31. Always configure GPUs with strings — use `gpu="H100:2"` for multiple GPUs and `gpu="A100-80GB"` for the 80 GB A100.
## GPU Selection Guide
@@ -172,3 +170,8 @@ def finetune():
"train.py"
], check=True)
```
> **Security:** These launchers use fixed, hardcoded argument lists. Never build the
> `subprocess` argument list from unsanitized user input. If a workload needs
> user-supplied values (e.g. hyperparameters), validate them against an allowlist or
> pass them as files / environment variables rather than as command arguments.
+14 -7
View File
@@ -47,10 +47,10 @@ image = modal.Image.from_dockerfile("./Dockerfile")
image = (
modal.Image.debian_slim(python_version="3.11")
.uv_pip_install(
"torch==2.8.0",
"transformers>=4.40",
"accelerate",
"scipy",
"torch==2.12.0",
"transformers==5.9.0",
"accelerate==1.13.0",
"scipy==1.17.1",
)
)
```
@@ -163,6 +163,12 @@ image = modal.Image.debian_slim().add_local_python_source("my_module")
This uses Python's import system to find and include the module.
> As of v1.0, Modal no longer "automounts" imported local modules. You must explicitly
> include local dependencies with `add_local_python_source` (the App's own source is
> still included automatically; set `include_source=False` on the App/Function to opt
> out). The deprecated `modal.Mount` object and the `mount=`/`context_mount=` parameters
> have been replaced by these `Image.add_local_*` methods.
### Individual Files
```python
@@ -193,11 +199,12 @@ Build from existing Dockerfiles:
```python
image = modal.Image.from_dockerfile("./Dockerfile")
# With build context
image = modal.Image.from_dockerfile("./Dockerfile", context_mount=modal.Mount.from_local_dir("."))
```
The build context is now inferred automatically from the Dockerfile's commands. The
old `context_mount=` parameter — along with the `modal.Mount` object it relied on — is
deprecated and was enforced as removed in v1.0; do not pass it.
## Alternative Package Managers
### Micromamba / Conda
@@ -141,3 +141,7 @@ def health_check():
if not status["healthy"]:
requests.post(os.environ["SLACK_URL"], json={"text": f"Alert: {status}"})
```
> The webhook URL is read from a Modal Secret (`SLACK_URL`), not hardcoded or taken
> from untrusted input. Keep notification endpoints in Secrets and avoid POSTing to
> URLs constructed from user-supplied data.
+5
View File
@@ -157,6 +157,11 @@ def serve():
The application must bind to `0.0.0.0` (not `127.0.0.1`).
> **Security:** The command above uses a fixed argument list. Do not interpolate
> unsanitized user input (model names, paths, flags) into `subprocess` arguments —
> validate against an allowlist or pass untrusted values as data, not as command
> arguments, to avoid command injection.
## WebSockets
Supported with `@modal.asgi_app`, `@modal.wsgi_app`, and `@modal.web_server`: