← Back to portfolio

Why Not Build an LLM?

How to talk our customers off the ledge…

Tim Sent · Director, Enterprise Architecture — Tech, Media & Telecom · June 24, 2024

A case for Retrieval-Augmented Generation over training a proprietary LLM from scratch — the cost curve behind frontier models, the history of deep learning and transformers that got us here, the datasets and benchmarks the field trains and evaluates against, the word-embedding and attention mechanics underneath every modern model, and the RAG and vector-database architecture that makes pre-trained models enterprise-ready without a nine-figure training bill.

Overview

What this covers

The Cost Case

Motivation for proprietary LLMs, business demands fueling model growth, and the true costs of training frontier models.

The History

Word embeddings, deep learning foundations, and the attention mechanism that produced the transformer era.

The Data & Evaluation

Open-source training datasets and the benchmarks used to evaluate language model performance.

In-Context Learning

Retrieval-Augmented Generation as the practical alternative to training from scratch.

Hypothesis

RAG achieves better results than training a proprietary LLM

Retrieval-Augmented Generation (RAG) achieves better results than training a proprietary large language model due to lower initial costs, reduced maintenance requirements, access to diverse data sources, optimized utilization of human resources, and the integration of extensive pre-existing knowledge.

01

Leveraging Extensive Pre-Trained Knowledge

  • RAG utilizes existing large language models already pre-trained on vast and diverse datasets, providing a strong baseline of language understanding
  • These models come equipped with extensive linguistic and factual knowledge, directly leveraged without training from scratch
02

Cost Efficiency

  • Using pre-trained models avoids the significant expenses of training from scratch — compute resources, data acquisition, and time
  • Continuous updates and maintenance of custom-trained models are costly; RAG relies on robust, well-maintained pre-trained models instead
03

Time to Market

  • Integrating domain-specific knowledge via RAG is much faster than training a proprietary model, enabling quicker deployment
  • Companies can start using a high-performance model almost immediately and incrementally improve capabilities through targeted augmentation
04

Scalability and Flexibility

  • RAG allows models to be adapted to new domains by integrating external knowledge sources, without extensive retraining
  • It can dynamically retrieve and incorporate up-to-date information, keeping the model relevant and accurate over time
05

Enhanced Performance with Domain-Specific Information

  • RAG improves contextual relevance by augmenting the model's base knowledge with domain- or customer-specific information
  • Targeted retrieval mechanisms enhance the precision and accuracy of outputs on specialized tasks
06

Innovation and Focus

  • Companies benefit from continuous improvements made by the broader AI research community in pre-trained models
  • Resources can go toward product features and user experience rather than developing foundational AI technology
07

Data Privacy and Security

  • RAG allows controlled integration of proprietary or sensitive data, ensuring privacy and security requirements are met
  • Using established models with robust security features helps adhere to regulatory standards more easily
08

Reducing Model Hallucination

  • RAG mitigates hallucination by retrieving accurate, up-to-date information from trusted sources
  • Grounding responses in verifiable data enhances the reliability of the generated content

Deep Learning Foundations

From the perceptron to the modern era

1943

The Perceptron

Invented by Warren McCulloch and Walter Pitts.

1958

Rosenblatt's Perceptron

Frank Rosenblatt introduces the Perceptron, an early form of neural network, demonstrating the potential of machines to learn from data.

1965

First Deep Feedforward Network

Published by Alexey Grigorevich Ivakhnenko and Valentin Lapa.

1975

Backpropagation

Paul Werbos introduces the concept of backpropagation in his PhD thesis, though it does not gain immediate recognition.

1982

Hopfield Network

John Hopfield introduces a neural network architecture capable of serving as an associative memory system.

1986

Backpropagation Popularized

David Rumelhart, Geoffrey Hinton, and Ronald Williams popularize backpropagation, allowing multi-layer networks to learn complex patterns — the beginning of the modern era of neural networks.

1990

Elman Network

A form of recurrent neural network (RNN) capable of processing sequences by maintaining a state that captures temporal information.

1997

LSTM

Long Short-Term Memory networks are introduced by Sepp Hochreiter and Jürgen Schmidhuber, addressing the vanishing-gradient problem in traditional RNNs and enabling long-range dependency learning.

2006

Deep Belief Networks

Geoffrey Hinton and colleagues introduce Deep Belief Networks, sparking renewed interest in deep learning with efficient training methods for deep architectures.

2009

Dropout

Introduced by Geoffrey Hinton as a technique for preventing overfitting, improving the generalization of deep networks.

2012

AlexNet

Alex Krizhevsky, Ilya Sutskever, and Geoffrey Hinton win the ImageNet competition by a large margin, significantly pushing forward deep learning in computer vision.

2014

GANs & Seq2Seq

Ian Goodfellow et al. introduce Generative Adversarial Networks. The same year, Google's Seq2Seq models revolutionize sequence learning, using two RNNs to transform an input sequence into an output sequence — useful for tasks like machine translation.

Attention Mechanism & Transformers

2017–2023: the transformer era

2017

"Attention Is All You Need"

Vaswani et al. introduce the original Transformer model, replacing recurrent layers with self-attention — enabling significantly more parallelization and improving training speed and performance on tasks like translation.

2018

BERT & GPT

Google releases BERT, pre-training deep bidirectional representations to state-of-the-art results across NLP benchmarks. OpenAI introduces GPT, a 117M-parameter transformer pre-trained on a large text corpus, showing a pre-trained transformer can generate coherent, contextually relevant text.

2019

GPT-2 & DistilBERT

OpenAI scales to GPT-2 (1.5B parameters), showing greater ability to generate coherent, persuasive text. DistilBERT introduces knowledge distillation — 40% smaller, 60% faster, most of BERT's performance retained.

