Large Language Models in Finance · Chapter 2 / Lecture 2

Large Language Models: Architecture and Practice

How a model learns to read a 100-page filing — from recurrent networks to the Transformer, and how to actually use one.
Juan F. Imbet  ·  EDHEC Business School / Paris Dauphine – PSL University
Roadmap

Where this lecture is going

  1. From sequences to attention — why reading word-by-word breaks down, and the idea that fixed it.
  2. The Transformer — the architecture behind every modern LLM.
  3. Pre-training & the landscape — BERT vs. GPT, reasoning models, and who builds what.
  4. Sampling & structured output — turning a model into a reliable tool.
  5. APIs, RAG & hallucinations — cost, grounding, and the failure modes that matter in finance.
  6. Model compression — distillation, LoRA, and quantisation for deployment.
the bigger picture Lecture 1 turned words into static vectors. Today we build the machine that reads a sequence in context — so "earnings did not decline" no longer reads like "earnings declined" — and then learn how to run it responsibly on real financial documents.
01

From sequences to attention

Document representations, polysemy, and the architecture evolution that handles both.
First problem: documents are long

How do you turn a 100-page filing into one vector?

Earnings calls run about 10,000 words; 10-K filings about 100,000. Three ways to compress all those word-vectors into a single document representation — each with a catch.

MethodIdeaWeakness
Mean embeddingAverage every word's vectorNo word order; permutation-invariant
TF-IDF weightedAverage, weight rare/distinctive words moreStill bag-of-words
SBERT (contextual)A BERT fine-tuned to embed whole sentencesCompute cost at encoding
why order matters Under mean pooling, "Revenue rose, costs fell" \(\equiv\) "Costs rose, revenue fell" — identical vectors, opposite meaning. SBERT advantage: cross-encoding \(N\) documents with vanilla BERT takes \(O(N)\) forward passes; SBERT bi-encoding needs only \(O(1)\) at query time.
Second problem: words mean different things

One word, many meanings — static embeddings pick one and ignore the rest

Word2Vec and GloVe assign a single fixed vector to each word. In finance, polysemy — one word, multiple meanings — is everywhere and consequential.

  • bank — financial institution OR a river's edge; a sentiment model trained on finance incorrectly transfers positive sentiment to sentences about river flooding
  • yield — bond yield, crop yield, or to give way
  • default — failure to repay a debt OR a software setting
  • position — a long/short holding OR a physical location
the fix Contextual embeddings (BERT, SBERT) assign different vectors depending on surrounding context. The same token bank gets different representations in "central bank" vs. "river bank."
Before the Transformer · recurrent models in one slide

RNNs and LSTMs: what they got right, and why they lost

For a decade, recurrent networks (RNN → LSTM → GRU → BiLSTM) were the default for financial NLP — named-entity recognition, sentiment, event extraction. They read a sequence one token at a time, carrying a running "memory" forward. Three structural limits are exactly what the Transformer was built to remove.

Pros
  • Natural fit for sequences of any length; compact, few parameters
  • LSTM/GRU gates tame the vanishing gradient over short and medium ranges
  • BiLSTM gives every token both past and future context
  • Dominant for financial NER & sentiment pre-2019; run on modest hardware
Cons
  • Long-range dependencies still fade — a guidance figure on p.3 tied to a caveat on p.20 of a 10-K stays unlearnable
  • Sequential by construction — no parallelism across the sequence; slow to train at scale
  • A fixed-size hidden state must compress the whole document into one vector — an information bottleneck
the move that follows Attention (Bahdanau et al., 2015) removes the fixed-vector bottleneck by letting the model look back at every token directly; applied within a single sequence it becomes self-attention — and fixes all three limits at once.
The breakthrough idea · attention

What if the model could look at every word at once?

The bottleneck in older translation models: the encoder had to squeeze the whole input into one fixed vector. Bahdanau et al. (2015) let the decoder instead look back at every input word and weight the ones it needs right now.

a usable intuition "Attention" is just a learned, soft lookup: given what I'm doing now, which parts of the input should I read most carefully? A decoder generating "net income" puts high weight exactly on the transcript tokens where income figures appear. Attention is interpretable.
the move that follows Apply attention within a single sequence — every word attending to every other word — and you get self-attention, the heart of the Transformer.
02

The Transformer

Self-attention, many heads, positional encoding, and the encoder block that stacks into every modern LLM.
Self-attention, mechanically

Every word asks every other word: "are you relevant to me?"

