Cutout Labs runs BiRefNet, an open-source background removal model, on NVIDIA T4 GPUs at Modal. The GPUs scale to zero when nobody is using them, so an idle service costs close to nothing. The catch is the first request after an idle period: it waits for Modal to start a container and for the model to load. On November 21, 2026, that first request took 66–73 seconds. Once the container was warm, processing the same image took under a second.

The obvious fix is to keep a GPU running all the time. At Modal's list price of $0.000164 a second, one always-on T4 costs about $425 a month for the GPU alone, or about $500 with the CPU and memory we reserve next to it. Before paying that, we wanted to know where the 73 seconds actually went. We set two rules: no change to the cutouts, and no extra running cost.

Results at a glance

Before (3 cold starts)After (8 cold starts)
First request after idle, end to end66–73 s (median 71)11–17 s, once 41 s (median 14)
Model ready (imports + loading the model)57–61 s2.6–3.7 s (median 2.8)
  Python imports57 s0.1 s
  Loading the model onto the GPU3.9 s2.5–3.6 s (median 2.6)
Modal finding a GPU, starting a container and routing the request7–8 s5.5–8.3 s, once 34 s (median 6.2)
Warm request, model processing0.7 s0.7 s
Extra running costNone; still scales to zero
Change to the cutoutsNone; pixel-identical masks

Before the fix, we split imports from model loading on one of the three cold starts. The 41-second request in the "after" column was a slow container start on Modal's side; the model itself loaded in a normal 3.7 seconds.

Three findings did most of the work:

  1. Most of the wait wasn't the model. Per-stage timing showed 57 of the 73 seconds were Python imports.
  2. We only needed a small part of the library we were importing. Replacing it with a few dozen lines of our own code removed the imports and produced pixel-identical cutouts.
  3. The model's graph was being optimized from scratch on every start. Doing that once, when the container image is built, cut model loading by about a third.

Our setup

A request goes from our API gateway, a Cloudflare Worker, to a FastAPI app on Modal. The app loads BiRefNet General Lite, a 224 MB ONNX model, and runs it with ONNX Runtime on the GPU. This is the part of the Modal deployment that decides how it scales (simplified; the real one also sets CPU, memory, secrets and authentication):

@app.function(
    image=image,
    gpu=["T4", "L4"],       # fall back to an L4 when no T4 is free
    min_containers=0,       # scale to zero when idle
    scaledown_window=60,    # keep an idle container for 60 s
    max_containers=3,
    timeout=120,
)
@modal.asgi_app()
def api():
    return create_app()

With min_containers=0, a request that arrives after the service has been idle for about a minute usually hits a cold start. Modal treats scaledown_window as a maximum rather than an exact timer, and a burst that needs more containers than are running also starts new ones. The container image is built once per deploy and includes CUDA, our Python packages and the model file, so our application doesn't download the model or install anything when a container starts. Modal itself still fetches the image's files on demand, which turns out to matter below.

1. Measure each stage before changing anything

A cold request passes through several stages: our gateway, Modal finding a GPU and starting a container, Python importing packages, ONNX Runtime loading the model onto the GPU, and finally processing the image. The end-to-end time alone told us nothing about which stage to fix.

So we gave every request an ID and timed each stage, from the gateway down to the model. Inside the container, the start-up timing is a few perf_counter calls around the imports and the model load:

started = time.perf_counter()
import onnxruntime as ort
from rembg.sessions.birefnet_general_lite import BiRefNetSessionGeneralLite
import_ms = round((time.perf_counter() - started) * 1000)

started = time.perf_counter()
session = BiRefNetSessionGeneralLite("birefnet-general-lite", options, providers=["CUDAExecutionProvider"])
session_init_ms = round((time.perf_counter() - started) * 1000)

The container returns these timings to the gateway in response headers, and the gateway logs one line per request. We log stage names and milliseconds only, never images or request contents. Here is the log line for the first cold request we measured this way:

{
  "request_id": "e5470d75-…",
  "backend_model_load_ms": 61195,
  "backend_runtime_import_ms": 57297,
  "backend_session_init_ms": 3881,
  "backend_inference_ms": 1373
}

Laid out as stages:

StageTime
Python imports57.3 s
Loading the model onto the GPU3.9 s
Processing the image1.4 s
Everything else (container start, upload, network)about 10 s
Total, measured from the client72.9 s

We had assumed the model's 224 MB of weights were the slow part. Loading them took under 4 seconds. Nearly a minute went to importing Python packages, before the model was even touched.

