Level 3 In-Depth AI · ML Engineering and Production
Data Pipelines and Datasets
The machinery that turns raw data into a trustworthy training set, again and again. Collecting, labelling, validating, splitting, versioning and documenting data, and feeding it to training at speed.
- Level
- ●●●●● Easy
- Reading
- 12 min
- To learn it well
- 45 minutes to read, an afternoon to practise
- Builds on
- 3 concepts →
- Quiz
- 5 questions ↓
Read first
Data Cleaning and PreparationThis leads to
Synthetic DataThe full path from zero — 3 concepts before this one
- Python for AI
- Pandas and Working with Data
- Data Cleaning and Preparation
- Data Pipelines and Datasets
Read them roughly in this order. See it on the concept map →
Why it matters
In a course, the dataset arrives as one tidy file. In a real project, data arrives every day from several places, in slightly different shapes, with missing pieces and the occasional disaster: a sensor reporting zeros, a schema change upstream, a labelling vendor who misunderstood the instructions. If the model is retrained on that data, the disaster flows straight into production.
A data pipeline is the automated chain of steps that turns raw data into a dataset a model can train on: ingest, validate, clean, label, join, split, version, document, and load. Because the The ML Project Lifecycle is a loop, the pipeline runs many times. It must give the same answer for the same input, and it must refuse bad input loudly rather than pass it on quietly.
Data work dominates real ML projects. Andrew Ng's "data-centric AI" movement and many industry surveys make the same point: for most applied problems, improving the data beats improving the model. This chapter builds on Data Cleaning and Preparation, which covers cleaning a single table, and turns it into a repeatable system.
The intuition
Think of a water treatment plant. River water comes in. It passes through screens, settling tanks, filters and disinfection, with sensors between the stages. If a sensor detects contamination, a valve closes and the water goes to a holding tank instead of the city's pipes. Every batch is logged, so if someone falls ill, the plant can trace which batch it was.
A data pipeline works the same way:
The steps form a directed acyclic graph (DAG): boxes connected by arrows that only go forward, never round in a circle. "Acyclic" is what makes it runnable. Each step can start as soon as the steps feeding it have finished, and an orchestrator such as Airflow, Dagster or Prefect schedules them, retries failures and records every run.
Key idea Treat data like code: every transformation is automated, every batch is validated before use, every dataset version is immutable and recorded, and every dataset has documentation saying what it is and isn't.
How it works
Collecting
Training data comes from application databases, event logs (clicks, purchases, sensor readings), public datasets, scraped web pages, or purchased data. Three questions matter more than volume:
- Is it representative? Data from your current users may not cover the users you want next year. A face dataset gathered from one country fails elsewhere.
- Is it available at prediction time? As in the The ML Project Lifecycle chapter, a feature that only exists after the event you predict is leakage.
- Are you allowed to use it? Consent, licences and privacy law limit what you can train on (Privacy, Data and Copyright).
Raw data is usually stored in columnar files such as Parquet, an open format that stores each column together and compresses well. A model that needs three columns out of two hundred reads only those three.
Validating: the quality gate
Data validation means checking each new batch against expectations before anyone uses it. Typical checks:
- Schema: the expected columns exist, with the expected types.
- Ranges and values: ratings between 1 and 5, ages not negative, categories from a known list.
- Completeness: the share of missing values below a threshold.
- Uniqueness: no duplicated IDs.
- Volume and distribution: roughly the usual number of rows, and averages not wildly different from previous batches. Comparing distributions is the same idea as drift detection (Monitoring and Data Drift).
A batch that fails is quarantined: stored for inspection, not passed on. The pipeline alerts a human. Libraries such as Great Expectations, pandera and TensorFlow Data Validation let you write these checks declaratively.
Labelling
For Supervised Learning you need labels, and labels made by people are expensive, slow and imperfect. Labelling (also called annotation) is usually done by in-house experts, contracted annotation teams, or crowdsourcing platforms, using tools such as Label Studio.
The single most useful document is the annotation guidelines: precise instructions with worked examples and edge cases. "Is this review positive?" sounds clear until an annotator meets "Great phone, shame it broke after a week."
To measure how clear the task is, give the same items to two annotators and measure inter-annotator agreement. Raw agreement is misleading, because two people guessing randomly will still agree sometimes. Cohen's kappa corrects for that:
Here is the observed share of items on which the annotators agree, and is the agreement you'd expect by chance from each annotator's label frequencies. means perfect agreement. means no better than chance.
Worked example. Two annotators label 100 reviews as positive or negative. They agree on 85, so . Annotator A said "positive" 55 times and B said it 50 times. The chance that both say "positive" at random is , and both say "negative" , so . Then
An 85% raw agreement turns out to be "substantial" rather than near-perfect. Rough conventions call 0.6–0.8 substantial and above 0.8 almost perfect, but what is acceptable depends on the task. Low agreement usually means the guidelines are unclear, not that the annotators are careless.
Some labels will be wrong anyway. This is label noise. A 2021 study by Northcutt and colleagues found that the test sets of ten popular benchmarks contain on average at least 3.3% wrong labels. Their website labelerrors.com shows examples. Wrong test labels make the leaderboard partly measure agreement with mistakes. Cheap remedies: have several annotators label each item and take a majority vote, review items where the model confidently disagrees with the label, and fix the guidelines when the same confusion repeats.
Splitting deterministically
A random split rerun on a grown dataset reshuffles everything: yesterday's test examples become today's training examples, and your test scores are no longer comparable. A hash-based split fixes that. Compute a hash of each example's stable ID and use it to choose the split. For example, if the hash modulo 100 is below 20, the example goes to the test set. The same ID always lands in the same split, even as new rows arrive.
When examples are grouped (several photos of the same person, several messages from the same user), hash the group ID so a group never straddles train and test. When predicting the future, split by time instead (Training, Validation and Test Sets).
Versioning
Every dataset the pipeline produces should be an immutable snapshot with a version ID, so that Experiment Tracking and Reproducibility can record exactly which data trained which model. Options range from dated folders of Parquet files plus a content hash, to tools such as DVC (git-like versions for data), Delta Lake and Apache Iceberg (table formats that keep history), or versioned dataset repositories on the Hugging Face Hub.
Documenting
A dataset without documentation will be misused. A datasheet (from Datasheets for Datasets, Gebru et al., 2018) answers a standard list of questions. Why was it created, and by whom? What does each record represent? How was it collected and labelled? What is missing or skewed? What uses are inappropriate? Who maintains it? Hugging Face dataset cards follow the same idea, and model cards (Mitchell et al., 2019) do the same for trained models.
Serving data to training
The last stage is feeding examples to the training loop fast enough to keep the GPU busy. In PyTorch a Dataset returns one example and a DataLoader batches, shuffles and loads them in parallel worker processes. For datasets too large for one machine, data is split into shards: many files of manageable size (often hundreds of megabytes each) that can be read in parallel and shuffled at the file level. Sharding is also how Distributed Training gives each GPU its own slice. Formats like WebDataset (tar shards) and the Hugging Face datasets library's streaming mode let you train on data you never fully download.
In code
A miniature pipeline in pandas: a raw batch with planted problems, a validation gate, cleaning, a hash-based split and a content-hash version.
import hashlib
import numpy as np
import pandas as pd
# A raw batch of product reviews, with the usual problems baked in.
rng = np.random.default_rng(0)
raw = pd.DataFrame({
"review_id": [f"r{i:05d}" for i in range(1000)],
"stars": rng.integers(1, 6, 1000).astype(float),
"text": rng.choice(["great", "awful", "ok I guess", "", None], 1000,
p=[0.3, 0.3, 0.3, 0.04, 0.06]),
})
raw.loc[[3, 7], "stars"] = [0, 11] # impossible values
raw = pd.concat([raw, raw.iloc[:20]], ignore_index=True) # 20 duplicate rows
def validate(df):
"""Return a list of failed checks; an empty list means the batch passes."""
checks = {
"review_id unique": df["review_id"].is_unique,
"stars in 1..5": df["stars"].between(1, 5).all(),
"text missing < 5%": df["text"].isna().mean() < 0.05,
}
return [name for name, ok in checks.items() if not ok]
def clean(df):
df = df.drop_duplicates("review_id")
df = df[df["stars"].between(1, 5)]
return df[df["text"].fillna("").str.strip() != ""]
def split_of(review_id, test_pct=20):
"""Deterministic split: the same id always lands in the same split."""
bucket = int(hashlib.md5(review_id.encode()).hexdigest(), 16) % 100
return "test" if bucket < test_pct else "train"
print("raw batch fails:", validate(raw))
df = clean(raw)
print("after cleaning:", validate(df) or "all checks pass", "| rows", len(raw), "->", len(df))
df["split"] = df["review_id"].map(split_of)
print(df["split"].value_counts().to_dict())
version = hashlib.sha256(pd.util.hash_pandas_object(df, index=False).values).hexdigest()[:10]
print("dataset version:", version)
# raw batch fails: ['review_id unique', 'stars in 1..5', 'text missing < 5%']
# after cleaning: all checks pass | rows 1020 -> 909
# {'train': 726, 'test': 183}
# dataset version: 46edeba199
Cohen's kappa for the worked example is one call in scikit-learn:
from sklearn.metrics import cohen_kappa_score
a = ["pos"] * 45 + ["neg"] * 5 + ["pos"] * 10 + ["neg"] * 40 # annotator A
b = ["pos"] * 45 + ["pos"] * 5 + ["neg"] * 10 + ["neg"] * 40 # annotator B
print(cohen_kappa_score(a, b)) # 0.7 (agreement 0.85, chance 0.5)
In production, each function would become a task in an orchestrator, the checks would live in a validation library, and the versioned output would be written to storage and recorded by the experiment tracker.
Common pitfalls
- Silent schema changes. An upstream team renames a column or changes units from seconds to milliseconds. Without schema and range checks, training happily continues on nonsense.
- Cleaning differently in training and serving. If training data is cleaned in a notebook and production data by a separate service, the two drift apart. This is training–serving skew. Share one implementation of every transformation.
- Duplicates across splits. Near-identical examples (the same photo resized, the same text with different punctuation) in both train and test inflate scores. Deduplicate before splitting, and split by group.
- Overwriting data in place. "data.csv" changes and every past result becomes irreproducible. Write new versions; never edit old ones.
- Trusting labels blindly. Measure agreement, look at the examples the model gets "wrong" with high confidence, and expect a few per cent of labels to be mistaken.
- Data loading as the bottleneck. A GPU at 30% utilisation is often waiting for data. Use more loader workers, pre-process once instead of every epoch, and store data in efficient formats.
Watch out The most damaging data bugs don't crash anything. A join that silently drops 10% of rows, a timezone shift that leaks tomorrow's information, a label column filled with a default value: the pipeline runs, the model trains and the scores may even improve. Validation checks and spot-checks of real rows are the only defence.
Where it leads
- Experiment Tracking and Reproducibility records which dataset version each model used.
- Monitoring and Data Drift applies the same distribution checks to live production data.
- Synthetic Data adds a new source: data generated by models, with its own quality filters.
- Data Augmentation creates variations of existing examples during training.
- For LLM pretraining, the pipeline is web-scale: crawling, text extraction, language identification, deduplication and quality filtering over trillions of tokens (Pretraining Large Language Models).
A bit of history
Data pipelines are older than machine learning. Businesses have run ETL (extract, transform, load) jobs into data warehouses since the 1970s and 1980s. The ML-specific ideas came with large labelled datasets. ImageNet, published in 2009, labelled millions of images through Amazon Mechanical Turk and showed both the power and the noise of crowdsourcing. Airbnb created the Airflow orchestrator in 2014, and it became an Apache project. Google described its approach to validating training data in the TFX platform from 2017 onwards. Datasheets for Datasets (2018) and Model Cards for Model Reporting (2019) made documentation a standard expectation. In 2021 Northcutt and colleagues showed how many errors lurk in famous test sets, and Andrew Ng launched the data-centric AI movement. Both pushed the field to treat data quality as engineering work rather than an afterthought.
Try it
- In the pipeline code, change
test_pctto 10 and rerun. Then add 500 new rows and rerun. Confirm that no review that was in the test set before moves to train.- Add a check that fails if fewer than 80% of rows survive cleaning. Does the current batch pass?
- Compute Cohen's kappa when the annotators agree on 85 items but A says "positive" 85 times and B 80 times. Why is kappa now much lower?
Hint for 3: when both annotators say "positive" most of the time, they'd agree often by pure chance, so is high.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
Designing Machine Learning Systems
The practical guide to data, features, deployment, monitoring and iteration in production ML.
Datasheets for Datasets
Proposes a standard set of questions every dataset should answer: motivation, composition, collection, labelling, uses and maintenance.
Datasets documentation
Loading, processing, streaming and sharing datasets with the datasets library.
Great Expectations
A widely used library for writing data-quality checks ('expectations') and running them on each new batch.
Pervasive Label Errors in Test Sets Destabilize Machine Learning Benchmarks
Finds wrong labels in the test sets of ten famous benchmarks and shows they can change which model looks best. Examples at labelerrors.com.
DVC (Data Version Control)
Version large data files and models next to git, and define pipelines that rerun only what changed.
Apache Airflow documentation
The best-known workflow orchestrator: define pipelines as DAGs of tasks in Python, schedule them and monitor runs.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/mlops/data-pipelines.md