2020

GPT-3

OpenAI releases GPT-3 at 175 billion parameters, demonstrating strong performance across tasks without task-specific tuning — setting a new standard for generative models.

2021

Data2Vec & Switch Transformers

Facebook's Data2Vec learns representations across text, images, and sound via self-supervised learning. Google's Switch Transformers use a mixture-of-experts approach, training very large models more efficiently by routing tokens to different parameter subsets.

2022

PaLM & InstructGPT

Google's PaLM demonstrates pathway-based model scaling with state-of-the-art multitasking and generalization results. OpenAI's InstructGPT trains models to follow instructions better, paving the way for practical applications.

2023

GPT-4 & LLaMA

OpenAI introduces GPT-4, refining the balance between generative capability and controlled output. Meta releases LLaMA (7B–65B parameters), then LLaMA-2 (7B/13B/70B), then LLaMA-3 (8B/70B, pre-trained on ~15T tokens) — each aiming for a more accessible alternative to closed models.

Customer Motivations

Why companies still want a proprietary LLM

Companies are motivated to create proprietary large language models to achieve tailored solutions that meet specific business needs, enhance competitive differentiation, maintain control over data privacy and security, and drive innovation aligned with their strategic objectives.

Domain Specific

  • Incorporates domain-specific knowledge, improving handling of industry-specific queries and tasks
  • Fine-tuned to the company's specific needs, often performing more accurately than generic models

Competitive Advantage

  • Unique features set the company apart from competitors — a significant market advantage
  • Owning a proprietary LLM fosters innovation, enabling new applications and services

Integration with Existing Systems

  • Designed to integrate with a company's existing IT infrastructure, ensuring compatibility
  • Optimized for the company's specific workflows and processes

Data Privacy and Security

  • Companies maintain full control over their data, ensuring compliance with privacy regulations
  • Can be designed to handle sensitive information securely, reducing third-party breach risk

Case Study

BloombergGPT: a large language model for finance

BloombergGPT is a specialized transformer-based language model designed by Bloomberg to enhance NLP capabilities within the financial domain. It incorporates a large number of layers and attention heads, tailored to process and analyze vast amounts of financial data. It excels at financial sentiment analysis, named entity recognition, and market prediction.

Key Features

  • Specialized for the financial domain
  • Excels in financial sentiment analysis, named entity recognition, and market prediction
  • Pre-trained on diverse financial texts — news articles, reports, and market data
  • High accuracy in domain-specific language understanding and generation

Architecture & Pre-training

  • Decoder-only transformer using self-attention to weigh word importance
  • 700B-token training corpus — half domain-specific text, half general-purpose
  • Masked Language Modeling (MLM) predicts masked tokens to learn context and meaning
  • Next Sentence Prediction (NSP) helps the model understand sentence relationships

Trained on "news, filings, press releases, web-scraped financial documents, and social media drawn from Bloomberg archives."

arxiv.org/abs/2303.17564 — Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Lukasz Kaiser, Illia Polosukhin

Landscape

Three types of models

Open Source

Full accessibility of source code and model weights. Community-driven development, modifiable, complete transparency in training data and methods, cost-effective.

Examples

  • GPT-Neo — EleutherAI
  • DistilBERT — Hugging Face
  • ALBERT — Google Research
  • RoBERTa — Facebook AI

Proprietary

Exclusive access requiring payment or agreements. High performance, comprehensive support, frequent updates, security and compliance measures.

Examples

  • Claude 3 Opus — Anthropic
  • GPT-3 — OpenAI
  • Megatron-Turing NLG — NVIDIA/Microsoft
  • Jurassic-1 — AI21 Labs

Open Models

Limited public accessibility, often through specific platforms or usage limits. Research-focused, benefits from community contributions, generally more transparent than proprietary models.

Examples

  • GPT-2 — OpenAI
  • T5 — Google Research
  • BERT — Google

Costs of Training Large Language Models

What it actually costs to train a frontier model

GPT-3 cost roughly $4.6M to train — using ~570GB of training data and 10,000 GPUs to train its 175B parameters. Released June 2020.

Data & Processing

Data Sources

  • Books, websites, academic papers

Datasets

  • Common Crawl / Wikipedia
  • Proprietary datasets

Cleaning & Prep

  • Removing duplicates
  • Filtering low-quality content
  • Normalizing misspellings

Tokenization

  • Byte Pair Encoding (BPE)
  • SentencePiece Encoding

Computational Resources

Hardware

  • High-performance GPUs — NVIDIA V100 or A100
  • TPUs from Google

Infrastructure

  • AWS, Google Cloud, Microsoft Azure

On-Premise Clusters

  • Dedicated computing clusters
  • Significant upfront investment

Time & Human Resources

Initial Training

  • Several weeks to months

Iterative Training

  • Iterative cycles of training, evaluation, and tuning that prolong the overall timeline

Team

  • Dozens of data scientists, ML engineers, project managers, researchers, IT/support staff

Illustrative Annual Cost Breakdown

$1.79M
Hardware & compute — 1,000 GPUs
$3.35M
Human resources (annual): 5 data scientists ($150K ea), 5 ML engineers ($200K ea), 5 research scientists ($220K total), 5 support staff ($100K total)
$700K
Infrastructure & ops (annual) — software tools
$4.6M
GPT-3's total training cost, for comparison

The Rising Costs of Frontier AI Models

Detailed cost estimates for hardware, energy, cloud rental, and staff

The costs of training frontier AI models have grown dramatically, but there is limited public data on the magnitude and growth of these expenses. Epoch AI's analysis estimates training costs using three approaches accounting for hardware, energy, cloud rental, and staff expenses.

