How LLMs Work

What a language model is, in econometric terms

Brendan Chapuis

March 17, 2027

Draws on talks by Scott Cunningham
Course Home Page

Lecture Goals

  • Open the second half of the course
    • Why the first half was done without AI
    • What AI changes about doing research
  • How a large language model (LLM) works, in econometric terms
    • Next-token prediction, tokens, embeddings, attention, training
  • A little about what it runs on and what it costs
  • What this means for your research

The Second Half

Halfway There

The first half of this course was done without AI.

  • Git, project organization, R, Python, the web
  • You wrote every line, ran it, and fixed it yourself

The second half is about AI methods for research.

Today: why the first half came first, and what a language model actually is.

Shockley (1957): Research Output Is a Product

William Shockley studied why a few researchers produce far more than everyone else.

His answer was not intelligence. He broke productivity into several abilities and multiplied them.

Add the inputs

\[P = F_1 + F_2 + F_3\]

\[0.5 + 0.5 + 0.5 = 1.5\]

Multiply the inputs

\[P = F_1 \times F_2 \times F_3\]

\[0.5 \times 0.5 \times 0.5 = 0.125\]

Now Take One Input Away

Add the inputs

\[0 + 0.5 + 0.5 = 1.0\]

Inputs are perfect substitutes. Having none of one is no problem.

Multiply the inputs

\[0 \times 0.5 \times 0.5 = \color{red}{0}\]

You need at least some of every input to make anything at all.

A zero in any one input sinks the output.

Shockley’s Eight Abilities

\[P = F_1 \times F_2 \times F_3 \times F_4 \times F_5 \times F_6 \times F_7 \times F_8\]

  1. Think of a good problem
  2. Work on it
  3. Recognize a worthwhile result
  4. Decide when to stop and write up
  1. Write adequately
  2. Profit from criticism
  3. Submit the paper to a journal
  4. Persist after the journal responds

Shockley (1957), “On the Statistics of Individual Variations of Productivity in Research Laboratories,” Proceedings of the IRE. He called it “a partial listing.”

AI Augments the Inputs

  • The eight are still the inputs to research.
  • AI can raise some of them, especially “work on it.”
  • It does not replace them.
    • Somebody still has to pick the problem.
    • Somebody still has to recognize whether a result is right and worth anything.

If AI raises \(F_2\) while your \(F_3\) falls toward zero, your output falls.

Three Legs: Production, Checking, Understanding

Before AI

  • Production: you wrote the code and made the tables.
  • Checking: your habits caught mistakes as you worked.
  • Understanding: you could only produce it because you understood it.

The three came as one bundle.

With agents

  • Production: an agent writes and runs the code for you.
  • Checking: you did not do it, so you cannot be sure it is right.
  • Understanding: if it cost you no time, you probably do not understand it.

Checking and understanding now have to be done on purpose.

What to Do With the Time You Save

Adapted from Scott Cunningham’s deskilling diagrams. Illustrative curves, not data.

Three Cases

  1. Keep your hours, take the output. The biggest gain, and your judgment stays sharp.
  1. Take some time back. Fine, as long as you stay engaged enough to stay above where you started.
  1. Cut too far, and you deskill. You stop building the skills you need to judge the output, and you end up worse off than before AI.

The first half was done by hand so that your skills exist before an agent can let you skip building them.

The Plan for the Second Half

Date Topic
3/17 How LLMs work (today)
3/22 LLMs as a research tool: APIs from R, text classification
3/24 From chatbots to agents
4/5 Directing agents: AGENTS.md, skills, hooks
4/7 Reviewing agent work: pull requests
4/14 Quarto: every number comes from code
4/19 Checking results
4/21 Research design with agents

What an LLM Does

The Whole Machine in One Picture

G A Your text B Tokens (word pieces) A->B C Vectors (lists of numbers) B->C D Transformer (many layers) C->D E Probabilities for the next token D->E

  • Text is chopped into tokens, and each token becomes a vector.
  • Each layer rewrites every vector using the vectors around it.
  • At the end, the last vector becomes a probability for every possible next token.

