Contents Responsible Practice Code Course home

Chapter 27Responsible NLP

After this chapter you will be able to

  • trace each harm in this chapter to a mechanism established earlier in the book;

  • name the four places where bias enters and the one that survives careful modelling;

  • run an association test, a disaggregated evaluation and a counterfactual test, and compare three fairness criteria on the same counts;

  • say what debiasing an embedding space can and cannot do;

  • name the three robustness failures, read a calibration table, and compute a drift index;

  • write a model card and say what attention weights and reasoning traces do and do not explain.

This chapter builds on the whole book, and especially Chapters 9, 15 and 24.

Why this chapter is not an appendix

It would be easy to read this chapter as the ethics section at the end, to be agreed with and skipped. That reading is available and it is wrong, for a technical reason. Every harm described here traces to a mechanism established earlier in this book, and every measurement uses a tool the reader has already built.

Bias is the distributional hypothesis of Chapter 6 working as specified, and hallucination is Equation (19.1) being minimised. The material is therefore continuous with the rest, and it belongs at the end only because it needs everything before it.

Where bias comes from

Chapter 9 measured social regularities in a word embedding using WEAT, Equation (9.14), and the finding was that a corpus of human text contains human associations, and that a method built to learn associations learns those too. This is the mechanism, and it does not change at scale, since a larger model trained on more text learns the same associations more thoroughly.

Four places it enters

The corpus comes first, because web text over-represents some languages, regions, registers and viewpoints, which Chapter 2 raised as the choice of corpus, the same question with higher stakes. The labels come next, since annotation reflects the annotators, and who was hired, what they were told and what they were paid all show up in the data. The objective is third, because cross-entropy rewards fitting the training distribution, so a model that reproduces a skew faithfully is scoring well. And the deployment is fourth, because a model applied to a population unlike its training data will fail on that population specifically while the aggregate metric will not show it. The fourth is the one that survives the most careful modelling work, because it is not a property of the model at all.

Figure 27.1. Four places where bias enters. The first three are properties of the data and the objective. The fourth is a property of where the model is used, and it survives careful modelling.

Measuring it

Nothing here requires new machinery. Association tests such as WEAT quantify how strongly two concept sets sit near two attribute sets, and the score has a sign and a magnitude, with Chapter 9 showing what it does and does not license you to conclude.

Disaggregated evaluation is the most useful practice in this chapter, being Chapter 15’s per-class table applied to groups and not labels, so report your metric separately for each population you can identify. A macro-F1F_1 of 0.820.82 computed over the pooled test set can hide 0.910.91 on one group and 0.580.58 on another, and the pooled figure sits above the average of the two because the stronger group is the larger one. The pooled figure is the number that gets reported.

Figure 27.2. The example from the text. A pooled macro-F1F_1 of 0.820.82 hides 0.910.91 on one group and 0.580.58 on another. The pooled value sits above the simple average of the two, 0.7450.745, because the stronger group is the larger.

Counterfactual testing changes one attribute in an input and asks whether the output changes, so swap a name, a pronoun or a dialect feature, and if the prediction moves then the model is using that attribute. All three are things you can run this week on a model you already have.

A disaggregated table, in counts

A pooled score is easy to produce and hard to interrogate, so work from the counts. A loan classifier approves or declines 10001000 applications, and approving is the positive class. The counts for the two groups follow.

TP FP FN TN nn
group A 280 40 40 370 730
group B 60 50 60 100 270
pooled 340 90 100 470 1000

Accuracy, precision, recall and F1F_1 come from these counts exactly as in Chapter 15.

accuracy precision recall F1F_1
group A 0.890 0.875 0.875 0.875
group B 0.593 0.545 0.500 0.522
pooled 0.810 0.791 0.773 0.782

The pooled F1F_1 of 0.7820.782 is a correct average over all applications, and it is a poor description of what group B experiences, which is 0.5220.522. The simple average of the two group scores is 0.6980.698, below the pooled value, because group A is 7373 per cent of the applications. The counts also support the parity checks that people ask for.

quantity group A group B gap
selection rate 0.438 0.407 0.031
true positive rate 0.875 0.500 0.375
false positive rate 0.098 0.333 −0.236-0.236
precision 0.875 0.545 0.330

The selection rates are close, so a check for demographic parity, which asks whether both groups are approved at the same rate, would pass. The error rates tell a different story. A deserving applicant in group B is approved half the time against 87.587.5 per cent in group A, and an undeserving applicant is approved a third of the time against about one in ten.

F1 for two groups and pooled, then approval, true positive and false positive rates per group
A pooled score can hide a group the model serves badly. Similar approval rates can coexist with very different error rates, so results need reporting for each group.

Three criteria that cannot all hold