→

Cost to train the most compute-intensive models has grown 2.4× per year since 2016 (95% CI: 2.0×–3.1×)

→

For frontier models like GPT-4 and Gemini, the largest expenses are AI accelerator chips and staff costs — each tens of millions of dollars

→

Other notable costs: server components (15–22%), cluster-level interconnect (9–13%), and energy consumption (2–6%)

If the trend continues, the largest training runs will cost more than a billion dollars by 2027 — meaning only the most well-funded organizations will be able to finance frontier AI models.

arxiv.org/abs/2405.21015 — Ben Cottier, Robi Rahman, Loredana Fattorini, Nestor Maslej, David Owen

Scale

Language models have grown exponentially

Parameter counts of major public and proprietary models, October 2018 (BERT) through May 2024 (GPT-4o) — plotted on a log scale.

100M 1B 10B 100B 1T 10T 2019 2020 2021 2022 2023 2024 BERT Base 110M GPT-2 1.5B T5 11B GPT-3 175B GPT-Neo 2.7B GPT-J 6B BloombergGPT 50B GPT-4 1.76T Mistral 7B Mixtral 8x7B Claude 3 Opus 2T LLaMA 3 70B GPT-4o 1.76T

Selected models plotted from the table below (log-scale parameter count vs. release date). Red points mark OpenAI's GPT-3 → GPT-4 jump — roughly a 10× parameter increase in under three years.

Full Model Comparison

ModelParametersDeveloperRelease DateCorpus SizeCtx WindowType
Gemma7,000,000,000,000GoogleFebruary 20246T Tokens8,192Decoder-Only
Phi-22,700,000,000,000MicrosoftDecember 20231.4T Tokens2,048Decoder-Only
Claude 3 Opus2,000,000,000,000AnthropicMarch 2024—200,000Encoder-Decoder
GPT-4o1,760,000,000,000OpenAIMay 2024—128,000Decoder-Only
GPT-4 Turbo1,760,000,000,000OpenAINovember 2023—128,000Decoder-Only
GPT-41,760,000,000,000OpenAIMarch 2023—8,192Decoder-Only
GPT-3175,000,000,000OpenAIJune 20203000B Tokens16,385Decoder-Only
LLaMA 370,000,000,000Meta AIApril 202415T Tokens8,192Decoder-Only
Claude 3 Sonnet70,000,000,000AnthropicMarch 2024—200,000Encoder-Decoder
Bloomberg GPT50,000,000,000BloombergMarch 2023700B Tokens—Decoder-Only
Mixtral 8x7B46,700,000,000MixtralJanuary 2024—64,000Decoder-Only
Claude 3 Haiku20,000,000,000AnthropicMarch 2024—200,000Encoder-Decoder
T5 11B11,000,000,000Google AIOctober 201934B Tokens512Encoder-Decoder
Mistral 7B7,300,000,000MixtralSeptember 2023—32,000Decoder-Only
GPT-J6,000,000,000EleutherAIJune 2021—2,048Decoder-Only
T5 3B3,000,000,000Google AIOctober 2019—512Encoder-Decoder
GPT-Neo 2.7B2,700,000,000EleutherAIMarch 2021—2,048Decoder-Only
CTRL1,600,000,000SalesforceSeptember 2019—256Decoder-Only
GPT-2 (largest)1,500,000,000OpenAIFebruary 2019—1,024Decoder-Only
GPT-Neo 1.3B1,300,000,000EleutherAIMarch 2021—2,048Decoder-Only
T5 Large770,000,000Google AIOctober 2019—512Encoder-Decoder
XLM-R Large550,000,000Facebook AINovember 2019—512Encoder-Only
BART Large406,000,000Meta AIOctober 2019—1,024Encoder-Decoder
RoBERTa Large355,000,000Meta AIJuly 2019—512Encoder-Only
BERT Large340,000,000Google AIOctober 2018—512Encoder-Only
ERNIE 2.0 Large340,000,000BaiduJuly 2019—512Encoder-Only
ELECTRA Large335,000,000Google AIMarch 2020—512Encoder-Only
Marian MT300,000,000MicrosoftOctober 2020—512Encoder-Decoder
XLM-R Base270,000,000Meta AINovember 2019—512Encoder-Only
T5 Base220,000,000Google AIOctober 2019—512Encoder-Decoder
RoBERTa Base125,000,000Meta AIJuly 2019—512Encoder-Only
BERT Base110,000,000Google AIOctober 2018—512Encoder-Only
XLNet Base110,000,000Google AIJune 2019—512Encoder-Only
ERNIE 2.0 Base110,000,000BaiduJuly 2019—512Encoder-Only
DistilBERT66,000,000Hugging FaceOctober 2019—512Encoder-Only
T5 Small60,000,000Google AIOctober 2019—512Encoder-Decoder

A frontier model is a state-of-the-art machine learning model representing the pinnacle of current capabilities — typically characterized by massive parameter counts, enabling it to process and understand vast amounts of data.

Chinchilla

Balancing model size, training tokens, and compute

Chinchilla is a family of large language models developed by DeepMind and introduced in March 2022, named as a successor to the Gopher model family, designed to further explore the scaling laws of large language models.

Researchers trained models ranging from 70 million to over 16 billion parameters on 5 to 500 billion tokens, and found that models trained following the optimal scaling law significantly outperformed larger, undertrained models such as GPT-3 and Megatron-Turing NLG.

ModelLayersHeadsKey/Value SizeDimension
Gopher 280B8012812816,384
Chinchilla 70B80641288,192

Optimized Training Algorithms

Employs advanced training algorithms designed to minimize redundant computations — improved data sampling, gradient accumulation, and adaptive learning rates for faster convergence with less compute.

