AILearn AI
LearnGlossarySources
ID/EN
Learn AI — open material for learning AIEvery lesson cites its original sources.
★Advanced & Frontier Topics
  1. Efficient Inference: Quantization, Distillation, Pruning and Faster Decoding
  2. Mixture of Experts: Bigger Models at the Same Compute
  3. Distributed Training: Many GPUs, One Model
  4. Interpretability: Opening the Black Box
  5. AI Safety & Ethics: Bias, Hallucination, Alignment and Regulation
Modules
  1. ◎ AI Foundations
  2. ∿ Classical Machine Learning
  3. ⌬ Neural Networks
  4. ↘ Training Results & Evaluation
  5. ▦ Deep Learning Architectures
  6. ✎ Large Language Models
  7. ◐ Image Generation
  8. ♪ Audio & Speech AI
  9. ◈ Multimodal, Video & 3D
  10. ↻ Reinforcement Learning
  11. ⚙ ML Development & MLOps
  12. ★ Advanced & Frontier Topics
Learn/Advanced & Frontier Topics

AI Safety & Ethics: Bias, Hallucination, Alignment and Regulation

The main ways AI systems cause harm and how practitioners reduce them: bias and fairness metrics, hallucination, alignment and RLHF/Constitutional AI, red-teaming, privacy, and the regulatory landscape (EU AI Act, NIST AI RMF, Indonesian rules).

Intermediate~28 min·6 references
Key terms
AI safetyAlignmentBias & fairnessRed-teamingHallucinationRLHF (Reinforcement Learning from Human Feedback)

AI now screens job applicants, scores loan requests, triages patients, moderates content and writes code that ships to production. When such systems fail, the harm is real: qualified people rejected, false information delivered confidently, private data leaked, or tools misused at scale. AI safety and ethics is the engineering discipline of anticipating these failures, measuring them and reducing them — not an optional add-on after the model is finished. As a practitioner, you will be expected to answer: *who could this hurt, how would we know, and what did we do about it?*

≈
Analogy: car safety
Cars became safe through layers: better design (crumple zones ≈ alignment training), crash tests before sale (evaluations and red-teaming), seatbelts and airbags for when things go wrong (guardrails, filters, human oversight), and traffic law with inspections (regulation and audits). No single layer is enough; together they make failures rarer and less severe.
RiskExampleTypical mitigations
Bias / unfairnessCV screener downgrades women because past hires were mostly menData audits, fairness metrics per group, constraints, human review
HallucinationChatbot invents a regulation number or a court caseRAG with citations, abstention, verification, evals
MisuseVoice cloning for scams; malware helpUsage policies, refusals, monitoring, provenance/watermarks
PrivacyModel regurgitates phone numbers from training dataData minimisation, PII filtering, differential privacy, access control
SecurityPrompt injection makes an agent email private filesLeast privilege, input isolation, confirmation for risky actions
MisalignmentAgent games its reward or objective instead of doing the taskBetter specifications, RLHF/CAI, oversight, interpretability

1. Bias and fairness

Bias enters at every stage (Mehrabi et al.)[1]: historical bias (the world itself was unfair), representation bias (some groups are under-sampled — e.g. speech data with few eastern-Indonesian accents), measurement bias (a proxy label like “arrests” standing in for “crime”), aggregation bias (one model for groups that behave differently) and deployment bias (using a model outside its intended context). Simply deleting the sensitive attribute (“fairness through unawareness”) rarely works, because proxies such as postcode, school or name carry the same information.

Fairness is measured by comparing error and decision rates across groups A and B. Common criteria: demographic parity (equal approval rates), equal opportunity (equal true-positive rates among people who truly qualify) and equalized odds (equal true- *and* false-positive rates). When base rates differ between groups, these criteria generally cannot all be satisfied at once — choosing one is a value judgement that should involve stakeholders, not just engineers.

DP gap = |P(ŷ=1 | A) − P(ŷ=1 | B)| EO gap = |P(ŷ=1 | y=1, A) − P(ŷ=1 | y=1, B)|
Example: loans approved for 60% of group A but 35% of group B → demographic-parity gap of 0.25.
In words: Read the first as “how different are approval rates between the two groups” (demographic parity) and the second as “how different are approval rates among people who truly qualify” (equal opportunity). 0 means perfectly equal on that criterion.
Symbols(hover a symbol in the formula)
DP gap
demographic-parity gap
EO gap
equal-opportunity gap (difference in true-positive rates)
P(ŷ=1 | A)
probability the model approves (predicts 1) for someone in group A
ŷ
y-hat, the model's decision
y=1
the person truly qualifies (true label positive)
|
inside P(… | …): “given”; the outer |…| is the absolute value
A
group A (e.g. one region or gender)
B
group B
▸Worked example
Group A: 60 of 100 approved; group B: 35 of 100 → DP gap = |0.60 − 0.35| = 0.25 Among qualified people: A 54 of 60 approved (0.9), B 28 of 40 (0.7) → EO gap = |0.9 − 0.7| = 0.2