Each word produces three roles — a query (what I'm looking for), a key (what I offer), and a value (what I'd contribute). Matching queries to keys decides how much of each value to pull in.

the causal mask In a generative (decoder) model we set \(\tilde{S}_{ij} = -\infty\) for \(j>i\), so a token can never "see" words that come after it — otherwise it would cheat at predicting the next word.
parallelism Unlike an RNN, all \(n\) tokens are processed simultaneously. Training a 100B-parameter model on financial filings becomes feasible in weeks, not years.
Many heads

Run attention several times in parallel — each head a different lens

One attention pattern can only capture one kind of relationship. Multi-head attention runs several in parallel, then concatenates them — so different heads can track grammar, co-reference, and figures at once.

What do heads learn? (Clark et al., 2019)

  • Lower layers — syntax: subject–verb agreement, negation scope
  • Deeper layers — semantics: entity co-reference, temporal relations
  • Financial models — heads specialise on "last quarter" → figures, entity linking
the cost of looking everywhere Complexity is \(O(n^2 d_{\text{model}})\) per layer. At \(n = 4{,}096\) tokens that's \(\approx\)134M values per layer — which is why FlashAttention (Dao et al., 2022) exists.
Positional encoding — injecting order

Self-attention is order-blind — so position is injected explicitly

Self-attention treats the input as a set: shuffle the words and the math is unchanged. A sinusoidal positional encoding tags each token with its location so the model can recover order.

  • Low-indexed dimensions oscillate rapidly (short period) — they pin down fine position within a few tokens.
  • High-indexed dimensions change slowly (long period) — they encode coarse position across the whole sequence.
  • Stacking the two gives every position a unique signature — a token at position 5 never collides with one at position 50.
  • Any fixed offset \(\Delta\) is a linear transformation of the encoding, so relative positions are linearly decodable: the model can learn "\(k\) tokens apart" directly.
Special tokens — the scaffolding of LLMs

Every LLM reserves a few tokens for structure, not words

Alongside word-pieces, LLMs keep a handful of tokens that carry structural rather than lexical meaning — and getting them wrong breaks financial pipelines in subtle ways.

TokenRoleFinancial consequence if misused
[CLS]BERT summary slot; final hidden state feeds classifierWrong features → bad sentiment scores
[SEP]Segment boundary (question | passage)Model misreads where document ends
[MASK]MLM training placeholderAccidentally masking at inference breaks extraction
<pad>Batch-padding fillerUnmasked padding biases pooled embeddings
<eos>End-of-sequence; decoding stops on this tokenMisplaced EOS truncates a risk disclosure mid-sentence
<unk>Out-of-vocabulary fallbackRare tickers → UNK → entity extraction fails
RAG splicing pitfall A retrieval pipeline that splices retrieved passages into a prompt must respect the model's special-token conventions — otherwise the model silently misreads where document boundaries lie.
Putting it together

One Transformer block: attend, then think, with safety rails

A block does two things — mix information across words (attention), then process each word on its own (a small feed-forward network) — each wrapped in a "shortcut" that keeps training stable.

Why residual connections are critical
They give gradients a direct pathway from output back to input, eliminating the multiplicative vanishing-gradient problem across layer depth — the same disease that crippled RNNs, now cured by design.
encoder vs decoder vs both BERT-style: encoder only (bidirectional, best for classification). GPT-style: decoder only (causal, best for generation). T5/BART: full encoder–decoder for summarisation and translation.
Tracing a forward pass

Seven steps from tokens to next-word probability — in miniature

A toy GPT (6-word vocab, \(d_\text{model}=4\), one decoder block) reads "revenue fell" and predicts the next word. The same seven steps run inside every production LLM — just with larger matrices.

  1. Embed — look up each token's row in the embedding table \(E\)
  2. Add positional encoding — inject sinusoidal signals so the model recovers order
  3. Form Q, K, V — project each row to a query, key, and value vector
  4. Score, mask, softmax — dot-product scores, causal \(-\infty\) mask, row-wise softmax → attention weights \(A\)
  5. Attention output + Add & Norm — weighted average of values, then residual + LayerNorm
  6. Feed-forward + Add & Norm — position-wise FFN (widen → ReLU → project), then residual + LayerNorm
  7. Un-embed + softmax — multiply final row by \(E^\top\) to get logits; softmax gives \(P(\text{next token})\)
the key insight The causal mask (step 4) makes autoregressive training efficient: a single forward pass on a sequence of length \(n\) simultaneously trains the model on all \(n\) prefixes in parallel.
Matrix walk-through · step 1 of 7

