Skip to main content

End-to-End MLOps Tutorial in Python — Part 2: Version Data and Models with DVC

· 47 min read
Jagdish Kumawat
Founder @ Dewiride

In Part 1, Git kept the code and the settings, but it ignored the data and the model, so no commit could say which data a model learned from or which model it made. In this part you put both under version control with DVC: every commit now names its exact data and model, and any earlier version comes back with two commands.

This is Part 2 of an 11-part series.

  1. Part 1: Set Up a Reproducible Machine Learning Project
  2. Part 2: Version Data and Models with DVC (you are here)
  3. Part 3: Build a Reproducible Training Pipeline with DVC (coming soon)
  4. Part 4: Validate Data in the Pipeline with Pandera (coming soon)
  5. Part 5: Track Pipeline Experiments with DVC and MLflow (coming soon)
  6. Part 6: Continuous Integration for Machine Learning with GitHub Actions (coming soon)
  7. Part 7: Serve the Model as an API with FastAPI and Docker (coming soon)
  8. Part 8: Continuous Delivery of the Model Image with GitHub Actions (coming soon)
  9. Part 9: Monitor Data Drift and Model Performance with Evidently (coming soon)
  10. Part 10: Automate Monitoring and Retraining with Prefect (coming soon)
  11. Part 11: Production Checklist and Recap (coming soon)

Every command and output on this page is real, captured while building the project.

Why Data and Models Need Version Control​

Part 1 made training reproducible: the same code, packages, data and settings give the same scores. But only part of that is in Git. .gitignore keeps data/ and models/ out, so a commit records how to make a model, not which model it made or which data it learned from. That gap shows up as soon as anything changes:

  • New data arrives and you train again. The new model file replaces the old one, and nothing records which data the old one came from.
  • A model in use starts to make bad predictions. To find out why, you need the exact data it learned from, maybe months later.
  • A teammate clones the project. They get the code, but not the data or the model, and have to rebuild both, hoping they come out the same.

Versioning data and models closes that gap. Each commit of the project names the exact data and the exact model that belong to it, and you can get them back at any time. Microsoft's MLOps maturity model expects it from level 2, "Automated training", on: "Training code and models are both version controlled."

Why Not Put Them in Git?​

Git is made for files that people write and edit, such as code. DVC's documentation describes what it adds as "data versioning – large files that should not be stored in a Git repository, but still need to be tracked and versioned." The trick is to give Git something small instead: "DVC metafiles such as dvc.yaml and .dvc files serve as placeholders to version data and ML pipelines. These files change along with your data, and you can use Git to place them under version control as a proxy to the actual data, which is stored in a cache (outside of Git)."

How DVC Versions Them​

  1. dvc add works out the file's MD5 hash, a 32-character fingerprint of its contents, and copies the file into DVC's cache, a folder that Git ignores.
  2. It also writes a small .dvc file next to the data, with that hash in it. That's what Git commits.
  3. dvc push copies the cache to a remote, a storage place outside the project. dvc pull brings it back in another copy of the project.
  4. To go back to an earlier version, git checkout brings back that commit's .dvc files, and dvc checkout puts the matching data in place.

So each tool keeps what it's good at:

WhatKept byWhere
Code, settings, uv.lock, metrics.jsonGitThe repository
The .dvc files: hash, size and pathGitNext to the data they describe
The data and the model themselvesDVCThe cache, .dvc/cache, and the remote

Versions Used​

ToolVersion
Python3.15.2
uv0.13.10
DVC3.67.1
scikit-learn1.9.1
pandas3.1.1
skops0.16.0
Git2.56.1

What This Part Costs​

Nothing. DVC is free, open-source software, and the remote in this part is a folder on your own computer. DVC can also keep its data in cloud storage, which its provider charges for; this series doesn't need any.

Prerequisites​

  • The project from Part 1, dewiride-bike-demand-forecast, with the data downloaded and the model trained. Part 1 builds it.
  • An internet connection, to install DVC.

Run every command in the project folder unless a step says otherwise. Every command works the same in Terminal (macOS), PowerShell (Windows) and Linux shells, unless a step shows a tab for each.

Step 1: Add DVC to the Project​

DVC is a Python package with a command-line tool, dvc. Add it to the project as a development dependency:

Terminal
uv add --dev dvc
Output (first lines)
Resolved 108 packages in 6.79s
Built antlr4-python3-runtime==4.9.3
Built bike-demand-forecast @ file:///Users/you/source/dewiride-bike-demand-forecast
Prepared 87 packages in 1.88s
Uninstalled 1 package in 2ms
Installed 87 packages in 74ms

The terminal after uv add --dev dvc: uv resolved 108 packages, built two of them, prepared 87 and installed 87, before its list of installed packages.

Then uv lists the 87 packages it installed, one per line: DVC itself, + dvc==3.67.1, 85 more packages that DVC needs, and the project again, marked ~, because pyproject.toml changed. uv.lock now pins all 108 packages of the project.

--dev puts DVC in the project's development group: tools for working on the project that its own code never imports. uv added this to the end of pyproject.toml:

pyproject.toml (added at the end by uv)
[dependency-groups]
dev = [
"dvc>=3.67.1",
]

uv's dependencies documentation says development dependencies "are local-only and will not be included in the project requirements when published to PyPI or other indexes", and that "the dev group is synced by default". So every copy of the project gets DVC with uv sync, as Step 8 shows. How to Install DVC with uv compares this with installing DVC once for all your projects.

DVC is installed inside the project's .venv, so you run it through uv, as uv run dvc, the same way uv run train runs the training command.

A known advisory in one of DVC's packages

One package DVC needs, diskcache 5.6.3, has a published security advisory with no fixed version yet, CVE-2025-69872: "An attacker with write access to the cache directory can achieve arbitrary code execution when a victim application reads from the cache." In treeverse/dvc#11068, a DVC maintainer explains that for DVC the risk is on Linux, where DVC keeps part of its cache in a folder every user of the computer can write to, and that other systems aren't affected. Until a DVC release fixes it, run DVC on a computer only you use, as this series does. The series moves to that release when it ships.

