TExcelTAD
Home › Generative AI & LLMs › Bias & Fairness

Bias & Fairness

LLMs learn from huge amounts of human-written text, and human text contains stereotypes, imbalances and blind spots. Models can absorb and reproduce these patterns: associating professions with one gender, describing some groups more negatively, working better in some languages or dialects than others. Fairness work aims to measure these effects and reduce harm, especially when AI influences decisions about people.

Where bias comes from

Source Example
Training data some groups are under-represented or described stereotypically
Labels and feedback annotators' own assumptions shape fine-tuning and preference data
Task design using a proxy (e.g. postcode) that correlates with a protected attribute
Deployment a model tested on one population is used on another
Language coverage fewer training documents in many languages → lower quality there

Bias in data: a co-occurrence probe

Statistical models learn associations from what co-occurs in text. If a corpus mostly pairs "nurse" with "she" and "engineer" with "he", any model trained on it will learn that skew. Here we measure it on a tiny, deliberately skewed corpus:

python · try it yourself
corpus = [
    "the nurse said she would help", "the nurse said she was tired", "the nurse said he would call",
    "the engineer said he fixed it", "the engineer said he was late", "the engineer said she checked it",
    "the engineer said he would test", "the teacher said she would explain", "the teacher said he would explain",
]

def pronoun_counts(job):
    she = sum(1 for s in corpus if job in s and " she " in f" {s} ")
    he = sum(1 for s in corpus if job in s and " he " in f" {s} ")
    return she, he

for job in ["nurse", "engineer", "teacher"]:
    she, he = pronoun_counts(job)
    print(f"{job:<9} she={she} he={he}  P(she|{job}) = {she / (she + he):.2f}")
nurse     she=2 he=1  P(she|nurse) = 0.67
engineer  she=1 he=3  P(she|engineer) = 0.25
teacher   she=1 he=1  P(she|teacher) = 0.50

A model trained only on this text would complete "The engineer said …" with "he" three times as often as "she". Real corpora are enormous, but researchers find similar patterns in them, which is why model developers measure and mitigate such associations.

Counterfactual testing

A practical test for your own application: change only a demographic detail in the input (a name, a pronoun) and check whether the output changes. Ideally it shouldn't, unless the detail is relevant. The "model" here is a stand-in scoring function with a hidden bias, to show what the test catches:

python · try it yourself
def screen_cv(text):
    """Stand-in for an AI CV screener (with a deliberately planted bias)."""
    score = 0
    score += 3 * text.count("Python")
    score += 2 * text.count("team lead")
    if "Ahmed" in text:          # the planted bias the test should reveal
        score -= 2
    return score

template = "{name}: 5 years of Python, Python testing, team lead for 2 years."
names = ["Anna", "Ahmed", "Mei", "John"]

scores = {name: screen_cv(template.format(name=name)) for name in names}
for name, s in scores.items():
    print(f"{name:<6} score={s}")
spread = max(scores.values()) - min(scores.values())
print("PASS" if spread == 0 else f"FAIL: identical CVs differ by {spread} points")
Anna   score=8
Ahmed  score=6
Mei    score=8
John   score=8
FAIL: identical CVs differ by 2 points

With a real model you would run many templates, many names, and repeated samples, then compare score distributions. Tools exist to automate such tests, but the idea is this simple.

Measuring outcomes: demographic parity

When a system makes decisions (approve / reject), one basic fairness metric compares the selection rate per group:

python · try it yourself
import pandas as pd

decisions = pd.DataFrame({
    "group":    ["A"] * 10 + ["B"] * 10,
    "approved": [1, 1, 1, 0, 1, 1, 0, 1, 1, 0,   1, 0, 0, 1, 0, 0, 1, 0, 0, 1],
})
rates = decisions.groupby("group")["approved"].mean()
print(rates.to_string())
ratio = rates.min() / rates.max()
print(f"selection-rate ratio: {ratio:.2f}")
print("flag for review" if ratio < 0.8 else "within the 0.8 rule of thumb")
group
A    0.7
B    0.4
selection-rate ratio: 0.57
flag for review

The "0.8 rule" (four-fifths rule) is a common screening heuristic, not a proof of fairness or unfairness. Fairness has several competing definitions (equal selection rates, equal error rates, calibration), and they generally cannot all be satisfied at once — choosing one is a value judgement that should involve the people affected.

What you can do as a builder

  • Don't use LLMs for high-stakes decisions about people (hiring, credit, housing, medical triage) without rigorous evaluation, human oversight and legal review — many jurisdictions regulate these uses.
  • Test with counterfactuals and diverse inputs, including multiple languages and dialects.
  • Write explicit instructions ("Do not infer gender, age or ethnicity from names") — helpful, but verify with tests.
  • Measure outcomes by group where you lawfully can, and monitor over time.
  • Offer recourse: a way for people to question and correct an AI-assisted decision.

Test yourself

What is a counterfactual fairness test?

  1. Testing the model with no input
  2. Changing only a demographic detail (like a name) and checking whether the output changes
  3. Comparing two different models' prices
  4. Removing all names from the training data

Where can bias in an LLM come from?

  1. Only from the tokenizer
  2. Training data, human feedback, task design and deployment context
  3. Only from the user's prompt
  4. Bias can't exist in software

Group A is approved 70% of the time and group B 40%. What is the selection-rate ratio?

  1. 0.40
  2. 0.57
  3. 0.70
  4. 1.75