RR Skillverse · Free Learning Handbook
RR Skillverse Module 4 of 12 Theory Handbook Finance + AI + Security

Module 4 — Generative AI, LLMs & RLHF

Same theory-first structure as Modules 1–3: for every technique below, what it is, why it exists — the specific problem it was invented to solve — what else you could use instead, and a real financial example. Module 3 gave you the Transformer's self-attention mechanism. Module 4 points that mechanism at generation, then walks the exact pipeline that turns a raw text-completion engine into something that behaves like a helpful assistant.

Recap — what RR Finance already has

Module 4 is not a fresh start. Here's exactly what it inherits before adding language generation and alignment.

MODULE 1

A validated tabular dataset, a logistic-regression baseline, and a documented data-poisoning defence.

MODULE 2

Deep learning fundamentals — an ANN, a CNN, and the first inference-time attack (adversarial examples) with a measured defence.

MODULE 3

Text representations, contextual embeddings (a small hand-built Transformer encoder), and two security lessons — prompt injection and PII redaction, including a toy mock of what LLM instruction-hijacking might look like.

What's new in Module 4
Module 3's encoder read text and produced representations. Module 4 builds a decoder that generates text, then spends most of the module on the harder problem: making that generator actually helpful and safe, not just fluent — the alignment problem, and the real security risks that come with an instruction-following system.

From "predict the next word" to "a helpful assistant"

A model trained on nothing but next-word prediction, at scale, implicitly learns grammar, facts, and reasoning patterns — but it does NOT automatically learn to be a helpful, instruction-following assistant. That gap is what most of this module's lessons close.

The surprising part

A raw next-token predictor is just as likely to continue a question with another question as with an answer — that's a statistically plausible continuation of internet text too.

The pipeline this module walks

Raw model → SFT (teach instruction-following) → Reward Model (learn what "good" means) → RL step (optimise toward it) → DPO (a simpler alternative).

Why the security lessons follow naturally

An LLM that follows instructions in its input is exactly the property that can be hijacked — closing the loop Module 3's toy prompt-injection demo opened.

CONCEPT 1

The GPT Decoder: Causal Self-Attention

The one architectural change that turns a representation-learner into a text generator.

Overview
🧮 Math & Algorithm
What it is

A GPT-style decoder is a Transformer that predicts the next token from everything before it, using a causal mask that prevents any position from attending to future tokens — the key difference from Module 3's bidirectional BERT-style encoder.

Why it exists — the history
2017
Vaswani et al.'s Transformer (Module 3) included both an encoder and a decoder half, originally for machine translation.
2018
Radford et al., OpenAI, "Improving Language Understanding by Generative Pre-Training" kept only the decoder half, added the causal mask, and showed that pretraining this architecture on raw text, then fine-tuning, beat task-specific models across many benchmarks — the paper that started the "GPT" lineage.

✓ Why the causal mask matters

  • Without it, the model could "see the answer" during training by copying its own future input — trivial training loss, useless at real generation where future tokens don't exist yet

✗ What this doesn't give you yet

  • A model that completes text plausibly is not the same as a model that follows instructions helpfully — that gap is what Lessons 3–6 close
REAL-WORLD FINANCIAL EXAMPLE
Every LLM-based financial tool — report drafting, chat-based analysis, document summarisation — sits on top of exactly this next-token-prediction mechanism, whether the underlying model has millions or hundreds of billions of parameters.
⬇ Run this lesson in the notebook
Causal mask: attention(i,j)=0 for j>i
P(x₁..x_T) = Π P(xₜ | x<ₜ)
Same self-attention as Module 3's Lesson 3, but with a causal mask: token i is only allowed to attend to tokens at position ≤ i, never future tokens — otherwise the model could "peek ahead" and next-token prediction would be trivial and useless.
The model is trained to maximise the product (equivalently, sum of logs) of the probability of every next token given everything before it — the entire pretraining objective is this one factorisation of the joint sentence probability.
Stacking many of these masked-attention blocks, plus feed-forward layers between them, is the entire GPT architecture — depth and width scale up, the core mechanism does not change.
CONCEPT 2

Sub-word Tokenization (BPE)

How a model represents words it has never seen before.

What it is

Byte-Pair Encoding (BPE) builds a vocabulary of frequently-occurring sub-word chunks from a training corpus — common words become single tokens, rare or unseen words fall back to smaller pieces, so the model never hits a hard "unknown word" wall.