Step 1 — "Embedding lookup" is literally one matrix times another

Our toy model knows a vocabulary of just \(V=6\) tokens — every "word" it can read or write:

id012345
token<s>revenuefellsharplyrose.

Each token owns exactly one row of the embedding table \(E\ (6\times4)\) — so \(V=6\) rows, one \(4\)-dimensional vector apiece. A production GPT swaps this \(6\) for a byte-pair vocabulary of ~100,000 tokens, but the mechanism below is identical.

The prefix "<s> revenue fell" has token ids \((0,1,2)\). Stack their one-hot rows into \(O\) and multiply by the embedding table \(E\) — each one-hot row just selects a row of \(E\):

\[ \underset{\textstyle O\ (3\times6)}{ \begin{bmatrix} 1&0&0&0&0&0 \\ 0&1&0&0&0&0 \\ 0&0&1&0&0&0 \end{bmatrix}} \underset{\textstyle E\ (6\times4)}{ \begin{bmatrix} 1&0&0&0 \\ 0&1&0&1 \\ 1&0&1&0 \\ 0&1&1&0 \\ 1&1&0&0 \\ 0&0&0&1 \end{bmatrix}} = \underset{\textstyle X^{(\mathrm{emb})}\ (3\times4)}{ \begin{bmatrix} 1&0&0&0 \\ 0&1&0&1 \\ 1&0&1&0 \end{bmatrix}} \]
the bigger picture A one-hot row holds a single \(1\), so the product simply copies the matching row of \(E\). That is all a token embedding is — a row lookup, written as a matrix multiply so the entire sequence is one operation. Add the positional encoding to \(X^{(\mathrm{emb})}\) and the block is ready to attend.
Matrix walk-through · step 2 of 7

Step 2 — Add position, so order is not lost

Self-attention is permutation-equivariant — on its own it cannot tell "revenue fell" from "fell revenue". We add a sinusoidal positional encoding \(\mathrm{PE}\) (\(n=3,\ d_\text{model}=4\)) to the embeddings:

\[ X^{(0)} = X^{(\mathrm{emb})} + \mathrm{PE} = \begin{bmatrix} 1&0&0&0 \\ 0&1&0&1 \\ 1&0&1&0 \end{bmatrix} + \begin{bmatrix} 0.00 & 1.00 & 0.00 & 1.00 \\ 0.84 & 0.54 & 0.01 & 1.00 \\ 0.91 & -0.42 & 0.02 & 1.00 \end{bmatrix} = \begin{bmatrix} 1.00 & 1.00 & 0.00 & 1.00 \\ 0.84 & 1.54 & 0.01 & 2.00 \\ 1.91 & -0.42 & 1.02 & 1.00 \end{bmatrix} \]

Row \(t\) of \(X^{(0)}\) now encodes both the word and where it sits. From here the model works only with these vectors.

Matrix walk-through · step 3 of 7

Step 3 — Project each row into a query, key, and value

Each token row is multiplied by three weight matrices. To keep the arithmetic legible we set \(W^Q=W^K=I\) (so \(Q=K=X^{(0)}\)); only \(W^V\) mixes the coordinates:

\[ W^V=\begin{bmatrix} 0&1&0&0 \\ 1&0&0&1 \\ 0&0&1&0 \\ 0&1&0&1 \end{bmatrix} \qquad V = X^{(0)}W^V = \begin{bmatrix} 1.00 & 2.00 & 0.00 & 2.00 \\ 1.54 & 2.84 & 0.01 & 3.54 \\ -0.42 & 2.91 & 1.02 & 0.58 \end{bmatrix} \]

\(Q\) asks "what am I looking for?", \(K\) advertises "what do I offer?", \(V\) carries "what I'll pass on if attended to."

Matrix walk-through · step 4 of 7

Step 4 — Scores → causal mask → softmax = attention

Score every pair with \(S=QK^{\top}/\sqrt{d_k}\) (\(\sqrt{d_k}=2\)); the causal mask sets the future to \(-\infty\) so a token cannot peek ahead; a row-wise softmax turns each row into weights \(A\):

