โ† Back to Course Home
Module 01

Foundation Models

Understanding the "engine" behind Gen AI

Introduction to Language Models

The Challenge: Teaching Machines to Understand Language

Human language is incredibly complex. Unlike images or structured data, language has sequential dependencies, context, ambiguity, and nuance. How do we teach machines to understand that "bank" means different things in "river bank" versus "savings bank"? Or that "I didn't say she stole my money" has seven different meanings depending on which word you emphasize?

Key Challenges in Natural Language Processing

๐Ÿ”—Sequential Dependencies

Words depend on context from earlier in the sentence. "She couldn't fit the trophy in the suitcase because it was too big" - what is "it"?

๐ŸŽญAmbiguity & Context

Same words mean different things in different contexts. "Apple" could be a fruit, a company, or even a record label.

๐Ÿ“Variable Length

Sentences can be 3 words or 300 words. Models need to handle any length gracefully.

๐ŸŒLong-Range Dependencies

Critical information might be separated by many words or sentences. Models must "remember" context across long distances.

Early Approaches: Sequence-to-Sequence Models

Before transformers, the dominant approach was Recurrent Neural Networks (RNNs) and their sequence-to-sequence (seq2seq) architecture. Let's understand why they were revolutionary - and why they ultimately fell short.

Recurrent Neural Networks (RNNs)

The
โ†“
RNN Cell
โ†“
h0
โ†’
cat
โ†“
RNN Cell
โ†’
โ†“
h1
โ†’
sat
โ†“
RNN Cell
โ†’
โ†“
h2
โ†’
on
โ†“
RNN Cell
โ†’
โ†“
h3
โ†’
mat
โ†“
RNN Cell
โ†’
โ†“
h4

Each word is processed sequentially, passing hidden state to the next step

โœ“Advantages
  • โ€ขCan handle variable-length sequences
  • โ€ขShares parameters across time steps
  • โ€ขMaintains a "memory" via hidden state
โœ—Critical Problems
  • โ€ขSequential bottleneck: Must process one word at a time (slow!)
  • โ€ขVanishing gradients: Hard to learn long-range dependencies
  • โ€ขInformation bottleneck: All context compressed into fixed-size hidden state

LSTM: Long Short-Term Memory Networks

LSTMs were designed to solve the vanishing gradient problem by introducing gates that control information flow

LSTM Cell Architecture
๐Ÿšช
Forget Gate

Decides what information to discard from cell state

ft = ฯƒ(Wf ยท [ht-1, xt])
๐Ÿ“ฅ
Input Gate

Decides what new information to store in cell state

it = ฯƒ(Wi ยท [ht-1, xt])
๐Ÿ“ค
Output Gate

Decides what to output based on cell state

ot = ฯƒ(Wo ยท [ht-1, xt])
Cell State Update
Ct = ft โŠ™ Ct-1 + it โŠ™ tanh(Wc ยท [ht-1, xt])

(Forget some old info + Add some new info = Updated memory)

Improvements over RNN
  • โœ“Better gradient flow via cell state "highway"
  • โœ“Can learn longer dependencies (100+ tokens)
  • โœ“More stable training
Still Limitations
  • โš Still sequential - cannot parallelize
  • โš Struggles with very long sequences (1000+ tokens)
  • โš Computationally expensive (4ร— gates)

Sequence-to-Sequence with Attention

A breakthrough came with the attention mechanism (Bahdanau et al., 2014) - allowing the model to "focus" on relevant parts of the input

Example: Machine Translation
Encoder (Source Language)
The
black
cat
Decoder (Target Language)
Le
Attends to: The
chat
Attends to: cat
noir
Attends to: black

Key Insight: When generating "noir" (black), the decoder can attend to the word "black" in the source, even though it appears in a different position!

The Birth of Attention

Attention mechanisms allowed models to create dynamic connections between input and output positions. This was revolutionary, but there was still a problem: the encoder and decoder were still RNNs/LSTMs, meaning they were still sequential and slow.

The question: What if we could use attention EVERYWHERE and get rid of recurrence entirely?

What are Large Language Models (LLMs)?

Large Language Models represent the culmination of decades of NLP research. They are neural networks trained on massive amounts of text data to understand and generate human language. The "large" refers to both the model size (billions of parameters) and training data (trillions of tokens).

LLM Components

๐Ÿ“Š
Massive Data

Books, websites, code repositories, articles

Trillions of tokens
๐Ÿง 
Transformer Architecture

Attention-based architecture that processes sequences in parallel

Billions of parameters
โšก
Training Process

Learning patterns through next-token prediction

Weeks of GPU compute

Key Characteristics of LLMs

1
Unprecedented Scale

Models range from millions to hundreds of billions of parameters. GPT-4 is estimated to have ~1.7 trillion parameters across multiple experts.

2
Emergent Capabilities

Can perform tasks they weren't explicitly trained for. At certain scales, models suddenly gain abilities like arithmetic, translation, and reasoning.

3
Contextual Understanding

Understand nuance, context, ambiguity, and can maintain coherent conversations across thousands of tokens.

4
Transfer Learning

Pre-trained knowledge can be fine-tuned for specific domains with minimal additional data, making them highly adaptable.

๐Ÿ’ผImpact on Financial Services

Customer Service

24/7 intelligent chatbots handling complex queries, understanding context across multiple interactions, and providing personalized financial advice.

Risk Analysis

Processing vast amounts of financial documents, earnings calls, news articles in seconds to identify risks and opportunities.

Compliance & Regulation

Automated monitoring of regulations, policy changes, and ensuring all communications meet compliance requirements.

Research & Analysis

Extracting insights from market data, financial news, analyst reports, and generating comprehensive investment research.

Transformer Architecture

The Transformer, introduced in the landmark 2017 paper "Attention Is All You Need" by Vaswani et al., revolutionized natural language processing. It solved the fundamental problems of RNNs/LSTMs by:

โšก

Parallel Processing

All tokens processed simultaneously instead of sequentially

๐ŸŽฏ

Direct Connections

Every word can attend to every other word directly

๐Ÿ“ˆ

Scalability

Can scale to billions of parameters efficiently

High-Level Architecture

ENCODER

Input Embeddings + Positional Encoding
โ†“
Encoder Block (ร—N)
Multi-Head Self-Attention
โ†“
Add & Normalize
โ†“
Feed Forward Network
โ†“
Add & Normalize
Stacked N times (e.g., 12 or 24 layers)

DECODER

Output Embeddings + Positional Encoding
โ†“
Decoder Block (ร—N)
Masked Multi-Head Attention
โ†“
Add & Normalize
โ†“
Cross-Attention to Encoder
โ†“
Add & Normalize
โ†“
Feed Forward Network
โ†“
Add & Normalize

Note: Modern LLMs like GPT use decoder-only architecture (no encoder). BERT uses encoder-only. Original Transformer used both for translation.

Input Preparation: From Text to Vectors

Step-by-Step Transformation

1
Input Text
"The cat sat on the mat"
โ†“
2
Tokenization
["The", "cat", "sat", "on", "the", "mat"]

Text split into tokens (can be words, subwords, or characters)

โ†“
3
Token IDs (Vocabulary Lookup)
[103, 2845, 2938, 2006, 103, 4971]

Each token mapped to unique integer from vocabulary (e.g., 50,000 tokens)

โ†“
4
Token Embeddings
[[0.12, -0.43, 0.87, ...], [0.34, 0.21, -0.56, ...], ...]

Each ID converted to dense vector (e.g., 768 dimensions). Learned during training.

โ†“
5
+ Positional Encoding
Embedding + Position โ†’ Final Input

Add positional information so model knows word order (sin/cos functions)

Why Positional Encoding?

Transformers process all tokens in parallel - they have NO inherent sense of order! We need to inject position information.

Formula (Sinusoidal)
PE(pos, 2i) = sin(pos / 10000^(2i/d))
PE(pos, 2i+1) = cos(pos / 10000^(2i/d))

Where: pos = position, i = dimension, d = embedding dimension

Properties
  • โœ“Unique encoding for each position
  • โœ“Can generalize to longer sequences
  • โœ“Allows model to learn relative positions
  • โœ“Deterministic (not learned parameters)

Self-Attention: The Core Innovation

Self-attention allows each word to look at all other words in the sequence and decide which ones are most relevant to understanding it. It's like giving each word the ability to ask: "Which other words should I pay attention to?"

Example: "The animal didn't cross the street because it was too tired"

What does "it" refer to?

Without Attention

"it" is just the 10th word. No understanding of what it refers to.

With Attention

"it" attends strongly to "animal" (not "street"), understanding the reference!

Attention scores for "it"
animal
0.65
tired
0.2
street
0.08
because
0.04
others
0.03

Query, Key, Value (QKV) Mechanism

Self-attention uses three transformations of the input: Query, Key, and Value

๐Ÿ”
Query (Q)

"What am I looking for?"

Q = X ยท WQ

The question each token asks

๐Ÿ”‘
Key (K)

"What do I have to offer?"

K = X ยท WK

What each token advertises

๐Ÿ’Ž
Value (V)

"What information do I give?"

V = X ยท WV

The actual content to pass

Deep Dive: What Are X and W?
๐Ÿ“ฅWhat is X?

X is the input matrix containing the embeddings of all tokens in your sequence. After tokenization and embedding lookup (+ positional encoding), each word becomes a vector of numbers.

X: Shape = (seq_length, d_model)

seq_length: Number of tokens in your input (e.g., 10 tokens)

d_model: Embedding dimension (e.g., 512 or 768)

Example: "The cat sat"
dim 0dim 1dim 2...dim 767
The0.12-0.430.87...0.21
cat0.340.21-0.56...-0.12
sat-0.230.670.45...0.89
Matrix shape: (3, 768) โ†’ 3 tokens ร— 768 dimensions
โš™๏ธWhat are WQ, WK, WV?

These are learned weight matrices that transform the input embeddings into different representations. Think of them as "projection lenses" that look at the same input from three different perspectives.

Weight Matrices Shape = (d_model, d_k)

d_model: Input embedding dimension (768)

d_k: Output dimension for Q and K (typically 64)

d_v: Output dimension for V (typically same as d_k)

WQ
(768, 64)
Transforms input into "query" space
WK
(768, 64)
Transforms input into "key" space
WV
(768, 64)
Transforms input into "value" space
๐Ÿ”ขThe Matrix Multiplication: X ยท W

When we compute Q = X ยท WQ, we're performing matrix multiplication that transforms each token's embedding from d_model dimensions to d_k dimensions.

X
(3, 768)
ร—
WQ
(768, 64)
=
Q
(3, 64)
Each of the 3 tokens now has a 64-dimensional query vector
Concrete Numerical Example

For token "cat" (row 2 of X):

X[1] = [0.34, 0.21, -0.56, ..., -0.12] (768 numbers)
โ†“ multiply by WQ โ†“

Result: Query vector for "cat"

Q[1] = [0.12, -0.34, 0.56, ..., 0.23] (64 numbers)

This query vector represents: "What is 'cat' looking for in other tokens?"

Why Do We Need Three Separate Transformations?

Q (Query): Represents what this token is "looking for" or "asking about". It encodes the search criteria.

K (Key): Represents what this token "advertises" or "offers" to other tokens. It's how tokens describe themselves.

V (Value): The actual information/content that will be passed along once we determine relevance.

Key Insight: Separating these three roles allows the model to learn different aspects of relationships. The Query and Key determine which tokens to pay attention to, while the Value determines what information to extract from those tokens. This is more powerful than using the same representation for all three purposes!