Enhanced Transformer Architecture

Integrates more efficient attention mechanisms and optimized layer configurations, maintaining high performance with fewer computational resources and lower energy usage.

Chinchilla Scaling Law

Training Compute-Optimal Large Language Models

Detailed in Hoffmann et al.'s paper of the same name, the Chinchilla Scaling Law addresses the optimal balance between model size, number of training tokens, and compute power to maximize performance within a given compute budget.

Model Size

Models with more parameters require more computational resources. More parameters necessitate more powerful, expensive hardware — increasing cost via GPU/TPU requirements and longer training times.

Optimal Balance

To achieve compute-optimal training, model size and the number of training tokens should scale equally — for every doubling of model size, training tokens should also double.

Undertraining Issue

Many current LLMs are undertrained because they use a constant amount of training data despite increasing model sizes — an imbalance that leads to suboptimal performance.

A model trained under the Chinchilla scaling law, despite being smaller in parameter count, achieved better performance and required less compute for fine-tuning and inference — underscoring the importance of balancing model size with training data.

arxiv.org/abs/2203.15556 — Jordan Hoffmann, Sebastian Borgeaud, Arthur Mensch, Elena Buchatskaya, Trevor Cai, Eliza Rutherford, Diego de Las Casas, Lisa Anne Hendricks, Johannes Welbl, Aidan Clark, Tom Hennigan, Eric Noland, Katie Millican, George van den Driessche, Bogdan Damoc, Aurelia Guy, Simon Osindero, Karen Simonyan, Erich Elsen, Jack W. Rae, Oriol Vinyals, Laurent Sifre

Open-Source Training Datasets

A growing number of high-quality datasets

Media & News Data

The Pile (886GB)

Books, academic papers, and web scrapes.

wikipedia.org →

Wikipedia

Comprehensive Wikipedia article corpus. Used by GPT-3, BERT, T5, RoBERTa, ELECTRA.

wikipedia.org →

RealNews

News articles from various websites. Used by GPT-2.

paperswithcode.com →

OpenSubtitles

Movie and TV subtitles. Used by GPT-2, BERT, T5.

paperswithcode.com →

COCO

Common Objects in Context — image dataset with context descriptions.

Web Data

Common Crawl (250B pages)

Vast repository of web page data. Used by GPT-3, GPT-2, GPT-Neo, BERT, T5.

commoncrawl.org →

Common Corpus (500B words)

The largest public-domain dataset released for training LLMs.

huggingface.co →

WebText (40GB)

Internal OpenAI corpus scraped with emphasis on document quality.

Reddit Corpus

Conversations and discussions from Reddit. Used by GPT-3.

Hugging Face Datasets

Platform providing access to multiple datasets. Used by GPT-3, BERT, RoBERTa.

ROOTS Corpus (1.6TB, 59 languages)

Responsible Open-science Open-collaboration Text Sources — used by the 176B-parameter BLOOM model.

SQuAD

Stanford Question Answering Dataset for QA tasks.

Literary & Academic Data

BooksCorpus (11,000 books)

High-quality book text. Used by BERT, RoBERTa.

arxiv.org →

Project Gutenberg (70K books)

Free eBooks including classical texts.

gutenberg.org →

arXiv

Repository of scientific papers. Used by GPT-3, BERT.

arxiv.org →

PubMed

Biomedical literature database. Used by BioBERT, SciBERT.

pubmed.ncbi.nlm.nih.gov →

USPTO

US Patent and Trademark database.

developer.uspto.gov →

Pile-of-Law

Court Listener, Federal Register, State Codes, Congressional Hearings, and more.

huggingface.co →

SWAG

Large-scale adversarial dataset for grounded commonsense inference.

WMT

Workshop on Machine Translation datasets. Used by MarianMT, T5.

The Pile

An 825GB dataset of diverse text, 22 subsets

The Pile is an 825 GiB English text corpus targeted at training large-scale language models, constructed from 22 diverse, high-quality subsets derived from academic and professional sources. Models trained on it improve significantly over both raw Common Crawl and CC-100 across all its components, while also improving downstream evaluation performance.

ComponentRaw Size (GB)Weight (%)EpochsSize (GB)Mean Doc Size (KB)
Pile-CC227.1218.111227.124.33
PubMed Central90.2714.402180.5530.55
Books3†100.9612.071.5151.44538.36
OpenWebText262.7710.012125.543.85
ArXiv56.218.962112.4246.61
Github95.167.59195.165.25
FreeLaw51.156.121.576.7315.06
Stack Exchange32.205.13264.392.16
USPTO Backgrounds22.903.65245.814.08
PubMed Abstracts19.263.07238.531.30
Gutenberg (PG-19)†10.882.172.527.19398.73
OpenSubtitles†12.981.551.519.4730.48
Wikipedia (en)†6.381.53319.131.11
DM Mathematics†7.751.24215.498.00
Ubuntu IRC5.520.88211.03545.48
BookCorpus26.300.751.59.45369.87
EuroParl†4.590.7329.1768.87
HackerNews3.900.6227.804.92
YoutubeSubtitles3.730.6027.4722.55
PhilPapers2.380.3824.7673.37
NIH ExPorter1.890.3023.792.11
Enron Emails†0.880.1421.761.78
The Pile (Total)825.18100—1254.205.91

To enable easier compliance with local laws, the Pile reproduction code is available and can exclude certain components inappropriate for a given user — undertaken at the component level, since exact per-text copyright metadata isn't available.

arxiv.org/abs/2101.00027v1 — Dec 2020 · Leo Gao, Stella Biderman, Sid Black, Laurence Golding, Travis Hoppe, Charles Foster, Jason Phang, Horace He, Anish Thite, Noa Nabeshima, Shawn Presser, Connor Leahy

