Courses3 levels
Level 1 · Foundations11 courses
Level 2 · Core5 courses
Level 3 · Advanced5 courses
Labs8 topics
Library Practice exams AI Range Pricing Start free

Lesson 10 · 40 minutes

Document a model and its data with a model card and a data sheet

After this lesson you can
  • Write a model card and a data sheet as structured files and render them as Markdown
  • Check the files for required fields with a script
  • Keep approvals that break when an approved card is changed
Lab files of this lesson (55)

The lab folder as it stands after this lesson. Unzip it in ~/krlab.

More

The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.

Scenario

A new engineer at Harbour Credit asks three questions about LoanScore: what is it for, what was it trained on, and who said that it may go live? The answers are in three people's heads and one old email. Your lead wants them in two files that travel with the model, a record of the approval that cannot be faked by a quiet edit, and a script that fails when a field is empty.

Recall

Lesson 9: why does the vendor record carry a date and a reviewer?

Providers change their terms. A dated record shows what you knew when you signed, and the reviewer is the person who answers for the judgement.

Lesson 5: what does an explanation record carry that links it to a model file?

The model version, for example loanscore-1.0. A reviewer can recompute the reasons from that version. The model card of this lesson carries the same version.

The idea

A model card is a short document that says what a model is for, how it was built and tested, how well it works for different groups, and where it must not be used. A data sheet does the same for a data set: why it exists, how it was collected, what it holds and what is wrong with it. Both ideas come from published research ("Model Cards for Model Reporting" and "Datasheets for Datasets"). Teams keep them next to the model, so that the next person does not guess. The EU AI Act asks providers of high-risk systems for technical documentation (lesson 6), and the list of its Annex IV mentions datasheets for the data. These two files are evidence for that work.

Keep each document as structured data, not as free text: a JSON file with named fields. A script can then check that no field is empty, and it can render the same data as a readable Markdown page, so that nobody edits two copies.

An approval says that a named person accepted this version of the card. To make the approval mean something, store a fingerprint (a SHA-256 hash) of the card with it. If anyone changes the card after the approval, the fingerprint no longer matches and the check fails. Two more rules protect the decision: the approver is not the owner or the builder, and the approval names the version.

Approving a model card
BuilderCard fileCheckerApproverApprovals filefill the fieldsrequired fields present?fingerprint, name, datedoes the fingerprint match?card changed, approve againBuilderCard fileCheckerApproverApprovalsfile12345
  1. Builder → Card file: fill the fields
  2. Card file → Checker: required fields present?
  3. Approver → Approvals file: fingerprint, name, date
  4. Checker → Approvals file: does the fingerprint match?
  5. Checker → Approver: card changed, approve again

Worked example

Work in ~/krlab/ai-governance with the environment on.

1. Write the model card

The numbers in metrics are the ones of lessons 4 and 5. They are text, so that 0.80 stays 0.80. Save model_card.json.

The main fields of the model card (metrics: the last three)
LoanScorename1.0versionAinoownerBrambuilder0.87accuracy0.80selection_rate_ratio300 held-out rowstested_onLoanScorename1.0versionAinoownerBrambuilder0.87accuracy0.80selection_rate_ratio300 held-out rowstested_on

model_card.json

{
  "name": "LoanScore",
  "version": "1.0",
  "owner": "Aino",
  "builder": "Bram",
  "purpose": "Ranks consumer loan applications for a credit officer. It does not decide alone.",
  "out_of_scope": "Business loans. Automatic decline. Any use on people outside the training population.",
  "model_type": "Logistic regression on income, debt ratio and years of credit history",
  "training_data": "loans.csv, described in datasheet.json",
  "metrics": {"accuracy": "0.87", "selection_rate_ratio": "0.80", "tested_on": "300 held-out rows"},
  "limits": "Trained on one year of synthetic applications. Group B has a lower income on average. The cut-off of group B is 0.36, chosen to reach a ratio of 0.80. The group cut-off needs legal approval."
}

2. Write the data sheet

Save datasheet.json. It says that the group column exists and why.

datasheet.json

