Sub topic 10
Machine-readable metadata in model cards
This chapter assumes you can read basic YAML, write Markdown, and have seen a model card with sections such as intended use and limitations. It also assumes you know common evaluation metrics. The chapter covers how to put facts about a model into a structured form that tools can read, and where that form breaks down.
Why prose alone is not enough
A model card written only as prose is easy for a person to read. It is hard for a program to read. Suppose your organization has 400 models and a compliance question arrives: "Which models are licensed for commercial use and were trained on data that includes personal information?" If the answers sit in free-form sentences, someone must open 400 documents.
Machine-readable metadata solves this. It is a block of structured key-value fields attached to the card. Tools can then:
- filter and search models by license, language, task, or library
- show badges and summaries in a registry or hub interface
- check that required fields exist before a model is published
- feed audits and inventories without parsing prose
The structured part does not replace the prose. It holds short, checkable facts. The prose holds the reasoning, caveats, and context that do not fit in a field.
Front matter: structured data on top of Markdown
The most common way to attach metadata to a Markdown card is YAML front matter. It is a block of YAML placed at the very top of the file between two lines containing only ---. The Hugging Face Hub reads front matter in a repository's README.md and uses it to power search, filters, and the sidebar.
---
license: apache-2.0
language:
- en
library_name: transformers
pipeline_tag: text-classification
tags:
- support-tickets
datasets:
- my-org/support-tickets
metrics:
- accuracy
- f1
base_model: distilbert-base-uncased
---
# support-ticket-classifier
## Intended use
Routes English-language support tickets to one of five queues.
## Limitations
Not evaluated on non-English text.Each field answers one question a tool might ask.
| Field | What it records | Typical type |
|---|---|---|
| `license` | The license identifier governing use of the weights | string |
| `language` | Languages the model handles | list of language codes |
| `library_name` | The library needed to load the model | string |
| `pipeline_tag` | The task the model performs | string from a fixed vocabulary |
| `tags` | Free-form labels for search | list of strings |
| `datasets` | Identifiers of training or evaluation datasets | list of strings |
| `metrics` | Names of metrics the card reports | list of strings |
| `base_model` | The model this one was fine-tuned or derived from | string or list |
Check the current documentation of your hub or registry for the exact field names and allowed values. They change over time, and unknown fields are often ignored silently.
Where the structure ends and the prose begins
Notice what the front matter above cannot say. The metrics field lists accuracy and f1, but it does not say what the values are, on which data, or for which groups. It also says nothing about why the model should not be used for legal triage. Those facts need either richer structure or prose.
A useful rule is to put a fact in metadata when all three of these hold:
- It has a small, well-defined set of values, or a stable identifier.
- A tool would plausibly filter, group, or validate by it.
- It is true on its own, without surrounding explanation.
License, language, task, base model, and dataset identifiers pass this test. Intended use, out-of-scope use, and limitations fail it. A one-line field such as limitations: "none" is worse than no field, because it looks like a checked answer when it is not.
Recording results as structured data
Some platforms let you record evaluation results in the metadata, not only metric names. The Hugging Face convention is a model-index entry that links a model name to a task, a dataset, and metric values.
model-index:
- name: support-ticket-classifier
results:
- task:
type: text-classification
dataset:
name: support-tickets-test
type: my-org/support-tickets
split: test
metrics:
- type: accuracy
value: 0.91
- type: f1
name: macro F1
value: 0.88This lets a hub display results and build leaderboards. It also creates a risk. A single number per metric invites the problem described in the chapter on disaggregated evaluation: an overall figure can hide large differences between groups. If you publish structured results, publish them per slice as well, using separate entries or a naming scheme your tooling understands. The structured block must not be the only place a reader sees performance.
Generating metadata from a single source
Two copies of a fact will drift apart. If the license appears in the front matter and again in a "License" paragraph, someone will eventually update only one. Two approaches avoid this.
The first is to keep the structured data as the source of truth and generate the prose from it. The ModelCard class below does this for core fields and renders Markdown.
from dataclasses import dataclass, field
@dataclass
class ModelCard:
name: str
version: str
intended_use: str
out_of_scope: str
training_data: str
metrics: dict
limitations: list = 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 += [f"- {name}: {value}" for name, value in self.metrics.items()]
lines += ["", "## Limitations"]
lines += [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 2022-2024.",
metrics={"accuracy": 0.91, "macro_f1": 0.88},
limitations=["Accuracy drops on tickets shorter than 5 words."],
)
print(card.to_markdown())The metric values in this card come from a Python dictionary. In a real pipeline that dictionary would be loaded from the evaluation job's output file, so the card cannot disagree with the evaluation that produced it.
The second approach is to keep the card as the source of truth and let tools read from it. This suits teams that write cards by hand and want the hub to index them. In that case, validation (below) is what keeps the structured part trustworthy.
Reading metadata back
Writing metadata is only useful if something reads it. The sketch below uses the PyYAML library to split a card into its front matter and its body, then returns the parsed fields.
import re
import yaml
def split_front_matter(text: str):
match = re.match(r"^---\s*\n(.*?)\n---\s*\n(.*)$", text, re.DOTALL)
if not match:
return {}, text
data = yaml.safe_load(match.group(1)) or {}
return data, match.group(2)
sample = """---
license: apache-2.0
language:
- en
---
# demo
"""
meta, body = split_front_matter(sample)
print(meta["license"], meta["language"])Always use yaml.safe_load, not yaml.load. Model cards often come from third-party repositories, and the unsafe loader can construct arbitrary Python objects from a crafted file.
Validating the card
Parsing makes validation possible. Two layers are worth checking separately.
- Metadata validity. Required keys exist, values have the right type, and identifiers come from an allowed list. A misspelled
licence:key is valid YAML and will be silently ignored by many tools. - Section presence. The prose has the headings your policy requires.
The script below covers the second layer. It fails a CI job when required headings are missing.
import re
REQUIRED = ["Intended use", "Training data", "Evaluation", "Limitations"]
def missing_sections(markdown: str) -> list:
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 f:
missing = missing_sections(f.read())
if missing:
raise SystemExit(f"Model card is missing sections: {missing}")A heading check is a weak test. An empty "Limitations" section passes it. Treat it as a floor, and add checks for minimum content where you can, for example that the section contains at least one list item or sentence, or that it does not contain placeholder text such as TODO.
How the pieces fit in a pipeline
The diagram shows one workable flow. Evaluation output feeds both the metadata and the generated prose, and a validation step gates publication.
Common errors
- Stale metadata. The front matter says
license: mitafter the team relicensed the weights. Generate the field from the same place the release process reads the license. - Wrong or invented identifiers. A
datasetsentry that points to nothing breaks provenance links. Validate that identifiers resolve, or at least match a pattern. - Silent key typos. YAML accepts any key. Use a schema, with a tool such as JSON Schema, so unknown keys produce a warning or an error.
- Metrics without context. A metric name or value with no dataset, split, or version is not a reproducible claim.
- Over-trusting the structure. A card that passes every check can still be misleading. Validation confirms that information exists and has the right shape. It does not confirm that the information is true or complete.
Choosing a level of structure
| Approach | Strength | Weakness | Fits when |
|---|---|---|---|
| Prose only | Easy to write, full nuance | Cannot be queried or checked | One-off research model, no registry |
| Front matter plus prose | Hub search and filters work, cheap to adopt | Metadata is shallow, easy to let drift | Most public and internal models |
| Generated card from a schema | One source of truth, enforceable | Needs pipeline work and upkeep | Many models, audits, regulated settings |
Start with front matter plus prose. Move to generation when you find yourself fixing the same drift errors repeatedly.
Exercise
A card's front matter lists metrics: [accuracy] and a CI check confirms that all four required headings exist. A reviewer still rejects the card. Give two reasons the automated checks could pass while the card is inadequate, and one change that would catch each.
Show answer
First, the headings may exist with empty or placeholder content, such as an empty "Limitations" section. Add a content check that requires at least one sentence or list item and rejects text like TODO. Second, the metadata lists only a metric name, so there is no value, dataset, split, or per-group breakdown. Add a schema that requires results to include a dataset, split, and value, and require per-group entries for the groups the card names as relevant. A further acceptable answer: a key typo such as licence passes YAML parsing, and a JSON Schema with unknown keys disallowed would catch it.
Exercise
Why should limitations be written as prose in the card body, not as a single metadata field, and which three fields in the example front matter are good candidates for structured metadata instead?
Show answer
Limitations have no small fixed set of values, no tool would filter on them, and they need explanation to be true, so a short field would be either empty or misleading. Good structured candidates include license, language, pipeline_tag, library_name, base_model, and datasets, because each has a defined vocabulary or stable identifier that tools can filter or validate.