\[ \begin{bmatrix} 1.50 & 2.19 & 1.25 \\ 2.19 & 3.54 & 1.49 \\ 1.25 & 1.49 & 2.93 \end{bmatrix} \xrightarrow{\text{mask}} \begin{bmatrix} 1.50 & -\infty & -\infty \\ 2.19 & 3.54 & -\infty \\ 1.25 & 1.49 & 2.93 \end{bmatrix} \xrightarrow{\text{softmax}} A=\begin{bmatrix} 1.00 & 0 & 0 \\ 0.21 & 0.79 & 0 \\ 0.13 & 0.17 & \mathbf{0.70} \end{bmatrix} \]

<s> can only see itself; fell (row 3) spreads its attention \(0.13/0.17/0.70\) — weighting its own position most. Every row of \(A\) sums to \(1\).

Matrix walk-through · step 5 of 7

Step 5 — Attention output, then Add & Norm

Each token's new vector is the attention-weighted average of the value rows, \(\mathrm{Att}=AV\). Add the residual input and layer-normalise: \(Z=\mathrm{LayerNorm}\!\left(X^{(0)}+\mathrm{Att}\right)\):

\[ \mathrm{Att}=AV=\begin{bmatrix} 1.00 & 2.00 & 0.00 & 2.00 \\ 1.43 & 2.67 & 0.01 & 3.22 \\ 0.09 & 2.78 & 0.72 & 1.26 \end{bmatrix} \qquad Z=\begin{bmatrix} 0.00 & 0.82 & -1.63 & 0.82 \\ -0.33 & 0.64 & -1.46 & 1.15 \\ -0.36 & 1.12 & -1.46 & 0.70 \end{bmatrix} \]

LayerNorm acts on each row (zero mean, unit variance) — which is why every row of \(Z\) sums to zero. The residual keeps the original signal in play.

Matrix walk-through · step 6 of 7 · (a)

Step 6a — Feed-forward: widen to 6 dims, then ReLU

The position-wise FFN, \(\mathrm{FFN}(\mathbf{z})=\max(0,\mathbf{z}W_1)W_2\), runs on each row independently. First widen \(4\to6\) with \(W_1\) and clip negatives with ReLU:

\[ W_1=\begin{bmatrix} 0&0&-1&1&-1&0 \\ 1&0&0&-1&0&0 \\ -1&-1&-1&0&-1&1 \\ 0&0&0&0&0&0 \end{bmatrix} \] \[ H=\max(0,\,ZW_1)=\begin{bmatrix} 2.45 & 1.63 & 1.63 & 0 & 1.63 & 0 \\ 2.11 & 1.46 & 1.80 & 0 & 1.80 & 0 \\ 2.58 & 1.46 & 1.82 & 0 & 1.82 & 0 \end{bmatrix} \]

Hidden units 4 and 6 are negative at every position, so ReLU switches them off (the \(0\) columns) — a concrete instance of the sparsity ReLU induces.

Matrix walk-through · step 6 of 7 · (b)

Step 6b — Project back to 4 dims, then Add & Norm

Project the 6-dim hidden layer back down with \(W_2\), then a second residual-and-norm gives the block output \(X^{(1)}\):

\[ W_2=\begin{bmatrix} 0&0&1&-1 \\ -1&0&0&0 \\ 0&0&0&0 \\ 1&1&-1&0 \\ 0&-1&-1&0 \\ -1&0&1&1 \end{bmatrix} \qquad F=HW_2=\begin{bmatrix} -1.63 & -1.63 & 0.82 & -2.45 \\ -1.46 & -1.80 & 0.31 & -2.11 \\ -1.46 & -1.82 & 0.76 & -2.58 \end{bmatrix} \] \[ X^{(1)}=\mathrm{LayerNorm}(Z+F)=\begin{bmatrix} -1.00 & 1.00 & 1.00 & -1.00 \\ -1.67 & 0.35 & 0.35 & 0.98 \\ -0.95 & 1.00 & 1.00 & -1.05 \end{bmatrix} \]

\(X^{(1)}\) is the output of one decoder block. A real GPT stacks 32–96 of these — each the same two sub-layers traced here.

Matrix walk-through · step 7 of 7

Step 7 — Un-embed → logits → softmax: the next word

With tied weights the logits are \(\mathrm{logits}=X^{(1)}E^{\top}\). Only the last row matters for generation — it scores every vocabulary word as the continuation of fell:

\[ \mathrm{logits}=\begin{bmatrix} -1.00 & 0.00 & 0.00 & 2.00 & 0.00 & -1.00 \\ -1.67 & 1.32 & -1.32 & 0.70 & -1.32 & 0.98 \\ -0.95 & -0.05 & 0.05 & \mathbf{2.00} & 0.05 & -1.05 \end{bmatrix} \]

