关于 alterlab-modal
alterlab-modal 是在 Modal 无服务器云平台运行 Python 函数的技能,面向 AI/ML 开发者和研究人员,介绍 GPU 计算、并行任务、定时作业及 API 部署。
主要功能
- 01定义云端 Python 函数
- 02构建容器镜像和依赖
- 03申请 GPU 与计算资源
- 04自动扩展并行工作负载
- 05使用 Volumes 持久化数据
- 06部署端点和定时作业
适用场景
- 01部署 ML 模型推理服务
- 02并行处理大型数据集
- 03使用 GPU 训练模型
- 04运行周期性计算任务
安装
复制下面的命令,在终端中运行。
npx skills add https:/ / github.com/ alterlab-ieu/ alterlab-academic-skills --skill alterlab-modal安装后在 Claude Code 中输入/alterlab-modal确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
evals/evals.jsonreferences/examples.mdfunctions.mdgetting-started.mdgpu.mdimages.mdresources.mdscaling.mdscheduled-jobs.mdsecrets.mdvolumes.mdweb-endpoints.md详细介绍
Modal
概述
Modal 是一个无服务器平台,可通过最少的配置在云端运行 Python 代码。使用强大的 GPU 执行函数,自动扩展到数千个容器,并且只为实际使用的计算资源付费。
Modal 尤其适用于 AI/ML 工作负载、高性能批处理、定时任务、GPU 推理和无服务器 API。前往 https://modal.com 免费注册,即可获得每月 $30 的额度。
何时使用此技能
在以下情况下使用 Modal:
- 部署和提供 ML 模型(LLM、图像生成、嵌入模型)
- 运行 GPU 加速计算(训练、推理、渲染)
- 并行处理大型数据集
- 安排计算密集型任务(每日数据处理、模型训练)
- 构建需要自动扩展的无服务器 API
- 执行需要分布式计算或专用硬件的科学计算
不适用的情况
| 场景 | 改用 |
|---|---|
| 以提供商无关的方式向 SLURM/HPC、RunPod 或 GCP Batch 派发任务(提交 → 轮询 → 收集) | alterlab-remote-compute |
| 本地 PyTorch 训练结构、多 GPU 策略、检查点处理 — 不涉及无服务器部署 | alterlab-pytorch-lightning |
| 在 Latch 平台上运行生物信息学工作流 | alterlab-latchbio |
| 在 DNAnexus 上开发基因组学应用/小程序 | alterlab-dnanexus |
身份验证与设置
Modal 需要通过 API 令牌进行身份验证。
初始设置
# Install Modal (SDK 1.x; current 1.5.x as of 2026-09)
uv pip install modal
# Authenticate (opens browser for login)
modal token new
这会创建一个存储在 ~/.modal.toml 中的令牌。该令牌用于验证所有 Modal 操作。
验证设置
import modal
app = modal.App("test-app")
@app.function()
def hello():
print("Modal is working!")
使用以下命令运行:modal run script.py
核心功能
Modal 通过在容器中运行的函数提供无服务器 Python 执行能力。以声明式方式定义计算需求、依赖项和扩展行为。
1. 定义容器映像
使用 Modal Images 为函数指定依赖项和环境。
import modal
# Basic image with Python packages
image = (
modal.Image.debian_slim(python_version="3.12")
.uv_pip_install("torch", "transformers", "numpy")
)
app = modal.App("ml-app", image=image)
常见模式:
- 安装 Python 包:
.uv_pip_install("pandas", "scikit-learn") - 安装系统包:
.apt_install("ffmpeg", "git") - 使用现有 Docker 映像:
modal.Image.from_registry("nvidia/cuda:12.8.1-devel-ubuntu24.04", add_python="3.12")(使用完整标签 — NVIDIA 不发布不带后缀的12.x.y-base标签) - 添加本地代码:
.add_local_python_source("my_module")
有关映像构建的完整文档,请参阅 references/images.md。
2. 创建函数
使用 @app.function() 装饰器定义在云端运行的函数。
@app.function()
def process_data(file_path: str):
import pandas as pd
df = pd.read_csv(file_path)
return df.describe()
调用函数:
# From local entrypoint
@app.local_entrypoint()
def main():
result = process_data.remote("data.csv")
print(result)
使用以下命令运行:modal run script.py
有关函数模式、部署和参数处理,请参阅 references/functions.md。
3. 请求 GPU
为函数配置 GPU,以加速计算。
@app.function(gpu="H100")
def train_model():
import torch
assert torch.cuda.is_available()
# GPU-accelerated code here
可用 GPU 类型:
T4、L4— 经济高效的推理A10、A100、A100-80GB— 标准训练/推理L40S— 出色的成本与性能平衡(48GB)H100、H200— 高性能训练(H100!固定使用 H100;普通H100可能会以相同价格升级为 H200)RTX-PRO-6000— Blackwell 工作站级 GPUB200、B300— 旗舰级 Blackwell(B200+可按 B200 价格使用任一型号)
请求多个 GPU:
@app.function(gpu="H100:8") # 8x H100 GPUs
def train_large_model():
pass
有关 GPU 选择指南、CUDA 设置和多 GPU 配置,请参阅 references/gpu.md。
4. 配置资源
为函数申请 CPU 核心、内存和磁盘。
@app.function(
cpu=8.0, # 8 physical cores
memory=32768, # 32 GiB RAM
ephemeral_disk=10240 # 10 GiB disk
)
def memory_intensive_task():
pass
默认分配:0.125 个 CPU 核心、128 MiB 内存。计费依据预留量或实际用量,以较高者为准。
有关资源限制和计费详情,请参阅 references/resources.md。
5. 自动扩展
Modal 会根据需求将函数自动扩展到从零至数千个容器。
并行处理输入:
@app.function()
def analyze_sample(sample_id: int):
# Process single sample
return result
@app.local_entrypoint()
def main():
sample_ids = range(1000)
# Automatically parallelized across containers
results = list(analyze_sample.map(sample_ids))
配置自动扩展:
@app.function(
max_containers=100, # Upper limit
min_containers=2, # Keep warm
buffer_containers=5 # Idle buffer for bursts
)
def inference():
pass
有关自动扩展配置、并发和扩展限制,请参阅 references/scaling.md。
6. 持久化存储数据
使用 Volumes 在函数调用之间持久化存储数据。
volume = modal.Volume.from_name("my-data", create_if_missing=True)
@app.function(volumes={"/data": volume})
def save_results(data):
with open("/data/results.txt", "w") as f:
f.write(data)
volume.commit() # Persist changes
Volumes 可在不同运行之间持久保存数据、存储模型权重、缓存数据集,以及在函数之间共享数据。
有关卷管理、提交和缓存模式,请参阅 references/volumes.md。
7. 管理机密信息
使用 Modal Secrets 安全存储 API 密钥和凭据。
@app.function(secrets=[modal.Secret.from_name("huggingface")])
def download_model():
import os
token = os.environ["HF_TOKEN"]
# Use token for authentication
在 Modal 控制面板中或通过 CLI 创建机密:
modal secret create my-secret KEY=value API_TOKEN=xyz
有关机密管理和身份验证模式,请参阅 references/secrets.md。
8. 部署 Web 端点
使用 @modal.fastapi_endpoint() 提供 HTTP 端点、API 和 Webhook。
@app.function()
@modal.fastapi_endpoint(method="POST")
def predict(data: dict):
# Process request
result = model.predict(data["input"])
return {"prediction": result}
部署方式:
modal deploy script.py
Modal 会为端点提供 HTTPS URL。
有关 FastAPI 集成、流式传输、身份验证和 WebSocket 支持,请参阅 references/web-endpoints.md。
9. 安排作业
使用 cron 表达式按计划运行函数。
@app.function(schedule=modal.Cron("0 2 * * *")) # Daily at 2 AM
def daily_backup():
# Backup data
pass
@app.function(schedule=modal.Period(hours=4)) # Every 4 hours
def refresh_cache():
# Update cache
pass
计划函数会自动运行,无需手动调用。
有关 cron 语法、时区配置和监控,请参阅 references/scheduled-jobs.md。
常见工作流
部署用于推理的 ML 模型
import modal
MODEL_ID = "distilbert/distilbert-base-uncased-finetuned-sst-2-english"
def download_model():
from transformers import pipeline
pipeline("text-classification", model=MODEL_ID) # fills the HF cache
# Define dependencies; run_function executes once at image build, so the weights
# are baked into the image instead of downloaded on every cold start
image = (
modal.Image.debian_slim()
.uv_pip_install("torch", "transformers")
.run_function(download_model)
)
app = modal.App("llm-inference", image=image)
# Serve model
@app.cls(gpu="L40S")
class Model:
@modal.enter()
def load_model(self):
from transformers import pipeline
self.pipe = pipeline("text-classification", model=MODEL_ID, device="cuda")
@modal.method()
def predict(self, text: str):
return self.pipe(text)
@app.local_entrypoint()
def main():
model = Model()
result = model.predict.remote("Modal is great!")
print(result)
批量处理大型数据集
@app.function(cpu=2.0, memory=4096)
def process_file(file_path: str):
import pandas as pd
df = pd.read_csv(file_path)
# Process data
return df.shape[0]
@app.local_entrypoint()
def main():
files = ["file1.csv", "file2.csv", ...] # 1000s of files
# Automatically parallelized across containers
for count in process_file.map(files):
print(f"Processed {count} rows")
在 GPU 上训练模型
@app.function(
gpu="A100:2", # 2x A100 GPUs
timeout=3600 # 1 hour timeout
)
def train_model(config: dict):
import torch
# Multi-GPU training code
model = create_model(config)
train(model)
return metrics
参考文档
特定功能的详细文档:
references/getting-started.md- 身份验证、设置、基本概念references/images.md- 镜像构建、依赖项、Dockerfilereferences/functions.md- 函数模式、部署、参数references/gpu.md- GPU 类型、CUDA、多 GPU 配置references/resources.md- CPU、内存、磁盘管理references/scaling.md- 自动扩缩容、并行执行、并发references/volumes.md- 持久化存储、数据管理references/secrets.md- 环境变量、身份验证references/web-endpoints.md- API、Webhook、端点references/scheduled-jobs.md- Cron 作业、定期任务references/examples.md- 科学计算的常见模式
最佳实践
- 在
.uv_pip_install()中固定依赖项,以确保构建可复现 - 使用合适的 GPU 类型——L40S 用于推理,H100/A100 用于训练
- 利用缓存——使用 Volumes 存储模型权重和数据集
- 配置自动扩缩容——根据工作负载设置
max_containers和min_containers - 如果本地无法使用相关包,则在函数体内导入
- 使用
.map()进行并行处理,而不是使用顺序循环 - 安全存储机密信息——切勿将 API 密钥硬编码
- 监控成本——在 Modal 控制面板中查看用量和账单
故障排除
“找不到模块”错误:
- 使用
.uv_pip_install("package-name")将包添加到镜像中 - 如果本地无法使用相关包,则在函数体内导入
未检测到 GPU:
- 确认 GPU 规格:
@app.function(gpu="A100") - 检查 CUDA 是否可用:
torch.cuda.is_available()
函数超时:
- 增加超时时间:
@app.function(timeout=3600) - 默认超时时间为 5 分钟
卷更改未持久保存:
- 写入文件后调用
volume.commit() - 确认卷已在函数装饰器中正确挂载
如需更多帮助,请参阅 Modal 文档:https://modal.com/docs,或加入 Modal Slack 社区。
AlterLab Academic Skills 套件的一部分。