Chatbots and agents sit on top of this one machine.

An LLM Predicts the Next Token


“The minimum wage reduces ______”

Illustrative numbers, not model output
Next token Probability
employment 0.41
poverty 0.22
hours 0.11
inequality 0.09
every other token 0.17

That is the only thing the model does: map the text so far to a distribution over what comes next.

Then It Draws One

  • The model draws one token from that distribution and appends it.
  • Then it predicts again, with the longer text as the new input.
The minimum wage reduces
The minimum wage reduces employment
The minimum wage reduces employment among
The minimum wage reduces employment among teenagers
...

An essay, a proof, an R script: each is thousands of these draws in a row.

Two Runs of the Same Prompt

Prompt: “The minimum wage reduced teen ______”

Next token Probability
employment 0.62
hours 0.18
turnover 0.09
wages 0.04
all others 0.07
  • Like rolling a weighted die.
  • Run 1 draws “employment.” Run 2 draws “hours.”
  • Each draw changes the text the next prediction sees.
  • So the two runs drift further apart with every token.

Temperature

The draw can be made more or less random. With scores \(z_k\) for each token \(k\):

\[\Pr(k) = \frac{\exp(z_k / T)}{\sum_j \exp(z_j / T)}\]

  • \(T\) is the temperature.
  • Small \(T\): the most likely token almost always wins.
  • Large \(T\): the distribution flattens and unusual tokens appear more often.

Lowering the temperature reduces the randomness. It does not make the most likely answer correct.

Asking Once Is a Sample of Size One

  • The same prompt gives the same probabilities for the first token.
  • But the output is a random draw, and every draw changes what follows.
  • One answer is one draw from a distribution.
  • To know what a model “thinks,” you need many draws.

You would not report a regression from one bootstrap draw. Do not treat one LLM answer as the answer.

Tokens

The Model Reads Tokens, Not Words

“Difference-in-differences estimates the treatment effect.”

Difference72917 -in4200 -d2469 if366 ferences10131 ␣estimates30233 ␣the290 ␣treatment7448 ␣effect3159 .13

  • Ten tokens, each with an ID number. ␣ marks a leading space.
  • Common words are one token. Rarer words are split into pieces.

The model never sees letters or words. It sees ten integers.

Real output from OpenAI’s o200k_base tokenizer, the one GPT-4o uses. Example from Scott Cunningham.

The Vocabulary Is a Fixed List

Picture 200,019 flashcards in a fixed order, with one piece of text on each.

Card 13 290 6922 72917 …
Text . ␣the ␣bank Difference …
  • The tokenizer swaps each piece of your text for its card number.
  • The deck was settled before training started and never changes.
  • Every text the model ever reads or writes is built from these cards.

A Token ID Is a Label

A token ID is a categorical variable, like a FIPS code.

  • County 44007 is not “more” than county 06037.
  • Token 6922 is not “bigger” than token 290.
  • You would never put FIPS codes into a regression as a number.
  • The model does not either. It uses each ID to look something up (next section).

Byte-Pair Encoding Builds the List

Nobody wrote 200,019 cards by hand. An algorithm did:

  1. Start with single characters (bytes).
  2. Count which neighboring pair appears most often in a large body of text.
  3. Glue that pair into one new piece and add it to the list.
  4. Repeat until the list reaches the chosen size.
  • Frequent strings end up as one card. Rare strings are left in pieces.
  • Engineers choose the text it counts and how long the list should be.

Sennrich, Haddow, and Birch (2016) brought byte-pair encoding to language models.

Byte-Pair Encoding: A Toy Example

Text: low lower lowest

Step Most common pair Pieces after the merge
0 l o w l o w e r l o w e s t
1 l + o lo w lo w e r lo w e s t
2 lo + w low low e r low e s t
3 low + e low lowe r lowe s t

“low” became one card because it was common in the text that was counted.