Step 2: Turn Off DVC's Usage Analytics​

DVC reports how it's used to its developers unless you turn that off. Its usage analytics page says: "To help us better understand how DVC is used and improve it, DVC captures and reports anonymized usage statistics." Each report holds things like the DVC version, your operating system, the command you ran and a random user ID, not your data. Turn it off for every project on your computer:

Terminal
uv run dvc config --global core.analytics false

It prints nothing. --global saves the setting in your user account's DVC settings file, not in this project, so every DVC project you open gets it. Check it:

Terminal
uv run dvc config --global --list
Output
core.analytics=false

Then check that DVC runs, and which version you have:

Terminal
uv run dvc --version
Output
3.67.1

The terminal after turning analytics off: dvc config --global --list prints core.analytics=false, and dvc --version prints 3.67.1.

How to Turn Off DVC Usage Analytics shows the other ways to turn it off, and how to see that DVC has.

Step 3: Initialize DVC​

dvc init turns the Git repository into a DVC project as well:

Terminal
uv run dvc init
Output
Initialized DVC repository.

You can now commit the changes to git.

What's next?
------------
- Check out the documentation: <https://dvc.org/doc>
- Get help and share ideas: <https://dvc.org/chat>
- Star us on GitHub: <https://github.com/treeverse/dvc>

The terminal after uv run dvc init: Initialized DVC repository, You can now commit the changes to git, and links to the documentation, the chat and GitHub.

Analytics is already off, so DVC skipped the notice about it that it prints the first time otherwise. dvc init created three files:

FileWhat it's for
.dvc/configDVC's settings for this project, empty for now
.dvc/.gitignoreKeeps DVC's own files, such as its cache, out of Git
.dvcignorePatterns for files DVC should skip, like .gitignore for Git

How to Initialize DVC in a Git Repository with dvc init goes through each of them. Ask Git what changed:

Terminal
git status
Output
On branch main
Changes to be committed:
(use "git restore --staged <file>..." to unstage)
new file: .dvc/.gitignore
new file: .dvc/config
new file: .dvcignore

Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git restore <file>..." to discard changes in working directory)
modified: pyproject.toml
modified: uv.lock

DVC already staged its three files for the next commit. pyproject.toml and uv.lock changed in Step 1, so stage them too, then commit:

Terminal
git add pyproject.toml uv.lock
git commit -m "Add DVC to the project"
Output
[main 134e8ba] Add DVC to the project
5 files changed, 1382 insertions(+), 26 deletions(-)
create mode 100644 .dvc/.gitignore
create mode 100644 .dvc/config
create mode 100644 .dvcignore

The terminal after git status lists the three new DVC files as staged and pyproject.toml and uv.lock as modified, and git add and git commit save commit 134e8ba with 5 files changed.

Step 4: Save the Training and Test Sets as Files​

DVC versions files. In Part 1, train split the data in memory, so the training set and the test set never existed as files, and there's nothing to version. A new prepare command will split the data and save both sets, and train will read them. That also gets the project ready for Part 3, where each step of training becomes a stage with its own input and output files.

First, give the two files a fixed place. Add three lines to data.py, below RAW_DIR:

src/bike_demand_forecast/data.py (add below RAW_DIR)
PREPARED_DIR = Path("data/prepared")
TRAIN_FILE = PREPARED_DIR / "train.csv"
TEST_FILE = PREPARED_DIR / "test.csv"

The / joins paths, so TRAIN_FILE is data/prepared/train.csv. The complete file:

src/bike_demand_forecast/data.py
"""Load the hourly rentals and split them into a training period and a test period."""

from datetime import date
from pathlib import Path

import pandas as pd

RAW_DIR = Path("data/raw")
PREPARED_DIR = Path("data/prepared")
TRAIN_FILE = PREPARED_DIR / "train.csv"
TEST_FILE = PREPARED_DIR / "test.csv"
TARGET = "cnt"

# The columns the model learns from. Left out: instant (a row number), dteday (used
# only to split), yr (which year it is), and casual and registered, which add up to
# cnt and would give the answer away.
FEATURES = [
"season",
"mnth",
"hr",
"holiday",
"weekday",
"workingday",
"weathersit",
"temp",
"atemp",
"hum",
"windspeed",
]


def load_rentals(path: Path) -> pd.DataFrame:
"""Read the hourly CSV file, with dteday as a real date."""
return pd.read_csv(path, parse_dates=["dteday"])


def split_by_date(
rentals: pd.DataFrame, train_end: date, test_end: date
) -> tuple[pd.DataFrame, pd.DataFrame]:
"""Train on the hours up to train_end; test on the hours after it, to test_end."""
day = rentals["dteday"]
train = rentals[day <= pd.Timestamp(train_end)]
test = rentals[(day > pd.Timestamp(train_end)) & (day <= pd.Timestamp(test_end))]
return train, test

Now create prepare.py in the same folder. It starts with the imports it needs and a logger:

src/bike_demand_forecast/prepare.py (the start)
"""Split the hourly rentals by date and save the training and test sets as CSV files."""

import logging

from bike_demand_forecast.data import (
PREPARED_DIR,
RAW_DIR,
TEST_FILE,
TRAIN_FILE,
load_rentals,
split_by_date,
)
from bike_demand_forecast.params import load_params

log = logging.getLogger(__name__)

It reuses Part 1's load_rentals and split_by_date, and the new paths. Its main function starts with the lines that used to be in train.py: read params.yaml, load hour.csv and split it by date:

src/bike_demand_forecast/prepare.py (add at the end)
def main() -> None:
logging.basicConfig(
level=logging.INFO, format="%(levelname)s %(name)s: %(message)s"
)
params = load_params()

rentals = load_rentals(RAW_DIR / params.data.file)
train, test = split_by_date(rentals, params.split.train_end, params.split.test_end)

Then it saves the two sets:

src/bike_demand_forecast/prepare.py (add inside main)
PREPARED_DIR.mkdir(parents=True, exist_ok=True)
# "\n" on every system, so the files are byte for byte the same on Windows too.
train.to_csv(TRAIN_FILE, index=False, lineterminator="\n")
test.to_csv(TEST_FILE, index=False, lineterminator="\n")
log.info("Saved %d training hours to %s", len(train), TRAIN_FILE.as_posix())
log.info("Saved %d test hours to %s", len(test), TEST_FILE.as_posix())
  • mkdir(parents=True, exist_ok=True) creates data/prepared, and data too if it's missing, and doesn't fail when they already exist.
  • index=False leaves out the row numbers pandas would add as a first column, so each file has only the data's own columns.
  • lineterminator="\n" ends every row with the same character on every system. The pandas documentation says the default "depends on the OS in which this method is called ('\n' for linux, '\r\n' for Windows, i.e.)". Without it, the same data saved on Windows would be a different file, with a different hash, and DVC would see a new version.
  • as_posix() writes the path with forward slashes on every system, so the log lines are the same on Windows.

The complete file:

src/bike_demand_forecast/prepare.py
"""Split the hourly rentals by date and save the training and test sets as CSV files."""

import logging

from bike_demand_forecast.data import (
PREPARED_DIR,
RAW_DIR,
TEST_FILE,
TRAIN_FILE,
load_rentals,
split_by_date,
)
from bike_demand_forecast.params import load_params

log = logging.getLogger(__name__)


def main() -> None:
logging.basicConfig(
level=logging.INFO, format="%(levelname)s %(name)s: %(message)s"
)
params = load_params()

rentals = load_rentals(RAW_DIR / params.data.file)
train, test = split_by_date(rentals, params.split.train_end, params.split.test_end)

PREPARED_DIR.mkdir(parents=True, exist_ok=True)
# "\n" on every system, so the files are byte for byte the same on Windows too.
train.to_csv(TRAIN_FILE, index=False, lineterminator="\n")
test.to_csv(TEST_FILE, index=False, lineterminator="\n")
log.info("Saved %d training hours to %s", len(train), TRAIN_FILE.as_posix())
log.info("Saved %d test hours to %s", len(test), TEST_FILE.as_posix())

The complete prepare.py in a macOS-style code window: the imports, a logger, and a main function that loads the settings and hour.csv, splits the rentals by date, and saves train.csv and test.csv with index=False and lineterminator set to a line feed.

train.py no longer splits the data. It reads the two files instead. These are the changes, with - for a removed line and + for a new one:

src/bike_demand_forecast/train.py (the changes)
from bike_demand_forecast.data import (
FEATURES,
- RAW_DIR,
TARGET,
+ TEST_FILE,
+ TRAIN_FILE,
load_rentals,
- split_by_date,
)

- rentals = load_rentals(RAW_DIR / params.data.file)
- train, test = split_by_date(rentals, params.split.train_end, params.split.test_end)
+ train = load_rentals(TRAIN_FILE)
+ test = load_rentals(TEST_FILE)

The complete file:

src/bike_demand_forecast/train.py
"""Train the demand model on the training period and score it on the test period."""

import json
import logging
from pathlib import Path

import skops.io as sio
from sklearn.ensemble import HistGradientBoostingRegressor
from sklearn.metrics import mean_absolute_error, r2_score, root_mean_squared_error

from bike_demand_forecast.data import (
FEATURES,
TARGET,
TEST_FILE,
TRAIN_FILE,
load_rentals,
)
from bike_demand_forecast.params import load_params

MODEL_FILE = Path("models/model.skops")
METRICS_FILE = Path("metrics.json")

log = logging.getLogger(__name__)


def main() -> None:
logging.basicConfig(
level=logging.INFO, format="%(levelname)s %(name)s: %(message)s"
)
params = load_params()

train = load_rentals(TRAIN_FILE)
test = load_rentals(TEST_FILE)
log.info("Training on %d hours, testing on %d hours", len(train), len(test))

model = HistGradientBoostingRegressor(**params.model.model_dump())
model.fit(train[FEATURES], train[TARGET])
predicted = model.predict(test[FEATURES])

metrics = {
"mae": round(mean_absolute_error(test[TARGET], predicted), 4),
"rmse": round(root_mean_squared_error(test[TARGET], predicted), 4),
"r2": round(r2_score(test[TARGET], predicted), 4),
}
MODEL_FILE.parent.mkdir(parents=True, exist_ok=True)
sio.dump(model, MODEL_FILE)
METRICS_FILE.write_text(json.dumps(metrics, indent=2) + "\n")
log.info("Saved %s and %s", MODEL_FILE.as_posix(), METRICS_FILE)
log.info("Test MAE %.2f, RMSE %.2f, R2 %.4f", *metrics.values())

Last, register the new command in pyproject.toml, between the other two:

pyproject.toml ([project.scripts])
[project.scripts]
download = "bike_demand_forecast.download:main"
prepare = "bike_demand_forecast.prepare:main"
train = "bike_demand_forecast.train:main"

Run the two commands:

Terminal
uv run prepare
Output
Built bike-demand-forecast @ file:///Users/you/source/dewiride-bike-demand-forecast
Uninstalled 1 package in 1ms
Installed 1 package in 3ms
INFO bike_demand_forecast.prepare: Saved 7185 training hours to data/prepared/train.csv
INFO bike_demand_forecast.prepare: Saved 1460 test hours to data/prepared/test.csv
Terminal
uv run train
Output
INFO bike_demand_forecast.train: Training on 7185 hours, testing on 1460 hours
INFO bike_demand_forecast.train: Saved models/model.skops and metrics.json
INFO bike_demand_forecast.train: Test MAE 32.56, RMSE 51.77, R2 0.8011

uv rebuilt the project first, because pyproject.toml changed. Then prepare saved the same split as Part 1, 7,185 training hours and 1,460 test hours, and train got the same scores from the two files. Look at the start of the training file:

Terminal
head -n 3 data/prepared/train.csv
Output
instant,dteday,season,yr,mnth,hr,holiday,weekday,workingday,weathersit,temp,atemp,hum,windspeed,casual,registered,cnt
1,2011-01-01,1,0,1,0,0,6,0,1,0.24,0.2879,0.81,0.0,3,13,16
2,2011-01-01,1,0,1,1,0,6,0,1,0.22,0.2727,0.8,0.0,8,32,40

Both shells print the same three lines: the same columns and rows as hour.csv. One value looks different: the wind speed is 0.0 where hour.csv has 0. pandas reads that column as decimal numbers and writes them back that way, so the prepared files are pandas' own output, not copies. Commit the code:

Terminal
git add pyproject.toml src
git commit -m "Save the training and test sets as files"
Output
[main 20749ba] Save the training and test sets as files
4 files changed, 40 insertions(+), 4 deletions(-)
create mode 100644 src/bike_demand_forecast/prepare.py

The terminal after uv run prepare saves 7,185 training hours and 1,460 test hours, uv run train reports MAE 32.56, RMSE 51.77 and R2 0.8011, head shows the first three lines of train.csv, and git commit saves commit 20749ba with 4 files changed.

Step 5: Track the Data and the Model with dvc add​

A model version is made of three things: the raw data, the prepared sets and the model itself. dvc add takes files and folders, so track all three at once:

Terminal
uv run dvc add data/raw/hour.csv data/prepared models/model.skops
Output
ERROR: bad DVC file name 'data/raw/hour.csv.dvc' is git-ignored.

DVC refused. For data/raw/hour.csv, it writes its record to data/raw/hour.csv.dvc, inside data/, and Part 1's .gitignore ignores all of data/ and models/. Git could never commit the .dvc files, so DVC won't create them. Ask Git which rule ignores each one:

Terminal
git check-ignore -v data/raw/hour.csv.dvc data/prepared.dvc models/model.skops.dvc
Output
.gitignore:13:/data/ data/raw/hour.csv.dvc
.gitignore:13:/data/ data/prepared.dvc
.gitignore:14:/models/ models/model.skops.dvc

The terminal after dvc add fails with ERROR: bad DVC file name 'data/raw/hour.csv.dvc' is git-ignored, and git check-ignore -v shows that lines 13 and 14 of .gitignore, /data/ and /models/, ignore the three .dvc files.

Each line names the file and line of the rule, the rule, and the path it ignores: lines 13 and 14 of .gitignore, the two rules Part 1 added. How to See Why Git Ignores a File with git check-ignore explains the format, and Fixed: "bad DVC file name '…' is git-ignored" When You Run dvc add covers this error in detail.

Git no longer needs those rules: dvc add writes its own, which ignore only the data files themselves. Open .gitignore and delete these three lines from its end, with the empty line above them:

.gitignore (delete these lines)
# Data and models: the pipeline downloads and creates them
/data/
/models/

The file is now back to what uv created:

.gitignore
# Python-generated files
__pycache__/
*.py[oc]
build/
dist/
wheels/
*.egg-info

# Virtual environments
.venv

Run the same dvc add again:

Terminal
uv run dvc add data/raw/hour.csv data/prepared models/model.skops
Output
100% Adding...|███████████████████████████████████████████████████████████|3/3 [00:00, 21.54file/s]

To track the changes with git, run:

git add data/raw/hour.csv.dvc models/.gitignore data/.gitignore data/prepared.dvc data/raw/.gitignore models/model.skops.dvc

To enable auto staging, run:

dvc config core.autostage true

DVC added all three and names the files to give Git. Plain git status shows only data/ and models/ as new folders; --untracked-files=all lists the files inside them:

Terminal
git status --short --untracked-files=all
Output
M .gitignore
?? data/.gitignore
?? data/prepared.dvc
?? data/raw/.gitignore
?? data/raw/hour.csv.dvc
?? models/.gitignore
?? models/model.skops.dvc

M is the .gitignore you changed, and ?? marks the six new files: a .dvc file and a .gitignore for each thing you added. Here is the .dvc file of the raw data:

data/raw/hour.csv.dvc
outs:
- md5: d50bd5a6f55131e72a7bedc334e2fce1
size: 1156736
hash: md5
path: hour.csv

That's all Git will ever store about hour.csv. DVC's .dvc files page describes each field:

FieldWhat it holds
md5The file's hash: which version of the data this commit has
size"Size of the file or directory (sum of all files)", in bytes
hash"Hash algorithm for the file or directory being tracked with DVC"
pathThe file, relative to the .dvc file

The folder gets one .dvc file for both of its files. Its hash ends in .dir, and nfiles counts the files inside:

data/prepared.dvc
outs:
- md5: 7d360b7bd536de5646397183ab4f6454.dir
size: 562860
nfiles: 2
hash: md5
path: prepared

The new data/raw/.gitignore holds one line, /hour.csv: Git ignores the data file, and only it. How to Track a Large File with dvc add and How to Track a Folder with dvc add show both cases step by step. Commit the seven files:

Terminal
git add .gitignore data/raw/hour.csv.dvc data/raw/.gitignore data/prepared.dvc data/.gitignore models/model.skops.dvc models/.gitignore
git commit -m "Track the data and the model with DVC"
Output
[main 63091bd] Track the data and the model with DVC
7 files changed, 19 insertions(+), 4 deletions(-)
create mode 100644 data/.gitignore
create mode 100644 data/prepared.dvc
create mode 100644 data/raw/.gitignore
create mode 100644 data/raw/hour.csv.dvc
create mode 100644 models/.gitignore
create mode 100644 models/model.skops.dvc

The terminal after the second dvc add tracks all three, git status lists the changed .gitignore and six new files, and git commit saves commit 63091bd with 7 files changed.

From this commit on, the project's history says exactly which data and which model go with the code.

Step 6: Look Inside the DVC Cache​

dvc add also copied each file into DVC's cache, in .dvc/cache. List the files in it:

Terminal
find .dvc/cache -type f
Output
.dvc/cache/files/md5/0d/54c8f60b3f6c40bce5e52814297c28
.dvc/cache/files/md5/56/acf5dbde4f7936542f98d5eb318043
.dvc/cache/files/md5/f5/9fe3941b6a4e6b18ccb5bb4cf1842e
.dvc/cache/files/md5/7d/360b7bd536de5646397183ab4f6454.dir
.dvc/cache/files/md5/d5/0bd5a6f55131e72a7bedc334e2fce1

Five files: one for each of the four files DVC tracks, hour.csv, train.csv, test.csv and model.skops, and one ending in .dir for the folder. None has its old name. DVC's internal files page explains: "DVC calculates the file hash, a 32 characters long string (usually MD5). The first two characters are used to name the directory inside the cache, and the rest become the file name of the cached file."

On your computer, the hashes of hour.csv, train.csv, test.csv and the .dir file are the same as these: the same data and the same code give the same bytes. The model's isn't. skops writes a slightly different file every time it saves a model, even the same model, so its cache file has another name for you. Step 9 shows what that means for DVC.

Check it on hour.csv. Its hash in hour.csv.dvc is d50bd5a6…, so its copy should be d5/0bd5a6f55131e72a7bedc334e2fce1. Work out the hash yourself:

Terminal
md5sum data/raw/hour.csv
Output
d50bd5a6f55131e72a7bedc334e2fce1 data/raw/hour.csv

On a Mac where md5sum isn't found, md5 data/raw/hour.csv prints the same hash in another layout.

The same hash: the cache holds hour.csv under its fingerprint. The .dir file is the folder's list of contents:

Terminal
cat .dvc/cache/files/md5/7d/360b7bd536de5646397183ab4f6454.dir
Output
[{"md5": "f59fe3941b6a4e6b18ccb5bb4cf1842e", "relpath": "test.csv"}, {"md5": "56acf5dbde4f7936542f98d5eb318043", "relpath": "train.csv"}]

The terminal after find lists the five files in .dvc/cache, md5sum prints hour.csv's hash d50bd5a6f55131e72a7bedc334e2fce1, and cat shows the .dir file listing test.csv and train.csv with their hashes.

It names each file in data/prepared and its hash, so DVC can rebuild the folder from the cache. cat works in PowerShell too. Because files are named by their contents, the same page adds that two files with the same contents are stored once: "only one copy is stored in the cache. This helps avoid data duplication." How to Find a DVC-Tracked File in the DVC Cache goes further.

Step 7: Store the Data in a Remote​

The cache lives inside the project folder, and .dvc/.gitignore keeps it out of Git. So a clone gets the .dvc files, but none of the data. A DVC remote fixes that: a storage place outside the project that every copy of it can upload to and download from. The dvc remote add reference says remotes "can point to a cloud storage service, an SSH server, network-attached storage, or even a directory in the local file system." This series uses a folder next to the project, which costs nothing:

Terminal
uv run dvc remote add -d storage ../bike-demand-storage
Output
Setting 'storage' as a default remote.
  • storage is the remote's name.
  • -d makes it the default remote, so dvc push and dvc pull use it without being told.
  • ../bike-demand-storage is a folder next to the project folder. DVC creates it on the first push.

See where DVC saved it:

Terminal
cat .dvc/config
Output
[core]
remote = storage
['remote "storage"']
url = ../../bike-demand-storage

The path became ../../bike-demand-storage. That's the same folder, written from .dvc/, where the config file is. DVC's remote storage guide says: "When using a relative path, it will be saved relative to the config file location, but resolved against the current working directory." The guide recommends an absolute path instead, "because it's saved as-is in DVC config". This project uses a relative one on purpose: .dvc/config is committed, and an absolute path would put your own folder names, like /Users/you, into Git and work only where that exact path exists. The relative path works for every copy of the project that sits next to bike-demand-storage, like the one in Step 8.

Upload the cache:

Terminal
uv run dvc push
Output
Collecting |5.00 [00:00, 909entry/s]
Pushing
5 files pushed

The five files of the cache are now in the remote too, in the same layout:

Terminal
find ../bike-demand-storage -type f
Output
../bike-demand-storage/files/md5/0d/54c8f60b3f6c40bce5e52814297c28
../bike-demand-storage/files/md5/56/acf5dbde4f7936542f98d5eb318043
../bike-demand-storage/files/md5/f5/9fe3941b6a4e6b18ccb5bb4cf1842e
../bike-demand-storage/files/md5/7d/360b7bd536de5646397183ab4f6454.dir
../bike-demand-storage/files/md5/d5/0bd5a6f55131e72a7bedc334e2fce1

The remote setting changed .dvc/config, so commit it, and every clone knows where the data is:

Terminal
git status --short
Output
M .dvc/config
Terminal
git add .dvc/config
git commit -m "Store DVC data in a folder next to the project"
Output
[main 8a4ffc1] Store DVC data in a folder next to the project
1 file changed, 4 insertions(+)

The terminal after dvc remote add sets storage as the default remote, cat shows url = ../../bike-demand-storage in .dvc/config, dvc push uploads 5 files, find lists them in ../bike-demand-storage, and git commit saves commit 8a4ffc1.

How to Use a Local Folder as a DVC Remote and How to Upload Data to a DVC Remote with dvc push cover both commands, including absolute paths and the errors you can meet.

Step 8: Get Everything Back in a Fresh Clone​

This is the test of Steps 5 to 7: does a new copy of the project get the data and the model back? Clone the project into a folder next to it, as in Part 1:

Terminal
cd ..
git clone dewiride-bike-demand-forecast bike-demand-check
cd bike-demand-check
Output
Cloning into 'bike-demand-check'...
done.

The clone has the .dvc files from Git, but not the data or the model: Git never had them. How to Clone a Local Git Repository into Another Folder explains the command. Install the locked packages:

Terminal
uv sync --locked
Output (first lines)
Using CPython 3.15.2 interpreter at: /Library/Frameworks/Python.framework/Versions/3.15/bin/python3.15
Creating virtual environment at: .venv
Resolved 108 packages in 8ms
Built bike-demand-forecast @ file:///Users/you/source/bike-demand-check
Built antlr4-python3-runtime==4.9.3
Prepared 47 packages in 1.38s
Installed 107 packages in 391ms

The terminal after git clone copies the project into bike-demand-check and uv sync --locked creates a virtual environment and installs 107 packages.

107 packages, DVC among them: the dev group is installed by default. Now get the data:

Terminal
uv run dvc pull
Output
Collecting |5.00 [00:00, 934entry/s]
Fetching
Building workspace index |3.00 [00:00, 601entry/s]
Comparing indexes |9.00 [00:00, 3.05kentry/s]
Applying changes |4.00 [00:00, 2.17kfile/s]
A data/prepared/
A data/raw/hour.csv
A models/model.skops
5 files fetched and 4 files added

The dvc pull reference says it "downloads tracked data from a dvc remote to the cache, and links (or copies) the files or directories to the workspace". That's the last line: 5 files fetched from the remote into the clone's cache, and 4 files added to the project. A marks what was added: the data/prepared/ folder with its two files, hour.csv and the model. Ask DVC whether everything matches the .dvc files:

Terminal
uv run dvc status
Output
Data and pipelines are up to date.

Then check two of the files yourself, by their hashes:

Terminal
md5sum models/model.skops data/raw/hour.csv
Output
0d54c8f60b3f6c40bce5e52814297c28 models/model.skops
d50bd5a6f55131e72a7bedc334e2fce1 data/raw/hour.csv

The clone's terminal after dvc pull fetches 5 files and adds 4, dvc status says Data and pipelines are up to date, and md5sum prints the model's hash 0d54c8f60b3f6c40bce5e52814297c28 and hour.csv's hash d50bd5a6f55131e72a7bedc334e2fce1.

The same hashes as in models/model.skops.dvc and data/raw/hour.csv.dvc: the clone has exactly the committed model and data, without training anything. How to Download DVC Data After Cloning with dvc pull and How to See Which DVC-Tracked Files Changed with dvc status cover these two commands.

Step 9: Retrain in the Clone and See What DVC Reports​

Part 1 showed that training again gives the same scores. Do it in the clone, with the same code, data and settings, and see what DVC thinks:

Terminal
uv run train
Output
INFO bike_demand_forecast.train: Training on 7185 hours, testing on 1460 hours
INFO bike_demand_forecast.train: Saved models/model.skops and metrics.json
INFO bike_demand_forecast.train: Test MAE 32.56, RMSE 51.77, R2 0.8011
Terminal
uv run dvc status
Output
models/model.skops.dvc:
changed outs:
modified: models/model.skops

The same scores, but DVC says the model changed. Git sees no change, because metrics.json is the same and Git doesn't track the model:

Terminal
git status --short

It prints nothing. dvc diff compares the project with the last commit and names the file:

Terminal
uv run dvc diff
Output
Modified:
models/model.skops

files summary: 1 modified

The clone's terminal after uv run train reports the same scores, dvc status says models/model.skops is modified, git status --short prints nothing, and dvc diff reports 1 modified file.

DVC compares hashes, not models. The dvc status reference says modified means the file "is found in the workspace, but the corresponding file hash in the dvc.lock or .dvc file is not up to date." And the same model saved twice gives two different files: skops writes Python object ids and the time of saving into each one, as Part 1's note said. Why a skops File Changes Every Time You Save the Same Model shows it, and I reported it to the skops project as skops-dev/skops#574. Fixed: dvc status Says a Model Is "modified" After Retraining with the Same Data proves that the retrained model makes the same predictions.

The clone should keep the committed model, so put it back with dvc checkout, which restores files from the cache:

Terminal
uv run dvc checkout models/model.skops
Output
Building workspace index |2.00 [00:00, 462entry/s]
Comparing indexes |3.00 [00:00, 2.70kentry/s]
ERROR: Can't remove the following unsaved files without confirmation. Use `--force` to force.
/Users/you/source/bike-demand-check/models/model.skops

DVC stopped. The retrained file isn't in the cache, so replacing it would lose it for good, and DVC wants you to confirm that. Nothing changed: uv run dvc status still reports the model as modified. Fixed: "Can't remove the following unsaved files without confirmation" in dvc checkout covers this error. Here the retrained file isn't needed, so confirm with --force:

Terminal
uv run dvc checkout --force models/model.skops
Output
Building workspace index |2.00 [00:00, 349entry/s]
Comparing indexes |3.00 [00:00, 3.01kentry/s]
Applying changes |1.00 [00:00, 1.24kfile/s]
M models/model.skops
Terminal
uv run dvc status
Output
Data and pipelines are up to date.

The clone's terminal after dvc checkout fails with Can't remove the following unsaved files without confirmation, dvc checkout --force replaces models/model.skops, and dvc status says Data and pipelines are up to date.

M means DVC modified models/model.skops: it's the committed model again. The lesson: judge a retrained model by its scores, as metrics.json does, and by its predictions. dvc status tells you a file's bytes changed, not whether the model did. When you do want to keep a new model, you save it as a new version, as the next step does.

Step 10: Save a New Version of the Data and the Model​

Go back to the main project:

Terminal
cd ../dewiride-bike-demand-forecast

In real use, new data keeps arriving, and the model is trained again on more of it. Do the same here: move the end of the training period from October to November, so the model learns from one more month. Change one line in params.yaml:

params.yaml (the change)
split:
- train_end: 2011-10-31 # the model learns from every hour up to this day
+ train_end: 2011-11-30 # the model learns from every hour up to this day
test_end: 2011-12-31 # and is scored on the hours after it, up to this day

Prepare the data and train again:

