Level 15 · HeroLesson 15.1 46 min read 10 question quiz 15 marks of written practice

Responsible AI: Fairness, Safety, Privacy and the Law

Why responsibility is part of engineering

AI systems now help decide who gets a loan, a job interview, a medical test or a university place. When they go wrong, real people are harmed, often people with the least power to complain.

YearCaseWhat happened
2016Criminal risk scores (COMPAS)A news investigation found that Black defendants who did not reoffend were almost twice as likely as white defendants to have been labelled high risk
2018A recruiting toolA large company dropped an experimental CV-screening model that had learned to mark down CVs containing the word "women's"
2018Face analysis (Gender Shades)Commercial systems misjudged the gender of darker-skinned women up to 34.7% of the time, and of lighter-skinned men 0.8% of the time
2020A-level grades in EnglandAn algorithm replaced cancelled exams and lowered about 39% of teachers' predicted grades; after protests, it was withdrawn

None of these systems was built to discriminate. Each learned from data that reflected an unequal world, or was judged by a measure that hid who it failed. Responsible AI is not a separate subject added at the end: it is part of doing the engineering properly.

Measuring fairness

"Fair" has several precise meanings, each comparing a different number between groups:

DefinitionEqual across groupsThe idea
Demographic parityThe share of people approvedOpportunities spread equally
Equal opportunityThe true positive rate: of those who deserve approval, the share approvedEqually good people get equal chances
Equalised oddsBoth the true and false positive ratesErrors fall equally on everyone
Predictive parityThe precision: of those approved, the share who succeedAn approval means the same for everyone
Fairness measures for two groupsTwo waffle charts of 100 squares, each square ten applicants. Group A: 36 squares would repay and were approved, 4 would repay but were refused, 12 were approved but did not repay, and 48 were refused and would not have repaid. Group B: 12, 8, 4 and 76. Paired bars compare the groups: approved, 48% against 16%, unequal, so demographic parity fails; true positive rate 90% against 60%, unequal, so equal opportunity fails; false positive rate 20% against 5%, unequal, so equalised odds fails; precision 75% for both, equal, so predictive parity holds.One model, two groups: which kind of fairness does it meet?group Agroup Bwould repay, approvedwould repay, refuseddid not repay, approveddid not repay, refusedeach square is 10 applicantsapproveddemographic parityA48%B16%unequaltrue positive rateequal opportunityA90%B60%unequalfalse positive rateequalised oddsA20%B5%unequalprecisionpredictive parityA75%B75%equal
The same numbers as the lesson's Python: fair by one definition, unfair by three others.

In the example in the figure, both groups have the same precision, 75%, so by one definition the model is fair. But group B's applicants who would repay are approved only 60% of the time, against 90% for group A.

Fairness definitions conflict

In 2016 and 2017, researchers proved that when two groups have different base rates, such as different shares of people who would repay, no model short of a perfect one can satisfy predictive parity and equalised odds at the same time. Choosing which kind of fairness matters is a value judgement about the situation, to be made openly, with the people affected, and not left to an optimiser.

Fairness lab

Move each group's approval threshold and watch four fairness measures pull against each other. This tool needs JavaScript, so turn it on to use it. Everything you need to answer the exam question is explained in the text above.

Where bias comes from, and what to do

Bias can enter at every stage (Level 3): historical bias in the world the data records, representation bias when some groups are scarce in the data, measurement bias when a label is a poor stand-in (arrests are not the same as crimes), and deployment bias when a model is used on people unlike those it learned from.

Engineers have three places to intervene:

  • Before training: collect better data, rebalance or reweight groups, remove proxies.
  • During training: add a fairness constraint or penalty to the loss.
  • After training: adjust decision thresholds per group, as the lab above lets you do.

Each has costs, often a little overall accuracy, and some, such as treating groups differently, are restricted by law in some settings. Just as important are the non-technical steps: involving the people affected, auditing results by group before and after release, and being willing to decide that a system should not be built at all.

Explaining decisions

People affected by a decision often have a right to an explanation, and engineers need explanations to find bugs.

  • Interpretable models, such as small decision trees or linear models, can be read directly.
  • Feature importance asks how much each input matters overall, for example by shuffling one feature and seeing how much worse the model gets.
  • Local explanations such as LIME (2016) and SHAP (2017) estimate how much each feature pushed one particular decision up or down.
  • Saliency maps highlight the pixels of an image that most affected a vision model's answer.
  • Counterfactual explanations say what would have had to be different: "If your income had been £57,500 instead of £38,000, the loan would have been approved."