To make sure every cold measurement really was cold, our probe script waited until Modal reported zero running containers for the app, then sent one request followed immediately by a second, warm one.

Measuring also surfaced a separate problem: one cold request failed with a 520 from Modal's web endpoint before it reached our code. The gateway now retries that specific case once. We couldn't reproduce it afterwards, so we haven't confirmed its cause.

2. Skip the imports you don't need

We used rembg, a widely used and well-maintained background removal library, to download BiRefNet and prepare images for it. rembg supports many models and features, and importing it loads a large set of scientific Python packages, such as scikit-image, pymatting and numba. Our cold-start logs even showed a warning from numba, a compiler we never used directly.

On a laptop, the same import took about 2 seconds. In a freshly started Modal container it took 57. We didn't trace exactly which files were slowest. The likely explanation is that Modal loads container files lazily, fetching each file the first time it's read. That makes starting a container fast, but the first import of a large dependency tree reads thousands of files that aren't cached on that machine yet.

For serving, we only needed three things: load the ONNX model, resize and normalize the image, and turn the model's output into a mask. Before, the request path went through rembg:

from rembg import remove

mask = remove(image.convert("RGB"), session=session, only_mask=True)

After, the same steps are a few lines of NumPy and ONNX Runtime:

pixels = np.asarray(image.convert("RGB").resize((1024, 1024), Image.Resampling.LANCZOS))
scaled = pixels / max(pixels.max(), 1e-6)
normalized = (scaled - (0.485, 0.456, 0.406)) / (0.229, 0.224, 0.225)
tensor = normalized.transpose(2, 0, 1)[None].astype(np.float32)
logits = session.run(None, {input_name: tensor})[0][0, 0]
probabilities = 1 / (1 + np.exp(-logits))
low, high = probabilities.min(), probabilities.max()
if high > low:
    alpha = ((probabilities - low) / (high - low) * 255).astype(np.uint8)
    mask = Image.fromarray(alpha).resize(image.size, Image.Resampling.LANCZOS)
else:
    mask = Image.new("L", image.size)  # a flat output has no foreground

These are rembg's own steps for this model, plus one guard rembg doesn't have: if the model's output is completely flat, rembg divides by zero, while we return an empty mask. We checked the steps line by line against rembg's source for the version we had deployed, then compared outputs pixel by pixel against rembg on four photos: a woman with long loose hair, a curly-haired puppy, a succulent's pointed leaves, and an image that was already partly transparent.

old = np.asarray(rembg_engine(image).getchannel("A"))
new = np.asarray(our_engine(image).getchannel("A"))
assert (old == new).all()

All four were pixel-identical. Imports dropped from 57 seconds to 0.1, and the first request after idle went from 66–73 seconds to 12–16.

We still use the same model file. It's now downloaded when the image is built, from the same release URL, and checked against the same checksum rembg uses. Since the running service no longer needs rembg, we also removed it and its dependencies from the image.

3. Optimize the model once, not on every start

The next-largest stage we controlled was loading the model onto the GPU: about 4 seconds. Part of that is ONNX Runtime optimizing the model's graph, which has about 16,400 operations. The optimizer simplifies and merges them, and it repeated that work on every cold start.

ONNX Runtime can save an optimized graph to disk, but only its first level is safe to save here. That level runs before ONNX Runtime decides whether the CPU or the GPU executes each operation, so its result is the same for both. The deeper levels fuse operations differently for CPU and GPU, and our build step runs without a GPU, so saving them would bake in fusions meant for the CPU. So we save only the first level, which already brings the graph down to about 4,100 operations. The GPU-specific optimizations still run at start-up, so processing speed is unchanged.

On Modal, this runs once as a build step, and the result becomes part of the container image:

def prepare_model():
    # ...download the checkpoint and verify its checksum...
    options = ort.SessionOptions()
    options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_BASIC
    options.optimized_model_filepath = "/models/birefnet-serving.onnx"
    ort.InferenceSession(checkpoint, options, providers=["CPUExecutionProvider"])

image = image.run_function(prepare_model, cpu=4, memory=8192)

At start-up, the service loads the saved file with the next level, ORT_ENABLE_EXTENDED. ONNX Runtime's levels are cumulative, so this still runs the basic passes as well, but on a graph that has already been simplified, they have little left to do:

options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_EXTENDED

The build step also runs the original and optimized models on the same synthetic input and fails if their outputs differ by more than 0.001; the measured difference was 0.00006. This is a graph-equivalence check: it catches an optimized file that doesn't match the original. It isn't full regression protection. Both models run on the same ONNX Runtime version, on the build machine's CPU, so a runtime upgrade that changed both outputs equally would pass, and it says nothing about cutouts on the GPU. For that, we compare real cutouts pixel by pixel after each change, as in the table below.

