Sub topic 11
Generating and validating cards in a pipeline
This chapter assumes you can read Python and YAML, know the standard model card sections from earlier chapters, and have used Git and a CI system such as GitHub Actions. You will build a small generator and validator, then run both in CI so a card cannot silently fall out of date.
Why automate model cards
A card written once by hand starts to go stale the next time someone retrains the model. Typical drift looks like this:
- The card reports accuracy 0.91, but the new model scores 0.89.
- A required section was never written.
- A template placeholder such as "TODO" shipped to production.
- The version in the card does not match the version of the artifact.
Automation addresses two separate problems. Generation fills in facts that a machine already knows, such as metrics, version, dataset identifier, and library. Validation checks that the card is complete and consistent before a model is released.
Neither step replaces human judgment. A script can check that an "Out-of-scope use" section exists and is not empty. It cannot check that the section is honest or useful.
Deciding what is generated and what is written
Split the card into measured facts and judgments. Generate the first kind and review the second kind in pull requests.
| Field | Source | Generated or written |
|---|---|---|
| Name, version, license | Project config | Generated |
| Overall and per-group metrics | Evaluation job output | Generated |
| Training data identifier and size | Data pipeline manifest | Generated |
| Intended use, out-of-scope use | Model owner | Written, reviewed |
| Limitations, ethical considerations | Model owner and reviewers | Written, reviewed |
| Interpretation of per-group gaps | Model owner | Written, reviewed |
Keep the written fields in a small file under version control, so edits show up in diffs. The pipeline combines that file with the evaluation output.
The pipeline at a glance
The validator reads metrics.json as well as the card. That lets it detect a card whose numbers no longer match the latest evaluation.
Step 1: Produce structured evaluation output
The evaluation job should write its results as JSON rather than print them. Include overall metrics and per-group metrics, because the earlier chapters showed that overall numbers can hide a weak group.
{
"overall": {"accuracy": 0.91, "macro_f1": 0.88},
"by_group": {
"tickets_5_words_or_more": {"accuracy": 0.93, "macro_f1": 0.90},
"tickets_under_5_words": {"accuracy": 0.74, "macro_f1": 0.69}
}
}Save this as metrics.json. The written fields go in card_inputs.json:
{
"name": "support-ticket-classifier",
"version": "1.2.0",
"license": "apache-2.0",
"library": "transformers",
"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 2022-2024.",
"limitations": [
"Accuracy drops on tickets shorter than 5 words.",
"Not evaluated on non-English text."
]
}Step 2: Generate the card
The generator below renders YAML front matter, the sections, and a per-group table. It formats every metric with two decimals, and the validator relies on that same format later.
import json
from pathlib import Path
FRONT_MATTER = """---
license: {license}
language:
- en
library_name: {library}
metrics:
- accuracy
- f1
---
"""
def metric_lines(metrics: dict) -> str:
return "\n".join(f"- {name}: {value:.2f}" for name, value in metrics.items())
def group_table(by_group: dict) -> str:
names = sorted({m for group in by_group.values() for m in group})
header = "| Group | " + " | ".join(names) + " |"
divider = "| --- |" + " --- |" * len(names)
rows = [
f"| {group} | " + " | ".join(f"{values[m]:.2f}" for m in names) + " |"
for group, values in by_group.items()
]
return "\n".join([header, divider, *rows])
def build_card(inputs: dict, metrics: dict) -> str:
body = [
f"# {inputs['name']} (v{inputs['version']})",
"",
"## Intended use",
inputs["intended_use"],
"",
"## Out-of-scope use",
inputs["out_of_scope"],
"",
"## Training data",
inputs["training_data"],
"",
"## Evaluation",
"### Overall",
metric_lines(metrics["overall"]),
"",
"### By group",
group_table(metrics["by_group"]),
"",
"## Limitations",
"\n".join(f"- {item}" for item in inputs["limitations"]),
]
return FRONT_MATTER.format(**inputs) + "\n" + "\n".join(body) + "\n"
if __name__ == "__main__":
inputs = json.loads(Path("card_inputs.json").read_text(encoding="utf-8"))
metrics = json.loads(Path("metrics.json").read_text(encoding="utf-8"))
Path("README.md").write_text(build_card(inputs, metrics), encoding="utf-8")
print("wrote README.md")Run python generate_card.py and the result is a complete README.md. Generation is deterministic: the same inputs produce the same bytes. That property matters in Step 4.
Step 3: Validate the card
The validator checks four things:
- The YAML front matter parses and has the required keys.
- Each required section exists and is not empty.
- No placeholder text remains.
- Every overall metric in
metrics.jsonappears in the card.
It collects all errors before exiting, so a contributor can fix them in one pass.
import json
import re
import sys
from pathlib import Path
import yaml
REQUIRED_SECTIONS = ["Intended use", "Training data", "Evaluation", "Limitations"]
REQUIRED_KEYS = ["license", "language", "library_name"]
PLACEHOLDERS = re.compile(r"\b(TODO|TBD|FIXME)\b|lorem ipsum", re.IGNORECASE)
def split_front_matter(text: str):
match = re.match(r"\A---\n(.*?)\n---\n(.*)\Z", text, re.DOTALL)
if not match:
return None, text
try:
return yaml.safe_load(match.group(1)), match.group(2)
except yaml.YAMLError:
return None, match.group(2)
def sections(body: str) -> dict:
parts = re.split(r"^#{2,6}\s+(.+)$", body, flags=re.MULTILINE)
return {
parts[i].strip().lower(): parts[i + 1].strip()
for i in range(1, len(parts) - 1, 2)
}
def check(card_path: str, metrics_path: str) -> list:
errors = []
text = Path(card_path).read_text(encoding="utf-8")
meta, body = split_front_matter(text)
if not isinstance(meta, dict):
errors.append("missing or invalid YAML front matter")
meta = {}
for key in REQUIRED_KEYS:
if not meta.get(key):
errors.append(f"front matter lacks '{key}'")
found = sections(body)
for name in REQUIRED_SECTIONS:
content = next(
(c for h, c in found.items() if h.startswith(name.lower())), None
)
if content is None:
errors.append(f"missing section: {name}")
elif not content:
errors.append(f"empty section: {name}")
if PLACEHOLDERS.search(body):
errors.append("placeholder text found")
metrics = json.loads(Path(metrics_path).read_text(encoding="utf-8"))
for name, value in metrics["overall"].items():
if f"{value:.2f}" not in body:
errors.append(f"metric {name}={value:.2f} not found in card")
return errors
if __name__ == "__main__":
problems = check(sys.argv[1], sys.argv[2])
if problems:
raise SystemExit("Model card problems:\n- " + "\n- ".join(problems))
print("Model card OK")Run it with python validate_card.py README.md metrics.json.
What this validator cannot catch
- Vacuous content. The text "N/A" passes the non-empty check. You can add a minimum length, but a determined author can still write filler.
- Wrong but consistent numbers. If the evaluation job used the wrong test set, the card and
metrics.jsonagree and both are wrong. - Substring matches. The check
"0.91" in bodyalso passes if 0.91 appears somewhere unrelated. Stricter checks parse the metric lines or the table. - Dishonest limitations. A section that says "None known" passes. Human review is the only defense.
Step 4: Run both in CI
Generating the card in CI and comparing it to the committed file catches the case where someone retrained the model and forgot to regenerate the card. The git diff --exit-code step fails if the generated output differs from what is committed.
name: model-card
on:
pull_request:
paths:
- "card_inputs.json"
- "metrics.json"
- "README.md"
- "generate_card.py"
- "validate_card.py"
jobs:
validate:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.12"
- run: pip install pyyaml
- run: python generate_card.py
- name: Card is up to date
run: git diff --exit-code README.md
- run: python validate_card.py README.md metrics.jsonTwo design choices are worth understanding.
- Fail, don't auto-commit. The job reports a stale card and leaves the fix to the author. If a bot silently rewrote the card, a reviewer might never see a metric change.
- Order matters. Generate first, then diff, then validate. If you validate first, a stale card can pass because it is still internally consistent.
Edge cases and common errors
- Floating-point formatting. Rounding differs between code paths. If the evaluation job writes 0.905 and one path formats it as 0.90 while another formats it as 0.91, the check fails. Use one formatting function, as the generator does.
- Missing groups. If a group has no examples, a per-group metric is undefined. Report the group with its count and "n/a", and do not drop it silently. Add a sample count column when groups are small, because a score on 12 examples is weak evidence.
- Different metric sets across versions. If version 1.3 adds a metric, the generator handles it, but comparisons between cards need the same definitions. Record metric names and test set versions in the card.
- Schema drift in metrics.json. Validate the JSON itself, for example with the
jsonschemapackage, so a renamed key fails with a clear message and not aKeyError. - Secrets and private data. Generated cards are often published. Keep internal paths, customer names, and raw example text out of
card_inputs.jsonandmetrics.json. - Heading style. The validator matches headings by prefix, case-insensitively. A heading such as "Evaluation results" matches "Evaluation". A heading renamed to "Results" fails, which is usually what you want.
Choosing how strict to be
| Check | Cost | Catches | Risk of false failures |
|---|---|---|---|
| Required sections exist | Low | Omissions | Low |
| Front matter keys | Low | Broken hub metadata | Low |
| No placeholders | Low | Unfinished drafts | Low |
| Metrics match evaluation | Medium | Stale numbers | Medium, from formatting |
| Card equals generated output | Medium | Skipped regeneration | Medium, if people hand-edit generated parts |
| Minimum length or per-group coverage | Medium | Filler, hidden gaps | Higher |
Start with the low-cost checks. Add the others once the team trusts the pipeline, so that a failing check is something people act on and not something they bypass.
Exercise
The validator passes on a card, but the model was retrained last week and the card still shows the old accuracy. The new accuracy was written to metrics.json by the evaluation job. Which check would have caught this, and what does it compare?
Show answer
The metric consistency check, which compares each value in metrics.json (formatted to two decimals) with the text of the card. The stale value is not present in the card body, so it reports an error. The "card equals generated output" step in CI would also catch it, because regenerating the card from the new metrics.json produces a different README.md than the committed one.
Exercise
Extend the validator so that a card fails if any group in metrics.json["by_group"] is missing from the card's text. Write the loop that appends the errors.
Show answer
Add this before the return statement in check(): for group in metrics.get("by_group", {}): if group not in body: errors.append(f"group '{group}' not reported in card") This works because the generator writes each group name as a row label in the table. A card that omits a group, for example one whose group table was hand-deleted, now fails validation.