Equal error rates, equal approval rates and equal precision are each a reasonable demand, and they cannot all be met when the groups differ in how many applicants deserve an approval, which is the base rate. Give two groups the same true positive rate, 0.80.8, and the same false positive rate, 0.10.1, with 10001000 applicants each.

base rate TP FN FP TN precision approved
group C 0.50 400 100 50 450 0.889 0.45
group D 0.20 160 40 80 720 0.667 0.24

The error rates are equal by construction, yet precision is 0.8890.889 for group C and 0.6670.667 for group D, and the approval rates are 0.450.45 and 0.240.24, because both depend on how common the positives are. Forcing the precision to match would push one of the error rates apart. Which criterion to prefer is a judgment about the harm each kind of error does, and no metric makes that judgment for you.

Swapping a name

The model in this example is a toy with a flaw built in. It adds a small amount for or against a first name, as a model trained on a skewed corpus might. Take three sentences and four names, which gives 3×(42)=183 \times \binom{4}{2} = 18 pairs that differ only in the name.

sentence Emily Greg Lakisha Jamal
NAME said the delivery was fine. pos pos pos neg
NAME called the service adequate. pos pos neg neg
NAME described the staff as helpful but slow. pos pos neg neg

The prediction changes in 1111 of the 1818 pairs, a rate of 0.6110.611. On the first sentence only Jamal is separated from the rest, and on the other two Lakisha and Jamal are separated from Emily and Greg. A rate of zero would show that the model ignores the name on these sentences. A rate above zero shows that it uses the name, and the table says which names and in which direction.

What mitigation can and cannot do

Debiasing an embedding space by projecting out a direction (removing from every vector its component along a chosen bias direction) reduces the measured score. It has repeatedly been shown to reduce the measurement more than the behaviour, because the information survives in other directions. That deserves plain statement, since a metric that improves while the behaviour does not is worse than no metric. This is Goodhart’s law from Chapter 23 arriving somewhere it does real harm. Corpus curation, disaggregated reporting and deployment limits are slower and they address the source.

Projection, in numbers

A small space shows the gap between the score and the behaviour. It has four dimensions, two of which carry gender, and two sets of male and female words, one used to find the bias direction and one held out. Career and family words are the targets, and the direction is the mean of the male vectors minus the mean of the female ones.

measurement before after
mean cosine of career words with the direction +0.533+0.533 0.0000.000
mean cosine of family words with the direction −0.533-0.533 0.0000.000
WEAT effect size dd, held-out words +1.825+1.825 +1.072+1.072

Subtracting each vector’s component along the direction takes the direction score to zero, which is what the method promises and what any score computed along that direction will report. The held-out test still gives d=1.072d = 1.072, down from 1.8251.825 by about two fifths and a long way from zero, because gender information also lives in the other dimensions. The headline number improved by construction, and the behaviour improved much less.

Robustness and its limits

There are three failure classes, each with a known cause and no complete fix. Hallucination is the first. A model trained to produce likely text produces plausible falsehoods, because a plausible falsehood is likely text. The practical responses are retrieval, as in Chapter 22, and a system that can say it does not know.

Adversarial input is the second, where small and deliberate perturbations change outputs, and for text-driven systems the important case is prompt injection, which Chapter 24 argued must be defended architecturally and not linguistically. Distribution shift is the third, where performance degrades as live data drifts from training data, and the response is monitoring, not a better model.

None of these is solved, and the systems that work in practice acknowledge them. They express uncertainty, keep a human in the loop for consequential decisions, and fail safely.

Knowing when it does not know

A system can only say that it does not know if its confidence scores mean something. Calibration compares what the model says with how often it is right. Sort 10001000 predictions into bins by confidence.

bin nn confidence accuracy gap
0.5 to 0.6 150 0.55 0.52 0.03
0.6 to 0.7 200 0.65 0.58 0.07
0.7 to 0.8 250 0.75 0.66 0.09
0.8 to 0.9 250 0.85 0.74 0.11
0.9 to 1.0 150 0.95 0.83 0.12

The expected calibration error is the sum over bins of n/Nn/N times the absolute gap, which is 0.08650.0865 here. Every bin is overconfident, and the top bin says 0.950.95 and is right 8383 per cent of the time. A model can abstain below a threshold and hand those cases to a person.

answer only above answered coverage accuracy
0.5 1000 1.00 0.668
0.7 650 0.65 0.730
0.8 400 0.40 0.774
0.9 150 0.15 0.830

Raising the threshold buys accuracy with coverage. At 0.80.8 the model answers 4040 per cent of the cases at 0.7740.774 accuracy and the other 6060 per cent go to a person. Because the model is overconfident, at thresholds of 0.80.8 and 0.90.9 the accuracy falls below the threshold, so a threshold chosen from the confidence scores alone promises more than it delivers.

