Sub topic 11
Generating and Validating Model Cards in a Pipeline
This chapter assumes basic supervised machine learning, common evaluation metrics, Python, Markdown, and Git. You will build a small documentation step that generates a model card from structured data and checks that the card contains required sections.
Why automate model cards?
A model card is part of a model release, not a document written once and forgotten. Manual editing creates predictable problems:
- A new model version may keep the old version number.
- Reported metrics may not match the evaluation results.
- Required sections may disappear during a merge.
- Users may not know which training data or code produced the model.
A pipeline can generate stable sections from release data, validate the result, and fail before publication when information is missing.
A useful pipeline separates facts from presentation:
- Evaluation code writes metrics and test-set details to structured data.
- A generator turns those facts into Markdown.
- A validator checks required sections and metadata.
- A reviewer approves the card before the model is released.
Generate the card from structured data
The generator should receive explicit values instead of discovering facts from prose. This makes the source data easier to test and compare across versions.
The following example uses a Python dataclass. A dataclass is a Python class designed to store related fields. Its to_markdown method produces the card content.
from dataclasses import dataclass, field
@dataclass
class ModelCard:
name: str
version: str
intended_use: str
out_of_scope: str
training_data: str
metrics: dict[str, float]
limitations: list[str] = field(default_factory=list)
def to_markdown(self) -> str:
lines = [
f"# {self.name} (v{self.version})",
"",
"## Intended use",
self.intended_use,
"",
"## Out-of-scope use",
self.out_of_scope,
"",
"## Training data",
self.training_data,
"",
"## Evaluation",
]
lines.extend(
f"- {name}: {value}" for name, value in self.metrics.items()
)
lines.extend(["", "## Limitations"])
lines.extend(f"- {item}" for item in self.limitations)
return "\n".join(lines) + "\n"
card = ModelCard(
name="support-ticket-classifier",
version="1.2.0",
intended_use="Route English-language support tickets to one of five queues.",
out_of_scope="Not for legal, medical, or safety-critical triage.",
training_data="120k anonymized tickets collected from 2022 through 2024.",
metrics={"accuracy": 0.91, "macro_f1": 0.88},
limitations=["Accuracy drops on tickets shorter than five words."],
)
with open("README.md", "w", encoding="utf-8") as output:
output.write(card.to_markdown())In a real project, the metrics would come from the evaluation job rather than being typed into the generator. The release process should also record the model artifact, source commit, dataset version, evaluation-set version, and reviewer.
Add machine-readable metadata
A model card can contain prose for people and metadata for tools. On the Hugging Face Hub, YAML front matter at the beginning of README.md can describe the license, language, task, dataset, and metrics.
---
license: apache-2.0
language:
- en
library_name: transformers
pipeline_tag: text-classification
datasets:
- my-org/support-tickets
metrics:
- accuracy
- f1
base_model: distilbert-base-uncased
---Keep metadata consistent with the prose. If the card says the model supports English only, the language field should not imply broader support. If the model is retrained, update both the version and the metadata.
Validate before publication
Validation checks machine-readable requirements. It does not replace human review. A validator can confirm that headings exist, but it cannot decide whether the intended-use statement is honest or whether a risk description is adequate.
import re
REQUIRED = ["Intended use", "Training data", "Evaluation", "Limitations"]
def missing_sections(markdown: str) -> list[str]:
headings = {
match.group(1).strip().lower()
for match in re.finditer(
r"^#{1,6}\s+(.+)$", markdown, re.MULTILINE
)
}
return [
section
for section in REQUIRED
if not any(section.lower() in heading for heading in headings)
]
with open("README.md", encoding="utf-8") as input_file:
missing = missing_sections(input_file.read())
if missing:
raise SystemExit(f"Model card is missing sections: {missing}")
print("Model card passed structural validation.")Run this script in continuous integration, the automated check that runs for each proposed change. A failed check should block publication. You can extend the validator to check that the version matches the model artifact, that metric values are numeric, and that required metadata fields exist.
| Check | Example failure | Best enforcement |
|---|---|---|
| Required headings | `Evaluation` is absent | Automated validator |
| Metric consistency | Card says `0.91`, report says `0.87` | Compare generated artifacts |
| Risk quality | Limitation is vague | Human review |
| Version identity | Card says `1.1.0` for a `1.2.0` artifact | Release automation |
Versioning and review
Store the card beside the model code or artifact, and review it in the same change as the model release. A changed dataset, preprocessing step, threshold, label definition, or evaluation population can require a new card version even when the model architecture stays the same.
Record who reviewed the card and what evidence supports its metrics. When a limitation is discovered in production, update the card and link the change to the incident or evaluation result. This turns documentation into part of model governance rather than a release checkbox.
Exercise
A new model passes the section validator, but its evaluation data changed from English tickets to multilingual tickets. What else must the release process check?
Show answer
It must update the training and evaluation descriptions, metrics, language metadata, intended-use boundaries, and limitations, then require human review because the change may alter where the model is reliable.