Terminal
uv run prepare
Output
INFO bike_demand_forecast.prepare: Saved 7904 training hours to data/prepared/train.csv
INFO bike_demand_forecast.prepare: Saved 741 test hours to data/prepared/test.csv
Terminal
uv run train
Output
INFO bike_demand_forecast.train: Training on 7904 hours, testing on 741 hours
INFO bike_demand_forecast.train: Saved models/model.skops and metrics.json
INFO bike_demand_forecast.train: Test MAE 31.41, RMSE 49.32, R2 0.7870

The model learned from 7,904 hours, January to November, and was tested on December's 741 hours. New data and a new test month give new scores; Part 3 compares the scores of two versions properly. Ask DVC what changed:

Terminal
uv run dvc status
Output
models/model.skops.dvc:
changed outs:
modified: models/model.skops
data/prepared.dvc:
changed outs:
modified: data/prepared
Terminal
uv run dvc diff
Output
Modified:
data/prepared/
data/prepared/test.csv
data/prepared/train.csv
models/model.skops

files summary: 3 modified

The terminal after uv run prepare saves 7,904 training hours and 741 test hours, uv run train reports MAE 31.41, RMSE 49.32 and R2 0.7870, dvc status shows the model and data/prepared as modified, and dvc diff lists the folder, its two files and the model.

Both prepared files and the model changed. dvc diff also lists the folder, data/prepared/, because its files changed; the summary counts only files, so it says 3. hour.csv didn't change, so it isn't listed. How to Compare Data Versions with dvc diff explains the output.

This time you want to keep the new version, so save it with dvc add, the same command as in Step 5:

Terminal
uv run dvc add data/prepared models/model.skops
Output
100% Adding...|███████████████████████████████████████████████████████████|2/2 [00:00, 71.16file/s]

To track the changes with git, run:

git add data/prepared.dvc models/model.skops.dvc

To enable auto staging, run:

dvc config core.autostage true

See what that did to a .dvc file:

Terminal
git diff models/model.skops.dvc
Output
diff --git a/models/model.skops.dvc b/models/model.skops.dvc
index 8b262e9..4c7c262 100644
--- a/models/model.skops.dvc
+++ b/models/model.skops.dvc
@@ -1,5 +1,5 @@
outs:
-- md5: 0d54c8f60b3f6c40bce5e52814297c28
- size: 2177170
+- md5: 4081ab0957d8a42c6b460b89a25562ce
+ size: 2177178
hash: md5
path: model.skops

Only the hash and the size changed. That's the whole new version, as far as Git is concerned. Commit it with the setting and the scores that go with it:

Terminal
git add params.yaml metrics.json data/prepared.dvc models/model.skops.dvc
git commit -m "Train on data up to the end of November"
Output
[main ea9dee7] Train on data up to the end of November
4 files changed, 7 insertions(+), 7 deletions(-)

And upload the new files to the remote:

Terminal
uv run dvc push
Output
Collecting |5.00 [00:00, 885entry/s]
Pushing
4 files pushed

The terminal after dvc add saves the new versions, git diff shows the new md5 and size in models/model.skops.dvc, git commit saves commit ea9dee7 with 4 files changed, and dvc push uploads 4 files.

4 files: the new model, the two new prepared files and the folder's new .dir list. hour.csv was already in the remote. Both versions are now in the cache and in the remote, side by side. How to Save a New Version of a DVC-Tracked File goes through this cycle on a small example.

Step 11: Go Back to the Earlier Version​

Here is the history so far:

Terminal
git log --oneline
Output
ea9dee7 (HEAD -> main) Train on data up to the end of November
8a4ffc1 Store DVC data in a folder next to the project
63091bd Track the data and the model with DVC
20749ba Save the training and test sets as files
134e8ba Add DVC to the project
d8022ef (tag: part-1) Set up a reproducible bike demand forecast project

Newest first, one commit per line. tag: part-1 is a label on my first commit; yours won't have it, and your hashes will be different. How to Show Git History One Line per Commit with git log --oneline explains this view.

Say you need the model from before the new month, to compare it or to find out why something changed. It's one commit back, HEAD~1. Check out that commit:

Terminal
git checkout HEAD~1
Output (last line)
HEAD is now at 8a4ffc1 Store DVC data in a folder next to the project

Git printed its note about a "detached HEAD" first: you're on an earlier commit, not on a branch. How to Check Out an Earlier Commit in Git explains it. Git brought back that commit's .dvc files, params.yaml and metrics.json, but not the data or the model, because Git doesn't have them. DVC does:

Terminal
uv run dvc checkout
Output
Building workspace index |9.00 [00:00, 909entry/s]
Comparing indexes |9.00 [00:00, 2.39kentry/s]
Applying changes |3.00 [00:00, 1.87kfile/s]
M data/prepared/
M models/model.skops

DVC replaced the prepared data and the model with the versions in the old .dvc files, from its cache. Check the scores and the size of the training set:

Terminal
cat metrics.json
Output
{
"mae": 32.5558,
"rmse": 51.7738,
"r2": 0.8011
}
Terminal
wc -l data/prepared/train.csv data/prepared/test.csv
Output
7186 data/prepared/train.csv
1461 data/prepared/test.csv
8647 total
Terminal
uv run dvc status
Output
Data and pipelines are up to date.

The terminal after git log --oneline lists six commits, git checkout HEAD~1 moves to 8a4ffc1, dvc checkout replaces data/prepared and the model, metrics.json shows MAE 32.5558, wc -l counts 7,186 and 1,461 lines, and dvc status says Data and pipelines are up to date.

This is the earlier version, complete: the scores of the October model, a training file of 7,186 lines, 7,185 hours plus the header row, and a test file of 1,461. dvc status confirms that the data and the model match this commit's .dvc files. Now return to the newest version, the same way:

Terminal
git checkout main
Output
Previous HEAD position was 8a4ffc1 Store DVC data in a folder next to the project
Switched to branch 'main'
Terminal
uv run dvc checkout
Output
Building workspace index |9.00 [00:00, 612entry/s]
Comparing indexes |9.00 [00:00, 2.41kentry/s]
Applying changes |3.00 [00:00, 1.98kfile/s]
M data/prepared/
M models/model.skops
Terminal
cat metrics.json
Output
{
"mae": 31.4083,
"rmse": 49.3242,
"r2": 0.787
}
Terminal
wc -l data/prepared/train.csv data/prepared/test.csv
Output
7905 data/prepared/train.csv
742 data/prepared/test.csv
8647 total

The terminal after git checkout main switches back to the main branch, dvc checkout replaces data/prepared and the model again, metrics.json shows MAE 31.4083, and wc -l counts 7,905 and 742 lines.

The November model and its data are back. git switch main does the same as git checkout main here. How to Go Back to an Earlier Version of Your Data with dvc checkout shows this pair of commands on a small example.

Always run them as a pair

After every git checkout, run uv run dvc checkout. Without it, the .dvc files describe one version while data/ and models/ still hold another, and dvc status reports the files as modified.

Your Project Now Looks Like This​

dewiride-bike-demand-forecast/
dewiride-bike-demand-forecast/
├── .dvc/
│ ├── .gitignore keeps cache/ and tmp/ out of Git
│ ├── cache/ every saved version, named by hash (ignored)
│ ├── config the default remote, storage
│ └── tmp/ DVC's working files (ignored)
├── .dvcignore
├── .git/
├── .gitignore no longer ignores data/ and models/
├── .python-version
├── .venv/
├── README.md
├── data/
│ ├── .gitignore ignores prepared/
│ ├── prepared/ train.csv and test.csv (DVC)
│ ├── prepared.dvc which version of prepared/ this commit has
│ └── raw/
│ ├── .gitignore ignores hour.csv
│ ├── hour.csv (DVC)
│ └── hour.csv.dvc
├── metrics.json
├── models/
│ ├── .gitignore ignores model.skops
│ ├── model.skops (DVC)
│ └── model.skops.dvc
├── params.yaml train_end: 2011-11-30
├── pyproject.toml DVC in the dev group, and the prepare command
├── src/
│ └── bike_demand_forecast/
│ ├── __init__.py
│ ├── data.py paths, load and split by date
│ ├── download.py
│ ├── params.py
│ ├── prepare.py split and save the two sets
│ └── train.py train on the saved sets
└── uv.lock

Next to it, bike-demand-storage/ holds the remote: every version you pushed.

Clean Up the Check Folder​

The clone was only for the check. Go back to the folder that holds the projects and delete it:

Terminal
cd ..
rm -rf bike-demand-check

Keep dewiride-bike-demand-forecast, and keep bike-demand-storage: it's the project's remote, and the later parts use it. Nothing runs in the background, so there's nothing to stop.

Common Mistakes​

MistakeWhat happensDo this instead
Ignoring the whole data/ or models/ folder in .gitignoredvc add stops with ERROR: bad DVC file name '…' is git-ignored.Remove those rules; dvc add writes a .gitignore that ignores only the data files
Running dvc instead of uv run dvczsh: command not found: dvcDVC is in the project's .venv: run uv run dvc
Committing without the files dvc add namesThe data changed, but no commit records the new versiongit add every file in the line dvc add prints
Forgetting uv run dvc pushA clone's dvc pull fails with failed to pull data from the cloudPush after every commit that changes a .dvc file
Running only git checkoutThe .dvc files are old, but the data is still the newest, and dvc status says modifiedRun uv run dvc checkout after every git checkout
Taking modified after a retrain as a new modelEvery skops save gives a new file, so the hash changes even when the model doesn'tJudge a model by its scores, and save a new version only when you mean to keep it

Troubleshooting​

SymptomLikely causeFix
ERROR: bad DVC file name '…' is git-ignored.A .gitignore rule covers the folder the .dvc file goes inRemove the rule, as in Step 5; the fixes post explains it
ERROR: Can't remove the following unsaved files without confirmation.The file DVC would replace isn't in the cacheKeep a copy if you need the file, then add --force; see the fixes post
dvc status says the model is modified right after training with the same dataskops saved the same model as a different fileCompare the predictions; the fixes post shows how
ERROR: failed to pull data from the cloud - Checkout failed for following targets:The data was committed but never pushedRun uv run dvc push in the original project, then pull again
zsh: command not found: dvcDVC is only in the project's .venvRun uv run dvc from the project folder

FAQ​

Does Git store the data now?​

No. Git stores the .dvc files, a few lines each with the hash, the size and the path. The data and the model themselves are in DVC's cache and in the remote.

Why DVC and not Git LFS?​

DVC's documentation compares the two: "DVC does not require special servers like Git-LFS demands. Any cloud storage like S3, Google Cloud Storage, or even an SSH server can be used as a remote storage." It adds that "Git-LFS was not made with data science in mind, so it doesn't provide related features (e.g. ML pipelines, metrics, etc.)." The next part uses those pipelines.

Does DVC send my data anywhere?​

In this part, only dvc push copies your data, and only to the remote you added: a folder on your own computer. The usage analytics from Step 2 never contain your files, and they're off.

Can the remote be cloud storage?​

Yes. The same dvc remote add takes a cloud storage address. DVC's installation guide for macOS lists extras for cloud storage, such as dvc[s3], that add the packages each kind needs. Storage on your own disk needs no extra.

Conclusion​

The project now versions everything a model is made of. Git holds the code, the settings, the scores and three small .dvc files; DVC holds the raw data, the prepared sets and the model, in its cache and in a remote folder next to the project. A fresh clone got the exact committed data and model back with dvc pull, without training. Retraining with the same inputs showed that DVC compares files, not models. A new month of training data became a new version with dvc add, and git checkout plus dvc checkout brought the earlier version back, scores, data and model, and then the newest one again.

In Part 3 you'll turn download, prepare and train into a DVC pipeline that knows which steps to rerun when something changes.

Additional Resources​


← Previous: Part 1: Set Up a Reproducible Machine Learning Project

Next → Part 3: Build a Reproducible Training Pipeline with DVC (coming soon)