That is why “the” is one token and “differences” is three.

Vocabulary Size Is Not Model Size

What it counts GPT-3 (2020) GPT-4o (2024)
Vocabulary tokens it can choose from 50,257 200,019
Context window tokens it can hold at once 2,048 128,000
Parameters weights estimated in training 175 billion not disclosed
Training text tokens read in training about 300 billion not disclosed

The choice set is small. What is enormous is the text it learned from and the number of weights it takes to choose well.

Sources: Brown et al. (2020) for GPT-3; OpenAI’s o200k_base tokenizer and model documentation for GPT-4o.

Try It: A Tokenizer

Tokenizing in Python

OpenAI’s tiktoken package does what the last few slides described.

import tiktoken

enc = tiktoken.get_encoding("o200k_base")     # the GPT-4o vocabulary
ids = enc.encode("Difference-in-differences estimates the treatment effect.")

print(ids)
print([enc.decode([i]) for i in ids])          # each token as text
print(enc.n_vocab)                             # size of the vocabulary
[72917, 4200, 2469, 366, 10131, 30233, 290, 7448, 3159, 13]
['Difference', '-in', '-d', 'if', 'ferences', ' estimates', ' the', ' treatment', ' effect', '.']
200019

Activity: How Is Text Split?

Use OpenAI’s web tokenizer (platform.openai.com/tokenizer), or run pip install tiktoken in your own Python environment and use the code on the last slide.

Try each of these and count the tokens:

  • Economics jargon: heteroskedasticity, instrumental variables, Cobb-Douglas
  • Numbers: 2027, 3.14159, 1,234,567
  • Code: df |> filter(year >= 2020) |> summarize(n = n())
  • Text in another language you know

Activity: What Did You Find?

  • Which jargon is one token, and which is split into pieces?
  • How are long numbers split? What might that do to arithmetic?
  • Does a sentence in another language take more tokens than in English?

Why it matters:

  • You pay by the token, and limits are counted in tokens.
  • The model works with these pieces, not with the letters or the digits.

Embeddings

Each Token ID Looks Up a Row

G A ␣bank B ID 6922 A->B C row 6922 of a table B->C D [0.12, -0.87, 0.33, ...] C->D

  • The model keeps a table with one row for every token in the vocabulary.
  • Each row is a vector of thousands of numbers (12,288 in GPT-3).
  • The rows are parameters: they are estimated in training.
  • The same token always starts from the same row, in every sentence.

The numbers in the vector are illustrative.

In Our Language: A Fixed Effect

You know this from fixest:

feols(wage ~ educ | county, data = df)
  • county is a categorical variable. Each county gets its own estimated number.
  • A token ID is a categorical variable too.
  • Its embedding is a fixed effect with thousands of dimensions, estimated jointly with everything else.

The list of tokens is chosen. What each token means is learned.

What the Rows Learn

  • Nobody tells the model what any token means.
  • Training only rewards rows that help predict the next token.
  • Tokens used in similar contexts end up with similar rows.
    • ␣wage ends up close to ␣salary and ␣earnings.
  • Distance between rows becomes a measure of similarity in meaning.

But one row per token is a problem: “bank” gets the same row in every sentence.

Attention

Same Token, Different Meaning

“She deposited the check at the bank.”

“We sat on the river bank.”

  • Both sentences give the model the same token, ID 6922.
  • It needs a different meaning in each.

Attention lets each token look back at the tokens before it and update its vector.

  • “Deposited” and “check” pull bank toward finance.
  • “River” pulls it toward water.

Each Token Divides Its Attention

Updating “bank” in sentence one

Token Share
She 0.04
deposited 0.38
the 0.03
check 0.33
at 0.05
the 0.03
bank 0.14

Updating “bank” in sentence two

Token Share
We 0.05
sat 0.12
on 0.08
the 0.04
river 0.55
bank 0.16

Each column sums to one. Illustrative shares, not model output.

A Weighted Average

