1 / 19
1
ComplianceGPT Lab · AI Innovation & Diffusion REU 2026

ML → DL → NLP → LLMs

The progression that made modern AI possible — and why you need to understand each step

Part 1
Machine Learning
Data replaces rules
Part 2
Deep Learning
Layers learn features
Part 3
NLP
Words become vectors
Part 4
Transformers & LLMs
Context at scale

Each step solved a problem the previous step couldn't. By the end you'll know exactly why LLMs are necessary for HIPAA compliance extraction — not because someone told you, but because you'll have hit every wall yourself.

2
Part 1 — Machine Learning
Part 1 · Machine Learning

The Central Idea: Data Replaces Rules

Every approach before ML required someone to write the logic. ML inverts this: you supply examples, the algorithm extracts the logic itself.

Before ML — Write the rules

# A programmer writes every rule by hand def is_permitted(scenario_text): if "court order" in scenario_text: return "PERMITTED" if "patient authorization" in scenario_text: return "PERMITTED" # ... 200 more rules ... return "DENIED"

Misses "judicial mandate". Catches "the officer mentioned a possible order". Never finished. Breaks on every edge case.

With ML — Show examples

from sklearn.ensemble import RandomForestClassifier # Show the algorithm labeled examples X = extract_features(scenarios) # your features y = ["PERMITTED", "DENIED", ...] # your labels model = RandomForestClassifier() model.fit(X, y) # algorithm finds patterns # Now classify new scenarios model.predict([new_scenario_features])

The algorithm finds its own rules from data. Works on synonyms it's seen in examples. Improves with more data.

The key shift: The programmer no longer decides what matters. The data decides. A feature that predicts PERMITTED well gets a high weight automatically. One that doesn't gets downweighted. The machine learns the decision boundary.

3
Part 1 — Machine Learning
Part 1 · Machine Learning

Features, Labels, and the Training Loop

Three concepts you need to understand everything that follows.

Features — What you tell the model

Numeric representations of your input. For HIPAA scenarios:

has_court_order: 1
receiver_is_LEO: 0
has_patient_auth: 0
is_treatment: 1
...24 features total

You choose what features to extract. Bad features → bad model, regardless of algorithm. Day 1 notebook: you hand-crafted these.

Labels — What you want to predict

The answer for each training example.

Scenario 1 → PERMITTED
Scenario 2 → DENIED
Scenario 3 → PERMITTED
...137 labeled cases

Labels come from human experts — lawyers or annotators who read each case. This is the GoldCoin dataset you're using this summer.

Training — Finding the pattern

The algorithm sees (features, label) pairs and adjusts internal parameters to minimize mistakes.

1. Make a prediction
2. Compare to the true label
3. Measure the error (loss)
4. Adjust parameters to reduce error
5. Repeat millions of times

After training: show the model a new scenario it has never seen. It predicts PERMITTED or DENIED based on learned patterns.

The wall you hit in Day 1

Hand-crafted boolean features gave you ~90% accuracy — on clean, pre-extracted features. The hard part is getting those features from raw text in the first place. That's the extraction problem, and it's what the rest of this week is about.

4
Part 1 — Machine Learning

Three Algorithms — What They Actually Do

You used all three in Day 1. Here's the intuition behind each.

Logistic Regression

Learns a weight for each feature. PERMITTED probability = sigmoid(w₁×f₁ + w₂×f₂ + ... + b).

Think: a weighted checklist. High weight on has_court_order means that feature pushes strongly toward PERMITTED.

Best for: understanding which features matter. Weights are directly interpretable.

Limitation: only learns linear decision boundaries. Can't capture "court order AND NOT officer request."

Decision Tree

Learns a sequence of if/else rules. Splits data at each node to maximize separation between PERMITTED and DENIED.

has_court_order?
├─ YES → PERMITTED
└─ NO → has_patient_auth?
    ├─ YES → PERMITTED
    └─ NO → DENIED

Best for: explainability — you can read the tree and verify it against HIPAA rules.

Random Forest

Trains 100 decision trees, each on a random subset of data and features. Final prediction = majority vote.

Each tree is slightly different. Their errors are uncorrelated. Average them → much lower error than any single tree.

Best for: accuracy. Almost always outperforms a single tree.

Limitation: less interpretable than a single tree. But feature importances still tell you what matters.