Library Analogy

Query: "I'm looking for books about machine learning"

Key: Each book's index card describing its content

Value: The actual book content

You compare your query with all keys, find relevant matches, then retrieve the corresponding values!

The Attention Formula

Attention(Q, K, V) = softmax(QKT / โˆšdk) V
The formula that changed AI forever
1
Compute Similarity: QKT

Dot product between query and all keys. High value = high relevance.

Shape: (seq_length, dk) ร— (dk, seq_length) โ†’ (seq_length, seq_length)
2
Scale: / โˆšdk

Divide by square root of key dimension to prevent vanishing gradients

Without scaling, dot products can be too large โ†’ softmax saturates
3
Softmax

Convert scores to probabilities (sum to 1). Determines how much to attend to each token.

Output: attention weights (0 to 1) for each position
4
Weighted Sum: ร— V

Multiply attention weights by values. Output is weighted combination of all values.

Final output: context-aware representation for each token

Multi-Head Attention: Power in Diversity

Instead of performing attention once, transformers use multiple attention heads in parallel. Each head learns to focus on different aspects of the relationships between tokens.

Why Multiple Heads?

๐Ÿ‘๏ธ
Head 1: Syntax

Focuses on grammatical relationships (subject-verb-object)

๐Ÿ”—
Head 2: Coreference

Tracks what pronouns refer to ("it" โ†’ "animal")

๐ŸŽจ
Head 3: Semantics

Captures meaning and context relationships

Multi-Head Attention Architecture
Input X (seq_len, d_model = 512)
โ†“
Head 1
WQ1, WK1, WV1
โ†“
Attention
โ†“
(seq, 64)
Head 2
WQ2, WK2, WV2
โ†“
Attention
โ†“
(seq, 64)
Head 3
WQ3, WK3, WV3
โ†“
Attention
โ†“
(seq, 64)
Head 4
WQ4, WK4, WV4
โ†“
Attention
โ†“
(seq, 64)
... typically 8 or 12 heads in parallel
โ†“
Concatenate all heads
(seq_len, 8 ร— 64 = 512)
โ†“
Linear projection: WO
(seq_len, d_model = 512)
MultiHead(Q, K, V) = Concat(head1, ..., headh) WO
where headi = Attention(QWQ,i, KWK,i, VWV,i)
The Magic of Multi-Head Attention
  • โœ“Each head can attend to different positions and capture different types of relationships
  • โœ“Smaller dimension per head (64 vs 512) makes computation efficient
  • โœ“Model learns richer representations by combining multiple perspectives

Layer Normalization & Residual Connections

Two critical techniques that enable training deep transformer networks: residual connections (skip connections) and layer normalization.

Residual Connections

Input: x
โ†“
Attention / FFN
F(x)
โ†“
+
Skip Connection
(original x)
โ†“
Output: x + F(x)
Why Residual Connections?
  • โœ“Enable gradient flow through deep networks
  • โœ“Allow model to learn identity function if needed
  • โœ“Preserve information from earlier layers

Layer Normalization

Formula
LayerNorm(x) = ฮณ ยท (x - ฮผ) / โˆš(ฯƒยฒ + ฮต) + ฮฒ

ฮผ: Mean across features

ฯƒยฒ: Variance across features

ฮณ, ฮฒ: Learned scale and shift parameters

ฮต: Small constant for numerical stability

Purpose
  • โœ“Stabilizes training by normalizing activations
  • โœ“Reduces internal covariate shift
  • โœ“Allows higher learning rates
  • โœ“Applied to each token's embedding independently

"Add & Norm" Pattern in Transformers

xinput
โ†“
xattn = LayerNorm(xinput + MultiHeadAttention(xinput))
โ†“
xoutput = LayerNorm(xattn + FeedForward(xattn))

Position-wise Feed Forward Network

After attention, each token passes through a simple 2-layer neural network independently. This is applied to each position separately and identically.

FFN Architecture

Input (d_model = 512)
โ†“
Linear Layer 1: W1
Expand to dff = 2048
โ†“
Activation: ReLU or GELU
Non-linearity
โ†“
Linear Layer 2: W2
Project back to dmodel = 512
โ†“
Output (d_model = 512)
FFN(x) = max(0, xW1 + b1)W2 + b2
Or with GELU: FFN(x) = GELU(xW1 + b1)W2 + b2
Key Characteristics
  • โ€ขApplied to each position independently
  • โ€ขSame weights shared across all positions
  • โ€ขIntermediate layer is 4ร— larger (2048 vs 512)
Purpose
  • โ€ขAdds non-linearity and complexity
  • โ€ขTransforms token representations after attention
  • โ€ขContains most of the model's parameters

Mixture of Experts (MoE)

Modern large models like GPT-4, Mixtral, and others use Mixture of Experts to scale efficiently. Instead of one feed-forward network, they have multiple "expert" networks and route each token to a subset of experts.

How MoE Works

Token Representation
โ†“
Router Network (Gating)
Decides which experts to use
โ†“
๐Ÿง 
Expert 1
FFN
๐Ÿง 
Expert 2
FFN
๐Ÿง 
Expert 3
FFN
๐Ÿง 
Expert 4
FFN
... up to 8, 16, or even 128 experts
โ†“
Weighted Combination
Top-K experts combined
โ†“
Output
Advantages
  • โœ“Sparse activation: Only 2-4 experts active per token
  • โœ“Efficient scaling: 100B+ parameters with cost of ~13B
  • โœ“Specialization: Experts learn different domains/tasks
  • โœ“Faster inference than dense models of same quality
Challenges
  • โš Load balancing: Ensure all experts are used
  • โš Training complexity: Need auxiliary loss functions
  • โš Memory requirements: All experts must fit in memory
Models Using MoE
GPT-4Mixtral 8x7BSwitch TransformerGLaMDeepseek V2

