Module 30
Interpretability, Robustness, Privacy and Security
How do we know whether to trust a model, why it produces a result, and when it will stop working?
- lessons
- 39
- duration
- 68 h
- concepts
- 213
- available in English
- 39 / 39
- completed by you
0 of 39
Where it fits
Overview
Study model reliability from complementary angles: quantify uncertainty with guarantees through conformal prediction and shift and OOD detection, explain decisions with SHAP and attributions to features and data, and open the black box through mechanistic interpretability, probing, circuits, induction heads, superposition, and sparse autoencoders in models you train. Study attacks and defenses including adversarial examples, certified robustness, poisoning, extraction, jailbreaks, prompt injection, and agent security. Protect data with differential privacy, DP-SGD, and federated learning. The module closes with fairness, red teaming, risk evaluation, and technical alignment problems. Each technique is implemented from scratch and evaluated using an appropriate adversarial protocol.
Why it matters
For an application-security leader, this module connects existing practice with AI through threat models, the attack surface of an ML pipeline, and the security of LLM agents with tools. For research, mechanistic interpretability helps investigate what algorithm a model has learned. Conformal prediction and differential privacy provide finite-sample mathematical guarantees for deployed systems. These tools help establish when a performance metric deserves trust.
Lessons 39
- 01Review and map: how models fail and what it means to trust themReview epistemic and aleatoric uncertainty and calibration as foundations of trustworthiness. Organize ML system failure modes and introduce threat models, lifecycle attack surfaces, and evaluation protocols for each dimension of trust.
- 02Uncertainty in deep networks: selective prediction and evaluation under shiftTurn uncertainty into decisions using abstention and confidence rankings. Study ReLU confidence away from data, distance-aware SNGP and DDU methods, and evaluation across shift intensities.
- 03Conformal prediction: distribution-free coverage guaranteesBuild split conformal prediction from the rank lemma, study realized coverage, and design regression and classification scores. Compare full conformal, jackknife+, and CV+.
- 04Conformal beyond exchangeability: conditional coverage, shift and risk controlExplore conditional coverage limitations and extensions of conformal prediction: group and function-class guarantees, weighting under covariate shift, adaptive conformal inference, monotone risk control, and LLM claim filtering.
- 05Detecting dataset shift: two-sample tests and monitoringBuild a drift detection pipeline using dimension reduction, corrected univariate tests, BBSD, MMD, and classifier tests. Compare power, distinguish benign from harmful shift, estimate accuracy without labels, and monitor sequentially.
- 06Out-of-distribution detectionMove from batch shift detection to deciding whether each input is recognized. Derive logit-based and feature-space scores, study outlier exposure and generative likelihood, and establish separate evaluation on near and far OOD examples.
- 07Robustness testing and rigorous model evaluationTreat model evaluation as test engineering using corruption and natural-shift benchmarks, behavioral templates, metamorphic testing without an oracle, and automatic subgroup discovery. Report disaggregated metrics, intervals, seeds, and model cards.
- 08Interpretability: framework, glass-box models and feature importanceFrame explainability around what is explained, to whom and for which decision. Compare transparent models with post-hoc explanations, implement marginal and conditional permutation importance, feature removal, PDP, ICE and ALE, and examine correlated features, GAMs and EBMs.
- 09Shapley values and SHAPGround local additive explanations in cooperative game theory, prove Shapley value uniqueness and examine interventional versus observational value functions. Implement exact calculation, permutation sampling and KernelSHAP; study TreeSHAP, interactions and limitations.
- 10LIME, anchors and counterfactual explanationsStudy local surrogate explanations with LIME and its relationship to KernelSHAP, anchor rules, counterfactuals and actionable recourse. Examine how similarly accurate models in a Rashomon set can explain the same data differently.
- 11Saliency and attribution methods for neural networksExplore attribution methods for differentiable networks: gradients and gradient times input, saturation, Integrated Gradients and its completeness proof and baseline choice, followed by SmoothGrad, DeepLIFT, LRP, Grad-CAM and the attention-as-explanation debate.
- 12Are explanations faithful? Evaluation and manipulationApply the same skepticism to explanation methods as to models. Run randomization sanity checks, measure faithfulness with deletion and insertion curves and ROAR, and study attribution fragility and manipulation by an adversary who controls the model. Finish with a checklist for using explanations in real audits.
- 13Data attribution: influence functions, TracIn and TRAKAttribute a prediction to training examples using influence functions, Hessian-vector products and their limitations in deep networks. Study TracIn, datamodels, TRAK and data Shapley, evaluate with LDS, and examine applications in label debugging, poisoning detection and LLMs.
- 14Probing: what information representations containStudy interpretability of internal representations through layer-wise linear probes, control tasks and MDL, distinguishing decodable information from information used. Explore evidence for linear representations, TCAV concept vectors and concept erasure as a causal test.
- 15The transformer under the microscope: residual stream, lenses and direct attributionEstablish a mathematical framework for mechanistic transformer interpretability: residual-stream decomposition, fixed-pattern paths, bigrams and skip-trigrams, head composition, hooks, activation caching, logit lens, tuned lens and direct logit attribution.
- 16Induction heads: train your own model and watch the phase changeStudy the two-head induction mechanism, its prefix-matching, copying, composition and in-context learning diagnostics, and reported phase changes. Construct a head by hand, test ablations, and examine measurements from models trained locally.
- 17Causal interventions: activation patching and ablationsMove from correlation to causal interventions within a network. Compare activation patching, ablation, causal tracing, path patching and attribution patching using explicit models and measured experiments.
- 18Circuit discovery: IOI, ACDC and causal scrubbingTurn patching experiments into testable circuit explanations. Study fidelity, completeness and minimality, the GPT-2 small IOI circuit and self-repair, automated discovery and edge attribution, causal scrubbing and distributed alignment search.
- 19Reverse-engineering an algorithm: grokking and modular arithmeticInvestigate a one-layer transformer trained on addition modulo p, its delayed generalization, Fourier-based circuits, frequency ablations, progress measures, and the question of universality.
- 20Superposition and polysemanticityStudy privileged bases, polysemanticity, and superposition through the Elhage et al. toy model. Explore phase diagrams, feature geometry, and interference as motivation for sparse dictionaries.
- 21Sparse autoencoders: feature dictionariesStudy sparse autoencoders as amortized sparse coding on activations, including decoder normalization, biases, penalties, shrinkage, and TopK, BatchTopK, JumpReLU, and Gated variants. Train and evaluate SAEs, build a feature dashboard, and investigate splitting and absorption.
- 22Steering and editing: intervening on representationsStudy activation steering, representation engineering, SAE feature steering, and knowledge editing. Derive a rank-one constrained least-squares update and evaluate the effectiveness and side effects of interventions.
- 23Frontier: transcoders, attribution graphs and the limits of interpretabilityStudy transcoders, cross-layer transcoders, crosscoders, and attribution graphs that approximate computations. Validate sparse feature circuits using controlled compiled transformers, model organisms, and interventions.
- 24Adversarial examples: evasion attacksIntroduce adversarial robustness through inference-time attacks. Formalize Lp and problem-space threat models, derive FGSM using norm duality, implement PGD and Carlini-Wagner, and study transferability and score-based and decision-based black-box attacks. Conclude with the explanations of why they exist (linearity in high dimension, non-robust features) and with domain constraints like malware and code.
- 25Defenses: adversarial training and honest evaluationDevelop adversarial training as robust optimization, alongside TRADES, fast training, and robust and catastrophic overfitting. Study careful evaluation: gradient masking, BPDA and EOT, and adaptive attack protocols with AutoAttack and RobustBench.
- 26Certified robustness: verification, bounds and randomized smoothingStudy provable robustness guarantees: exact verification and its complexity, Lipschitz-margin certificates, interval propagation, CROWN-style linear relaxations and randomized smoothing with Monte Carlo estimation and its limits.
- 27Data poisoning, backdoors and the ML supply chainStudy attacks that enter before a model is deployed. Formalize poisoning as bilevel optimization, implement triggered backdoors and clean-label poisons, and examine poisoning in web corpora and LLM fine-tuning. Study spectral signatures, activation clustering, trigger reconstruction, certified aggregation, and model supply chain security.
- 28Model extraction and intellectual property protection: watermarkingStudy the confidentiality of the model itself. Move from solving linear-model equations to recovering production LLMs' final layers from log-probabilities, via learning-based extraction and ReLU-network cryptanalysis. Analyze extraction defenses and their costs, then study evidence of copying: model watermarks, fingerprints, dataset inference, and statistical watermarks in generated text.
- 29Privacy attacks: membership inference, data extraction and inversionMeasure how much a model reveals about its training data before learning to protect it. Formulate membership inference as a hypothesis test, progress from threshold attacks to LiRA, and evaluate TPR at very low FPR. Extract synthetic training data from your own language model using canaries, including fictitious API keys relevant to code models, measure memorization, and introduce the reconstruction attacks that motivate differential privacy.
- 30Differential privacy: definition, mechanisms and proofsIntroduce differential privacy and its guarantee under auxiliary information. Develop its definition and hypothesis-testing interpretation, randomized response, sensitivity and the Laplace mechanism, postprocessing, group privacy and basic composition, with empirical checks and implementation pitfalls.
- 31Composition, advanced mechanisms and privacy accountingTraining a network composes thousands of mechanisms, making privacy accounting essential. This lesson covers Gaussian and exponential mechanisms, advanced composition, Rényi privacy and amplification by subsampling, and builds RDP and numerical privacy-loss accountants for comparison with library implementations.
- 32DP-SGD: training networks with differential privacy and auditing themApply the preceding ideas to training. Implement DP-SGD from scratch with Poisson sampling, per-example clipping, noise addition, and privacy accounting. Study how its hyperparameters interact and techniques for narrowing the gap with non-private training, including private LLM fine-tuning with LoRA. Close the loop with the attacks from lesson 29 by empirically auditing a trained model's ε using canaries.
- 33Federated learning: distributed privacy and robustnessTrain without centralizing data and discover why this alone does not ensure privacy. Implement FedAvg and corrections for heterogeneous data, use gradient inversion to show that updates can leak data, and build two complementary defenses: cryptographic secure aggregation and user-level DP. Examine malicious clients, robust aggregators, and the tension between hiding updates and inspecting them.
- 34Fairness: definitions, impossibility results and mitigationStudy fairness criteria for groups, their incompatibilities under differing base rates and three families of mitigation. Examine individual and counterfactual fairness and conduct a disaggregated intersectional audit with intervals and explicit limitations.
- 35Jailbreaks and adversarial attacks on LLMsApply adversarial robustness to aligned language models, where the adversary is the person making requests. Explain failures of safety training through competing objectives and mismatched generalization, implement GCG as discrete token optimization, and study automated, adaptive, and long-context attacks. Evaluate defenses with the discipline of lesson 25: validated judges and attackers who know the defense. All labs use harmless objectives under your control.
- 36Prompt injection: when data becomes instructionsExplain a central security problem in LLM applications through classic application security: injection without an equivalent to parameterized queries. Distinguish direct and indirect injection, catalog objectives and exfiltration channels, and evaluate prompting, detection, and instruction-hierarchy training using a controlled test suite and adaptive attacks. See why system-level defenses are needed.
- 37LLM agent security: systems that are secure by designWhen a model cannot reliably distinguish data from instructions, security must come from the architecture. Model threats to tool-using agents, including the lethal trifecta and confused deputy, explore designs that limit injection impact, and build a CaMeL-style interpreter with information flow control and capabilities. Add least privilege, sandboxing, confirmation, and MCP tool review, then evaluate utility and security with an AgentDojo-style test suite.
- 38Red teaming, model evaluation and risk managementBring the module together into a process. Distinguish red teaming (finding failures) from evaluation (measuring rates), automate adversarial case generation with attacker models and diversity, and develop the statistics needed to make claims about rare failures. Review threats to the validity of dangerous capability evaluations (underestimation, sandbagging, contamination), then conclude with risk management frameworks, risk registers, and incident response.
- 39Alignment: technical problems and the research frontierAsk whether a model does what we intend when the measured objective is incomplete. Distinguish specification gaming from goal misgeneralization, study hypotheses about deceptive alignment and evidence from model organisms, and examine scalable oversight, trusted-monitor control protocols, and interpretability audits including chain-of-thought monitoring. Finish with research projects that can be reproduced within 8 GB.
Module capstone
Reliability and security audit of a custom LLM system
For a small language model you trained, or an open 1B to 3B model, deployed as an agent with tools, produce a reproducible audit with an explicit threat model and seven parts: (1) a conformal factuality guarantee on your own question set; (2) a drift monitor and OOD detector for input prompts; (3) mechanistic interpretability: locate the circuit for a specific task using activation patching, train a sparse autoencoder on an intermediate layer, and demonstrate causal steering with one feature; (4) robustness: a GCG attack on refusal and evaluation of two defenses; (5) agent security: an AgentDojo-style indirect prompt-injection suite with at least three defenses, measuring utility and attack success with confidence intervals; (6) privacy: DP-SGD fine-tuning on data with canaries, measuring exposure and membership-attack LiRA AUC against ε; and (7) subgroup evaluation and a model card. Deliver a report with ablations, limits of each guarantee, and residual risks.
Check what you already know
- Formulate the threat model of an ML system, including attacker objective, knowledge, and capabilities, and locate it in the lifecycle.
- Construct a split conformal set and prove its finite-sample coverage guarantee.
- Implement and evaluate OOD detectors (MSP, energy, Mahalanobis) with AUROC and FPR at 95% TPR.
- Calculate exact Shapley values for a small model and distinguish interventional from observational SHAP.
- Apply Integrated Gradients, check completeness, and pass randomization sanity checks.
- Train linear probes with control tasks and distinguish decodable from used information.
- Explain an induction head through K-composition between a previous-token head and a copying head.
- Perform activation patching between clean and corrupted runs and interpret recovered logit difference.
- Train a sparse autoencoder on activations and measure L0, recovered loss, and dead latents.
- Implement PGD in an L-infinity ball and evaluate a defense with adaptive attacks without gradient masking.
- Derive the certified radius of randomized smoothing.
- Prove the Laplace mechanism is ε-DP and translate (ε, δ) into a bound on any membership attack.
- Compose subsampled Gaussian mechanisms using RDP and convert the result to (ε, δ).
- Implement DP-SGD with per-example clipping and empirically audit its ε.
- Design system-level prompt-injection defenses for an agent with tools.
References
- Probabilistic Machine Learning: Advanced Topics
- Introduction to AI Safety, Ethics, and Society
- Interpretable Machine Learning
- The Algorithmic Foundations of Differential Privacy
- Fairness and Machine Learning: Limitations and Opportunities
- Transformer Circuits Thread
- A Gentle Introduction to Conformal Prediction and Distribution-Free Uncertainty Quantification