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
From sequences to attention — why reading word-by-word breaks down, and the idea that fixed it.
The Transformer — the architecture behind every modern LLM.
Pre-training & the landscape — BERT vs. GPT, reasoning models, and who builds what.
Sampling & structured output — turning a model into a reliable tool.
APIs, RAG & hallucinations — cost, grounding, and the failure modes that matter in finance.
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.
Method
Idea
Weakness
Mean embedding
Average every word's vector
No word order; permutation-invariant
TF-IDF weighted
Average, weight rare/distinctive words more
Still bag-of-words
SBERT (contextual)
A BERT fine-tuned to embed whole sentences
Compute 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.
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.
Token
Role
Financial consequence if misused
[CLS]
BERT summary slot; final hidden state feeds classifier
Wrong features → bad sentiment scores
[SEP]
Segment boundary (question | passage)
Model misreads where document ends
[MASK]
MLM training placeholder
Accidentally masking at inference breaks extraction
<pad>
Batch-padding filler
Unmasked padding biases pooled embeddings
<eos>
End-of-sequence; decoding stops on this token
Misplaced EOS truncates a risk disclosure mid-sentence
<unk>
Out-of-vocabulary fallback
Rare 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.
Embed — look up each token's row in the embedding table \(E\)
Add positional encoding — inject sinusoidal signals so the model recovers order
Form Q, K, V — project each row to a query, key, and value vector
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:
id
0
1
2
3
4
5
token
<s>
revenue
fell
sharply
rose
.
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\):
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:
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:
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\):
<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)\):
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:
\(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:
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:
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?
Task
Architecture
Why
Sentiment classification
Encoder (BERT)
Full bidirectional context
NER in filings
Encoder (BERT)
Token-level labels
Earnings-call summarisation
Enc–Dec (T5/BART)
Seq2seq; full input read
Report drafting, Q&A
Decoder (GPT)
Generative by design
Numerical reasoning (FinQA)
Decoder + CoT
Multi-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.
Model
Org.
Arch.
Params
Context
Finance
GPT-5.6
OpenAI
Decoder
n/d
400K
No
Claude Opus 4.8
Anthropic
Decoder
n/d
1M
No
Llama 4 (Maverick)
Meta
Decoder
400B MoE
10M
No
Gemini 3 Pro
Google DM
Multimodal
n/d
1M+
No
FinBERT
Araci 2019 / Huang 2023
Encoder
110M
512
Yes
BloombergGPT
Bloomberg
Decoder
50B
2K
Yes
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.
Task
Temperature
Sampling
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/A
Beam 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.
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.
Numerically wrong-but-valid — a clean number that's simply incorrect (pair with \(\tau=0\) + RAG)
Silent field omission — model emits explicit null; detectable but requires required/optional field discipline in the schema
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.
Model
Input (\(\$\)/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.
RAG — ground answers in verified passages; model rarely fabricates figures absent from retrieved text
Self-consistency sampling — \(K\) chains at \(\tau>0\), majority vote; best for multi-step numerical reasoning (Wang et al., 2022)
Chain-of-thought (Wei et al., 2022) — force explicit steps; each independently verifiable; reasoning models implement this natively
Claim decomposition (FActScore) — break output into atomic claims; flag unsupported ones before human review
Confidence elicitation + abstention — model flags uncertainty; calibrate thresholds against accuracy; confidence-gating for production pipelines
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.
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.
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
Benchmark
Task
Size
Metric
FinancialPhraseBank (Malo et al., 2014)
Sentiment (3-class)
4,840 sent.
Accuracy
FiQA SA / QA (Maia et al., 2018)
Opinion mining; Q&A
~1,200
F1, NDCG
ECTSum (Mukherjee et al., 2022)
Earnings-call summarisation
2,425 docs
ROUGE-L
FinQA (Chen et al., 2021)
Numerical reasoning
8,281 Q&A
Exec. acc.
FLUE (Shah et al., 2022)
Multi-task financial NLU
Multi-task
Task-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.