The shared limitation of all three: They classify based on features you provide. Change the features, change the model. For text, what features do you provide? This is the next problem.

5
Part 2 — Deep Learning
Part 2 · Deep Learning

Neural Networks — Learning Features, Not Just Patterns

In Day 1, you engineered features by hand. Deep learning eliminates that step: layers of the network learn to extract features automatically from raw input.

What a neuron does

A neuron receives inputs, multiplies each by a learned weight, adds a bias, and passes the sum through a non-linear function (ReLU, sigmoid):

output = ReLU(w₁x₁ + w₂x₂ + w₃x₃ + b)

Stack millions of these in layers and the network learns arbitrarily complex functions from data.

Why "deep"?

Multiple hidden layers. Each layer learns increasingly abstract features:

  • Layer 1 → detects word patterns ("court order")
  • Layer 3 → detects phrase semantics
  • Layer 6 → detects legal concepts
  • Layer 12 → detects compliance-relevant conditions

No human labeled these levels. The network figured them out from the training signal alone.

3-Layer Neural Network
Input
x₁
x₂
x₃
x₄
⋮⋯⋮
Hidden
h₁
h₂
h₃
h₄
h₅
⋮⋯⋮
Output
PER
DEN
Every neuron connects to every neuron in the next layer.
Each connection has a learned weight.
6
Part 2 — Deep Learning

Backpropagation — How Networks Learn

Training a neural network is an iterative loop. The same loop runs billions of times.

Step 1 — Forward pass

Input flows through the network layer by layer. Each neuron computes its output. The final layer produces a prediction: e.g., 72% PERMITTED, 28% DENIED.

Step 2 — Compute loss

Compare prediction to the true label. The loss function (e.g., cross-entropy) gives a single number measuring how wrong the prediction was. High loss = very wrong.

Step 3 — Backward pass

Compute how much each weight contributed to the error (gradient). Chain rule propagates error backward from the output layer to the input layer.

Step 4 — Update weights

Gradient descent: nudge every weight slightly in the direction that reduces the loss. Learning rate controls the step size. Repeat from Step 1.

The AlexNet moment — 2012

ImageNet challenge: classify 1.2M images into 1,000 categories. Best 2011 approach: 26% error. AlexNet (deep network on GPUs, 2012): 15.3% error. Next best: 26.2%.

A 10-point gap, not 1. Everyone in AI pivoted overnight. GPUs became research infrastructure.

Why GPUs changed everything

The backprop loop runs the same operation (matrix multiply) millions of times. GPUs have thousands of cores designed for exactly this — they run these operations in parallel.

  • CPU: ~10 matrix ops/sec for large networks
  • GPU: ~10,000 matrix ops/sec
  • H100 (cluster): 2,000× faster than a 2012 GPU
7
Part 3 — NLP
Part 3 · Natural Language Processing

The Text Problem — Numbers Only

Neural networks process numbers. Text is not numbers. Every NLP approach is an answer to: how do we represent text as vectors? Each approach captures more meaning than the last.

Bag of Words

Count how many times each word appears. Vocabulary of 10,000 words → 10,000-dimensional vector.

"court order signed"
court: 1, order: 1,
signed: 1, the: 0,
...9997 zeros

Problem: no word order. "court dismissed order" = "order court dismissed". No semantic meaning.

TF-IDF

Weight rare words more. "subpoena" appears in 3 scenarios → very informative. "the" appears in all → useless.

TF-IDF score:
subpoena: 0.84 (rare, important)
court: 0.42 (moderately common)
the: 0.00 (appears everywhere)

Better, but: "court order" and "judicial mandate" have 0% word overlap → near-zero similarity. Semantically blind.

Word Embeddings

Train a network to predict word context. Words used in similar contexts end up close in vector space.

cosine_sim(
"court order",
"judicial mandate"
) → 0.87 ✓

Captures meaning! But still fails on adversarial context: "implied there might be a court order" also scores ~0.80.

8
Part 3 — NLP

Bag of Words → TF-IDF in Code

Two lines of sklearn. You used these in Day 2's notebook. Here's what they actually do.

Bag of Words