The last row's top score is column 4, sharply — the dot product of \(X^{(1)}_3=(-0.95,1.00,1.00,-1.05)\) with sharply's embedding \((0,1,1,0)\) is \(1.00+1.00=2.00\). A row-wise softmax turns it into probabilities:

\[ P_{\texttt{fell}}=\bigl( \underset{\langle s\rangle}{0.03},\ \underset{\text{revenue}}{0.08},\ \underset{\text{fell}}{0.09},\ \underset{\textbf{sharply}}{\mathbf{0.66}},\ \underset{\text{rose}}{0.09},\ \underset{.}{0.03}\bigr) \]
the payoff The tiny GPT completes "revenue fell" with sharply at \(66\%\). Every production LLM does exactly this — byte-pair tokens, \(d_\text{model}\) in the thousands, dozens of heads, 32–96 stacked blocks. Same arithmetic, more of it.
03

Pre-training and the LLM landscape

Two ways to learn from raw text, reasoning models, RLHF, and who ships what.
Recipe 1 · BERT

BERT learns by playing fill-in-the-blank

Hide 15% of the words in a sentence and train the model to guess them from the words on both sides. Reading in both directions makes it a powerful reader — but not a writer.

best for Classification (sentiment, credit rating), token-level extraction (NER, metric extraction), and semantic similarity. Not for text generation.
Recipe 2 · GPT

GPT learns by always guessing the next word

Read left to right and predict what comes next, over and over. That single skill, at scale, becomes fluent generation — and it's why one architecture can draft, answer, and reason.

Which architecture for which job?

TaskArchitectureWhy
Sentiment classificationEncoder (BERT)Full bidirectional context
NER in filingsEncoder (BERT)Token-level labels
Earnings-call summarisationEnc–Dec (T5/BART)Seq2seq; full input read
Report drafting, Q&ADecoder (GPT)Generative by design
Numerical reasoning (FinQA)Decoder + CoTMulti-step generation
Reasoning models

Chain-of-thought + RL reward: the next frontier beyond standard generation

Standard LLMs generate tokens one step at a time with no backtracking. Reasoning models are trained to produce an explicit thinking trace before committing to an answer — dramatically improving multi-step financial tasks.

  • Standard generation — one autoregressive pass; fast but commits to the most plausible next token without deliberation
  • Chain-of-thought prompting (Wei et al., 2022) — instruct the model to show its steps; each step independently verifiable
  • Reasoning models (o1, o3, DeepSeek-R1) — trained via RL with verifiable rewards to generate a latent trace \(\mathbf{r}\) before producing answer \(\mathbf{a}\)
not a silver bullet Reasoning models reduce hallucination on tasks with verifiable steps (FinQA), but extrinsic hallucination on obscure regulatory facts persists. All mitigation techniques (Section 05) remain necessary.
From raw model to assistant

Instruction tuning + RLHF: teaching a model to follow orders

A raw pre-trained model completes text; it doesn't follow instructions. Two extra training stages turn it into a reliable assistant that respects structured output formats and financial conventions.

Stage 1 — Instruction tuning
Fine-tune on curated (instruction, response) pairs. The model learns to follow natural-language directives and produce structured outputs (JSON, Markdown tables) that downstream pipelines depend on.
Stage 2 — RLHF (Ouyang et al., 2022)
Train a reward model on pairwise human rankings; optimise the language model via PPO to maximise human-preferred completions. Result: the "chat" or "instruct" model you actually call via API.
why this matters for finance LopezLira & Tang (2023): ChatGPT sentiment scores for news headlines significantly predict next-day stock returns — and predictability increases monotonically with model size. Return predictability is an emergent property of scale, not explicit financial training (Wei et al., 2022). General frontier models at large scale often match BloombergGPT on financial benchmarks.
The market map

Who builds the models you'll actually call?

A handful of general frontier models plus a few finance-specific ones. Context length (how much text it can read at once) and open vs. closed weights matter as much as raw size.

