---
description: "Version fine-tuned models on Verda: run an MLflow model registry on a CPU instance with the weights in Object Storage, fine-tune on an Instant Cluster or a GPU instance, package each registered version as a container image, and serve, promote and roll back versions on Serverless Containers."
revision_date: 23.11.2026
---

# Tutorial: Model Registry and Fine-Tune-to-Serve Pipeline with MLflow

## What you'll build

In this guide we will build a pipeline that takes a model from a fine-tuning job to a live
endpoint, with a model registry in between that records every version.

The example model routes customer support messages. It reads a message such as "I want my
money back for the damaged item" and answers with one category, `REFUND`. A small open-weight
model gets this wrong too often out of the box, so we fine-tune it, and we keep track of each
attempt.

By the end of the guide:

- A fine-tuning job on an Instant Cluster or a GPU instance scores the base model, trains it,
  scores it again and registers the result as a numbered version.
- The registry keeps each version's weights in Object Storage, next to the accuracy it
  reached, the data and base model it came from, and the endpoint that serves it.
- Each version runs as its own Serverless Container deployment, built from its own container
  image.
- One command moves the `champion` alias to another version and the application follows it.
  Rolling back is the same command with the previous version number.

We use **MLflow** because its model registry provides versions, aliases and tags, its
tracking server records the metrics of every training run, and its artifact store works with
S3-compatible storage. The model is served with vLLM, as in the other
[Serverless Container tutorials](https://docs.verda.com/serverless-containers/tutorials/).

***

## Architecture

<pre style="overflow-x: auto; white-space: pre;">

    +-------------------------------+
    | Instant Cluster/GPU instance  |
    |   fine-tuning job, train.py   |
    +---------------+---------------+
                    |
                    | 1. metrics and weights, over HTTPS
                    v
    +-------------------------------+  2. weights  +----------------+
    |    registry instance (CPU)    | -----------> | Object Storage |
    |     MLflow and PostgreSQL     |    S3 API    |     bucket     |
    +---------------+---------------+              +----------------+
                    |
                    | 3. fetch a version, build its image
                    v
    +-------------------------------+
    |      Container Registry       |
    |    support-router:v1, :v2     |
    +---------------+---------------+
                    |
                    | 4. one deployment per version
                    v
    +-------------------------------+
    |     Serverless Containers     |
    |    support-router-v1, -v2     |
    +-------------------------------+

</pre>

The numbers follow one version from training to serving. The fine-tuning job sends its
metrics and the finished weights to MLflow over HTTPS (1). MLflow keeps the records in
PostgreSQL and writes the weights to the bucket (2). To serve a version, you fetch its weights
from the registry, build them into a vLLM image and push the image to the Container Registry
(3), then create a deployment from it (4). The address of that deployment goes back into the
registry as a tag on the version, so the registry can always say where each version is served.

<div style="display: block !important; width: 100% !important; margin: 0 !important;">
<table style="display: table !important; width: 100% !important; margin: 0 !important; table-layout: fixed;">
<thead>
<tr><th>Component</th><th>Tier</th><th>Runs when</th></tr>
</thead>
<tbody>
<tr><td>MLflow and PostgreSQL</td><td>CPU instance</td><td>Continuously, while the instance is on</td></tr>
<tr><td>Model weights</td><td>Object Storage bucket</td><td>Stored until you delete them</td></tr>
<tr><td>Fine-tuning job</td><td>Instant Cluster or GPU instance</td><td>While the job runs</td></tr>
<tr><td>Serving image</td><td>Container Registry</td><td>Stored until you delete it</td></tr>
<tr><td>One deployment per version</td><td>Serverless Container</td><td>On demand</td></tr>
</tbody>
</table>
</div>

**Only the registry holds the Object Storage keys.** Training jobs talk to MLflow, and MLflow
talks to the bucket, so a job needs one address and one login, not storage credentials.

**The registry instance is a single point of failure for registering and looking up
versions.** The deployments keep serving if it stops, because each one carries its weights
in its image.

***

## Prerequisites

- Register an SSH key in your Verda account, if you have not already.
- Create [Container Registry](https://docs.verda.com/storage/container-registry/quickstart/) credentials, on
  the Container Registry or Credentials page, with **Verda** as the provider. Copy the full
  credential name and the secret, which is shown only once. Steps 3 and 6 push images with
  them.
- Have ready an
  [Inference API Key](https://docs.verda.com/account/account-and-access/api-credentials/#create-inference-api-keys),
  which is how you call the deployments in Step 6.
- Have an [Instant Cluster](https://docs.verda.com/clusters/deploy-an-instant-cluster/) or a
  GPU instance for the fine-tuning job. The job needs one GPU, and Step 4 shows how to run it
  on either.

***

## Step 1: Create a bucket and an access key

The weights of every version go into one Object Storage bucket.

In the [Verda console](https://console.verda.com), open your project and go to
**Storage → Object storage**. Click **Create bucket**, enter a **Bucket name**, pick the
**Location** and confirm. Bucket names are unique across all of Verda, so choose one of your
own, such as `registry-` followed by your team name.

Then go to **Project management → Credentials**. In the **Object Storage Access Keys**
section, click **Create**, name the key, and confirm with **Create access key**. Copy the
**Access key** and the **Secret key** before closing the dialog, because the secret key is
shown only once.

The [Object Storage quickstart](https://docs.verda.com/storage/object-storage/quickstart/) shows both screens
in more detail.

!!! info
    Every access key in a project can reach every bucket in that project. Keep this one on
    the registry instance only.

## Step 2: Start the registry

### Create the instance

MLflow runs on one CPU instance, named `registry` throughout this guide. Create it in the
console with these settings:

| Setting | Value | Notes |
|---|---|---|
| Name | `registry` | The guide refers to it by this name |
| Instance type | `CPU.4V.16G` or `CPU-TURIN.4V.16G` | 4 vCPU and 16 GB RAM, whichever your location offers. The registry is light. The instance also builds the container images in Steps 3 and 6 |
| Image | Debian 13 | The latest Debian image, which is minimal. **Docker is required**: it runs MLflow and builds the images, and you install it below |
| SSH key | Your registered key | |
| Network | **Public IP only** | The address is how you SSH in and how the fine-tuning job reaches the registry |
| Storage | OS volume, 150 GB | The images built in Steps 3 and 6 need room: the training image takes about 10 GB and the vLLM-based serving image about 36 GB |

SSH into the instance. Everything in Steps 2, 3, 5 and 6 runs there. If the login prints
`setlocale` warnings, they come from the language settings of your own computer and can be
ignored.

### Install Docker

The Debian image does not include Docker. Install Docker Engine with its Compose and Buildx
plugins from Docker's own package repository, following Docker's
[installation guide for Debian](https://docs.docker.com/engine/install/debian/).

**Add Docker's signing key**, so the package manager can verify what it downloads. Refresh
the package list first:

```bash
sudo apt-get update
```

Install the two tools that fetch the key:

```bash
sudo apt-get install -y ca-certificates curl
```

Create the folder that holds signing keys:

```bash
sudo install -m 0755 -d /etc/apt/keyrings
```

Download the key into it:

```bash
sudo curl -fsSL https://download.docker.com/linux/debian/gpg -o /etc/apt/keyrings/docker.asc
```

Let the package manager read the key:

```bash
sudo chmod a+r /etc/apt/keyrings/docker.asc
```

**Add Docker's package repository.** The two `$(...)` parts fill in your Debian release and
CPU type:

```bash
sudo tee /etc/apt/sources.list.d/docker.sources <<EOF
Types: deb
URIs: https://download.docker.com/linux/debian
Suites: $(. /etc/os-release && echo "$VERSION_CODENAME")
Components: stable
Architectures: $(dpkg --print-architecture)
Signed-By: /etc/apt/keyrings/docker.asc
EOF
```

**Install the packages.** Refresh the package list again, so that it includes Docker's
repository:

```bash
sudo apt-get update
```

```bash
sudo apt-get install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
```

**Check that Docker runs a container** and that Compose is installed:

```bash
sudo docker run --rm hello-world
```

The output should include `Hello from Docker!`.

```bash
docker compose version
```

```text {.no-copy}
Docker Compose version v5.8.0
```

Your version may be newer.

### Create a certificate

**Create the working directory** and move into it:

```bash
mkdir -p ~/registry/certs ~/registry/train ~/registry/serve
```

```bash
cd ~/registry
```

MLflow serves plain HTTP by default, so passwords and model weights would travel unencrypted.
A certificate encrypts that traffic and lets a client check that it is talking to your
registry. Everything reaches the registry on its public address, so that is the address the
certificate carries.

Replace `<registry-public-ip>` with the instance's public address, keeping the `IP:` in front
of it and the quotation marks around the whole value:

```bash
openssl req -x509 -newkey rsa:2048 -nodes -days 365 \
  -keyout certs/key.pem \
  -out    certs/cert.pem \
  -subj   "/CN=registry" \
  -addext "subjectAltName=IP:<registry-public-ip>"
```

If OpenSSL answers `bad ip address`, the placeholder is still in the command.

```bash
chmod 600 certs/key.pem
```

Check that the address made it in:

```bash
openssl x509 -in certs/cert.pem -noout -text | grep -A1 "Alternative"
```

```text {.no-copy}
X509v3 Subject Alternative Name:
    IP Address:<registry-public-ip>
```

This certificate signs itself, so nothing trusts it until you say so: every client in this
guide is given a copy of `cert.pem` to check the registry against.

### Set the credentials

Docker Compose reads the registry's settings from a private `.env` file. The block below
writes that file with three generated secrets: a database password, the password of MLflow's
`admin` account, and a secret key that MLflow's login layer requires to protect its forms.

```bash
cat > .env <<EOF
PUBLIC_IP=<registry-public-ip>
BUCKET=<bucket-name>
S3_ACCESS_KEY=<access-key>
S3_SECRET_KEY=<secret-key>
POSTGRES_PASSWORD=$(openssl rand -hex 24)
MLFLOW_ADMIN_PASSWORD=$(openssl rand -hex 16)
MLFLOW_SECRET_KEY=$(openssl rand -hex 32)
EOF
```

Keep the file private, since it holds the secrets:

```bash
chmod 600 .env
```

Now open the file and replace the four placeholders in angle brackets, brackets included,
with the instance's public address, the bucket name and the access key pair from
[Step 1](#step-1-create-a-bucket-and-an-access-key):

```bash
nano .env
```

Editing the file this way keeps the storage keys out of your shell history.

### Define the services

Create `compose.yaml` by copying the whole block below into the terminal. `cat > ... <<'EOF'`
writes every line up to the closing `EOF` into the file, and the quotes around `'EOF'` keep
the shell from changing any `$` signs in it. The other files in this guide are created the
same way.

```bash title="compose.yaml"
# compose.yaml
cat > ~/registry/compose.yaml <<'EOF'
name: registry

services:
  db:
    image: postgres:16
    restart: unless-stopped
    environment:
      POSTGRES_USER: mlflow
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?Missing POSTGRES_PASSWORD}
      POSTGRES_DB: mlflow
    volumes:
      - postgres_data:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U mlflow -d mlflow"]
      interval: 5s
      timeout: 5s
      retries: 20

  mlflow:
    image: ghcr.io/mlflow/mlflow:v3.18.0-full
    restart: unless-stopped
    depends_on:
      db:
        condition: service_healthy
    working_dir: /mlflow
    environment:
      MLFLOW_BACKEND_STORE_URI: postgresql://mlflow:${POSTGRES_PASSWORD}@db:5432/mlflow
      MLFLOW_ARTIFACTS_DESTINATION: s3://${BUCKET:?Missing BUCKET}/mlflow
      MLFLOW_S3_ENDPOINT_URL: https://objects.eu-north-3.verda.storage
      MLFLOW_BOTO_CLIENT_ADDRESSING_STYLE: path
      AWS_ACCESS_KEY_ID: ${S3_ACCESS_KEY:?Missing S3_ACCESS_KEY}
      AWS_SECRET_ACCESS_KEY: ${S3_SECRET_KEY:?Missing S3_SECRET_KEY}
      AWS_DEFAULT_REGION: eu-north-3
      AWS_REQUEST_CHECKSUM_CALCULATION: when_required
      AWS_RESPONSE_CHECKSUM_VALIDATION: when_required
      MLFLOW_AUTH_ADMIN_PASSWORD: ${MLFLOW_ADMIN_PASSWORD:?Missing MLFLOW_ADMIN_PASSWORD}
      MLFLOW_FLASK_SERVER_SECRET_KEY: ${MLFLOW_SECRET_KEY:?Missing MLFLOW_SECRET_KEY}
    command:
      - mlflow
      - server
      - --host=0.0.0.0
      - --port=5000
      - --workers=2
      - --app-name=basic-auth
      - --allowed-hosts=${PUBLIC_IP:?Missing PUBLIC_IP}:5000
      - --cors-allowed-origins=https://${PUBLIC_IP}:5000
      - --uvicorn-opts
      - "--ssl-keyfile /certs/key.pem --ssl-certfile /certs/cert.pem"
    volumes:
      - ./certs:/certs:ro
      - mlflow_data:/mlflow
    ports:
      - "5000:5000"
    healthcheck:
      test:
        - CMD
        - python
        - -c
        - "import ssl, urllib.request; urllib.request.urlopen('https://127.0.0.1:5000/health', context=ssl._create_unverified_context(), timeout=5)"
      interval: 10s
      timeout: 10s
      retries: 18
      start_period: 30s

volumes:
  postgres_data:
  mlflow_data:
EOF
```

The settings that matter:

| Setting | What it does |
|---|---|
| `MLFLOW_BACKEND_STORE_URI` | Keeps runs, versions, aliases and tags in PostgreSQL |
| `MLFLOW_ARTIFACTS_DESTINATION` | Sends every uploaded file to the bucket, under `mlflow/`. Clients upload to MLflow, and MLflow writes to the bucket |
| `MLFLOW_S3_ENDPOINT_URL`, `AWS_DEFAULT_REGION` | The Object Storage [endpoint and region](https://docs.verda.com/storage/object-storage/#how-it-works) |
| The two `CHECKSUM` settings and the addressing style | The client settings from the [Object Storage quickstart](https://docs.verda.com/storage/object-storage/quickstart/#using-boto3-python). They keep MLflow's S3 client from adding optional checksum headers to its requests |
| `--app-name=basic-auth` | Requires a username and password. MLflow creates the `admin` account on first start, with the password from `.env` |
| `--allowed-hosts`, `--cors-allowed-origins` | MLflow only answers requests addressed to hosts it knows, which by default means the instance itself and private addresses. The first line adds the public address, and the second lets the web interface at that address make changes |
| `--uvicorn-opts` | Serves HTTPS with the certificate you created |
| `working_dir` and the `mlflow_data` volume | MLflow keeps its user accounts in a file in its working directory. The volume keeps that file when the container is replaced |

`postgres:16` keeps PostgreSQL on major version 16, which matters because a database created
by one major version cannot be opened by another. The MLflow tag pins the version this guide
is written against.

### Start and check

**Start the two services.** Compose waits for PostgreSQL to be healthy before starting MLflow,
and for MLflow to answer before returning:

```bash
docker compose up -d --wait --wait-timeout 300
```

```bash
docker compose ps
```

Both services should be listed as `healthy`. If Compose stops with a `Missing ...` message, a
line has been removed from `.env`. If MLflow does not become healthy, read its log with
`docker compose logs mlflow`.

### Set up the command line

The rest of the guide talks to the registry with MLflow's Python client, which you install in
a virtual environment. Install the package that creates virtual environments:

```bash
sudo apt-get install -y python3-venv
```

Create the environment:

```bash
python3 -m venv ~/regenv
```

Activate it:

```bash
source ~/regenv/bin/activate
```

Install the client:

```bash
pip install "mlflow-skinny==3.18.0"
```

`mlflow-skinny` is the client without the server, and its version matches the server's.

**Create `admin.env`**, which points the client at the registry and logs it in as `admin`:

```bash title="admin.env"
# admin.env
cat > ~/registry/admin.env <<'EOF'
source ~/regenv/bin/activate
export MLFLOW_TRACKING_URI="https://$(sed -n 's/^PUBLIC_IP=//p' ~/registry/.env):5000"
export MLFLOW_TRACKING_USERNAME=admin
export MLFLOW_TRACKING_PASSWORD="$(sed -n 's/^MLFLOW_ADMIN_PASSWORD=//p' ~/registry/.env)"
export MLFLOW_TRACKING_SERVER_CERT_PATH="$HOME/registry/certs/cert.pem"
EOF
```

**Load it** in this session:

```bash
source ~/registry/admin.env
```

Your prompt now starts with `(regenv)`, which is how you can tell that `admin.env` is loaded.

**Load it in every new session** as well. A new SSH session starts without it, so add the
same line to `~/.bashrc`, which Bash reads whenever a session starts:

```bash
echo 'source ~/registry/admin.env' >> ~/.bashrc
```

**Check the whole chain** by storing one small file. This goes through the certificate, the
login, MLflow and the bucket:

```bash
python3 - <<'EOF'
import mlflow
with mlflow.start_run(run_name="storage-check"):
    mlflow.log_text("stored through the registry", "check.txt")
print("artifact stored")
EOF
```

```text {.no-copy}
🏃 View run storage-check at: https://<registry-public-ip>:5000/#/experiments/0/runs/3497cada75634a11bf09107de99762f9
🧪 View experiment at: https://<registry-public-ip>:5000/#/experiments/0
artifact stored
```

The address and the run id will be your own. If you see an error instead, it names the link
that failed.

The file is now in your bucket, under `mlflow/`. You can see it on the bucket's page in the
console, or list it with the [Verda CLI](https://docs.verda.com/developer-tools/verda-cli/reference/object-storage/):
`verda object-storage ls s3://<bucket-name>/mlflow/ --recursive`.

**Open the web interface** at `https://<registry-public-ip>:5000` in your browser. The browser
warns that it does not know the certificate, which is expected, because it is the one you
created. Accept it, and sign in as `admin` with the password printed by:

```bash
sed -n 's/^MLFLOW_ADMIN_PASSWORD=//p' ~/registry/.env
```

!!! warning
    The registry is reachable from the internet on port 5000, protected by its login and the
    certificate. To also limit who can connect, see
    [Securing your instance](https://docs.verda.com/instances/secure-your-instance/).

## Step 3: Build the training image

The fine-tuning job runs from a container image that holds the training script and its
libraries, so the same job runs the same way on any cluster node. Building the image here and
pushing it to the Container Registry also records exactly which code produced a version.

**Create `train.py`** in `~/registry/train`:

```bash title="train.py"
# train.py
cat > ~/registry/train/train.py <<'EOF'
# train.py
import argparse, os, random, tempfile

import mlflow
import torch
from datasets import load_dataset
from mlflow import MlflowClient
from mlflow.exceptions import MlflowException
from peft import LoraConfig, get_peft_model
from transformers import AutoModelForCausalLM, AutoTokenizer

DATASET = "bitext/Bitext-customer-support-llm-chatbot-training-dataset"
DATASET_REVISION = "430d1a89bd93bd1fa23c16f29dd53e73f0087443"

p = argparse.ArgumentParser()
p.add_argument("--base-model", default="Qwen/Qwen2.5-1.5B-Instruct")
p.add_argument("--model-name", default="support-router")
p.add_argument("--train-samples", type=int, default=200)
p.add_argument("--eval-samples", type=int, default=500)
p.add_argument("--epochs", type=int, default=1)
p.add_argument("--batch-size", type=int, default=16)
p.add_argument("--lr", type=float, default=2e-4)
args = p.parse_args()

device = "cuda" if torch.cuda.is_available() else "cpu"
dtype = torch.bfloat16 if device == "cuda" else torch.float32
torch.manual_seed(0)

# The same shuffle every run, so every version is scored on the same held-out rows.
rows = list(load_dataset(DATASET, revision=DATASET_REVISION, split="train"))
random.Random(0).shuffle(rows)
eval_rows = rows[:args.eval_samples]
train_rows = rows[args.eval_samples:args.eval_samples + args.train_samples]
labels = sorted({r["category"] for r in rows})
system = ("You route customer support messages. Reply with exactly one category "
          "from this list and nothing else: " + ", ".join(labels))

tok = AutoTokenizer.from_pretrained(args.base_model)
model = AutoModelForCausalLM.from_pretrained(args.base_model, dtype=dtype).to(device)


def prompt(text):
    messages = [{"role": "system", "content": system}, {"role": "user", "content": text}]
    return tok.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)


@torch.no_grad()
def accuracy(net):
    net.eval()
    tok.padding_side = "left"
    correct = 0
    for i in range(0, len(eval_rows), 32):
        batch = eval_rows[i:i + 32]
        enc = tok([prompt(r["instruction"]) for r in batch], return_tensors="pt",
                  padding=True).to(device)
        out = net.generate(**enc, max_new_tokens=8, do_sample=False)
        answers = tok.batch_decode(out[:, enc["input_ids"].shape[1]:], skip_special_tokens=True)
        correct += sum(a.strip() == r["category"] for a, r in zip(answers, batch))
    return correct / len(eval_rows)


def collate(batch):
    ids, targets = [], []
    for r in batch:
        question = tok(prompt(r["instruction"]), add_special_tokens=False)["input_ids"]
        answer = tok(r["category"] + tok.eos_token, add_special_tokens=False)["input_ids"]
        ids.append(question + answer)
        targets.append([-100] * len(question) + answer)   # learn the answer only
    width = max(len(x) for x in ids)
    pad = tok.pad_token_id
    return (torch.tensor([x + [pad] * (width - len(x)) for x in ids]),
            torch.tensor([[1] * len(x) + [0] * (width - len(x)) for x in ids]),
            torch.tensor([t + [-100] * (width - len(t)) for t in targets]))


mlflow.set_experiment(args.model_name)
with mlflow.start_run(run_name=f"{args.train_samples}-samples") as run:
    mlflow.log_params({**vars(args), "dataset": DATASET, "dataset_revision": DATASET_REVISION})
    base_accuracy = accuracy(model)
    mlflow.log_metric("base_accuracy", base_accuracy)
    print(f"base model accuracy: {base_accuracy:.3f}")

    model = get_peft_model(model, LoraConfig(
        r=16, lora_alpha=32, lora_dropout=0.05, task_type="CAUSAL_LM",
        target_modules=["q_proj", "k_proj", "v_proj", "o_proj"]))
    optimizer = torch.optim.AdamW([w for w in model.parameters() if w.requires_grad], lr=args.lr)
    step = 0
    for epoch in range(args.epochs):
        model.train()
        random.Random(epoch).shuffle(train_rows)
        for i in range(0, len(train_rows), args.batch_size):
            ids, mask, targets = (t.to(device) for t in collate(train_rows[i:i + args.batch_size]))
            loss = model(input_ids=ids, attention_mask=mask, labels=targets).loss
            loss.backward()
            optimizer.step()
            optimizer.zero_grad()
            step += 1
            mlflow.log_metric("train_loss", loss.item(), step=step)
    print(f"trained {step} steps, last loss {loss.item():.4f}")

    model = model.merge_and_unload()      # fold the adapter into the base weights
    eval_accuracy = accuracy(model)
    mlflow.log_metric("eval_accuracy", eval_accuracy)
    print(f"fine-tuned accuracy: {eval_accuracy:.3f}")

    with tempfile.TemporaryDirectory() as out:
        model.save_pretrained(out)
        tok.save_pretrained(out)
        mlflow.log_artifacts(out, artifact_path="model")

    client = MlflowClient()
    try:
        client.create_registered_model(args.model_name)
    except MlflowException:
        pass                              # it already exists, so this run adds a version
    version = client.create_model_version(
        args.model_name, source=f"{run.info.artifact_uri}/model", run_id=run.info.run_id,
        tags={"base_model": args.base_model, "train_samples": str(args.train_samples),
              "eval_accuracy": f"{eval_accuracy:.3f}", "system_prompt": system,
              "training_image": os.environ.get("TRAINING_IMAGE", "unknown")})
    print(f"registered {args.model_name} version {version.version}")
EOF
```

The script does five things, in order:

1. **It splits the data the same way every run.** The first 500 shuffled rows are held out for
   scoring and never trained on, so the accuracy of one version can be compared with the
   accuracy of another.
2. **It scores the base model first**, which is the number a fine-tune has to beat.
3. **It trains a LoRA adapter**, a small set of extra weights, on the next rows. Only the
   category is learned: the `-100` entries tell the loss to ignore the question.
4. **It merges the adapter into the base weights** and scores the result. The merged model is
   an ordinary model folder, which is what vLLM serves.
5. **It uploads that folder and registers it.** `log_artifacts` sends the folder to the
   registry, and `create_model_version` records it as the next version of `support-router`,
   tagged with what it was trained from and how well it scored.

The dataset is the
[Bitext customer support dataset](https://huggingface.co/datasets/bitext/Bitext-customer-support-llm-chatbot-training-dataset),
pinned to one revision so a later change to it cannot alter your results. Its messages fall
into 11 categories.

**Create the `Dockerfile`** next to it:

```bash title="Dockerfile"
# Dockerfile
cat > ~/registry/train/Dockerfile <<'EOF'
FROM pytorch/pytorch:2.15.0-cuda13.2-cudnn9-runtime

RUN pip install --no-cache-dir --break-system-packages \
    "transformers==5.22.2" "peft==0.21.2" "datasets==5.2.0" "mlflow-skinny==3.18.0"

COPY train.py /opt/train/train.py

ARG IMAGE
ENV TRAINING_IMAGE=${IMAGE} GIT_PYTHON_REFRESH=quiet PYTHONUNBUFFERED=1
EOF
```

The base image brings PyTorch built for CUDA 13, which the B300 GPUs in Instant Clusters
[require](https://docs.verda.com/clusters/slinky/containers/#import-once-run-many-times).
The library versions are pinned, so the image you build next month behaves like the one you
build today. `--break-system-packages` is needed because the base image's Python is the one
that Ubuntu manages. The last line stores the image's own address, so each version can record
which image trained it, silences a warning about Git, which the image does not contain, and
makes the job print its progress as it happens.

**Set the image address.** Replace `<project-id>` with your project's id, which is part of
your registry credentials' name:

```bash
export REPO='vccr.io/<project-id>'
```

Save it for new sessions too, in the same way as `admin.env`:

```bash
echo "export REPO='$REPO'" >> ~/.bashrc
```

**Build the image** from the `train` folder:

```bash
cd ~/registry/train
```

```bash
docker build --build-arg IMAGE=$REPO/support-router-train:1 -t $REPO/support-router-train:1 .
```

**Log in to the Verda Container Registry.** Replace the three placeholders,
`<registry-secret>`, `<project-id>` and `<credentials-name>`, keeping the quotes. The secret
and the credentials name come from the Container Registry credentials in the
[Prerequisites](#prerequisites), and the whole `-u` value is their full credential name. They
are not the Object Storage access key from Step 1:

```bash
echo '<registry-secret>' | docker login vccr.io/<project-id> \
  -u 'vcr-<project-id>+<credentials-name>' --password-stdin
```

```text {.no-copy}
Login Succeeded
```

If the registry answers `unauthorized` instead, the command holds the wrong pair of values.
Check that it uses the registry secret and the name of the registry credentials.

**Push the image:**

```bash
docker push $REPO/support-router-train:1
```

## Step 4: Fine-tune and register a version

### Create an account for training jobs

The job needs to log in to the registry, and it should not do so as `admin`. Create a second
account, `trainer`, which can record runs and register versions but cannot manage accounts.

On the `registry` instance, with `admin.env` loaded, move into the working directory:

```bash
cd ~/registry
```

Generate a password for the account. It stays in a shell variable, which the commands below
read:

```bash
TRAINER_PASSWORD=$(openssl rand -hex 16)
```

Create the account:

```bash
curl --silent --show-error --fail-with-body --cacert certs/cert.pem \
  --user "admin:${MLFLOW_TRACKING_PASSWORD}" \
  --header 'Content-Type: application/json' \
  --data "{\"username\": \"trainer\", \"password\": \"${TRAINER_PASSWORD}\"}" \
  "${MLFLOW_TRACKING_URI}/api/2.0/mlflow/users/create"
```

```json {.no-copy}
{"user":{"id":2,"is_admin":false,"username":"trainer"}}
```

Then write the four settings a job needs into `registry.env`:

```bash
cat > registry.env <<EOF
MLFLOW_TRACKING_URI=${MLFLOW_TRACKING_URI}
MLFLOW_TRACKING_USERNAME=trainer
MLFLOW_TRACKING_PASSWORD=${TRAINER_PASSWORD}
MLFLOW_HTTP_REQUEST_TIMEOUT=900
EOF
```

Keep the file private, since it holds a password:

```bash
chmod 600 registry.env
```

The last setting, `MLFLOW_HTTP_REQUEST_TIMEOUT`, gives uploads more time. MLflow answers an
upload only after it has written the
file to the bucket, and for a model of several gigabytes that can take longer than the
client's default of two minutes.

The base model and the dataset are public, so the job needs no Hugging Face token. To use
one anyway, for higher download limits, add a line `HF_TOKEN=<your-hugging-face-token>` to
the file.

Print the file and the certificate. You paste both into the place the job runs from:

```bash
cat registry.env
```

```bash
cat certs/cert.pem
```

### Run the job

The job is the same everywhere: the training image, one GPU, and the two files you just
printed. Pick the tab that matches where you run it.

Each tab starts by saving those two files in a folder called `~/registry`. To save pasted
text as a file, run `cat > <file>`. The command prints nothing and waits for the text: paste
it, press **Enter** and then **Ctrl+D**.

=== "Slinky cluster"

    SSH into the cluster, which lands you in the Slurm login pod:

    ```bash
    ssh ubuntu@<cluster-ip>
    ```

    Save the two files, keeping the certificate's BEGIN and END lines:

    ```bash
    mkdir -p ~/registry && chmod 700 ~/registry
    ```

    ```bash
    cat > ~/registry/registry.env
    ```

    ```bash
    cat > ~/registry/ca.pem
    ```

    Jobs pull images with Enroot, which reads registry logins from a credentials file.
    Create its folder:

    ```bash
    mkdir -p ~/.config/enroot
    ```

    Write the file. Replace the three placeholders:

    ```bash
    cat > ~/.config/enroot/.credentials <<'EOF'
    machine vccr.io login vcr-<project-id>+<credentials-name> password <registry-secret>
    EOF
    ```

    Keep the file private, since it holds the registry secret:

    ```bash
    chmod 600 ~/.config/enroot/.credentials
    ```

    Create the job script. Replace `<project-id>` in the image name, and keep the `#` between
    the registry and the image, which is how
    [Enroot writes image names](https://docs.verda.com/clusters/slinky/containers/#pyxis-srun-container-image):

    ```bash title="finetune.sbatch"
    # finetune.sbatch
    cat > ~/finetune.sbatch <<'EOF'
    #!/bin/bash
    #SBATCH --job-name=finetune
    #SBATCH --nodes=1
    #SBATCH --gres=gpu:1
    #SBATCH --mem=64G
    #SBATCH --time=01:00:00

    set -a
    . "$HOME/registry/registry.env"
    set +a
    export MLFLOW_TRACKING_SERVER_CERT_PATH="$HOME/registry/ca.pem"
    export HF_HOME=/local/hf-cache-$USER

    srun --container-image='vccr.io#<project-id>/support-router-train:1' \
         --container-name=support-router-train-1 \
         python3 /opt/train/train.py --train-samples "${1:-200}"
    EOF
    ```

    The script loads the registry settings into the job's environment, which the container
    inherits, and keeps the downloaded base model on the worker's local disk. The number at
    the end of the `sbatch` command is how many rows to train on.

    Submit it with 200 rows:

    ```bash
    cd ~ && sbatch finetune.sbatch 200
    ```

    Watch the queue with `squeue --me`. Once the job is running, its output goes to
    `slurm-<jobid>.out` in your home directory:

    ```bash
    tail -f slurm-*.out
    ```

=== "Kubernetes cluster"

    SSH into the cluster's jumphost, where `kubectl` is set up:

    ```bash
    ssh ubuntu@<cluster-ip>
    ```

    Save the two files, keeping the certificate's BEGIN and END lines:

    ```bash
    mkdir -p ~/registry && chmod 700 ~/registry
    ```

    ```bash
    cat > ~/registry/registry.env
    ```

    ```bash
    cat > ~/registry/ca.pem
    ```

    Store them as secrets, together with the login for the Container Registry. Replace the
    three placeholders in the first command:

    ```bash
    kubectl create secret docker-registry vccr \
      --docker-server=vccr.io \
      --docker-username='vcr-<project-id>+<credentials-name>' \
      --docker-password='<registry-secret>'
    ```

    ```bash
    kubectl create secret generic registry-client --from-env-file="$HOME/registry/registry.env"
    ```

    ```bash
    kubectl create secret generic registry-ca --from-file=ca.pem="$HOME/registry/ca.pem"
    ```

    Create the job. Replace `<project-id>` in the image name:

    ```bash title="finetune-job.yaml"
    # finetune-job.yaml
    cat > ~/finetune-job.yaml <<'EOF'
    apiVersion: batch/v1
    kind: Job
    metadata:
      name: finetune-200
    spec:
      backoffLimit: 0
      template:
        spec:
          restartPolicy: Never
          imagePullSecrets:
            - name: vccr
          containers:
            - name: train
              image: vccr.io/<project-id>/support-router-train:1
              command: ["python3", "/opt/train/train.py", "--train-samples", "200"]
              envFrom:
                - secretRef:
                    name: registry-client
              env:
                - name: MLFLOW_TRACKING_SERVER_CERT_PATH
                  value: /etc/registry/ca.pem
              volumeMounts:
                - name: registry-ca
                  mountPath: /etc/registry
                  readOnly: true
              resources:
                limits:
                  nvidia.com/gpu: 1
          volumes:
            - name: registry-ca
              secret:
                secretName: registry-ca
    EOF
    ```

    Submit it, wait for the image to be pulled, then follow the log:

    ```bash
    kubectl create -f ~/finetune-job.yaml
    ```

    ```bash
    kubectl wait --for=condition=Ready pod -l job-name=finetune-200 --timeout=15m
    ```

    ```bash
    kubectl logs -f job/finetune-200
    ```

=== "GPU instance"

    Without a cluster, the same image runs on one GPU instance. Create one with a Docker
    image, such as Ubuntu 26.04, CUDA 13.1, Docker. We tested the job on B200 and A100 GPUs.
    Tesla V100 instances cannot run it, because CUDA 13, which the training image is built
    on, does not support that GPU.

    SSH into the instance. A new instance can refuse the connection for the first few
    minutes, while it is still starting.

    Save the two files, keeping the certificate's BEGIN and END lines:

    ```bash
    mkdir -p ~/registry && chmod 700 ~/registry
    ```

    ```bash
    cat > ~/registry/registry.env
    ```

    ```bash
    cat > ~/registry/ca.pem
    ```

    Log in to the Container Registry, as in
    [Step 3](#step-3-build-the-training-image):

    ```bash
    echo '<registry-secret>' | docker login vccr.io/<project-id> \
      -u 'vcr-<project-id>+<credentials-name>' --password-stdin
    ```

    Run the job with 200 rows. Replace `<project-id>` in the image name:

    ```bash
    docker run --rm --gpus all \
      --env-file ~/registry/registry.env \
      --env MLFLOW_TRACKING_SERVER_CERT_PATH=/etc/registry/ca.pem \
      --volume ~/registry/ca.pem:/etc/registry/ca.pem:ro \
      vccr.io/<project-id>/support-router-train:1 \
      python3 /opt/train/train.py --train-samples 200
    ```

The first run downloads the training image, the base model and the dataset, so expect a wait
before the first line. A warning about unauthenticated requests to the HF Hub is expected,
because the job uses no Hugging Face token. Between the download progress bars and MLflow's
own messages, the job prints four lines:

```text {.no-copy}
base model accuracy: 0.716
trained 13 steps, last loss 0.4939
fine-tuned accuracy: 0.852
registered support-router version 1
```

Your numbers may differ slightly. The base model put 72% of the held-out messages in the
right category, and after 13 training steps on 200 rows the fine-tuned model reaches 85%.
That model is now version 1 in the registry.

If the job stops with `certificate verify failed`, the certificate was not saved completely.
Save it again, with its BEGIN and END lines. If it stops with `401`, check `registry.env` for
a missing line or a stray space.

## Step 5: Read the registry

Back on the `registry` instance, with `admin.env` loaded, create a small script for the
registry tasks in the rest of the guide:

```bash title="registry.py"
# registry.py
cat > ~/registry/registry.py <<'EOF'
# registry.py
import shutil, sys

import mlflow
from mlflow import MlflowClient

NAME = "support-router"
client = MlflowClient()


def resolve(ref):
    """Turn a version number, or an alias such as champion, into a version number."""
    return ref if ref.isdigit() else client.get_model_version_by_alias(NAME, ref).version


def show_all():
    aliases = client.get_registered_model(NAME).aliases        # alias -> version
    print(f"{'version':<9}{'alias':<10}{'accuracy':<10}{'samples':<9}endpoint")
    for v in sorted(client.search_model_versions(f"name='{NAME}'"), key=lambda v: int(v.version)):
        alias = ",".join(a for a, n in aliases.items() if n == v.version)
        print(f"{v.version:<9}{alias:<10}{v.tags.get('eval_accuracy', ''):<10}"
              f"{v.tags.get('train_samples', ''):<9}{v.tags.get('serving.endpoint', '')}")


command, args = (sys.argv[1], sys.argv[2:]) if len(sys.argv) > 1 else ("", [])
if command == "list":
    show_all()
elif command == "show" and len(args) == 1:
    version = client.get_model_version(NAME, resolve(args[0]))
    print(f"{NAME} version {version.version}, from run {version.run_id}")
    for key, value in sorted(version.tags.items()):
        print(f"  {key}: {value}")
elif command == "fetch" and len(args) == 1:
    number = resolve(args[0])
    shutil.rmtree("model", ignore_errors=True)
    mlflow.artifacts.download_artifacts(artifact_uri=f"models:/{NAME}/{number}", dst_path="model")
    print(f"downloaded {NAME} version {number} to ./model")
elif command == "tag" and len(args) == 3:
    client.set_model_version_tag(NAME, resolve(args[0]), args[1], args[2])
    show_all()
elif command == "promote" and len(args) == 1:
    client.set_registered_model_alias(NAME, "champion", args[0])
    show_all()
else:
    sys.exit("usage: registry.py list | show <ref> | fetch <ref> | "
             "tag <ref> <key> <value> | promote <version>")
EOF
```

List the versions:

```bash
python3 ~/registry/registry.py list
```

```text {.no-copy}
version  alias     accuracy  samples  endpoint
1                  0.852     200
```

If you see `ModuleNotFoundError: No module named 'mlflow'` instead, `admin.env` is not loaded
in this session, and the prompt does not start with `(regenv)`. Run
`source ~/registry/admin.env` and repeat the command.

Then look at everything the registry holds about version 1:

```bash
python3 ~/registry/registry.py show 1
```

```text {.no-copy}
support-router version 1, from run 91f0072051b148cea89003c2ecc3398f
  base_model: Qwen/Qwen2.5-1.5B-Instruct
  eval_accuracy: 0.852
  system_prompt: You route customer support messages. Reply with exactly one category from this list and nothing else: ACCOUNT, CANCEL, CONTACT, DELIVERY, FEEDBACK, INVOICE, ORDER, PAYMENT, REFUND, SHIPPING, SUBSCRIPTION
  train_samples: 200
  training_image: vccr.io/<project-id>/support-router-train:1
```

These tags are the version's metadata. The system prompt is stored with the version because a
fine-tuned model should be called with the prompt it was trained on, and the run id links to
the training run, where the web interface shows the loss curve and every parameter.

The weights are in your bucket, in the folder of that run:
`mlflow/<experiment-id>/<run-id>/artifacts/model/`.

## Step 6: Package version 1 and deploy it

A version becomes servable once its weights are inside a container image. The image starts
from the vLLM image used in the [vLLM quickstart](https://docs.verda.com/serverless-containers/quickstart/) and adds the
model folder, so a deployment needs no credentials and no download at start-up.

Every command in this step runs on the `registry` instance. Only the deployment itself is
created in the console.

**Create the `Dockerfile`** in `~/registry/serve`:

```bash title="Dockerfile"
# Dockerfile
cat > ~/registry/serve/Dockerfile <<'EOF'
FROM vllm/vllm-openai:v0.29.0

COPY model/ /models/support-router/

ARG MODEL_VERSION
ENV MODEL_VERSION=${MODEL_VERSION}

ENTRYPOINT ["/bin/sh", "-c", "exec vllm serve /models/support-router --served-model-name support-router-v${MODEL_VERSION} support-router"]
EOF
```

The model is served under two names. Applications ask for `support-router`, which stays the
same across versions. The first name carries the version number, and vLLM returns the first
name in every response, so each answer says which version produced it.

**Fetch version 1 from the registry.** Move into the `serve` folder first, because the script
downloads into the folder it is run from:

```bash
cd ~/registry/serve
```

```bash
python3 ~/registry/registry.py fetch 1
```

```text {.no-copy}
downloaded support-router version 1 to ./model
```

**Build its image.** The build packages whatever is in `./model`, so always fetch a version
right before you build its image:

```bash
docker build --build-arg MODEL_VERSION=1 -t $REPO/support-router:v1 .
```

The first build takes several minutes, since it pulls the vLLM base image. If Docker answers
`invalid tag` instead, `REPO` is empty in this session. Set it as in
[Step 3](#step-3-build-the-training-image) and repeat the build. If your
SSH connection drops during the build, reconnect and run it again. Docker keeps the layers it
already has, so the second run is quick.

**Push it:**

```bash
docker push $REPO/support-router:v1
```

**Create a deployment** in **Containers → New deployment** with these settings:

| Field | Value |
|---|---|
| Deployment name | `support-router-v1` |
| GPU type | L40S 48GB, which is enough for this model. Use RTX PRO 6000 if no L40S is available |
| Container image | `vccr.io/<project-id>/support-router:v1` |
| Registry credentials | The credentials you used to push |
| Start command | Leave the toggle off. The image starts vLLM itself |
| Exposed HTTP port and healthcheck port | `8000`, the port vLLM listens on |
| Healthcheck path | `/health`, the path vLLM exposes |

The deployment pulls the image, starts the container and loads the weights, which took about
three minutes in our test. Until it is healthy, its system log shows
`Startup probe failed: connection refused`. That is expected, because nothing listens on the
port while the weights load.

Once the deployment reports healthy, copy its **Endpoint Address** from the deployment page.

**Record where the version is served.** Back on the `registry` instance, run these two
commands. Replace `<endpoint-address-v1>` with the address you copied:

```bash
python3 ~/registry/registry.py tag 1 serving.image $REPO/support-router:v1
```

```bash
python3 ~/registry/registry.py tag 1 serving.endpoint '<endpoint-address-v1>'
```

**Make version 1 the champion:**

```bash
python3 ~/registry/registry.py promote 1
```

```text {.no-copy}
version  alias     accuracy  samples  endpoint
1        champion  0.852     200      <endpoint-address-v1>
```

### Call the champion

An application should not hold the address of one deployment. It asks the registry which
version is the champion, and calls the endpoint recorded for it.

**Create `ask.py`**, which does exactly that:

```bash title="ask.py"
# ask.py
cat > ~/registry/ask.py <<'EOF'
# ask.py
import os, sys

import requests
from mlflow import MlflowClient

NAME = "support-router"
version = MlflowClient().get_model_version_by_alias(NAME, "champion")
endpoint = version.tags["serving.endpoint"].rstrip("/")

response = requests.post(
    f"{endpoint}/v1/chat/completions",
    headers={"Authorization": f"Bearer {os.environ['VERDA_INFERENCE_KEY']}"},
    json={"model": NAME, "temperature": 0, "max_tokens": 8,
          "messages": [{"role": "system", "content": version.tags["system_prompt"]},
                       {"role": "user", "content": sys.argv[1]}]},
    timeout=600,   # covers a cold start
)
response.raise_for_status()
answer = response.json()

print(f"champion: version {version.version} at {endpoint}")
print(f"answered by: {answer['model']}")
print(f"category: {answer['choices'][0]['message']['content']}")
EOF
```

Set your Inference API Key, which is how Verda authenticates callers to any container
endpoint, and ask a question:

```bash
export VERDA_INFERENCE_KEY='<your-inference-api-key>'
```

The key is not saved on the instance, so set it again after you reconnect. Without it,
`ask.py` stops with `KeyError: 'VERDA_INFERENCE_KEY'`.

**The first call can sit silent for about five minutes.** A deployment with no replica
running starts one when a request arrives, and the new replica pulls the 36 GB image and
loads the weights before it answers. That wait is a [cold start](https://docs.verda.com/serverless-containers/#cold-starts), and
it took about five minutes in our test. `ask.py` prints nothing until the answer arrives, and
waits up to 600 seconds for it.

```bash
python3 ~/registry/ask.py "I want my money back for the damaged item"
```

```text {.no-copy}
champion: version 1 at <endpoint-address-v1>
answered by: support-router-v1
category: REFUND
```

The script took the endpoint and the system prompt from the registry, and the
`answered by` line comes from the deployment itself. `temperature: 0` makes the model pick
its most likely answer every time, which is what a router should do.

## Step 7: Train a second version and promote it

Version 1 saw 200 rows. Run the job again with 1,000:

=== "Slinky cluster"

    ```bash
    cd ~ && sbatch finetune.sbatch 1000
    ```

=== "Kubernetes cluster"

    ```bash
    sed 's/200/1000/g' ~/finetune-job.yaml | kubectl create -f -
    ```

    ```bash
    kubectl wait --for=condition=Ready pod -l job-name=finetune-1000 --timeout=15m
    ```

    ```bash
    kubectl logs -f job/finetune-1000
    ```

=== "GPU instance"

    Run the same `docker run` command as in
    [Step 4](#step-4-fine-tune-and-register-a-version), with `--train-samples 1000`.

```text {.no-copy}
base model accuracy: 0.716
trained 63 steps, last loss 0.0223
fine-tuned accuracy: 0.992
registered support-router version 2
```

The base model's score is the same as before, because both runs are scored on the same
held-out rows. Trained on 1,000 rows instead of 200, the model now puts 99% of them in the
right category. On the `registry` instance, the registry now holds two versions:

```bash
python3 ~/registry/registry.py list
```

```text {.no-copy}
version  alias     accuracy  samples  endpoint
1        champion  0.852     200      <endpoint-address-v1>
2                  0.992     1000
```

Version 2 scores higher, but nothing has changed for the application. It is still served by
version 1 until you decide otherwise.

**Package and deploy version 2** the same way as version 1:

```bash
cd ~/registry/serve
```

```bash
python3 ~/registry/registry.py fetch 2
```

```bash
docker build --build-arg MODEL_VERSION=2 -t $REPO/support-router:v2 .
```

```bash
docker push $REPO/support-router:v2
```

Create a second deployment with the settings from
[Step 6](#step-6-package-version-1-and-deploy-it), named `support-router-v2`, with the
container image `vccr.io/<project-id>/support-router:v2`. When it is healthy, record its
Endpoint Address:

```bash
python3 ~/registry/registry.py tag 2 serving.image $REPO/support-router:v2
```

```bash
python3 ~/registry/registry.py tag 2 serving.endpoint '<endpoint-address-v2>'
```

Both versions are now deployed, and the champion is still version 1. Check that:

```bash
python3 ~/registry/ask.py "I want my money back for the damaged item"
```

```text {.no-copy}
champion: version 1 at <endpoint-address-v1>
answered by: support-router-v1
category: REFUND
```

**Promote version 2:**

```bash
python3 ~/registry/registry.py promote 2
```

```text {.no-copy}
version  alias     accuracy  samples  endpoint
1                  0.852     200      <endpoint-address-v1>
2        champion  0.992     1000     <endpoint-address-v2>
```

Ask again, without changing anything else. This is the first call to the version 2
deployment, so it can wait for a cold start, as in [Step 6](#call-the-champion):

```bash
python3 ~/registry/ask.py "I want my money back for the damaged item"
```

```text {.no-copy}
champion: version 2 at <endpoint-address-v2>
answered by: support-router-v2
category: REFUND
```

The same command now reaches the other deployment. The switch was one write to the registry,
with no deployment edited and no image rebuilt.

## Step 8: Roll back

If version 2 misbehaves in use, move the alias back:

```bash
python3 ~/registry/registry.py promote 1
```

```text {.no-copy}
version  alias     accuracy  samples  endpoint
1        champion  0.852     200      <endpoint-address-v1>
2                  0.992     1000     <endpoint-address-v2>
```

```bash
python3 ~/registry/ask.py "I want my money back for the damaged item"
```

```text {.no-copy}
champion: version 1 at <endpoint-address-v1>
answered by: support-router-v1
category: REFUND
```

Version 1 answers again. Rolling back is one command because the previous version's
deployment and image were never touched. Keeping that deployment costs little: with a
minimum of zero replicas, an idle deployment scales to zero and costs nothing until the next
request, which then waits for a cold start of about five minutes.

Congratulations! You now have a registry that records every fine-tuned version with its
weights and its score, a repeatable way to turn a version into an endpoint, and one command
that decides which version your application uses.

***

## After it works

### Protecting version images

A rollback relies on `support-router:v1` still being the image you tested. Add a
[tag immutability rule](https://docs.verda.com/storage/container-registry/tag-immutability-rules/) for the
`support-router` repository, so that a later push cannot replace a version's image.

### Larger models

Two things in this guide grow with the size of the model:

- **Uploads pass through the registry instance.** MLflow writes each uploaded file to its own
  disk before sending it to the bucket, so the instance needs free space for the largest
  file, and a long upload needs a larger `MLFLOW_HTTP_REQUEST_TIMEOUT` in `registry.env`.
- **The weights are part of the image.** That keeps a deployment self-contained, and suits
  models of a few gigabytes. For much larger models, keep the weights on
  [storage attached to the deployment](https://docs.verda.com/serverless-containers/storage/) instead and build the image without
  them.

Object Storage is in Beta and has a [quota](https://docs.verda.com/storage/object-storage/#limits-and-quota)
on stored data and on the number of objects. Each version in this guide stores six files.

### One address for applications

`ask.py` reads the registry on every call, which suits a script. For several applications,
put the [LLM API gateway](https://docs.verda.com/serverless-containers/tutorials/guide-llm-api-gateway/) in front of the deployments instead, so
that they keep one address and one key each while you change which deployment is behind it.

***

## Conclusion

You now have an MLflow registry on a CPU instance that stores model weights in Object
Storage, a fine-tuning job that registers its result as a version with its accuracy, a
container image and a Serverless Container deployment for each version, and a `champion`
alias that switches between them.

**To clean up.** Delete both deployments, `support-router-v1` and `support-router-v2`, and
the `support-router` and `support-router-train` repositories in the Container Registry.
Delete the cluster or the GPU instance you trained on. To stop the registry while keeping its
data:

```bash
cd ~/registry
```

```bash
docker compose stop
```

Stopping the services does not stop the instance, which keeps billing while it exists.
[Discontinue](https://docs.verda.com/instances/shutdown-and-delete/) the `registry`
instance when you no longer need it. The weights stay in Object Storage, which bills for
stored data, until you remove them. A bucket has to be empty before it can be deleted, so
empty it first, for example with
`verda object-storage rm s3://<bucket-name>/mlflow/ --recursive` from the
[Verda CLI](https://docs.verda.com/developer-tools/verda-cli/reference/object-storage/), then delete the bucket on the **Object storage**
page. Neither step can be undone. Finally, delete the Object Storage access key and the
registry credentials on the **Credentials** page if nothing else uses them.

***

## Related guides

- [Deploy with vLLM](https://docs.verda.com/serverless-containers/quickstart/): the deployment settings and the vLLM image
  this guide builds on.
- [Object Storage](https://docs.verda.com/storage/object-storage/): buckets, access keys, pricing and
  quota.
- [Verda CLI: Object Storage](https://docs.verda.com/developer-tools/verda-cli/reference/object-storage/): list, copy and sync the stored
  weights from the command line.
- [Container Registry](https://docs.verda.com/storage/container-registry/): credentials, image
  addresses and tag rules.
- [Slinky containers](https://docs.verda.com/clusters/slinky/containers/) and
  [Kubernetes quickstart](https://docs.verda.com/clusters/kubernetes/quickstart/):
  running container images as cluster jobs.
- [LLM API gateway](https://docs.verda.com/serverless-containers/tutorials/guide-llm-api-gateway/): one endpoint in front of several deployments,
  with per-application keys and failover.
- [Secrets management](https://docs.verda.com/serverless-containers/tutorials/guide-secrets-management/): keeping credentials such as the
  registry login out of job scripts.