Why it exists — the history
1994
BPE started as a data-compression algorithm (Gage) with nothing to do with language models.
2016
Sennrich et al. repurposed it for NLP tokenization in machine translation, and it was adopted as the standard tokenization approach from GPT-2 onward.
OptionTrade-off
Character-level (Module 4's Lesson 1 tokenizer)Simple, no "unknown word" problem, but produces long sequences for long words
Whole-wordShort sequences, but any unseen word becomes an unknown token entirely
Sub-word BPEThe practical middle ground — common words stay whole, rare/novel words decompose gracefully
Domain vocabulary matters
A tokenizer trained on general English can split financial terms like "amortization" or "collateralized" into several awkward sub-word pieces — worth inspecting before trusting a model's behaviour on financial text.
REAL-WORLD FINANCIAL EXAMPLE
RR Finance's own vocabulary (loan product names, internal terms) may tokenize inefficiently under a generic tokenizer — a genuine, checkable property before deploying any LLM-based financial tool.
⬇ Run this lesson in the notebook
CONCEPT 3

Supervised Fine-Tuning (SFT)

The first step that teaches a raw model to follow instructions at all.

Overview
🧮 Math & Algorithm
What it is

SFT is continued training on a curated dataset of high-quality example interactions — architecturally identical to pretraining (same cross-entropy next-token loss), just on a smaller, higher-quality, task-shaped dataset.

Why it exists — the history
2022
Ouyang et al., OpenAI, "Training language models to follow instructions with human feedback" formalised the full SFT → Reward Model → RL pipeline — this is the InstructGPT paper, the direct ancestor of ChatGPT's alignment approach.

✓ What SFT gives you

  • A model that has seen many examples of "instruction → helpful response" and mimics that pattern

✗ What SFT alone doesn't give you

  • A general sense of which of several plausible responses is better — that requires the reward model (next lesson)
  • Too many SFT steps on a narrow dataset risks "catastrophic forgetting" of general capability
REAL-WORLD FINANCIAL EXAMPLE
An SFT'd model that has seen many examples of "financial question → helpful, factual answer" behaves completely differently from a raw base model when asked a customer-service question — the difference between a text-completion engine and something that resembles an assistant.
⬇ Run this lesson in the notebook
L_SFT = −(1/T) Σₜ log P(yₜ | y<ₜ, prompt)
Standard cross-entropy loss (same shape as Module 1's log-loss), but now token-by-token: for every token in a curated, human-written response, penalise the model for assigning it low probability.
This is exactly the pretraining objective (predict the next token) applied to a much smaller, higher-quality dataset of instruction→response pairs — SFT doesn't teach new knowledge so much as teach the format of being a helpful assistant rather than a raw text-continuer.
CONCEPT 4

Reward Modelling

Turning "humans prefer this response" into a trainable scoring function.

Overview
🧮 Math & Algorithm
What it is

A reward model is a classifier that outputs one scalar score for a piece of text, trained so `score(preferred) > score(rejected)` on human-labelled preference pairs — the same sequence-classification architecture as Module 3's sentiment model, repurposed.

Why it exists — the history
2017
Christiano et al. formalised learning a reward function from pairwise human preferences for deep RL — because humans are notoriously inconsistent at assigning absolute scores, but reliably good at saying "A is better than B."
OptionTrade-off
Absolute scoring by humansInconsistent across raters and over time
Pairwise preference (Bradley-Terry loss)More consistent human judgments; only needs relative ranking, not an absolute scale
A real, honestly-measured limitation
A reward model trained on only a handful of examples per class can correctly rank its exact training examples, yet fail to generalise to paraphrased, unseen text — demonstrated directly in the notebook, not hidden. Whatever the reward model has actually learned — not what was intended — is what the next lesson's RL step will optimise toward.
REAL-WORLD FINANCIAL EXAMPLE
RR Finance wants its assistant to prefer accurate, policy-grounded answers over vague, evasive ones — a reward model is the mechanism that turns that preference into a trainable signal instead of a vague aspiration.
⬇ Run this lesson in the notebook
Bradley-Terry: P(A≻B) = e^{r(A)} / (e^{r(A)}+e^{r(B)})
L = −log σ(r(chosen) − r(rejected))
Given a pair of responses where a human preferred A over B, the reward model r is trained so that r(A) > r(B) — the Bradley-Terry formula converts a reward-score gap into a preference probability.
The loss is exactly logistic regression's log-loss again (Module 1), but on the difference between two scores instead of one — push σ(r(chosen)−r(rejected)) toward 1, i.e. make the gap large and positive.
Once trained, r(response) becomes a learned, automatic proxy for "how much would a human like this," reusable at scale where a human can't review every generation.
CONCEPT 5

The RL Step: PPO

How a reward score actually updates the model's weights.

Overview
🧮 Math & Algorithm
What it is

Given a trained reward model, the RL step adjusts the language model to produce higher-reward outputs more often. At its core: policy gradient / REINFORCE — `loss = -advantage × log π(action)`. PPO adds clipping and a KL penalty on top, purely for training stability at scale.

Why it exists — the history
2017
Schulman et al., OpenAI introduced PPO as a simpler, more stable alternative to earlier policy-gradient methods like TRPO — it became RLHF's RL algorithm of choice not because it's conceptually different from REINFORCE, but because its clipping mechanism tolerates larger, more efficient updates without training collapsing.
OptionTrade-off
REINFORCE / policy gradient (the core mechanism)Simple, directly demonstrable — but noisy and less stable at scale
PPOREINFORCE plus clipping and a KL penalty — the stability engineering that makes it viable at production scale
Reward hacking is real
The RL step optimises toward whatever the reward model actually learned — not necessarily the intended concept. If the reward model has a blind spot, RL will confidently exploit it. This is a well-known, still-open problem in production RLHF, called reward hacking or reward over-optimisation.
REAL-WORLD FINANCIAL EXAMPLE
This is the mechanism that turns "we have a scoring function for good answers" into "the model now actually gives better answers more often" — the step that makes the reward model's judgment actionable rather than just observational.
⬇ Run this lesson in the notebook
PPO objective: E[min(ρₜAₜ, clip(ρₜ,1−ε,1+ε)Aₜ)]
ρₜ = π_new(a|s)/π_old(a|s)
ρₜ — the probability ratio between the updated policy and the policy that generated the data; Aₜ (advantage) — how much better this action was than average, using the reward model's score.
Plain policy gradient (ρₜAₜ alone) can take a catastrophically large step if ρₜ swings far from 1. clip(ρₜ, 1−ε, 1+ε) caps how far the update is allowed to trust a single batch of data, and taking the min of the two terms means the objective never rewards moving further than that clip allows.
Net effect: nudge the language model toward generations the reward model scores highly, without ever changing the policy so drastically in one step that training destabilises — the entire reason PPO replaced simpler policy-gradient methods for this use case.
CONCEPT 6

DPO: Direct Preference Optimisation

Collapsing three training stages into one.

Overview
🧮 Math & Algorithm
What it is

DPO shows that the reward model and the RL step (Lessons 4–5) can be mathematically collapsed into one direct loss function, computed straight from (prompt, chosen, rejected) triples against a frozen reference copy of the model — no separate reward model, no RL loop.

Why it exists — the history
2023
Rafailov et al., Stanford proved the RLHF objective and a direct classification-style loss on preference pairs share the same optimum — a genuinely influential simplification, now used alongside (and sometimes instead of) full RLHF in many recent open-model releases.
RL pipeline (SFT → Reward Model → PPO)DPO
Moving partsThree separate stagesOne stage, on top of SFT
Compute costHigherLower
When still preferredNeed the reward model as a reusable, inspectable artifactJust need the fine-tuned model, fewer infrastructure pieces
REAL-WORLD FINANCIAL EXAMPLE
A team without a large ML infrastructure investment can realistically run a DPO fine-tuning pass on its own preference data, where a full RL pipeline might be out of reach.
⬇ Run this lesson in the notebook
L_DPO = −log σ( β log[π(y_w|x)/π_ref(y_w|x)] − β log[π(y_l|x)/π_ref(y_l|x)] )
DPO skips training a separate reward model and skips the RL loop entirely — it shows mathematically that the same preference-alignment objective can be rewritten as a direct classification loss on the policy model itself, using a frozen copy of the pre-SFT model (π_ref) as a reference point.
y_w, y_l — the preferred ("winning") and dispreferred ("losing") response from a human comparison. The loss pushes the policy's log-probability-ratio-vs-reference higher for y_w than for y_l.
β controls how far the new policy is allowed to drift from the reference model — conceptually doing the same "don't move too far, too fast" job that PPO's clipping does, but built directly into a single differentiable loss instead of a separate RL algorithm.
CONCEPT 7

Parameter-Efficient Fine-Tuning: LoRA & QLoRA

Adapting a huge model by training a tiny fraction of it.

Overview
🧮 Math & Algorithm
What it is

LoRA freezes an entire pretrained model and injects small, trainable low-rank matrices alongside its existing weights — often training under 1% of the original parameter count. QLoRA adds 4-bit quantisation of the frozen weights on top, cutting GPU memory needs further.

Why it exists — the history
2021
Hu et al., Microsoft introduced LoRA.
2023
Dettmers et al. introduced QLoRA — the combination made fine-tuning a 65-billion-parameter model feasible on a single consumer GPU, a dramatic accessibility shift.

✓ Why this matters practically

  • Maintaining several lightweight fine-tuned variants of one base model (e.g. retail lending, commercial lending, customer support) becomes practical instead of storing several full copies

✗ The capacity trade-off

  • Higher rank (`r`) gives the adapter more expressive capacity at the cost of more trainable parameters — the same trade-off as choosing hidden-layer width in Module 2's ANN lesson
REAL-WORLD FINANCIAL EXAMPLE
RR Finance could realistically fine-tune a real 7-billion-parameter open model with LoRA on a single consumer GPU, where full fine-tuning would need many high-end GPUs just to hold the optimiser state — and could serve it fully locally via Ollama, keeping sensitive data in-house.
⬇ Run this lesson in the notebook
LoRA: W' = W₀ + BA, B∈ℝ^{d×r}, A∈ℝ^{r×k}, r≪d,k
Instead of updating the full pretrained weight matrix W₀ (potentially billions of parameters), LoRA freezes W₀ entirely and learns a small correction BA — the product of two much smaller "low-rank" matrices.
r (rank) is a small number (e.g. 8–64) far smaller than the original dimensions d, k — this is the key compression: a d×k update normally needs d×k parameters, but BA only needs r×(d+k), a huge reduction when r is small.
QLoRA adds one more trick on top: it quantises the frozen W₀ down to 4-bit precision (far less GPU memory) while keeping the small LoRA matrices A, B in higher precision for stable training — memory saved on the part that isn't being trained anyway.
CONCEPT 8 · CYBERSECURITY

LLM Jailbreaks

Same harmful intent, different words — and a naive filter can't tell.

What it is

A jailbreak is a prompt crafted to make an instruction-following model ignore its safety training — typically by reframing a harmful request as roleplay, fiction, or a claimed "developer mode," rather than asking directly.

Why it exists — the history
Late 2022 onward
Jailbreak prompts (character roleplay like "DAN — Do Anything Now," fictional framing, authority-override claims) emerged rapidly alongside ChatGPT's public release, as users discovered safety training could often be circumvented by reframing rather than defeating the underlying check.
A real, undisguised demonstration
The notebook builds a simple keyword-based guardrail, then shows three jailbreak-style prompts — roleplay framing, fictional framing, and "developer mode" framing — all genuinely bypassing it, on purpose. A keyword filter can only catch phrasings it has literally seen; natural language has effectively unlimited ways to express the same intent.
REAL-WORLD FINANCIAL EXAMPLE
An LLM-based financial assistant that can be jailbroken into providing fraud instructions or bypassing compliance guardrails is a direct, serious business and regulatory risk — not a hypothetical one.
⬇ Run this lesson in the notebook
CONCEPT 9 · CYBERSECURITY · LAB

Red-Teaming With Garak

Moving from manually inventing jailbreaks to a systematic scanning tool.

What it is

Garak ("Generative AI Red-teaming & Assessment Kit") is a real, open-source, actively maintained LLM vulnerability scanner with dozens of probe categories — jailbreaks, prompt injection, data leakage, toxic generation, and more — each paired with automated detectors that judge whether an attack succeeded.

Why it exists — the history
2023 onward
Released by Leon Derczynski and contributors, with significant NVIDIA involvement, as the field recognised that ad hoc manual jailbreak-hunting (Lesson 8's approach) doesn't scale to the breadth of known attack techniques — the same progression from manual checks to a systematic tool that Module 1 made when Isolation Forest replaced ad hoc anomaly spotting.

✓ What the notebook demonstrates

  • A real garak scan, run fully offline against a null test target — genuine plumbing: a real probe, a real detector, a real pass/fail report

✗ What it doesn't prove on its own

  • A clean scan against one probe category (or an offline test target) says nothing about the others — a real security review runs many probe categories against the actual deployed system
REAL-WORLD FINANCIAL EXAMPLE
Before RR Finance deploys any LLM-based system into production, a real security review would run garak's jailbreak, prompt-injection, and data-leakage probe categories against the actual deployed endpoint — exactly the evidence a compliance or security team would expect to see.
⬇ Run this lesson in the notebook

Module 4 hand-off

The notebook trains a from-scratch GPT, a real SFT model, a real reward model, a real DPO model, a real LoRA adapter, and produces both a manual jailbreak demonstration and a real garak scan — saved as artifacts and a metrics summary for the next module.

What Module 5 builds on this
Module 5 (RAG, LangChain & AI Agents) gives the instruction-following model this module built toward tools and retrieval — the ability to look things up and take actions, not just generate text. The jailbreak and red-teaming lessons here become the foundation for Module 5's agentic threat surface: an LLM that can call tools is an LLM whose tool calls can potentially be hijacked too.