ModelOrg.Arch.ParamsContextFinance
GPT-5.6OpenAIDecodern/d400KNo
Claude Opus 4.8AnthropicDecodern/d1MNo
Llama 4 (Maverick)MetaDecoder400B MoE10MNo
Gemini 3 ProGoogle DMMultimodaln/d1M+No
FinBERTAraci 2019 / Huang 2023Encoder110M512Yes
BloombergGPTBloombergDecoder50B2KYes
  • FinBERT: two independently trained models share the name — Araci (2019) on Reuters/Bloomberg/10-K; Huang (2023) on analyst-labelled sentences. Do not conflate in benchmarks.
  • BloombergGPT (Wu et al., 2023): 363B finance + 345B general tokens. Outperforms same-size general models on FinancialPhraseBank and ConvFinQA. Large frontier models often match it via scale.
  • Open-weight models (Llama family) enable on-premises deployment — no data-privacy risk. 405B at 16-bit requires ~810 GB GPU memory.
04

Sampling and structured generation

The dials that control creativity vs. determinism — and how to force clean, machine-readable output.
The creativity dial

One knob decides whether the model plays it safe or improvises

At each step the model has a probability over possible next words. Temperature, nucleus, top-\(k\), and beam search are different rules for picking from that distribution.

  • Temperature — low = predictable, high = adventurous
  • Top-\(k\) — only sample from the \(k\) highest-probability words
  • Nucleus (top-\(p\)) — only sample from the smallest set of words covering probability \(p\) (Holtzman et al., 2020); adapts vocabulary size to model confidence
  • Beam search — keep the \(B\) best partial sentences; deterministic; prone to degeneration on open-ended tasks
beam search degeneration Beam search dominated neural machine translation and is still preferred for ROUGE/BLEU tasks with reference texts, but produces repetitive, generic prose on open-ended generation. Nucleus sampling replaced it for conversational use.
Choosing the dial in finance

If a machine reads the output, set temperature to zero

The right setting depends entirely on whether you want one correct answer or a range of ideas.

TaskTemperatureSampling
Structured extraction (earnings, covenants)\(\tau = 0\) (greedy)
Sentiment labelling\(\tau \approx 0.1\)greedy / top-\(k\)
Document summarisation\(\tau \approx 0.3\text{–}0.5\)top-\(p\) = 0.9
Regulatory Q&A / compliance\(\tau \approx 0.1\)greedy + RAG
Scenario / stress-test narrative\(\tau \approx 0.7\text{–}1.0\)top-\(p\) = 0.95
Extractive summarisation (ROUGE)N/ABeam search (\(B=4\))
Rule of thumb
If the output feeds a downstream system or is compared to ground truth: \(\tau = 0\). If a human analyst values breadth and novelty: \(\tau \in [0.5, 1.0]\) with nucleus.
self-consistency Run \(K\) samples at \(\tau > 0\) and take the majority vote (Wang et al., 2022) — especially effective for multi-step numerical reasoning (FinQA-type tasks).
Forcing clean output

How to make a model return data, not prose

To extract figures into a database you need valid JSON every time. Constrained decoding blocks any token that would break the required schema before the model can pick it.

class EarningsReport(BaseModel):
    revenue_bn: Optional[float] = None
    net_income_bn: Optional[float] = None
    eps: Optional[float] = None

client.messages.create(
  tools=[{"name": "record_earnings",
          "input_schema": EarningsReport.model_json_schema()}],
  tool_choice={"type": "tool", "name": "record_earnings"},
  ...
)

Anthropic tool use + Pydantic: the schema defines exactly what fields come back. tool_choice forces the tool call — no silent fallback to free text.

Even valid output can be wrong

Three failure modes constrained decoding does NOT fix

Guaranteeing the shape of the answer says nothing about whether the numbers inside it are right.

  1. Numerically wrong-but-valid — a clean number that's simply incorrect (pair with \(\tau=0\) + RAG)
  2. Silent field omission — model emits explicit null; detectable but requires required/optional field discipline in the schema
  3. Unit confusion — millions vs. billions; requires application-level validation with canonical units in the Pydantic model
the lesson Schema validity is necessary, not sufficient. Always validate values against the source and expected units. Structured generation is an architectural requirement in any production financial NLP pipeline.
05

APIs, RAG, and hallucinations

What it costs to run these models, how to ground them in real documents, and where they lie.
What you actually pay for

Models bill by the token — and token math decides your budget

Before processing, text is chopped into sub-word "tokens" (BPE). You pay per token in and per token out, so the same job can cost wildly different amounts across providers.

ModelInput (\(\$\)/MTok)Output (\(\$\)/MTok)
GPT-5.6 Sol\(\$\)5.00\(\$\)30.00
Claude Haiku 4.5\(\$\)1.00\(\$\)5.00
Llama 4 self-hosted≈\(\$\)0≈\(\$\)0
worked example 10,000 transcripts × (7,000 input + 400 output tokens): GPT-5.6 Sol ≈ \(\$\)470; Claude Haiku 4.5 ≈ \(\$\)90 (≈5× cheaper). Prompt caching a shared system-prompt prefix cuts up to 90% of cost (Anthropic prefix caching; OpenAI ≥1,024-token contexts).
Grounding the model

