AI Tools8 min read

Modal for AI Workloads: GPUs, Volumes and Web Endpoints

How Modal runs Python AI code in the cloud: apps and functions, images, GPUs, volumes, web endpoints, autoscaling, cron schedules, secrets and pricing.

By AI Agents DirectoryLast checked
LinkedIn logo shown on a laptop screen

Modal is a hosted platform for running Python code, including GPU inference, batch jobs and training, without setting up servers yourself. You write normal Python functions, add a decorator that says what container and hardware each one needs, and Modal runs them in containers in its own cloud, adding and removing containers as load changes. This guide walks through the pieces you use day to day: apps and functions, images, GPUs, volumes, web endpoints, scaling and cold starts, schedules, secrets and pricing. Everything here is taken from Modal’s documentation, its pricing page and the modal-client repository.

How Modal works

Modal packages your code into a container, runs it on its own infrastructure and scales the number of containers with traffic. The docs say capacity is pooled across the major clouds, and that Modal chooses where to run each job based on what is available. There is no YAML: the container definition and the GPU choice live in your Python file.

Python is the main language for writing Modal functions. Modal also ships JavaScript/TypeScript and Go SDKs, which can call deployed functions, run Sandboxes and manage some platform resources, but they don’t define functions. The SDK source is on GitHub under the Apache-2.0 licence.

Getting started takes three steps:

pip install modal
modal setup   # authenticates your machine
modal run my_file.py

Note that GPU functions only run once your account has a payment method on file.

Apps and functions

An App groups one or more Functions that deploy together and share a namespace. After deployment, each Function scales on its own, separately from the other Functions in the App. When a Function has no inputs, no containers run for it and you aren’t charged for compute, even though the App stays deployed.

Apps come in two forms:

Created withLifetime
Ephemeralmodal run or app.run()Stops when your local script exits (unless you pass --detach)
Deployedmodal deployStays up until you stop it from the dashboard or with modal app stop

Running modal deploy again for an App with the same name updates that App in place. For local testing, mark a function with @app.local_entrypoint(). If its arguments are simple types such as int or str, modal run exposes them as command-line flags.

A GPU function from the docs

This is the quickstart from Modal’s GPU guide. It builds an image with PyTorch and runs a function on an A100:

import modal

image = modal.Image.debian_slim().pip_install("torch", "numpy")
app = modal.App(image=image)

@app.function(gpu="A100")
def run():
    import torch
    assert torch.cuda.is_available()

Save it as a file and start it with modal run. Torch is imported inside the function body because it is installed in the remote container, not necessarily on your laptop. The images guide recommends this pattern so you don’t hit an ImportError locally.

Images

An Image is the filesystem snapshot your function starts from. Unless you say otherwise, functions run on Debian with the same minor Python version as your local interpreter. You customise an image by chaining methods onto a base image:

  • uv_pip_install(...) adds Python packages using uv; pip_install(...) is the fallback that uses plain pip.
  • apt_install(...) adds system packages, and run_commands(...) and env(...) cover arbitrary build steps and environment variables.
  • add_local_dir, add_local_file and add_local_python_source bring in files or modules from your machine.

Modal recommends pinning exact versions (for example torch==2.8.0) so builds stay reproducible. Local files are attached when the container starts instead of being baked into a new layer, so redeploys are quick. Pass copy=True if a later build step needs those files. If you already have a Dockerfile or a registry image, you can build on that.

GPUs

Set the hardware with the gpu argument. The GPU guide lists these values: T4, L4, A10, L40S, A100, A100-40GB, A100-80GB, RTX-PRO-6000, H100, H200, B200 and B300. Some details worth knowing:

  • Several GPUs per container: append a count, as in gpu="H100:8". The docs say most types go up to eight per container and the A10 up to four, all on one physical machine. They also warn that asking for more than two usually means waiting longer.
  • Fallbacks: pass a list, such as gpu=["H100", "A100-40GB:2"], and Modal tries the types in that order.
  • Free upgrades: an H100 request may land on an H200, and an A100 request on the 80 GB card, with no change in price. Use H100! to opt out, for example when benchmarking.
  • Where to start: for inference rather than training, the docs suggest the L40S, which has 48 GB of memory.

Multi-GPU training on a single node is supported. The GPU guide describes multi-node training as being in private beta.

Volumes for model weights