2. Hallucination

LLMs are trained to produce *plausible* continuations, not *true* ones, so they can state invented facts, quotes, references or legal articles fluently — Hallucination. Risk is highest for rare facts, numbers, recent events and long chains of reasoning. Mitigations: ground answers in retrieved documents (RAG) and show citations; let the model say “I don't know”; lower Temperature for factual tasks; verify with tools (calculators, code execution, search); and measure hallucination rates with task-specific Evals before deployment.

3. Alignment

Alignment means getting AI systems to do what their designers and users actually intend, and to avoid harmful behaviour even in situations nobody anticipated. Amodei et al.'s *Concrete Problems in AI Safety*[2] framed five practical research problems that still organise the field:

  • Avoiding negative side effects — achieving the goal without breaking things along the way.
  • Avoiding reward hacking — not exploiting loopholes in the objective (specification gaming).
  • Scalable oversight — supervising behaviour that is too costly or complex for humans to check every time.
  • Safe exploration — learning without trying catastrophic actions.
  • Robustness to distributional shift — behaving sensibly (or knowing it doesn't know) on inputs unlike the training data.

Today's main practical alignment tools are RLHF (learn a reward model from human preferences, then optimise the policy) and Constitutional AI (Bai et al., 2022)[3]: the model critiques and revises its own outputs against a written list of principles, and AI-generated preference labels (RLAIF) replace most human harmfulness labels — making the values explicit and reducing the burden on human labellers. Both reduce harmful outputs, but neither guarantees safety: models can still be jailbroken, be sycophantic, or behave differently in deployment than in testing.

4. Red-teaming

Red-teaming means deliberately attacking your own system to find failures before others do: jailbreak prompts, role-play tricks, multilingual and code-switched attacks (safety training is often weaker in lower-resource languages, including Indonesian and regional languages), prompt injection hidden in web pages or documents, and probing for dangerous capabilities. Ganguli et al.[4] red-teamed models of several sizes with ~39,000 human attacks and released the dataset; they found RLHF-trained models became harder to red-team as they scaled, while other model types did not show that trend. Red-teaming combines human experts, automated attacks (one model generating attacks against another) and structured reporting, and it must be repeated whenever the model or its tools change.

5. Privacy

Large models can memorise and regurgitate rare training strings such as names with phone numbers or API keys. Good practice: collect only what you need, filter personally identifiable information (PII) before training, restrict who can query fine-tuned models trained on private data, and, where strong guarantees are needed, use differential privacy (e.g. DP-SGD, which clips per-example gradients and adds noise). In Indonesia, UU No. 27 Tahun 2022 tentang Pelindungan Data Pribadi (UU PDP) sets legal duties for processing personal data — including a lawful basis such as consent, data-subject rights, and breach notification — that apply to AI training and inference pipelines too.

6. Regulation and governance

The EU AI Act (Regulation (EU) 2024/1689)[5] is the first comprehensive AI law. It applies to anyone placing AI systems on the EU market or whose system's output is used in the EU — including companies outside Europe — and regulates by risk level. It entered into force on 1 August 2024; prohibitions applied from February 2025 and general-purpose AI obligations from August 2025, with most high-risk obligations phased in afterwards (check the current official timeline, as the EU has proposed adjustments). Fines for prohibited practices reach €35 million or 7% of global annual turnover.

Risk tierExamplesObligations
Unacceptable (banned)Social scoring, manipulative techniques exploiting vulnerabilities, untargeted scraping of faces for recognition databases, emotion recognition at work or schoolProhibited (narrow exceptions)
High riskHiring, credit scoring, education access, critical infrastructure, medical devices, law enforcement, migrationRisk management, data governance, technical documentation, logging, human oversight, accuracy & robustness, conformity assessment
Transparency riskChatbots, deepfakes, AI-generated contentTell people they are interacting with AI; label synthetic media
Minimal riskSpam filters, game AI, most recommender featuresNo new obligations (voluntary codes)
General-purpose AI modelsFoundation models / LLMsTechnical documentation, copyright policy, training-data summary; extra evaluation, red-teaming and incident reporting for models with systemic risk

Outside the EU, the NIST AI Risk Management Framework (AI RMF 1.0)[6] is a voluntary, widely used guide organised around four functions — Govern, Map, Measure, Manage — for building trustworthy AI (valid, safe, secure, accountable, explainable, privacy-enhanced, fair). In Indonesia, besides UU PDP, the Ministry of Communication and Informatics issued Surat Edaran Menkominfo No. 9 Tahun 2023 on AI ethics (principles such as inclusivity, humanity, security, transparency, accountability and personal data protection), and national AI governance continues to develop — check current regulations for your sector (e.g. OJK for financial services).

The knobs

knobdecision threshold (per use case or group)
What it is
The score above which a model approves, flags or refuses. In moderation and safety filters, the threshold sets how aggressively content is blocked.
↑ If you increase it
Fewer false alarms and over-refusals, but more harmful content (or unqualified applicants) slips through.
↓ If you decrease it
Catches more harm, but over-blocks legitimate users — itself a harm, often concentrated on dialects or minority groups the classifier misreads.
Typical values
Choose from precision/recall curves per group, with stakeholders; re-check per language.
knobtemperature (factual tasks)
What it is
Sampling randomness of an LLM.
↑ If you increase it
More creative and varied, but more likely to wander into unsupported claims.
↓ If you decrease it
More consistent, reproducible answers; reduces random fabrications but does not fix confident errors the model believes.
Typical values
0–0.3 for factual Q&A and extraction; higher for brainstorming.
knobprivacy budget ε (differential privacy)
What it is
Bounds how much any single person's data can change the trained model; smaller ε = stronger privacy. (Not the same ε as in ε-greedy.)
↑ If you increase it
Better model accuracy, weaker privacy guarantee.
↓ If you decrease it
Stronger protection against memorisation and membership inference, but more noise and lower accuracy — especially for small groups, which can worsen fairness.
Typical values
Single digits (≈ 1–10) are common in practice; report ε together with δ.

In code: a fairness audit with Fairlearn

python
from fairlearn.metrics import (MetricFrame, selection_rate,
                               demographic_parity_difference, equalized_odds_difference)
from sklearn.metrics import accuracy_score, recall_score

group = df_test["jenis_kelamin"]            # sensitive attribute, kept for auditing only
mf = MetricFrame(
    metrics={"accuracy": accuracy_score, "recall": recall_score,
             "selection_rate": selection_rate},
    y_true=y_test, y_pred=y_pred, sensitive_features=group)

print(mf.by_group)                          # one row per group
print(mf.difference())                      # largest gap per metric
print("DP gap:", demographic_parity_difference(y_test, y_pred, sensitive_features=group))
print("EO gap:", equalized_odds_difference(y_test, y_pred, sensitive_features=group))
Auditing requires keeping the sensitive attribute (securely) even if the model never sees it. Repeat for every relevant group, including intersections.
!
Common pitfalls
One aggregate number hides harm: 95% accuracy overall can mean 70% for a minority group — always disaggregate. Removing the protected attribute is not enough (proxies). One-off audits go stale: data drift changes fairness and safety over time, so monitor in production. Over-refusal is also a failure: a model that refuses legitimate medical or legal questions harms users. Safety-washing: publishing principles without evaluations, documentation and accountability is not governance. English-only testing misses failures in Indonesian, regional languages and code-switched text.
▸Go deeper: why fairness criteria conflict

Suppose 50% of group A and 20% of group B truly repay a loan, and the model is equally accurate for both. Demographic parity demands equal approval rates, which forces either rejecting many qualified A applicants or approving many unqualified B applicants — breaking equal error rates. Conversely, a perfectly calibrated score with equal error rates will approve A more often. Formal results (Kleinberg et al.; Chouldechova) show calibration and equal error rates cannot hold together when base rates differ, except for a perfect predictor. Fairness is therefore a choice about which errors matter most, for whom — which is why documentation and stakeholder input are part of the engineering.

Quiz

1.
A loan model approves 60% of men and 45% of women. Which fairness metric does this directly describe?
2.
A team removes the “ethnicity” column, but the model still treats groups very differently. What is the most likely cause?
3.
Which approach most directly reduces hallucinated facts in a customer-support chatbot?
4.
What distinguishes Constitutional AI from standard RLHF?
5.
Under the EU AI Act, a CV-screening system used to rank job applicants falls into which category?
Score: 0/5

References

  1. [1]
    A Survey on Bias and Fairness in Machine Learning
    PaperMehrabi et al.2019arxiv.org
  2. [2]
    Concrete Problems in AI Safety
    PaperAmodei et al.2016arxiv.org
  3. [3]
    Constitutional AI: Harmlessness from AI Feedback
    PaperBai et al.2022arxiv.org
  4. [4]
    Red Teaming Language Models to Reduce Harms: Methods, Scaling Behaviors, and Lessons Learned
    PaperGanguli et al.2022arxiv.org
  5. [5]
    Regulation (EU) 2024/1689 — Artificial Intelligence Act (official text)
    DocsEuropean Union2024eur-lex.europa.eu
  6. [6]
    AI Risk Management Framework (AI RMF 1.0)
    DocsNIST2023nist.gov
← Previous
Interpretability: Opening the Black Box