Putting It All Together: The Complete Transformer Block

Single Transformer Layer (Decoder Block)

Input: x (seq_len, d_model)
Multi-Head Self-Attention
1. Compute Q, K, V for each head
2. Apply attention mechanism
3. Concatenate heads
4. Linear projection
+
Add & Normalize
LayerNorm(x + Attention(x))
โ†“
Feed Forward Network
1. Linear: d_model โ†’ d_ff (2048)
2. Activation: GELU/ReLU
3. Linear: d_ff โ†’ d_model
+
Add & Normalize
LayerNorm(x + FFN(x))
โ†“
Output โ†’ Next Layer
Key Insights

Attention layer: Allows tokens to communicate and share information

FFN layer: Processes each token independently with non-linear transformations

Residual connections: Preserve information and enable deep architectures

Layer norms: Stabilize training and improve convergence

Full Model: Stack 12-96 of these layers, add final layer normalization and linear projection to vocabulary. That's a transformer!

Training vs Inference: How Transformers Actually Work

Now that we understand the transformer architecture, let's explore how transformers actually work in practice - the critical difference between training (learning from data) and inference (generating new text). Understanding this is essential for deploying LLMs in production financial systems.

Masked Self-Attention: Preventing "Cheating"

In decoder models (GPT, Claude, etc.), we use masked self-attention to prevent tokens from "looking ahead" at future tokens. This ensures the model learns to predict the next token using only past context.

The Problem: Without Masking

Imagine we're training the model on: "The stock price increased"

โŒ Without Masking (Cheating!):

When predicting "price", the model can see "increased" โ†’ It's cheating by looking at future tokens!

With masking, each token can only attend to itself and previous tokens:

โœ“ With Masking (Proper Training):

When predicting "price", the model can only see "The stock" โ†’ Must learn to predict next word from past context only!

Attention Mask Matrix (Causal Mask)

The mask is a lower-triangular matrix. A value of 1 means "can attend", 0 means "cannot attend" (or -โˆž in practice before softmax).

Thestockpriceincreased
The1000
stock1100
price1110
increased1111

Green (1): Token can attend to this position

Red (0): Token blocked from attending (future position)

Creating the Causal Mask (PyTorch):

import torch

seq_len = 4  # "The stock price increased"

# Create causal mask (lower triangular)
mask = torch.tril(torch.ones(seq_len, seq_len))

# In practice, convert 0s to -inf before softmax
# This ensures attention weights to future tokens = 0
mask = mask.masked_fill(mask == 0, float('-inf'))
mask = mask.masked_fill(mask == 1, 0.0)