The new vector for “bank” is a weighted average of the vectors before it, using those shares.

  • Every token gets its own set of shares, in every layer.
  • Models stack dozens of these layers, so meanings are refined again and again.

In our language: a kernel-weighted average, where the kernel is learned from data.

How the Shares Are Computed

For token \(i\) looking at an earlier token \(j\), with current vectors \(x_i\) and \(x_j\):

\[\text{score}_{ij} = (W_Q\, x_i)'(W_K\, x_j) \qquad a_{ij} = \frac{\exp(\text{score}_{ij})}{\sum_{k \le i}\exp(\text{score}_{ik})}\]

\[x_i^{\text{new}} = \sum_{j \le i} a_{ij}\, W_V\, x_j\]

  • The shares \(a_{ij}\) have the multinomial logit form.
  • \(W_Q\), \(W_K\), \(W_V\) are parameters, estimated once in training.
  • The shares are not parameters. They are recomputed from your text every time.

Computed, Not Estimated

  • Nobody optimizes the shares directly.
  • Training chooses the matrices \(W_Q\), \(W_K\), \(W_V\).
  • The shares fall out of those matrices and your text.

Same logit formula, two different jobs:

  • Inside the model, to choose where to look.
  • At the very end, to choose the next token (coming up).

What a Share Can and Cannot Be

Question Answer
Can it be negative? No. It is a ratio of exponentials.
Can it exceed one? No. The shares are positive and sum to one.
Can it be zero? Only for later tokens, which are masked out.
Is it a probability? Same shape, but nothing is ever drawn from it.
Is it causal? No. A large share does not mean that token caused the output.

Reading attention shares as “what the model based its answer on” is a common mistake.

On causality: Jain and Wallace (2019), “Attention is not Explanation.”

The Output Layer and Training

Next-Token Prediction Is a Multinomial Logit

After all the layers, the context is summarized in one vector, \(h(\text{context})\).

\[\Pr(\text{next token} = k \mid \text{context}) = \frac{\exp\big(h(\text{context})' w_k\big)}{\sum_{j=1}^{V}\exp\big(h(\text{context})' w_j\big)}\]

  • The choice set is the vocabulary: \(V \approx 200{,}000\).
  • \(w_k\) is the coefficient vector for alternative \(k\).
  • \(h(\text{context})\) plays the role of the regressors.

What Is Familiar and What Is New

Familiar

  • A multinomial logit
  • One coefficient vector per alternative
  • Fit by maximum likelihood

New

  • You do not choose the regressors.
  • \(h(\cdot)\) is the whole transformer, learned jointly with \(w\).
  • Billions of parameters, not a dozen.
  • 200,000 alternatives, not three.

Training Is Maximum Likelihood

The weights are all the parameters \(\theta\): embeddings, attention matrices, the \(w_k\), and the rest.

\[\hat{\theta} = \arg\max_{\theta} \sum_{t} \log \Pr_{\theta}\big(\text{token}_t \mid \text{tokens before } t\big)\]

  • Take an enormous amount of text.
  • At every position, ask the model to predict the next token.
  • Choose \(\theta\) to make the true next token as likely as possible.

The “labels” come free with the text: the next token is always right there.

Stochastic Gradient Descent

There is no closed form like OLS, so the maximum is found step by step:

  1. Take a small batch of text.
  2. Compute how the log-likelihood would change if each weight moved a little (the gradient).
  3. Nudge every weight a small step uphill.
  4. Repeat, for trillions of tokens.
  • “Stochastic” because each step uses a random batch, not all the data.
  • This is the expensive part: months on thousands of GPUs.

Once Trained, the Weights Are Fixed

  • Training happens once. Then the weights are frozen.
  • When you use the model, nothing is being estimated. It is only being evaluated.
  • The model does not learn from your conversation.
  • What looks like memory is the earlier conversation sent back in as part of the text.

Fixed weights plus random draws: the same model, with the same prompt, gives different answers.

Likely, Not True

The objective rewards one thing: putting high probability on the text that actually came next.

  • Nothing in the likelihood rewards being true, only being likely.
  • A fake citation that looks like a real one is very likely text.
  • A wrong coefficient written in a confident sentence is very likely text.

It is a prediction model. Good predictions are often true, but truth is not what was estimated.

One Model, One Objective

Text → token IDs Embedding table Attention layers Output logit
Estimated (fixed after training) (chosen before training) rows of the table \(W_Q, W_K, W_V\) \(w_k\)
Computed (fresh for your text) token IDs one vector per token attention shares, \(h(\text{context})\) next-token probabilities
  • All the parameters are chosen together to maximize one likelihood.
  • There is no separate model for attention.

Three Kinds of Numbers

Weights Attention shares Next-token probabilities
Where they come from maximizing the likelihood a logit formula inside \(h(\cdot)\) the logit formula at the end
What goes in the training text \(W_Q\), \(W_K\), and your text \(h(\text{context})\) and \(w_k\)
When once, before you use it every layer, every token once per token it writes
Fixed afterward? yes no no
Can be negative? yes no no
Sum to one? no yes, for each token yes, over the vocabulary
In the logit the coefficients part of the regressors the fitted probabilities

When someone says a model has 175 billion weights, they mean the first column. The other two are computed fresh each time.

From Predictor to Assistant

A model trained only on next-token prediction continues text. It does not answer questions. A second stage, post-training, changes that:

  • Instruction tuning: more next-token training, on example conversations written by people.
  • Learning from feedback: raters compare two answers; the weights are adjusted toward the answers raters prefer.

The objective moves from “likely on the internet” to “preferred by raters.”

Still not “true.” Raters reward answers that look helpful and confident.

Ouyang et al. (2022), “Training language models to follow instructions with human feedback.”

Training Runs on Hidden Human Labor

Mary Gray and Siddharth Suri call it ghost work:

  • People label text and images so a model can learn from the labels.
  • People read the worst material online and flag it, so a filter can learn to block it.
  • People rate and correct a model’s answers after training.

In 2023, TIME reported that Kenyan workers labeling abusive text for OpenAI’s filter took home less than $2 an hour.

Sources: Gray and Suri, Ghost Work (2019); Billy Perrigo, TIME, January 18, 2023.

Compute and Economics

GPUs Do the Arithmetic in Parallel

What the arithmetic is

  • Every layer is matrix multiplication.
  • Billions of weights means billions of multiply-and-adds per token.
  • None of them has to wait for any other.

Why a GPU

  • A CPU has a few fast cores that work one step at a time.
  • A GPU has thousands of simple cores doing the same operation at once.
  • Built for video-game graphics, which is also matrix arithmetic.

One NVIDIA H100: about 17,000 arithmetic cores, 80 GB of memory, up to 700 watts, and $25,000 to $40,000 to buy.

Sources: NVIDIA product pages; Epoch AI hardware data; Jensen Huang, CNBC, March 2024.

Training Runs Keep Getting More Expensive

The cost of the largest run has grown about 2.4 times a year. Most labs do not disclose theirs.

Ranges: hardware used up (low) to cloud rental rates (high). Sources: Patterson et al. (2021); Meta; xAI; OpenAI briefing, September 2026; Epoch AI; Stanford AI Index; Cottier et al. (2024). Data compiled by Scott Cunningham.

Data Centers Show Up in the National Statistics

  • Data centers used 4.4% of U.S. electricity in 2023. Projections for 2028 range from 6.7% to 12%.
  • The five largest cloud companies were set to spend more than $690 billion on capital in fiscal 2026.
  • One planned OpenAI site in Abilene, Texas is sized at 1.2 gigawatts.
  • Nearly all the electricity a GPU uses leaves as heat, so data centers also need cooling and water.
  • A good research question for an economist: who pays for the power lines?

Sources: Lawrence Berkeley National Laboratory (2024); FactSet, July 2026; Epoch AI.

Closed and Open-Weight Models

Closed models

Claude, GPT, Gemini

  • The weights are a trade secret.
  • You rent them by the token or by subscription.
  • Your text goes to their servers.
  • They lead on capability.

Open-weight models

Llama, Qwen, DeepSeek, Gemma, Mistral, gpt-oss

  • You download the weights.
  • You run them with tools like Ollama.
  • Your data never leaves your machine.
  • A pinned version never changes.

In September 2026, the best open-weight model scored 44 and the best closed model 53 on the same public index.

Source: Artificial Analysis Intelligence Index, September 7, 2026.

Effort Is a Dial

Before its answer, a model can write itself a scratchpad of reasoning tokens.

Claude OpenAI
Name of the setting effort reasoning_effort
Levels low, medium, high, xhigh, max minimal, low, medium, high, xhigh
  • Higher effort means more tokens, more time, and a bigger bill.
  • Same model, same weights. Effort only changes how many draws it makes before committing to an answer.

By the Token or by the Month

By the token (the API)

Dollars per million tokens In Out
Claude Fable 5.1 10 50
Claude Opus 5.5 4 20
Claude Haiku 4.5 1 5
GPT-6 Astra 10 50
GPT-6.1 Sol 2 10
GPT-6 Luna 0.10 0.50

By the month (a subscription)

  • Claude Pro: $20
  • Claude Max: $100 or $200
  • Includes the coding agent

A million tokens is about 750,000 English words.

A subscription suits daily interactive work. The API suits a script that labels 300,000 documents overnight, which is where we start on 3/22.

Sources: Anthropic and OpenAI pricing pages, October 1, 2026.

What This Means for Research

Outputs Are Random: Treat Them Like Data

  • Every answer is a draw, so repeat important calls and look at the spread.
  • Log every prompt and every response, like you log a regression specification.
  • Pin the exact model version. “The latest model” changes under you.
  • Record the settings: temperature, effort, date.

If you cannot reproduce how a number was made, it is not evidence.

Plausible Is Not True

  • The model was trained to produce likely text.
  • Likely text is often right, and it is always fluent, including when it is wrong.
  • Fluency is not a signal of accuracy.
  • Check outputs against something you trust: hand labels, a second source, your own code.

This is the “checking” leg. It does not come for free anymore.

Where We Go Next

  • 3/22, LLMs as a research tool: call a model from R with ellmer, classify text, and check the labels against labels done by hand.
  • 3/24, from chatbots to agents: an agent is this same model, but its tokens become commands that run on your computer.

Everything an agent does starts from next-token prediction.

Summary

  • An LLM predicts a distribution over the next token, then draws one.
  • Text is split into tokens from a fixed vocabulary built by byte-pair encoding.
  • Each token ID looks up an embedding: a high-dimensional fixed effect.
  • Attention mixes in context with shares computed from your text, not estimated, and not causal.
  • The output layer is a multinomial logit, trained once by maximum likelihood.
  • Nothing rewards being true, only being likely.
  • Asking once is a sample of size one: repeat, log, pin, and check.

References

  • Brown et al. (2020). “Language Models are Few-Shot Learners.”
  • Cunningham, Scott (2026). Talks at Texas A&M (October 2) and Baylor (October 14). This deck adapts their structure and explanations.
  • Gray, Mary L. and Siddharth Suri (2019). Ghost Work.
  • Jain, Sarthak and Byron C. Wallace (2019). “Attention is not Explanation.”
  • Ouyang et al. (2022). “Training language models to follow instructions with human feedback.”
  • Perrigo, Billy (2023). “OpenAI Used Kenyan Workers on Less Than $2 Per Hour to Make ChatGPT Less Toxic.” TIME, January 18.
  • Sennrich, Rico, Barry Haddow, and Alexandra Birch (2016). “Neural Machine Translation of Rare Words with Subword Units.”
  • Shockley, William (1957). “On the Statistics of Individual Variations of Productivity in Research Laboratories.” Proceedings of the IRE.
  • Vaswani et al. (2017). “Attention Is All You Need.”