RAG: don't trust the model's memory — hand it the document

Retrieval-Augmented Generation fetches the most relevant passages first, then asks the model to answer using only those — so every claim traces back to a real source.

why RAG for finance Update the knowledge base by adding new filings — no retraining. Every factual claim traces back to a retrieved passage (auditability). It's the dominant architecture for production document Q&A.
FinanceBench lesson (Zhang et al., 2024) GPT-4-Turbo with a retrieval system incorrectly answers or refuses 81% of questions from SEC filings. Naive RAG is insufficient for high-stakes financial QA; advanced chunking, re-ranking, and verification are necessary.
The core danger

Hallucination: fluent, confident, and wrong

A hallucination is output that sounds authoritative but isn't supported by the input or the real world. In finance, three kinds do the most damage.

  • numerical D/E ratio of 1.8 reported as 0.8 — indistinguishable from correct figures downstream
  • entity wrong company or regulatory body substituted
  • citation a fabricated regulation, ruling, or standard (Ji et al., 2023)
root cause Models are trained to produce plausible text. Setting \(\tau = 0\) removes randomness but not hallucination — the most probable completion can still be false (Kang et al., 2023).
The defense

No single fix — stack six defenses together

In production you layer complementary techniques; none is sufficient alone.

  1. RAG — ground answers in verified passages; model rarely fabricates figures absent from retrieved text
  2. Self-consistency sampling — \(K\) chains at \(\tau>0\), majority vote; best for multi-step numerical reasoning (Wang et al., 2022)
  3. Chain-of-thought (Wei et al., 2022) — force explicit steps; each independently verifiable; reasoning models implement this natively
  4. Claim decomposition (FActScore) — break output into atomic claims; flag unsupported ones before human review
  5. Confidence elicitation + abstention — model flags uncertainty; calibrate thresholds against accuracy; confidence-gating for production pipelines
  6. Prompted self-critique — a second pass re-checks every claim against the source and retracts unsupported ones; the inference-time analogue of Constitutional AI (Bai et al., 2022), and the one defense a closed-API user can deploy without model weights
reasoning models help, but don't close the gap They reduce hallucination on tasks with verifiable steps (FinQA), but extrinsic hallucination on obscure regulatory facts persists. All six techniques remain necessary.
Using these responsibly

The legal and ethical traps practitioners must know

Beyond accuracy, deploying LLMs in finance runs into regulation, contaminated back-tests, privacy law, and built-in geographic bias.

  • EU AI Act (Reg. 2024/1689, in force Aug 2024) — credit scoring, insurance pricing, AI-assisted securities pricing are high-risk: conformity assessments, human oversight, transparency to regulators
  • Look-ahead bias (Didisheim et al., 2025) — LLMs can reconstruct historical time series from memory, producing spurious back-test predictability; memorised data is contaminated data
  • GDPR (EU 2016/679) — fine-tuning or RAG on client personal data triggers right-to-erasure; a model trained on personal data can't satisfy erasure without retraining; data-transfer restrictions on non-EU API routing
  • Geographic bias — all five major benchmarks are North American / English; US-trained sentiment models may misread Japanese, Chinese, or Indian financial contexts
  • US / fiduciary duty — SEC posture holds the human adviser fully responsible for AI-generated outputs; whether an LLM answer counts as a "recommendation" is unsettled, but "the model said so" is not a defense
06

Model compression

Distillation, LoRA, and quantisation — deploying frontier-quality models on production hardware.
The deployment problem

A 70B model is too large for real-time trading — compression bridges the gap

A 70B model at 16-bit precision needs ~140 GB of GPU memory and has latency measured in seconds — incompatible with risk monitoring or order routing. Three complementary techniques shrink the model without gutting accuracy.

Knowledge distillation (Hinton et al., 2015)
A large teacher trains a smaller student via soft labels — the teacher's probability distribution over all tokens, not just the correct one. Soft labels expose inter-class similarity invisible in hard one-hot targets. Finance use: 70B teacher + curated financial corpus → 7B student with similar accuracy at inference-feasible cost.
LoRA: fine-tune on a single GPU (Hu et al., 2022)
Freeze pre-trained weights \(W_0\); learn only a low-rank update \(\Delta W = BA\), \(B\in\mathbb{R}^{d\times r},\; A\in\mathbb{R}^{r\times k},\; r\ll\min(d,k)\). At \(d=k=4096,\,r=16\): 131K trainable params vs. 16.8M — a 128× reduction. Only adapters \(A,B\) accumulate gradients; \(W_0\) needs no optimizer state.
Quantisation and pruning