Cold starts: 3 before this step, 8 afterBefore this stepAfter
Loading the model onto the GPU3.6–4.3 s (median 4.0)2.5–3.6 s (median 2.6)
Processing the first image1.42–1.55 s1.41–1.58 s
Processing a warm image0.69–0.71 s0.69–0.71 s
Mask pixels changed0 of 960,000, in all 16 cutouts

A Modal detail that keeps deploys fast

Modal caches each step of an image build and reuses it until something before it changes. We set a release ID as an environment variable for error reporting. While that variable came before the model step, every deploy downloaded the model again, and with the optimization step added it would also re-optimize it every time. Moving per-release settings after the model step lets every deploy reuse the cached model. When a deploy happened in the middle of our final measurements, Modal rebuilt only the release-ID step, in 2.3 seconds:

image = base_image.run_function(prepare_model)            # cached across deploys
image = image.env({"SENTRY_RELEASE": release})            # changes on every deploy
image = image.add_local_file("app.py", "/root/removal_api.py")

4. What didn't help, and what we skipped

  • Faster GPU kernel selection. We set ONNX Runtime's cudnn_conv_algo_search to HEURISTIC, so cuDNN picks convolution kernels without first benchmarking them. The first image took just as long, so we reverted it.
  • A smaller container image. Removing rembg and its dependencies didn't make containers start any faster, as you'd expect with lazily loaded files. We kept it anyway, since the image no longer ships code the service doesn't use.
  • Warming the model up at start-up. The first request waits for start-up to finish either way, so this only moves time around.
  • CPU memory snapshots. Modal can save a container's memory after its imports and restore it on later starts, which targets exactly our 57-second problem. Removing the imports fixed it without depending on a platform feature, and left only 0.1 seconds for a snapshot to skip.
  • GPU memory snapshots. Modal can snapshot a running container's GPU state and restore it on the next start. The feature is in alpha, its documentation notes it doesn't speed up loading weights from storage, and a failed restore could break cold starts. We didn't try it.

Where the remaining time goes

StageTime
Modal finding a GPU, starting the container and routing the request5.5–8.3 s, once 34 s
Loading the model2.6–3.7 s
Processing the first image: about 0.7 s of normal processing plus about 0.8 s of first-image overhead1.4–1.6 s
Upload and networkthe rest

Container start is now the largest stage, the least predictable, and the one we control least: in one of our eight final cold starts it took 34 seconds. So after these measurements, we did something cheaper than making it faster: we raised scaledown_window from 60 seconds to 5 minutes, so that a batch of images pays the cold start only once. Each burst of requests now keeps a T4 idle for up to about 4 extra minutes, which costs roughly 5 cents per container.

If you run models on serverless GPUs

  • Time each start-up stage separately before optimizing anything. Our assumption about the slow part was wrong.
  • Check what your imports pull in. A library that imports in 2 seconds on a laptop can take a minute in a fresh container.
  • Do one-off work at build time, such as downloading weights and optimizing graphs, and check its output before it ships.
  • Order image build steps from least to most frequently changing, so deploys reuse the expensive ones.
  • Compare outputs pixel by pixel after every change that touches the model path.

How we measured

  • Service: BiRefNet General Lite in ONNX format, on Modal NVIDIA T4 GPUs, ONNX Runtime 1.23.2, scaling to zero after 60 idle seconds.
  • Test request: the same 1200×800 photo of a person with loose hair, sent as a PNG through our public API, asking for the alpha mask. Each cold request was sent after Modal reported no running containers, followed immediately by a warm one.
  • Timings: end-to-end times were measured from the client and include upload over the internet. Stage times come from the server-side logs described above.
  • Sample sizes are small. We measured three cold starts before the fixes, three after removing the imports, and eight for the final setup, between November 21 and 22, 2026. Model start-up took 57–61 seconds on every cold start before the fix; we split out the import time on one of them. Container start-up varied by several seconds between runs, and once by nearly 30.
  • One deploy happened during the final measurements. It added code for another service but didn't change the path these requests took. All 16 final-setup requests were served by the same model on Modal.
  • Cutout comparisons were pixel by pixel on the full-resolution masks.

Want to test the serving path yourself? Try the Cutout Labs web editor or the /v1.0/removebg HTTP API, or read how we also tuned BiRefNet on serverless CPUs without losing quality.