Databricks

Open-source innovation: Dolly and DBRX

DBRX

An open, general-purpose LLM created by Databricks with a fine-grained mixture-of-experts architecture, released March 27, 2024.

  • Architecture: Mixture-of-experts transformer
  • Parameters: 132B total, 36B active per token
  • Versions: Base foundation model + instruct-tuned variant
  • Outperforms LLaMA 2, Mixtral, Grok, and GPT-3.5 on the Databricks Model Gauntlet and Hugging Face Open LLM Leaderboard
  • Training: 2.5 months on 3,072 Nvidia H100s (3.2 Tb/s InfiniBand)
  • Training cost: $10M USD
  • Training dataset: 12T curated tokens

Dolly & Dolly 2.0

An open-source LLM developed by Databricks to democratize access to high-performing language models, released April 12, 2023.

  • Architecture: GPT-like decoder-based transformer
  • Parameters: 6 billion
  • Versions: Base foundation model + instruct-tuned variant
  • Competitive with other open-source models on summarization, QA, and content creation
  • Training dataset: The Pile, Wikipedia subsets, Databricks Questions — may contain copyrighted material from web scraping

Benchmarks for Evaluating LLM Performance

How the field measures a model

Commonsense & Reasoning

BIG-Bench

204 language tasks covering a range of topics and languages, not fully solvable by current models.

Tasks Include

  • Logical reasoning
  • Free response
  • Reading comprehension
  • Programmatic
  • Mathematics

The HELM Benchmark

Comprehensive evaluation categorizing potential use cases and metrics, adopting a multi-metric approach across core scenarios.

Tasks Include

  • Recognition of incompleteness
  • Multi-metric measurement
  • Targeted evaluations
  • Standardization

General Language Understanding

GLUE

Nine diverse NLP tasks evaluating models' understanding and generalization across domains.

Tasks Included

  • Sentiment analysis (SST-2)
  • Natural language inference (MNLI)
  • Similarity & paraphrase (MRPC, QQP, STS-B)
  • Linguistic acceptability (CoLA)
  • Commonsense reasoning (RTE)
  • Question answering (QNLI)

SuperGLUE

An extension of GLUE with additional tasks focused on reasoning and coreference resolution.

Additional Tasks

  • Coreference resolution (WSC)
  • Question answering (BoolQ, MultiRC)
  • Word sense disambiguation (WiC)
  • Sentence completion (COPA)

Reading Comprehension & Question Answering

SQuAD

Stanford Question Answering Dataset. 1.1 requires finding exact answers in text; 2.0 adds unanswerable questions to test model understanding.

MMLU

Massive Multitask Language Understanding — 57 exam-like tasks spanning elementary mathematics, US history, computer science, law, and more.

FLASK

Decomposes coarse-level scoring into skill-set-level scoring for each instruction — model-based evaluation with comparison and correlation analysis.

COPA / WiC

COPA: Choice of Plausible Alternatives. WiC: a binary classification benchmark evaluating context-sensitive word embeddings across two contexts per target word.

HELM

Holistic Evaluation of Language Models

Benchmarks like SuperGLUE, EleutherAI LM Harness, and BIG-bench differ in their selection of scenarios and metrics, each with varying priorities and transparency. HELM aims for holistic evaluation by explicitly detailing the relationship between intended and actual evaluations through a top-down taxonomy of scenarios and metrics.

Recognition of Incompleteness

HELM implements a core set of 16 scenarios across tasks (question answering, information retrieval, summarization, toxicity detection) and domains (news, books), currently focused on English.

Multi-Metric Measurement

Seven categories of metrics — accuracy, calibration, robustness, fairness, bias, toxicity, efficiency — cover 98 of 112 possible scenario-metric pairs (87.5%).

Metrics

  • Ethics and Fairness
  • Knowledge and Information Retrieval
  • Creativity
  • Robustness and Calibration
  • Bias and Toxicity
  • Efficiency

Tasks Performed

  • General Language Understanding
  • Reading Comprehension
  • Question Answering
  • Commonsense Reasoning
  • Logical Reasoning
  • Mathematical Reasoning

arxiv.org/abs/2211.09110 — Holistic Evaluation of Language Models

LLM Benchmark for CRM

Salesforce launches the world's first CRM benchmark

Salesforce developed the first LLM benchmark for CRM to assess the efficacy of generative AI models for business applications — evaluating LLMs for sales and service use cases across accuracy, cost, speed, and trust & safety, based on real CRM data and expert evaluations. What sets it apart: human evaluations by both Salesforce employees and actual external customers, on real-world datasets from Salesforce and customer operations.

Accuracy

  • Factuality — is the response true and free of false information?
  • Instruction following — content and format per request
  • Conciseness — to the point, no repetition
  • Completeness — comprehensive, all relevant info

Cost

Some use cases require over ½ million calls per year. If a model is at the right cost, accuracy can be increased if needed — shown as high/medium/low.

Speed

Also known as latency — critical for real-time use cases, though some are asynchronous. Defined as seconds needed for a full LLM response.

Trust

Average of Safety, Privacy, Truthfulness, and CRM Fairness — how often the LLM avoids unsafe answers, avoids revealing private info, stays accurate, and returns unbiased results across account/gender perturbations.

Word Embeddings

Learning general language representations

The initial phase of training transformer-based models: learning general language representations from a large and diverse corpus of text data.

TF-IDF

1972

Bag of Words

Foundational

Word2Vec

2013

GloVe

2014

RNNs / LSTM

2015

Transformers

2017

BERT / GPT

2018

