> ## Documentation Index
> Fetch the complete documentation index at: https://anaconda.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Monitoring model training with cards

When a training step runs for hours, problems don't always show up as errors. The model might stop improving halfway through, or the step might slow to a crawl without failing. If you find out only after training finishes, you've already paid for compute that didn't help. If you catch the problem while the step is still running, you can stop it early and adjust your settings for the next run.

The usual ways to watch a running step each come with a tradeoff. Print statements take one line to add, but they produce a stream of numbers that's hard to read at a glance, so spotting a trend takes work. A dashboard or experiment-tracking service turns those numbers into charts, but it's another service to set up and maintain, and its view of a run can drift from the code that produced it.

With a few lines of Python, the `@card` decorator adds progress bars, metrics, and charts to a step and updates them while the step runs, without needing to set up a separate service. You can watch the card while the step progresses. Because the card is stored with the task, it still shows what the step reported after the run finishes, so it can't drift from the code that produced it.

![The local card viewer at localhost:8324, showing the training card with its status heading, a completed progress bar, the best validation log loss, and a line chart of training and validation loss across 500 rounds](https://mintcdn.com/anaconda-29683c67/3nMRFuY0GC_hhV8o/images/platform/plat_tutorial_live_card_local_viewer.png?fit=max\&auto=format\&n=3nMRFuY0GC_hhV8o\&q=85\&s=24f4f7cff3e6bbef156caa077c3eed09)

Advanced

**Purpose**: This tutorial teaches you how to monitor a long-running training step in real time.

**Outcome**: You'll build a model training flow that uses a card to show training progress, the best validation score so far, and a chart of training and validation loss that updates while the step runs. You'll watch the card in your browser as the step runs locally, then in the platform's  **Runs** view while it runs on cloud compute.

**Audience**: Data scientists and ML engineers who already run flows on Anaconda Platform.

**Duration**: 30 to 45 minutes, including environment build time

## Prerequisites

Before you begin, make sure you have the following:

* A macOS or Linux machine, or a [cloud workstation](https://anaconda.com/docs/platform/concepts/what-is-a-workstation.md).

  > [!NOTE]
  >
  > Metaflow is built for macOS and Linux. Windows machines require [Windows Subsystem for Linux (WSL)](https://learn.microsoft.com/en-us/windows/wsl/install) to run Metaflow.

* The `outerbounds` package installed and connected to your platform.

  > [!TIP]
  >
  > For setup instructions, see [Connect to Anaconda Platform and run your first flow](https://anaconda.com/docs/platform/getting-started/connect-and-first-run.md).

* Access to a compute pool for running *Metaflow Tasks*.

## How cards work

By default, adding the `@card` decorator to a step produces a visual report of the step after it finishes. However, you can instruct your flow to update the card as the step runs, allowing you to watch the step complete in real time. You can view the card in the  Runs view, or in Metaflow's local card viewer, which shows cards in your browser without the platform UI.

Cards display components that you configure, such as blocks of text, progress bars, and charts. Each component is a Python object that you create in your step's code.

To configure a card to update while a step runs:

**1. Attach a card to the step**

`@card(type="blank")` attaches an empty card that you fill with components. Without `type="blank"`, Metaflow uses the default card, which also lists the step's artifacts.

**2. Add components to the card**

There are two methods for adding components to your card:

* `current.card.append(<COMPONENT>)` adds one component
* `current.card.extend([<COMPONENT_1>, <COMPONENT_2>])` adds a list of components

> [!TIP]
>
> Components appear on the card in the order you add them.

**3. Update component values**

Each component has its own `update()` method, which sets a new value for that component, such as a progress bar's position or the text in a Markdown block. Call it from the loop or callback where your step does its work.

**4. Refresh the card**

New values received from calling `update()` stay in your step's memory until you refresh the card. `current.card.refresh()` sends the current state of every component to the viewer. Call it after your updates, in the same loop.

```python Minimal training loop example theme={null}
from metaflow import card, current, step
from metaflow.cards import ProgressBar

@card(type="blank")
@step
def train(self):
    progress = ProgressBar(max=500, label="Rounds")
    current.card.append(progress)
    for i in range(500):
        ...  # Train one round
        progress.update(i + 1)
        current.card.refresh()
```

The card in this tutorial uses four built-in components:

Component

What it shows on this tutorial's card

`Markdown`

A status line at the top of the card, such as **"Training: round 120 of 500"**.

`ProgressBar`

A bar that fills as rounds complete, with the training speed in rounds per second.

`ValueBox`

The lowest validation loss so far, as one large number, with the training round where it happened.

`VegaChart`

A line chart of training and validation loss for every round so far, defined as a Python dictionary in [Vega-Lite](https://vega.github.io/vega-lite/) format.

LearnMore

**Learn more**

Review the following resources to learn more about the topics covered in this section, or continue on to the next section.

* [Visualizing results](https://docs.metaflow.org/metaflow/visualizing-results)
* [Updating cards during task execution](https://docs.metaflow.org/metaflow/visualizing-results/dynamic-cards)
* [Card components reference](https://docs.metaflow.org/api/cards#card-components)

## Building a step that updates its card

In this section, you'll create two files: a module that builds and updates the card during XGBoost training and the flow that uses it.

**1. Create a project directory**

Create a directory for the tutorial and navigate to it:

```sh theme={null}
mkdir live-card-tutorial && cd live-card-tutorial
```

Metaflow packages every Python file in this directory with your flow, so the flow can import the module you create next, both locally and in the cloud.

**2. Create the card callback**

XGBoost calls a [training callback](https://xgboost.readthedocs.io/en/stable/python/callbacks.html) after every boosting round, along with the latest evaluation scores. That makes a callback a natural place to update the card. Create a file named `live_card.py` with the following contents:

```python live_card.py expandable highlight={28-33,39-44,49-53,58} theme={null}
import time

import xgboost
from metaflow import current
from metaflow.cards import Markdown, ProgressBar, ValueBox, VegaChart


class CardUpdater(xgboost.callback.TrainingCallback):
    def __init__(self, total_rounds):
        self.total_rounds = total_rounds
        self.started = time.time()
        self.spec = {
            "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
            "data": {"values": []},
            "mark": "line",
            "encoding": {
                "x": {"field": "round", "type": "quantitative", "title": "Round"},
                "y": {
                    "field": "logloss",
                    "type": "quantitative",
                    "title": "Log loss",
                    "scale": {"type": "log"},
                },
                "color": {"field": "dataset", "type": "nominal", "title": "Dataset"},
            },
        }

        self.status = Markdown("## Starting training")
        self.progress = ProgressBar(max=total_rounds, label="Boosting rounds")
        self.best = ValueBox(title="Best validation log loss", value="Waiting")
        self.chart = VegaChart(self.spec)
        current.card.extend([self.status, self.progress, self.best, self.chart])
        current.card.refresh()

    def after_iteration(self, model, epoch, evals_log):
        done = epoch + 1
        train_loss = evals_log["train"]["logloss"]
        valid_loss = evals_log["validation"]["logloss"]
        self.spec["data"]["values"].extend(
            [
                {"round": done, "dataset": "train", "logloss": train_loss[-1]},
                {"round": done, "dataset": "validation", "logloss": valid_loss[-1]},
            ]
        )
        best = min(valid_loss)
        best_round = valid_loss.index(best) + 1
        rate = done / (time.time() - self.started)

        self.status.update(f"## Training: round {done} of {self.total_rounds}")
        self.progress.update(done, metadata=f"{rate:.1f} rounds/s")
        self.best.update(value=round(best, 4), subtitle=f"Round {best_round}")
        self.chart.update(self.spec)
        current.card.refresh()
        return False

    def after_training(self, model):
        elapsed = time.time() - self.started
        self.status.update(f"## Training finished in {elapsed:.0f} seconds")
        current.card.refresh()
        return model


class SlowDown(xgboost.callback.TrainingCallback):
    def __init__(self, seconds):
        self.seconds = seconds

    def after_iteration(self, model, epoch, evals_log):
        time.sleep(self.seconds)
        return False
```

The file defines two callbacks:

* **`CardUpdater`**: Builds the card and keeps it current. The highlighted lines are where it works with the card:
  * When training starts, it creates the four components, adds them to the card with `current.card.extend()`, and calls `refresh()` so the card appears before the first round finishes.
  * After each round, it adds the latest training and validation loss to the chart's data, calls `update()` on each component, and then calls `refresh()`.
  * When training ends, it updates the status heading with the total training time.
* **`SlowDown`**: Pauses after each round so that training lasts about two minutes, long enough to watch the card change. The sample dataset trains in seconds on most machines. Leave this callback out of your own projects.

The chart plots loss on a logarithmic scale, so small changes late in training stay visible next to the large drop in the first few rounds.

**3. Create the flow**

Create a file named `live_card_flow.py` with the following contents:

```python live_card_flow.py expandable highlight={29,38-40,46-47} theme={null}
from metaflow import FlowSpec, Parameter, anaconda_base, card, step


@anaconda_base(
    python="3.12",
    packages={"xgboost": "3.4.1", "scikit-learn": "1.9.1"},
)
class LiveCardFlow(FlowSpec):
    rounds = Parameter("rounds", help="Total boosting rounds", default=500)
    pause = Parameter(
        "pause",
        help="Seconds to wait after each round, to slow training down (0 disables)",
        default=0.2,
    )

    @step
    def start(self):
        from sklearn.datasets import make_classification
        from sklearn.model_selection import train_test_split

        X, y = make_classification(
            n_samples=100_000, n_features=50, n_informative=20, random_state=42
        )
        self.X_train, self.X_valid, self.y_train, self.y_valid = train_test_split(
            X, y, random_state=42
        )
        self.next(self.train)

    @card(type="blank", id="training", refresh_interval=1)
    @step
    def train(self):
        import xgboost as xgb
        from live_card import CardUpdater, SlowDown

        train = xgb.DMatrix(self.X_train, label=self.y_train)
        valid = xgb.DMatrix(self.X_valid, label=self.y_valid)

        callbacks = [CardUpdater(total_rounds=self.rounds)]
        if self.pause:
            callbacks.append(SlowDown(seconds=self.pause))

        self.model = xgb.train(
            {"objective": "binary:logistic", "eval_metric": "logloss", "max_depth": 8},
            train,
            num_boost_round=self.rounds,
            evals=[(train, "train"), (valid, "validation")],
            callbacks=callbacks,
            verbose_eval=False,
        )
        self.next(self.end)

    @step
    def end(self):
        print(f"Trained {self.model.num_boosted_rounds()} rounds")


if __name__ == "__main__":
    LiveCardFlow()
```

The flow has two parameters you can change on the command line. `--rounds` sets the total number of boosting rounds, and `--pause` sets the seconds to wait after each round. The default pause of 0.2 seconds makes the run last about two minutes. Set `--pause 0` to disable it.

The highlighted lines connect the card to training:

* `@card(type="blank", id="training", refresh_interval=1)` attaches an empty card to the `train` step that updates at most once per second. The `id` gives the card a name, which the Runs view uses as the card's tab label.
* The `callbacks` list passes `CardUpdater` to XGBoost, along with `SlowDown` unless you set `--pause 0`.
* The `evals` argument tells XGBoost to score the model on the training and validation data after every round. Those scores arrive in the callback as `evals_log`, a dictionary keyed by dataset name and then by metric name.

The `start` step generates a sample classification dataset with scikit-learn and splits it into training and validation sets. `@anaconda_base` declares the packages every step needs, sourced from Anaconda's `main` channel. After training, Metaflow saves `self.model` as an artifact of the `train` task, which you can load later with the Client API.

Your `live-card-tutorial` directory now contains `live_card.py` and `live_card_flow.py`.

LearnMore

**Learn more**

Review the following resources to learn more about the topics covered in this section, or continue on to the next section.

* [Define the environment](https://anaconda.com/docs/platform/getting-started/defining-the-environment.md)
* [Managing dependencies](https://anaconda.com/docs/platform/guides/compute/managing-dependencies.md)
* [Vega-Lite examples](https://vega.github.io/vega-lite/examples/)

## Watching the card locally

Metaflow includes a local card viewer that shows cards in your browser as a flow runs. It's the quickest way to check a card while you're developing it.

**1. Start the card viewer**

From the `live-card-tutorial` directory, start the card viewer:

```sh theme={null}
python live_card_flow.py --environment=anaconda card server --poll-interval 1
```

The viewer follows the latest run of `LiveCardFlow` and switches to each new run automatically when it starts. The `--poll-interval 1` option checks for card updates every second instead of every five seconds.

Leave the viewer running, and open `http://localhost:8324` in your browser.

**2. Run the flow**

Open a second terminal, navigate to the `live-card-tutorial` directory, and run the flow:

```sh theme={null}
python live_card_flow.py --environment=anaconda run
```

> [!TIP]
>
> The first run takes a few minutes longer than subsequent runs because Metaflow needs to build the environment declared in `@anaconda_base`.

Troubleshoot

The run fails with a 403 error from `repo.anaconda.cloud`

***

<details>
  <summary>Cause</summary>

  Your conda configuration lists channels on `repo.anaconda.cloud`. Metaflow builds local environments with micromamba, which reads your conda configuration but can't authenticate to those channels with the token that `anaconda-auth` stores.
</details>

***

<details>
  <summary>Solution</summary>

  Run the flow with micromamba's configuration files turned off:

  ```sh theme={null}
  MAMBA_NO_RC=true python live_card_flow.py --environment=anaconda run
  ```
</details>

**3. Watch the card update**

When the `train` step starts, return to your browser. The viewer shows the card for the `train` task and updates it every second as training progresses.

As the card updates, watch the two lines on the chart. Training loss keeps falling for the whole run, but validation loss flattens out near 0.09 within the first hundred rounds, and the gap between the two lines keeps growing. The **Best validation log loss** box stops changing at round 194 and holds that score for the rest of the run, with **Round 194** underneath. The growing gap is the model learning details of the training data that don't carry over to new data. In a real training job, a card like this tells you while the job is still running that the remaining rounds won't improve the model, so you can stop early or adjust your settings.

**Expected result**: The card shows `Training finished in` followed by the total time, and the progress bar shows `500/500`. In the second terminal, the run ends with `Trained 500 rounds`.

When you're done, press Ctrl+C in the first terminal to stop the card viewer.

LearnMore

**Learn more**

Review the following resources to learn more about the topics covered in this section, or continue on to the next section.

* [Using the local card viewer](https://docs.metaflow.org/metaflow/visualizing-results/effortless-task-inspection-with-default-cards#using-local-card-viewer)
* [Early stopping in XGBoost](https://xgboost.readthedocs.io/en/stable/python/python_intro.html#early-stopping)

## Watching the card in the cloud

The card works the same way when the step runs on cloud compute. The task sends card updates to your platform's storage as it runs, and the  **Runs** view shows them, so you can check on a long training job from anywhere without keeping a terminal open.

**1. Run the flow on cloud compute**

Run the same flow on cloud compute. You don't need to change any code:

```sh theme={null}
python live_card_flow.py --environment=fast-bakery run --with kubernetes
```

Anaconda Platform builds the environment into a container image and runs each step in its own container on the cluster. The first run takes a few minutes while the image builds and the cluster starts the containers.

**2. Open the card in the Runs view**

When the output shows that the `train` step has started, follow the link printed at the start of the run to view it in the UI. Select the `train` task, then select the **Cards** tab.

![Viewing the card in the Platform UI as it updates](https://mintcdn.com/anaconda-29683c67/3nMRFuY0GC_hhV8o/images/platform/live_card_tutorial.gif?s=0848daed0213b163737d4ab590b51ef3)

**Expected result**: The **training** card shows the same components as in the local viewer and updates while the task runs. After the run finishes, the card stays with the task, so you can return to it at any time to see how training went.

LearnMore

**Learn more**

Review the following resources to learn more about the topics covered in this section, or continue on to the next section.

* [Scale to the cloud](https://anaconda.com/docs/platform/getting-started/scaling-to-the-cloud.md)
* [What is compute?](https://anaconda.com/docs/platform/concepts/what-is-compute.md)

## Tutorial wrap up

You've built a card that reports on training while it happens. The card showed training progress, the best validation score, and the loss curves as each round finished, first in the local card viewer and then in the  **Runs** view while the step ran on cloud compute.

**What you learned**

* How a card behaves differently when you update it while a step runs
* How to add components to a card with `current.card.extend()` and keep them current with `update()` and `current.card.refresh()`
* How to use a training callback to update a card after every round
* How to watch cards locally with the card viewer and in the  **Runs** view
* How a chart of the loss curves shows when more training stops helping

**Next steps**

* The [dynamic card gallery](https://github.com/outerbounds/dynamic-card-examples) includes `monitor-callback`, which uses the same callback pattern as this tutorial. It also shows work in separate threads and subprocesses, and charts built with Altair.
* [Card templates](https://docs.metaflow.org/metaflow/visualizing-results/advanced-shareable-cards-with-card-templates) explain how to build fully custom cards with any JavaScript library and share them as Python packages. The [3D scatter plot card](https://github.com/outerbounds/metaflow-card-scatter3d) is a starter template for a custom card.
* [Training models that recover from interruptions](https://anaconda.com/docs/platform/tutorials/fault-tolerant-training.md) shows how to resume a failed training step from its latest checkpoint, which pairs well with an updating card on long training jobs.

**Have feedback?**

Use the thumbs up/thumbs down feedback buttons below to let us know what you thought about this tutorial and help us improve.