{
  "name": "loans.csv",
  "owner": "Aino",
  "purpose": "Train and test a model that ranks loan applications.",
  "collection": "Generated by makedata.py with seed 7. No real person is in it.",
  "rows": 1000,
  "fields": ["id", "group", "income", "debt_ratio", "history_years", "repaid"],
  "personal_data": "none, the data is synthetic",
  "known_issues": ["Group B has a lower income on average by construction.", "The group column is used only to measure fairness."]
}

3. Write the tool

hashlib.sha256 makes a fingerprint. json.dumps(doc, sort_keys=True, separators=(",", ":")) writes a document in one fixed form, with the keys in order and no spaces. So a change of layout does not change the fingerprint, and a change of content does. isinstance(value, list) tests the type of a value. str.replace swaps text, and "a" as a file mode appends to the end of a file. The tool has three commands: render, check and approve.

card.py

"""card.py: render, check and approve a model card and a data sheet.

    python3 card.py render model_card.json datasheet.json
    python3 card.py check model_card.json datasheet.json approvals.jsonl
    python3 card.py approve model_card.json approvals.jsonl APPROVER DATE
"""
import hashlib
import json
import sys

from govlib import finish

CARD = ["name", "version", "owner", "builder", "purpose", "out_of_scope", "model_type", "training_data", "metrics", "limits"]
SHEET = ["name", "owner", "purpose", "collection", "rows", "fields", "personal_data", "known_issues"]


def load(path):
    with open(path, encoding="utf-8") as f:
        return json.load(f)


def digest(doc):
    """The fingerprint of a document. Sorted keys, so the layout of the file does not change it."""
    return hashlib.sha256(json.dumps(doc, sort_keys=True, separators=(",", ":")).encode()).hexdigest()


def markdown(doc):
    lines = [f"# {doc['name']}", ""]
    for key, value in doc.items():
        if key == "name":
            continue
        lines += [f"### {key.replace('_', ' ').capitalize()}", ""]
        if isinstance(value, list):
            lines += [f"- {item}" for item in value]
        elif isinstance(value, dict):
            lines += [f"- {k}: {v}" for k, v in value.items()]
        else:
            lines.append(str(value))
        lines.append("")
    return "\n".join(lines)


def problems(card_path, sheet_path, approvals_path):
    card, sheet = load(card_path), load(sheet_path)
    found = [f"model card: {name} is missing or empty" for name in CARD if not card.get(name)]
    found += [f"data sheet: {name} is missing or empty" for name in SHEET if not sheet.get(name)]
    with open(approvals_path) as f:
        approvals = [json.loads(line) for line in f if line.strip()]
    mine = [a for a in approvals if a["version"] == card.get("version")]
    if not mine:
        found.append(f"no approval for version {card.get('version')}")
    elif mine[-1]["card_sha256"] != digest(card):
        found.append("the card changed after its approval: approve it again")
    elif mine[-1]["approver"] in (card.get("owner"), card.get("builder")):
        found.append(f"{mine[-1]['approver']} approved a card that they own or built")
    return found


if __name__ == "__main__":
    command = sys.argv[1]
    if command == "render":
        for path in sys.argv[2:4]:
            with open(path.replace(".json", ".md"), "w", encoding="utf-8") as f:
                f.write(markdown(load(path)))
            print("wrote", path.replace(".json", ".md"))
    elif command == "approve":
        with open(sys.argv[3], "a") as f:
            card = load(sys.argv[2])
            f.write(json.dumps({"version": card["version"], "card_sha256": digest(card),
                                "approver": sys.argv[4], "date": sys.argv[5]}) + "\n")
        print("approved version", card["version"])
    else:
        finish(problems(*sys.argv[2:5]))

4. Render the Markdown

sed -n '1,12p' prints lines 1 to 12.

python card.py render model_card.json datasheet.json
sed -n '1,12p' model_card.md
wrote model_card.md
wrote datasheet.md
# LoanScore

### Version

1.0

### Owner

Aino

### Builder

5. Check, approve, check again

touch makes an empty file. The first check fails: no approval exists. Elif, who neither owns nor built LoanScore, approves it. The approval writes one line of approvals.jsonl, in parts.