The NLP evolution strip that recurs across this section of the deck.

Bag of Words

A foundational text-encoding technique originating in the early 1950s: text is represented as an unordered collection of words, disregarding grammar and word order. A vocabulary is built from the entire corpus, and each document becomes a vector indicating the frequency (or presence/absence) of each vocabulary word. This transforms text into a numerical format suitable for ML algorithms, but it can't capture semantic relationships between words.

Example Sentences

"The cat sat on the mat."
"The dog lay on the rug."

Tokenized

["The","cat","sat","on","the","mat"]
["The","dog","lay","on","the","rug"]

Sent.Thecatsatonthematdoglayrug
1111111000
2100110111

Word2Vec Encoding

Converting words into vectors that capture meaning

Word2Vec, developed by Mikolov et al. at Google in 2013, is a highly influential method for learning word embeddings from large text corpora — transforming words into continuous vector representations that capture semantic relationships and syntactic properties. Words are represented as dense vectors in a high-dimensional space, typically 50 to 300 dimensions, enabling mathematical operations like dot products and vector addition.

⋮ ⋮ 10,000 positions 1 ΣΣΣΣΣ 300 neurons (linear, hidden) ⋮ ⋮ 10,000 neurons, Softmax Input Vector Hidden Layer Output Layer

CBOW architecture — a shallow, two-layer network. Input receives context words; the hidden layer averages context-word vectors; the output softmax predicts the target word.

Training Process

  • A context window (e.g. size 2) determines which words around the target word count as context
  • Averaged context vectors predict the target word by maximizing its probability given the context
  • SGD and backpropagation minimize the loss function, typically cross-entropy

Embedding Vectors

  • Both CBOW and Skip-Gram produce dense, continuous vectors for each vocabulary word
  • Typically 100–300 dimensions, capturing semantic relationships
  • Words with similar meanings are positioned closer together in the vector space

Word2Vec Embeddings

Transforming text into continuous vectors for NLP tasks

Word embeddings are a fundamental component of LLMs, mapping words or phrases from a vocabulary to vectors of continuous numbers. These vectors capture semantic meanings and relationships, enabling models to perform NLP tasks more effectively. Words with similar meanings sit closer together in the vector space — "king" and "queen" are closer to each other than "king" and "apple."

Vector arithmetic captures analogies vector("king") − vector("man") + vector("woman") ≈ vector("queen")
royal ↑ commoner ↓ ♂ male female ♀ King Queen Man Woman Prince Princess Boy Girl Duke Duchess

Illustrative 2D projection of a high-dimensional embedding space — not the deck's original coordinates, but the relationship it depicts: gender and royalty as roughly consistent directions across word pairs.

Semantic Similarity

Vector operations capture analogies — the offset between "man" and "woman" is roughly the same as the offset between "king" and "queen."

Training Impact

Context window size trades off syntactic vs. semantic information; dimensionality trades off nuance vs. compute; and a larger, more diverse corpus produces embeddings that generalize better.

Sequence2Sequence Encoding

Sequence learning with multilayered LSTM

Seq2Seq networks, introduced by Sutskever, Vinyals, and Le in 2014, transform sequences from one domain into sequences in another — making them effective for machine translation, text summarization, and dialogue systems. They typically consist of an encoder and a decoder, often implemented with RNNs, LSTMs, or more recently, transformers.

LSTM Cell Cₜ₋₁ Cₜ × + σ σ tanh σ tanh × [hₜ₋₁, xₜ] hₜ forget input candidate output

A single LSTM cell — forget, input, and output gates (σ) regulate what the cell state Cₜ keeps, adds, and exposes as the hidden state hₜ.

LSTM LSTM LSTM LSTM Encoder thought vector LSTM LSTM LSTM LSTM Decoder

Encoder → thought vector → decoder. The encoder compresses the input sequence into a fixed-length context vector; the decoder generates the output sequence one token at a time from it.

Encoder

Processes the input sequence and converts it into a fixed-length context vector capturing information about the entire input. In RNN-based models, a series of RNN cells take input tokens one at a time, updating the hidden state at each step — the final hidden state is the context vector.

Decoder

Generates the output sequence from the encoder's context vector, as a sequence of RNN, LSTM, or Transformer blocks. At each step, it predicts the next token based on the current hidden state and previously generated tokens.

arxiv.org/abs/1409.3215 — Ilya Sutskever, Oriol Vinyals, Quoc V. Le

Transformer Multi-Head Self-Attention

The architecture behind every modern LLM

Transformer architectures surpass LSTMs and RNNs on three fronts: parallelization (self-attention processes entire sequences simultaneously, rather than one token at a time), long-range dependencies (self-attention attends to all words in a sequence at once, avoiding the vanishing-gradient problems that limit RNNs), and attention mechanisms (multi-head self-attention is inherently integrated into the architecture, not bolted on).

Encoder N× Add & Norm Feed Forward Add & Norm Multi-Head Attention Positional Encoding + Input Embedding Inputs Decoder N× Add & Norm Feed Forward Add & Norm Multi-Head Attention (cross, from encoder) Add & Norm Masked Multi-HeadAttention Positional Encoding + Output Embedding Outputs (shifted right) Softmax Linear Output Probabilities

The Transformer (Vaswani et al., 2017) — encoder stack (left, blue) and decoder stack (right, red), each repeated N× (N=6 in the original paper). The decoder's second attention block attends over the encoder's output.

Encoder: a stack of N=6 identical layers, each with a multi-head self-attention sub-layer and a position-wise feed-forward sub-layer, each wrapped in a residual connection followed by layer normalization: LayerNorm(x + Sublayer(x)). All sub-layers and embedding layers output dimension d_model = 512.