# Applied in attention: softmax(QK^T / sqrt(d) + mask)
Why This Matters
  • โ€ขTraining: Ensures model learns proper sequential prediction
  • โ€ขCausality: Respects the order of information (can't use future to predict past)
  • โ€ขAutoregressive: Enables token-by-token generation at inference time

Training Phase: Learning from Data

During training, transformers process entire sequences in parallel using a technique called teacher forcing. This is fast and efficient.

How Training Works: Teacher Forcing

Training Example: "The company reported strong earnings"

INPUT (what we give the model):

[BOS] The company reported strong earnings
โ†“

TARGET (what we want the model to predict at each position):

Position 0: Predict "The" (after BOS)
Position 1: Predict "company" (after "The")
Position 2: Predict "reported" (after "company")
Position 3: Predict "strong" (after "reported")
Position 4: Predict "earnings" (after "strong")
Position 5: Predict [EOS] (after "earnings")
โ†“

KEY INSIGHT - Parallel Processing:

The model predicts ALL positions simultaneously in one forward pass! The causal mask ensures position N can only see positions 0 to N-1.

Loss Computation (Cross-Entropy)

For each position, compute cross-entropy loss:

Loss = -ฮฃ log P(correct_token | past_context)

Position 2 (predicting "reported"):

Context: "The company"
Target: "reported"
Model outputs probabilities over 50k vocab
Loss = -log P("reported" | "The company")

Backward Pass:

1. Compute total loss across all positions
2. Backpropagate gradients
3. Update all model parameters
4. Repeat for next batch
โœ“ Training Advantages
  • โ€ขParallel: All tokens processed simultaneously
  • โ€ขEfficient: Full GPU utilization, fast training
  • โ€ขDense signal: Learn from every token position
  • โ€ขTeacher forcing: Always has correct previous tokens
Training Scale
  • โ€ขBatch size: 1-8 million tokens per batch
  • โ€ขData: Trillions of tokens (entire internet!)
  • โ€ขTime: Weeks to months on thousands of GPUs
  • โ€ขCost: $10M - $100M+ for frontier models

Inference Phase: Autoregressive Generation

During inference (generation), the model produces text one token at a time in a sequential loop. This is called autoregressive generation and is fundamentally different from training.

Autoregressive Generation Loop

User Prompt: "The company's Q3 revenue"

Step 1: Initial Forward Pass
Input: [The, company's, Q3, revenue]
โ†’ Model outputs probability distribution over vocabulary
Generated: "increased" (highest probability)
Step 2: Append and Re-run
Input: [The, company's, Q3, revenue, increased]
โ†’ Forward pass through entire network again
Generated: "by" (highest probability)
Step 3: Continue...
Input: [The, company's, Q3, revenue, increased, by]
โ†’ Forward pass again
Generated: "15" (highest probability)
... repeat until [EOS] token or max length ...

Final Output:

"The company's Q3 revenue increased by 15% year-over-year."

Generation Flow Diagram
Prompt
โ†’
Forward Pass
โ†’
Sample Token
โ†“ (append token)
Loop back
โ†
Stop if [EOS] or max_length reached

Sampling Strategies: How to Choose the Next Token

The model outputs a probability distribution over 50,000+ tokens. How do we pick which one to generate? Different strategies produce different text characteristics.

1. Greedy Decoding
Always pick the token with the highest probability.
Probabilities: {increased: 0.45, grew: 0.30, rose: 0.15, ...}
โœ“ Choose: "increased" (highest)
Pros: Deterministic, fast
Cons: Repetitive, boring, can get stuck in loops
2. Temperature Sampling
Scale logits by temperature T before softmax. Controls randomness.
T = 0.1 (low): More confident, focused
Original: {increased: 0.45, grew: 0.30}
After T=0.1: {increased: 0.85, grew: 0.12} โ†’ More deterministic
T = 1.5 (high): More random, creative
Original: {increased: 0.45, grew: 0.30}
After T=1.5: {increased: 0.38, grew: 0.35} โ†’ More uniform
Use case: T=0.1-0.3 for factual tasks (finance!), T=0.7-1.0 for creative tasks
3. Top-k and Top-p (Nucleus) Sampling
Restrict sampling to most likely tokens to avoid nonsense.
Top-k (e.g., k=40):
Only consider top 40 tokens.
Set others to 0 probability.
Sample from these 40.
Top-p (e.g., p=0.9):
Include tokens until cumulative probability reaches 90%.
Dynamic cutoff based on distribution.
Best practice: Combine temperature + top-p for balanced output
โš  Inference Challenges
  • โ€ขSequential: Cannot parallelize token generation
  • โ€ขSlow: Each token requires full forward pass
  • โ€ขLatency: 500 tokens at 20 tokens/sec = 25 seconds!
  • โ€ขMemory: Must store KV cache for past tokens
  • โ€ขCost: More expensive per query than training per token
โœ“ Optimization Techniques
  • โ€ขKV Caching: Reuse past key-value computations
  • โ€ขQuantization: Use INT8/INT4 instead of FP16
  • โ€ขBatching: Process multiple requests together
  • โ€ขSpeculative decoding: Predict multiple tokens ahead
  • โ€ขStreaming: Show tokens as generated (better UX)

Financial Services: Training vs Inference in Practice

Understanding the difference between training and inference is crucial for deploying LLMs in production financial systems. Let's see how this plays out in practice.

๐Ÿ“š Training: Fine-tuning on Financial Documents

Scenario: Fine-tune a large language model (70B+ params) on your bank's credit analysis reports

Training Data Format:
Document: "Credit Score: 720. Debt-to-Income: 35%. Payment History: Excellent. Recommendation: APPROVE"
How Training Works:
  • โ€ข Process thousands of examples in parallel (batch size 64-256)
  • โ€ข Each document teaches the model the pattern of credit analysis
  • โ€ข Model learns: high credit score + low DTI โ†’ likely approval
  • โ€ข Training on 10,000 reports takes ~2-4 hours on A100 GPUs
10,000
Training Examples
2-4 hrs
Training Time
$50-200
Cost (GPU time)

๐Ÿš€ Inference: Real-time Credit Assessment

Scenario: Loan officer queries the fine-tuned model

User Input (Prompt):
"Analyze this applicant: Credit Score: 680. Debt-to-Income: 42%. Payment History: 2 late payments in past year. Provide recommendation:"
Autoregressive Generation (token-by-token):
Token 1: "Based"
Token 2: "on"
Token 3: "the"
Token 4: "provided"
Token 5: "information"
... (continuing for ~150 tokens)
Final: "Based on the provided information, this applicant presents MODERATE RISK. The credit score of 680 is acceptable, but the DTI of 42% exceeds our 40% threshold, and recent late payments indicate potential repayment issues. Recommendation: CONDITIONAL APPROVAL with 10% higher interest rate and required co-signer."
~150
Tokens Generated
5-8 sec
Response Time
$0.01-0.05
Cost per Query
Production Deployment Considerations for Financial Services
1.
Latency Requirements: Interactive applications need <2s response time. Use smaller models (7B-13B params) or optimize inference with quantization.
2.
Cost at Scale: 1 million queries/day at $0.02/query = $20,000/day = $7.3M/year. Consider self-hosting for high-volume use cases.
3.
Sampling Strategy: For factual financial analysis, use temperature=0.1-0.3 and top-p=0.9to minimize hallucinations and ensure consistent outputs.
4.
Streaming Responses: Show tokens as they're generated for better user experience. Critical for long-form reports (earnings analysis, due diligence).
5.
Audit Trail: Log all prompts, generated tokens, and sampling parameters for regulatory compliance and model monitoring.

Key Takeaways: Training vs Inference

๐ŸŽ“ Training

  • โœ“Parallel processing of entire sequences
  • โœ“Teacher forcing with ground truth
  • โœ“Fast and efficient (GPU saturated)
  • โœ“One-time cost (expensive but amortized)
  • โœ“Causal mask prevents looking ahead

๐Ÿš€ Inference

  • โœ“Sequential autoregressive generation
  • โœ“One token at a time (cannot parallelize)
  • โœ“Slower (bottleneck for deployment)
  • โœ“Per-query cost (adds up at scale)
  • โœ“Sampling strategy controls output quality

Why This Matters: Understanding training vs inference is essential for estimating costs, optimizing latency, and making architectural decisions when deploying LLMs in production financial systems. Training is a one-time investment; inference cost scales with usage.

Evolution of Foundation Models

From the first transformer in 2017 to today's multi-trillion parameter models, let's trace the remarkable evolution of foundation models and understand the key innovations at each stage.

GPT-1 (2018)

OpenAI
117M
Parameters
12
Layers
Decoder
Architecture
Key Innovation: Generative Pre-training
  • โ†’Pre-train on unlabeled text (BooksCorpus) using next-token prediction
  • โ†’Fine-tune on specific tasks with small labeled datasets
  • โ†’Showed that unsupervised pre-training works better than training from scratch
  • โ†’Established the "pre-train then fine-tune" paradigm

BERT (2018)

Google
340M
Parameters (BERT-Large)
24
Layers (Large)
Encoder
Architecture
Key Innovation: Bidirectional Training & Masked Language Modeling
  • โ†’Masked Language Modeling (MLM): Randomly mask 15% of tokens and predict them
  • โ†’Bidirectional context: Can see both left and right context (unlike GPT)
  • โ†’Next Sentence Prediction (NSP): Learns relationships between sentences
  • โ†’Dominated understanding tasks (classification, NER, Q&A) for years

The Debate: GPT (decoder-only, generative) vs BERT (encoder-only, understanding). Both architectures had their strengths - but the future belonged to decoder-only models...

GPT-2 (2019)

OpenAI
1.5B
Parameters
48
Layers
40GB
Training Data
Key Innovation: Scale + Zero-Shot Learning
  • โ†’10ร— larger than GPT-1, showing scaling laws in action
  • โ†’Zero-shot capabilities: Could perform tasks without fine-tuning, just from prompts
  • โ†’Coherent text generation over longer contexts
  • โ†’So good at generating realistic text that OpenAI initially delayed release due to safety concerns

GPT-3 (2020)

OpenAI
175B
Parameters
96
Layers
$12M
Training Cost (est.)
Key Innovation: Emergent Abilities & Few-Shot Learning
  • โ†’100ร— larger than GPT-2 - the first truly "large" language model
  • โ†’In-context learning: Could learn from examples in the prompt (few-shot)
  • โ†’Emergent abilities: Arithmetic, code generation, translation - not explicitly trained!
  • โ†’Launched via API - democratized access to powerful AI
  • โ†’Sparked the current Gen AI revolution and race

The Turning Point

GPT-3 proved that massive scale unlocks qualitatively new capabilities. The industry realized: bigger is genuinely better. The race to scale began.

ChatGPT / GPT-3.5 (2022)

OpenAI
~175B
Parameters (base)
100M+
Users in 2 months
RLHF
Key Training Method
Key Innovation: RLHF (Reinforcement Learning from Human Feedback)
  • โ†’Instruction tuning: Trained to follow instructions and engage in dialogue
  • โ†’RLHF: Human feedback used to align model behavior with human preferences
  • โ†’Conversational interface: Made AI accessible to everyone, not just developers
  • โ†’Fastest-growing consumer application in history
  • โ†’Brought Gen AI into mainstream consciousness

The Inflection Point

ChatGPT made AI tangible for billions of people. Within weeks, every tech company pivoted to Gen AI. The era of ubiquitous AI assistants had begun.

LLaMA / LLaMA 2 / LLaMA 3 (2023-2024)

Meta
7B-405B
Parameter Range
Open
Source (mostly)
15T+
Training Tokens
Key Innovation: Open-Weight Efficiency
  • โ†’Efficiency focus: Competitive performance at smaller scales
  • โ†’Open weights: Democratized access to powerful models
  • โ†’Fine-tuning ecosystem: Spawned thousands of derivative models (Alpaca, Vicuna, etc.)
  • โ†’LLaMA 3.1 (405B) rivals GPT-4 on many benchmarks
  • โ†’Enabled on-premise deployment for regulated industries
Impact on Finance

Open-weight models like LLaMA are crucial for financial institutions that require data sovereignty, customization, and regulatory compliance. Banks can fine-tune on proprietary data without sending it to third parties.

GPT-4 (2023)

OpenAI
~1.7T
Params (rumored, MoE)
Multimodal
Vision + Text
128K
Context Window
Key Innovations: Multimodality + Reasoning + MoE
  • โ†’Multimodal: Processes images, text, and code seamlessly
  • โ†’Advanced reasoning: Scores in 90th percentile on bar exam, excels at math
  • โ†’MoE architecture: Uses ~280B params per forward pass (efficient)
  • โ†’Tool use: Can call functions, browse web, run code
  • โ†’Massive context window allows analyzing entire codebases or reports

State of the Art (2023-2024)

GPT-4 represented the frontier of LLM capabilities: reasoning, coding, multimodal understanding. It showed that scaling + architectural improvements continue to yield gains.

PaLM 2 & Gemini (2023-2024)

Google
540B+
Parameters (PaLM 2)
Ultra/Pro
Gemini Tiers
Native
Multimodal
Key Innovations: Native Multimodality + Efficiency
  • โ†’PaLM 2: Excels at multilingual tasks, reasoning, and code
  • โ†’Gemini Ultra: Competitive with GPT-4 on most benchmarks
  • โ†’Native multimodality: Trained on text, images, audio, video from the start
  • โ†’Model sizes: Nano, Pro, Ultra for different use cases
  • โ†’Integrated deeply into Google ecosystem (Search, Workspace, Cloud)

Claude (2, 3, 3.5) (2023-2024)

Anthropic
200K+
Context Window
Opus
Top Tier Model
Safety
Core Focus
Key Innovations: Constitutional AI + Long Context + Reasoning
  • โ†’Constitutional AI: Trained with AI-generated feedback based on principles
  • โ†’Extended context: 200K tokens enables processing entire books
  • โ†’Claude 3.5 Sonnet: Best-in-class coding and reasoning
  • โ†’Safety focus: Lower refusal rates on harmless queries, higher on harmful ones
  • โ†’Preferred by many developers for nuanced, thoughtful responses
Why Claude Matters for Finance

Claude's extended context window and strong reasoning make it ideal for analyzing lengthy financial documents (10-Ks, contracts, regulations). Its safety-first approach aligns with compliance requirements.

The Current Landscape (2024-2025)

Key Trends
  • โ€ขMultimodality: Text + Vision + Audio + Video integration
  • โ€ขLong context: 100K-1M+ token windows
  • โ€ขEfficiency: Smaller models (7B-70B) approaching GPT-3.5 quality
  • โ€ขSpecialization: Domain-specific models for code, math, finance
  • โ€ขInference optimization: Quantization, distillation, speculative decoding
Open Questions
  • โ“Will scaling laws continue indefinitely, or are we approaching limits?
  • โ“How do we verify outputs and prevent hallucinations at scale?
  • โ“What's the right balance between open and closed models?
  • โ“Can we achieve GPT-4 level performance at 10ร— lower cost?
  • โ“How do we ensure safety, alignment, and regulatory compliance?
What's Next?

The next frontier: reasoning models (OpenAI o1, o3), agentic AI that can plan and execute complex tasks, personalized models that adapt to individual users, and multimodal agents that seamlessly interact with the physical and digital world. We're moving from passive question-answering to active problem-solving partners.

Fine-Tuning Large Language Models

Pre-trained foundation models are powerful, but they're generalists. To excel at specific tasks or domains (like financial analysis), we need to adapt them. Fine-tuning is the process of taking a pre-trained model and specializing it for your use case.

Why Fine-Tune?

๐ŸŽฏ
Domain Expertise

Adapt to specialized domains (finance, medicine, law) with domain-specific knowledge and terminology

๐Ÿ“Š
Better Performance

Achieve superior results on specific tasks compared to zero-shot or few-shot prompting

๐Ÿ”’
Data Privacy

Use proprietary data to customize models without exposing it via API prompts

๐Ÿ’ฐ
Cost Efficiency

Smaller fine-tuned models can match larger base models, reducing inference costs

Fine-Tuning Approaches

Full Fine-Tuning

Update all parameters of the model during training on your custom dataset.

Base Model (175B params) โ†’ Training โ†’ Fine-tuned Model (175B params)
Advantages
  • โœ“Maximum performance gains
  • โœ“Model fully adapts to new domain
Disadvantages
  • โœ—Extremely expensive (compute & memory)
  • โœ—Risk of catastrophic forgetting
  • โœ—Need multiple GPU clusters

PEFT (Parameter-Efficient Fine-Tuning)

Update only a small subset of parameters, keeping the base model frozen.

Base Model (frozen 175B) + Adapter (10M params) = Fine-tuned
Advantages
  • โœ“Train on consumer GPUs
  • โœ“100-1000ร— fewer params
  • โœ“No catastrophic forgetting
  • โœ“Swap adapters for multi-task
Trade-offs
  • โš Slightly lower performance ceiling
  • โš Requires careful hyperparameter tuning

Supervised Fine-Tuning (SFT)

The most common form of fine-tuning: train the model on input-output pairs to teach it specific behaviors or knowledge.

SFT Process

1
Prepare Training Data

Create dataset of (instruction, response) pairs

Example: Financial Q&A
Input: "What is the P/E ratio of Apple?"
Output: "As of [date], Apple's P/E ratio is 28.5, calculated as price per share divided by earnings per share..."
โ†“
2
Fine-Tune Model

Train using supervised learning (next-token prediction)

Loss = CrossEntropy(model_output, target_response)

Model learns to generate outputs that match your training examples

โ†“
3
Evaluate & Deploy

Test on held-out data, measure performance, deploy for inference

SFT for Financial Services
  • โ†’Fine-tune on financial reports to improve 10-K/10-Q analysis
  • โ†’Train on compliance documents to answer regulatory questions
  • โ†’Use customer service transcripts to build banking chatbots
  • โ†’Adapt to risk assessment tasks with historical loan data

RLHF: Reinforcement Learning from Human Feedback

RLHF is how models like ChatGPT learned to be helpful, harmless, and honest. Instead of just predicting the next token, models learn to maximize human preferences.

RLHF Pipeline

Phase 1: Supervised Fine-Tuning
Base โ†’ SFT Model

Start with high-quality human demonstrations to teach basic instruction-following behavior.

โ†“
Phase 2: Train Reward Model
Human Rankings
Collect Human Preferences
Prompt: "Explain compound interest"
โœ“ Response A (Preferred): Clear, accurate, helpful
โœ— Response B (Rejected): Confusing, contains errors

Train a reward model to predict which responses humans prefer. This model outputs a scalar score for any (prompt, response) pair.

Reward(prompt, response) โ†’ score (higher = better)
โ†“
Phase 3: RL Fine-Tuning (PPO)
Optimize for Reward

Use PPO (Proximal Policy Optimization) to fine-tune the model to maximize the reward model's scores, while staying close to the original model.

RL Objective
Maximize: E[reward(prompt, model_response)]
Constraint: KL_divergence(new_model, old_model) < threshold

The KL constraint prevents the model from drifting too far from its original behavior

โ†“
๐ŸŽ‰
RLHF Model

A model aligned with human preferences: helpful, honest, and harmless

Why RLHF Matters
  • โ†’Makes models conversational and instruction-following
  • โ†’Reduces harmful outputs and improves safety
  • โ†’Can encode complex human values that are hard to specify with rules
  • โ†’Used by ChatGPT, Claude, Gemini, and most production models

PEFT Techniques: Fine-Tuning on a Budget

Parameter-Efficient Fine-Tuning methods allow you to adapt large models with minimal compute. Instead of updating billions of parameters, update only millions.

LoRA (Low-Rank Adaptation)

Most Popular
Core Idea

Instead of updating the full weight matrix W, add a low-rank decomposition: W' = W + ฮ”W = W + BA, where B and A are much smaller matrices.

Original: W (d ร— d) โ†’ LoRA: W + BยทA
W
Original weights
(4096, 4096)
16.7M params
B
Low-rank matrix
(4096, 8)
32K params
A
Low-rank matrix
(8, 4096)
32K params
LoRA: 64K params vs Original: 16.7M params
~260ร— reduction in trainable parameters!
Advantages
  • โœ“Train 7B models on single consumer GPU
  • โœ“Adapter files are tiny (few MB vs many GB)
  • โœ“Can merge adapters or swap them on the fly
  • โœ“No inference latency penalty (merge at load)
Common Use Cases
  • โ†’Domain adaptation (finance, medicine, legal)
  • โ†’Task-specific fine-tuning (summarization, QA)
  • โ†’Multi-tenant serving (one base model, many adapters)

QLoRA (Quantized LoRA)

Combines quantization (4-bit) with LoRA to enable fine-tuning even larger models on limited hardware.

Memory Comparison
Full FP16 (65B model)~130 GB
4-bit + LoRA (65B model)~48 GB

Result: Fine-tune 65B models on a single 48GB GPU! Democratizes LLM customization.

Other PEFT Methods

Adapter Layers

Insert small trainable modules between frozen transformer layers. Simple but adds inference latency.

Prefix Tuning

Prepend trainable "virtual tokens" to the input. Model learns task-specific context without changing weights.

Prompt Tuning

Learn soft prompts (continuous embeddings) instead of discrete text. Extremely parameter-efficient.

Practical Considerations for Financial Institutions

When to Use Each Approach
Use SFT when:

You have labeled examples and want task-specific behavior

Use RLHF when:

You need human-like judgment and alignment with preferences

Use LoRA/QLoRA when:

Limited compute budget or need multiple task-specific models

Key Challenges
  • โš Data quality: Garbage in, garbage out. Need high-quality training data.
  • โš Overfitting: Small datasets can cause models to memorize instead of generalize
  • โš Catastrophic forgetting: Fine-tuning can degrade general capabilities
  • โš Evaluation: Hard to measure if model truly improved on your specific task
  • โš Compliance: Need audit trails, version control, and model governance
Recommendation for Financial Institutions

Start with LoRA fine-tuning on open-weight models (LLaMA 3, Mistral). This gives you control, data privacy, and cost efficiency. Use SFT for task-specific adaptation, then consider RLHF only if you need sophisticated alignment with complex human preferences. Always maintain rigorous evaluation pipelines and model versioning for regulatory compliance.

2025 โ€“ 2026 Updates

Latest Advancements in Foundation Models

The foundation model landscape has shifted dramatically. Here is what every practitioner needs to know today.

Paradigm Shift

The Reasoning Model Revolution

A new class of models โ€” called reasoning models โ€” emerged in late 2024 and changed how we think about model capabilities. Instead of answering immediately, they spend extra compute thinking before responding (test-time compute).

OpenAI o1 / o3 / o4-mini

OpenAI's reasoning series. o3 achieves near-human performance on graduate-level science and advanced math. o4-mini is fast and cheap.

Claude Extended Thinking

Anthropic's Claude 3.5/4.x with thinking mode: the model shows its reasoning chain. Excellent for multi-step compliance and legal analysis.

DeepSeek-R1

Open-weights Chinese reasoning model matching o1-level performance at a fraction of the cost. Shook the market in early 2025.

Google Gemini 2.5 Pro

Google's reasoning model with 1M-token context. Strong on code, science, and multimodal reasoning.

Finance Impact

Reasoning models excel at multi-step financial analysis: "Given this 10-K, calculate the debt coverage ratio, compare it to the industry average, and flag any covenant risks." Tasks that used to require Chain-of-Thought prompting now just need a clear goal statement.

Game Changer

Context Window Explosion

Context windows have grown 100ร— in two years, fundamentally changing what's possible without RAG.

ModelContext WindowWhat Fits
GPT-3.5 (2022)4K tokens~3 pages
GPT-4 Turbo128K tokens~100 pages / a short book
Claude 3.5/4.x200K tokens~150 pages / a full annual report
Gemini 2.0/2.5 Flash1M tokens~750 pages / an entire regulatory handbook

Implication: for many financial document tasks (single annual report Q&A, one regulatory circular), you can now load the entire document into context instead of building a RAG pipeline. RAG still wins for large corpora, freshness, access control, and cost at scale.

Model Landscape Update (2025โ€“2026)

Anthropic
Claude Haiku 4.5, Sonnet 4.6, Opus 4.8

Best for nuanced reasoning, safety-critical finance apps.

OpenAI
GPT-4o, o3, o4-mini

o3 for hard problems; o4-mini for cost-efficient reasoning at scale.

Google
Gemini 2.0/2.5 Flash, Pro, Ultra

Best multimodal capabilities; Flash is very cost-efficient.

Meta (Open)
Llama 4 Scout, Maverick

Open weights; deploy in your own infrastructure for data control.

DeepSeek (Open)
DeepSeek-V3, DeepSeek-R1

Competitive with frontier models; open weights; cost disruption.

Microsoft
Phi-4 (14B)

Small but capable; runs on-device; no data leaves the endpoint.

Small Language Models (SLMs)

Phi-4 (14B), Gemma 3 (27B), Llama 3.2 (3B/11B) prove you don't need a massive model for every task.

  • โ€ขRun entirely on-device (laptop, mobile, edge server)
  • โ€ขNo data leaves your environment โ€” critical for MNPI handling
  • โ€ขFaster and cheaper for high-volume, simple tasks
  • โ€ขFinance use: document classification, PII detection, form parsing

Multimodal Becomes Standard

Every frontier model now handles text + images natively. Some handle audio and video too.

  • โ€ขGPT-4o: real-time text + vision + audio in one model
  • โ€ขGemini 2.0: text + vision + audio + video + code execution
  • โ€ขFinance use: read earnings slides directly, analyze portfolio charts, process scanned regulatory forms
  • โ€ขNo more OCR pipelines for standard document types
๐Ÿงช
Try Lab 1: Model Comparison Bench
Run one financial task on two or more models and compare accuracy, honesty about missing facts, speed and consistency. About 30 minutes.
Try the Lab โ†’