One line of approvals.jsonl
1.0version of the card6193067e...card_sha256: fingerprint of the cardElifapprover2026-11-15date1.0version of the card6193067e...card_sha256: fingerprint of the cardElifapprover2026-11-15date
touch approvals.jsonl
python card.py check model_card.json datasheet.json approvals.jsonl
python card.py approve model_card.json approvals.jsonl Elif 2026-11-15
python card.py check model_card.json datasheet.json approvals.jsonl
PROBLEM no approval for version 1.0
problems: 1
approved version 1.0
problems: 0

6. Break the approval in two ways

First, change one word of the card after the approval. Second, let the builder approve.

sed 's/Group B has a lower income on average/Group B has the same income/' model_card.json > edited.json
python card.py check edited.json datasheet.json approvals.jsonl
touch self.jsonl
python card.py approve model_card.json self.jsonl Bram 2026-11-16
python card.py check model_card.json datasheet.json self.jsonl
PROBLEM the card changed after its approval: approve it again
problems: 1
approved version 1.0
PROBLEM Bram approved a card that they own or built
problems: 1

The edit made the fingerprint differ, so the old approval no longer counts. Bram built the model, so his approval is rejected, as it should be.

The finished file: approvals.jsonl

approvals.jsonl

{"version": "1.0", "card_sha256": "6193067e800d6506caed2ff97a8bfab1daa4ee42a29d525632bffa57cf010e93", "approver": "Elif", "date": "2026-11-15"}

Your turn

The DocSum team (invented) has a card, a data sheet and an approval. Save the three files. There are no steps: run the checker, then repair what it reports, and approve the result with a person who is not an owner or a builder.

card-b.json

{
  "name": "DocSum",
  "version": "1.0",
  "owner": "Nico",
  "builder": "Olga",
  "purpose": "Summarises customer documents for a case worker.",
  "out_of_scope": "Legal advice. Documents in languages other than English.",
  "model_type": "Hosted language model with a fixed prompt",
  "training_data": "None of ours. The provider trained the model.",
  "metrics": {"summary_check": "40 of 50 summaries rated good by a reviewer"},
  "limits": ""
}

sheet-b.json

{
  "name": "docsum-test-set",
  "owner": "Nico",
  "purpose": "50 documents used to check the summaries.",
  "collection": "Copied from closed cases, with names removed.",
  "rows": 50,
  "fields": ["case_id", "text"],
  "personal_data": "names removed, free text may still hold personal data",
  "known_issues": []
}

approvals-b.jsonl

{"version": "1.0", "card_sha256": "9a6e08e912e528621e2b12a47a62c07e078b63dd7d6065c57609cc4dbcf15854", "approver": "Olga", "date": "2026-11-12"}

Use the files as they are printed for the first three answers.

Last, write two sentences on known_issues of the DocSum sheet: why an empty list there is itself a finding.

Check yourself

Why keep the card as JSON and render the Markdown, instead of writing the Markdown by hand?

One source of truth. A script can check fields in JSON and render the readable page from it, so the two can never disagree. A hand-written page and a data file drift apart within a month.

The approval stores a fingerprint of the card. What attack or mistake does it stop?

A quiet edit after approval, for example someone changing the limits or the metrics because they look inconvenient. The old approval no longer matches, and the check fails until a person approves the new text. It does not stop a fake approval line. For that, keep the approvals file in version control with review.

Why must the approver be different from the owner and the builder?

It is the separation of duties of lesson 1. The person who approves is the one who may stop the launch. A builder or owner has an interest in the launch, so their approval is weaker evidence.

What must a data sheet say about the group column of LoanScore, and why?

That the column exists, that it is used only to measure fairness, and who may read it. It is sensitive data, and a reader who finds it in the file must not assume that the model uses it.

Field notes

  • Put the model version, the data version and the code version in the card. Without them a metric has nothing to belong to. Tag the files in version control at each approval.
  • Report metrics by group, not only overall (lesson 4). A single accuracy number hides the gap that a card exists to show.
  • Say plainly what the model must not be used for. The out_of_scope field is the most useful line for a person who wants to reuse the model for something else.
  • A card is a record of a decision, not a sales page. List the known weaknesses, and update the card when the monitoring report (lesson 8) shows drift.
  • For a model that you buy, the provider's card is an input to your due-diligence record (lesson 9), and you still write your own card for the system that you build on it.