Decoder: also a stack of N=6 identical layers, adding a third sub-layer that performs multi-head attention over the encoder's output. The self-attention sub-layer is masked to prevent positions from attending to subsequent positions, preserving the auto-regressive property.

Attention Is All You Need

Self-attention redefines sequence processing

Vaswani et al.'s 2017 paper introduces the Transformer, a neural network architecture that relies entirely on attention mechanisms, dispensing with recurrence and convolutions entirely — a paradigm shift demonstrating how self-attention can significantly enhance the efficiency and performance of sequence transduction tasks like machine translation.

Core Concepts

  • Self-attention simplifies sequence-to-sequence learning without recurrent layers, enabling better parallelization
  • Encoder/decoder architecture, each with multi-head self-attention and a fully connected feed-forward network

Methodology

  • Attention computes a weighted sum of values, weighted by a compatibility function of query and key
  • Multi-head attention lets the model jointly attend to different representation subspaces

Key Innovations

  • Layer normalization and positional encoding introduce information about token position
  • No recurrence — enables significantly more parallel computation, reducing training time
  • State-of-the-art results on WMT 2014 English-German and English-French translation
  • Foundation for BERT, the GPT series, and the Transformer-based architectures that dominate recent AI

arxiv.org/abs/1706.03762 — Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Lukasz Kaiser, Illia Polosukhin

BERT

Bidirectional Encoder Representations from Transformers

BERT, developed by Google AI in 2018, uses a transformer-based encoder-only structure, reading text bidirectionally to capture context from both sides of a word. It leverages self-attention across 12 layers (BERT Base) or 24 layers (BERT Large), each with multiple attention heads, feed-forward networks, and residual connections with layer normalization. Its open-source release significantly influenced RoBERTa, ALBERT, and DistilBERT.

Key Features

  • Bidirectional context, left-to-right and right-to-left
  • Pre-training then fine-tuning on downstream tasks
  • Versatile: QA, sentiment analysis, NER, text classification

Architecture

  • Transformer-based self-attention
  • Encoder-only

Layers

  • BERT Base: 12 layers, 768 hidden units, 12 attention heads
  • BERT Large: 24 layers, 1024 hidden units, 16 attention heads
  • Input: token + positional + segment embeddings

Pre-training Tasks

  • Masked Language Modeling (MLM) — predicts randomly masked tokens
  • Next Sentence Prediction (NSP) — predicts whether sentence pairs follow sequentially

arxiv.org/abs/1810.04805 — Jacob Devlin, Ming-Wei Chang, Kenton Lee, Kristina Toutanova

Transformer Types

Grouped by structure and functionality

AutoEncoder Models (Encoder-Only)

Strengths

  • Classification tasks
  • Feature extraction

Weakness

  • Context limitation in long sequences
  • Limited generative capability

Use Cases

  • Classification, NER, sentiment analysis

Training

  • MLM, NSP

Examples

  • ALBERT, BERT, DistilBERT, RoBERTa

Autoregressive Models (Decoder-Only)

Strengths

  • Generative capability
  • Autoregressive nature

Weakness

  • Dependency on previous outputs
  • Slower inference

Use Cases

  • Text generation

Training

  • Autoregressive / Causal LM (CLM)

Examples

  • CTRL; GPT (2/3/4); LLaMA (2/3); Mistral; Transformer XL

Sequence-to-Sequence (Encoder-Decoder)

Strengths

  • Flexibility
  • Contextual understanding and generation

Weakness

  • Complexity and resource intensity
  • Harder to optimize

Use Cases

  • Summarization, translation, QA

Training

  • Span corruption, denoising autoencoding, Seq2Seq MLM

Examples

  • BART, mBART, Marian, T5, Claude (2, 3)

Tokenization

Converting text into numerical representations

Several advanced tokenization methods are widely used in transformer architectures to address large vocabularies, rare words, and out-of-vocabulary terms.

SentencePiece

Treats input text as a raw byte stream with no pre-tokenization, using a data-driven approach to generate subword units (BPE or unigram language model). Handles multiple languages and scripts.

Example "The quick brown fox" →
["▁The", "▁quick", "▁brown", "▁fox"]
▁ denotes a word boundary

Usage

  • Mistral, T5, XLNet, ALBERT, mBART, Big Bird

Byte Pair Encoding (BPE)

Iteratively merges the most frequent pairs of characters or character sequences to form a fixed-size vocabulary, balancing manageable vocabulary size with handling rare/OOV words.

Example "The quick brown fox" →
["T","h","e"," ","q","u"...] →
merged: ["Th","e"," qu","ick"," bro","wn"," f","ox"]

Usage

  • GPT, GPT-2, RoBERTa, BART, DeBERTa

WordPiece

Similar to BPE but uses a probabilistic approach to merge tokens, maximizing the likelihood of training data given the vocabulary. Originally built for Google Translate; now widely used in BERT.

Example "The quick brown fox" →
["The","qu","##ick","bro","##wn","f","##ox"]

Usage

  • BERT, DistilBERT, MobileBERT, Funnel Transformers, MPNET

CTRL

A Conditional Transformer for controllable generation

CTRL, developed by Salesforce in 2019, is a 1.63-billion-parameter conditional transformer language model trained on a dataset containing control codes that govern style, content, and task-specific behavior — enabling fine-grained control over the model's output. Control codes were derived from structure that naturally co-occurs with raw text, preserving the advantages of unsupervised learning while adding explicit control, and enabling model-based source attribution over training data.

Key Features

  • Fine-grained control via codes for style, content, and structure
  • Effective for creative writing, dialogue, content creation
  • State-of-the-art on several NLP benchmarks