Accuracy bars against stated confidence in five bins, then accuracy at abstention thresholds
A model's stated confidence should match how often it is right. Overconfident scores make a threshold promise more than it delivers, and abstaining trades coverage for accuracy.

Noticing a shift

Distribution shift can be watched without labels. The population stability index compares the share of live inputs in each bucket with the share in training, as the sum of (live−train)ln⁡(live/train)(\text{live} - \text{train}) \ln(\text{live}/\text{train}) over the buckets. Take input length in four buckets.

input length training live term
1 to 10 words 0.40 0.20 0.1386
11 to 30 words 0.35 0.30 0.0077
31 to 100 words 0.15 0.25 0.0511
over 100 words 0.10 0.25 0.1374
index 0.3349

A common rule of thumb reads an index below 0.10.1 as stable, from 0.10.1 to 0.250.25 as a moderate shift and above 0.250.25 as a large one, so this shift is large. The check needs no labels, so it can run on every day of live traffic, and it tells you to look at the outputs before the accuracy has had time to fall.

Transparency and accountability

Document what you built

Two practices help here, and both are cheap relative to what they prevent. Model cards record intended use, training data, evaluation results including disaggregated ones, and known limitations. Data statements record how a corpus was collected, from whom, with what consent, and what it does not cover. Both exist because the alternative is a system whose limits are discovered by the people harmed by them.

A model card for the loan classifier above can be short, and it should state the things the tables of this chapter measured.

intended use ranking applications for a loan officer to review. Not for automatic decline.
training data past decisions of one lender, so it reproduces that lender’s approvals, including any skew in them.
overall result accuracy 0.810 and F1F_1 0.782 on the 10001000 applications above.
by group group A F1F_1 0.875 and group B F1F_1 0.522. True positive rates 0.875 and 0.500.
limitations weaker for group B on every error measure. Approval rates are similar, so a parity check alone would not show this. Not tested on applicants unlike the training population.
monitoring population stability index of the input length, reviewed weekly.

The limitations row is the one a reader needs most, and it is written from the disaggregated table and not from the overall score.

Explanation, with care

Attention weights are often presented as explanations, and they are not, for a reason that matters. Attention says where information was read from without saying how that information was used, and models with very different attention patterns can produce identical outputs.

A chain-of-thought trace is a plausible narrative, not a record of the computation. Chapter 20 gave the mechanism, which is that the model is generating tokens that give it room to compute, and those tokens need not describe what the forward pass did. Both are useful diagnostics and neither is a guarantee, and presenting either as one is a transparency failure dressed as transparency.

Who is accountable

A system’s behaviour is a shared responsibility, and model developers, deployers and operators each control something the others do not. The one position that is not available is the one that blames the model, because a model has no agency and responsibility therefore does not stop there. It stops with whoever chose to deploy it, for what, and with what checks.

The end of the beginning

This book followed one idea from its first chapter to its last. Language resists rules and yields to numbers and to learning, so we counted words, turned counts into geometry, geometry into probability, and probability into models that converse.

At every stage the same three questions mattered most. What are we counting, what are we optimising, and how do we know it worked? Those questions do not go out of date, and they are what remains when the current architectures have been replaced.

What you should be able to do now

You should be able to read a paper and identify its representation, its objective and its evaluation. You should build a baseline before reaching for a large model, and know why the baseline is often close enough. You should choose an evaluation before running an experiment, and hold to it when the result is disappointing. You should diagnose a failure by looking at the outputs instead of the score. And you should say what a system cannot do, as precisely as what it can. The last one is the hardest. A system whose limits are stated can be trusted inside them.

Summary

Every harm in this chapter traces to a mechanism established earlier. Bias is the distributional hypothesis working as specified, and it enters through the corpus, the labels, the objective and the deployment. Association tests, disaggregated evaluation and counterfactual testing measure it with tools the reader already has, and disaggregation is the most useful because a pooled score can hide a failing group. On the worked counts, approval rates were nearly equal while the true positive rates were 0.8750.875 and 0.5000.500, and equal error rates cannot coexist with equal precision when base rates differ. Projecting out a bias direction lowers the measured score more than the behaviour. Hallucination, adversarial input and distribution shift are not solved, and systems that work express uncertainty, keep a person in the loop and fail safely. Calibration shows whether the stated confidence can be trusted, abstention trades coverage for accuracy, and a population stability index watches the inputs without labels. Model cards and data statements record limits, attention weights and reasoning traces are diagnostics, not explanations, and responsibility stops with whoever chose to deploy the model. The three questions that remain are what we count, what we optimise and how we know it worked.