Volumes are Modal’s distributed file system. They are built for data you write once and read many times, such as model weights loaded by many inference containers. You create one with modal volume create my-volume or in code with modal.Volume.from_name("my-volume", create_if_missing=True), then mount it into a function:

vol = modal.Volume.from_name("my-volume")

@app.function(volumes={"/data": vol})
def run():
    with open("/data/xyz.txt", "w") as f:
        f.write("hello")
    vol.commit()

Volumes don’t behave quite like a local disk. Changes made in one container become visible elsewhere only after a commit, and a container that is already running sees other containers’ commits only after it calls .reload(). Modal recommends v2 Volumes for anything new, but v1 is still the default, so pass version=2 when you create one.

Web endpoints

To call a function over HTTP, add @modal.fastapi_endpoint(), which wraps the function in a FastAPI app. Query parameters become function arguments, and you can set method="POST" to accept a JSON body. You can also serve a complete FastAPI, Django or Flask app, or any server that listens on a port.

During development, modal serve runs an ephemeral App with a temporary public URL and reloads it whenever you change your files. When you’re ready, modal deploy gives you an endpoint that stays up.

Autoscaling and cold starts

Every Function has its own pool of containers. Modal’s autoscaler adds containers when inputs are waiting and removes idle ones, and by default a Function scales to zero. You can change this behaviour with decorator arguments:

SettingWhat it controls
max_containersUpper limit on containers for the Function
min_containersContainers kept warm even with no traffic
buffer_containersSpare idle containers kept ready while the Function is busy
scaledown_windowHow long an idle container may wait before shutting down (default 60 seconds, configurable from 2 seconds to 20 minutes)

The docs present these as a trade-off: more warm capacity means lower latency and a bigger bill. You can also change them without redeploying through Function.autoscaler.update(). One example in the docs uses scheduled functions to grow the warm pool in the morning and shrink it at night. For batch work, .map() and .starmap() send many inputs to a function in parallel. A single Function is limited to 4,000 concurrent containers, and your plan sets the limits across the workspace.

A cold start is what happens when no warm container is free and Modal has to start one. Modal says the container itself boots in about a second, but your global imports and any @modal.enter setup run before the container can take inputs. In practice, a large model download during startup is often the slow part. The docs suggest downloading weights ahead of time, for example to a Volume, so the download happens only once.

Scheduled jobs

Pass schedule= to a function and deploy the App. Use modal.Period(hours=5) for a fixed interval, or modal.Cron("0 6 * * *", timezone="America/New_York") for cron syntax. A Period restarts its count each time you redeploy, and a Cron schedule doesn’t. You can’t pause a schedule. To stop it, remove the schedule and redeploy. The dashboard also has a “run now” button for running a scheduled function on demand.

Secrets

Secrets hold API keys and other credentials. You can create them in the dashboard (which has templates for services such as Hugging Face and Weights & Biases), with the modal secret CLI, or in code with Secret.from_dict() or Secret.from_dotenv(). Attach them with secrets=[modal.Secret.from_name("secret-keys")], and their keys appear as environment variables inside the container. If two attached secrets share a key, the one later in the list wins.

Pricing

Modal bills compute per second. Its pricing page describes the plans like this at the time of writing:

PlanBase feeIncluded creditsConcurrency
Starter$0 + compute$30 per month100 containers, 10 GPUs
Team$250 per month + compute$100 per month5,000 containers, 50 GPUs
EnterpriseCustomCustomCustom

GPU rates are listed per second for each card. The T4 is the cheapest, and the B300 and B200 are at the top. Billable time includes container startup, input processing and the idle window before scale-down. Containers kept warm with min_containers are billed as well. Functions can be preempted by default. Non-preemptible execution, which is also how Sandboxes are priced, costs 3x the base CPU and memory rates, and region selection adds a multiplier as well. Check the pricing page before you estimate costs, because rates change.

Where Modal fits

Modal suits teams that work in Python and want GPU inference, batch jobs or fine-tuning without managing clusters. If you are fine-tuning, see our guides to parameter-efficient fine-tuning and fine-tuning domain-specific agents. Keep the limits in mind: you run on Modal’s infrastructure, not your own cloud account, and functions are written in Python. If you would rather launch jobs on your own cloud accounts, SkyPilot is an open-source option. More tools are listed under LLM infrastructure.

#Modal#Serverless#GPU inference#LLM infrastructure#Python
AI

Written by AI Agents Directory

Editorial team

Facts in this guide are checked against official documentation and repositories, which are linked in the article.