serverless-modal skill
Run GPU workloads on Modal — training, fine-tuning, inference, batch processing. Zero-config serverless: no SSH, no Docker, auto scale-to-zero. Use when user says \"modal run\", \"modal training\", \"modal inference\", \"deploy to modal\", \"need a GPU\", \"run on modal\", \"serverless GPU\", or needs remote GPU compute.
Is the serverless-modal skill safe?
Clean: nothing in its files matched our rules. We read 1 file in the folder on 2026-09-28.
No findings.
Install the serverless-modal skill
A skill is a folder. Copy it into your agent's skills folder and the agent loads it when the task matches its description.
git clone --depth 1 https://github.com/wanshuiyin/Auto-claude-code-research-in-sleep.git /tmp/Auto-claude-code-research-in-sleep mkdir -p ~/.claude/skills cp -r /tmp/Auto-claude-code-research-in-sleep/skills/serverless-modal ~/.claude/skills/serverless-modal
In the Claude apps, zip the folder and upload it from the Skills settings. The folder on GitHub
The instructions your agent would load
SKILL.md as published, without the frontmatter. Read it on GitHub
Modal Cloud GPU — Training & Inference
Task: $ARGUMENTS
Overview
Modal is a serverless GPU cloud. Key advantages over SSH-based platforms (vast.ai, remote servers):
Treat the modal.Image chain as the RENDERED form of the declarative env spec in ../shared-references/compute-env-contract.md — same spec fields (base, ordered pip phases, env vars, smoke probes), same env:@ ledger entry in .aris/compute/modal.md, same three-tier validation before a long run.
- Zero config: no SSH, no Docker, no port forwarding. Write Python → modal run → done.
- Auto scale-to-zero: billing stops the instant your code finishes. No idle instances.
- Local-first: run modal run from your laptop. Code, data, and results stay local; only the GPU function runs remotely.
- Reproducible environments: dependencies declared in code via modal.Image, not system-level packages.
Best for: Users without a local GPU who need to debug CUDA code, run small-scale tests, or iterate quickly on experiments. The $5 free tier (no card) is enough for code debugging; $30 (with card) covers most small-scale experiment runs.
Trade-off: Modal costs more per GPU-hour than vast.ai or Lightning for some GPU tiers, but eliminates setup time and idle billing, often making it cheaper for short/medium workloads. For long training runs (>4 hours), consider vast.ai for lower $/hr.
Authentication
pip install modal
modal setup # Opens browser login, writes token to ~/.modal.toml
# Verify:
modal run -q 'print("ok")'- Sign up: https://modal.com (GitHub/Google login)
- Free (no card): $5/month — enough for quick tests
- Free (with card): $30/month — bind a payment method at https://modal.com/settings for the full free tier. Set a workspace spending limit to prevent accidental overcharge (Settings → Usage → Spending Limit)
- Academic: apply for $10k credits | Startups: apply for $25k credits
- Secrets: modal secret create huggingface-secret HFTOKEN=hfxxxxx
Recommended setup: Bind a card to unlock $30/month, then immediately set a spending limit (e.g., $30) so you never exceed the free tier. Modal will pause your workloads when the limit is hit.
SECURITY WARNING: Always bind your card and set spending limits directly on https://modal.com/settings in your browser. NEVER enter payment information, card numbers, or billing details through Claude Code or any CLI tool. Only the official Modal website is safe for payment operations.
Pricing (source: modal.com/pricing, per-second billing)
CPU: $0.047/core/hr | RAM: $0.008/GiB/hr (GPU typically 90%+ of total cost)
!! Cost Estimation Required !!
Before EVERY run, estimate cost and show to user for confirmation.
Key insights:
- Inference bottleneck is memory bandwidth, not compute → high-bandwidth GPUs are often cheaper overall
- 7-8B BF16 inference needs ~22GB VRAM (weights 15G + KV cache 1G + overhead), T4 (16GB) insufficient
- H100 is often cheaper than L4 for benchmarks (11x faster but only 5x more expensive)
Cost Estimation Template (required before every run)
Cost estimate (Modal):
Model: [name] ([params], [precision])
VRAM: ~[X]GB (weights + KV cache + overhead)
GPU: [type] ([VRAM]GB, $[X]/sec = $[X]/hr, bandwidth [X] GB/s)
Estimate: ~[N] min, ~$[X]7-8B BF16 Benchmark Cost Comparison
Workflow
Step 1: Analyze Task → Estimate Cost → Choose GPU
Same analysis as any GPU skill — determine VRAM needs from model size, pick GPU, estimate hours, calculate cost. See pricing table above.
VRAM Rules of Thumb:
Step 2: Generate Modal Launcher
Based on the task type, generate the appropriate launcher script.
Pattern A: One-Shot GPU Function (training, evaluation, benchmark)
The most common pattern for run-experiment integration. Wraps an existing training script:
import modal
app = modal.App("experiment-name")
# One .pip_install() call per SPEC PHASE (chained calls install in order, so a
# pinned torch in the first call can't be dragged by packages in the second —
# the rendered form of compute-env-contract.md's ordered pip_phases):
image = (
modal.Image.debian_slim(python_version="3.11")
.pip_install("torch") # phase 1: pins
.pip_install("transformers", "accelerate", "datasets", "wandb") # phase 2
)
# Mount local project code into the container
local_code = modal.Mount.from_local_dir(".", remote_path="/workspace")
# Persistent volume for checkpoints and results
volume = modal.Volume.from_name("experiment-results", create_if_missing=True)
@app.function(
image=image,
gpu="A100-80GB", # Chosen based on Step 1 analysis
mounts=[local_code],
volumes={"/results": volume},
timeout=3600 * 6, # 6 hours max
secrets=[modal.Secret.from_name("wandb-secret")], # Optional
)
def train():
import subprocess
subprocess.run(
["python", "train.py", "--output_dir", "/results/run_001"],
cwd="/workspace",
check=True,
)
volume.comRun: modal run launcher.py
Pattern B: Web API (persistent inference service)
import modal
app = modal.App("inference-api")
image = (
modal.Image.debian_slim(python_version="3.11")
.pip_install("torch") # phase 1: pins
.pip_install("transformers", "accelerate") # phase 2
)
@app.cls(image=image, gpu="L40S")
@modal.concurrent(max_inputs=10)
class InferenceAPI:
@modal.enter()
def load_model(self):
from transformers import AutoModelForCausalLM, AutoTokenizer
self.tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-3.2-1B")
self.model = AutoModelForCausalLM.from_pretrained(
"meta-llama/Llama-3.2-1B", device_map="auto"
)
@modal.fastapi_endpoint(method="POST")
def generate(self, request: dict):
inputs = self.tokenizer(request.get("prompt", ""), return_tensors="pt").to("cuda")
outputs = self.model.generate(**inputs, max_new_tokens=256)
return {"text": self.tokenizer.decode(outputs[0], skip_special_tokens=True)}Deploy: modal deploy app.py
Pattern C: vLLM High-Performance Inference
import modal, subprocess
app = modal.App("vllm-server")
image = modal.Image.debian_slim(python_version="3.11").pip_install("vllm")
VOLUME = modal.Volume.from_name("model-cache", create_if_missing=True)
MODEL = "Qwen/Qwen3-4B"
@app.function(image=image, gpu="H100", volumes={"/models": VOLUME}, timeout=3600)
@modal.concurrent(max_inputs=100)
@modal.web_server(port=8000)
def serve():
subprocess.Popen(["python", "-m", "vllm.entrypoints.openai.api_server",
"--model", MODEL, "--download-dir", "/models", "--port", "8000"])Pattern D: Batch Parallel (map over dataset)
@app.function(image=image, gpu="T4", timeout=600)
def process_item(item: dict) -> dict:
# ... process one item ...
return {"result": "processed"}
@app.local_entrypoint()
def main():
results = list(process_item.map([{"id": i} for i in range(1000)]))Pattern E: LoRA Fine-Tuning
@app.function(
image=image, gpu="A100-80GB", volumes={"/output": volume},
timeout=3600 * 6, secrets=[modal.Secret.from_name("huggingface-secret")],
)
def train():
# ... transformers + peft + trl training code ...
trainer.save_model("/output/final")
volume.commit()Pattern F: Multi-GPU Distributed Training
@app.function(image=image, gpu="H100:4", volumes={"/output": volume}, timeout=3600 * 12)
def train_distributed():
import subprocess
subprocess.run(["accelerate", "launch", "--num_processes", "4",
"--mixed_precision", "bf16", "train.py"], check=True)Step 3: Run
modal run launcher.py # One-shot execution (most common for experiments)
modal deploy app.py # Persistent service deploymentStep 4: Verify & Monitor
modal app list # List running apps
modal app logs <app-name> # Stream logsStep 5: Collect Results
Results collection depends on the pattern used:
Volume-based (recommended for training):
# Download results from volume after run completes
# Option A: In the launcher script, copy results to local mount before exit
# Option B: Use modal volume commands
modal volume ls experiment-results
modal volume get experiment-results /run_001/results.json ./results/Stdout/return-based (for evaluation/benchmarks): Results are printed to terminal or returned from the function — already local.
Step 6: Cleanup
Modal auto-scales to zero — no manual instance destruction needed. But clean up unused resources:
modal app stop <app-name> # Stop a deployed service
modal volume rm <volume-name> # Delete a volume when doneCLI Reference
modal run app.py # Run once
modal deploy app.py # Deploy persistent service
modal app logs <app> # View logs
modal app list # List apps
modal app stop <app> # Stop
modal volume ls # List volumes
modal volume get <vol> <remote> <local> # Download from volume
modal secret create NAME KEY=VALUE # Create secretKey Tips
- GPU fallback: gpu=["H100", "A100-80GB", "L40S"] — Modal tries each in order
- Multi-GPU: gpu="H100:4" (up to 8 GPUs, cost scales linearly)
- Volume: modal.Volume.fromname("x", createif_missing=True) for persistent storage
- @modal.enter() loads model once per container | @modal.concurrent() for concurrent requests
- Long training: set timeout=3600 * N (default is 5 min)
- Local code: modal.Mount.fromlocaldir(".", remote_path="/workspace")
- W&B integration: secrets=[modal.Secret.from_name("wandb-secret")] + wandb.init() in your script
Composing with Other Skills
More skills from wanshuiyin/Auto-claude-code-research-in-sleep
- Aablation-plannerUse when main results pass result-to-claim (claim_supported=yes or partial) and ablation studies are needed for paper submission.
- Aablation-plannerUse when main results pass result-to-claim (`claim_supported = yes` or `partial`) and ablation studies are needed for paper submission. A secondary Codex agent designs ablations from a reviewer's perspective; the local executor reviews feasibility and implements.
- AalphaxivQuick single-paper lookup via AlphaXiv LLM-optimized summaries with tiered source fallback. Use when user says "explain this paper", "summarize paper", pastes an arXiv/AlphaXiv URL, or provides a bare arXiv ID for quick understanding - not for broad literature search.
- AalphaxivQuick single-paper lookup via AlphaXiv LLM-optimized summaries with tiered source fallback. Use when user says "explain this paper", "summarize paper", pastes an arXiv/AlphaXiv URL, or provides a bare arXiv ID for quick understanding - not for broad literature search.
- Aanalyze-resultsAnalyze ML experiment results, compute statistics, generate comparison tables and insights. Use when user says "analyze results", "compare", or needs to interpret experimental data.
- Aanalyze-resultsAnalyze ML experiment results, compute statistics, generate comparison tables and insights. Use when user says \"analyze results\", \"compare\", or needs to interpret experimental data.
- AarxivSearch, download, and summarize academic papers from arXiv. Use when user says "search arxiv", "download paper", "fetch arxiv", "arxiv search", "get paper pdf", or wants to find and save papers from arXiv to the local paper library.
- AarxivSearch, download, and summarize academic papers from arXiv. Use when user says \"search arxiv\", \"download paper\", \"fetch arxiv\", \"arxiv search\", \"get paper pdf\", or wants to find and save papers from arXiv to the local paper library.
- Aauto-paper-improvement-loopAutonomously improve a generated paper via GPT-6-Astra xhigh review → implement fixes → recompile, for 2 rounds. Use when user says \"改论文\", \"improve paper\", \"论文润色循环\", \"auto improve\", or wants to iteratively polish a generated paper.
- Aauto-paper-improvement-loopAutonomously improve a generated paper via Claude review through claude-review MCP → implement fixes → recompile, for 2 rounds. Use when user says \"改论文\", \"improve paper\", \"论文润色循环\", \"auto improve\", or wants to iteratively polish a generated paper.
- Aauto-paper-improvement-loopAutonomously improve a generated paper via Gemini review through gemini-review MCP → implement fixes → recompile, for 2 rounds. Use when user says \"改论文\", \"improve paper\", \"论文润色循环\", \"auto improve\", or wants to iteratively polish a generated paper.
- Aauto-paper-improvement-loopAutonomously improve a generated paper via GPT-6-Astra xhigh review → implement fixes → recompile, for 2 rounds. Use when user says \"改论文\", \"improve paper\", \"论文润色循环\", \"auto improve\", or wants to iteratively polish a generated paper.