Trading bits for bytes: deploy a 70B model on two consumer GPUs

Quantisation reduces weight precision from 16-bit float to 4–8-bit integer, cutting memory 2–4× with negligible accuracy loss on most tasks — without any retraining.

MethodIdeaResult
GPTQ (Frantar et al., 2022)Layer-wise second-order PTQ: minimise quantisation error propagated forwardINT4 models match FP16 perplexity; no retraining required
AWQ (Lin et al., 2023)Protect the 1% of weight channels with highest activations from aggressive quantisationBetter accuracy–compression than GPTQ on most tasks
PruningZero low-magnitude weights (unstructured) or remove full heads/blocks (structured)Structured pruning: dense, hardware-efficient models
the practical deployment stack QLoRA to fine-tune on proprietary data → AWQ to quantise for deployment → serve on-premises. This stack brings frontier-class quality to a single A100 with no data-privacy exposure.
Wrap-up

What we covered — and where Lecture 3 goes

Architecture arc

  • Mean/TF-IDF/SBERT; polysemy; long-document strategies (truncation/chunking/hierarchical)
  • RNN vanishing gradient → LSTM additive cell state → GRU → BiLSTM → Bahdanau attention → self-attention → Transformer
  • Scaled dot-product, multi-head, positional encoding (sinusoidal + RoPE), residual + LayerNorm, causal mask, cross-attention, special tokens
  • BERT (MLM) vs. GPT (CLM); reasoning models (CoT + RL); RLHF; FinBERT; BloombergGPT

Engineering & safety

  • Temperature / nucleus / top-k / beam; sampling table; constrained decoding + tool use; grammar-based generation
  • BPE, cost model, prompt caching, RAG (dense + sparse + hybrid + re-rank), FinanceBench
  • Hallucination taxonomy; SelfCheckGPT; FActScore; inner confidence (+20% Sharpe); 6-layer mitigation
  • Distillation; LoRA / QLoRA; GPTQ / AWQ; pruning; EU AI Act; look-ahead bias; GDPR; SEC fiduciary duty
Next lecture
Lecture 3 — Sentiment Analysis in Finance: applying these foundations to FinancialPhraseBank, FinBERT fine-tuning, and LLM-based sentiment extraction at scale.
A

Appendix — extended derivations & benchmarks

The √dₖ variance proof, financial benchmarks, and retrieval internals. Beyond the core lecture.
Appendix · the missing √dₖ

Why divide attention scores by √dₖ?

Without scaling, dot-product scores grow with dimension, the softmax saturates, and gradients die — reintroducing the very problem attention was meant to solve.

Consequence
Without scaling, the softmax saturates and gradients vanish — the same problem LSTMs were designed to fix, now reappearing inside the attention layer.
Appendix · how progress is measured

The benchmarks that define financial NLP

BenchmarkTaskSizeMetric
FinancialPhraseBank (Malo et al., 2014)Sentiment (3-class)4,840 sent.Accuracy
FiQA SA / QA (Maia et al., 2018)Opinion mining; Q&A~1,200F1, NDCG
ECTSum (Mukherjee et al., 2022)Earnings-call summarisation2,425 docsROUGE-L
FinQA (Chen et al., 2021)Numerical reasoning8,281 Q&AExec. acc.
FLUE (Shah et al., 2022)Multi-task financial NLUMulti-taskTask-specific

FinQA requires multi-step arithmetic over tables — reasoning models dominate. ECTSum evaluates abstractive summarisation against expert-written gold summaries.

geographic bias All five benchmarks are built from English-language, North American sources. Do not assume generalisation to European or Asian financial contexts.
Appendix · retrieval internals

Dense, sparse, or hybrid: how RAG finds passages

Dense retrieval matches meaning; sparse (BM25) matches exact strings like CUSIPs and tickers; hybrid fuses both. The combination is the production default.

MethodStrengthWeakness
DenseSemantic similarityExact-match failures
BM25Exact-match recallMisses paraphrases
HybridBothSlightly slower
Re-ranker (ColBERT)High precisionHigher latency