Explaining a decisionA waterfall chart for one loan applicant. The score starts at minus 4. Income of 38 thousand pounds adds 3.04, two years at the address adds 0.60, and one missed payment subtracts 1.20, ending at minus 1.56, below the approval line at 0, so the application is refused. A note gives the counterfactual: it would be approved if income were 57,500 pounds instead of 38,000, or with 7.2 years at the address; even with no missed payments it would still be refused.Explaining one decision: how each feature moved the score-4-3-2-101approve if the score is 0 or more−4.00startbias+3.04income£38k+0.60address2 years−1.20missed1 payment−1.56finalrefusedCounterfactual:approved if income were£57,500 instead of £38,000,or 7.2 years at the addressEven with no missedpayments: still refused
The same model as the lesson's Python: a transparent score that explains itself.

Explanations of complex models are approximations, and a convincing explanation can still be wrong. They help, but they do not replace testing.

Privacy

Models can leak the data they were trained on. In 2021 researchers extracted names, phone numbers and email addresses that GPT-2 had memorised word for word from its training text. And "anonymised" data is often not anonymous: in 2008, researchers re-identified people in a dataset of film ratings released by Netflix by matching it against public reviews.

Two techniques protect privacy by design:

  • Differential privacy adds carefully measured random noise to results, so that no answer reveals much about any one person. A parameter ε (epsilon) sets the trade-off: smaller ε means more noise and more privacy. The 2020 US Census used it.
Differential privacyTwo surveys differ by one person, Sam: the true counts are 142 without Sam and 143 with Sam. Each count has random noise added, with epsilon 0.5. The graph shows the distribution of released answers for each: two pointed curves, centred on 142 and 143, that overlap almost completely, so no released answer reveals whether Sam took part. A smaller epsilon means more noise, more privacy and less accuracy.Differential privacy: the answer barely depends on any one personsurvey without Sam:true count 142survey with Sam:true count 143add noiseε = 0.5135140145150released answerthe two curves overlap almost completely,so no answer reveals whether Sam took partsmaller ε: more noise, more privacy, less accuracy
Laplace noise with scale 2, as in the lesson's Python with ε = 0.5.
  • Federated learning trains a shared model without collecting the raw data: each phone improves the model on its own data and sends back only the changes, which are averaged on the server. Phone keyboards learn to predict the next word this way.
Federated learningThree phones each hold their own data and train the shared model on it. Amber arrows carry only model updates up to a violet server, which averages them; green arrows bring the improved model back down to every phone. Raw messages never leave the phones, and noise can be added to the updates for extra privacy.Federated learning: the data stays on the phones; only updates travelserveraverages the updatesdatatrains on itsown messagesdatatrains on itsown messagesdatatrains on itsown messagesmodel updates go upthe improved model comes backRaw messages never leave the phones. Noise can be added to updates for extra privacy.
Phone keyboards learn to predict your next word this way.

The simplest rule of all is data minimisation: do not collect, keep or train on personal data you do not need.

Robustness and adversarial examples

In 2014 researchers showed that adding a carefully designed pattern of noise, too faint for a person to see, made an image classifier change its answer for a photo of a panda from "panda" to "gibbon", with 99% confidence. These adversarial examples work against almost every kind of neural network, and in 2018 a few stickers on a real stop sign were enough to make a vision system read it as a speed limit sign.

An adversarial exampleA picture of a panda, which a classifier labels panda with 57.7% confidence, plus 0.007 times a crafted pattern of tiny changes, equals a picture that looks identical to a person but which the classifier labels gibbon with 99.3% confidence. Defences include adversarial training, input checks, and never relying on one model alone.An adversarial example: invisible to people, decisive for the model“panda”57.7% confident+ 0.007 ×a crafted patternof tiny changes=“gibbon”99.3% confidentTo a person the two pictureslook identical.To the model, the second isalmost certainly a gibbon.Defences: adversarial training,input checks, and neverrelying on one model alone.
The confidences are from the 2014 paper that made the panda famous; the pictures here are redrawn as pixel art.

Defences include adversarial training (adding such examples to the training data), checking whether an input looks unlike the training data, and never relying on one model alone where safety matters. The deeper lesson is that a model can score brilliantly on a test set yet fail on inputs that would never fool a person.

Safety and alignment

