SKILL.md
SKILL.mdBrowse 3 files
2,289 tokens
9,023 bytes
Token encoding: o200k_base
Snapshot 24fd22b
1---2name: modal3description: Serverless GPU cloud for ML jobs and model APIs.4version: 1.0.15author: Orchestra Research6license: MIT7dependencies: [modal>=1.0]8platforms: [linux, macos, windows]9metadata:10 hermes:11 tags: [Infrastructure, Serverless, GPU, Cloud, Deployment, Modal]12 13---14 15# Modal Serverless GPU16 17Guide to running ML workloads on Modal's serverless GPU cloud platform.18 19## When to use Modal20 21**Use Modal when:**22- Running GPU-intensive ML workloads without managing infrastructure23- Deploying ML models as auto-scaling APIs24- Running batch processing jobs (training, inference, data processing)25- Need pay-per-second GPU pricing without idle costs26- Prototyping ML applications quickly27- Running scheduled jobs (cron-like workloads)28 29**Key features:**30- **Serverless GPUs**: T4, L4, A10G, L40S, A100, H100, H200, B200 on-demand31- **Python-native**: Define infrastructure in Python code, no YAML32- **Auto-scaling**: Scale to zero, scale to 100+ GPUs instantly33- **Sub-second cold starts**: Rust-based infrastructure for fast container launches34- **Container caching**: Image layers cached for rapid iteration35- **Web endpoints**: Deploy functions as REST APIs with zero-downtime updates36 37**Use alternatives instead:**38- **RunPod**: For longer-running pods with persistent state39- **Lambda Labs**: For reserved GPU instances40- **SkyPilot**: For multi-cloud orchestration and cost optimization41- **Kubernetes**: For complex multi-service architectures42 43## Quick start44 45### Installation46 47```bash48pip install modal49modal setup # Opens browser for authentication50```51 52### Hello World with GPU53 54```python55import modal56 57app = modal.App("hello-gpu")58 59@app.function(gpu="T4")60def gpu_info():61 import subprocess62 return subprocess.run(["nvidia-smi"], capture_output=True, text=True).stdout63 64@app.local_entrypoint()65def main():66 print(gpu_info.remote())67```68 69Run: `modal run hello_gpu.py`70 71### Basic inference endpoint72 73```python74import modal75 76app = modal.App("text-generation")77image = modal.Image.debian_slim().pip_install("transformers", "torch", "accelerate")78 79@app.cls(gpu="A10G", image=image)80class TextGenerator:81 @modal.enter()82 def load_model(self):83 from transformers import pipeline84 self.pipe = pipeline("text-generation", model="gpt2", device=0)85 86 @modal.method()87 def generate(self, prompt: str) -> str:88 return self.pipe(prompt, max_length=100)[0]["generated_text"]89 90@app.local_entrypoint()91def main():92 print(TextGenerator().generate.remote("Hello, world"))93```94 95## Core concepts96 97### Key components98 99| Component | Purpose |100|-----------|---------|101| `App` | Container for functions and resources |102| `Function` | Serverless function with compute specs |103| `Cls` | Class-based functions with lifecycle hooks |104| `Image` | Container image definition |105| `Volume` | Persistent storage for models/data |106| `Secret` | Secure credential storage |107 108### Execution modes109 110| Command | Description |111|---------|-------------|112| `modal run script.py` | Execute and exit |113| `modal serve script.py` | Development with live reload |114| `modal deploy script.py` | Persistent cloud deployment |115 116## GPU configuration117 118### Available GPUs119 120| GPU | VRAM | Best For |121|-----|------|----------|122| `T4` | 16GB | Budget inference, small models |123| `L4` | 24GB | Inference, Ada Lovelace arch |124| `A10G` | 24GB | Training/inference, 3.3x faster than T4 |125| `L40S` | 48GB | Recommended for inference (best cost/perf) |126| `A100-40GB` | 40GB | Large model training |127| `A100-80GB` | 80GB | Very large models |128| `H100` | 80GB | Fastest, FP8 + Transformer Engine |129| `H200` | 141GB | Auto-upgrade from H100, 4.8TB/s bandwidth |130| `B200` | Latest | Blackwell architecture |131 132### GPU specification patterns133 134```python135# Single GPU136@app.function(gpu="A100")137 138# Specific memory variant139@app.function(gpu="A100-80GB")140 141# Multiple GPUs (up to 8)142@app.function(gpu="H100:4")143 144# GPU with fallbacks145@app.function(gpu=["H100", "A100", "L40S"])146 147# Any available GPU148@app.function(gpu="any")149```150 151## Container images152 153```python154# Basic image with pip155image = modal.Image.debian_slim(python_version="3.11").pip_install(156 "torch==2.1.0", "transformers==4.36.0", "accelerate"157)158 159# From CUDA base160image = modal.Image.from_registry(161 "nvidia/cuda:12.1.0-cudnn8-devel-ubuntu22.04",162 add_python="3.11"163).pip_install("torch", "transformers")164 165# With system packages166image = modal.Image.debian_slim().apt_install("git", "ffmpeg").pip_install("whisper")167```168 169## Persistent storage170 171```python172volume = modal.Volume.from_name("model-cache", create_if_missing=True)173 174@app.function(gpu="A10G", volumes={"/models": volume})175def load_model():176 import os177 model_path = "/models/llama-7b"178 if not os.path.exists(model_path):179 model = download_model()180 model.save_pretrained(model_path)181 volume.commit() # Persist changes182 return load_from_path(model_path)183```184 185## Web endpoints186 187### FastAPI endpoint decorator188 189```python190@app.function()191@modal.fastapi_endpoint(method="POST")192def predict(text: str) -> dict:193 return {"result": model.predict(text)}194```195 196### Full ASGI app197 198```python199from fastapi import FastAPI200web_app = FastAPI()201 202@web_app.post("/predict")203async def predict(text: str):204 return {"result": await model.predict.remote.aio(text)}205 206@app.function()207@modal.asgi_app()208def fastapi_app():209 return web_app210```211 212### Web endpoint types213 214| Decorator | Use Case |215|-----------|----------|216| `@modal.fastapi_endpoint()` | Simple function → API |217| `@modal.asgi_app()` | Full FastAPI/Starlette apps |218| `@modal.wsgi_app()` | Django/Flask apps |219| `@modal.web_server(port)` | Arbitrary HTTP servers |220 221## Dynamic batching222 223```python224@app.function()225@modal.batched(max_batch_size=32, wait_ms=100)226async def batch_predict(inputs: list[str]) -> list[dict]:227 # Inputs automatically batched228 return model.batch_predict(inputs)229```230## Secrets management231 232```bash233# Create secret234modal secret create huggingface HF_TOKEN=hf_xxx235```236 237```python238@app.function(secrets=[modal.Secret.from_name("huggingface")])239def download_model():240 import os241 token = os.environ["HF_TOKEN"]242```243 244## Scheduling245 246```python247@app.function(schedule=modal.Cron("0 0 * * *")) # Daily midnight248def daily_job():249 pass250 251@app.function(schedule=modal.Period(hours=1))252def hourly_job():253 pass254```255 256## Performance optimization257 258### Cold start mitigation259 260```python261# Modal 1.0 autoscaler params: scaledown_window (was container_idle_timeout).262# Input concurrency moved to the @modal.concurrent decorator.263@app.function(scaledown_window=300) # Keep warm 5 min264@modal.concurrent(max_inputs=10) # Handle concurrent requests per container265def inference():266 pass267```268 269### Model loading best practices270 271```python272@app.cls(gpu="A100")273class Model:274 @modal.enter() # Run once at container start275 def load(self):276 self.model = load_model() # Load during warm-up277 278 @modal.method()279 def predict(self, x):280 return self.model(x)281```282 283## Parallel processing284 285```python286@app.function()287def process_item(item):288 return expensive_computation(item)289 290@app.function()291def run_parallel():292 items = list(range(1000))293 # Fan out to parallel containers294 results = list(process_item.map(items))295 return results296```297 298## Common configuration299 300```python301@app.function(302 gpu="A100",303 memory=32768, # 32GB RAM304 cpu=4, # 4 CPU cores305 timeout=3600, # 1 hour max306 scaledown_window=120, # Keep warm 2 min (was container_idle_timeout)307 retries=3, # Retry on failure308 max_containers=10, # Max concurrent containers (was concurrency_limit)309 min_containers=1, # Keep N containers warm (was keep_warm)310)311def my_function():312 pass313```314 315> **Modal 1.0 autoscaler renames** (see the [migration guide](https://modal.com/docs/guide/modal-1-0-migration)):316> - `container_idle_timeout` → `scaledown_window`317> - `concurrency_limit` → `max_containers`318> - `keep_warm` → `min_containers`319> - `allow_concurrent_inputs=N` → the `@modal.concurrent(max_inputs=N)` decorator320 321## Debugging322 323```python324# Test locally325if __name__ == "__main__":326 result = my_function.local()327 328# View logs329# modal app logs my-app330```331 332## Common issues333 334| Issue | Solution |335|-------|----------|336| Cold start latency | Increase `scaledown_window`, use `@modal.enter()` |337| GPU OOM | Use larger GPU (`A100-80GB`), enable gradient checkpointing |338| Image build fails | Pin dependency versions, check CUDA compatibility |339| Timeout errors | Increase `timeout`, add checkpointing |340 341## References342 343- **[Advanced Usage](references/advanced-usage.md)** - Multi-GPU, distributed training, cost optimization344- **[Troubleshooting](references/troubleshooting.md)** - Common issues and solutions345 346## Resources347 348- **Documentation**: https://modal.com/docs349- **Examples**: https://github.com/modal-labs/modal-examples350- **Pricing**: https://modal.com/pricing351- **Discord**: https://discord.gg/modal352 Discovery context
Discovered by repository scan. No exact path reference found in the snapshot’s root AGENTS.md.