from sklearn.feature_extraction.text import CountVectorizer texts = [ "The judge signed a court order", "The hospital disclosed records", "A court order required disclosure", ] bow = CountVectorizer() X = bow.fit_transform(texts) # X is a 3×8 sparse matrix # Each row = one scenario # Each column = one vocabulary word # Value = count of that word print(bow.get_feature_names_out()) # ['a', 'court', 'disclosed', 'hospital', # 'judge', 'order', 'records', 'required', # 'signed', 'the']

TF-IDF

from sklearn.feature_extraction.text import TfidfVectorizer tfidf = TfidfVectorizer(ngram_range=(1,2)) X = tfidf.fit_transform(texts) # ngram_range=(1,2) captures BIGRAMS too # "court order" = one feature (not two) # This helps: "court order" gets one weight # TF-IDF formula: # tf(t,d) = count(t in d) / len(d) # idf(t) = log(N / df(t)) # tfidf(t,d) = tf × idf # "subpoena" appears in 1/80 docs # idf = log(80/1) = 4.38 → HIGH weight # "the" appears in 80/80 docs # idf = log(80/80) = 0 → ZERO weight

Key result from Day 2

TF-IDF cosine similarity: "court order" vs "judicial mandate"0.08. Zero word overlap = near-zero similarity. Legally they enable the same HIPAA exception. TF-IDF doesn't know that. This is the wall TF-IDF hits.

9
Part 3 — NLP

Word Embeddings — Meaning as Geometry

Word2Vec (2013): train a network to predict word context. The byproduct is a 300-dimensional vector for every word where meaning is encoded as position in space.

The training task (Word2Vec)

Given "The [BLANK] is a medical facility" — predict the blank. Network learns to represent words that fill similar blanks similarly.

hospital → fills blank ✓
clinic → fills blank ✓
lawsuit → doesn't fill blank ✗

The hidden layer weights become the word vectors. Hospital and clinic end up geometrically close. Lawsuit ends up far away.

The famous analogy

king − man + woman ≈ queen

Vector arithmetic preserves relationships. This proved that meaning is encoded geometrically, not symbolically.

Simplified 2D embedding space

hospital • • clinic • physician
healthcare court • • subpoena • warrant
legal-process • "implied court order"
⚠ close to legal cluster → hallucination
10
Part 3 — NLP

Sentence Embeddings — The Day 3 Upgrade

Word2Vec embeds individual words. Sentence transformers embed entire sentences — capturing context, not just vocabulary.

from sentence_transformers import SentenceTransformer from sklearn.metrics.pairwise import cosine_similarity model = SentenceTransformer('all-MiniLM-L6-v2') phrases = [ "A court order required production", "A judicial mandate required disclosure", "implied there might be a court order", "Officer said records were needed", ] embs = model.encode(phrases) sim = cosine_similarity(embs) # court order ↔ judicial mandate: 0.87 ✓ # court order ↔ implied order: 0.79 ⚠ # court order ↔ officer request: 0.52

What you saw in Day 3

court order ↔ judicial mandate0.87 ✓ FIXED
court order ↔ implied court order0.79 ✗ STILL CLOSE
court order ↔ officer request0.52

The remaining problem

"Implied there might be a court order" is semantically about court orders — it just doesn't constitute one. An embedding model captures topic similarity. It cannot detect the legal distinction between mentioning a court order and having one.

This is the exact gap LLMs try to close. A model that reads the full sentence in context can attend to "implied" and "might be" and understand they are hedging qualifiers.

11
Part 4 — Transformers & LLMs
Part 4 · Transformers & LLMs

The Transformer — Attention Over Sequences

Vaswani et al., 2017. The paper that changed everything. Instead of processing one word at a time (RNNs), every word attends to every other word simultaneously.

The RNN problem (before 2017)

RNNs process tokens sequentially. Token 1 → hidden state → Token 2 → hidden state → ... By token 50, information from token 1 has faded (vanishing gradient).

"The patient, who was admitted after a workplace injury treated by a physician who had previously disclosed records in an unrelated matter, filed for damages claiming the hospital had shared information without court authorization."

Key fact ("without court authorization") is at the end. Subject ("patient") is at the start. RNN has trouble connecting them over 40 tokens.

Self-attention — every word to every word

For each token, compute: how much should I attend to every other token?