Key terms

disaggregated evaluation. reporting a metric separately for each identifiable group.

counterfactual testing. changing one attribute of an input and checking whether the output changes.

model card. a document recording intended use, data, disaggregated results and limits.

data statement. a document recording how a corpus was collected and what it does not cover.

calibration. the match between a model’s stated confidence and how often it is right.

population stability index. a score comparing the distribution of live inputs with that of the training inputs.

hallucination. a plausible but false output.

distribution shift. a change in live data away from the training data.

Run it. code/worked_examples/responsible.py produces every table in this chapter except the model card. --groups gives the counts and parity checks, --criteria the base rate table, --weat the projection, --counterfactual the name swap, --calibration the bins and thresholds, and --drift the index.

Run it

Further reading.

Caliskan et al. (2017) is the WEAT paper, and a model of careful measurement. Bender et al. (2021) argue about the risks of scale and the consequences of corpus composition. Mitchell et al. (2019) propose model cards and Bender and Friedman (2018) data statements. Jurafsky and Martin (2025) treat ethics alongside the technical material throughout, which is the arrangement this book has tried to follow.

Practice problems

27.1 Pooled and per group. Two groups have macro-F1F_1 of 0.910.91 and 0.580.58 and make up 7373 and 2727 per cent of the test set. Compute the size-weighted average, compare it with the pooled figure of this chapter, and say what the simple average would have reported.

27.2 A WEAT sign. A WEAT score is +0.4+0.4 for two target sets and two attribute sets. State in a sentence what the sign says, and what it does not say about any single word or any single person.

27.3 How many pairs? A counterfactual test swaps one of three names and one of four dialect features. How many input pairs does a full factorial test of one sentence need, and why is that already a lot?

27.4 Trace a harm to a mechanism. Choose one failure from this chapter and trace it back to a specific equation or method earlier in the book. State the mechanism, not the sentiment.

27.5 Selection and error rates. Group P has 3030 true positives, 1010 false positives, 2020 false negatives and 140140 true negatives. Group Q has 1212, 88, 1212 and 168168. Compute the selection rate, the true positive rate and the false positive rate of each group, and say which parity check would look worse.

27.6 A calibration error. Three confidence bins hold 100100, 300300 and 100100 predictions, with mean confidence 0.60.6, 0.80.8 and 0.950.95 and accuracy 0.50.5, 0.70.7 and 0.90.9. Compute the expected calibration error.

Build and measure

27.7 A reliability table. Take a classifier you have built and sort its dev-set predictions into five confidence bins. Report the expected calibration error and the coverage and accuracy at three abstention thresholds. State at which threshold the accuracy first falls below the threshold itself.

27.8 Disaggregate. Take a classifier you have built. Split your test set by any attribute you can identify and report the metric per group. Compare the worst group against the aggregate. Would the aggregate have told you what you learned?

27.9 Counterfactual test. Construct twenty input pairs differing in exactly one attribute. Measure how often the prediction changes. State what a non-zero rate does and does not prove.

27.10 Debiasing that is not. Explain why projecting out a bias direction can reduce a WEAT score without changing behaviour. Design a test that would distinguish the two outcomes.

In practice

27.11 Write a model card. Produce one for a system you have built: intended use, training data, disaggregated evaluation, known limitations. The limitations section should be the longest one.

27.12 Attention is not explanation. Construct or describe two models with different attention patterns and identical outputs. What does this show about attention weights as an explanation, and what are they still good for?

27.13 Say what it cannot do. For a system you have built, write the paragraph you would give a user describing its limits. Then check each claim against an experiment you have actually run, and delete anything you cannot support.

27.14 Who is accountable? A deployed model denies a loan on the basis of an association it learned from the corpus. List who controlled each of the four entry points of bias, and say who is accountable.

27.15 Pick the threshold. A triage assistant answers only above a confidence threshold and hands the rest to a clinician. Using a reliability table like the one in this chapter, say how you would pick the threshold, who bears the cost of a wrong answer and who bears the cost of a handover, and what you would monitor after launch.

27.16 A fail-safe design. Design the fallback for a medical-question assistant when its confidence is low. Say what it says, who it hands over to, and how you would test that the fallback works.

Code for this chapter

Each one reproduces the tables above. Run it in the page, change an input and watch which numbers move.

  • responsible.pyMeasuring a model's harms

    Per-group metrics, three fairness criteria that cannot all hold, a WEAT score before and after debiasing, a counterfactual name swap, calibration with abstention, and a drift index. Every model is a toy, so the tables show how to measure.

    runs in your browser Run it

From Natural Language Processing: From Corpus Statistics to Grounded LLMs, by Ramaseshan Ramachandran.