Architecture

  • Transformer-based, self-attention across long sequences
  • Leverages both encoder- and decoder-style mechanisms though primarily generative

Layers

  • Multi-layered transformer blocks
  • Multiple attention heads per layer
  • Feed-forward networks + residual connections + layer normalization

arxiv.org/abs/1909.05858 — Nitish Shirish Keskar, Bryan McCann, Lav R. Varshney, Caiming Xiong, Richard Socher

Retrieval Augmented Generation

Combining retrieval with generation

RAG is a hybrid NLP approach that combines the strengths of retrieval-based methods and generative models to enhance the quality and relevance of generated text.

User Question Vector Store Retriever Vector Store Text Corpus Chunks · Index · Embeddings Semantic Search Relevant Chunks + user question LLM Query Prompt Template Chunks + Question Answer with Sources

RAG pipeline: the user question is embedded, matched against a vector store of chunked, indexed, embedded source text, and the relevant chunks are combined with the question in a prompt template before the LLM generates a sourced answer.

Retrieval Mechanism

A large corpus or database — structured or unstructured — from which relevant information is retrieved. Algorithms like TF-IDF, BM25, or neural retrieval methods (e.g. Dense Passage Retrieval) identify and rank the most relevant documents or passages.

Query Processing

The input query is converted into embeddings using models like BERT or other transformer-based encoders, so it can be effectively matched against the knowledge base — capturing semantic meaning and context to aid accurate retrieval.

Integration with Generative Model

Retrieved passages are integrated with the input query — concatenated or merged via attention mechanisms. A generative model (GPT-3, T5, BART) processes the combined input to generate a coherent, contextually relevant response.

Feedback & Refinement Loop

RAG often includes mechanisms to iteratively refine retrieval and generation — multiple rounds of retrieval and generation, with re-ranking of retrieved passages based on relevance to the generated context.

Vector Database

Architecture and indexing for similarity search

Vector databases are a specialized class of databases designed to handle and query high-dimensional vector representations of data — essential for image recognition, NLP, and recommendation systems, where retrieval is based on vector similarity rather than exact match.

1. Data Collection & Preprocessing

Raw data — text, images, audio — is collected and preprocessed for quality and consistency: tokenization, normalization, and stop-word removal for text; resizing, normalization, and augmentation for images.

2. Feature Extraction

Preprocessed data passes through models like BERT (text) or ResNet (images) to generate high-dimensional feature vectors representing each data point in a continuous vector space.

3. Database Insertion

Vectors are indexed for efficient retrieval, alongside metadata like identifiers and attributes. ANN indexing methods let the database quickly find vectors similar to a given query vector.

A Vector in Practice

Content passes through an embedding model and an indexer, producing a fixed-length array of floating-point numbers:

0.030.26-0.570.90-0.140.68-0.850.010.47-0.180.620.09

Indexing Techniques

Approximate Nearest Neighbor (ANN) algorithms, tree-based algorithms, and hybrid/composite approaches, each trading off accuracy, speed, and storage differently.

HNSW

Hierarchical Navigable Small World — a graph-based algorithm building a hierarchical network of vectors, each layer a navigable small-world graph.

Advantages

Logarithmic-time search with high accuracy.

Use Cases

Real-time search — recommendation systems, image retrieval.

Product Quantization (PQ)

Divides vectors into smaller sub-vectors, quantizes each independently, and encodes into shorter codes.

Advantages

Balances storage efficiency and search speed.

Use Cases

Large-scale search requiring efficient storage.

LSH

Locally Sensitive Hashing — hashes input vectors so similar vectors land in the same bucket; multiple hash functions improve accuracy.

Advantages

Fast similarity search with sub-linear query times.

Use Cases

High-dimensional spaces — plagiarism detection, large-scale NN search.

K-Graph

A graph where each node connects to its k nearest neighbors; the search explores the graph to find approximate nearest neighbors.

Advantages

Balances accuracy and efficiency.

Use Cases

Applications needing a speed/accuracy trade-off.

KD-Tree

A binary tree recursively partitioning the data space into nested orthogonal regions, effective for low-dimensional spaces.

Advantages

Efficient range queries and NN search in low-dimensional data.

Use Cases

Spatial databases, organizing k-dimensional points.

Ball Tree

Organizes data into a tree where each node represents a cluster of points within a hypersphere.

Advantages

Efficient NN search for high-dimensional data.

Use Cases

Clustering and classification tasks.

Annoy

Approximate Nearest Neighbors Oh Yeah — builds a forest of random projection trees, similar to KD-Trees but optimized for approximate NN search.

Advantages

Memory-efficient, fast query times.

Use Cases

Recommendation systems — e.g. Spotify's music recommendations.

FAISS

Facebook AI Similarity Search — a library integrating multiple ANN algorithms (HNSW, PQ, LSH) for optimized speed and accuracy.

Advantages

Highly flexible, efficient, handles large-scale datasets.

Use Cases

Image similarity search, large-scale information retrieval.

LangChain

A framework for developing LLM-powered applications

LangChain streamlines and enhances the operations of large language models, integrating components and tools for efficient training, fine-tuning, and deployment across diverse NLP tasks. It provides robust support for modular workflows, letting practitioners build and customize pipelines for text generation, summarization, question answering, and more.

Development

Build applications using LangChain's open-source building blocks and components. Hit the ground running with third-party integrations and templates.

Productionization

Use LangSmith to inspect, monitor, and evaluate chains, so you can continuously optimize and deploy with confidence.

Deployment

Turn any chain into an API with LangServe.

References

Sources cited throughout this deck

Transformer Architectures

Embeddings

Proprietary Large Language Models

Datasets

Training Cost

Evaluating Model Performance

Tutorials

Blogs