Attention weights for "order" in "He signed the order":
"signed" → 0.72  (legal action → court)
"records" → 0.61  (production context)
"He" → 0.03     (pronoun, low signal)
→ "order" = court order ✓
  • All tokens equidistant — no vanishing gradient
  • Fully parallelizable — runs on all GPUs simultaneously
  • Scales predictably with compute
12
Part 4 — Transformers & LLMs

Encoder vs Decoder — Two Paths from One Architecture

Encoder — BERT (2018)

Reads the entire input bidirectionally. Every token can attend to every other token in both directions simultaneously.

Training task: Masked Language Model — randomly mask 15% of tokens and predict them from context.

Input: "The [MASK] signed an order"
Predict: "judge" from left+right context

Use for: classification, extraction, understanding. BERT representations are the foundation of ComplianceGPT's extraction layer.

Decoder — GPT (2018 → now)

Generates tokens left-to-right. Each token can only attend to previous tokens — never future ones (causal masking).

Training task: Next token prediction — given all previous tokens, predict the next one. Trained on trillions of tokens from the internet.

Input: "The patient has a court"
Predict: "order" (most likely next token)

Use for: text generation, completion, conversation. Gemma3 and Llama3 are decoder-only LLMs.

The practical difference for you: When Gemma3 extracts oracle predicates, it's doing next-token prediction on your prompt. It predicts "has_court_order": true because that's the most statistically likely completion of your prompt — not because it verified the text.

13
Part 4 — Transformers & LLMs

Tokenization + Embeddings Inside a Transformer

Everything you learned about text representations (Parts 1–3) comes together here.

1 · Raw Text
"The judge
signed a
court order"
2 · Tokenization
[512, 4008,
9431, 287,
2267, 1502]
integer IDs
3 · Embedding
[0.32, -0.71,
0.45, ...
×4096 dims]
dense vectors
4 · Attention Layers
Each token updates
its representation
by attending to all
other tokens
5 · Output
"court_order":
true
"purpose":
"judicial"

This happens for every token in parallel, across 32+ transformer layers, for every scenario in your batch.

Context window = your working memory

Gemma3:4B can process 8,192 tokens at once. Everything outside the window is invisible to the model. A long court case narrative can fill 30–50% of that window before your prompt instructions even start.

Temperature = how random is generation?

temp=0: always picks the highest-probability next token. Deterministic — same input, same output every time. Always use temp=0 for extraction experiments — otherwise you can't reproduce results.

14
Part 4 — Transformers & LLMs

How LLMs Are Trained — The 3 Stages

Stage 1

Pretraining

Train on 10+ trillion tokens: web pages, books, code, legal documents. Task: predict the next token.

Result: a model that has absorbed statistical patterns of human knowledge. It can complete sentences in any domain — including legal text.

⚠ At this stage: will complete "How do I..." with harmful instructions. No safety yet.
Stage 2

Instruction Fine-Tuning

Train on thousands of (instruction, good-response) pairs. Task: generate the helpful response given a user request.

Result: model understands what it's supposed to do. Follows instructions, stays on topic, uses correct format.

Same weights as Stage 1 but radically different behavior. GPT-3 → InstructGPT.
Stage 3

RLHF

Human raters rank model outputs. A reward model is trained on rankings. LLM fine-tuned to maximize reward.

Result: optimized for what humans prefer — helpful, harmless, honest.

⚠ RLHF trains confidence. Model may give a confident wrong extraction over an uncertain correct one.

Why this matters for your research

RLHF optimizes for human approval of fluency, not legal precision. A model that confidently writes "has_court_order": true sounds good to a human rater. But it may be wrong. You can't distinguish confidence from correctness in LLM output — you have to verify against ground truth.

15
Part 4 — Transformers & LLMs

Hallucination — The Mechanism

Not a random bug. A predictable consequence of how LLMs work. Understanding it lets you design prompts that prevent it.

Why it happens: next-token prediction ≠ fact verification

When generating "has_court_order": , the model predicts whether true or false is the most likely next token given the prompt and everything generated so far.

It cannot look back at the scenario text and verify. It predicts what statistically tends to follow prompts like this one.

"acting pursuant to what might be a court order"
↓ prompt activates legal-process context ↓
p("true" | prompt) = 0.81
→ model outputs "true" — WRONG

False Positive (FP) — Oracle hallucination

Oracle set True without evidence → formal engine fires exception → verdict PERMITTED → PHI leak