Alignment is the problem of making AI systems pursue what their designers and users actually intend, not just what they were literally rewarded for (Level 13's reward hacking). As systems become more capable, the questions get more serious:

  • Will a model tell people what they want to hear rather than what is true?
  • Could it help someone cause serious harm, for example with cyber attacks or dangerous chemistry?
  • Does it behave the same when it is not being tested?

Developers evaluate models for dangerous capabilities before release, pay red teams to attack them, train them to refuse harmful requests, and study their insides with interpretability research, looking for the circuits that implement behaviours. In November 2023, 28 countries and the EU signed the Bletchley Declaration on AI safety at Bletchley Park, and the UK set up a government AI Safety Institute, since renamed the AI Security Institute, to test advanced models.

AI and the law

Laws already apply to AI, and new ones are arriving.

  • Data protection: the GDPR, which the UK keeps in its own version, gives people rights over their personal data, including rights around decisions made solely by automated means that have legal or similarly significant effects, and a right to meaningful information about how such decisions are made.
  • Equality law forbids discrimination by protected characteristics, whether a person or an algorithm does it.
  • The EU AI Act, in force since August 2024 with its rules applying in stages, sorts AI systems by risk:
The EU AI Act's risk tiersA pyramid of four tiers. At the top, unacceptable risk: banned, for example social scoring by governments and manipulating people's behaviour. Then high risk: strict requirements, for job screening, credit scoring, exam marking and medical devices. Then limited risk: be transparent, so chatbots must say they are AI and deepfakes must be labelled. At the wide base, minimal risk: no new rules, for spam filters, video games and most everyday AI.The EU AI Act: the higher the risk, the stricter the rulesunacceptablebannedsocial scoring by governments;manipulating people's behaviourhighstrict requirementsjob screening, credit scoring,exam marking, medical deviceslimitedbe transparentchatbots must say they are AI;deepfakes must be labelledminimalno new rulesspam filters, video games,most everyday AI
Most AI systems sit in the wide base; the rules concentrate on the narrow top.

Uses with unacceptable risk, such as social scoring by governments, have been banned since February 2025. High-risk uses, such as screening job applicants, credit scoring, marking exams and safety components of medical devices, must meet requirements for data quality, documentation, human oversight and accuracy. Limited-risk systems must be transparent: people must be told they are talking to a chatbot, and deepfakes must be labelled.

Copyright is still being argued in courts and parliaments: whether training on copyrighted books, art and music without permission is lawful, and who owns what an AI produces.

AI and society

  • Work: AI automates some tasks and assists with others. Most jobs are bundles of tasks, so many will change more than disappear, but the benefits and costs will not fall evenly.
  • Information: cheap fluent text, images and voices make misinformation and scams easier, and make provenance (Level 12) more important.
  • Energy and resources: the International Energy Agency estimated that data centres used about 415 terawatt-hours of electricity in 2024, around 1.5% of the world's electricity, with AI a fast-growing share; cooling also uses water.
  • Power: training frontier models costs so much that few organisations can do it, which concentrates influence.
  • Benefits: AI already helps detect disease in scans, predict protein structures, translate between languages, make technology accessible to people with disabilities, and speed up science.

Engineers do not decide all of these questions alone, but they decide many of the details that settle them.

Hands-on: auditing a model

Fairness metrics for two groups

Python
# Outcomes of a loan model for two groups of applicants.
# tp: would repay, approved; fn: would repay, refused; fp: approved but did not repay; tn: refused, did not repay
groups = {"group A": {"tp": 360, "fn": 40, "fp": 120, "tn": 480},
          "group B": {"tp": 120, "fn": 80, "fp": 40, "tn": 760}}

print(f"{'':8} {'approved':>9} {'TPR':>6} {'FPR':>6} {'precision':>10}")
for name, g in groups.items():
    n = sum(g.values())
    selection = (g["tp"] + g["fp"]) / n                 # demographic parity compares this
    tpr = g["tp"] / (g["tp"] + g["fn"])                 # equal opportunity compares this
    fpr = g["fp"] / (g["fp"] + g["tn"])                 # equalised odds compares TPR and this
    precision = g["tp"] / (g["tp"] + g["fp"])           # predictive parity compares this
    print(f"{name:8} {selection:9.0%} {tpr:6.0%} {fpr:6.0%} {precision:10.0%}")

Explaining one decision

Python
weights = {"income (thousands)": 0.08, "years at address": 0.3, "missed payments": -1.2}
bias = -4.0

def score(person):
    return bias + sum(weights[k] * person[k] for k in weights)

applicant = {"income (thousands)": 38, "years at address": 2, "missed payments": 1}
s = score(applicant)
print(f"score {s:.2f}: {'approved' if s >= 0 else 'refused'}")
print("contribution of each feature:")
print(f"  {'starting point':20} {bias:+6.2f}")
for k, w in weights.items():
    print(f"  {k:20} {w * applicant[k]:+6.2f}")
print("smallest single change that would approve this application:")
for k, w in weights.items():
    target = applicant[k] - s / w                 # the value of this feature that brings the score to 0
    if target >= 0:
        print(f"  {k}: {applicant[k]} -> {target:.1f}")
    else:
        print(f"  {k}: no possible value is enough on its own")

Differential privacy in one line of noise

Python
import random

random.seed(3)
def laplace(scale):
    # the difference of two exponential random numbers has a Laplace distribution
    return random.expovariate(1 / scale) - random.expovariate(1 / scale)

true_count = 142            # e.g. how many students in a survey said they had been bullied
for epsilon in (0.1, 0.5, 1.0, 5.0):
    answers = [true_count + laplace(1 / epsilon) for _ in range(1000)]
    typical_error = sum(abs(a - true_count) for a in answers) / len(answers)
    print(f"epsilon {epsilon:3}: one released answer {answers[0]:7.1f}; typical error {typical_error:5.1f}")

Adding or removing one student changes the true count by at most 1, and with ε = 0.5 the noise is typically about 2, so nobody can tell from the answer whether any one student took part.

Try this

  1. Change group B's numbers so that its true positive rate matches group A's. What happens to its precision?
  2. Give the applicant 0 missed payments. Is the loan approved now? What does the counterfactual say?

Level check

  • Describe real cases where AI systems caused harm, and why
  • Define demographic parity, equal opportunity, equalised odds and predictive parity, and calculate them
  • Explain why fairness definitions can conflict
  • Describe where bias enters and three places to mitigate it
  • Compare ways of explaining a model's decisions, including counterfactuals
  • Explain differential privacy and federated learning
  • Explain adversarial examples and defences against them
  • Explain what alignment means and how developers test for safety
  • Describe the EU AI Act's risk tiers and data protection rights over automated decisions
  • Discuss AI's effects on work, information, energy and power

Key terms you must be able to define

Demographic parity
Equal shares of each group receiving the positive decision.
Equal opportunity
Equal true positive rates: deserving people in each group are approved equally often.
Equalised odds
Equal true positive and false positive rates across groups.
Predictive parity
Equal precision across groups: a positive decision means the same for everyone.
Counterfactual explanation
A statement of the smallest change to the inputs that would have changed the decision.
SHAP
A method that estimates how much each feature pushed one prediction up or down.
Differential privacy
Adding measured noise to results so that no answer reveals much about any individual.
Federated learning
Training a shared model on many devices, sending model updates instead of raw data.
Data minimisation
Collecting and keeping only the personal data a task needs.
Adversarial example
An input altered, often invisibly, to make a model give a wrong answer.
Alignment
Making AI systems pursue what people actually intend.
Red teaming
Deliberately attacking a system to find harmful behaviour before release.
EU AI Act
European law that regulates AI systems according to their level of risk.

Flashcards

DefineDemographic parity
AnswerEqual shares of each group receiving the positive decision.
DefineEqual opportunity
AnswerEqual true positive rates: deserving people in each group are approved equally often.
DefineEqualised odds
AnswerEqual true positive and false positive rates across groups.
DefinePredictive parity
AnswerEqual precision across groups: a positive decision means the same for everyone.
DefineCounterfactual explanation
AnswerA statement of the smallest change to the inputs that would have changed the decision.
DefineSHAP
AnswerA method that estimates how much each feature pushed one prediction up or down.
DefineDifferential privacy
AnswerAdding measured noise to results so that no answer reveals much about any individual.
DefineFederated learning
AnswerTraining a shared model on many devices, sending model updates instead of raw data.

Go further: notes for future AI engineers

The impossibility result, in one line

Precision, recall and the false positive rate are linked by the base rate p, the share of a group that is truly positive:

FPR = p ÷ (1 − p) × (1 − precision) ÷ precision × TPR

If two groups have the same precision and the same TPR but different base rates p, the right-hand side differs, so their false positive rates must differ. Equal precision and equal error rates cannot all hold at once unless the base rates are equal or the model is perfect. You can check it with the hands-on numbers: group A has p = 0.4, group B has p = 0.2.

Model collapse of the commons

As more of the web is written by AI, future models trained on web text learn partly from earlier models, and rare voices, languages and ideas risk being drowned out. Careful data curation, provenance labels and preserving human-written archives are becoming part of responsible AI too.

Misconceptions to avoid

Avoid these
  • Thinking a model is fair because it ignores protected characteristics. Postcodes, names and other proxies can carry the same information.
  • Assuming one fairness measure settles the question. The definitions conflict, so the choice is a judgement about the situation.
  • Treating anonymised data as safe. Records can often be re-identified by matching them with other data.
  • Trusting a high test score as proof of safety. Adversarial and unusual inputs can still break the model.
  • Believing AI law is only coming in the future. Data protection and equality law already apply to automated decisions.
Fun fact

In 2024 the Nobel Prize in Chemistry was shared by Demis Hassabis and John Jumper of Google DeepMind for AlphaFold, which predicts the shapes of proteins, alongside David Baker for designing new proteins. AI's power to help is as real as its power to harm.

Knowledge check

0 of 10 answered
1What does equal opportunity require across groups?
2Group A has 48% of applicants approved and group B 16%. Which fairness definition is clearly broken?
3Why can a model not usually satisfy every fairness definition at once?
4A model removes the "gender" column but still treats women worse. What is the most likely reason?
5"If your income had been £57,500 instead of £38,000, the loan would have been approved." What kind of explanation is this?
6In differential privacy, what happens as ε gets smaller?
7What does federated learning send from each phone to the server?
8What is an adversarial example?
9Under the EU AI Act, which of these is treated as high-risk?
10Which right gives people protection against decisions made solely by automated means with significant effects?
Score 0 / 10

Check you could explain this

15 marks
1A university uses a model to decide which applicants to interview. Explain how it could check whether the model is fair, and why this is not straightforward.6 marks
Explain

Mark scheme0 / 6
  • LCompare outcomes across groups (e.g. sex, ethnicity, disability)
  • LSelection rate / demographic parity
  • LTrue positive rate / equal opportunity among qualified applicants
  • LPrecision / predictive parity, or error rates / equalised odds
  • LThe definitions conflict when base rates differ, so not all can be met
  • LProxies, poor labels, small groups or historical bias complicate it; a value judgement and the affected people are needed
Model answer

The university should audit the model's decisions separately for different groups, such as sex, ethnicity and disability. It can compare the selection rate, the share of each group invited to interview, which tests demographic parity; the true positive rate among applicants who would succeed, which tests equal opportunity; and the precision and false positive rates, which test predictive parity and equalised odds. This is not straightforward because these definitions conflict: when groups have different base rates, a model cannot satisfy them all, so the university has to decide which matters most here, ideally with the people affected. The labels may themselves be biased, other features may act as proxies for protected characteristics, and small groups give unreliable figures.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.

Think this answer or mark scheme is wrong? Report it

2Compare differential privacy and federated learning as ways of protecting people's data.4 marks
Compare

Mark scheme0 / 4
  • LDifferential privacy adds measured random noise to results or training
  • LSo no output reveals much about any one person; ε sets the privacy/accuracy trade-off
  • LFederated learning keeps raw data on the devices and sends only model updates
  • LFederated learning alone can still leak information through updates; the two are often combined
Model answer

Differential privacy adds carefully measured random noise to statistics or to the training process, so that no released result reveals much about whether any one person's data was included; the parameter ε controls how much noise, trading privacy against accuracy. Federated learning instead keeps the raw data on people's own devices: each device improves the model locally and sends only the changes to a server, which averages them. Federated learning stops raw data being collected in one place, but the updates themselves can still leak information, so the two are often combined, with noise added to the updates.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.

Think this answer or mark scheme is wrong? Report it

3Evaluate the risk-based approach of the EU AI Act.5 marks
Evaluate

Mark scheme0 / 5
  • LSystems are sorted into tiers: unacceptable (banned), high, limited and minimal risk
  • LHigh-risk uses (jobs, credit, education, medical) must meet requirements such as data quality, documentation and human oversight
  • LStrength: focuses effort on uses that can harm people, while leaving low-risk uses free to innovate
  • LWeakness: classifying systems can be hard, general-purpose models fit awkwardly, and compliance costs burden small firms
  • LA judgement weighing protection against innovation and enforcement
Model answer

The EU AI Act sorts AI systems by the harm they could do: uses with unacceptable risk, such as government social scoring, are banned; high-risk uses, such as screening job applicants, credit scoring and marking exams, must meet requirements for data quality, documentation, accuracy and human oversight; limited-risk systems such as chatbots must be transparent; and minimal-risk uses such as spam filters face no new rules. Its strength is proportion: the strictest rules fall on uses that affect people's lives, while low-risk innovation is left alone. Its weaknesses are that deciding which tier a system belongs to can be hard, general-purpose models that can be used for anything fit the tiers awkwardly, and compliance costs fall heavily on small companies. Overall it is a sensible framework, but its success will depend on clear guidance and on enforcement.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.

Think this answer or mark scheme is wrong? Report it

Machine mark 0 / 15