Most common error in ComplianceGPT FPs: has_court_order hallucinated in law-enforcement scenarios

False Negative (FN) — Under-extraction

Oracle left False even though scenario text clearly states it → exception cannot fire → verdict DENIED → over-blocking

Happens when the enabling fact is stated indirectly or with unusual phrasing

16

The Full Progression — Side by Side

What you built this week. Each row: what it can do and what it can't.

Approach What you built Accuracy Wall hit
Hand-crafted rules if "court order" in text ~60% Misses synonyms. Catches false positives. Never finished.
ML + hand features Day 1 — sklearn on boolean features ~90% Who extracts the features from raw text?
Bag of Words + ML Day 2 — CountVectorizer + LogReg ~70% Word order ignored. No semantic meaning.
TF-IDF + ML Day 2 — TfidfVectorizer + LogReg ~80% "court order" ↔ "judicial mandate" similarity = 0.08
Sentence Embeddings Day 3 — sentence-transformers ~87% "implied court order" still embeds near real court order
LLM Extraction Exercise 9 — Gemma3 on cluster 94.2% Still hallucinates has_court_order on adversarial phrasing

The research frontier: That last 5.8% gap. Each error is an oracle hallucination or under-extraction that LLMs still make despite reading in full context. Closing that gap — through better prompts, schema design, few-shot examples, or model selection — is your project this summer.

17

Why Each Step Was Necessary

Every technique solved something the previous one couldn't. The story is cumulative, not replaceable.

ML (sklearn) Added: data replaces hand-coded logic. Algorithm finds decision boundary automatically. Still needs features
Deep Learning Added: network learns features from raw input. No more manual feature engineering. Still sequential (RNN)
Bag of Words Added: text becomes numbers. Can feed any text to any ML algorithm. No word order, no semantics
TF-IDF Added: rare important words weighted higher. Reduces noise from common words. No semantic similarity
Embeddings Added: semantic meaning as geometry. "court order" ≈ "judicial mandate" now measurable. Can't use sentence context
Transformer Added: every word in context of every other word. "order" = court order or medical order, determined by the full sentence. Still: hallucination
LLM (Gemma3) Added: scale. 4 billion parameters trained on 10T tokens can follow complex extraction instructions in natural language. 94.2% — your starting point
18

Your Research — Closing the Last Gap

You've now built every step of the 70-year progression by hand. Here's where you stand.

What 94.2% means

  • 137 GoldCoin court cases
  • 8 wrong predictions
  • Every error is an oracle extraction failure
  • No errors in the formal Soufflé engine — the logic is correct
  • Your job: reduce those 8 errors to fewer

What the errors look like

  • Oracle hallucination — model sets has_court_order=true when text only implies possible authority
  • Under-extraction — enabling fact present in text but model misses it
  • Role confusion — sender and receiver swapped
  • Purpose OOV — purpose category not in schema vocabulary

Six research directions (choose one)

P1 Adversarial Robustness P2 Multi-Regulation P3 Model Comparison P4 Prompt Engineering P5 Error Explanation P6 Few-Shot Examples

Every project attacks the same 5.8% gap from a different angle. See projects.html for full descriptions. Project selection due Friday Jul 3.

19

This Week's Work

Day 1 (Monday)

day1_sklearn.ipynb

  • Train LogReg, DecisionTree, RandomForest
  • Read feature weights and tree rules
  • Hit the feature extraction wall

Day 2 (Tuesday)

day2_nlp.ipynb

  • Bag of Words → TF-IDF
  • Cosine similarity reveals the semantic gap
  • Cluster setup session

Day 3 (Wednesday)

day3_embeddings.ipynb

  • Sentence embeddings close the semantic gap
  • Adversarial phrases remain close to real ones
  • First GPU experiment (Exercise 9)

Days 4–5 (Thu/Fri)

  • Finish week2_nlp.ipynb Exercises 5–9
  • Karpathy "State of GPT" (45 min)
  • Jay Alammar "Illustrated Transformer"
  • Project selection decision

Submit by Friday Jul 3, 5pm

  • All 3 daily notebooks (flexible timing)
  • week2_nlp.ipynb Exercises 5–9
  • Cluster run evidence (sacct screenshot)
  • 1-page error analysis
  • Project selection (Slack)