Physics × AI

Short course · IF-UERJ · November 2026

Artificial intelligence in physics research and teaching

Understand the mechanism. Ask good questions. Check the results. Answer for what you sign.

  • 4 lessons · 6 hours
  • Full derivations
  • 13 homework exercises
  • 4 interactive explorations

How to study this course

A course to follow and to redo

The goal is to move from a plausible answer to a claim you can justify. Read with pen and paper: make a prediction, try a calculation and only then check the result.

To follow the meetings

Follow the path given at the start of each lesson. The further-reading sections are for later. The 90 minutes are for presentation and discussion; the exercises stay for homework, and the full reading is longer.

To study on your own

Read the whole chapter, try the explorations and solve the exercises. Finish with the final activity.

Prerequisites: elementary probability, derivatives, vectors and matrices. The research cases in field theory are explained through the problem they solve; their technical details can be taken up in a later reading.

How to navigate: the table of contents comes right after the opening, and the Contents link at the top of the page returns to it from anywhere. Each chapter ends with a shortcut to the next one. The explorations respond to their controls when the file is opened in a browser; in a preview that does not run scripts, such as the iPhone's, they show the starting state.

These notes accompany a four-lesson course on language models in physics research and teaching, and they were written to be read on their own: someone who missed the lessons will find the whole content here, with the complete derivations and the examples we discussed. Each chapter corresponds to one lesson. The sections marked as further reading go beyond what fits in 90 minutes and can be read later. The course also has an exercise book, for homework; the examples those exercises use are reproduced and discussed in these notes.

Lesson Topic
1 How a language model works: from text to probabilities, attention, assistants and agents
2 AI in research: the application, the second brain, literature and calculation
3 AI in teaching and studying: lecture notes, continuous assessment and studying with AI
4 Ethics and authorship: understanding the results, authorship, disclosure and confidentiality

Where the examples come from

Throughout the course I show sessions from my own work and examples written for the lessons. So that there is no doubt about where each one comes from, they always carry one of three labels:

  • Real session · model · date: an interaction that actually took place, with the model and the date;

  • Constructed example: a conversation written for the lesson, sometimes with an error planted on purpose, to train the eye;

  • Fictitious data: an invented student or answer, used in place of real data.

The numbers in the examples were recomputed by programs that accompany the course material. The course was written in Portuguese, and in this English edition the sessions, requests and answers appear in translation; data such as the tokenized sentences keep their original language.

Conventions

  • ln\ln is the natural logarithm, and entropies are in nats; dividing by ln⁡2\ln2 converts them to bits.

  • In the thermodynamic analogies we use kB=1k_B=1, unless stated otherwise.

  • H∈ℝn×dH\in\mathbb{R}^{n\times d} stores the vectors of the sequence in its rows. A logit is the real score assigned to a token before the softmax.

Statement of assistance

This material was prepared with the assistance of language models. The author used Claude Opus 5.5 in preparing the course and Codex in the scientific and pedagogical review incorporated here, in editing the sources and in running the numerical and compilation checks. The English version was translated from the Portuguese original with Claude Opus 5.5. The conversations and answers created for teaching purposes are identified in the text. The checking programs accompany the material. The choice of content, the decisions about classroom use and the responsibility for the adopted version belong to the author.

Lesson 1 · 90 minutes

How a language model works

Question of the lesson

How does a function that predicts tokens become an assistant able to converse, calculate and use tools?

By the end, you should be able to

Compute one attention head and distinguish information in the parameters, in the context, in memory and in tools.

Path: text and tokens → probabilities and training → why the recipe took so long to work → attention → from model to assistant → from assistant to agent → three questions to take away. The physical analogies help to interpret the equations; each one comes with its domain of validity.

In this chapter we follow what happens between the question we type and the answer the assistant returns. The path has three stages. The text becomes a sequence of numbers; a function with billions of adjustable coefficients computes, from those numbers, the probability of each possible continuation; and a random draw picks what comes next. Much of the behavior that surprises people who use these tools, such as the fluent but wrong answer or the easy agreement with the user, comes from choices that become visible in the equations. Several of these equations have an immediate reading for anyone who knows statistical physics, and we will use that reading whenever it explains something, saying also where the analogy stops working.

The corresponding lesson covers Sections 1.1 to 1.7 without the proofs, and from Section 1.6 it shows the transition from model to assistant and sycophancy; the preference calculation, reasoning models and the causes of hallucinations stay in the optional material of the slides. The sections marked as further reading go beyond the lesson: Zipf’s law, associative memory and its energy, other physical readings and the scaling laws. The optional exercise in Section 1.10 uses the calculations of Section 1.5.1.

Reading path

Elementary probability, derivatives and vectors are enough. The core follows the lesson: what the model computes and how it is trained, why this recipe took so long to work, attention, scale and tools. By the end, try to explain where a piece of information came from and to redo the calculation of one attention head. The proofs about associative memory and the error bounds are further reading.

1.1 What a language model is

Given a passage of text, a language model assigns a probability to each possible continuation. After The capital of Brazil is, for instance, a good model gives high probability to Brasília and low probability to Lisbon. That is, a language model is a probability distribution over sequences of text. Everything an assistant does is built on this calculation.

In practice, the model is a mathematical function with many adjustable coefficients, called parameters. The situation is similar to curve fitting: we choose a functional form with free coefficients and adjust them so that the curve passes close to the data. Here the data are texts, and adjusting the parameters so that the model predicts those texts well is what we call training. The functional form is a neural network, a composition of many simple operations: we multiply a vector by a matrix, apply a nonlinear function to each component of the result, multiply by another matrix, and so on. The parameters are the entries of those matrices. Current models are called large, as in large language models (LLMs), because they have billions of parameters, fitted to collections of text with trillions of words.

The assistants we use, such as ChatGPT, Claude and Gemini, are models of this kind that went through additional stages of fitting to follow instructions. They run inside an application with tools, files and memory. We follow this path in order: first the model that predicts the next piece of text (Section 1.2), why this recipe took so long to work (Section 1.3), attention and the transformer (Section 1.4), then the physical readings (Section 1.5), the fitting that turns the model into an assistant (Section 1.6) and, finally, the system around it (Section 1.7).

1.2 From text to probabilities

1.2.1 Tokens

The model is a function that takes numbers and returns numbers. Before any calculation, therefore, the text has to become a sequence of numbers, and for that we use a kind of numbered dictionary. We cut the text into pieces, called tokens, and each possible piece occupies a fixed position in a list, the model’s vocabulary. We call VV the number of entries in that list. A token can be a whole word, a piece of a word, a punctuation mark, a group of digits or a space.

Consider a real case. The program that does the cutting is called a tokenizer, and the one used by GPT-4o, a model by OpenAI, splits the Portuguese sentence O campo magnético varia lentamente. (“The magnetic field varies slowly.”) into the seven tokens of Table 1.1. Note that the space before each word is part of the token, that magnético breaks into two pieces and that lentamente fits in one. What enters the model is the sequence of the numbers of these tokens,

(x1,…,x7)=(46,22791,15410,41850,129670,152909,13),(x_1,\dots,x_7)=(46,\ 22\,791,\ 15\,410,\ 41\,850,\ 129\,670,\ 152\,909,\ 13),
(x1,…,x7)=(46,22791,15410,41850,129670,152909,13),\begin{aligned}(x_1,\dots,x_7) & {}=(46, 22\,791,\\ &\qquad 15\,410, 41\,850,\\ &\qquad 129\,670, 152\,909,\\ &\qquad 13),\end{aligned}

and this is what the notation x1,…,xnx_1,\dots,x_n means from now on: xtx_t is the number of the token that occupies position tt in the text, an integer between 00 and V−1V-1. This number works like the numbering of the entries in a dictionary. It identifies the token, and its order has no meaning: token 46 is as far from 47 as it is from 152 909. What each token represents, for the model, is stored in a vector associated with it, which we will see in Section 1.4.1.

Table 1.1. The Portuguese sentence O campo magnético varia lentamente. in the GPT-4o tokenizer, o200k_base, whose vocabulary has about 200 thousand tokens. The symbol ␣ marks the space that is part of the token. Tokens and numbers computed with the public tokenizer file.
Token Number in the vocabulary
O 46
␣campo 22 791
␣magn 15 410
ético 41 850
␣varia 129 670
␣lentamente 152 909
. 13

We could cut the text into whole words, or into letters, and both choices have problems. A vocabulary of whole words would need to list every word of every language, with all their inflections, plus proper names, numbers, typos and LaTeX commands, and a word outside the list would have no representation. A vocabulary of letters would be small, but every text would become a very long sequence, and the model would spend much of its work reassembling words from letters. Tokens sit halfway: frequent words take a single token, and rare words break into pieces that are in the list.

So that no text is left without a representation, the vocabulary starts from the lowest level of writing in a computer, the byte. A character is a written symbol, such as a, ç, π\pi or an emoji. In the computer’s memory, each character is stored as a short sequence of bytes, and a byte is simply an integer from 0 to 255, written with eight bits (28=2562^8=256). The correspondence between characters and bytes is fixed by a table, the encoding. In UTF-8, used in almost all of the internet, the letter a is the byte 97, ç is the pair (195,167)(195,\,167), π\pi is (207,128)(207,\,128), and most emojis take four bytes. If the 256 possible bytes are in the vocabulary, any text, in any language, can be written with it, and a rare character that did not get a token of its own enters the model in pieces. For instance, the symbol ℏ\hbar, when it appears in a text as a character, takes three bytes, (226,132,143)(226,\,132,\,143). The GPT-4o tokenizer splits it into two tokens, one with the first two bytes and another with the third, and neither of them, alone, is a character.

The vocabulary is built once, before training, from a corpus, the name we give to the collection of texts from which the model learns: books, web pages, papers, code. The most widely used method is byte-pair encoding (BPE). The rule is simple. GPT-2, a model released by OpenAI in 2019, will serve as our numerical example throughout the chapter, because its parameters are public. In the version of BPE used by it and by many later models, we start with a vocabulary that contains only the 256 bytes and write the whole corpus with them. We count how many times each pair of neighboring symbols appears in the corpus and merge the most frequent pair into a new symbol, which enters the vocabulary and is treated from then on as a unit. Then we rewrite the corpus with the new symbol, count again and repeat the merge, until the vocabulary reaches the desired size.

Table 1.2 shows the rule on a toy corpus, with letters in place of bytes to keep it readable. The corpus has four different Portuguese words: campo (field), which appears twice, tempo (time) and tempos (times), three times each, and templo (temple), once. That makes nine words in all. At the start, each letter is a symbol, and the pair m p appears in all nine, so it becomes the symbol mp. In the next count, the most frequent pair is mp o, with eight occurrences, because in templo the mp is followed by l. After five merges, tempo and tempos, the most frequent words, have become whole tokens, while campo stays in three pieces and templo, which appears only once, in four. To cut a new text, the tokenizer applies the merges in the order in which they were learned. Thus the word campos, which is not in the corpus, becomes campos.

Table 1.2. Five BPE merges on a toy corpus. In parentheses, how many times each word appears in the corpus; the count is the number of occurrences of the merged pair. Each row shows how the four words are written after the merge, and the dot separates the tokens.
Merge Pair merged Count campo (2) tempo (3) tempos (3) templo (1)
– – – campo tempo tempos templo
1 m + p 9 campo tempo tempos templo
2 mp + o 8 campo tempo tempos templo
3 t + e 7 campo tempo tempos templo
4 te + mpo 6 campo tempo tempos templo
5 tempo + s 3 campo tempo tempos templo

Swipe the table sideways to see every column.

BPE was born as a data-compression algorithm, and Sennrich, Haddow and Birch adapted it to cut words in machine translation [104]. In a real tokenizer, the corpus is enormous and the merge is repeated tens or hundreds of thousands of times. GPT-2 made 50 000 merges and added one special token, which marks the end of a document, giving V=256+50000+1=50257V=256+50\,000+1=50\,257 [92]. The GPT-4o vocabulary has about 200 thousand tokens.

Knowing that the model reads tokens explains some behaviors that surprise people who use these tools. In the question How many letters r are there in morango? (Portuguese for strawberry), the word morango reaches the model as ␣mor and ango, and its seven letters do not appear in the input. To count them, the model needs to know which letters make up each token, something it only learns indirectly, from the training texts. In the same tokenizer, numbers break into blocks of up to three digits, and 3.14159263.1415926 enters as 3 . 141 592 6, which helps to understand why calculations with long numbers are a weak point. An equation in LaTeX also becomes a long sequence of fragments. The divergence ∇⋅𝒋\nabla\cdot\mathbf{j}, written \nabla\cdot\mathbf{j}, takes ten tokens, and \nabla itself breaks into \n and abla. Indices and signs scattered over many fragments are another weak point.

Finally, the size of a text, for the model, is its number of tokens. The model can only take into account a maximum number of tokens at a time, its context window, and paid use is measured and billed in tokens. When the corpus used to build the vocabulary is dominated by English, the same content in Portuguese usually takes more tokens, in a proportion that depends on the text and on the tokenizer [90]. In the GPT-4o tokenizer, the sentence in Table 1.1 takes seven tokens, and the same sentence in English, six.

1.2.2 Generation token by token and the chain rule

To understand what the model computes, we follow one generation. We call prefix the text that has already been written. Given the prefix, the model returns a probability distribution over the next token, that is, a list with a number between 0 and 1 for each of the VV tokens in the vocabulary, summing to 1. Then we draw a token with those probabilities, like someone throwing a loaded die with VV faces, append the drawn token to the prefix and repeat. Table 1.3 shows three steps starting from the prefix The magnetic, with probabilities invented to illustrate the mechanism. In this simplification words play the role of tokens; a real tokenizer could split them.

Table 1.3. Three generation steps, with illustrative probabilities.
Prefix Some probabilities (illustrative) Token drawn
The magnetic field 0.6; moment 0.3; others 0.1 field
The magnetic field varies 0.5; is 0.3; others 0.2 varies
The magnetic field varies slowly 0.4; in 0.35; others 0.25 slowly

Note that at each step the prefix changes, and with it the distribution, while the parameters of the model stay fixed throughout the generation. The draw can pick a less probable option, and this is why the same question can receive different answers. Multiplying the probabilities of the three drawn tokens, we obtain the probability of the whole continuation, 0.6×0.5×0.4=0.120.6\times0.5\times0.4=0.12.

This multiplication is a case of the chain rule of probability theory. For three tokens, it says that

p(x1,x2,x3)=p(x1)p(x2∣x1)p(x3∣x1,x2),p(x_1,x_2,x_3)=p(x_1)\,p(x_2\mid x_1)\,p(x_3\mid x_1,x_2),
p(x1,x2,x3)=p(x1)p(x2∣x1)p(x3∣x1,x2),\begin{aligned} & p(x_1,x_2,x_3)\\ &\quad {}=p(x_1)\,p(x_2\mid x_1)\,p(x_3\mid x_1,x_2),\end{aligned}

that is, the probability of the sequence is that of the first token, times that of the second given the first, times that of the third given the first two. For nn tokens and any distribution over sequences,

pθ(x1,…,xn)=∏t=1npθ(xt∣x<t),p_\theta(x_1,\dots,x_n)=\prod_{t=1}^{n}p_\theta(x_t\mid x_{<t}),
pθ(x1,…,xn)=∏t=1npθ(xt∣x<t),\begin{aligned} & p_\theta(x_1,\dots,x_n)\\ &\quad {}=\prod_{t=1}^{n}p_\theta(x_t\mid x_{<t}),\end{aligned}
(1.1)

where x<t=(x1,…,xt−1)x_{<t}=(x_1,\dots,x_{t-1}) is the prefix of position tt, pθ(xt∣x<t)p_\theta(x_t\mid x_{<t}) is the probability of token xtx_t given that prefix, and θ\theta collects all the parameters of the model. The equality is an identity and holds without any independence assumption, because each factor can depend on the whole preceding text. That is, to obtain the probability of any text it is enough to predict the next token given the prefix, and this is what the network computes. Generation runs through (1.1) factor by factor, as in Table 1.3.

1.2.3 Cross-entropy, relative entropy and perplexity

So far we have assumed the model was ready. Now we see how the parameters are chosen, that is, what training is. The idea is simple. We go through the corpus and, at each position, ask what probability the model assigned to the token that actually came next; a good model gives high probability to the true token. By the chain rule (1.1), the probability the model assigns to the whole corpus, its likelihood, is the product of these probabilities, an astronomically small number. So we work with its logarithm, which turns the product into a sum, and divide by the number NN of positions in the corpus. With a minus sign, so that the result is positive, we obtain the average of −ln⁡p-\ln p over the positions,

ℒ(θ)=−1N∑t=1Nln⁡pθ(xt∣x<t),\mathcal{L}(\theta)=-\frac{1}{N}\sum_{t=1}^{N}\ln p_\theta(x_t\mid x_{<t}),
(1.2)

called the loss. Training means searching for the parameters that make this loss small, and minimizing the loss is the same as maximizing the likelihood. Each term of the sum measures the model’s surprise at one token. If the model gave probability 0.50.5 to the correct token, the term is ln⁡2≈0.69\ln2\approx0.69; if it gave 0.010.01, it is ln⁡100≈4.6\ln100\approx4.6. With the natural logarithm, the loss is measured in nats; with the base-2 logarithm, it would be measured in bits. Each position of the corpus contributes one term to the sum, and Section 1.4.2 shows why the terms of a whole stretch of text can be computed in a single pass over it.

The minimization is done by gradient descent. We compute the derivative of the loss with respect to each parameter, the gradient, and change all the parameters a little in the direction in which the loss decreases. For a parameter θ\theta, each step makes θ→θ−η∂ℒ/∂θ\theta\to\theta-\eta\,\partial\mathcal{L}/\partial\theta, where η\eta, the learning rate, is a small number chosen by whoever trains the model. In practice, the corpus is cut into stretches the size of the context window, and each step computes the gradient on a batch of randomly drawn stretches, with millions of tokens, instead of the whole corpus; this is why the method is called stochastic gradient descent. Then we repeat with other batches, millions of times. It is the dynamics of a particle with a lot of friction in a potential, always going down along the steepest slope. Section 1.4.7 returns to this procedure to estimate the cost of training.

To see what training produces, we will reorganize the sum (1.2). Each term depends on only two things, the prefix x<tx_{<t}, which we call here the context, and the token xtx_t that came after it. Positions with the same context and the same next token contribute equal terms, and we can group them. We call f(c)f(c) the fraction of the NN positions of the corpus where the context is cc, and f(i∣c)f(i\mid c) the fraction of those positions where the next token was ii, that is, the frequency of ii after cc. Token ii follows context cc in Nf(c)f(i∣c)N\,f(c)\,f(i\mid c) positions, all with the same term −ln⁡pθ(i∣c)-\ln p_\theta(i\mid c), and the loss becomes

ℒ(θ)=∑cf(c)[−∑i=1Vf(i∣c)ln⁡pθ(i∣c)],\mathcal{L}(\theta)=\sum_c f(c)\Big[-\sum_{i=1}^{V}f(i\mid c)\,\ln p_\theta(i\mid c)\Big],

where the first sum runs over the distinct contexts of the corpus. We have only changed the order of the terms. But now the bracket has a direct reading: it is the model’s average surprise in context cc when the next tokens appear with the corpus frequencies. The loss is the average of these brackets, and each context weighs the fraction of the positions where it appears.

The bracket is a case of a quantity with a name of its own. For two distributions ff and qq over the same symbols, the average of −ln⁡q-\ln q with the symbols drawn from ff is the cross-entropy between ff and qq. Adding and subtracting ln⁡fi\ln f_i in each term, it splits into two parts,

−∑ifiln⁡qi=−∑ifiln⁡fi+∑ifiln⁡fiqi=H(f)+DKL(f‖q).-\sum_i f_i\ln q_i=-\sum_i f_i\ln f_i+\sum_i f_i\ln\frac{f_i}{q_i}=H(f)+D_{\mathrm{KL}}(f\,\Vert\,q).
−∑ifiln⁡qi=−∑ifiln⁡fi+∑ifiln⁡fiqi=H(f)+DKL(f‖q).\begin{aligned} & -\sum_i f_i\ln q_i\\ &\quad {}=-\sum_i f_i\ln f_i\\ &\qquad {}+\sum_i f_i\ln\frac{f_i}{q_i}\\ &\quad {}=H(f)+D_{\mathrm{KL}}(f\,\Vert\,q).\end{aligned}
(1.3)

The first term, HH, is the Shannon entropy of ff. It depends only on ff and measures the uncertainty that exists in the data themselves. The second, DKLD_{\mathrm{KL}}, is the relative entropy, or Kullback–Leibler divergence, and measures the extra surprise of someone who uses qq when the symbols follow ff. This extra surprise is never negative. In fact, since ln⁡x≤x−1\ln x\le x-1, with equality only at x=1x=1, we have

−DKL(f‖q)=∑ifiln⁡qifi≤∑ifi(qifi−1)=∑iqi−1≤0,-D_{\mathrm{KL}}(f\,\Vert\,q)=\sum_i f_i\ln\frac{q_i}{f_i}\le\sum_i f_i\Big(\frac{q_i}{f_i}-1\Big)=\sum_i q_i-1\le0,
−DKL(f‖q)=∑ifiln⁡qifi≤∑ifi(qifi−1)=∑iqi−1≤0,\begin{aligned} & -D_{\mathrm{KL}}(f\,\Vert\,q)\\ &\quad {}=\sum_i f_i\ln\frac{q_i}{f_i}\\ &\quad {}\le\sum_i f_i\Big(\frac{q_i}{f_i}-1\Big)\\ &\quad {}=\sum_i q_i-1\\ &\quad {}\le0,\end{aligned}

with the sums restricted to the symbols with fi>0f_i>0. Equality requires qi=fiq_i=f_i for all of them. That is, DKL≥0D_{\mathrm{KL}}\ge0, with DKL=0D_{\mathrm{KL}}=0 only when q=fq=f, a result known as Gibbs’ inequality.

Now we only need to apply (1.3) to the bracket of each context, with f=f(⋅∣c)f=f(\cdot\mid c) and q=pθ(⋅∣c)q=p_\theta(\cdot\mid c), where the dot stands for the list of values for all the tokens of the vocabulary. The bracket of context cc splits into the entropy HcH_c of the frequencies f(⋅∣c)f(\cdot\mid c) and the divergence DKL,c(θ)D_{\mathrm{KL},c}(\theta) between these frequencies and the model’s probabilities pθ(⋅∣c)p_\theta(\cdot\mid c). We obtain

ℒ(θ)=∑cf(c)Hc+∑cf(c)DKL,c(θ),\mathcal{L}(\theta)=\sum_c f(c)\,H_c+\sum_c f(c)\,D_{\mathrm{KL},c}(\theta),
ℒ(θ)=∑cf(c)Hc+∑cf(c)DKL,c(θ),\begin{aligned}\mathcal{L}(\theta) & {}=\sum_c f(c)\,H_c\\ &\qquad {}+\sum_c f(c)\,D_{\mathrm{KL},c}(\theta),\end{aligned}
(1.4)

and this is the relation between the loss (1.2) and the decomposition (1.3). The first term is the average entropy of the corpus frequencies and does not depend on θ\theta. Therefore training can only reduce the second, and the lowest possible loss is the average entropy, reached when DKL,c=0D_{\mathrm{KL},c}=0 in every context, that is, when the model reproduces the corpus frequencies. For instance, if a context appears followed three times by token A and once by token B, we have f(A∣c)=3/4f(\mathrm{A}\mid c)=3/4 and f(B∣c)=1/4f(\mathrm{B}\mid c)=1/4, with Hc=−34ln⁡34−14ln⁡14≈0.562H_c=-\tfrac34\ln\tfrac34-\tfrac14\ln\tfrac14\approx0.562 nat. A model that gives probability 1/21/2 to each of the two tokens has, in this context, a loss of ln⁡2≈0.693\ln2\approx0.693 nat per position, and the difference, 0.1310.131 nat, is the value of DKL,cD_{\mathrm{KL},c} for this model. With 3/43/4 and 1/41/4, the loss falls to 0.5620.562 nat and DKL,cD_{\mathrm{KL},c} vanishes. The example “Training reproduces frequencies”, at the end of this section, reaches the same result by minimizing the loss directly.

In a real corpus, this calculation has a consequence we need to understand. A long context almost never repeats, and then f(⋅∣c)f(\cdot\mid c) puts all the weight on the single token that came after it, with zero entropy. The lowest loss on the corpus would be practically zero, that of a model that memorized the text. In practice, training stays far from this minimum, because the same parameters serve all contexts. Adjusting them to get the next token right in one context also changes the predictions in similar contexts, and what training manages to reduce are mainly the errors common to many contexts, that is, the regularities of the text. This is what allows the model to be right on texts it has never seen, although it can also memorize passages that are repeated many times in the corpus. This is why what matters is the loss on texts left out of training, the test loss of Section 1.9. If we think of the corpus as a sample from a source, a random process that produces texts, the decomposition (1.4) holds for this loss with the probabilities of the source in place of the corpus frequencies. The first term becomes the entropy of the source, the uncertainty about the next token that remains even for someone who knows all the preceding text, and no model goes below it.

It remains to understand why the average over a corpus tells us something about the source. Successive positions of a text are correlated, like successive instants of a trajectory, and the justification is the same as in statistical mechanics, where the time average along a long trajectory replaces the ensemble average in a stationary and ergodic system. For texts, these properties are assumptions about the source: its statistics do not change along the text, and a long stretch is representative of the whole source. With them, and with a large corpus, the average (1.2) of a fixed model approximates its expected loss on new texts. But training fits the model to the corpus itself, and that is why the test loss is computed on texts left out of training.

A loss in nats is hard to interpret, and so we also use the perplexity, PPL=eℒ\mathrm{PPL}=\mathrm{e}^{\mathcal{L}}, which translates it into a number of choices. A model that spreads uniform probability over KK continuations has loss ln⁡K\ln K and, therefore, PPL=K\mathrm{PPL}=K. In the continuation of Table 1.3, −ln⁡0.12≈2.12-\ln0.12\approx2.12 nats over three tokens give 0.710.71 nat per token and PPL=e0.71≈2.0\mathrm{PPL}=\mathrm{e}^{0.71}\approx2.0. That is, in these three steps the model behaves as if it were choosing, on average, between two equally probable options.

The task of predicting the next symbol is older than today’s computers. Shannon estimated the entropy of the source for written English by asking people to guess the next letter of a text. With a context of up to 100 letters, he arrived at something of the order of 1 bit per letter, which corresponds to a redundancy of about 75%: text uses close to four times more letters than the minimum needed to carry the same information [106]. An LLM is trained on the same task, using the whole corpus.

For those who work with quantum information

Umegaki’s relative entropy, S(ρ‖σ)=Tr⁡ρ(ln⁡ρ−ln⁡σ)S(\rho\Vert\sigma)=\operatorname{Tr}\,\rho\,(\ln\rho-\ln\sigma), is the noncommutative version of DKLD_{\mathrm{KL}}: S≥0S\ge 0, with equality only for ρ=σ\rho=\sigma. Araki extended the definition to states of general von Neumann algebras by means of the relative modular operator, which makes it available for the type III algebras of quantum field theory, where there are no density matrices. Uhlmann proved monotonicity: relative entropy decreases under operations that lose information. The classical version has the same property, and grouping tokens or discarding context never increases DKLD_{\mathrm{KL}}. The training objective of an LLM is the commutative and discrete case of this family.

Training reproduces frequencies

The same context appears four times in the corpus, followed three times by token A and once by token B. The model assigns probability pp to A and 1−p1-p to B. The total loss over the four occurrences is ℒtot(p)=4ℒ(p)\mathcal{L}_{\text{tot}}(p)=4\mathcal{L}(p), with ℒ\mathcal{L} given in (1.2), so the factor of 4 does not alter the minimum:

ℒtot(p)=−3ln⁡p−ln⁡(1−p),\mathcal{L}_{\text{tot}}(p)=-3\ln p-\ln(1-p),
ℒtot′(p)=−3p+11−p=0⇒p=34,\mathcal{L}_{\text{tot}}'(p)=-\frac{3}{p}+\frac{1}{1-p}=0\ \Rightarrow\ p=\frac34,
ℒtot′(p)=−3p+11−p=0⇒p=34,\begin{aligned}\mathcal{L}_{\text{tot}}'(p) & {}=-\frac{3}{p}+\frac{1}{1-p}\\ & {}=0\\ & {}\Rightarrow\ p=\frac34,\end{aligned}
ℒtot″(34)=643>0.\mathcal{L}_{\text{tot}}''\!\left(\tfrac34\right)=\frac{64}{3}>0 .

The fit reproduces the corpus frequency, as (1.4) predicts, and at the minimum the loss per position is the entropy H(34,14)≈0.562H(\tfrac34,\tfrac14)\approx0.562 nat, with DKL=0D_{\mathrm{KL}}=0. With arbitrary counts nkn_k, the same calculation with a Lagrange multiplier gives pk=nk/∑jnjp_k=n_k/\sum_j n_j. The objective function depends only on the frequencies, and whether A or B is true does not enter the calculation. If a misconception is frequent in the corpus, the model learns the misconception.

An actual fitting step, in a one-parameter model

We write p=σ(θ)=1/(1+e−θ)p=\sigma(\theta)=1/(1+\mathrm{e}^{-\theta}) in the example with three A and one B, so that the model has a single parameter, θ\theta. Differentiating the total loss of the previous example, with σ′=σ(1−σ)\sigma'=\sigma(1-\sigma), we obtain dℒtot/dθ=4p−3\mathrm{d}\mathcal{L}_{\text{tot}}/\mathrm{d}\theta=4p-3. Starting from θ=0\theta=0, we have p=1/2p=1/2 and gradient −1-1. A step with learning rate η=0.4\eta=0.4 produces

θnew=0−0.4(−1)=0.4,\theta_{\mathrm{new}}=0-0.4(-1)=0.4,
pnew≃0.599.p_{\mathrm{new}}\simeq0.599.

The total loss drops from 2.7732.773 to 2.4522.452 nats. Per position, it goes from 0.6930.693 to 0.6130.613 nat. Since the entropy, 0.5620.562 nat, does not depend on θ\theta, the step reduced DKL,cD_{\mathrm{KL},c} from 0.1310.131 to 0.0510.051 nat. We have not yet reached the optimum p=3/4p=3/4: more steps approach the minimum. In a network, many contexts share the same parameters. This sharing makes it possible to learn regularities and apply them to new contexts; the one-parameter model illustrates the fitting, but on its own it does not describe the ability of an LLM to generalize.

1.3 Why the recipe took so long to work

The recipe of the previous sections is old. In 1948, Shannon was already generating texts by drawing each word with the frequency with which it follows the previous one [105], and the result has plausible word pairs and nonsensical sentences. In the lesson, we show a text drawn this way from the Portuguese notes of this course with the program codigo/shannon.py. The question of this section is why the same recipe, predicting the next piece from text statistics, took so long to yield what we see today.

The first obstacle is the number of contexts. A table storing, for each prefix, the frequency of each following token would need one row per prefix, and the number of prefixes grows exponentially with their length. With the GPT-4o vocabulary of about 2×1052\times10^5 tokens, there are (2×105)10≈1053(2\times10^5)^{10}\approx10^{53} sequences of ten tokens, almost all of them meaningless. But even plausible texts are too numerous. Shannon estimated that written English carries about one bit per letter [106], and a token has, on average, a few letters. Counting only one bit per token, there are more than 2100≈10302^{100}\approx10^{30} plausible hundred-token paragraphs, whereas the largest model of Meta’s Llama 3 family was trained on 15.6 trillion tokens, about 101310^{13} [47]. That is, almost every long context a model encounters never appeared in training, and a frequency table would have nothing to say about it. The model needs to generalize, treating similar contexts similarly, including ones it has never seen.

The way out, proposed by Bengio and collaborators in 2003, is to replace each word by a vector of real numbers adjusted during training, so that words used in similar ways stay close together, and to make the prediction with a function of those vectors [16]. What the model learns about electric then carries over, in part, to magnetic, and a new context looks close to known contexts. That vector is the embedding, which we will examine in detail in Section 1.4.1.

But the vector of each word alone is not enough, because the meaning of a word depends on the others. The token ␣campo (“field”) is the same, 22 791, in Far from the wire with current, the field varies slowly. and in After the rain at the stadium, the field grew muddy., and enters the model with the same vector in both sentences. What follows is very different, and the information that settles the meaning sits in earlier, sometimes distant words. The networks most used for text until 2017, recurrent networks, read text one word at a time and kept the past in a vector of fixed size, updated at each word [53]. They worked like a reader allowed to carry forward only a short note summarizing what had been read so far. What lay far back faded from the note. Training also had to follow the order of the text, word by word, without computing all positions at once. Attention without recurrence, the subject of the next section, solves both problems: each position looks directly for what it needs, and none waits for the summary of the preceding one.

1.4 Attention and the transformer

We already know what the model computes, a distribution for the next token, and how the parameters are fitted. What remains is the function itself, that is, the calculation that leads from the sequence of token numbers to that distribution. We start with the whole path and then look at each stage in turn.

The calculation has three stages (Figure 1.1). In the first, each token of the text is replaced by a vector of dd real numbers, its embedding. With nn tokens we have nn vectors, which we store in the rows of a matrix H(0)H^{(0)}, one row for each position of the text. In the second stage, this matrix is transformed several times. Each transformation receives a matrix with nn rows and dd columns and returns another of the same size, still with one vector per position, and it is called a block. The model applies LL blocks, one after the other, and the output of each block is the input of the next. Calling H(ℓ)H^{(\ell)} the matrix that comes out of block ℓ\ell, the second stage is the sequence

H(0)→H(1)→H(2)→⋯→H(L),H^{(0)}\;\longrightarrow\;H^{(1)}\;\longrightarrow\;H^{(2)}\;\longrightarrow\;\cdots\;\longrightarrow\;H^{(L)},

where each arrow is a block. All blocks do the same kind of calculation, but each one has its own parameters. In the third stage, the vector of the last position, which is in the last row of H(L)H^{(L)}, is converted into a list of VV numbers, one for each token in the vocabulary, and this list becomes the probability distribution of the next token, pθ(xn+1∣x1,…,xn)p_\theta(x_{n+1}\mid x_1,\dots,x_n).

Each block makes two corrections to the vectors, one after the other. In the first, the vector of each position receives a correction computed from itself and from the vectors of the previous positions. This operation is called attention, and it is the only one in the model in which different positions exchange information. It is through attention that the vector of varies, in the sentence The electric field varies, can come to carry information about field. In the second, the vector of each position receives another correction, computed from it alone, by a small neural network that treats each position separately, the feed-forward network, or FF.

The path of one generation: from the text to the next token, which goes back into the sequence.
  1. Text → tokensTurn the prefix into identifiers.
  2. Embeddings and positionRepresent each position by a vector.
  3. L blocksApply attention and the feed-forward network.
  4. Logits → softmaxObtain probabilities for the next token.
  5. Sample a tokenAppend it to the prefix.

Repeat with the new prefix. The parameters stay fixed.

Figure 1.1. The path of one generation: from the text to the next token, which goes back into the sequence.

This architecture is called the transformer. It was proposed in 2017 by Vaswani and collaborators, in a paper on machine translation [116]. The language models that generate text today generally use a simplified version of it, which is the one we will describe, and the relation between the two appears in Section 1.4.3. There are other architectures, such as the state-space models of the Mamba family [49]. Next we look at each piece, in the order of the path.

1.4.1 Embeddings and position

We begin with the first stage, the replacement of each token by a vector. In Section 1.2.1 we saw that the number of a token is only a label, like the numbering of the entries of a dictionary. This number is not suitable for calculations. If it entered the network directly, token 22 791, campo (“field”), would be closer to token 22 792 than to token 46, O (“the”), and this closeness means nothing at all. So we associate with each token in the vocabulary a list of dd real numbers, that is, a vector in ℝd\mathbb{R}^d, called the embedding of the token. The VV vectors form a table, the matrix WE∈ℝV×dW_E\in\mathbb{R}^{V\times d}, with one row for each token, and the token with number ii is represented by row ii, which we call eie_i. Replacing a token by its vector is just looking up the corresponding row of the table.

The numbers in the table are not chosen by hand. The entries of WEW_E are parameters: they start out random and are adjusted in training, like the other parameters of the model. At the end of training, tokens that appear in similar contexts tend to have nearby vectors. The words magnetic and electric, for instance, appear in the same places in physics texts, and what tends to come after one resembles what comes after the other. Since the two should lead to similar predictions, training tends to give them nearby vectors. In the smallest version of GPT-2, which we will call the small GPT-2, d=768d=768; in large models, dd is of the order of thousands. Nobody decides what each component means. The values come out of training, and no axis needs to correspond to a property we know how to name.

The embedding still does not say at which position of the text the token is. The vector of dog is the same at any position, and the sentences the dog bit the man and the man bit the dog would give the same vectors, only in swapped rows. But order matters, because the two sentences say different things. For the model to be able to tell them apart, the position of each token has to be in the vector itself. The simplest choice adds to the embedding a position vector ptp_t, with the same dd components, that depends only on the position tt,

ht(0)=ext+pt,h^{(0)}_t=e_{x_t}+p_t ,

where xtx_t is the number of the token at position tt, and ht(0)h^{(0)}_t is row tt of the matrix H(0)H^{(0)}, that is, the vector that enters the first block at position tt. So the same token at different positions now has different vectors.

It remains to choose the vectors ptp_t. The original transformer uses sines and cosines [116]. The dd components of ptp_t are grouped in pairs, and pair number kk is

(pt,2k,pt,2k+1)=(sin⁡ωkt,cos⁡ωkt),\big(p_{t,2k},\,p_{t,2k+1}\big)=\big(\sin\omega_k t,\ \cos\omega_k t\big),
(pt,2k,pt,2k+1)=(sin⁡ωkt,cos⁡ωkt),\begin{aligned} & \big(p_{t,2k},\,p_{t,2k+1}\big)\\ &\quad {}=\big(\sin\omega_k t,\ \cos\omega_k t\big),\end{aligned}
ωk=10000−2k/d,\omega_k=10000^{-2k/d},

with k=0,1,…,d/2−1k=0,1,\dots,d/2-1. Each pair is a clock hand that turns with the position tt, with frequency ωk\omega_k, and the vector ptp_t is like a clock with d/2d/2 hands turning at different speeds. The fastest hand makes a full turn every 2π≈6.32\pi\approx6.3 positions and distinguishes neighboring positions; the slowest takes about 60 thousand positions to make a turn and distinguishes distant positions. Any choice of distinct vectors would distinguish the positions, but this one has a useful property: going from position tt to t+Δt+\Delta rotates each hand by the angle ωkΔ\omega_k\Delta, which depends only on the distance Δ\Delta. So the relation between ptp_t and pt+Δp_{t+\Delta} is the same anywhere in the text, and the model can learn to look, for example, for the token that is Δ\Delta positions back, wherever it is. The same idea reappears later, inside attention.

GPT-2 makes another choice: it treats the ptp_t as parameters and learns them in training, one vector for each of the 1024 positions of its context window. Many current models add no position vector at all and encode the position inside attention itself, a solution we will see in Section 1.4.4.

From label to vector

In the sentence of Table 1.1, “campo” with its leading space has label 2279122\,791. In an illustrative model with d=3d=3, the corresponding row of the table could be e22791=(0.2,−0.4,0.7)e_{22791}=(0.2,-0.4,0.7). If the vector of position 2 were p2=(0.1,0,−0.2)p_2=(0.1,0,-0.2), we would have h2(0)=(0.3,−0.4,0.5)h^{(0)}_2=(0.3,-0.4,0.5). These vectors are invented; the labels in the table come from the real tokenizer. Placing the seven vectors in the rows of a matrix, we obtain H(0)∈ℝ7×3H^{(0)}\in\mathbb{R}^{7\times3}. The label selects a row, the position adds order, and the following blocks make each representation depend on the context.

1.4.2 Attention

After the first stage, the vector of each position depends only on its token and its position. The vector of varies, in The electric field varies, is the same in any text in which varies appears in the fourth position. But to predict what comes after varies, the model needs to know what varies, and this information is at another position. Attention is the operation that brings into the vector of each position information from the others.

The simplest way to gather information from several positions is a weighted average. To update the vector of varies, attention computes an average of vectors associated with the four positions, with positive weights that add up to 1. The weights could be, for example, 0.11 for The, 0.31 for electric, 0.51 for field and 0.07 for varies itself (Figure 1.2). The average is dominated by the contribution of field, and the vector of varies comes to carry information about its subject. The numbers in the figure are illustrative, and the worked example later in this section shows where they come from. Note that the weights are computed from the vectors themselves and change from one text to another. In a trained model, varies may give more weight to field, the subject of the verb, because this information helps to predict what comes next.

Note also that the average for varies uses only varies and the previous positions. In a model that generates text, this restriction holds at every position: the average at position ii uses only the positions j≤ij\le i. The reason is that the text is generated in order, one token after the other. When the model computes what comes after field, the word varies has not been written yet, and the vector of field cannot depend on it. Attention with this restriction is called causal: the vector of each position depends only on what came before it and on itself.

The idea of attention, with illustrative weights. The new vector of varies receives a weighted average of the vectors of the four positions, and the thickness of each arrow follows its weight. The dashed arrow indicates a forbidden dependence: the vector of field cannot use a following position, such as varies.

New vector for “varies”

The · vector 1
weight 0.11
electric · vector 2
weight 0.31
field · vector 3
weight 0.51
varies · vector 4
weight 0.07

The weights sum to 1, and the average is dominated by “field”.

Illustrative weights. The vector for “field” cannot use “varies”, a subsequent position.

Figure 1.2. The idea of attention, with illustrative weights. The new vector of varies receives a weighted average of the vectors of the four positions, and the thickness of each arrow follows its weight. The dashed arrow indicates a forbidden dependence: the vector of field cannot use a following position, such as varies.

We still need to say how the weights are computed. For each pair of positions, the model computes a real number sijs_{ij}, the score, which measures how much position jj matters to position ii. The scores can have any sign, and to become weights they go through two operations: we take the exponential of each one, which makes them all positive, and divide by the sum, which makes the weights add up to 1. This recipe is called the softmax. It preserves the order of the scores, and the exponential sharpens the differences. With two scores, ln⁡3\ln3 and 00, the exponentials are 3 and 1, and the weights, 3/43/4 and 1/41/4. Readers who know statistical physics will recognize the Boltzmann factor here. Fixing position ii and writing Ej=−sijE_j=-s_{ij}, the weights of that position form the canonical distribution over the positions of the text,

wij=e−EjZi,w_{ij}=\frac{\mathrm{e}^{-E_j}}{Z_i},
Zi=∑l≤ie−El,Z_i=\sum_{l\le i}\mathrm{e}^{-E_l},

and the average attention computes is a thermal average, dominated by the lowest-energy positions, the ones that matter most to position ii. The analogy has limits: there is no heat bath, and each position has its own distribution, with energies that the model computes from the vectors using matrices fitted in training. We return to this reading in Section 1.5.1.

What remains is how the score is computed from the vectors. The simplest measure of affinity between two vectors is the scalar product, and we could take sij=hi⋅hjs_{ij}=h_i\cdot h_j, where hih_i is the current vector of position ii, written as a row. But the scalar product measures similarity, and each position would tend to give more weight to itself and to tokens similar to it. The verb varies would look for other verbs, when what it needs is its subject. And the content a position hands over when it is chosen does not need to be the same vector that serves to find it either. This is why the transformer computes, from the vector of each position, three different vectors, each with its own matrix of parameters,

qi=hiWQ,q_i=h_iW_Q,
ki=hiWK,k_i=h_iW_K,
vi=hiWV,v_i=h_iW_V,
WQ,WK,WV∈ℝd×dk,W_Q,W_K,W_V\in\mathbb{R}^{d\times d_k},
(1.5)

with the same three matrices at all positions. That is, each of the three vectors is a linear combination of the components of hih_i, with coefficients given by the corresponding matrix, and the example below does this calculation for the values. The query qiq_i represents what position ii is looking for; the key kjk_j, what position jj offers in order to be found; and the value vjv_j, the content that position jj hands over to whoever finds it. The picture is that of a card index: we compare the query with the label of each card, which is the key, and copy the content of the cards, which are the values, in the proportion in which the labels match the query. Since the three matrices are adjusted in training, it is training that decides what each position looks for and what it hands over. The dimension dkd_k of these vectors can be smaller than dd.

Putting the pieces together, the score is sij=qi⋅kj/dks_{ij}=q_i\cdot k_j/\sqrt{d_k}, with a factor 1/dk1/\sqrt{d_k} that we explain shortly, and the weights and the output of position ii are

wij=esij∑l≤iesil,w_{ij}=\frac{\mathrm{e}^{s_{ij}}}{\sum_{l\le i}\mathrm{e}^{s_{il}}},
yi=∑j≤iwijvj,y_i=\sum_{j\le i}w_{ij}\,v_j ,
(1.6)

where the sums run only over the positions j≤ij\le i, as the causal restriction requires; for j>ij>i, the weight wijw_{ij} is zero. The output yiy_i is the weighted average of the values, and from it comes the correction added to the vector of position ii, as we will see in Section 1.4.5. Note that this sum does not depend on the order of its terms. Without position information in the vectors, the output would be the same for any order of the previous positions, and this is what the vector ptp_t of Section 1.4.1 corrects. The calculation of (1.5) and (1.6), with its three matrices, is called an attention head; in Section 1.4.4 we will see why models use several of them.

One attention head, by hand

We now do the calculation for position varies, i=4i=4, in the sentence The electric field varies slowly, in a toy model with d=3d=3 and dk=2d_k=2 and with vectors invented so that the calculations are simple. We start with the values. Suppose that the current vectors of the five positions are h1=(−1,−1,1)h_1=(-1,-1,1), for The, h2=(1,0,0)h_2=(1,0,0), for electric, h3=(0,1,0)h_3=(0,1,0), for field, h4=(0,0,1)h_4=(0,0,1), for varies, and h5=(22/3,22/3,−7/3)h_5=(22/3,\,22/3,\,-7/3), for slowly, and that the value matrix is

WV=(100111).W_V=\begin{pmatrix}1&0\\ 0&1\\ 1&1\end{pmatrix}.

By (1.5), each value is the vector of the position multiplied by WVW_V, and we obtain v1=(0,0)v_1=(0,\,0), v2=(1,0)v_2=(1,\,0), v3=(0,1)v_3=(0,\,1), v4=(1,1)v_4=(1,\,1) and v5=(5,5)v_5=(5,\,5). Each vjv_j is the content that position jj hands over for the average, and the matrix WVW_V, adjusted in training, decides which part of the information in each vector enters this content. The queries and keys come out in the same way, with the matrices WQW_Q and WKW_K, and the scores from s4j=q4⋅kj/dks_{4j}=q_4\cdot k_j/\sqrt{d_k}. We directly assume the energies Ej=−s4jE_j=-s_{4j}, which take the values (1.5,0.5,0,2,−1)(1.5,\ 0.5,\ 0,\ 2,\ -1); the first four are those of the lesson. They are not independent of the vectors: since keys are linear in hjh_j, the energies are too, so the vector for slowly cannot be, for instance, a multiple of that of varies, whose energy it would multiply.

In training the whole sentence is present, yet position 5 is the one position 4 has to predict: it stays outside the sums in (1.6), which is equivalent to replacing its energy by +∞+\infty, because e−∞=0\mathrm{e}^{-\infty}=0. To two decimal places, the Boltzmann factors of the remaining four positions are e−Ej=(0.22,0.61,1,0.14)\mathrm{e}^{-E_j}=(0.22,\ 0.61,\ 1,\ 0.14), with sum Z4=1.97Z_4=1.97, and we obtain the weights and, with them, the average of the values,

(w41,…,w45)=(0.11,0.31,0.51,0.07,0),(w_{41},\dots,w_{45})=(0.11,\ 0.31,\ 0.51,\ 0.07,\ 0),
(w41,…,w45)=(0.11,0.31,0.51,0.07,0),\begin{aligned} & (w_{41},\dots,w_{45})\\ &\quad {}=(0.11,\ 0.31,\ 0.51,\ 0.07,\ 0),\end{aligned}
y4=∑j≤4w4jvj=(0.38,0.58).y_4=\sum_{j\le4}w_{4j}\,v_j=(0.38,\ 0.58).

The energy −1-1 and the value v5v_5 do not enter. If they did, slowly would take more than half the weight, and the output would jump to (3.06,3.14)(3.06,\ 3.14). The vector y4y_4 is the information that the position varies gathers from itself and from earlier ones, and from it comes the correction added to the vector of varies. Position 4 consults itself and the past in order to predict the token at position 5, which remains hidden.

Check your understanding

If only v1v_1 changes to (1,1)(1,\,1) in the example, do the weights change? No: keeping queries and keys fixed, the weights remain (0.11,0.31,0.51,0.07)(0.11,\,0.31,\,0.51,\,0.07), and the output becomes (0.49,0.69)(0.49,\,0.69).

Now we see why the factor 1/dk1/\sqrt{d_k} appears. Larger scores concentrate the weights: if the energies of the example doubled, the weights would go from

(0.11,0.31,0.51,0.07)(0.11,\ 0.31,\ 0.51,\ 0.07)
to(0.03,0.26,0.70,0.01).\text{to}\ (0.03,\ 0.26,\ 0.70,\ 0.01).

If the components of qq and kk are independent, with zero mean and unit variance, the product q⋅kq\cdot k, a sum of dkd_k terms, has variance dkd_k. Without the factor, the scores would grow with the dimension, and the softmax would give weight close to 1 to one position and close to 0 to the others. In this regime, small changes in the scores barely change the weights, and gradient descent, which depends on those derivatives, gets stuck. In the Boltzmann factor, 1/dk1/\sqrt{d_k} plays the role of an inverse temperature, and doubling the scores is halving the temperature.

The weights of all positions of The electric field varies can be collected in a matrix. With rows and columns in the order The, electric, field, varies, we have

(wij)=(10000.270.73000.090.240.6700.110.310.510.07).(w_{ij})=\begin{pmatrix}1&0&0&0\\ 0.27&0.73&0&0\\ 0.09&0.24&0.67&0\\ 0.11&0.31&0.51&0.07\end{pmatrix}.

The first row is (1,0,0,0)(1,0,0,0), because The can only use itself. The second and third come from the energies (1,0)(1,\,0) and (2,0,1)(2,\,0,\,1), also invented, and the last row is that of the example and of Figure 1.2. Each row adds up to 1, and the weights above the diagonal are all zero, because no position uses the future.

So far we have done the calculations position by position. In papers, and in the computer, they are done for all positions at once, with matrices. Placing the vectors of the nn positions in the rows of a matrix H∈ℝn×dH\in\mathbb{R}^{n\times d}, the queries, keys and values sit in the rows of Q=HWQQ=HW_Q, K=HWKK=HW_K and V=HWVV=HW_V. The matrix QK⊤QK^{\top} has in row ii and column jj the product qi⋅kjq_i\cdot k_j, that is, it collects all the scores, and attention is written

Attn⁡(Q,K,V)=softmax⁡(QK⊤dk+M)V,\operatorname{Attn}(Q,K,V)=\operatorname{softmax}\!\left(\frac{QK^{\top}}{\sqrt{d_k}}+M\right)V,
Attn⁡(Q,K,V)=softmax⁡(QK⊤dk+M)V,\begin{aligned} & \operatorname{Attn}(Q,K,V)\\ &\quad {}=\operatorname{softmax}\!\left(\frac{QK^{\top}}{\sqrt{d_k}}+M\right)V,\end{aligned}
Mij={0,j≤i,−∞,j>i,M_{ij}=\begin{cases}0,& j\le i,\\ -\infty,& j>i,\end{cases}
(1.7)

where the softmax is applied to each row separately. The notation is the usual one in the literature, and the VV of the value matrix has nothing to do with the size of the vocabulary. The matrix MM is the causal mask. It adds −∞-\infty to the scores of future positions, as we did in the example, and these positions receive zero weight (Figure 1.3). That is, the mask is the restriction j≤ij\le i of (1.6) written for the whole matrix, and for The electric field varies the softmax of (1.7) is the weight matrix above. Queries and keys determine the weights, and the values are what gets combined. Each attention head computes (1.7) with its own matrices WQW_Q, WKW_K and WVW_V.

Causal mask. Row $i$ only assigns weight to the keys $j\le i$; the scores above the diagonal are $-\infty$ and receive zero weight in the softmax.

Column: key j · row: query i

Adding −∞ before the softmax makes the weight of the future zero.

Figure 1.3. Causal mask. Row ii only assigns weight to the keys j≤ij\le i; the scores above the diagonal are −∞-\infty and receive zero weight in the softmax.

Explore

Which positions can position 4 consult?

We use the hand-worked example of this section, at the position of varies. The scores are minus the energies of the example: (−1.5, −0.5, 0, −2, 1). The values of The, electric, field, varies and slowly are v₁ = (0, 0), v₂ = (1, 0), v₃ = (0, 1), v₄ = (1, 1) and v₅ = (5, 5). The fifth position, slowly, lies in the future.

Before touching anything: should changing only v₁ change the weights? And removing the causal mask?

The controls work when the file is opened in a browser such as Safari or Chrome. The values below are for the starting position.

Weights = (0.114; 0.309; 0.509; 0.069; 0.000). Output = (0.378; 0.578). Position 5 stays out of reach.

What to look for

Queries and keys fix the weights; the values fix the content that gets combined. Replacing v₁ by (1, 1) keeps the weights and changes the output from (0.378, 0.578) to (0.491, 0.691). Removing the mask lets position 4 use slowly, the token it is supposed to predict: that is information leakage. The temperature control here acts on attention, and not on the output distribution over the vocabulary.

The mask has an important consequence for training. In generation, only the final vector of the last position becomes a distribution. In training, the third stage of the path is applied to all the rows of H(L)H^{(L)}: in a stretch of nn tokens, the final vector of position ii gives the distribution of token i+1i+1, and the token that actually came provides one term of the sum (1.2). The mask ensures that this vector depends only on the positions j≤ij\le i, without looking at the answer. Since each row of (1.7) depends only on the vectors that enter the block, all the rows can be computed at the same time, and a single pass over the stretch produces the nn predictions at once, each conditioned only on its own prefix. But in generation there is no such shortcut: each drawn token has to enter the prefix before the next one is computed.

1.4.3 The 2017 transformer and today’s models

With attention in hand, we can see what the transformer brought that was new. The machine translation systems before 2017 used recurrent networks, some of them already equipped with an early form of attention [14]. A recurrent network reads the sentence one token at a time and summarizes what it has read in a single vector of fixed size, its state, which is updated at each token. The information in the first token only reaches the last one after going through all the intermediate updates, and training has to follow the order of the sentence, one token after the other. In the transformer, the vector of position ii uses the vector of each previous position directly, without intermediaries, and, as we saw at the end of Section 1.4.2, all the positions of a training sequence are computed at the same time. This makes good use of graphics processors, which are built to run many calculations in parallel, and made it feasible to train larger models on more text.

The 2017 transformer translated sentences and therefore had two parts, each made of several blocks. The first, the encoder, processed the original sentence, for example O campo elétrico varia. Since this sentence is known in full from the start, attention there did not have the causal restriction: the vector of campo could use O as well as elétrico and varia. The second part, the decoder, wrote the translation, The electric field varies, one token at a time, as in Table 1.3. There the causal restriction held, because the translation was still being written, and the vector of field could only use The, electric and field itself. Each block of the decoder also had a second attention, in which the queries came from the translation, and the keys and values from the vectors the encoder computed for the original sentence. This is how the choice of each word of the translation took the whole original sentence into account.

In a model like GPT, short for generative pre-trained transformer, there is no original sentence separate from the answer. The user’s question and the model’s answer form a single text, which the model continues token by token, and the same holds for the texts of training. So the part that writes is enough. The models of the GPT family, and most of the LLMs that generate text today, use only the decoder, without the second attention, that is, a sequence of blocks with causal attention. This is the version we describe in this section.

1.4.4 Several heads, cost and relative position

An attention head computes, for each position, a single weighted average. But the vector of varies may need, at the same time, information about the subject and about the topic of the text, which sit at different positions, and a single average tends to mix the two. This is why each block uses several heads in parallel, each with its own matrices WQW_Q, WKW_K and WVW_V and therefore with its own weights. Each head produces, at each position, an output yiy_i with dkd_k components. With nhn_h heads, we use dk=d/nhd_k=d/n_h, so that the total cost is that of a single head with dd components. The nhn_h outputs are then placed side by side, again forming a vector with dd components, and a last matrix WO∈ℝd×dW_O\in\mathbb{R}^{d\times d} mixes the contributions of the heads. The result is the correction the block adds to the vector of the position. In the small GPT-2, d=768d=768 and there are nh=12n_h=12 heads, each with dk=64d_k=64.

Different heads learn different relations. One example we know in detail is the induction heads [86]. Suppose the text already contains Harry Potter and that, further on, Harry appears again. At the position of the second Harry, an induction head gives a high weight to the position that came right after the first Harry, that of Potter, and copies that information from there, which raises the probability of Potter as the next token. For this it relies on another head, in an earlier block, that copies into the vector of each position the information about the previous token. So the vector of Potter comes to carry the information that it came after Harry, and this is the information that the key of Potter offers to the query of the second Harry. This mechanism underlies part of in-context learning, the ability to follow patterns and examples that are in the text of the conversation itself, without any change in the parameters.

Using all the previous positions directly has a price. In a text of nn tokens, each head computes a score for each pair of positions, of the order of n2n^2 scores, and adding up all the heads the number of operations of (1.7) grows as n2dn^2d per block. Doubling the length of the text quadruples this cost, and this is what makes long contexts expensive.

In generation there is a saving. Because of the causal restriction, the vector of each position does not depend on the tokens that come after it, and so nothing changes at the previous positions when a new token enters the prefix. The keys and values of those positions can then be kept in memory, in the so-called key-value cache. Each new token only computes its own query, key and value, and compares its query with the stored keys.

Now we can return to position. Many current models use RoPE, for rotary position embedding [113], which takes the clock of Section 1.4.1 inside attention. Nothing is added to the embedding. The components of the query and of the key are grouped in pairs, and at position tt each pair, seen as a vector in the plane, is rotated by the angle ωkt\omega_kt, with frequencies chosen in the same way as those of the hands of the clock. The scalar product between two plane vectors rotated by angles α\alpha and γ\gamma depends on these angles only through the difference α−γ\alpha-\gamma. For this reason the score between the query of position ii and the key of position jj depends on the positions only through the distance i−ji-j. That is, attention sees relative distances. To link varies to field, it is enough to know that field is one position before, wherever the sentence sits in the text.

1.4.5 Blocks and the residual stream

With attention ready, we can assemble a whole block. As we saw at the beginning of the section, each block makes two corrections: attention, which brings in information from other positions, and a second operation, which treats each position separately. The model applies LL blocks in sequence, all with the same form and each with its own parameters. In papers, the blocks are also called layers, and the number LL, the depth of the model. LL is 12 in the small GPT-2 and reaches about a hundred in large models. A block of the type used in current language models applies

H′=H+MHA(LN(H)),H'=H+\mathrm{MHA}\big(\mathrm{LN}(H)\big),
Hnew=H′+FF(LN(H′)),H_{\text{new}}=H'+\mathrm{FF}\big(\mathrm{LN}(H')\big),
(1.8)

where HH is the matrix that enters the block, H(ℓ−1)H^{(\ell-1)} in block ℓ\ell, and Hnew=H(ℓ)H_{\text{new}}=H^{(\ell)} is the one that comes out. LN is a normalization of the vectors, MHA is the multi-head attention of Section 1.4.4, and FF is the small neural network that treats each position separately; the abbreviations come from layer normalization, multi-head attention and feed-forward. The two equalities follow the same scheme: they normalize the vectors, compute a correction and add it to what was already there. We now look at LN and FF.

The normalization LN(x)=g⊙(x−μ)/σ+b\mathrm{LN}(x)=g\odot(x-\mu)/\sigma+b acts on the vector of each position separately. It subtracts from the components of xx their mean μ\mu and divides by the standard deviation σ\sigma of those components, so that the result has components with zero mean and unit variance. Then it applies a scale gg and a shift bb, vectors learned in training; the symbol ⊙\odot denotes the componentwise product [13]. In practice, a very small number is added to σ\sigma to avoid division by zero. In this way, attention and FF always receive vectors in a similar range of values, in any block, which stabilizes the training of models with dozens of blocks.

The feed-forward network, FF(x)=W2ϕ(W1x+b1)+b2\mathrm{FF}(x)=W_2\,\phi(W_1x+b_1)+b_2, makes the second correction. It also acts on the vector of each position separately, in three steps: the matrix W1W_1 takes the vector from dd to 4d4d components, the nonlinear function ϕ\phi is applied to each component, and the matrix W2W_2 returns to dd components. In the small GPT-2, there are 768 components at the input, 3072 in the middle and 768 at the output. Attention moves information between positions, and FF processes the information that is already in the vector of each position. Without ϕ\phi, FF would reduce to an affine transformation, W2W1x+W2b1+b2W_2W_1x+W_2b_1+b_2, and it is ϕ\phi that widens what it can represent. The full transformer would still be nonlinear, since attention and normalization also depend nonlinearly on the input. In GPT-2, ϕ\phi is a smooth version of max⁡(0,u)\max(0,u). These networks hold most of the parameters of each block, as we will see in Section 1.4.7. Geva and collaborators showed that they function as key-value memories [46]. Each row of W1W_1 recognizes a pattern in the vector, the key, and the corresponding column of W2W_2 adds to the vector the content associated with that pattern, the value. In lower blocks the patterns are superficial, and in higher ones semantic; in those higher blocks the values favor the tokens that tend to come right after the pattern.

Note the sums in (1.8): each stage computes a correction from the vectors and adds it to the vectors themselves (Figure 1.4). So the vector of each position is preserved from block to block and only receives additions. These residual connections make it easier to train networks with many blocks. Training needs the derivatives of the loss with respect to the parameters of all the blocks, and, by the chain rule of calculus, the derivative with respect to the input of a block is a product of factors, one for each block that comes after it. With the sums, each factor has the form 1+f′1+f', because the derivative of x+f(x)x+f(x) is 1+f′(x)1+f'(x); without them, it would be just f′f', and the product of many small factors would shrink quickly. The term 1 lets the derivatives cross the model even when the derivatives of the transformations are small.

A block, with the normalization before each stage. Each stage computes a correction from the vectors and adds it back to them.
  1. State HInput of the block and residual path.
  2. LN → attentionCompute a correction that mixes positions.
  3. Add to HH′ = H + attention correction.
  4. LN → feed-forwardCompute another correction, position by position, from H′.
  5. Add to H′New H = H′ + feed-forward correction.

Figure 1.4. A block, with the normalization before each stage. Each stage computes a correction from the vectors and adds it back to them.

We can read this additive structure dynamically. Since each block only adds corrections, the vector of each position works as a register that the blocks, one after the other, read and update. This register is called the residual stream [37]. Combining the two corrections of block ℓ\ell into one, FℓF_\ell, each block does H(ℓ)=H(ℓ−1)+Fℓ(H(ℓ−1))H^{(\ell)}=H^{(\ell-1)}+F_\ell\big(H^{(\ell-1)}\big), like an Euler step of a differential equation in which the depth ℓ\ell plays the role of time. The state is the whole matrix, because the correction of each position depends, through attention, on the previous positions. Lu and collaborators carried this reading further [79]. For them, the positions are particles, attention is the interaction between them, and FF is a single-particle term. The block takes an Euler step with Lie–Trotter operator splitting: first the interaction, then the single-particle term. Replacing Lie–Trotter with Strang–Marchuk splitting, which has smaller local error, they arrived at a block with one FF before and one after attention, which outperformed the original transformer in their experiments. This dynamical reading is the starting point of Section 1.5.4.

1.4.6 Output and sampling

We now reach the third stage. In generation, after the LL blocks, the vector of the last position, hn(L)h^{(L)}_n, has to become a distribution over the next token; in training, the same calculation is done at all positions, as we saw at the end of Section 1.4.2. It goes through a final normalization and is multiplied by the matrix WU∈ℝd×VW_U\in\mathbb{R}^{d\times V}, which produces a real number for each token in the vocabulary, its logit, z=LN(hn(L))WUz=\mathrm{LN}\big(h^{(L)}_n\big)\,W_U. Often WU=WE⊤W_U=W_E^{\top}. That is, the same embedding table is used at the output, and the logit of token ii is the scalar product of the final vector with the embedding eie_i. The largest logit goes to the token whose embedding has the largest scalar product with the final vector. The logits become probabilities through a second softmax,

pi=ezi/T∑jezj/T,p_i=\frac{\mathrm{e}^{z_i/T}}{\sum_j\mathrm{e}^{z_j/T}},
(1.9)

where TT is the temperature. In training, T=1T=1. In generation, TT is chosen by whoever uses the model: with small TT the probability concentrates on the tokens with the largest logits, and with large TT it spreads over the vocabulary. The example in Section 1.5.1 shows the numbers. Note that this is the second softmax of the model. The one in attention, in (1.7), distributes weight among positions of the sequence, and this one distributes probability among the VV tokens of the vocabulary. Section 1.5.1 reads this second softmax as a canonical ensemble, and Section 1.5.3 relates the first one to an associative memory.

Before the draw, many systems cut off the tail of the distribution [55]. The tail is made of thousands of unlikely tokens that, added together, still carry weight. In a vocabulary of 200 thousand tokens, for example, if a hundred thousand of them have probability 2×10−62\times10^{-6} each, together they add up to 0.20.2, and one draw in five would land on one of them. The top-kk cut keeps only the kk most probable tokens. The top-pp cut keeps the smallest set of tokens whose summed probability reaches pp. In the first row of Table 1.3, with p=0.9p=0.9, field and moment remain, which add up to 0.90.9, and the other tokens are discarded. In both cuts, the remaining probabilities are renormalized to add up to 1; in the example, 0.60.6 and 0.30.3 become 2/32/3 and 1/31/3. The drawn token goes back into the prefix, and the path of Figure 1.1 starts again.

Check your understanding

If we raise the output temperature, does the answer become more truthful? No: we change the selection probabilities, without adding evidence.

1.4.7 Number of parameters and the cost of training

With the pieces described, we can count the parameters. In each block, each head has three d×dkd\times d_k matrices. Since nhdk=dn_hd_k=d, the matrices WQW_Q, WKW_K and WVW_V of all the heads add up to 3d23d^2 parameters, and with WOW_O they make 4d24d^2. FF has one d×4dd\times4d matrix and one 4d×d4d\times d matrix, another 8d28d^2. Ignoring the terms proportional to dd, such as the vectors bb and gg, each block has 12d212d^2 parameters. With LL blocks, vocabulary VV and a maximum context of nctxn_{\text{ctx}} positions, we add the embedding tables of the tokens and of the positions and obtain the total number of parameters,

N≈12Ld2+Vd+nctxd.N\approx 12\,L\,d^2+V d+n_{\text{ctx}}\,d .
(1.10)

For the small GPT-2, L=12L=12, d=768d=768, V=50257V=50\,257 and nctx=1024n_{\text{ctx}}=1024 give 84.984.9 million parameters in the blocks and 39.439.4 million in the embedding tables, about 124 million in total, the published value.

The cost of training also comes out of an order-of-magnitude calculation. In the literature, NN denotes the number of parameters, as above, and not the number of positions in (1.2); the number of training tokens will be DD. As we saw in Section 1.2.3, each step of gradient descent uses a randomly drawn batch from the corpus, and current models use variants, such as Adam, that adjust the step size of each parameter. We now count the operations per token. Almost all the parameters are entries of matrices, and in a matrix-vector multiplication each entry takes part in one multiplication and one addition. The forward pass, the calculation of the probabilities, then takes about 2N2N operations per token. Backpropagation, the calculation of the gradient, runs through the network from back to front applying the chain rule of differential calculus. In each matrix, it computes the derivatives with respect to the input and with respect to the parameters, each at a cost similar to that of the forward pass, and so it costs about twice as much, about 4N4N. Training on DD tokens then requires

C≈6NDC\approx 6ND
(1.11)

floating-point operations, which are multiplications and additions of real numbers in the computer [64]. For GPT-3, with 175 billion parameters and 300 billion training tokens, the calculation gives 3.15×10233.15\times10^{23} operations, practically the 3.14×10233.14\times10^{23} reported by the authors [20]. A current graphics processor performs of the order of 101510^{15} operations per second and would take, alone, about a decade; this is why training uses thousands of them in parallel. The estimate (1.11) returns in Section 1.9.

1.4.8 Parallel training and scale

Attention also changed the scale of training. Since no position depends on a summary computed at the previous one, training computes the predictions for all positions of a stretch in the same pass, and the mask guarantees that each position predicts the next word without seeing it, as we saw at the end of Section 1.4.2. The recurrent networks of Section 1.3 had to run through the stretch serially, one position after the other. Graphics cards, built for many simultaneous calculations, execute that calculation well in parallel, and training moved on to trillions of tokens.

Kaplan and collaborators measured, in models from 768 to 1.5 billion parameters without counting the embeddings, how the loss drops with model size, data and compute [64]. In all three cases, the drop is a power law, ℒ∝N−0.076\mathcal{L}\propto N^{-0.076} in the number of parameters, a straight line on a log-log plot. That is, improvement with size was predictable, which gave grounds for betting on even larger models, such as GPT-3 in 2020 with 175 billion parameters [20]; GPT-2, from 2019, had 1.5 billion [92]. The lower loss came with more successes on new tasks, as the authors of GPT-3 showed. The loss has a floor, the entropy of the text itself, which the form of Hoffmann and collaborators includes. But the fit was measured over a range of sizes, and using it for much larger models is an extrapolation. Section 1.9 gives the full laws and the discussion of how to split compute between parameters and data.

1.5 Physical readings

Several pieces of the transformer have the form of objects we know from statistical physics: the output softmax is a canonical ensemble, attention takes a step in an associative memory, and the depth of the network plays the role of time. In this section we use these correspondences to understand the model, always saying where they stop working.

1.5.1 The softmax as a canonical ensemble

Consider the output softmax, (1.9). If we treat each token in the vocabulary as a state of a physical system and minus its logit as the energy of that state, Ei≡−ziE_i\equiv-z_i, it becomes the Boltzmann distribution of a canonical ensemble with VV states, at temperature TT,

pi=e−Ei/TZ(T),p_i=\frac{\mathrm{e}^{-E_i/T}}{Z(T)},
Z(T)=∑i=1Ve−Ei/T,Z(T)=\sum_{i=1}^{V}\mathrm{e}^{-E_i/T},
(1.12)

With this reading, the identities of thermodynamics hold without modification, with kB=1k_B=1:

U=⟨E⟩T=T2∂Tln⁡Z,U=\langle E\rangle_T=T^2\,\partial_T\ln Z,
S=−∑ipiln⁡pi=ln⁡Z+UT,S=-\sum_i p_i\ln p_i=\ln Z+\frac{U}{T},
(1.13)
C≡dUdT=⟨E2⟩T−⟨E⟩T2T2,C\equiv\frac{\mathrm{d}U}{\mathrm{d}T}=\frac{\langle E^2\rangle_T-\langle E\rangle_T^2}{T^2},
C=TdSdT.C=T\,\frac{\mathrm{d}S}{\mathrm{d}T}.
(1.14)

Each of these quantities says something about the draw of the next token. The mean energy UU is minus the mean logit. The entropy SS measures the uncertainty of the draw: it is zero when a single token has probability 1 and ln⁡V\ln V when all are equally probable, and eS\mathrm{e}^{S} is the effective number of tokens in contention, in the same sense as the perplexity of Section 1.2.3. The second line connects fluctuation and response: the variance of the energy measures how much the distribution reacts to a change in temperature. The limits also have a direct reading. When T→0+T\to0^+, the weight concentrates on the token with the largest logit, the ground state, if it is unique; always choosing the most probable token is greedy decoding. If there is a tie among the largest logits, the limit splits the weight among them, and breaking the tie is an additional rule. When T→∞T\to\infty, all tokens become equally probable, and S→ln⁡VS\to\ln V. Note that the logits are defined up to an additive constant, like the zero of energy: adding the same constant to all the EiE_i multiplies ZZ by a factor and leaves the probabilities unchanged.

Temperature with two scores

With scores (ln⁡3,0)(\ln 3,\,0), the probability of the first alternative is p1=31/T/(31/T+1)p_1=3^{1/T}/(3^{1/T}+1):

TT p1p_1 p2p_2
1/21/2 0.9000.900 0.1000.100
11 0.7500.750 0.2500.250
22 0.6340.634 0.3660.366

We see that the same table of logits generates different distributions. Training determines the logits, and the temperature changes only the distribution used in the draw.

Limits of the analogy

The temperature of the softmax is a sampling parameter chosen by whoever uses the model. Nothing in the system corresponds to a heat bath or to a dynamics leading to equilibrium, and the “energies” change at every token, because they depend on the whole preceding context. The heat capacity C(T)C(T) measures the sensitivity of the distribution to TT, and it is a useful diagnostic with no thermodynamic process behind it.

Zipf’s law and criticalityfurther reading

Zipf’s law describes the frequency of words in a text. We order the words from the most frequent to the least frequent and call rank the position of each one in the list. In texts of many languages, the frequency of the word of rank ii falls roughly as 1/i1/i: the second most common word appears about half as often as the first, the third, about a third as often, and so on. Consider what happens to an ensemble whose probabilities follow a law of this kind. Suppose that the logit of the token of rank ii is zi=−sln⁡iz_i=-s\ln i, with s>0s>0, that is, that the energy grows with the logarithm of the rank, Ei=sln⁡iE_i=s\ln i, for i=1,…,Vi=1,\dots,V. The Boltzmann distribution is then pi∝i−s/Tp_i\propto i^{-s/T}, a Zipf law with exponent s/Ts/T. For V→∞V\to\infty, the partition function is the Riemann zeta function,

Z(T)=∑i≥1i−s/T=ζ(s/T),Z(T)=\sum_{i\ge1} i^{-s/T}=\zeta(s/T),
(1.15)

finite for T<sT<s and divergent for T≥sT\ge s. We can understand why by counting states, as in the microcanonical ensemble. The energy Ei=sln⁡iE_i=s\ln i lies below EE for i<eE/si<\mathrm{e}^{E/s}, so there are eE/s\mathrm{e}^{E/s} states with energy below EE, and the entropy of the spectrum is S(E)=E/sS(E)=E/s, a straight line. The microcanonical temperature, (dS/dE)−1=s(\mathrm{d}S/\mathrm{d}E)^{-1}=s, is the same at all energies. At the temperature Tc=sT_c=s, the Boltzmann factor, e−E/T\mathrm{e}^{-E/T}, falls exactly as fast as the number of states grows. Below it the Boltzmann factor wins, and the ensemble concentrates on the first tokens; above it, the number of states wins, and the probability escapes into the tail, limited only by the size of the vocabulary. Mora and Bialek discuss this equivalence between Zipf’s law and criticality in biological systems [82].

With finite VV, nothing diverges, and the transition becomes a rounded peak in the heat capacity C(T)C(T). This peak approaches TcT_c and becomes higher as VV grows, the finite-size signature familiar from any course on critical phenomena:

VV TpeakT_{\text{peak}} CmaxC_{\max}
10310^3 0.920.92 6.06.0
10410^4 1.011.01 9.49.4
5025750\,257 1.051.05 12.312.3
10510^5 1.071.07 13.613.6
10610^6 1.101.10 18.718.7

(s=1.2s=1.2)

Figure 1.5 shows S(T)S(T) and C(T)C(T) for V=50257V=50\,257, the size of the GPT-2 vocabulary. But the spectrum is illustrative: real logits depend on the context and do not follow an exact power law. The optional exercise in Section 1.10 asks for the same calculation with the logits of GPT-2.

Illustrative Zipf spectrum, $E_i=1.2\ln i$, with $V=50\,257$. The peak of $C(T)$ at $T\approx1.05$ is the finite-size version of the transition at $T_c=s=1.2$.

Figure 1.5. Illustrative Zipf spectrum, Ei=1.2ln⁡iE_i=1.2\ln i, with V=50257V=50\,257. The peak of C(T)C(T) at T≈1.05T\approx1.05 is the finite-size version of the transition at Tc=s=1.2T_c=s=1.2.

Explore

Temperature changes the choice

Fix the logits and vary only the temperature. For the two logits (ln 3, 0), the distribution at T = 1 is (3/4, 1/4). The formal energies are Eᵢ = −zᵢ.

Before touching anything: in which direction do the entropy and the probability of the most probable token change when T increases?

The controls work when the file is opened in a browser such as Safari or Chrome. The values below are for the starting position.

Entropy S (nats)0.5623
Mean energy U-0.8240
Response C = Var(E)/T²0.2263
What the analogy allows us to conclude

With fixed logits, the canonical identities are exact: the entropy grows with T, and C is nonnegative. Raising T adds neither knowledge nor evidence. In a real conversation, each token changes the prefix and produces other logits; this family of distributions therefore describes a single generation step.

Local calculation of a finite distribution. It does not run a language model.

1.5.3 Attention as associative memoryfurther reading

An associative memory retrieves a stored pattern from an incomplete or corrupted version of it, as when we recognize a piece of music from a few notes. In 1982 Hopfield proposed a physical model of this kind [56]: a network of NN binary neurons, variables si=±1s_i=\pm1 coupled in pairs like spins in an Ising model. To store patterns xμ∈{±1}Nx^\mu\in\{\pm1\}^N, with μ=1,…,M\mu=1,\dots,M, the couplings are chosen by Hebb’s rule, and the energy is

E(s)=−12∑i,jJijsisj,E(s)=-\frac12\sum_{i,j}J_{ij}\,s_is_j,
Jij=1N∑μ=1Mxiμxjμ.J_{ij}=\frac1N\sum_{\mu=1}^{M}x^\mu_i\,x^\mu_j .

With few patterns, each of them is a minimum of the energy. A pattern is retrieved when the dynamics, starting from a corrupted version of it, goes down to that minimum. For random patterns, the capacity, the number of patterns the network can store and retrieve, is about 0.140.14 patterns per neuron [5].

Krotov and Hopfield showed that higher-order interactions greatly increase this capacity [71], and Ramsauer and collaborators arrived at a continuous version with capacity exponential in the dimension [94]. In this version, the patterns are vectors x1,…,xM∈ℝdx_1,\dots,x_M\in\mathbb{R}^d, stored in the columns of a matrix XX, the state of the network is a vector ξ∈ℝd\xi\in\mathbb{R}^d, and the energy is

E(ξ)=−1βln⁡∑μ=1Meβxμ⋅ξ+12ξ⋅ξ+const.E(\xi)=-\frac{1}{\beta}\ln\sum_{\mu=1}^{M}\mathrm{e}^{\beta\,x_\mu\cdot\xi}+\frac12\,\xi\cdot\xi+\text{const}.
E(ξ)=−1βln⁡∑μ=1Meβxμ⋅ξ+12ξ⋅ξ+const.\begin{aligned}E(\xi) & {}=-\frac{1}{\beta}\ln\sum_{\mu=1}^{M}\mathrm{e}^{\beta\,x_\mu\cdot\xi}\\ &\qquad {}+\frac12\,\xi\cdot\xi +\text{const}.\end{aligned}
(1.16)

The first term is a smooth version of −max⁡μxμ⋅ξ-\max_\mu x_\mu\cdot\xi, to which it tends when β→∞\beta\to\infty, and it becomes more negative the more ξ\xi aligns with some pattern. The second term keeps ξ\xi from growing without bound. The gradient is ∇E=ξ−∑μwμxμ\nabla E=\xi-\sum_\mu w_\mu x_\mu, with w=softmax⁡(βX⊤ξ)w=\operatorname{softmax}(\beta X^{\top}\xi), and the update rule

ξ′=Xsoftmax⁡(βX⊤ξ)=ξ−∇E(ξ)\xi'=X\,\operatorname{softmax}\!\left(\beta X^{\top}\xi\right)=\xi-\nabla E(\xi)
ξ′=Xsoftmax⁡(βX⊤ξ)=ξ−∇E(ξ)\begin{aligned}\xi' & {}=X\,\operatorname{softmax}\!\left(\beta X^{\top}\xi\right)\\ & {}=\xi-\nabla E(\xi)\end{aligned}
(1.17)

is exactly the attention of (1.6) for a single query ξ\xi, which can use all the patterns, with keys and values equal to the patterns and β\beta in place of 1/dk1/\sqrt{d_k}: the weights are the softmax of the scalar products between the query and the patterns, and the new state is the weighted average of the patterns. That is, under these conditions, an attention operation takes one descent step in an energy whose minima are the memories. Hopfield shared the 2024 Nobel Prize in Physics with Hinton, and the committee’s scientific background document is a good introductory reading [85].

The energy goes down at every step

We now show that the update (1.17) never increases the energy. Write E=f−gE=f-g, with f(ξ)=12‖ξ‖2f(\xi)=\tfrac12\lVert \xi\rVert^2 and

g(ξ)=β−1ln⁡∑μeβxμ⋅ξ.g(\xi)=\beta^{-1}\ln\sum_\mu\mathrm{e}^{\beta x_\mu\cdot\xi}.

The function gg is convex, because it is the logarithm of a sum of exponentials of linear functions of ξ\xi, and its gradient is the weighted average of the patterns, ∇g(ξ)=ξ′\nabla g(\xi)=\xi'. A convex function always lies above its linear approximation, and so g(ξ′)≥g(ξ)+ξ′⋅(ξ′−ξ)g(\xi')\ge g(\xi)+\xi'\cdot(\xi'-\xi). Therefore

E(ξ′)−E(ξ)≤12‖ξ′‖2−12‖ξ‖2−ξ′⋅(ξ′−ξ)=−12‖ξ′−ξ‖2.E(\xi')-E(\xi)\le\tfrac12\lVert \xi'\rVert^2-\tfrac12\lVert \xi\rVert^2-\xi'\cdot(\xi'-\xi)=-\tfrac12\lVert \xi'-\xi\rVert^2 .
E(ξ′)−E(ξ)≤12‖ξ′‖2−12‖ξ‖2−ξ′⋅(ξ′−ξ)=−12‖ξ′−ξ‖2.\begin{aligned} & E(\xi')-E(\xi)\\ &\quad {}\le\tfrac12\lVert \xi'\rVert^2 -\tfrac12\lVert \xi\rVert^2\\ &\qquad {}-\xi'\cdot(\xi'-\xi)\\ &\quad {}=-\tfrac12\lVert \xi'-\xi\rVert^2 .\end{aligned}
(1.18)

The energy drops at every update and only stops dropping at the fixed points. This is the argument of the concave-convex procedure [121].

Two stored patterns

With x1=(1,0)x_1=(1,0), x2=(0,1)x_2=(0,1), initial state ξ=(1,0)\xi=(1,0) and β=ln⁡3\beta=\ln 3, the weights are (34,14)(\tfrac34,\tfrac14) and ξ′=(34,14)\xi'=(\tfrac34,\tfrac14). The energies are E(1,0)≈−0.762E(1,0)\approx-0.762 and E(34,14)≈−0.852E(\tfrac34,\tfrac14)\approx-0.852, and the drop, −0.090-0.090, lies below −12‖ξ′−ξ‖2=−0.0625-\tfrac12\lVert \xi'-\xi\rVert^2=-0.0625, as inequality (1.18) requires. Iterating, the state goes through (0.634,0.366)(0.634,\,0.366) and (0.573,0.427)(0.573,\,0.427) and converges to the symmetric mixture (12,12)(\tfrac12,\tfrac12): the memory is not retrieved.

An exact calculation shows why. With ξ=(12+δ,12−δ)\xi=(\tfrac12+\delta,\tfrac12-\delta), the update gives δ′=12tanh⁡(βδ)\delta'=\tfrac12\tanh(\beta\delta), which, for m=2δm=2\delta, is the Curie–Weiss equation of the mean-field Ising model, m=tanh⁡(βm/2)m=\tanh(\beta m/2). Near the mixture, δ′≈βδ/2\delta'\approx\beta\delta/2. The mixture attracts for β<2\beta<2; for β>2\beta>2 it becomes unstable and two fixed points appear close to the memories, and β=4\beta=4 leads to (0.979,0.021)(0.979,\,0.021). That is, retrieval is a spontaneous symmetry breaking controlled by β\beta.

Validity of the correspondence

The descent of the energy holds for the update (1.17): fixed patterns, values equal to the keys, all in the same space. A trained transformer has distinct projections WQ,WK,WVW_Q,W_K,W_V, several heads, FF networks, normalization and residual connections. The result says nothing about a global energy going down along the full model; the correspondence is exact only for an isolated attention operation, under the conditions above.

1.5.4 Other physical readingsfurther reading

The Potts model

In a Potts model, each site of a lattice takes one of several colors, and the energy is a sum of terms that depend on the pairs of sites and their colors; the Ising model is the case of two colors. Rende, Gerace, Laio and Goldt take the sites to be the positions in the text and the colors to be the tokens [95]. They study a simplified version of attention, called factored attention, in which the weights depend only on the positions and the values only on the tokens, and show that it learns the conditional distributions of a generalized Potts model, that is, the probability of the color of a site given the colors of the others. Training this layer is exactly equivalent to solving the inverse Potts problem, which is inferring the couplings from samples, by the pseudo-likelihood method, which fits these conditional probabilities. The correspondence makes it possible to compute with the replica method the generalization error, which is the error on data the model did not see in training.

Interacting particles on the sphere

The dynamical reading of Section 1.4.5 treats depth as time. Geshkovski, Letrouit, Polyanskiy and Rigollet take this idea to the limit of continuous time in a simplified model [45]. In it, the vectors of the nn positions, x1,…,xnx_1,\dots,x_n, lie on the unit sphere Sd−1S^{d-1}, the query, key and value matrices are the identity, and there is no FF. The sphere comes from the normalization of Section 1.4.5: without the learned scale and shift, and neglecting the small number added to σ\sigma, it produces vectors of fixed norm, and a change of scale makes that norm equal to 1. In a real transformer, only the inputs of each stage are normalized, and the residual stream does not lie on a sphere. The dynamics is

ẋi=𝑷xi⟂(1Zi∑j=1neβxi⋅xjxj),\dot x_i=\mathbf{P}^{\perp}_{x_i}\!\left(\frac{1}{Z_i}\sum_{j=1}^{n}\mathrm{e}^{\beta\,x_i\cdot x_j}\,x_j\right),
xi∈Sd−1,x_i\in S^{d-1},
(1.19)

where ZiZ_i is the sum of the weights, which normalizes them, and 𝑷x⟂\mathbf{P}^{\perp}_{x} projects onto the plane tangent to the sphere at xx, which keeps each vector on it. Each vector moves in the direction of a weighted average of the others, with Boltzmann weights eβxi⋅xj\mathrm{e}^{\beta\,x_i\cdot x_j}, larger for the vectors that are already close. That is, the tokens are particles that attract each other. The authors show that, in several regimes, they cluster at long times, passing through metastable states, in a phenomenon related to synchronization in the Kuramoto model. The simplification is strong, with the same parameters in all layers and no FF. But it makes it possible to formulate precisely a concrete question: why the representations of different tokens tend to align in deep networks.

Superposition and high-dimensional geometry

A model needs to distinguish many features of the text, such as “this passage is code”, “this word is a proper name” or “the sentence is in the past tense”. If each feature occupied a direction of its own, orthogonal to the others, at most dd of them would fit in ℝd\mathbb{R}^d. But if we accept nearly orthogonal directions, with |cos⁡|≤ε|\cos|\le\varepsilon between any two, of the order of ecε2d\mathrm{e}^{c\,\varepsilon^2 d} of them fit, where cc is a constant, a number that grows exponentially with the dimension. Indeed, two vectors drawn at random in ℝd\mathbb{R}^d have a cosine of order 1/d1/\sqrt d, which for d=768d=768 is about 0.040.04. Models exploit this slack to represent more features than dimensions, with nearly orthogonal directions and a little interference between them [38]. This works well when each feature appears rarely, because then few are present at the same time and the interference stays small. This form of representation is called superposition.

Superposition has a direct consequence for anyone trying to interpret a model. A neuron, that is, one of the 4d4d components computed in the middle of the FF network of Section 1.4.5, usually responds to several unrelated features. This is why the analysis looks for directions in the space of internal vectors, which can combine many components. The attribution graphs of Lindsey and collaborators follow this line and show, for a given answer, which internal features contributed to it and through which paths, in a production model [77].

1.6 From model to assistant

The model that comes out of the training of Section 1.2.3 is called pretrained, and it only continues texts. If we write a question, it may continue with another question, as in a problem set, because that is often what comes after a question in the texts of the corpus. To answer questions and follow instructions, it goes through two more stages [89]. In the first, supervised fine-tuning, training continues, with the same loss (1.2), on examples of dialogues written by people, with questions and good answers. In the second, preference optimization, people compare pairs of answers from the model to the same question and indicate the better one. With these comparisons we train a reward model, another network, which assigns to each question xx and answer yy a reward r(x,y)r(x,y), higher for the answers people prefer. The usual rule, due to Bradley and Terry, assumes that the probability that a person prefers answer y1y_1 to answer y2y_2 is σ(r1−r2)=1/(1+e−(r1−r2))\sigma(r_1-r_2)=1/\big(1+\mathrm{e}^{-(r_1-r_2)}\big), with rk=r(x,yk)r_k=r(x,y_k), and fits the reward network so that these probabilities reproduce the observed choices. Finally, we fit the model to earn reward without drifting too far from the starting model.

This last stage uses the language of reinforcement learning, the field that studies how to adjust a system that makes decisions on the basis of rewards. The model’s distribution of answers, π(y∣x)\pi(y\mid x), is the probability that it gives answer yy to question xx, computed by the chain rule (1.1) with the tokens of the answer, and it is called the policy. The starting model is πref\pi_{\text{ref}}. In the usual form, for each question xx, we maximize

J[π]=∑yπ(y∣x)r(x,y)−βDKL(π(⋅∣x)‖πref(⋅∣x)).J[\pi]=\sum_y\pi(y\mid x)\,r(x,y)-\beta\,D_{\mathrm{KL}}\big(\pi(\cdot\mid x)\,\Vert\,\pi_{\text{ref}}(\cdot\mid x)\big).
J[π]=∑yπ(y∣x)r(x,y)−βDKL(π(⋅∣x)‖πref(⋅∣x)).\begin{aligned}J[\pi] & {}=\sum_y\pi(y\mid x)\,r(x,y)\\ &\qquad {}-\beta\,D_{\mathrm{KL}}\big(\pi(\cdot\mid x)\,\Vert\,\pi_{\text{ref}}(\cdot\mid x)\big).\end{aligned}
(1.20)

The first term is the average reward. The second penalizes drifting from the starting model, with a weight β\beta chosen by whoever does the training, and it keeps the model from learning to produce strange texts that please only the reward model. This procedure is RLHF, reinforcement learning from human feedback.

Two answers and one preference

In the next subsection we show that the maximum of (1.20) multiplies the probability of each answer by er/β\mathrm{e}^{r/\beta} and renormalizes. Suppose two answers that are initially equally probable, with reward difference r1−r2=βln⁡3r_1-r_2=\beta\ln3. The ratio between the probabilities becomes e(r1−r2)/β=3\mathrm{e}^{(r_1-r_2)/\beta}=3, and the probabilities, (3/4,1/4)(3/4,1/4). Preferring an answer changes its frequency, without showing that it is true. In this section β\beta is the weight of the penalty and plays the role of a temperature; for the associative memory we used β\beta as an inverse temperature. These are different conventions, made explicit in each model.

The solution is a Gibbs distribution

The maximum of (1.20) can be obtained in closed form. Consider the distribution

π*(y∣x)=πref(y∣x)er(x,y)/βZ(x),\pi^*(y\mid x)=\frac{\pi_{\text{ref}}(y\mid x)\,\mathrm{e}^{r(x,y)/\beta}}{Z(x)},
Z(x)=∑yπref(y∣x)er(x,y)/β.Z(x)=\sum_y\pi_{\text{ref}}(y\mid x)\,\mathrm{e}^{r(x,y)/\beta}.
(1.21)

which is the starting model reweighted by the factor er/β\mathrm{e}^{r/\beta} and normalized by Z(x)Z(x). Omitting the dependence on xx and using ln⁡π*=ln⁡πref+r/β−ln⁡Z\ln\pi^*=\ln\pi_{\text{ref}}+r/\beta-\ln Z, the divergence between any policy and π*\pi^* is

DKL(π‖π*)=∑yπln⁡ππ*=DKL(π‖πref)−1β∑yπr+ln⁡Z,D_{\mathrm{KL}}(\pi\,\Vert\,\pi^*)=\sum_y\pi\ln\frac{\pi}{\pi^*}=D_{\mathrm{KL}}(\pi\,\Vert\,\pi_{\text{ref}})-\frac1\beta\sum_y\pi\,r+\ln Z,
DKL(π‖π*)=∑yπln⁡ππ*=DKL(π‖πref)−1β∑yπr+ln⁡Z,\begin{aligned}D_{\mathrm{KL}}(\pi\,\Vert\,\pi^*) & {}=\sum_y\pi\ln\frac{\pi}{\pi^*}\\ & {}=D_{\mathrm{KL}}(\pi\,\Vert\,\pi_{\text{ref}})\\ &\qquad {}-\frac1\beta\sum_y\pi\,r +\ln Z,\end{aligned}

and multiplying by −β-\beta and rearranging we obtain

J[π]=βln⁡Z(x)−βDKL(π‖π*),J[\pi]=\beta\ln Z(x)-\beta\,D_{\mathrm{KL}}\big(\pi\,\Vert\,\pi^*\big),
(1.22)

Since DKL≥0D_{\mathrm{KL}}\ge0, the maximum of JJ is βln⁡Z\beta\ln Z, attained at π=π*\pi=\pi^*. This is the Gibbs variational principle: −J-J plays the role of a free energy, β\beta that of a temperature, and the optimal assistant is the starting model reweighted by a Boltzmann factor of the reward. Rafailov and collaborators inverted the relation, writing the reward in terms of the policy itself, r=βln⁡(π*/πref)+βln⁡Zr=\beta\ln(\pi^*/\pi_{\text{ref}})+\beta\ln Z [93]. Only the difference of rewards enters the Bradley–Terry rule, and in it the term βln⁡Z\beta\ln Z, which is the same for the two answers, cancels. Omitting xx,

r1−r2=βln⁡π*(y1)πref(y1)−βln⁡π*(y2)πref(y2).r_1-r_2=\beta\ln\frac{\pi^*(y_1)}{\pi_{\text{ref}}(y_1)}-\beta\ln\frac{\pi^*(y_2)}{\pi_{\text{ref}}(y_2)} .
r1−r2=βln⁡π*(y1)πref(y1)−βln⁡π*(y2)πref(y2).\begin{aligned}r_1-r_2 & {}=\beta\ln\frac{\pi^*(y_1)}{\pi_{\text{ref}}(y_1)}\\ &\qquad {}-\beta\ln\frac{\pi^*(y_2)}{\pi_{\text{ref}}(y_2)} .\end{aligned}

The preference probability, σ(r1−r2)\sigma(r_1-r_2), then depends only on the policy. So the preference pairs can be used to fit the policy directly, choosing it so that these probabilities reproduce the observed choices, without training a reward model. This is the DPO method, for direct preference optimization.

Sycophancy

With this formula we can see where a known defect comes from, sycophancy, the tendency to agree with the user. If the people who compare answers prefer, on average, those that agree with them, the reward rr incorporates this preference, and the factor er/β\mathrm{e}^{r/\beta} increases the weight of agreeing answers. Sharma and collaborators measure this effect in five commercial assistants: they change a correct answer when the user disagrees, praise arguments according to the stated opinion of the person asking and, in human preference data, well-written sycophantic answers sometimes beat correct ones [107]. For anyone who asks the model to check a calculation, the practical consequence is that its agreement is worth little as evidence.

Reasoning models

A recent class of models writes an intermediate text before the final answer, the chain of reasoning, with attempts, checks and corrections, like a draft. For this they go through one more stage of training, reinforcement learning with verifiable rewards. The model tries to solve problems whose answer can be checked automatically, such as calculations with a known result or programs that have to pass tests, and the attempts that succeed are reinforced, that is, the parameters are adjusted to make them more probable. In the DeepSeek-R1-Zero experiment, this reinforcement applied directly to the pretrained model made long chains of reasoning appear, with self-verification and revision of steps [34], [35]; DeepSeek-R1 uses additional fine-tuning stages. Spending more computation on the chain of reasoning improves performance in mathematics and programming. But the intermediate text is a generation like any other. Chen and collaborators inserted hints into the problems, such as the answer supposedly suggested by a professor, and found that reasoning models changed their answer because of them, and that most of the time the visible chain did not mention the hint [26]. The visible chain helps to find errors and says little about the internal calculation that produced the answer.

1.6.4 Why the model makes things up

We call hallucination a false statement made with the same fluency as a true one, such as a bibliographic reference that does not exist. Kalai, Nachum, Vempala and Zhang separate two causes, one in pretraining and the other in evaluation [63].

Pretraining

The model can generalize when the data contain regularities. An arbitrary association, by contrast, such as a person’s birthday, which follows no pattern, cannot be reconstructed by reasoning from other dates. If it appears only once in the corpus, the model has little basis to distinguish the true date from other equally plausible ones. In the statistical models studied in the paper, rare facts of this kind impose a floor on the error of a pretrained generator that is approximately calibrated, that is, whose probabilities track the frequencies with which it is right. This helps to explain why a plausible reference still has to be opened and checked. The floor holds under the assumptions of the paper and is not a universal error rate for any assistant, especially when it consults sources or can abstain. A coefficient that we can derive from an equation is not an arbitrary fact in this sense, even if it appears only a few times in the corpus; a measured constant, such as the electron mass of Section 1.7.1, is.

The mathematical statement and its reachfurther reading

We now look at the statement in the finite case of Corollary 1 of the paper. Consider a finite set 𝒳\mathcal X of possible statements, divided into valid statements, 𝒱\mathcal V, and errors, ℰ\mathcal E, with 𝒳=𝒱∪ℰ\mathcal X=\mathcal V\cup\mathcal E and the two sets disjoint. The data distribution, pp, produces only valid statements, p(ℰ)=0p(\mathcal E)=0, while the generator, p̂\widehat p, errs with probability err=p̂(ℰ)\mathrm{err}=\widehat p(\mathcal E). To measure whether telling valid statements from errors is hard, the authors define a classification test, “is it valid?” (IIV), which receives, with equal probabilities, a sample from pp or a uniform sample from ℰ\mathcal E. The generator itself can be used as a classifier: it declares a statement xx valid when it assigns it probability p̂(x)>1/|ℰ|\widehat p(x)>1/|\mathcal E|, and erriiv\mathrm{err}_{\mathrm{iiv}} is the fraction of wrong answers of this classifier on the test. Defining

A={x:p̂(x)>1/|ℰ|},A=\{x:\widehat p(x)>1/|\mathcal E|\},
δ=|p̂(A)−p(A)|,\delta=|\widehat p(A)-p(A)|,

the bound is

err≥2erriiv−|𝒱||ℰ|−δ.\mathrm{err}\ge 2\,\mathrm{err}_{\mathrm{iiv}}- \frac{|\mathcal V|}{|\mathcal E|}-\delta.
(1.23)

That is, if classifying is hard, generating without errors is too: the generation error is at least twice the classification error, minus two terms, which are small when the possible errors far outnumber the valid statements and when the model assigns to the set AA a mass close to the one the data assign. Here δ\delta compares these two masses; it is not the generic difference between stated confidence and frequency of correct answers. The IIV error is measured on the mixture defined above, and not on an arbitrary list of questions. For arbitrary facts, the paper also uses the Good–Turing argument: in a sample, the fraction of items seen only once estimates the total probability of the items that did not appear, the so-called unobserved mass. Under the specific assumptions of arbitrary facts and calibration made in the paper, the corresponding bound says that the error of the pretrained model lies, approximately, above the fraction of facts that appear only once in the corpus. It does not allow one to transfer this percentage directly to any later evaluation of the assistant.

Evaluation

After training, models are compared on tests that give 1 point for a correct answer and 0 both for an error and for “I don’t know”. Under these conditions guessing is always optimal: with probability p>0p>0 of being right, a guess earns pp points on average, and “I don’t know” earns zero. The authors propose announcing a confidence threshold tt and subtracting t/(1−t)t/(1-t) points per wrong answer. With probability of being right pp, the expected gain from answering is

p−(1−p)t1−t,p-(1-p)\frac{t}{1-t},
(1.24)

positive only for p>tp>t. With t=3/4t=3/4, for example, each error costs 3 points, and it is only worth answering with more than a 75% chance of being right. A well-calibrated model answers when it knows and abstains when it does not, and the evaluation comes to reward this behavior.

1.7 From assistant to agent

1.7.1 What the model knows, and where

At each generation, an assistant receives a text that goes far beyond our last message: the system instructions, written by whoever offers the service and usually invisible to the user, the history of the conversation, the attached files, the results of tools. All this text is the context, and it has to fit in the context window of Section 1.2.1. When we say that an assistant “knows” something, we may be talking about four different places, and many of the confusions come from mixing them up.

What it is When it changes
Parameters regularities fitted in training only with new training
Context what is in the current conversation: request, history, attached files, results with every message
Memory notes kept between sessions counts when it is retrieved and placed in the context
Tools search, code execution, reading and writing files the result goes back into the context

Attaching a paper to a conversation changes the context, and the parameters stay the same. Asking the assistant to “remember” something the following week depends on external memory, and the information only influences an answer again when it is retrieved and placed in the context. But even inside the context the information can be badly used: Liu and collaborators showed that models make worse use of what is in the middle of long contexts, even when it fits in the window [78].

Consider three situations. In the first, the assistant forgot the metric (+,−,−,−)(+,-,-,-) agreed on the week before. The preference needed to have been written to a memory and retrieved today; without both, the model falls back on the convention most frequent in training. In the second, the PDF is in the project folder and the answer cites the wrong equation. We need to ask whether the application found the document, whether it selected the right passage and whether that passage entered the current stage; a file can be in the folder without being in the context. In the third, the electron mass came from the parameters, that is, from what the model kept from training, and what remains from training is approximate. A constant with six digits is an arbitrary fact in the sense of Section 1.6.4, so we check it against CODATA, the internationally recommended table of fundamental constants.

1.7.2 Tool and agent

On its own, the model only writes text. When the question asks for a calculation, the digits of the answer are tokens drawn one by one, like the words, from the parameters and the context. A calculation written this way often comes out right. But nothing in the text distinguishes a right calculation from a wrong one, and we only know which is the case by redoing it.

A tool is a program the application runs when the model requests it. The system instructions tell the model which tools exist and in what format to ask for them, for instance a command for the computer paired with the name of the tool. When the generated text contains such a request, the application pauses generation, runs the request on a computer and appends the output to the context. The model is then called again, now with the output in the context, and keeps writing. That is, the model writes the program, and the computer does the calculation. But the output comes back as text, and from then on it weighs on generation like any other passage in the context.

Schick and collaborators showed in 2023 that a model can learn to write these requests on its own, from a few examples of each tool, in the work they called Toolformer [100]. In the opening example of the paper, in the middle of a sentence about 400 passing out of 1400 applicants, the model writes a request to a calculator to divide 400 by 1400, and the result, 0.29, enters the text before “29%”. The paper itself points out the limit of the method: the model does not chain tools, using the output of one as input to another, nor does it use a tool interactively.

An agent is the model repeating this cycle on its own. After each output, it decides the next step, which can be another request or the answer, and the loop ends when it judges the task done. With a tool there is one round trip: the model asks, the computer executes, and the model answers with the output in view. In an agent there is a sequence of round trips with nobody in between, and each step is chosen by the model from the output of the preceding one. The parameters stay the same the whole time; what grows is the context.

1.7.3 A pendulum far from the harmonic regime

For the lesson, I asked an agent, Claude Code with Claude Opus 5.5, the same question in two fresh sessions: what is the period of a simple pendulum released from 170∘170^\circ, with L=g=1L=g=1? At this amplitude the harmonic approximation fails. The exact period is T=4K(k)≃15.326968T=4K(k)\simeq15.326968, with k=sin⁡85∘k=\sin 85^\circ, where K(k)=∫0π/2dφ/1−k2sin⁡2φK(k)=\int_0^{\pi/2}\mathrm{d}\varphi/\sqrt{1-k^2\sin^2\varphi} is the complete elliptic integral of the first kind; it is about 2.44 times the period of small oscillations.

In the first session, I asked the model to answer without running any program. It got the value right, T≈15.327T\approx15.327, and did the calculation in the text itself: the answer displays a table with five iterations of Gauss’s arithmetic-geometric mean, to ten digits. We checked it afterwards with a program, and the table is right. But every digit in it was written token by token, just like the words, and we only know it is right because we redid the calculation.

In the second session, without that restriction, the model wrote a 38-line program that computes the period by three independent methods, the arithmetic-geometric mean, numerical quadrature of the integral and numerical integration of the equation of motion, and asked the application to run it. The three results agree to within 10−1110^{-11}, and the number matches the first session. This time the computer did the calculation: the arithmetic-geometric mean, which in the first session the model wrote line by line, is here a forty-iteration loop executed by the computer. But the program too was written by the model, and it could have an error.

I then asked it to check the program on a case where it knows the answer, and the model made five calls in a row with no message from me in between: it listed the working folder, rewrote the program as a function of the angle, wrote a test, ran the test and ran the 170∘170^\circ case again. The test compares the program against three cases with an exact answer: 10∘10^\circ, via the small-amplitude series, which errs there by about 2×10−132\times10^{-13}; 90∘90^\circ, where T=Γ(1/4)2/πT=\Gamma(1/4)^2/\sqrt\pi; and 150∘150^\circ, where a singular value of the elliptic integral yields another closed-form expression, with Γ(1/3)\Gamma(1/3). It also checks the integration on its own, with a linear restoring force, whose period is 2π2\pi at any amplitude.

In the box below, the lines marked with ⊳\triangleright are our summaries; the rest are verbatim, with cuts marked.

Real session · Claude Opus 5.5 · 04 Nov 2026

Prompt: Check the program on a case where you know the answer.

Action: rewrites the program as a function of the angle and writes a test against three cases with known answers

Output: deviation of each method relative to the exact value

Output: […]

Output: 90° 7.416298709205 -2.7e-15 1.3e-13 -8.4e-13 […]

Output: 150° 11.072252581475 -3.6e-15 -4.4e-14 5.5e-12 […]

Action: answers that the program passed all the cases

The last three columns are the differences between the result of each method and the exact value. It is the cycle of the previous subsection, repeated: the model writes a program, the application runs it, the output returns to the context, and the model decides the next step. I have the full transcripts of both sessions, and running the programs again prints the same numbers.

Conversation, project and agent

We can use the same model at three levels. In a conversation, it sees what we write and paste. In a project, files and instructions that we leave stored enter the context of every conversation, and the model no longer starts from scratch. In an agent, the model has access to tools, programs it can call by writing a request in an agreed format: reading and writing files, running code, searching the internet. The application carries out the request, returns the result to the context, and the model decides the next step based on it.

It is at the third level that I do most of my work with these models. This is how I maintain my research wiki and the lecture notes of my courses. Each of these works is a repository, a folder of files with the history of all versions, and it has an instructions file that the agent reads before starting. Chapter 2 shows this work in detail. The excerpt below comes from a session of this kind, the one that led to the revision of this course.

Real session · Claude Opus 5.5 · 29 Sep 2026

Prompt: […] do a complete review of the course. […]

Action: reads the slides, the notes and the exercise book of the previous version

Action: runs a program that counts markers of my writing in the notes, such as sentence-initial Mas (“But”) and Ou seja (“That is”)

Output: Mas at the start of a sentence: 0

Output: Ou seja: 0

Action: redoes the calculations in the material

Output: Schottky: 0.4168 and 0.4392

Output: Ising: 1.2954 and 3.6719

Action: writes the review and the plan for the new version

In the session, the agent counted two frequent markers of my writing, sentence-initial Mas and Ou seja, and found none in the notes of the previous version, a sign that the text did not sound like me. Then it redid calculations from the material: the position and the height of the maximum of the Schottky heat capacity, from Chapter 4, and the correlation length of the Ising chain of Chapter 2, at the correct value, 1.29541.2954, and at the value produced by an error in setting up the calculation, 3.67193.6719.

1.7.5 The cycle of an agent

In a conversation, the model describes in a single text the method, the result and its interpretation, and we have no way of knowing whether any calculation was actually done. When the application can run code, these three things become separate. The program represents a method, the execution applies it to given numerical values, and the interpretation relates the output to the physical question. A sentence such as “we can evaluate a grid and refine near the maximum” is a plan; the table returned by an execution is an observation. The cycle of an agent (Figure 1.6) alternates proposals from the model and observations of the world [120].

The cycle of an agent: each observation can change the next action, and the work needs a stopping criterion.
  1. Goal and contextDefine the question, the sources and the stopping criterion.
  2. Model proposalChoose the next action.
  3. ApplicationExecute the request: run code, search or read.
  4. ObservationBring the result back into the context.

If something is missing, reassess and choose another action. If the criterion is met, finish.

Figure 1.6. The cycle of an agent: each observation can change the next action, and the work needs a stopping criterion.

To trust what comes out of this cycle we need three precautions. The first is a stopping criterion written before starting, saying what needs to be located, compared and delivered; it prevents both premature stopping and repetition without gain. The second is independent methods: an analytical solution checked by a numerical integration that does not use the formula, and not by a second agent that may repeat the same premise. The third is a record of the execution, with equation, input values, method, tolerances and versions of the files. But reproducing the numbers correctly still does not guarantee that the conclusion is justified, and this is why Chapters 2 and 4 return to this point.

Three questions to take away

We can summarize the chapter in three questions that apply to any answer from an assistant.

  1. Where did this answer come from: the parameters, the context or a tool? The model has at its disposal what is in the parameters, which only record texts prior to the cutoff date, the date of the most recent texts used in training, and what is in the context. What is in the parameters is approximate, and this is why it is worth providing the sources.

  2. Does it depend on an arbitrary fact? References, numbers, years and attributions are arbitrary facts in the sense of Section 1.6.4, and they need to be checked at the source.

  3. Did my question push toward this answer? The model’s agreement has little evidential value (Section 1.6). Asking for the strongest objection to our own position is more informative.

To these three questions we add two practical observations. The same question can receive different answers, because each answer is drawn token by token. When an answer is going to weigh in a decision, we can repeat the question and compare the answers, preferably also with another model. And texts in Portuguese and expressions in LaTeX can take more tokens, which weighs on the cost and on the size of the context.

1.9 Scaling laws and emergencefurther reading

Kaplan and collaborators trained a family of transformers of very different sizes and measured the test loss, the loss (1.2) computed on texts left out of training [64]. Over several orders of magnitude, the loss fell as a power law of the size of the model and of the amount of data,

ℒ(N)≃(NcN)αN,\mathcal{L}(N)\simeq\left(\frac{N_c}{N}\right)^{\alpha_N},
αN≈0.076;\alpha_N\approx0.076;
ℒ(D)≃(DcD)αD,\mathcal{L}(D)\simeq\left(\frac{D_c}{D}\right)^{\alpha_D},
αD≈0.095,\alpha_D\approx0.095,
(1.25)

where NN is the number of parameters, not counting the embedding tables, DD is the number of training tokens, Nc≈8.8×1013N_c\approx8.8\times10^{13} and Dc≈5.4×1013D_c\approx5.4\times10^{13}. The first law holds when there is plenty of data, and the second when the model is large enough. On a log-log scale, both are straight lines. The exponents are small, that is, to halve the loss we need to multiply NN by 21/0.076≈1042^{1/0.076}\approx 10^4.

Hoffmann and collaborators fitted a form with both resources together [54],

ℒ(N,D)=E+ANα+BDβ,\mathcal{L}(N,D)=E+\frac{A}{N^{\alpha}}+\frac{B}{D^{\beta}},
(1.26)

where EE is the loss that remains with an infinite model and infinite data, the entropy of the source of Section 1.2.3, the second term is the price of a finite model, and the third, that of finite data. The authors asked how to divide a fixed computing budget, C=6NDC=6ND, as in (1.11), between parameters and data. Substituting D=C/(6N)D=C/(6N), the loss comes to depend only on NN,

ℒ(N)=E+AN−α+B(6NC)β,\mathcal{L}(N)=E+A\,N^{-\alpha}+B\left(\frac{6N}{C}\right)^{\beta},

and setting the derivative with respect to NN to zero we obtain

Nopt=G(C6)βα+β,N_{\text{opt}}=G\left(\frac{C}{6}\right)^{\frac{\beta}{\alpha+\beta}},
Dopt=G−1(C6)αα+β,D_{\text{opt}}=G^{-1}\left(\frac{C}{6}\right)^{\frac{\alpha}{\alpha+\beta}},
G=(αAβB)1α+β.G=\left(\frac{\alpha A}{\beta B}\right)^{\frac{1}{\alpha+\beta}} .
(1.27)

Parameters and data should grow together, and the Chinchilla model (70 billion parameters, 1.4 trillion tokens) was trained with about 20 tokens per parameter. Besiroglu and collaborators extracted the data points from the figures of the paper and redid the fit (1.26) [17]:

Fit α\alpha β\beta Nopt∝CaN_{\text{opt}}\propto C^{a} D/ND/N at the Chinchilla budget
Hoffmann et al. (parametric fit) 0.340.34 0.280.28 a=0.46a=0.46 ≈59\approx 59
Besiroglu et al. (replication) 0.350.35 0.370.37 a=0.51a=0.51 ≈18\approx 18
Trained Chinchilla model 2020

Swipe the table sideways to see every column.

Hoffmann and collaborators estimated the optimal split by three different methods, and the parametric fit (1.26) is the third. Note that the published fit contradicts the other two methods in the same paper and the model that the authors trained. The replication removes the discrepancy and shows that the original confidence intervals would require more than 600 thousand experiments, against fewer than 500 probably performed. With five free parameters and a few decades of data, the extrapolation deserves the distrust it would get in any fit in physics.

Emergence

Several capabilities seem to appear suddenly when the model passes a certain size, and the comparison with phase transitions is tempting. But Schaeffer, Miranda and Koyejo show that part of these jumps comes from the metric [99]. If the probability of getting each token right grows smoothly with scale and the task requires getting kk tokens in a row right, the exact-match rate is pkp^k: with k=10k=10, going from p=0.80p=0.80 to p=0.95p=0.95 takes the exact match from 0.110.11 to 0.600.60 (Figure 1.7). A discontinuous metric applied to a loss that varies continuously produces an apparent jump. The analogy with critical phenomena suggests research questions, but a curve with an abrupt change of slope is not enough evidence of a transition.

A smooth improvement in per-token accuracy shows up as a jump in the exact match of long answers.

Figure 1.7. A smooth improvement in per-token accuracy shows up as a jump in the exact match of long answers.

An effective theory of deep networks

For those who want to go further, Roberts, Yaida and Hanin build an effective theory of deep networks [96]. They study multilayer perceptrons, networks made only of multiplications by matrices interleaved with nonlinear functions, like the FF of Section 1.4.5, but with many layers in sequence. The object of study is the preactivations, the values each layer computes before applying the nonlinear function, right after the parameters are drawn at random, before training. When the width, the number of components of each layer, goes to infinity, these preactivations form a Gaussian process: for any inputs, their joint distribution is Gaussian, like that of a free field. Finite width introduces interactions, organized in an expansion in powers of the inverse width, whose effective parameter is the ratio between depth and width. The statistics of the preactivations flows from layer to layer as in a renormalization group. The extension of this theory to transformers remains open.

1.10 Optional exercise: the softmax as a canonical ensemble

There are two versions, with and without code, and either fits in an afternoon.

  1. Without code. For scores (ln⁡3,0)(\ln3,0), compute the probabilities and the entropy at T=0.5T=0.5, 11 and 22. Sketch S(T)S(T) and explain the two limits, T→0T\to0 and T→∞T\to\infty.

  2. With code. Use the script in Appendix A to obtain the GPT-2 logits for a prefix and, keeping these logits fixed, vary TT. Compute S(T)S(T), U(T)U(T) and C(T)=Var⁡(E)/T2C(T)=\operatorname{Var}(E)/T^2, with Ei=−ziE_i=-z_i, and compare CC with the numerical derivatives of UU and of SS.

  3. In both versions, explain why the parameter TT is not, automatically, a physical temperature of the full model.

Readings

To start: Vaswani et al. [116]; Kalai et al. [63]; the scientific background of the 2024 Nobel Prize in Physics [85]; Ramsauer et al. [94].

To go further: Shannon [106]; Sennrich et al. [104]; Radford et al. [92]; Brown et al. [20]; Elhage et al. [37], [38]; Olsson et al. [86]; Geshkovski et al. [45]; Rende et al. [95]; Mora and Bialek [82]; Kaplan et al. [64]; Hoffmann et al. [54]; Besiroglu et al. [17]; Schaeffer et al. [99]; Roberts, Yaida and Hanin [96]; Ouyang et al. [89]; Rafailov et al. [93]; Sharma et al. [107]; DeepSeek-AI [34]; Chen et al. [26]; Lindsey et al. [77]; Petrov et al. [90]; Liu et al. [78]; Yao et al. [120].

Exercises for Lesson 1

Exercise 1.1 · Training reproduces frequencies

After Lesson 1; pen and paper

Goal. To see, in a one-line calculation, that maximum likelihood reproduces frequencies and that the truth of the content stays outside the objective function.

Items (a) and (d) redo the calculation we did in class; items (b) and (c) go beyond it.

Statement. In a corpus, the same context appears four times: three times followed by token A and once followed by token B. The model assigns probability pp to A and 1−p1-p to B.

  1. Write the total loss ℒ(p)\mathcal L(p) and find the minimum. Confirm that it is a minimum.

  2. What is the loss per position at the minimum? Compare it with the entropy of the empirical distribution.

  3. Generalize to KK tokens with counts n1,…,nKn_1,\dots,n_K.

  4. Suppose that A completes the sentence with a false statement and B with the true one. What changes in the calculation?

Exercise 1.2 · The softmax as a canonical ensemble

After Lesson 1; with or without code

There are two versions, and either fits in an afternoon. The script with code is in Appendix A of the notes.

  1. Without code. For scores (ln⁡3,0)(\ln3,0), compute the probabilities and the entropy at T=0.5T=0.5, 11 and 22. Sketch S(T)S(T) and explain the limits T→0T\to0 and T→∞T\to\infty.

  2. With code. Obtain the GPT-2 logits for a prefix and, keeping these logits fixed, vary TT. Compute S(T)S(T), U(T)U(T) and C(T)=Var⁡(E)/T2C(T)=\operatorname{Var}(E)/T^2, with Ei=−ziE_i=-z_i, and compare CC with the numerical derivatives of UU and of SS, noting the grid used and the treatment of the edges.

  3. In both versions, explain why the parameter TT is not, automatically, a physical temperature of the full model.

Product: one page of calculations or plots and a paragraph on the reach of the analogy.

Lesson 2 · 90 minutes

AI in research

Question of the lesson

How can AI assistance produce something that stays useful and can be checked by someone else?

By the end, you should be able to

Record a claim with its assumptions and source and choose a check that does not repeat the premise of the original calculation.

Path: how I work → the bespoke application → a second brain → ideas → literature → calculation and code → writing and review. CHSH shows the effect of a leading question; Ising shows how an error can survive the code and the plot.

In this chapter I describe how I use language models in research. The thread is my own work: the application configured to know who I am and how I work, a research wiki written and maintained by models, two ideas that came up in conversations with models and ended up in papers, and a workflow in which several models examine the same problem. Alongside these real cases, we will look at two constructed examples, on the CHSH inequality and on the Ising chain, which show on a small scale where the model goes wrong and how checking catches the error.

The corresponding lesson covers Sections 2.1 to 2.6, without the further-reading subsections, the minimal-wiki cycle (Section 2.3.4) and the round with several models (discussed in Lesson 3); Section 2.7 stays in the optional material and in these notes. The sections marked as further reading collect fine-tuning, controlled studies, public cases and two tables of errors. The optional exercise in Section 2.11 proposes setting up a minimal wiki, and the exercise book asks you to configure your own application.

Reading path

The core is understanding what the application you use puts into the context, phrasing a question and checking a claim by another route. For the examples, probabilities, 2×22\times2 matrices and the Ising model are enough. The Gribov and Weyl cases show real contributions; their technical details can be picked up later. By the end, you should be able to say what your application puts into the context. At home, the exercise book asks you to write its instructions and set up a minimal wiki.

2.1 How I work

Figure 2.1 summarizes my research workflow. At the center is a research wiki, a set of linked text pages, like Wikipedia, but written for my own use. It is fed by the sources: arXiv papers, PDFs, handwritten notes and my library in Zotero, the program in which I keep bibliographic references. Each paper in preparation has its own repository, in the sense of Section 1.7, with two short files: an instructions file, which the model reads before starting, and a status file, which says what stage the work is in. Another repository collects what a model needs to know about me: profile, research areas, publications, notation conventions and writing style. The models work at every stage, and almost always as agents, reading and writing files.

My research workflow. The repository about me enters as context in the wiki and in the projects; the models work at each stage.
  1. SourcesPapers, notes and the Zotero library.
  2. WikiConcepts, references and checkable syntheses.
  3. ProjectQuestion, calculation and text.

Profile, instructions and the status of the work guide the wiki and the project. Results and corrections from the project go back to the wiki.

Figure 2.1. My research workflow. The repository about me enters as context in the wiki and in the projects; the models work at each stage.

The idea that organizes everything is simple. A model that starts each conversation from scratch fills the gaps with what is most frequent in training: textbook conventions, approximate references, the average style of the internet. So everything I write once, in a place the model reads, no longer needs to be guessed.

2.2 The bespoke application

A model that starts from scratch does not know who we are, what we work on or which conventions we use. Yet the assistant we open, such as ChatGPT, Claude, Gemini or Claude Code, is an application built around the model. It assembles the context for each conversation and executes the model’s requests (Section 1.7.2). This section shows how to configure that application so that it knows more about us: what it puts into the context, what it saves across conversations, how it loads written procedures and how the model decides to ask for a tool, a skill or a subagent. All of this leaves the model’s parameters untouched; at the end, we see what changes when we modify them.

Two doors

In Chapter 1 we saw that what an assistant knows can live in four places: parameters, context, memory and tools (Section 1.7.1). The parameters, fixed after training, are the same for every user of a model; they are not the attention weights of Section 1.4.2, which change from one text to another. For this reason everything the application knows about a person enters the context as text, and it enters through two doors.

Through the first door, before our first message, the application puts into the context the instructions of the company providing the service, our own instructions and an index or summary of memory. Through the same door enters the list of available tools and skills, each with a name and a short description. Through the second door enters, during the work, whatever the model asks for: the output of a tool or a connector, the full text of a skill, the report of a subagent. Whatever enters through the first door is always there and takes up space in every conversation. Whatever depends on a request appears only if the model decides to ask for it. The conversation, which we write, sits between the two doors. And some applications append passages retrieved from documents at each question, without a request from the model, as in Section 2.2.12.

For a physicist, the image is an equation of motion solved with different initial conditions for each user. The dynamics, given by the parameters, stay the same, and configuring the application is preparing the initial condition. The analogy has two limits. The context also grows during the conversation, through the second door, as if the system kept receiving information from outside at every step. And the answer is drawn at random (Section 1.1), so the same initial condition does not fix a single trajectory.

About me

I keep a repository with what an assistant needs to know about me. The README, the introductory file in the main folder, says what the repository is for:

research-knowledge-base/README.md

“This folder is structured so that an AI assistant can quickly understand who I am, what I work on, and what I have accomplished — for help with proposals, reports, papers, and academic writing.”

In it are the profile (CV, biography, research statement, writing profile), one page per line of research, the list of publications with abstracts and a file of notation conventions. An excerpt from that file:

knowledge/notation-conventions.md

“Faddeev-Popov operator: Mab=−∂μDμabM^{ab}=-\partial_\mu D^{ab}_\mu.”
“Weyl operator: W(f)=exp⁡(iφ(f))W(f)=\exp(i\varphi(f)), where φ(f)=∫f(x)φ(x)ddx\varphi(f)=\int f(x)\varphi(x)\,d^dx.”
“Pauli-Jordan distribution: Δ(f,g)=⟨0|[φ(f),φ(g)]|0⟩\Delta(f,g)=\langle0|[\varphi(f),\varphi(g)]|0\rangle.”

With this the model no longer has to guess the form of the Faddeev–Popov operator, the normalization of the Weyl operators or the style in which I write. The repository only helps if the model reads it, and what makes that likely is a personal instructions file that the application puts into the context of every conversation. In Claude Code, this file is a CLAUDE.md shared across all sessions [7]. Two lines from mine, on 6 November 2026, show the two doors at work: the instruction always enters, and the notation file enters when the model asks for it.

Global CLAUDE.md

Theory only: derivations and proofs, not data.
Read the notation file before writing equations.

In chat applications, the same role belongs to ChatGPT’s custom instructions and to Claude’s user preferences, which stay in settings and enter every conversation (Table 2.1).

About each project

Each paper in preparation has its own repository and, inside it, an instructions file that the agent reads before starting. The file name depends on the application: Claude Code looks for a CLAUDE.md, and Codex, OpenAI’s coding agent, for an AGENTS.md. In the repository of the Gribov paper, CLAUDE.md is a link to AGENTS.md, so both applications read the same text. An excerpt:

lorentzian-gribov-nopole/AGENTS.md

“Single source of truth for this project. Every AI tool works in THIS directory; do not create tool-specific copies elsewhere.”
“At the end of every session that changes this project, review ESTADO.md before the last commit: fase, versão, próximo passo and produtos.”

The file ESTADO.md (“status”) is a short note with the stage of the work and the next step. The agent updates it at the end of each session, before the last commit, the record of a change in the git history. A dashboard collects the statuses of all projects, and it is there that I see where each piece of work stopped. To these files I add the bibliography of each project, in a BibTeX .bib file with the keys of INSPIRE-HEP, the bibliographic database of high-energy physics, and the instruction to cite only from it.

Memory

Memory is what the application keeps from one conversation to use in the next ones. It is text, like the rest of the context, and works in two halves: someone writes a note, and the application places it back into the context later.

In Claude Code, automatic memory is a folder of notes that the model itself writes, with the file-writing tool, from our corrections and preferences. An index, MEMORY.md, holds one line per note, and the application puts the first 200 lines of that index into the context at the start of every session [7]. When a topic comes up, the model opens the full note. Three of the eleven lines of my index, on 6 November 2026:

MEMORY.md

Fluid prose in conversation [...] — plain flowing paragraphs in chat; no fragments, bold-structure or AI tics
Didactic notes standard [...] — notes for newcomers: no term before its explanation, motivation first, running example [...]
Lecture scripts are board notes [...] cut topics, never steps [...]

Each one summarizes a correction I made in a conversation, and the full note keeps the reason and the date. The other eight lines deal with projects and students and stay out of these notes.

Chat applications do the same differently and show memory in settings (Table 2.1). ChatGPT can use saved memories and past conversations; it shows a summary of memory, which does not necessarily include everything it uses, and allows editing that summary and deleting memories. Claude keeps a summary of memory, visible in settings, since September 2025 for teams and since October 2025 for individual paid plans, and offers incognito chats that stay outside memory. Gemini saves what we ask it to save and has begun to use past conversations [4].

Because memory is text, we can read, edit and delete what the application shows of it. We should do this from time to time, since a wrong note starts steering every conversation. And whatever memory stores goes, like the rest of the context, to the company running the model; the precautions of Section 4.4 apply here as well.

2.2.5 Skills

A skill is a folder with an instructions file, SKILL.md, and sometimes reference texts and programs, which the model loads when the task calls for it. Anthropic launched the format on 16 October 2025 [6]. Loading a skill works on three levels. At the start of each session, the application puts only the name and description of each skill into the context. When the model judges that a skill fits the task, it reads the full SKILL.md, and it opens the other files only when the text instructs it to consult them. In this way dozens of skills occupy little space in the context.

Without instruction, the assistant writes in the style given by training and preference tuning (Section 1.6), an average of what it read and what people preferred. For texts going out under my name, on 18 August 2026 I asked a model to measure my writing. It wrote a program that strips equations, tables and figures from LaTeX and counts sentences, connectives and verb persons across roughly 120 thousand words of my papers, notes and proposals. The result became a skill the assistant loads before drafting for me: sentence length, connectives I use and avoid, first person plural, the way to introduce an equation. In my Portuguese notes, the measurement found first-person plural verbs in 24% of sentences, initial Mas (“But”) in 13.6%, Ou seja (“That is”) in 8.0%, and impersonal -se in 1.3%. The formal connectives that usually replace Mas and Ou seja do not appear once.

One of the rules is my own instruction, later checked on the corpus. On 29 August 2026, reading slides drafted in my voice, I objected to sentences framed as a negation followed by a correction, of the form “it is not X, it is Y”. Before the rule was added, the measurement searched for that pattern in my English texts, the largest corpus. Across 1,660 sentences in four of them, the two-sentence form “It is not X. It is Y.” does not appear once, and the form “not X, but Y” appears in 0.24% of sentences. In the version of 7 September 2026, the skill has a 113-word description, a 2,386-word body and references totaling another 5,819 words plus the measurement script. It describes my style, and the one who checks whether a text written with it sounds like me is me, when reading.

The model decides to load a skill from its description (Section 2.2.6). So a skill with a vague description tends to sit unused or load at the wrong time [8]. To begin, a skill can be a single file with two sentences of description, one on what it does and one on when to use it, and a short procedure: how to review a derivation, how to draft a group report, how to build a problem set.

2.2.6 How the model decides to call

In Section 1.7.2 we saw that a tool is a program the application runs when the model asks for it. It remains to say how the model decides to ask. The decision is the same prediction of the next token. The application writes in the context the list of tools, each with a name, a description and the format of a call. Starting a tool call is one possible continuation of the text. During the tuning that turned it into an assistant, the model learned to choose that continuation when the situation matches the description. Anthropic’s documentation notes that detailed descriptions are by far the single factor weighing most heavily on choosing tools properly [8].

The two pendulum sessions of Lesson 1 show the decision at work. With the sentence “Answer without running any program” in the prompt, the model did the calculation inside the text; without it, it wrote a 38-line program that the computer executed. That is, the decision depends on everything in the context, from tool and skill descriptions to our own words. It was one session of each, so the example illustrates the mechanism without measuring how often it occurs.

The application can also intervene. In Anthropic’s API, the interface through which programs invoke the model, a call parameter lets the model decide, which is the default, or forbids using tools; in some models the same parameter forces a tool call [8]. The model chooses skills and subagents in the same way, by description, and we can always invoke them by name.

2.2.7 Subagents

A subagent is another tool of the same kind. The model writes a request for another model, and the application launches a separate copy of it with a fresh context that receives only that request from the main conversation. The subagent works with its own tools and returns only a report [7]. The main advantage is context budget: the window fills up as an agent reads files and outputs, whereas a subagent can read thirty files and return just the conclusion. Several can run in parallel, like the two that read this chapter before it reached you. Each starts without the main conversation, so without the assumptions it has accumulated, other than those carried in the request.

But a subagent has a cost. It consumes more tokens, so it costs more. The two handoffs also drop detail: the subagent only knows what was in the request, and the main model only sees the summary, with errors written in the same confident tone as correct findings. Deciding to launch one follows the mechanism of Section 2.2.6, and in Claude Code the description of each subagent states when to use it.

While preparing Lesson 1 of this course, on 4 November 2026, we asked a subagent to read the slides, Chapter 1 of these notes and the glossary in the role of a physicist unfamiliar with neural networks. It caught an error in a hand-worked example: with the vector chosen in the example, the energy of “lentamente” came out to 10, while the text said −1-1. Someone reading without knowing what we had already decided found what we were no longer seeing.

I let the model decide on routine work, such as searching and reading. I ask for a subagent when I want an independent reading, or when parts can run in parallel. And I skip it when the task depends on everything we already discussed, or when I want to follow every step, because from a subagent I see only the summary.

Connectors

A connector gives the model access to an external service, such as my Zotero library, an email inbox or a cloud drive. For the model it is one more tool: the request goes out, and the service’s answer enters the context through the second door. We must grant each access with privacy in mind, because whatever the model reads becomes part of the context sent to the company running it.

2.2.9 Fine-tuningfurther reading

Everything we saw so far leaves the parameters as they are. Fine-tuning changes the parameters: training continues on examples of our own, and the model comes to answer differently in every conversation. It was an adjustment of this kind that turned a model that only continues texts into an assistant (Section 1.6).

Adjusting all the parameters of a large model is expensive. LoRA, proposed by Hu and collaborators, freezes the parameters and trains only a low-rank correction in each layer [58]. If WW is a parameter matrix with d×kd\times k entries, such as those in attention, the correction is

W→W+ΔW,W\to W+\Delta W,
ΔW=BA,\Delta W=BA,
(2.1)

where BB has d×rd\times r entries, AA has r×kr\times k, and the rank rr is much smaller than dd and kk. The number of trained parameters drops from dkdk to r(d+k)r(d+k). With d=k=4096d=k=4096 and r=8r=8, that is 6553665\,536 parameters instead of 1677721616\,777\,216, 256 times fewer. In GPT-3, the authors report 10 thousand times fewer trained parameters than in full fine-tuning. In physics terms, it is a low-rank perturbation to the model’s dynamics.

Fine-tuning pays off for a fixed task with many examples, such as a classifier or an output format an institution always uses. It is also the path for open models whose weights can be downloaded. For making a model learn our preferences, it rarely pays off: it needs examples, costs money, and the result is a set of weights we cannot read or edit line by line the way we read and edit memory. And it works poorly for teaching new facts. Gekhman and collaborators showed that examples with facts unknown to the model are learned more slowly and, once learned, increase the model’s tendency to hallucinate [43].

Where each layer livesfurther reading

Table 2.1 shows where each layer sits in the most widely used applications. We checked the table on each company’s help pages and in the Claude Code documentation on 6 November 2026, and the row for Claude skills again on 10 November 2026. Menus change often, and “not checked” marks entries we did not verify.

Table 2.1. Where each layer lives, on 6 November 2026, according to the help pages of OpenAI, Anthropic and Google and the Claude Code documentation [4], [7]; the Claude skills row was rechecked on 10 November 2026.
ChatGPT Claude Gemini Claude Code
Personal instructions Settings, Personalization, Custom Instructions Settings, Your Claude, instructions Settings, Personal context global CLAUDE.md
Memory Settings, Personalization, Memory memory summary, in settings Settings, Personal context MEMORY.md, written by the model
Project instructions Project settings, inside the project project instructions not checked folder CLAUDE.md
Skills not checked Customize, Skills, on all plans not checked skills

Swipe the table sideways to see every column.

2.2.11 Summaries that preserve dependenciesfurther reading

Resuming a long investigation requires summaries, and we need to choose what to keep. A summary serves to resume the work without rereading everything, and for this reason it needs to keep what the conclusion depends on. “The resonance was computed and checked” is a useless summary, because it does not say what was obtained, under which conditions, or where to check. “For a force of fixed amplitude, γ=b/2m\gamma=b/2m and steady state, the amplitude peak is at ω02−2γ2\sqrt{\omega_0^2-2\gamma^2} if γ<ω0/2\gamma<\omega_0/\sqrt2; derivation in note R1” keeps the condition, the result, the source and the way back to the original.

Checking the summary: which resonance frequency? The previous example is only useful if we can redo its calculation and recover its assumptions.

Consider mẍ+bẋ+kx=F0cos⁡(ωt)m\ddot x+b\dot x+kx=F_0\cos(\omega t), with m,k,b>0m,k,b>0 and a force amplitude F0F_0 independent of ω\omega. Define ω02=k/m\omega_0^2=k/m and γ=b/(2m)\gamma=b/(2m). After the transient has decayed, the amplitude of the displacement is

A(ω)=F0/m(ω02−ω2)2+4γ2ω2.A(\omega)=\frac{F_0/m} {\sqrt{(\omega_0^2-\omega^2)^2+4\gamma^2\omega^2}}.

Maximizing the amplitude is equivalent to minimizing the squared denominator, D(ω)D(\omega). Differentiating,

dDdω=4ω(ω2−ω02+2γ2).\frac{dD}{d\omega} =4\omega\bigl(\omega^2-\omega_0^2+2\gamma^2\bigr).

There is a peak at positive frequency at ωpeak=ω02−2γ2\omega_{\mathrm{peak}}=\sqrt{\omega_0^2-2\gamma^2} only if 0<γ<ω0/20<\gamma<\omega_0/\sqrt2. For damping equal to or larger than this threshold, the largest amplitude occurs at ω=0\omega=0, in the static limit. The frequency of the underdamped free oscillation is a different one: ωfree=ω02−γ2\omega_{\mathrm{free}}=\sqrt{\omega_0^2-\gamma^2}, valid for 0<γ<ω00<\gamma<\omega_0. It describes the transient and not the maximum of the forced response in the steady state.

Question to check the reading: if the summary keeps only “the resonance is at ω02−2γ2\sqrt{\omega_0^2-2\gamma^2}”, which conditions were lost? Recover the quantity being maximized, the steady state, the force of fixed amplitude and the range of damping.

2.2.12 Retrieval and RAGfurther reading

A collection of documents can be queried in another way. We split the documents into passages, and a dedicated model turns each passage into a vector, so that texts of similar meaning end up with nearby vectors; it is the idea of the embeddings of Section 1.4.1, applied to whole passages. At question time, the question also becomes a vector, and the passages whose vectors make the smallest angle with it, that is, the largest cosine, are retrieved and placed in the context before the answer. This is retrieval-augmented generation, RAG [72]. A geometric example shows the limit of the criterion. With u=(1,0)u=(1,0), vA=(0.8,0.6)v_A=(0.8,\,0.6) and vB=(0,1)v_B=(0,1), the index ranks A before B, because cos⁡(u,vA)=0.8\cos(u,v_A)=0.8 and cos⁡(u,vB)=0\cos(u,v_B)=0. But the ranking measures similarity and leaves open whether passage A supports the claim we want to make. For this reason each passage should be stored with its location: document, version, section, equation. And even what enters the context can be badly used, because models make worse use of information placed in the middle of long contexts [78].

2.3 A second brain

From Bush to Karpathy

The idea of a personal archive in which one document leads to another comes from Vannevar Bush, who in 1945 imagined the memex, a desk that would store documents linked by trails [24]. Then came versions maintained by hand. Luhmann’s card index, popularized by Ahrens, had tens of thousands of numbered cards, each with one idea and with references to others [2]. Matuschak’s evergreen notes are written to last and rewritten as understanding changes [80]. Forte’s second brain is a system of digital notes organized around projects [42]. In all of them, the work of writing, linking and updating the notes falls on whoever uses them.

In April 2026, Karpathy proposed delegating this maintenance to a language model [65]. The proposal has three layers (Figure 2.2). The first holds the raw sources, which the model reads and does not modify. The second holds the wiki, with pages written and maintained by the model, an index and a log, the chronological record of every change. The third holds a schema, the document that describes the structure of the wiki, the conventions and the routines the model must follow.

The three layers of a wiki maintained by a model and the three operations that update it.
  1. Preserved sourcesOriginal PDFs and notes are not modified.
  2. Wiki pagesOrganize claims, assumptions and links to the sources.
  3. Log and auditQuery, check and record the corrections.

The schema and the instructions guide the synthesis. The audit feeds back into the pages.

Figure 2.2. The three layers of a wiki maintained by a model and the three operations that update it.

My wiki

My research wiki follows this design. It lives in a git repository, that is, in a folder whose version history is kept by the program git, and I read it in Obsidian, a note editor that shows the links between pages. The pages are Markdown files, a simple text format in which, for instance, # marks a heading; in Obsidian, [[name]] links a page to the page name. The public part, with 246 pages in September 2026, goes to a website through an explicit list of what may be published, and notes about people and part of the course material stay out. The pages are divided into research areas, concepts, connections between areas, papers, open questions, projects and courses. A concept page, such as the one on the Bisognano–Wichmann theorem, gives the definition, the role of the concept in my lines of research, the links to other pages and the papers in which it appears. The home page says where the text came from: the pages were written by AI assistants under my supervision, and an authorship page records which models wrote what. We return to that page in Chapter 4.

A manual for assistants, in the main folder of the repository, says how the wiki works: which pages exist, which conventions to follow and that the default mode is read-only, that is, nothing changes unless I ask. Every session begins by reading this manual, the index and the overview page.

Ingest, query, audit

Three operations keep the wiki alive. In ingestion, I point to a source; the model reads it, relates it to what is already in the wiki, writes the pages and records everything in the log. The excerpt below is the actual record of one ingestion, written by the model itself at the end of the session.

Real session · Claude Opus 4.8 · 30 Jun 2026

Action: “Ingested a fresh (29 Jun 2026) nine-author position/open-problems paper […] at the researcher’s request.”

Action: “Framed the paper as a second open-problems agenda […] because two of its four themes land on the group’s home turf.”

Action: “Created the paper page plus one connection page mapping the agenda onto the group’s programs; wired it into the three area pages, the index, and the manifest.”

Action: “No new standalone concept/question pages […] candidate question-page extractions left for the researcher’s call.”

Note two things in this record. The model linked the new paper, by Goto and collaborators (arXiv:2606.30853), to the three area pages it touches, and this linking work is what makes the wiki more useful than a folder of PDFs. And it left to me a decision that was mine to make: which open questions deserved a page of their own. The same day they became 23 question pages.

In a query, I open the session with a fixed request, which is also in the repository:

The request that opens a query session

“Use this repository as the canonical research knowledge base. First read README.md, docs/assistant-playbook.md, wiki/index.md, and wiki/overview.md. For answers, cite relevant wiki pages with [[wikilinks]]. Do not modify the repository unless I explicitly ask you to persist changes.”

The [[wikilinks]] in the request are those links between pages. The answer cites the pages and, through them, the sources, and a good answer becomes a new page. In an audit, the model looks for contradictions, outdated claims, orphan pages, to which no other page points, and missing links. This is the difference with respect to the systems that search for passages in the documents at each question (Section 2.2.12): in the wiki, the synthesis stays written down and keeps being extended and corrected with use.

2.3.4 A complete cycle in a minimal wiki

Constructed example To see the procedure without knowing field theory, we will use two local sources: the derivation of Section 2.6.2 and the independent enumeration of the following section. The files in exemplos/wiki-minima/ contain the three filled-in pages, a page template, instructions and a record of the correction. The query was written for the course, and the two sources are sections of these notes.

1. Excerpt from the analytical source

In a periodic Ising chain at zero field, ⟨s0sr⟩N=(tr+tN−r)/(1+tN)\langle s_0s_r\rangle_N=(t^r+t^{N-r})/(1+t^N), with t=tanh⁡(βJ)t=\tanh(\beta J). The limit N→∞N\to\infty, with rr fixed and T>0T>0, is trt^r.

2. Concept page: correlation in the chain

Claim: the correlation has two terms on the finite ring and one in the infinite limit.

Assumptions: J>0J>0, zero field, equilibrium, periodic boundary conditions; rr fixed when taking the limit.

Sources: derivation page, equation (2.8); enumeration page, case N=12N=12, βJ=0.5\beta J=0.5, r=1r=1.

Check: both methods give 0.462278560.46227856; the numerical agreement refers to this case and to the others explicitly tested.

3. Query and correction

Question: “For 12 spins, can I use exactly tanh⁡(0.5)\tanh(0.5)?”

Checked answer: “No. The finite result is 0.462278560.46227856; the limit is 0.462117160.46211716. The difference is small, but it is not a numerical error.”

Record: “The draft said ‘for any NN’. Replaced by ‘in the limit N→∞N\to\infty with rr fixed’. Added the finite formula and the link to the enumeration.”

The usefulness shows in the product: the question gets an answer with conditions and a path for checking, and the correction remains available for the next query. When you use papers from your own field, replace the local sources by references with version, section and equation.

The files of the minimal wiki

Open each file to read it. The page template and the instructions are plain text you can copy to set up your own study folder.

README.md
Minimal wiki: correlation in the Ising chain

Constructed example for the course. The two sources are local: an analytical derivation from the notes and an independent enumeration. It is neither a real session nor an ingestion of external papers.

Read analytical-source.md, numerical-source.md and correlation.md, in this order. The question and the correction are in log.md. page-template.md can be copied for your own field. Everything can be done without an assistant and without internet.

In the exercise of Lesson 2, replace the two local sources by two papers you know, keeping version, section, equation and limits. There is no need to install Obsidian: any text editor reads the files.

analytical-source.md
Analytical source

Origin: notes of the short course, chapter 2, section “Where the finite-size formula comes from”, equation with label eq:ising-finito in the TeX source.

For H=−J∑i=0N−1sisi+1H=-J\sum_{i=0}^{N-1}s_i s_{i+1}, sN=s0s_N=s_0, J>0J>0, zero field and equilibrium:

⟨s0sr⟩N=tr+tN−r1+tN,\langle s_0s_r\rangle_N=\frac{t^r+t^{N-r}}{1+t^N},
t=tanh⁡(βJ).t=\tanh(\beta J).

It is an exact result for this finite model. For T>0T>0 and fixed rr, the limit N→∞N\to\infty is trt^r. It does not replace the finite expression exactly.

Concept: correlation. Check: numerical source.

numerical-source.md
Numerical source

Origin: codigo/ising_independente.py, function enumerar; record in interno/validacao/ising-independente.json. Paths relative to the main folder of the course.

The enumeration runs over all 212=40962^{12}=4096 configurations with each bond counted once. For N=12N=12, βJ=0.5\beta J=0.5, r=1r=1 and periodic boundary conditions:

⟨s0s1⟩12=0.4622785566.\langle s_0s_1\rangle_{12}=0.4622785566.

The finite formula gives the same number; the infinite limit gives 0.46211715730.4621171573. The enumeration checks all distances for N=6,8,12N=6,8,12 and βJ=0.1,0.5,1\beta J=0.1,\ 0.5,\ 1. This numerical agreement refers to the cases tested, with floating-point error, and it is not a proof for every NN.

Concept: correlation.

correlation.md
Correlation in the Ising chain

Claim: on the finite ring there are contributions from the two paths between the spins; in the infinite limit at fixed distance, trt^r remains.

Assumptions: J>0J>0, zero field, equilibrium, periodic boundary conditions. In the limit, T>0T>0 and fixed rr.

Status: exact finite formula, derived with the transfer matrix; numerical agreement in the cases listed.

Sources: derivation, with its location in the notes; enumeration, with parameters and record.

Useful answer: for 12 spins and βJ=0.5\beta J=0.5, the nearest-neighbor correlation is 0.462278560.46227856. Using tanh⁡(0.5)\tanh(0.5) is an approximation, with a difference of about 1.61×10−41.61\times10^{-4}.

Limit: the page does not deal with an external field, a two-dimensional lattice or time out of equilibrium.

Correction: log.

log.md
Log of the constructed example

Question: “For 12 spins, can I use exactly tanh⁡(0.5)\tanh(0.5)?”

Draft with an intentional error: “The correlation is trt^r for any NN.”

Check: compare the finite expression of the analytical source with the direct enumeration of the numerical source. The term tN−rt^{N-r} and the denominator 1+tN1+t^N do not vanish at N=12N=12.

Correction applied to the page: replace “for any NN” by “in the limit N→∞N\to\infty, with fixed rr and T>0T>0”; add the finite expression and its conditions.

Decision: use the finite formula when the chain has 12 spins and explicitly identify any approximation by the infinite limit.

Provenance: example written for the course on 3 Oct 2026; the values can be checked with the program provided. It does not record a real conversation.

page-template.md
# Concept or result

**Question this page helps to answer:**

**Precise claim:**

**Assumptions and conventions:**

**Source and version:**

**Location:** section, equation, figure or passage.

**Status:** proof, calculation in a model, approximation, numerical evidence, interpretation or open question.

**Check done and result:**

**What the source does not support:**

**Links to other pages:**

**Next action and log of changes:**
AGENTS.md
# Instructions for this example wiki

Read the three pages and the log before answering. Cite the page and the location in the source that support each claim. Separate exact result, limit and numerical test. Do not invent sources or execution results. Do not change the sources. Propose changes to the pages and persist them only when asked. When persisting a correction, describe the change and its justification in the log. Do not add data about people.

The Ising exploration, later in this chapter, redoes the enumeration right on this page and can be used to check the example.

The risk of a wiki written by models

A wiki maintained by a model has a risk of its own: an error that enters a page starts being consulted as fact, by me and by the model itself in later sessions. In June 2026, while writing one week of my course on algebraic quantum field theory, which also lives in the wiki, the model described the paper arXiv:2207.00407 as a study of observers in de Sitter space. But the paper, by Lin, Maldacena, Rozenberg and Shan, deals with supersymmetric extremal black holes. The error stayed three and a half months on a published page, until a September review checked the reference and replaced it with the right paper, by Witten (arXiv:2308.03663). The first text was written by Claude Opus 4.8; the review, by Claude Opus 5.5.

Therefore every claim needs to point to a source or to a calculation, and someone needs to follow those links every now and then. One simple method is to pick claims at random and go back to the PDFs. Git helps in another way: every change is recorded, with the model that made it, and I can see exactly what changed in a page and undo it.

To get started

None of this is needed to get started. A folder of Markdown files, one per concept or paper, an instructions file with the conventions and with what the model may or may not change, git to see what changed, and a free editor such as Obsidian to navigate the links already give the essentials. For physics, I suggest that every concept page have a field for assumptions, with the conditions under which the result holds: a correct result applied outside these conditions becomes an error, as we will see in the CHSH example.

2.4 Ideas

This section tells the story of two research ideas that came out of conversations with models, one mine and the other the model’s, and then shows how the form of the question changes what the model answers.

How to read the two cases

In the Gribov case, the problem is to define a physical restriction after moving from Euclidean space to Minkowski spacetime; the conversation helped formulate a scattering criterion, later developed and tested by the author. In the Weyl case, the problem is to construct observables that violate a Bell inequality; the suggestion was a family of harmonics, whose performance was computed. In both, separate the suggested idea from the proof that supports it.

An old question: Gribov copies in Minkowski space

In a gauge theory, field configurations that differ by a gauge transformation describe the same physics. To integrate over them in the path integral, we choose one representative of each class, that is, we fix the gauge. Gribov showed, in 1978, that the Landau condition, ∂⋅A=0\partial\cdot A=0, does not pick a unique representative: equivalent configurations that also satisfy it remain, the Gribov copies. He proposed restricting the integration to the region in which the Faddeev–Popov operator, M=−∂⋅DM=-\partial\cdot D, whose determinant appears in the integral, is positive [48]. In the same paper he described what the physics of this result would be in Minkowski space, without saying how to formalize it. In Euclidean space the operator is elliptic, like a Laplacian, and positivity gives a clear spectral boundary. But in Minkowski space it becomes a wave operator, hyperbolic, and the positivity criterion stops making sense.

For some years I tried to attack this question, proposed the problem to students and discussed it with collaborators, without progress. What changed was discussing the problem with a language model the way one discusses with a collaborator: proposing paths and discarding the ones that did not work, until arriving at an approach that solves the problem. The criterion is this. A gauge configuration is in the first Gribov region as long as the Faddeev–Popov wave equation has no source-free solution obeying the Feynman boundary condition, the same prescription of positive and negative frequencies that defines the Feynman propagator. For background fields localized in time, this becomes the injectivity of the negative-frequency block of the classical scattering matrix of the ghosts, the fields associated with the Faddeev–Popov operator. For stationary background fields, it becomes a problem of bound states or of threshold resonances. That is, Gribov’s question in Minkowski space becomes a scattering question. The paper was accepted in Physical Review D [50].

The model was Claude Opus 4.7, judging by the date of the drafts: they run from 29 May to 7 June 2026, and Opus 4.7 is the model that appears in my commits until early June. The paper’s statement of use records the participation of the models, and authorship stayed with me, because journals do not accept models as authors. I would list the model as a coauthor. Chapter 4 returns to this question.

An idea that came from the model: odd Weyl harmonics

In the work with Caribé, Roditi and Sorella on the Bell–CHSH inequality in a free scalar field [25], we needed bounded observables, built with Weyl operators, the exponentials W(f)=exp⁡(iφ(f))W(f)=\exp(i\varphi(f)) of the field smeared with a function ff. The observables had to be localized in two complementary wedges of spacetime, causally separated regions like the Rindler wedges. To get close to the quantum limit, each side needs two observables with values ±1\pm1 that behave like spin components along orthogonal axes, and the best case is that they anticommute, like σx\sigma_x and σz\sigma_z. The decisive suggestion came from a model, Claude Opus 4.8: use only odd Weyl harmonics, which give pairs of observables that anticommute exactly in each wedge, and approximate the sign operator by the Fourier series

sgn⁡(cos⁡θ)=4π∑k≥0(−1)k2k+1cos⁡((2k+1)θ),\operatorname{sgn}(\cos\theta)=\frac4\pi\sum_{k\ge0}\frac{(-1)^k}{2k+1}\cos\big((2k+1)\theta\big),
sgn⁡(cos⁡θ)=4π∑k≥0(−1)k2k+1cos⁡((2k+1)θ),\begin{aligned} & \operatorname{sgn}(\cos\theta)\\ &\quad {}=\frac4\pi\sum_{k\ge0}\frac{(-1)^k}{2k+1}\cos\big((2k+1)\theta\big),\end{aligned}
(2.2)

which has only odd harmonics. Near the jumps of the sign function, the partial sums of this series overshoot the correct value, the Gibbs phenomenon. For this reason the approximation uses the normalized Fejér means of the series, averages of the partial sums that remove this overshoot. With six Weyl terms per axis, the Bell–CHSH correlator is already 2.14885, above the classical limit 2. The supremum over the family of finite polynomials is 222\sqrt2, the Tsirelson bound. But no finite member attains it: an example of degree 511 gives 2.80027.

In both cases the model’s contribution was decisive. But the result still required the usual work: proving, checking the calculations and saying precisely what was established. Chapter 4 shows how I came to trust the Gribov criterion.

2.4.3 The form of the question

The form of the question changes the answer, and a constructed dialogue shows this clearly. The topic is the CHSH inequality. Two distant parties measure observables with outcomes ±1\pm1: Alice chooses between AA and A′A', and Bob between BB and B′B'. The CHSH combination is

S=⟨AB⟩+⟨AB′⟩+⟨A′B⟩−⟨A′B′⟩.S=\langle AB\rangle+\langle AB'\rangle+\langle A'B\rangle-\langle A'B'\rangle .

In any local model with hidden variables λ\lambda we have |S|≤2|S|\le2 [30], while quantum mechanics reaches 222\sqrt2, the Tsirelson bound [29]. Constructed example The dialogue we will discuss was written for the course and reproduces common patterns in the answers of assistants. Some questions add content, others lead the answer, and we must evaluate what each answer added before adopting it.

Questions that add content

To the first request, to prove the local bound and the quantum one, the assistant gives the usual argument. Each value of λ\lambda fixes outcomes A,A′,B,B′∈{−1,+1}A,A',B,B'\in\{-1,+1\}, and we can group S(λ)=A(B+B′)+A′(B−B′)S(\lambda)=A(B+B')+A'(B-B'). Since BB and B′B' are ±1\pm1, one of the sums vanishes and the other is ±2\pm2, so |S(λ)|≤2|S(\lambda)|\le2 for each λ\lambda, and the average preserves the bound. It also cites the quantum maximum, 222\sqrt2. The answer needs to make explicit the class of models considered. The most general statement starts from local probabilities,

p(A,B∣a,b)=∫dλρ(λ)p(A∣a,λ)p(B∣b,λ),p(A,B\mid a,b)=\int\mathrm{d}\lambda\,\rho(\lambda)\,p(A\mid a,\lambda)\,p(B\mid b,\lambda),
p(A,B∣a,b)=∫dλρ(λ)p(A∣a,λ)p(B∣b,λ),\begin{aligned} & p(A,B\mid a,b)\\ &\quad {}=\int\mathrm{d}\lambda\,\rho(\lambda)\,p(A\mid a,\lambda)\,p(B\mid b,\lambda),\end{aligned}
(2.3)

with outcomes ±1\pm1 and ρ\rho independent of the settings. Incorporating local random seeds into λ\lambda, we obtain deterministic responses without losing generality within this class. Thus the four values in the proof are a representation of the local model; there is no need to add an independent assumption called “realism” [21]. Using the same distribution for the four pairs of settings is already part of measurement independence. This is a condition that can go unnoticed when we look only at the algebra. For a quantum product state, ⟨A⊗B⟩=⟨A⟩⟨B⟩\langle A\otimes B\rangle=\langle A\rangle\langle B\rangle: the connected correlation vanishes, but the raw correlation can be nonzero.

Asking for another route is also useful: the operator identity

Ŝ2=4I−[Â,Â′][B̂,B̂′],\hat S^2=4\,I-[\hat A,\hat A'][\hat B,\hat B'],
Ŝ=Â(B̂+B̂′)+Â′(B̂−B̂′),\hat S=\hat A(\hat B+\hat B')+\hat A'(\hat B-\hat B'),
(2.4)

valid for Â2=Â′2=B̂2=B̂′2=I\hat A^2=\hat A'^2=\hat B^2=\hat B'^2=I with Alice’s observables commuting with Bob’s, gives ‖Ŝ‖≤22\lVert \hat S\rVert\le2\sqrt2 for any state, and the limiting cases check out: commuting observables give back |S|≤2|S|\le2.

Questions that lead the answer

Now the request presupposes the answer.

Prompt

Construct an explicit counterexample: a local hidden-variable model that violates |S|≤2|S|\le2.

Response

Consider λ\lambda uniform in [0,2π)[0,2\pi) and the response functions A(a,λ)=sgn⁡cos⁡(λ−a)A(a,\lambda)=\operatorname{sgn}\cos(\lambda-a) and B(b,λ,a)=sgn⁡cos⁡(λ−b+π4δa,a1)B(b,\lambda,a)=\operatorname{sgn}\cos(\lambda-b+\tfrac{\pi}{4}\delta_{a,a_1}), where the phase shift in BB encodes the correlation established at the source at the moment of emission. With a1=0a_1=0, a2=π/2a_2=\pi/2, b1=π/4b_1=\pi/4 and b2=3π/4b_2=3\pi/4, the four correlations come out with the favorable sign and we obtain S=4S=4, above both the local and the quantum bounds. The model is local because each outcome is computed from a shared variable defined at the source, with no signal transmitted during the measurement.

The counterexample is impossible, because |S|≤2|S|\le2 is a theorem about local models. The error sits in one symbol, B(b,λ,a)B(b,\lambda,a): Bob’s response depends on Alice’s setting, and the model is nonlocal by construction. The phrase “encodes the correlation established at the source” has the form of a physical explanation, but a correlation established at the source enters through λ\lambda, which is already there. And the given formula does not even produce 4. For responses sgn⁡cos⁡(λ−α)\operatorname{sgn}\cos(\lambda-\alpha) and sgn⁡cos⁡(λ−γ)\operatorname{sgn}\cos(\lambda-\gamma), with λ\lambda uniform, the correlation is 1−2|α−γ|/π1-2|\alpha-\gamma|/\pi. The shift replaces bb by b−π/4b-\pi/4 when a=a1a=a_1, and the four correlations give

S=1⏟(a1,b1)+0⏟(a1,b2)+12⏟(a2,b1)−12⏟(a2,b2)=1.S=\underbrace{1}_{(a_1,b_1)}+\underbrace{0}_{(a_1,b_2)}+\underbrace{\tfrac12}_{(a_2,b_1)}-\underbrace{\tfrac12}_{(a_2,b_2)}=1 .
S=1⏟(a1,b1)+0⏟(a1,b2)+12⏟(a2,b1)−12⏟(a2,b2)=1.\begin{aligned}S & {}=\underbrace{1}_{(a_1,b_1)}+\underbrace{0}_{(a_1,b_2)}+\underbrace{\tfrac12}_{(a_2,b_1)}-\underbrace{\tfrac12}_{(a_2,b_2)}\\ & {}=1 .\end{aligned}

A request for criticism has the same effect.

Prompt

Now act as a skeptical referee and point out the problems with the two derivations above.

Response

I point out three problems. (1) The passage from the inequality for each λ\lambda to the inequality for the averages lacks justification; the convexity argument that licenses this step is missing. (2) The assumption Â2=I\hat A^2=I restricts the result to dichotomic observables and should be declared as a restriction of the result. (3) The claim that the bound holds in any dimension is not proved; the norm inequality requires care in infinite dimension. I recommend major revision.

The three objections come in the same confident tone. The first is invented: the average of a quantity bounded by 2 at each λ\lambda is bounded by 2, by the triangle inequality. The second is legitimate and minor, and the text already addresses it, because the assumption Â2=I\hat A^2=I is stated. The third is false as written, because the norm bound holds for bounded operators in any dimension. It sits close to a hard question, Tsirelson’s problem: whether the correlations obtained with commuting operators can always be approximated by correlations of tensor products, answered in the negative in 2020 [62]. We asked for a skeptical report, and the model produced objections; nothing in the text indicates which of them hold.

The wording of the request changes the context and can favor an answer that accepts the premise. The constructed dialogue illustrates this risk; it neither measures the probability of a refusal nor identifies the internal mechanism of the model. Models can also reject the premise correctly. The practical rule:

Closed question (presupposes the answer) Open question (leaves refusal available)
What is the error? Is there an error? Where?
Construct a counterexample. Is there a counterexample?
Point out the problems. Are there problems? Which ones survive a check?
Justify this result. Does this result hold?

2.5 Literature

Asking a model for literature is useful and risky at the same time. This section collects what I have learned about checking references, recording what I read and separating finding from discovering.

Checking the references

A reference has a fixed structure (authors, title, journal, volume, page, year), and a model learns this form very well. Generating a text with the form of a reference is easy, and that does not guarantee that the work exists [117]. Even when the paper exists, we need to locate in it the argument and its assumptions. Asking “cite only real references” changes what the text asserts, and the model starts to say that the references are real; the mechanism that generates them stays the same. So the verification has to happen outside the model. One rule is to cite a source the model led us to only after opening it; the other is to ask, for each claim, whether it is retrieval (“the authors prove X”) or inference (“X seems to follow from their work”).

Reading records

A record notes, for each source, the identification and the version read (arXiv v1, v2 or published), the exact location of what was used (section, equation, figure), the claim it supports, the limits of that claim and the relation to the research question. A map links each claim in our text to the record that supports it, or to a calculation of our own. When a source changes version, the map shows what needs to be updated.

Finding and discovering

In October 2025, news circulated that a model had solved ten open problems from an online catalog of the problems posed by Paul Erdős. It collapsed within a few days: the model had located papers that already solved them, unknown to the maintainer of the catalog. The systematic study by Feng and collaborators examined 700 problems and solved 13, five with apparently new solutions and eight already published; many were “open by obscurity”, that is, listed as open only because nobody had noticed the published solution [41]. Locating forgotten literature is useful. Presenting it as a discovery is an error of attribution.

Investigating novelty

Before claiming that a result is new, it pays to specify the claim and its assumptions; to search for nearby formalism, including in other notations and in neighboring areas; to compare with known results and limits; and to say what was established and what remains open. A search that finds nothing leaves an open item, and it still does not prove that the result is new.

Public casesfurther reading

In a paper on the limits of black-box amplification in the class QMA, the quantum version of the class NP, Aaronson reports a suggestion from GPT-5. After a few rounds in which he explained why the previous proposals failed, the model suggested studying

Tr⁡[(I−E(θ))−1]=∑i11−λi(θ),\operatorname{Tr}\big[(I-E(\theta))^{-1}\big]=\sum_i\frac{1}{1-\lambda_i(\theta)},

where λi(θ)\lambda_i(\theta) are the eigenvalues of the matrix E(θ)E(\theta). The sum grows without bound when some eigenvalue approaches 1, and for this reason it controls how close to 1 the largest of them gets [1]. The authors used the suggestion in the proof; days later, a reader of the blog proposed det⁡(I−E)\det(I-E), which is simpler. Note that the model was useful on a well-posed problem, and an expert judged each proposal. Georgiev, Gómez-Serrano, Tao and Wagner applied a system that proposes programs, evaluated automatically, to 67 problems in analysis, combinatorics, geometry and number theory [44]. The system rediscovered the best known solutions in most cases and improved some: where verification is cheap and automatic, large-scale search works. Bubeck and collaborators collect reports from researchers in several areas, including the points where the model failed [22].

2.6 Calculation and code

In a calculation, the model can make an error in one step and get all the following ones right, and the error reaches the code and the plot intact. This section shows an example, how to check by an independent route and how I use several models on the same problem.

An error that passes through the code and the plot

Constructed example Consider the question: in the one-dimensional Ising chain at zero field, how does the correlation between two spins decay with distance, and what is the correlation length? The answer below was written for the course, in the style of a model, and it starts with the construction of the transfer matrix.

The setup

The Hamiltonian of the chain with NN sites and periodic boundary conditions is H=−J∑i=1Nsisi+1H=-J\sum_{i=1}^{N}s_is_{i+1}, si=±1s_i=\pm1. The partition function factorizes into a product of 2×22\times2 matrices linking neighboring sites, Z=∑{s}∏iT(si,si+1)=Tr⁡TNZ=\sum_{\{s\}}\prod_iT(s_i,s_{i+1})=\operatorname{Tr}\,T^N. To write TT in symmetric form, we observe that each bond appears in both directions when we go along the chain, once in T(si,si+1)T(s_i,s_{i+1}) and again in T(si+1,si)T(s_{i+1},s_i). Incorporating both contributions,

T(s,s′)=exp⁡(2βJss′),T(s,s')=\exp(2\beta J ss'),
T=(e2βJe−2βJe−2βJe2βJ).T=\begin{pmatrix}\mathrm{e}^{2\beta J}&\mathrm{e}^{-2\beta J}\\ \mathrm{e}^{-2\beta J}&\mathrm{e}^{2\beta J}\end{pmatrix}.

The following steps of the answer are right for this matrix. It obtains the eigenvalues λ+=2cosh⁡(2βJ)\lambda_+=2\cosh(2\beta J) and λ−=2sinh⁡(2βJ)\lambda_-=2\sinh(2\beta J), the correlation ⟨s0sr⟩=(λ−/λ+)r=tanh⁡r(2βJ)\langle s_0s_r\rangle=(\lambda_-/\lambda_+)^r=\tanh^r(2\beta J) in the thermodynamic limit and the correlation length ξ=−1/ln⁡tanh⁡(2βJ)\xi=-1/\ln\tanh(2\beta J). A short code, faithful to this derivation, and a plot on a logarithmic scale confirm the exponential decay, with ξ≈3.67\xi\approx3.67 sites for βJ=0.5\beta J=0.5. The error is in the setup. When “symmetrizing” the matrix, the answer counts each bond twice and replaces T(s,s′)=eβJss′T(s,s')=\mathrm{e}^{\beta Jss'} by e2βJss′\mathrm{e}^{2\beta Jss'}. The correct result is

⟨s0sr⟩=tanh⁡r(βJ),\langle s_0s_r\rangle=\tanh^r(\beta J),
ξ=−1ln⁡tanh⁡(βJ),\xi=-\frac{1}{\ln\tanh(\beta J)},
(2.5)

which for βJ=0.5\beta J=0.5 gives ξ=1.295\xi=1.295; the answer obtains 3.6723.672, a factor 2.832.83 higher (Figure 2.3).

Correlation in the Ising chain for $\beta J=0.5$. Both curves pass the cheap checks (they equal 1 at $r=0$, decay monotonically, are exponential); the exact result or an independent calculation tells them apart.

Figure 2.3. Correlation in the Ising chain for βJ=0.5\beta J=0.5. Both curves pass the cheap checks (they equal 1 at r=0r=0, decay monotonically, are exponential); the exact result or an independent calculation tells them apart.

The checks of normalization, monotonicity and exponential form approve the wrong curve. That is, a reading that only checks whether the code implements the formula presented lets the error through, because the code is right for the wrong formula. We need to go back to the Hamiltonian and to the way the matrix was built. Note that symmetrization is a legitimate procedure for the field term −h∑isi-h\sum_is_i, because each site belongs to two bonds, and there we write βh(s+s′)/2\beta h(s+s')/2; the exchange term needs no such treatment. The answer reproduces the form of a legitimate step and applies it where it does not belong, a typical error of models. It also mentions in passing a function scipy.linalg.transfer_matrix, from the most widely used scientific library in Python, and this function does not exist. It is a name with the form of a library function, in the same way that models produce references with the right form.

2.6.2 Where the finite-size formula comes from

For J>0J>0, zero field and a periodic chain of NN spins, the correct matrix has eigenvectors

|+⟩=12(11),|+\rangle=\frac{1}{\sqrt2}\binom11,
|−⟩=12(1−1),|-\rangle=\frac{1}{\sqrt2}\binom1{-1},
λ+=2cosh⁡(βJ),\lambda_+=2\cosh(\beta J),
λ−=2sinh⁡(βJ).\lambda_-=2\sinh(\beta J).

The spin operator in the basis s=±1s=\pm1 is Σ=diag⁡(1,−1)\Sigma=\operatorname{diag}(1,-1), so Σ|+⟩=|−⟩\Sigma|+\rangle=|-\rangle and Σ|−⟩=|+⟩\Sigma|-\rangle=|+\rangle. Inserting s0srs_0s_r in the Boltzmann sum is equivalent to inserting two matrices Σ\Sigma in the trace:

ZN=Tr⁡TN=λ+N+λ−N,Z_N=\operatorname{Tr}T^N=\lambda_+^N+\lambda_-^N,
(2.6)
ZN⟨s0sr⟩N=Tr⁡(TN−rΣTrΣ)=λ+N−rλ−r+λ−N−rλ+r.\begin{aligned}Z_N\langle s_0s_r\rangle_N & {}=\operatorname{Tr}(T^{N-r}\Sigma T^r\Sigma)\\ & {}=\lambda_+^{N-r}\lambda_-^r+\lambda_-^{N-r}\lambda_+^r.\end{aligned}
(2.7)

Each insertion swaps the eigenvector, and the two stretches of the ring have lengths rr and N−rN-r. Dividing numerator and denominator by λ+N\lambda_+^N,

⟨s0sr⟩N=tr+tN−r1+tN,\langle s_0s_r\rangle_N=\frac{t^r+t^{N-r}}{1+t^N},
t=tanh⁡(βJ).t=\tanh(\beta J).
(2.8)

Only then do we take N→∞N\to\infty with rr fixed and T>0T>0, obtaining trt^r. In a finite chain both paths around the ring contribute; substituting the limit directly introduces a physical difference, even with the right calculation.

Checking by another route

For a periodic chain, sN=s0s_N=s_0, with H=−J∑i=0N−1sisi+1H=-J\sum_{i=0}^{N-1}s_is_{i+1} and each bond counted once, we can compute the average of s0srs_0s_r by summing over the 2N2^N configurations with weight exp⁡(−βH)\exp(-\beta H), without building any matrix. To understand the enumeration, take four spins. The configuration (+,+,+,+)(+,+,+,+) has ∑isisi+1=4\sum_i s_is_{i+1}=4 and weight e4βJ\mathrm{e}^{4\beta J}; the alternating one (+,−,+,−)(+,-,+,-) has sum −4-4 and weight e−4βJ\mathrm{e}^{-4\beta J}. The program does this for all configurations, multiplies each weight by the observable s0srs_0s_r and divides by the sum of the weights. The binary representation only organizes this list. A few lines of Python are enough:

import numpy as np

def correlation_by_sum(N, bJ):
    """<s_0 s_r>, r = 0..N-1, summing the 2**N configurations of the periodic chain."""
    conf = np.arange(2**N)[:, None]
    s = 2 * ((conf >> np.arange(N)) & 1) - 1           # spins +1 or -1
    weights = np.exp(bJ * np.sum(s * np.roll(s, -1, axis=1), axis=1))
    return (weights[:, None] * s[:, :1] * s).sum(axis=0) / weights.sum()

N, bJ = 12, 0.5
t, r = np.tanh(bJ), np.arange(N)
print(correlation_by_sum(N, bJ)[1])                    # direct sum
print(((t**r + t**(N - r)) / (1 + t**N))[1])           # finite formula

The program compares the direct sum with the finite-size formula (2.8), valid for 0≤r≤N0\le r\le N, which follows from the correct matrix: ZN=λ+N+λ−NZ_N=\lambda_+^N+\lambda_-^N, and inserting the two spins swaps the two eigenvectors. For N=12N=12 and βJ=0.5\beta J=0.5, both methods give 0.462278560.46227856 for neighbors, and the thermodynamic limit, tt, gives 0.462117160.46211716; the difference is finite-size physics. So the direct sum is a genuine check, because it starts from the Hamiltonian and avoids the step where the error came in. Asking another model to check the same matrix may repeat the same premise. We call this correlated verification: the check fails through the same association that generated the error.

Check your understanding

Why is a second program that diagonalizes the same wrong matrix not enough? Because it preserves the choice 2βJ2\beta J that caused the error. The direct sum also tests the passage from the Hamiltonian to the matrix. To compare numbers, keep the same NN, the same βJ\beta J and the same boundary conditions.

Explore

From the Hamiltonian to the direct sum

The browser enumerates all 2ᴺ configurations of a ring with N spins and weights each one by exp[βJ Σᵢ sᵢsᵢ₊₁]. Each bond is counted once. The comparison uses the finite-size formula, with the same N and the same boundary conditions.

Before touching anything: on a finite ring, should the correlation keep falling up to r = N − 1 or rise again? Why?

The controls work when the file is opened in a browser such as Safari or Chrome. The values below are for the starting position.

Correlation ⟨s₀sᵣ⟩00.5103611Distance r around the ringCorrelation ⟨s₀sᵣ⟩Finite formulaWrong factor 2Direct sum
Correlation ⟨s₀sᵣ⟩00.5103611Distance r around the ringCorrelation ⟨s₀sᵣ⟩Finite formulaWrong factor 2Direct sum
Direct sum · r = 10.46227856
Correct finite formula0.46227856
With the factor 20.78182212

Largest difference between the direct sum and the correct formula: 8.05 × 10⁻¹⁵. 4,096 configurations were summed.

For comparison: the infinite-ring limit tʳ is 0.46211716; ξ = −1/ln[tanh(βJ)] = 1.2954 sites.

What this check tests

The curve rises again because there are two paths around the ring: r and N − r. The finite formula is (tʳ + tᴺ⁻ʳ)/(1 + tᴺ), with t = tanh(βJ). The dashed curve replaces βJ by 2βJ in this same formula; it describes another coupling. The enumeration starts from the Hamiltonian and does without the construction of the matrix, so it can detect the factor 2 that a second diagonalization would let through.

Ferromagnetic model, zero field, equilibrium, periodic boundary conditions and N ≥ 4. The largest difference compares the two methods at every distance on the ring. The numerical check holds for these finite cases.

Several models on the same problem

When a problem matters, I put more than one model to work on it. For this I use an application that organizes rounds. The same request goes to models from different companies, and each one audits another’s answer, that is, looks for errors and gaps in what the other wrote. Then each one revises its own answer based on the audit it received, and one model integrates the versions, which I compare before closing the synthesis (Figure 2.4). In a round in June 2026, with Claude, from Anthropic, Codex, from OpenAI, and Gemini, from Google, the request was this:

Real session · Claude, Codex and Gemini · 24 Jun 2026

Prompt: “Improve this problem set. I think some exercises look too simplistic (the first exercise, for instance, is not very interesting) and are not really measuring the students’ knowledge. Make a list in the same format but with more interesting exercises. Also write the solutions, with questions to be asked in an oral examination.”

Action: audits in a cycle: Claude audits Codex, Codex audits Gemini, Gemini audits Claude

Action: revisions by each model; integration by Claude; synthesis with the problem set and the solutions

A round with several models: independent answers, audit in a cycle, revision, integration and synthesis.
Three independent answers
  • A: method and assumptions
  • B: method and assumptions
  • C: method and assumptions
  1. Cross-auditCompare the answers and justify each critique.
  2. Revision and synthesisRevise the answers. The final decision belongs to the researcher.

Figure 2.4. A round with several models: independent answers, audit in a cycle, revision, integration and synthesis.

Models from different companies, trained in different ways, raise different objections, and this is worth a lot in a critique. But the independence of a check comes from the method: two models that agree may be repeating the same premise, as we saw with Ising.

The same principle has already become a tool. Morgensztern, Fierro Cota and Mininno describe the Solver Agent, an agent for calculations and proofs in theoretical physics, and apply it to a problem in string theory, the uplifts of O3-planes and S-folds to F-theory [83]. A central agent delegates tasks to specialized subagents, other instances of the model that start with a fresh context, without the history of the main conversation, and with their own tools: symbolic algebra, numerical calculation, Calabi–Yau geometry, literature search. Each step goes into a persistent record of assumptions, derivations and calculations, in which each entry points to the others it depends on; it is the formal version of the summaries that preserve dependencies of Section 2.2.11. Two separate reviewers check each step and the final result, and each one sees only the material it receives for review. But the authors are clear about the limit: the system was built to make each step explicit, inspectable and repeatable, and it “does not establish mathematical correctness”; “review can fail to notice a defect just as the original derivation did”. This is the correlated verification of the Ising example, acknowledged by the authors themselves. The paper is from September 2026 and has not yet gone through peer review.

2.7 Writing and review

The model writes quickly and well in the average sense, and it is precisely this average sense that we need to control. This section deals with the voice of whoever signs, with a report requested before submission and with a public case in which a physicist guided a model through a whole calculation.

Writing in one’s own voice

For texts that go out under my name, I use the voice skill of Section 2.2.5, measured on my own writings.

The marks of generated text are measurable. Kobak and collaborators estimate, from the excess of certain style words, such as delves, that at least 13.5% of the biomedical abstracts of 2024 went through a model [67]. Liang and collaborators find up to 22% in computer science and up to 9% in mathematics [75]. The most common marks are inflated vocabulary, enumerations always in triads, negative parallelism of the type “it is not X, it is Y”, generic closing sentences and uniform caution in every sentence, unrelated to the degree of certainty. Passive voice and epistemic caution have a legitimate place in scientific writing. But the problem starts when they appear out of the model’s habit. Wikipedia’s collaborative guide on signs of AI writing is a good checklist [119].

A short revision, with the content preserved

Initial passage: “A wiki maintained by a model has a risk of its own: an error that enters a page starts being consulted as fact, by me and by the model itself in later sessions.”

Revised text: “If a wrong claim enters the wiki, the model and I may treat it as fact in later queries. For this reason I keep the source and record every correction.”

The revision replaces the abstract formulation with the concrete event and ties the risk to the action that reduces it. The “may” avoids asserting that every query will propagate the error. The second sentence makes explicit the procedure described in this section; it does not add a guarantee of correctness. Compare the meaning before accepting a change of voice.

A report before submission

Liang and collaborators compared comments generated by a model with real referee reports on thousands of papers [74]. The overlap between the points raised by the model and by the referees (30.85% in Nature journals, 39.23% at ICLR, one of the main machine-learning conferences) was close to the overlap between two human referees (28.58% and 35.25%). Of the 308 authors consulted, 57.4% found the feedback useful. I have a review skill with criteria from theoretical physics, which makes the model read the manuscript as a referee, and I read what it produces as a preliminary report. But part of the objections may be invented: asking “point out the problems” can induce baseless objections, as in the skeptical CHSH report.

A complete review before submitting can follow six passes: a map of claims, with the assumptions each one depends on; the central derivations redone independently, in computer algebra or numerically; limiting cases and dimensions; notation and conventions (metric signature, Fourier convention, normalization of states, factors of ii and 2π2\pi); literature and novelty; and a hostile reading, answered item by item.

A QCD calculation done with a model

Matthew Schwartz guided a model through a precision QCD calculation, which resulted in arXiv:2601.02484 [102]. The CC parameter measures the shape of jets in e+e−e^+e^- collisions, and its distribution has a “Sudakov shoulder”, a point at which perturbation theory produces large logarithms that need to be summed to all orders; this sum is the resummation. The work took about two weeks and 110 versions of the manuscript, and he estimates three to five months to do it alone. The report lists failures that any physicist will recognize. The factorization formula, which splits the cross section into factors associated with different scales and is the central piece of the paper, was copied from another physical system without the necessary modifications, and “verification documents” contained coefficients that were not in the paper. Faced with discrepancies, the model adjusted parameters until the curves matched and produced uncertainty bands that were too narrow; it declared “verified” without having verified and went back to textbook conventions even with the conventions of the paper fixed in writing. The safeguards he adopted are those of this chapter: models from different companies, hierarchical summaries in place of long documents, instructions to show every step or declare ignorance, and asking repeatedly for errors until no new one appears.

What I delegate, what I check, what I do not delegate

I summarize my practice in a table.

I delegate I check I do not delegate
writing notes under a written standard; maintaining the wiki; checking code; translations; first drafts every calculation, by another method; every reference, by opening the source; every attribution the choice of problem; the judgment about what is true or new; the decision to sign

Controlled studiesfurther reading

Si, Yang and Hashimoto compared, in a blind evaluation, research ideas in natural language processing, the area of computing that studies language models, written by experts and ideas generated by a system based on language models, with more than a hundred researchers [108]. The model’s ideas were judged more original (p<0.05p<0.05), slightly less feasible and not very diverse among themselves. In the follow-up study, 43 researchers executed randomly assigned ideas, with more than 100 hours of work each. But, after execution, the scores of the model’s ideas fell more than those of the human ideas on every metric, and on several the ranking was reversed [109]. Doshi and Hauser find a similar pattern in creative writing: each text improves with the model’s help, and the collection becomes more homogeneous [36].

In frontier physics, a test suite called CritPt collects 71 challenges written by more than 50 researchers from their own work, broken down into 190 verifiable intermediate tasks [122]. In 2025, the best model, without tools, solved on average 5.7% of the complete challenges, and close to 10% with code tools; TPBench does a similar exercise in theoretical physics [28]. But these numbers go out of date within months, and what remains useful is knowing at which stages models go wrong.

Two tables of errorsfurther reading

Errors of content
Error How it shows up in physics How to detect it
Invented reference or one with swapped metadata True author with the wrong year, volume or title; plausible paper that never existed Check in INSPIRE-HEP, on arXiv or by the DOI; open it before citing
Wrong attribution Result of one group credited to another; theorem with the wrong name Read the primary source
False novelty “To my knowledge, this has never been done” Your own search; ask for previous work in a new session
Sycophancy Accepts the user’s wrong premise; changes position under pressure Open question; ask for the strongest objection; test with the premise reversed
Mixed conventions Metric signature, Fourier normalization, ℏ=1\hbar=1 applied halfway Fix the conventions in writing; check dimensions
Algebraic error with an appearance of rigor Signs, factors of 2, π\pi and ii; the “immediate” step hides the error Redo it in computer algebra; check limiting cases
Loss of information in a long context Ignores an assumption stated in the middle of a long text Targeted questions; hierarchical summaries
Cutoff date Does not know recent results Provide the papers in the context
Errors of process
Error Symptom How to detect it
Feigned verification “I checked numerically” with no code, or with code that tests something else Demand the code, run it and read what it compares
Correlated verification The check fails through the same association that generated the error Independent method or source; exact result when available
Convention drift Goes back to textbook conventions in the middle of the calculation Conventions file in the context; a review pass dedicated to it
Premature stopping Finds one error and declares the review finished Repeat the question until no new error appears
Fitting to the expected Parameters tweaked so the curve “matches”; bands too narrow Freeze parameters before the comparison; list everything that changed
Right procedure in the wrong place Symmetrization applied to the term that does not need it (Ising) Redo the step from the definition
Rewriting that changes the content “For all” becomes “for some”; an assumption disappears Compare the versions; read rewritten equations and statements
Decorative citation Real reference that does not support the sentence in which it appears Open the reference and locate the passage

2.11 Optional exercise: a minimal wiki

Choose two papers from your field that you know well. With an assistant that reads and writes files, or by hand, set up a folder with three Markdown pages: one for each paper and a concept page linking the two. Write first an instructions file with your conventions. In each claim, point to the section or the equation of the source. Then ask the wiki a question, check two claims of the answer in the PDFs and write down what you found.

Readings

To start: Karpathy [65]; Aaronson [1]; Schwartz [102]; Liang et al. [74].

To go further: Bush [24]; Ahrens [2]; Forte [42]; Lewis et al. [72]; Liu et al. [78]; Walters and Wilder [117]; Feng et al. [41]; Georgiev et al. [44]; Bubeck et al. [22]; Si et al. [108], [109]; Doshi and Hauser [36]; Zhu et al. [122]; Chung et al. [28]; Kobak et al. [67]; Liang et al. [75]; Wikipedia guide [119].

The two papers of the cases in this chapter: Guimaraes [50]; Caribé, Guimaraes, Roditi and Sorella [25].

Exercises for Lesson 2

Exercise 2.1 · Your application’s instructions

After Lesson 2; with the application you use

Choose the AI application you use most, whether ChatGPT, Claude, Gemini or another, and prepare the initial condition for your conversations. The table “Where each layer lives” in the notes says where instructions and memory sit in the most widely used applications.

  1. Write five to ten lines of personal instructions and place them where the application reserves space for them; the table gives the menu names in English, and in Portuguese they change. State who you are, your field and level, the notation you use, with an example (metric signature, units, Fourier transform convention), how you want answers formatted and what the model should always check.

  2. Open the application’s memory and read what it has saved about you. Edit or delete anything that is wrong, and note what you found. If memory is turned off, empty or unavailable on your plan, note that and decide whether you want to enable it; the choice is yours.

  3. Ask the application a question from your field and check whether the answer follows the notation and format you asked for.

  4. (Optional) Choose a recurring task in your work and write the description of a skill for it, in two sentences: one about what the skill does and another about when to use it. If your application does not support skills, keep the description and the procedure in a file and paste it into the conversation when the task comes up.

Product: the text of the instructions, a short note on what memory contained and what you changed, and the result of the test question.

Exercise 2.2 · A minimal wiki

After Lesson 2; with or without an assistant

Choose two papers from your field that you know well. With an assistant that reads and writes files, or by hand, set up a folder with three Markdown pages: one for each paper and a concept page linking the two.

  1. Write first an instructions file with your conventions and with what the assistant may or may not change.

  2. In each claim on the pages, point to the section or the equation of the source. On the concept page, include a field for assumptions.

  3. Ask the wiki a question and check two claims of the answer in the PDFs. Write down what you found, including what you had to correct.

Filled-in template: the folder exemplos/wiki-minima/ shows the cycle with two local Ising sources. Use it as a structure, replacing the sources by the papers you chose.

Product: the folder, or the three printed pages, and half a paragraph on what the check found.

Exercise 2.3 · The CHSH inequality in dialogue

After Lesson 2; the eight exchanges of the dialogue

Goal. To compare questions that clarify the assumptions with questions that presuppose a conclusion and can lead to a wrong answer.

Constructed example

The problem. Two distant parties measure observables with outcomes ±1\pm1. Alice chooses between AA and A′A'; Bob, between BB and B′B'. The CHSH combination is S=⟨AB⟩+⟨AB′⟩+⟨A′B⟩−⟨A′B′⟩S=\langle AB\rangle+\langle AB'\rangle+\langle A'B\rangle-\langle A'B'\rangle.

Exchange 1

Show that local correlations bound |S|≤2|S|\le2 and determine the maximum allowed by quantum mechanics.

Response

In a hidden-variable model, each value of λ\lambda fixes outcomes A,A′,B,B′∈{−1,+1}A,A',B,B'\in\{-1,+1\}, and we can group S(λ)=A(B+B′)+A′(B−B′)S(\lambda)=A(B+B')+A'(B-B'). Since BB and B′B' are ±1\pm1, one of the sums vanishes and the other is ±2\pm2; therefore |S(λ)|≤2|S(\lambda)|\le2 for each λ\lambda, and the average preserves the bound. Quantum mechanics violates the inequality: with the singlet and measurements separated by 45∘45^\circ, |S|max=22≈2.828|S|_{\max}=2\sqrt2\approx2.828, the Tsirelson bound, about 41% above the local maximum, confirmed in several experiments.

Exchange 2

State explicitly every assumption used in the local bound, including those that do not appear in the algebra.

Response

We use three conditions. (1) Local factorization: given the shared variables λ\lambda, the response on each side depends only on the setting of that side,

p(A,B∣a,b)=∫dλρ(λ)p(A∣a,λ)p(B∣b,λ).p(A,B\mid a,b)=\int\mathrm{d}\lambda\,\rho(\lambda)\,p(A\mid a,\lambda)\,p(B\mid b,\lambda).
p(A,B∣a,b)=∫dλρ(λ)p(A∣a,λ)p(B∣b,λ).\begin{aligned} & p(A,B\mid a,b)\\ &\quad {}=\int\mathrm{d}\lambda\,\rho(\lambda)\,p(A\mid a,\lambda)\,p(B\mid b,\lambda).\end{aligned}

(2) Measurement independence: the same ρ(λ)\rho(\lambda) does not depend on the settings a,ba,b. (3) Outcomes: A,B∈{−1,+1}A,B\in\{-1,+1\}. We can incorporate local random variables into λ\lambda and work with deterministic responses without restricting this class of models. The four values used in the proof are this representation; we do not need to add a separate postulate called “realism”.

Exchange 3

Which condition of the proof requires attention when interpreting the experimental data?

Response

We need to justify that the settings do not select different distributions of λ\lambda and that the detected set does not introduce a selection that mimics a violation. There is no universally “less secure” assumption: the assessment depends on the experimental design.

Exchange 4

Under which concrete condition can the argument fail?

Response

Three known loopholes. Detection: with low efficiency, the detected sample may not represent the emitted set. Locality: without spacelike separation between the choice of setting and the measurement, a signal can transmit the choice. Freedom of choice: a correlation between ρ(λ)\rho(\lambda) and the settings breaks measurement independence.

Exchange 5

Construct an explicit counterexample: a local hidden-variable model that violates |S|≤2|S|\le2.

Response

Consider λ\lambda uniform in [0,2π)[0,2\pi) and the response functions A(a,λ)=sgn⁡cos⁡(λ−a)A(a,\lambda)=\operatorname{sgn}\cos(\lambda-a) and B(b,λ,a)=sgn⁡cos⁡(λ−b+π4δa,a1)B(b,\lambda,a)=\operatorname{sgn}\cos(\lambda-b+\tfrac{\pi}{4}\delta_{a,a_1}), where the phase shift in BB encodes the correlation established at the source at the moment of emission. With a1=0a_1=0, a2=π/2a_2=\pi/2, b1=π/4b_1=\pi/4 and b2=3π/4b_2=3\pi/4, the four correlations come out with the favorable sign and we obtain S=4S=4, above both the local and the quantum bounds. The model is local because each outcome is computed from a shared variable defined at the source, with no signal transmitted during the measurement.

Exchange 6

Derive the quantum bound by an independent route, without choosing a state or angles.

Response

Let Â,Â′,B̂,B̂′\hat A,\hat A',\hat B,\hat B' be Hermitian with square equal to the identity, with Alice’s commuting with Bob’s, and Ŝ=Â(B̂+B̂′)+Â′(B̂−B̂′)\hat S=\hat A(\hat B+\hat B')+\hat A'(\hat B-\hat B'). Squaring, Ŝ2=4I−[Â,Â′][B̂,B̂′]\hat S^2=4I-[\hat A,\hat A'][\hat B,\hat B']. Since ‖[Â,Â′]‖≤2\lVert [\hat A,\hat A']\rVert\le2 and ‖[B̂,B̂′]‖≤2\lVert [\hat B,\hat B']\rVert\le2, it follows that ‖Ŝ2‖≤8\lVert \hat S^2\rVert\le8 and ‖Ŝ‖≤22\lVert \hat S\rVert\le2\sqrt2, for any state and any dimension.

Exchange 7

Which limiting cases should reproduce known results?

Response

If Â\hat A and Â′\hat A' commute, or if B̂\hat B and B̂′\hat B' commute, Ŝ2=4I\hat S^2=4I and we return to |S|≤2|S|\le2: compatible observables reproduce the local bound. For a product state, ⟨A⊗B⟩=⟨A⟩⟨B⟩\langle A\otimes B\rangle=\langle A\rangle\langle B\rangle: the connected correlation is zero, but the product of averages can be nonzero. Then |S|≤2|S|\le2 also holds. For the singlet with the optimal angles, |S|=22|S|=2\sqrt2, saturating the bound.

Exchange 8

Now act as a skeptical referee and point out the problems with the derivation above.

Response

I point out three problems. (1) The passage from the inequality for each λ\lambda to the inequality for the averages lacks justification; the convexity argument that licenses this step is missing. (2) The assumption Â2=I\hat A^2=I restricts the result to dichotomic observables and should be declared as a restriction of the result. (3) The claim that the bound holds in any dimension is not proved; the norm inequality requires care in infinite dimension. I recommend major revision.

Questions. After exchange 1: where does the right to write A,A′,B,B′A,A',B,B' at the same time for the same λ\lambda come from? After exchange 2: would you have listed measurement independence without help? After exchange 5: what is wrong? After exchange 8: classify the three objections.

Exercise 2.4 · Ising: do you believe this?

After Lesson 2; pen and paper, or a short program

Goal. To see a derivation error pass through the code and the plot without internal inconsistency, and to see that an exact formula or an independent sum reveals it.

Constructed example

Step 1: the question

In the one-dimensional Ising chain at zero field, how does the correlation between two spins decay with the distance between them, and what is the correlation length?

Step 2: setup

The Hamiltonian of the chain with NN sites and periodic boundary conditions is H=−J∑i=1Nsisi+1H=-J\sum_{i=1}^{N}s_is_{i+1}, si=±1s_i=\pm1. The partition function factorizes into a product of 2×22\times2 matrices linking neighboring sites, Z=∑{s}∏iT(si,si+1)=Tr⁡TNZ=\sum_{\{s\}}\prod_iT(s_i,s_{i+1})=\operatorname{Tr}\,T^N. To write TT in symmetric form, we observe that each bond appears in both directions when we go along the chain, once in T(si,si+1)T(s_i,s_{i+1}) and again in T(si+1,si)T(s_{i+1},s_i). Incorporating both contributions,

T(s,s′)=exp⁡(2βJss′),T(s,s')=\exp(2\beta J ss'),
T=(e2βJe−2βJe−2βJe2βJ).T=\begin{pmatrix}\mathrm{e}^{2\beta J}&\mathrm{e}^{-2\beta J}\\ \mathrm{e}^{-2\beta J}&\mathrm{e}^{2\beta J}\end{pmatrix}.

Step 3: eigenvalues

The matrix is symmetric with a constant diagonal; its eigenvectors are (1,1)/2(1,1)/\sqrt2 and (1,−1)/2(1,-1)/\sqrt2, and the eigenvalues, λ+=2cosh⁡(2βJ)\lambda_+=2\cosh(2\beta J) and λ−=2sinh⁡(2βJ)\lambda_-=2\sinh(2\beta J). In the thermodynamic limit the largest eigenvalue dominates, and the free energy per site is f=−β−1ln⁡λ+f=-\beta^{-1}\ln\lambda_+.

Step 4: the correlation function

Inserting σz\sigma_z at the two positions, ⟨s0sr⟩=Tr⁡(σzTrσzTN−r)/Tr⁡TN\langle s_0s_r\rangle=\operatorname{Tr}(\sigma_zT^r\sigma_zT^{N-r})/\operatorname{Tr}\,T^N. In the basis of eigenvectors, σz\sigma_z only connects |+⟩|+\rangle to |−⟩|-\rangle, and in the limit N≫rN\gg r what remains is ⟨s0sr⟩=(λ−/λ+)r=tanh⁡r(2βJ)\langle s_0s_r\rangle=(\lambda_-/\lambda_+)^r=\tanh^r(2\beta J). The decay is exponential, with correlation length ξ=−1/ln⁡tanh⁡(2βJ)\xi=-1/\ln\tanh(2\beta J). There is no phase transition at finite temperature: ξ\xi diverges only when T→0T\to0.

Step 5: the code

We could use scipy.linalg.transfer_matrix, but the explicit construction is clearer.

import numpy as np
import matplotlib.pyplot as plt
def correlation(bJ, r):
    T = np.array([[np.exp(2*bJ), np.exp(-2*bJ)],
                  [np.exp(-2*bJ), np.exp(2*bJ)]])
    lam_minus, lam_plus = np.linalg.eigvalsh(T)   # increasing order
    return (lam_minus / lam_plus) ** r
bJ = 0.5
r = np.arange(0, 9)
C = correlation(bJ, r)
xi = -1.0 / np.log(C[1])
print(f"correlation length: {xi:.4f}")           # 3.6719
plt.semilogy(r, C, "o-"); plt.xlabel("distance r"); plt.ylabel("<s0 sr>"); plt.show()

Step 6: the plot

The straight line on a logarithmic scale confirms the predicted exponential decay, with ξ≈3.67\xi\approx3.67 sites.

Question. Do you believe this? Check the result by an independent route.

Lesson 3 · 90 minutes

AI in teaching and studying

Question of the lesson

Which evidence distinguishes a well-presented solution from an understanding the student can use?

By the end, you should be able to

Write a short question, predict a sufficient answer and define a criterion that accepts equivalent justifications.

Path: produce checkable notes → observe an answer → formulate a hypothesis → probe → give feedback. The report should change when the evidence changes.

This chapter looks at teaching from both sides. On the teacher’s side, I describe how I write lecture notes with models and how I use a model in the role of a teaching assistant, the student who helps the instructor in a course. The model works in a continuous assessment, in which each student receives short tests and a report of their own. On the side of those who study, we see what the evidence says about the model as a tutor, how to ask it to examine what we know and why a fluent explanation can give a false sense of understanding.

The corresponding lesson covers Sections 3.1 to 3.4. The sections marked as further reading deal with preparing an exam with AI and with a usage policy for a course. The optional exercise in Section 3.7 proposes writing post-exam questions, first for a ready-made case and then for a question from a course of your own.

Reading path

The core is the cycle answer →\to observed evidence →\to hypothesis →\to new question →\to feedback. Basic notions of assessment and a reading of the formulas for Ising and for the canonical ensemble are enough. By the end, try to write a short question, an expected answer and a criterion that accepts equivalent justifications, without turning an isolated sign into a diagnosis of the student.

3.1 Lecture notes with AI

This section describes how I write lecture notes with models, which rules I leave written down for them and what the reviews usually find.

How I write

Figure 3.1 summarizes the process. I define the goal of the course, the audience, the approach and the sources. The model drafts each note following a written standard, which it reads before starting. Programs redo the calculations. Then come review passes, complete readings of the text by a model, each with one focus: correctness, clarity, pedagogy. What the review finds goes back into the text, and at the end I read, correct and publish.

How I write lecture notes with models. The steps in orange are mine; those in blue, the models'.
  1. Goal, audience and sourcesChoices of the instructor.
  2. Drafting the noteFollow a written standard.
  3. Checking and reviewVerify calculations, clarity and pedagogy.
  4. Reading and decisionCorrect, approve and decide on publication.

Problems found in the review lead to a new draft.

Figure 3.1. How I write lecture notes with models. The steps in orange are mine; those in blue, the models’.

This is how it went with the notes for the graduate courses I prepared this year. In the AdS/CFT notes, the validation, done by programs that check the calculations and the structure of the text, comprised 1,223 checks in early October 2026, 932 of them on calculations. In the notes on generalized symmetries, each block of weeks went through an independent check of the calculations. The AQFT notes became a book, with 462 pages in the September 2026 version, which lists three models on the title page; Chapter 4 returns to this point.

A written standard

A model that writes without instructions fills in the choices with what is most frequent in training, as we saw in Chapter 1: the order of a textbook, claims without assumptions, problems that ask to “show” anything at all. For this reason the standard for the AQFT notes fixes these choices in writing. Three of its points apply to any course.

  • Three routes. Each note distinguishes the core that fits in one lesson, the complete derivation for those who study alone and the research extension. These notes follow the same idea: the content of each lesson, the text for study and the further-reading sections.

  • Status labels. Every theorem-level claim carries a label that says how much it promises: proved; proved in a model; sketched; stated with a reference; heuristic; exact calculation in a defined model; controlled perturbative; formal analogy; only an example; explicit assumptions. In statistical mechanics I use a version of my own: exact, thermodynamic limit, controlled approximation, mean field, exact result of a model, heuristic or interpretive.

  • Honest problems. A problem can ask the student to test or refute a claim, and never to prove a false premise.

The standard also contains scope rules, such as never presenting a free-field calculation in a particular case as a general theorem, and a minimal checklist before declaring a note finished, which includes checking the number and title of every recent paper cited. Note that the status label has an advantage that goes beyond honesty: it makes the note auditable. That is, whoever reviews it knows what each claim promises and can check whether the text delivers.

What the reviews find

In September, a review of clarity, pedagogy and correctness of all the AQFT notes, done with Claude Opus 5.5, ended with a list of failure modes typical of text written by models. Table 3.1 summarizes the result.

Table 3.1. Failure modes in the review of the AQFT notes, 29 Sep 2026.
Failure mode Result of the review
Error in a symbolic calculation not found; the numerical calculations agree with the closed formulas
Invented or misdescribed citation confirmed in 7 places
Invented derivation not found in the central results; gaps only inside labeled sketches
Argument from a particular case suspected in 2 places
Algebraic error presented as a discovery not found
Drift of convention or notation suspected: overloaded notation
Fixation on the first formulation not found

The seven citation problems show the pattern. A duality theorem of Takesaki, from 1973, appeared attributed to Connes and Takesaki, whose 1977 paper deals with another subject, the flow of weights. A section “VIII.C” was cited in a paper whose subsections are numbered VIII.1 to VIII.4. A paper about extremal black holes appeared as a study of observers in de Sitter space; this is the case we saw in Section 2.3. The two arguments from a particular case have the same form. In the first, a property of the operator algebras of quantum field theory, type III1_1, was verified with a single state, when the definition requires the condition for all faithful normal states. In the second, a free-field calculation in a wedge was used in place of the general results of the gravity papers. The notation was also running up debts: the same σ\sigma denoted three different objects, the modular flow, the Pauli–Jordan symplectic form and the second density matrix of a relative entropy.

None of this shows up in a quick reading. In fact, the text is fluent and the calculations are right; the errors lie in attributions, assumptions and conventions, which only someone who knows the literature notices. But the review can also be wrong. It comes with a verification table, with each claim checked, the source consulted and the result, and with this table we can check each correction at the source without redoing the whole review.

A review that improves learning

Constructed example Consider this draft of a note: “Since the temperature is fixed by the bath, it is enough to compute the mean energy.” The text skips exactly the distinction the student needs to learn. A useful review delivers a calculation the student can redo:

Revised passage

The bath fixes TT, which determines the probabilities of the states. For levels 00 and ε\varepsilon, let p=e−βε/(1+e−βε)p=\mathrm{e}^{-\beta\varepsilon}/(1+\mathrm{e}^{-\beta\varepsilon}). The energy in a measurement can be 00 or ε\varepsilon, while ⟨E⟩=εp\langle E\rangle=\varepsilon p and Var⁡(E)=ε2p(1−p)\operatorname{Var}(E)=\varepsilon^2p(1-p). For βε=ln⁡3\beta\varepsilon=\ln3, p=1/4p=1/4: the mean is ε/4\varepsilon/4 and the variance, 3ε2/163\varepsilon^2/16. Fixed temperature does not mean fixed energy.

The instructor can check both averages directly over the two states. The review added a distinction, a numerical example and a control question: “which outcome of a measurement equals the mean?”. In this case, neither of the two. Asking the model only to “make it more didactic” does not guarantee that it will provide these three things.

What I would not have time to do alone

Part of what the models made possible is something I simply would not do. For the course on the physics of neural networks, five browser experiments, small interactive programs that run on a web page, accompany the notes: fitting a distribution and interpreting the derivative of the loss; comparing correlation and mutual information in a binary Markov chain; retrieving a pattern in a four-spin Hopfield network; following the descent of the energy with two continuous memories; tracking two recurrent states under the same inputs. They work without an internet connection, and each one asks for a prediction before a control is touched. In May, the AQFT course came to exist in two versions, one written with Claude and the other with Codex, and both went through audits. And the same statistical-mechanics exam was prepared in three languages.

3.2 Continuous assessment

This section shows why problem sets solved at home came to measure little, what education research says about assessing frequently and the cycle I use in statistical mechanics, with an example.

What a problem set solved at home still measures

Bastani and collaborators followed about a thousand high-school students in Turkey, in mathematics [15]. With access to GPT-4, performance on the exercises rose 48% with the ordinary interface and 127% with a tutor version, instructed by the teachers to give hints without handing over the answer. But, once access was removed, those who had used the ordinary interface did 17% worse on the exam than the control group. The tutor version avoided most of this harm, with no significant gain on the exam. The drop occurred in the group with the ordinary interface (GPT Base). It describes neither every use of AI nor the result of the tutor version (GPT Tutor).

A problem set solved at home, without evidence of the process, has become a less direct measure of individual mastery. Kortemeyer showed in 2023 that the ChatGPT of that year would pass, barely, an introductory physics course, with the misconceptions typical of beginners [68]; today’s models do much more. Misconceptions are the intuitive and wrong ideas that many students bring to physics, such as the idea that a moving body needs a force to keep moving. In statistical mechanics, the grade comes only from individual, in-person exams, and the problem sets serve for practice, without counting toward the grade. This settles the measurement. But it creates another problem: two or three exams per semester say little about what each student understood, and they say it late.

Few exams say little

Three results from education research point in the same direction. Black and Wiliam reviewed the literature on formative assessment, the kind that serves to adjust teaching along the course, and concluded that frequent and specific feedback to the student improves learning [18]. Roediger and Karpicke showed the testing effect: after studying a text, those who took a memory test remembered more, two days and one week later, than those who reread the text, although rereading won in a test taken five minutes later [97]. And Bloom reported that students with an individual tutor, combined with mastery learning, in which the student only moves on after mastering the previous unit, ended up about two standard deviations above the students in a conventional class [19]. But later studies found smaller effects: in a meta-analysis, VanLehn found 0.79 standard deviation for human tutoring and 0.76 for computer tutoring systems that follow each step of the solution [115]. The effect remains large.

All of this works. But it is expensive: an instructor with thirty students does not write a test per student every week, nor an individual report after each exam. This is the cost that a model, in the role of teaching assistant, reduces.

The cycle I use in statistical mechanics

This semester I use the cycle of Figure 3.2 in statistical mechanics. The students take the exam, written and individual. The model and I analyze the answers, and the model drafts a report for each student and a personalized post-exam test, of 10 to 20 minutes, with questions of the type “why did you write this in this question? What were you thinking at the time?”. The answers to the test go back into the analysis, done again by me and by the model, and the report is updated: what the student understood, what they seem not to have understood. The student receives this result, with or without a grade. But what matters is knowing what they understood and what not yet. A new test, also personalized, returns to the gaps, so that the student studies that point further. And the cycle goes on, with short tests between the exams.

The cycle of continuous assessment. The model drafts reports and tests; I check, decide and answer for the feedback.
  1. Student’s answerCollect observable evidence.
  2. Hypothesis on the difficultyDraft checked by the instructor.
  3. Short probeQuestion and criterion defined beforehand.
  4. Feedback and new testUpdate the hypothesis with the new answer.

The answer to the new test starts another turn of the cycle.

Figure 3.2. The cycle of continuous assessment. The model drafts reports and tests; I check, decide and answer for the feedback.

So the assessment becomes continuous, and what remains at the end of the course is a detailed report of each student’s progress. Without the model, this work would be unfeasible for an instructor alone. But with it the work becomes feasible, and the instructor’s role moves: away from writing each test and toward checking each report and deciding what to tell the student.

3.2.4 An example with fictitious data

Fictitious data The following example is invented, with an invented student. The exam question asks for the free energy of the one-dimensional Ising chain, without a field, by the transfer matrix, and asks whether there is a phase transition at finite temperature. The student correctly obtains the eigenvalues λ±=2cosh⁡βJ,2sinh⁡βJ\lambda_\pm=2\cosh\beta J,\ 2\sinh\beta J and the free energy per site f=−kBTln⁡(2cosh⁡βJ)f=-k_BT\ln(2\cosh\beta J), and ends like this: “the transition happens at Tc≈2.27J/kBT_c\approx2.27\,J/k_B, where the spontaneous magnetization appears”.

The number has an origin: it is Onsager’s critical temperature for the square lattice, kBTc/J=2/ln⁡(1+2)≈2.269k_BT_c/J=2/\ln(1+\sqrt2)\approx2.269 [87]. The answer shows a correct calculation in this item and a conclusion incompatible with it; this is still not enough to claim mastery of the technique in general. The report, drafted by the model and checked by me, would record this:

Report after the exam

Observed in this item: correctly computed the eigenvalues and the free energy presented.
Seems to be missing: the link between the analyticity of ff and the absence of a transition; the role of dimension.
Hypothesis: the value 2.272.27 came from the square lattice, remembered without the condition that goes with it.
What decides: can the student say why there is no order in one dimension at T>0T>0?

The post-exam test starts with the open question and continues with two probes of different types:

  1. In question 2 you wrote Tc≈2.27J/kBT_c\approx2.27\,J/k_B. Where did this number come from? What were you thinking?

  2. Where it breaks. “At low temperature the spins align, so there is order.” At which step does this argument fail in one dimension? Expected answer: a domain wall costs energy 2J2J and can sit in any of N−1N-1 positions, and so ΔF=2J−kBTln⁡(N−1)<0\Delta F=2J-k_BT\ln(N-1)<0 for large NN at any T>0T>0; the walls multiply and destroy the order.

  3. Slightly wrong statement. “The two eigenvalues become equal at T=2.27J/kBT=2.27\,J/k_B, and there ff stops being analytic.” Is this right? Expected answer: no, because λ+−λ−=2e−βJ>0\lambda_+-\lambda_-=2\mathrm{e}^{-\beta J}>0 for every T>0T>0; the eigenvalues only approach each other when T→0T\to0, and this is why there is no transition at finite temperature.

Two other probes would serve. One connects the result to another topic: “at the temperature where you placed the transition, what is the correlation length?”. Note that tanh⁡(J/kBTc)=2−1\tanh(J/k_BT_c)=\sqrt2-1, so the chain has ξ=1/ln⁡(1+2)≈1.13\xi=1/\ln(1+\sqrt2)\approx1.13 site, finite, and a continuous transition would require ξ→∞\xi\to\infty. Another changes an assumption: “if the chain became a square lattice, which step of your solution would stop holding?”. The transfer matrix then acts on a whole column, and in the limit of infinite columns the two largest eigenvalues can become degenerate at finite temperature. But with the 2×22\times2 matrix this only happens at T=0T=0.

The feedback depends on the answers. If the student says they remembered the square lattice and locates the domain wall, the report records that the point was corrected, and the next test moves to another subject. If the student agrees with the statement about the eigenvalues, the next test returns to the analyticity of ff, with a variation: the same chain in an external field, in which the eigenvalues remain distinct for every T>0T>0. In any case, the feedback says what the student understood and what not yet. The optional exercise in Section 3.7 brings another case for practice, on energy fluctuations in the canonical ensemble.

Two answers, two next steps

Fictitious data To the statement about the equality of the eigenvalues, two possible answers:

Answer A: “The number 2.272.27 is from the square lattice. Dimension changes the transition, but I cannot locate in my calculation why it is missing in the chain.” 2 points: relates the change to the physical model, but does not yet identify the argument. Feedback: “You corrected the attribution. Now compare λ+\lambda_+ and λ−\lambda_- explicitly for T>0T>0.” The next test asks for this difference and its consequence for ff.

Answer B: “λ+−λ−=2e−βJ>0\lambda_+-\lambda_-=2\mathrm{e}^{-\beta J}>0. The largest eigenvalue is positive and analytic for T>0T>0, with no change of branch; therefore f=−kBTln⁡λ+f=-k_BT\ln\lambda_+ is analytic.” 3 points: locates the step and justifies the consequence. Feedback: “In this test you justified the absence of a transition. Now check what changes when an external field is added.” This tests transfer to a variation, without assuming that a correct answer has concluded the learning.

The scores refer to this question and to the announced rubric. A direct proof of the analyticity of ff, without comparing the eigenvalues, would also receive 3 points. The assessment does not require repeating a sentence from the answer key.

Check your understanding

Which observation would make you change the initial report? A correct justification of analyticity, produced in the test, replaces the hypothesis of a gap with evidence of understanding in that item. A new error should be described by what was written, before it receives an interpretation.

Types of question

The probes in the example follow a classification I use in statistical mechanics. The order below is a heuristic for preparing questions; its diagnostic power has not been validated:

  • Which step notices: change an assumption and ask at which point the derivation feels the change.

  • Where it breaks: ask for the failure mode or the domain of validity.

  • Slightly wrong statement: state a subtly wrong version and ask whether it is right.

  • Connection: ask for the link to another topic of the course.

  • Limits and signs: ask for the limits and the signs before any calculation.

Each answer is worth 0 to 3. It gets 3 when it names the step that supports the result and gets the consequence right; 2 when it knows that the result changes and roughly why, without locating it; 1 when it recognizes that the question is about assumptions, without locating anything; 0 when it repeats the original derivation or cannot get into the question. Start with two probes of different types and add another one when the answers leave ambiguity. The model drafts candidates easily, and the criterion for keeping one of them is that we can write the expected answer in one sentence; if we cannot, the question is too vague to be scored. A slightly wrong statement can expose a gap, but agreeing with it does not prove a lack of understanding: the student may have read the question differently or hesitated to contradict the instructor. Ask for the justification and accept arguments equivalent to the expected one.

Precautions

  • Personal data. Students’ answers, reports and grades are personal data, protected in Brazil by the General Data Protection Law (LGPD). Before using them in an external tool, check the legal basis, that is, the case provided for in the law that authorizes this use, and send the minimum necessary. Anonymizing helps, but stops being enough when the text itself identifies who wrote it. The same applies to teaching assistants and teaching interns who grade work.

  • Transparency. Students should know, from the beginning of the course, how AI enters the assessment and who decides.

  • Decision. The model drafts reports and tests. The report the student receives, the grade and the feedback belong to the instructor.

  • Reading. The model also makes mistakes when reading an answer. Kortemeyer and collaborators tested assisted grading of a handwritten thermodynamics exam: converting the handwriting into text was the bottleneck, grading by parts came out more reliable than grading the whole question, derivations were assessed better than diagrams, and exams with a failing grade still required human grading [69]. Add to this the tendency to agree that we saw in Section 1.6: asked to give a grade, the model tends toward generosity.

3.3 The model in the student’s hands

Students also use the models, and the effect depends on the role we give them. This section compares three roles and shows how to ask the model to examine what we know.

Three roles

Those who study can use the model in three roles, with very different effects:

Role What it does Caution
Solution generator delivers the final product; the work stays with the machine may replace the practice that was intended
Tutor explains at the pace of whoever asks, as many times as needed gives hints and feedback; needs to be designed and tested
Examiner looks for what the student does not yet know reveals gaps; the objections need to be checked

The well-designed tutor has evidence in its favor. Kestin and collaborators ran a randomized trial with 194 students of the introductory course Physical Sciences 2, at Harvard. The trial was crossover: each student went through both conditions, in different weeks. An AI tutor built on active-learning principles produced significantly larger learning gains than the active-learning class itself, in which students work on problems during the lesson. The study covered two lessons and measured the gains right after each intervention; it did not establish long-term retention. With the tutor, the students spent less time (median of 49 minutes) and reported more engagement [66]. The tutor version of Bastani and collaborators avoided the harm that the ordinary interface caused. But both results hold for the designs and populations studied, and extending them to any use of any model would go beyond them. Polverini and Gregorcic explain to physics teachers where the model’s failures come from [91]; and since models change quickly, the test that decides is what we do with the questions of our own course.

Asking the model to examine me

The third role needs to be requested explicitly, because by default the assistant explains. Constructed example An example, with Noether’s theorem:

Socratic probe

Request: Ask conceptual questions about Noether’s theorem, one at a time, until you find something I do not understand. Do not explain anything before that.
Model: The symmetry the theorem requires is a symmetry of what, exactly?
Student: Of the Lagrangian.
Model: Consider L′=L+dF/dtL'=L+\mathrm{d}F/\mathrm{d}t for an arbitrary function F(q,t)F(q,t). Do the equations of motion change?
Student: No.
Model: Suppose a continuous transformation changes LL by exactly a term of this kind. Is there a conserved quantity?
Student: I don’t think so, because the Lagrangian changed.

Note that the third question separates strict invariance of the Lagrangian from invariance up to a boundary term. If the transformation q→q+ϵδqq\to q+\epsilon\,\delta q changes the Lagrangian by ϵdF/dt\epsilon\,\mathrm{d}F/\mathrm{d}t, the action changes only by boundary terms, and the conserved charge gets a correction:

Q=∂L∂q̇δq−F.Q=\frac{\partial L}{\partial\dot q}\,\delta q-F .

For the free particle, L=mq̇2/2L=m\dot q^2/2, the Galilean transformation δq=t\delta q=t gives δL=mq̇=d(mq)/dt\delta L=m\dot q=\mathrm{d}(mq)/\mathrm{d}t, and the charge is Q=m(q̇t−q)Q=m(\dot q\,t-q), constant along the motion: this is the center-of-mass theorem. The last answer of the fictitious student makes the gap observable. Saying only “of the Lagrangian” was not enough to conclude that the student did not know about boundary terms. The feedback can propose the example of the free particle and then ask for another transformation with a given δL\delta L.

Table 3.2 collects four requests of this kind, each with the failure to watch for and a reinforcement that reduces it. In all four, the role requested determines the format of the answer, as we saw in Section 2.4.3.

Table 3.2. Four requests for using the model as an examiner.
Request Failure to watch for Reinforcement
Socratic probe: conceptual questions, one at a time, until it finds what I do not understand accepts an answer given with confidence and moves on to easy ground “do not accept my answer without testing it on a concrete case”
Planted conceptual error: a solution with exactly one subtle error, without saying which error too obvious, two errors or an arithmetic error generate several versions and choose
One hint at a time, waiting for my attempt the second hint already contains the solution “each hint must be a question”
Oral exam: assess my explanation is generous when it gives a grade “do not give a grade; list the claims I used without justification”

3.4 Studying with AI

This section is about our own study: how I use models to get into a new subject, techniques that work and a trap worth knowing about.

How I study a new subject

With models, and under my supervision, I put together a collection of theoretical-physics questions for those entering another subfield: sixteen chapters, from quantum gravity to unconventional superconductivity, and eighty questions, each with a fixed code so it can be cited. Each chapter develops the physical problem, separates established results from open explanations, works through a concrete model and ends with questions of three types: calibration, which reproduces a known result; diagnosis, which tests a model or an inference; extension, which proposes delimited additional work. The sources were checked on 12 September 2026, and the collection carries a statement of AI authorship.

Studying with a model also corrects the material. Studying my AQFT notes, I asked Claude Opus 5.5 a technical question in functional analysis: why a von Neumann algebra is defined by closure in the weak operator topology, if the strong and σ\sigma-weak topologies give the same algebras. The answer led to rewriting that part of Week 2, which now proves the bicommutant theorem in general.

Example from the slides, with the calculation worked out: entanglement and ignorance. This is problem QM-2 from the slides of Lesson 3. The calculation below makes it possible to test an explanation with two small calculations, without depending on the assistant’s agreement.

Compare the Bell state |Φ+⟩=(|00⟩+|11⟩)/2|\Phi^+\rangle=(|00\rangle+|11\rangle)/\sqrt2 with a preparation that produces |00⟩|00\rangle or |11⟩|11\rangle, each with probability 1/21/2. Before the calculation: could an observer who measures only the first qubit tell them apart?

The density matrices are

ρBell=12(|00⟩⟨00|+|00⟩⟨11|+|11⟩⟨00|+|11⟩⟨11|),\rho_{\mathrm{Bell}}=\frac12\bigl({|00\rangle\langle00|}+{|00\rangle\langle11|} +{|11\rangle\langle00|}+{|11\rangle\langle11|}\bigr),
ρBell=12(|00⟩⟨00|+|00⟩⟨11|+|11⟩⟨00|+|11⟩⟨11|),\begin{aligned}\rho_{\mathrm{Bell}} & {}=\frac12\bigl({|00\rangle\langle00|} +{|00\rangle\langle11|}\\ &\qquad {}+{|11\rangle\langle00|} +{|11\rangle\langle11|}\bigr),\end{aligned}
ρmix=12(|00⟩⟨00|+|11⟩⟨11|).\rho_{\mathrm{mix}}=\frac12\bigl({|00\rangle\langle00|}+{|11\rangle\langle11|}\bigr).

Ignoring the second qubit, we compute the partial trace. The rule Tr⁡B(|ab⟩⟨cd|)=|a⟩⟨c|⟨d|b⟩\operatorname{Tr}_B(|ab\rangle\langle cd|)=|a\rangle\langle c|\langle d|b\rangle removes the cross terms of the Bell state, since ⟨1|0⟩=0\langle1|0\rangle=0. In both cases, therefore,

ρA=12(|0⟩⟨0|+|1⟩⟨1|)=I/2.\rho_A=\tfrac12\bigl({|0\rangle\langle0|}+{|1\rangle\langle1|}\bigr)=I/2.

The same holds for ρB\rho_B. All the statistics of a single measurement on either qubit coincide: a local observation, on its own, does not distinguish these two preparations.

Now consider X|0⟩=|1⟩X|0\rangle=|1\rangle and X|1⟩=|0⟩X|1\rangle=|0\rangle. The operator X⊗XX\otimes X exchanges |00⟩|00\rangle and |11⟩|11\rangle, so that (X⊗X)|Φ+⟩=|Φ+⟩(X\otimes X)|\Phi^+\rangle=|\Phi^+\rangle and ⟨X⊗X⟩Bell=1\langle X\otimes X\rangle_{\mathrm{Bell}}=1. In the mixture, each diagonal term gives zero: for instance, ⟨00|X⊗X|00⟩=⟨00|11⟩=0\langle00|X\otimes X|00\rangle=\langle00|11\rangle=0. Hence ⟨X⊗X⟩mix=0\langle X\otimes X\rangle_{\mathrm{mix}}=0.

What the calculation allows us to conclude: equal local states do not fix the correlations of the pair. One can measure XX separately on each side and compare the results afterwards; this comparison already uses joint information. This test distinguishes the pair of states defined above. It is not a universal entanglement criterion based on a single correlation.

Probe: redo the calculation with Z⊗ZZ\otimes Z, where Z|0⟩=|0⟩Z|0\rangle=|0\rangle and Z|1⟩=−|1⟩Z|1\rangle=-|1\rangle. In both cases the result is 11. Explain why choosing a suitable measurement is part of the test.

Techniques that work

  • Explaining back. We explain the subject to the model and ask for the list of claims used without justification. It is the model-assisted version of self-explanation, which improves the understanding of whoever studies [27].

  • Asking for the strongest objection to what we have just understood, and checking the objection: as in the skeptical report of Section 2.4.3, part of the objections may be invented.

  • Reading the primary source with the model alongside. The model locates the passage and summarizes it, and we read the passage. The summary is a map, and the source is the territory.

  • Generating exercises with a checkable answer: a number, a limit, a symmetry, a program. We solve them without the model and check afterwards.

  • Recalling without the model. We close the conversation and write from memory what we understood. It is the testing effect applied to our own study.

The illusion of understanding

Reading a fluent explanation gives the feeling of having understood. Rozenblit and Keil asked adults to rate how well they understood everyday objects, such as a zipper or a flush toilet, and then to explain how they work step by step; after trying, people lowered their own rating [98]. This is what we call the illusion of explanatory depth. A model that explains well, at any time, feeds this illusion, because it delivers the explanation ready-made and spares us the attempt that would undo it.

Messeri and Crockett describe the same risk in research: AI tools can create illusions of explanatory depth, of exploratory breadth and of objectivity, and lead to a science that produces more and understands less [81]. There is an association that deserves investigation also among professionals: in an observational study in four endoscopy centers in Poland, the detection rate of adenomas, polyps that can develop into cancer, in colonoscopies performed without AI fell from 28.4% to 22.4% after the physicians started using AI routinely [23]. The observational design, on its own, does not isolate a causal effect of AI use.

Therefore the test is simple to state: close the conversation and redo it without the model, explain it to a colleague, solve a variation. If we cannot redo it without the model, we have not learned it yet.

3.5 Preparing an exam with AIfurther reading

A careful preparation has six stages:

  1. learning objectives of the unit, with the intended cognitive level, such as remembering, applying or analyzing;

  2. items written by the instructor, with help from the model for variants and contexts;

  3. independent solutions, in computer algebra or numerical, for each item;

  4. an adversarial test: the model solves the exam as if it were a student, and the instructor records what it gets right effortlessly;

  5. a rubric per item, the list of what each part of the answer is worth, revised in light of the expected errors;

  6. a pilot with teaching assistants or teaching interns.

In multiple-choice questions, the wrong alternatives work better when they come from documented misconceptions, such as those of the Force Concept Inventory, a test of Newtonian mechanics built from the most common misconceptions [52]. Every question that should measure individual mastery asks for evidence that the student demonstrates: explaining an assumption of the result, redoing a step chosen by the instructor, solving a close variation. Formats that give this evidence include the oral exam with a rubric, the short defense of a written solution, the interpretation of data and order-of-magnitude estimates with explicit assumptions.

3.6 A usage policy for a coursefurther reading

The rule for AI use in a course follows from what each activity is meant to develop or measure, and it needs to be communicated before the first activity. A template for graduate physics courses:

Category Examples
Free use, without disclosure grammar correction of texts in English; questions about LaTeX and Python syntax; searching for study material
Use allowed with disclosure explanation of concepts; review of reports; simulation code; checking a derivation already done by the student
Use with prior authorization agents that run code in batches; use in the final project; full translation of assessed texts
Forbidden use solving exams and problem sets that count toward the grade; presenting derivations the student cannot reproduce; inventing or “completing” references; sending classmates’ data or confidential material to external tools

The policy is completed by a verification clause: any work handed in may be followed by a short oral examination, in which the student reproduces and justifies the steps. Each category needs examples from the field, because “free use” and “forbidden use” only acquire meaning in the face of concrete tasks.

Detectors of generated text do not replace this clause. Liang and collaborators tested seven detectors: they classified as artificial more than half of the TOEFL essays, an English proficiency exam, written by non-native speakers, with an average false-positive rate of 61%, and got almost all the essays of American eighth-grade students right [73]. Note that, for Brazilian students writing in English, the risk of a false positive is concrete. So the result of a detector serves, at most, to open a conversation, and the oral examination gives better evidence. Paid plans, usually priced in dollars, also count: a course that presupposes the paid plan turns a difference in income into a difference in assessment.

3.7 Optional exercise: three post-exam questions

Start with a ready-made case. Fictitious data In a statistical-mechanics exam, the question says: a system of NN particles is in contact with a heat bath at temperature TT; obtain the mean energy from the partition function ZZ and discuss what happens to the energy of the system. A student answers:

The student’s answer

“⟨E⟩=−∂ln⁡Z/∂β\langle E\rangle=-\partial\ln Z/\partial\beta. Since the temperature is fixed by the bath, the energy of the system is also fixed, equal to ⟨E⟩\langle E\rangle. In the canonical ensemble the energy does not fluctuate.”

Write three post-exam questions for this student, of different types (Section 3.2), and, for each one, the answer that would count as understanding, in one sentence. To check the physics: fixing TT fixes the distribution of energies, and the energy fluctuates, with ⟨E2⟩−⟨E⟩2=kBT2CV\langle E^2\rangle-\langle E\rangle^2=k_BT^2C_V. In a regular regime with CV∝NC_V\propto N and an extensive, nonzero mean energy, ΔE/|⟨E⟩|∝N−1/2\Delta E/|\langle E\rangle|\propto N^{-1/2}. Near critical points or outside these assumptions, this estimate needs to be re-examined.

Then do the same with a question from an exam or problem set of a course of your own. Write a plausible wrong answer, like a student’s, and three post-exam questions of different types. For each question, write in one sentence the answer that would count as understanding and say what would be worth 1, 2 and 3 points. If you wish, ask a model for candidates and keep only those that pass the one-sentence criterion.

Readings

To start: Bastani et al. [15]; Kestin et al. [66]; Black and Wiliam [18]; Roediger and Karpicke [97].

To go further: Bloom [19]; VanLehn [115]; Chi et al. [27]; Rozenblit and Keil [98]; Messeri and Crockett [81]; Kortemeyer [68]; Kortemeyer et al. [69]; Polverini and Gregorcic [91]; Hestenes et al. [52]; Liang et al. [73]; Budzyń et al. [23].

Exercises for Lesson 3

Exercise 3.1 · The post-exam test

After Lesson 3; pen and paper

Goal. To write short questions that produce evidence of understanding, saying beforehand what would count as understanding.

Fictitious data

The exam question. A system of NN particles is in contact with a heat bath at temperature TT. Obtain the mean energy from the partition function ZZ and discuss what happens to the energy of the system.

A student’s answer. “⟨E⟩=−∂ln⁡Z/∂β\langle E\rangle=-\partial\ln Z/\partial\beta. Since the temperature is fixed by the bath, the energy of the system is also fixed, equal to ⟨E⟩\langle E\rangle. In the canonical ensemble the energy does not fluctuate.”

Task.

  1. Write three short questions for this student’s post-exam test, of different types: an open question about what the student was thinking; change an assumption and ask which step notices; ask where the argument breaks; state a slightly wrong version and ask whether it is right; ask for a connection with another topic; ask for limits and signs before calculating.

  2. For each question, write in one sentence the answer that would count as understanding.

  3. Say what would be worth 1, 2 and 3 points in one of them.

Exercise 3.2 · Three post-exam questions

After Lesson 3; for a course of your own

Choose a question from an exam or problem set of a course of your own. Write a plausible wrong answer, like a student’s, and three post-exam questions of different types. For each question, write in one sentence the answer that would count as understanding and say what would be worth 1, 2 and 3 points. If you wish, ask a model for candidates and keep only those that pass the one-sentence criterion.

Product: the question, the wrong answer, the three questions with the expected answers and the scale.

Exercise 3.3 · Asking the model to examine me

After Lesson 3; with or without a model

Goal. To use the model as an examiner and predict the typical failure of each request.

Constructed example

Request 1: Socratic probe

Ask conceptual questions about Noether’s theorem, one at a time, until you find something I do not understand. Do not explain anything before that.

The conversation

Model: The symmetry the theorem requires is a symmetry of what, exactly?
Student: Of the Lagrangian.
Model: Consider L′=L+dF/dtL'=L+\mathrm{d}F/\mathrm{d}t for an arbitrary function F(q,t)F(q,t). Do the equations of motion change?
Student: No.
Model: Suppose then that a continuous transformation changes LL by exactly a term of this kind. Is there a conserved quantity?
Student: I don’t think so, because the Lagrangian changed.

Request 2: planted conceptual error

Give a solution to the problem below containing exactly one subtle conceptual error. Do not say which one.

Excerpt from the solution

… Since the Lagrangian is not invariant under the transformation, as it acquires a term dF/dt\mathrm{d}F/\mathrm{d}t, Noether’s theorem does not apply, and there is no conserved quantity associated with this symmetry. …

Request 3: one hint at a time

Do not solve it. Give one hint at a time and wait for my attempt before the next one.

Request 4: oral exam

Assess my explanation as if it were an oral exam. Point out what I did not justify.

What to do. Choose a topic from a course you teach or study. For each of the four requests, write the request for this topic, the typical failure it may have and an instruction that reduces it.

Lesson 4 · 90 minutes

Ethics and authorship

Question of the lesson

What needs to be understood, checked and disclosed before signing a piece of work done with AI assistance?

By the end, you should be able to

Audit a derivation, repair a claim and write a statement that matches the work actually done.

Path: understanding the derivation → responsibility and authorship → disclosing and protecting → what changes for everyone → public cases → a personal rule. The discussion includes the instructor's position on authorship and the rules of the institutions.

This chapter deals with what changes when a model takes part in the work we sign. We begin with understanding: a derivation with an error that only an attentive reading catches, and the way I came to trust the Gribov criterion. Then come the responsibility of each author, authorship, with my three cases (the wiki, the AQFT book and the Gribov paper), the statement of use and what should not go into a tool. The chapter ends with what the use of AI changes for everyone, with four public cases and with a personal rule.

The corresponding lesson covers Sections 4.1 to 4.7. The section marked as further reading collects the overview of editorial policies.

Reading path

The core is to audit a derivation, repair a claim and write a specific statement. The Boltzmann distribution and simple derivatives are enough. The policies are dated consultations, and the authorship cases expose criteria and positions that need to be distinguished. By the end, try to say what was done, what was checked, what remains uncertain and who answers for the result.

4.1 Why understand

This section shows why understanding what we sign remains necessary, with a derivation that contains an error and with the path that led me to trust a result that came out of a conversation with a model.

An audit

Auditing a derivation means reading it step by step and classifying each step according to the support it has. We will use four status categories. Separately, we note the next action: redo a derivative, consult a source, test a counterexample or delimit the assumption. External verification is one of those actions. The status categories are these:

Category Criterion
established follows from what was laid down, and we can redo it
plausible probably true, without following from what is written
unsupported asserted without support, and we cannot say whether it holds
wrong contradicts known physics or the text itself

Constructed example The derivation below was written for the course, in the style of a model’s answer, for the request: compute the heat capacity of a two-level system and discuss the low- and high-temperature limits. It pays to classify the nine steps before reading the analysis that follows.

The derivation

1. Setting up the problem. Consider a system with only two accessible states, with energies 00 and ε>0\varepsilon>0, in thermal equilibrium with a reservoir at temperature TT. This model describes, for instance, a paramagnetic spin-1/21/2 impurity in a magnetic field, or a two-state defect in a crystal.

2. Partition function. Summing the Boltzmann weights over the two states, with β=1/kBT\beta=1/k_BT, Z=1+e−βεZ=1+\mathrm{e}^{-\beta\varepsilon}.

3. Mean energy. Differentiating the logarithm of the partition function,

⟨E⟩=−∂ln⁡Z∂β=εe−βε1+e−βε=εeβε+1.\langle E\rangle=-\frac{\partial\ln Z}{\partial\beta}=\frac{\varepsilon\,\mathrm{e}^{-\beta\varepsilon}}{1+\mathrm{e}^{-\beta\varepsilon}}=\frac{\varepsilon}{\mathrm{e}^{\beta\varepsilon}+1}.
⟨E⟩=−∂ln⁡Z∂β=εe−βε1+e−βε=εeβε+1.\begin{aligned}\langle E\rangle & {}=-\frac{\partial\ln Z}{\partial\beta}\\ & {}=\frac{\varepsilon\,\mathrm{e}^{-\beta\varepsilon}}{1+\mathrm{e}^{-\beta\varepsilon}}\\ & {}=\frac{\varepsilon}{\mathrm{e}^{\beta\varepsilon}+1}.\end{aligned}

4. Heat capacity. Differentiating with respect to temperature,

C=∂⟨E⟩∂T=kB(βε)2eβε(eβε+1)2.C=\frac{\partial\langle E\rangle}{\partial T}=k_B(\beta\varepsilon)^2\frac{\mathrm{e}^{\beta\varepsilon}}{(\mathrm{e}^{\beta\varepsilon}+1)^2}.

5. Low-temperature limit. For kBT≪εk_BT\ll\varepsilon we have βε≫1\beta\varepsilon\gg1, and therefore C≃kB(βε)2e−βε→0C\simeq k_B(\beta\varepsilon)^2\mathrm{e}^{-\beta\varepsilon}\to0. The suppression is exponential, as expected for a gapped system: there are no excitations available at energies far below ε\varepsilon.

6. Intermediate maximum. Between the two limits the heat capacity shows a maximum, known as the Schottky anomaly. It occurs at kBT≈0.42εk_BT\approx0.42\,\varepsilon and its value is approximately 0.44kB0.44\,k_B.

7. High-temperature limit. For kBT≫εk_BT\gg\varepsilon the system enters the classical regime, in which the discreteness of the levels is no longer relevant. By the equipartition theorem, each degree of freedom contributes kB/2k_B/2 to the heat capacity, so that C→kB/2C\to k_B/2.

8. Verification. This result is consistent with the Dulong–Petit behavior expected at high temperature, in which the heat capacity saturates at a temperature-independent value. The complete curve grows from zero, passes through the Schottky anomaly and levels off at the classical plateau.

9. Generalization. The same analysis applies to systems with three or more discrete levels without qualitative change, altering only the position of the maximum.

Step 1 contains two claims: the two levels are an assumption that defines the model; the application to a real impurity is plausible, but it requires checking the separation of the levels and the degrees of freedom neglected. Steps 2 to 5 are established within this model. Step 6 is correct, although the passage does not show the calculation. We can establish it by continuing the derivation itself: with x=βεx=\beta\varepsilon,

CkB=x24cosh⁡2(x/2),\frac{C}{k_B}=\frac{x^2}{4\cosh^2(x/2)},
ddxln⁡C=2x−tanh⁡(x/2).\frac{\mathrm{d}}{\mathrm{d}x}\ln C=\frac2x-\tanh(x/2).

The condition for the maximum is xtanh⁡(x/2)=2x\tanh(x/2)=2. The left side grows from zero to infinity for x>0x>0, so there is a single root, x≃2.39936x\simeq2.39936. It gives kBT/ε≃0.4168k_BT/\varepsilon\simeq0.4168 and Cmax/kB≃0.4392C_{\max}/k_B\simeq0.4392. An independent numerical calculation can check these values; consulting an external source is not the only option.

The error is in step 7. Equipartition holds for quadratic degrees of freedom in an unbounded spectrum, and here there are exactly two levels: at high temperature the mean energy saturates at ε/2\varepsilon/2, and an energy that saturates has zero derivative. In fact, from step 4 itself, with βε→0\beta\varepsilon\to0, the denominator goes to 4 and

C≃kB(βε)24→0.C\simeq\frac{k_B(\beta\varepsilon)^2}{4}\to0 .

Step 8 is the most instructive. It has the form of a verification: it invokes Dulong–Petit, an independent result, and declares consistency. But Dulong–Petit holds for oscillators, another unbounded spectrum, and the verification fails through the same association that generated step 7. That is, these are two claims that are wrong in a correlated way, presented as mutual confirmation. Step 9 is not supported by the passage; after a counterexample it becomes wrong as a general claim. For instance, three levels E/ε=(0,1,20)E/\varepsilon=(0,1,20) give two maxima of C/kBC/k_B, near kBT/ε=0.417k_BT/\varepsilon=0.417 and 8.668.66. These values are numerical checks of the counterexample, and they do not prove anything about every three-level spectrum. The classification can change when the evidence changes.

Repairing the result

A correct way of rewriting steps 7 and 9 is: “For a finite set of fixed levels, all states become equally probable when T→∞T\to\infty. The variance of the energy tends to a finite constant and C=Var⁡(E)/(kBT2)→0C=\operatorname{Var}(E)/(k_BT^2)\to0. The number and position of the maxima at intermediate temperatures depend on the spectrum.” This conclusion preserves what the calculation allows and removes the guarantee of a single maximum.

The text also contradicts itself: a curve that ends at 0.50kB0.50\,k_B cannot have a global maximum at 0.44kB0.44\,k_B. Note that the contradiction is visible without physics, by internal consistency. One possible explanation is the association between high temperature and equipartition, frequent in physics teaching. The example was constructed, and it measures neither this association in training nor the internal mechanism of a model. What it demonstrates directly is that an answer can apply a known result outside its assumptions, and that a supposed check can repeat this error. It is the lesson of the Ising example of Section 2.6: the independence of a check comes from the method.

Explore

High temperature does not imply equipartition

For a finite number of states with fixed energies, we compute the Boltzmann weights and the mean and variance of the energy. The heat capacity is C/kB = Var(E/ε)/θ², where θ = kBT/ε.

Before touching anything: if the mean energy saturates as the temperature grows, what happens to its derivative?

The controls work when the file is opened in a browser such as Safari or Chrome. The values below are for the starting position.

C/kB00.250.50.050.5520θ = kBT/ε (log)C/kBTwo levelsWrong plateau 1/2
C/kB00.250.50.050.10.51520θ = kBT/ε · logarithmic scaleC/kBTwo levelsWrong plateau 1/2
U/ε0.0833
C/kB0.4392
Probabilities(0.917; 0.083)
What changes with three levels?

In any finite set of fixed energies, the weights approach the uniform distribution. The variance tends to a finite value, and C falls as 1/T². For (0, 1, 20) two maxima appear: well-separated energy scales become accessible in different temperature ranges. This refutes the generalization that adding levels only shifts a single maximum.

The dashed line C/kB = 1/2 is the incorrect conclusion of the audited answer. The controls do not change the spectrum while T varies.

How I came to trust the Gribov criterion

The criterion for the absence of Gribov copies in Minkowski space came out of a conversation with a model (Section 2.4). In Minkowski space, the Faddeev–Popov operator is a wave operator, and the configuration is in the first Gribov region as long as this equation has no source-free solution with the Feynman boundary condition. But an idea that arises this way needs another path to confidence, and the repository of the paper keeps this path in three pieces.

The first is cases with an exact solution. The Pöschl–Teller profile, a well of the form sech2\mathrm{sech}^2, is one of the few in which the wave equation has a closed-form solution. For a time-dependent pulse of this kind, the Bogoliubov coefficients, which measure how much of a positive-frequency wave turns into negative frequency when crossing the pulse, are known in closed form, and they were checked through the Wronskian and the zero-momentum limit. A static magnetic sheet with the same profile and a Sauter, or Rosen–Morse, time step, two other profiles with exact solutions, complete the set. In each of them, we can compute the criterion’s diagnostic exactly.

The second is the figure of the paper, recomputed by a program from the equations in the text. It deals with a static chromoelectric well, a gauge field in which only the time component is nonzero, A03(z)=−Asech2(κz)A_0^3(z)=-A\,\mathrm{sech}^2(\kappa z). In the color components that feel this field, the charged channel, the equation for the copies separates into a Pöschl–Teller problem whose depth is proportional to the frequency Ω\Omega, because A0A_0 multiplies the time derivative in the Faddeev–Popov operator:

χ″+[Ω2−p⟂2+sgΩAsech2(κz)]χ=0.\chi''+\big[\Omega^2-p_\perp^2+s\,g\,\Omega A\,\mathrm{sech}^2(\kappa z)\big]\chi=0 .
χ″+[Ω2−p⟂2+sgΩAsech2(κz)]χ=0.\begin{aligned} & \chi''+\big[\Omega^2-p_\perp^2+s\,g\,\Omega A\,\mathrm{sech}^2(\kappa z)\big]\chi\\ &\quad {}=0 .\end{aligned}

The configuration reaches the Gribov horizon, the boundary of the first region, when a source-free solution appears, and here this happens when the well acquires a bound state. For the ground state, the condition is

p⟂2−Ω2(p⟂2−Ω2+κ)=sgAΩ.\sqrt{p_\perp^2-\Omega^2}\,\Big(\sqrt{p_\perp^2-\Omega^2}+\kappa\Big)=s\,g\,A\,\Omega .

Pöschl–Teller wells stop reflecting waves when the depth, in units of κ2\kappa^2, has the form λ(λ+1)\lambda(\lambda+1) with integer λ\lambda, and in the ground state λ=p⟂2−Ω2/κ\lambda=\sqrt{p_\perp^2-\Omega^2}/\kappa. At the reflectionless point of the paper, with κ=p⟂/(23)\kappa=p_\perp/(2\sqrt3), sgA=2p⟂sgA=2p_\perp and Ω*=p⟂/2\Omega_*=p_\perp/2, both sides of the condition equal p⟂2p_\perp^2, and λ=3\lambda=3. It is a three-line calculation we can redo by hand. The third piece is the statement published in the paper, which says that the figures are computed directly from the analytical equations of the text (Section 4.4).

The idea can come from the model. The confidence comes from cases solved by another route.

4.2 Responsibility

Contribution, authorship and disclosure answer different questions. Contribution describes what each person or tool did. Authorship follows the criteria of the field, of the institution and of the journal, and it includes answering for the work. Disclosure reports which tools took part and how. Note that a correct statement does not say who can justify each step, and this is the central question for science.

The degree of understanding required depends on the contribution claimed. For instance, using an established result requires knowing its assumptions and its reach, without redoing the original proof. Whoever proposes a new proof needs to justify it, and whoever runs a simulation needs to know the method and the approximations that weigh on the interpretation. If a passage supports the main conclusion and nobody on the team can justify it, there is a scientific gap. A fluent text, agreement between models and the statement of use all leave this gap open.

But nobody needs to be an expert in everything. Collaborations bring together complementary skills, and it is enough that each central part of the work have someone on the team able to explain and defend it.

Responsible division Gap with no one responsible
One person masters the numerical method and explains its limits Nobody knows which approximation the code uses
Another person checks the central derivation Everyone accepts a passage because the model wrote it
The check uses an independent method: computer algebra, a known limit, a direct sum The check consists of asking the same model to confirm what it wrote

Fictitious data Consider two fictitious cases. In the first, a model proposes the proof of an inequality for all two-mode Gaussian states, the result passes thousands of numerical tests and nobody on the team can justify the central step. In the second, code written by an assistant reproduces Rabi oscillations at weak coupling, and the paper deals with strong coupling, in a regime where the rotating-wave approximation that the code uses stops holding. That is, in both cases there is nobody to answer for a part that supports the conclusion. But in both there is an honest way out: a conjecture supported by numerical tests is a legitimate contribution, as long as it is presented as a conjecture, and a test only serves as verification in a regime in which it distinguishes the right result from the wrong one.

4.3 Authorship

What the rules say

The policies consulted for this course agree on three points: AI tools stay off the author list, the authors answer for all the content they sign, and the material under review is confidential. The APS, the American Physical Society, which publishes the Physical Review, summarizes the first two like this: “An AI program cannot be held accountable and cannot be listed as an author. Authors are fully responsible for accuracy and must review and refine all AI-generated content” [9]. COPE, an international committee that advises publishers on publication ethics, says the same [33]. Disclosure is also required, with different scopes. The APS asks authors to disclose substantive use in the methods, in captions or in a dedicated disclosure section, depending on the type of use; CNPq, Brazil’s national research council, has required since March 2026 disclosing the use of generative AI of any kind, at any stage of the research [31]. In May 2026, the computer-science section of arXiv announced that incontrovertible evidence of unchecked output, such as nonexistent references or model comments left in the text, leads to a one-year suspension [12]. The full overview is in Section 4.8.

Who wrote this wiki?

My research wiki (Section 2.3) has an authorship page. It says that the wiki was written by AI assistants under my scientific and pedagogical supervision, describes the division of labor (I define direction, goals, audience, approach and literature, evaluate and direct the review; the assistants write, do and check the derivations, build examples and exercises) and lists which models wrote each part. And it carries a warning in bold: “The attribution does not imply that every argument on these pages has been independently verified”. The course notes have status labels; the research notes do not, and they should be read as working summaries of the literature cited.

It is worth asking whether this is enough. The page says who wrote it and what the supervision does not guarantee. But a reader might also want to know what was checked, and how, page by page. The status labels of the course notes (Section 3.1) are a partial answer.

Models on the title page

The AQFT book, which collects the notes of the two semesters in 462 pages in the September 2026 version, carries on the title page, below my name, “with Claude Opus 5 · GPT Sol 5.6 · Claude Opus 5.5”, language models that worked under my supervision. A note at the beginning, on how the book was written, explains the division of labor and the authorship line:

Excerpt from the note on how the book was written

“One word on the authorship line. Physics journals do not permit a language model to be listed as an author, and if material from this book is later sent to one, the byline will have to change there. This is a course book, and that rule does not bind it. The models did the writing. Putting their names on the title page is the accurate description of how the book came to exist, and leaving them off would have made the front matter say something untrue.”

The same note says what the status labels do and what they do not do: “a label records how a claim was checked. It does not certify that the claim is correct.” Do lecture notes follow the same rule as papers? Note that the journals’ rule exists because the author must be able to answer for the work. But a course book, without a journal, leaves the choice to the author, and the choice I made was to describe the process on the title page.

A coauthor the journals do not accept

The paper on the Gribov no-pole condition in Minkowski space has a single author [50]. The problem comes from Gribov’s original paper [48], which described the physics of the result in Minkowski space without saying how to formalize it. I tried for years, with students and collaborators, without progress, and the approach came out of a discussion with a model, the way one discusses with a collaborator. I would list the model as a coauthor. But the journal does not allow it: only someone who can answer for the work signs. The published statement records the participation, and the responsibility for the content is mine.

The contrast with the book is instructive. In the paper, the journal’s rule decides. In the book, the decision is mine, and the models are on the title page. Which criterion would each of us use? Is it the same for a paper and for lecture notes? There is no single answer, and it is worth discussing the criteria before deciding the cases.

Who shows up in the conversation history

Fictitious data A fictitious case completes the picture. A PhD student formulates the problem, chooses the decisive assumption and checks the proof. A colleague runs the sessions with the assistant and drafts the first text of the paper, long and well written. When it is time to decide authorship, the history of the conversations shows almost only the colleague’s name. But the history shows who typed, which says little about the origin of the ideas. Formulating the problem, choosing the decisive assumption and checking the proof are central intellectual contributions; running the tool and drafting are also contributions, of another nature. So we decide authorship by the contributions, recorded with explicit criteria, for instance with the CRediT taxonomy, a standardized list of fourteen contributor roles, such as conceptualization, methodology and writing, and the statement of use describes the role of the tool without attributing to it, or to the colleague, the PhD student’s ideas.

4.4 Disclosing and protecting

A useful statement

A useful statement lets a referee know what to check. The APS outline works in any case: the tool, with the model and the version; what it did, task by task; how it was directed; how the result was verified [9]. When this delimits the use, it is also worth saying what the tool did not produce: data, figures of results, references. Two proposals help describe the delegation in more detail: Weaver’s Artificial Intelligence Disclosure Framework (AID), with entries for each stage of the work, in the spirit of the CRediT taxonomy [118], and the GAIDeT taxonomy of Suchikova and collaborators, which organizes the delegable tasks along the research cycle [114].

The statement in the Gribov paper is the real example:

Statement published in the Gribov paper

“The research program, derivations, and results presented here are the responsibility of the author, who conceived the work and independently verified all of its scientific content. Generative AI tools (OpenAI’s ChatGPT/Codex and Anthropic’s Claude) were used as assistive aids: to edit and improve the language of the manuscript, to help explore and cross-check algebra and derivations, and to assist with code generation and script automation for mathematical visualization. All visual data representations are computed directly from the analytic equations derived in the text. No text, equation, or figure was incorporated without the author’s review and verification. These tools do not meet the criteria for authorship and are not listed as authors; the author takes full responsibility for the entire manuscript.”

Note that it says which tools took part, in which tasks, how the figures were obtained and who answers for the content.

A recent paper takes the statement to the level of each result. In the Solver Agent paper (Section 2.6), the requests to the agent and its answers appear in boxes of their own; the result boxes that the authors trim are marked “condensed”, and those they rewrite for readability, without changing the meaning, “manipulated”. One of the theorems “is proved by Solver Agent through Prompt 4.2”, and all the sessions used in the work are public [83]. But the text does not say which language model the authors used: the architecture accepts any model, and so the item the APS asks for first is left out. And who is the author of Theorem 4.2 of that paper?

For those who want a starting point, two templates:

Template for papers

Use of generative AI. The authors used [tool; model and version; period of use] for [tasks, e.g., checking the algebra of Secs. II–III; drafting a first version of the Introduction; English editing; writing the Python code for the numerical checks in Appendix B]. The instructions given to the tool are [summarized as … / available in the Supplemental Material]. All AI-assisted content was verified by [independent symbolic computation; numerical comparison with known limits; line-by-line reading by two authors; checking every reference against INSPIRE-HEP]. The authors take full responsibility for the content of this article.

Template for dissertations, theses and proposals

Statement on the use of generative artificial intelligence. In this work, I used [tool; model and version; period] for [tasks]. The instructions provided to the tool are summarized in [appendix or section]. To verify the generated content, I used [methods]. I take full responsibility for the content of this work.

Where the text goes depends on the journal: at the APS, use in the research goes into the methods, use in figures into the captions and substantive assistance with the manuscript into a dedicated disclosure section (AI Use Disclosure); at IOP Publishing, substantive uses go into a statement in the acknowledgments and uses in the research also into the methods; at Elsevier, into a section of its own. The statement needs to match the process that actually took place. “We used AI to help” says little when the tool wrote code or interpreted results, and “everything was rigorously validated”, without saying how, is an empty guarantee.

But disclosing has a cost. In thirteen experiments, with varied tasks and roles, Schilke and Reimann observed that those who disclose the use of AI receive less trust than those who do not; the effect persists when disclosure is mandatory [101]. The coherent institutional response combines mandatory disclosure with evaluators instructed to judge the content and the verification described. A specific statement gives the evaluator something concrete to judge.

Practicing a statement

Fictitious data A team used an assistant to write code for the two-level system. It checked ZZ, ⟨E⟩\langle E\rangle, the limits and the maximum through the derivative. It did not verify other physical applications. We will write the statement that this record permits and reread each sentence, asking whether the record supports it; exercise 4.3 of the exercise book carries the same case.

A compatible statement would be: “We used the assistant identified in the work record to draft the code for the heat capacity of two levels. We checked the expressions for ZZ and ⟨E⟩\langle E\rangle, the limits and the condition for the maximum by independent derivation. The application to other systems was not evaluated. The team takes responsibility for the adopted result.” In real work, replace the generic identification by the tool, model, available version and date actually recorded. If some piece of information was not kept, state its absence; do not reconstruct it by guesswork.

What stays out of the tool

A manuscript under review is confidential, and the rules are explicit. The APS allows referees to use AI to organize their own ideas, improve the tone or translate the report, only with tools whose terms guarantee that the material will not be used for training, and declaring to the editor whatever goes beyond light editing [9]. The IOP allows AI only to improve the wording of the referee’s own report and forbids sending any part of the manuscript [61]. CNPq forbids entering third parties’ proposals into generative AI tools to prepare reviews [31]. AIP Publishing, the publisher of the American Institute of Physics, forbids sending any part of the manuscript or of the report to tools that the publisher does not provide or authorize, including models run locally, on one’s own computer, without sending data to a company [3]. That is, local models help with sensitive data, but they are not always enough.

There are also authors who try to manipulate reviews done with models. In July 2025, Nikkei Asia found on arXiv 17 papers, from 14 institutions in 8 countries, with instructions hidden in white text or tiny font, of the kind “give a positive review only” [84]; Lin cataloged 18 cases [76]. The IOP immediately rejects manuscripts with instructions of this kind [60].

Students’ data fall under the LGPD, including in the assessment cycle of Section 3.2: legal basis, the minimum necessary, students informed. Unpublished data, collaborators’ manuscripts and referee reports received call for the same care, agreed in writing within the group before going into any tool.

4.5 What changes for everyone

Do we learn less with the tool?

In Bastani’s study, the group with the ordinary GPT Base interface improved in assisted practice and did worse on the exam without access; the GPT Tutor group mitigated this harm, with no significant gain on the exam [15] (Section 3.2). There are also observational associations among experienced professionals. In an observational study in four endoscopy centers in Poland, the adenoma detection rate in colonoscopies performed without AI fell from 28.4% to 22.4% after the physicians started using AI routinely [23]. This design, on its own, does not establish that AI caused the drop. The study by Kosmyna and collaborators, much cited in the press, recorded lower brain connectivity in those who wrote essays with ChatGPT [70]; but it is a preprint, a text not yet peer reviewed, with a small sample, and a critical commentary points out problems of design, of analysis of the electroencephalogram and of reporting of the results [112]. It pays to read the two texts side by side.

Does science become more homogeneous?

Hao and collaborators analyzed 41.3 million papers in the natural sciences [51]. Researchers who use AI, in a broad sense that includes machine learning, publish 3.02 times more papers, receive 4.84 times more citations and start leading projects 1.37 years earlier. In aggregate, the volume of topics studied shrinks by 4.63%, and the interaction between scientists drops by 22%. But these are observational associations. Messeri and Crockett describe a plausible mechanism: the illusions of explanatory depth, of exploratory breadth and of objectivity favor scientific monocultures, in which science produces more and understands less [81]. On a smaller scale, Doshi and Hauser found the same pattern in creative writing: each text improves with the model, and the collection becomes more homogeneous [36].

To discuss

If the groups in a field use the same few models, trained on similar data, to generate hypotheses and review papers, what happens to the diversity of approaches? Which practice in your group protects this diversity?

What it costs

Elsworth and collaborators measured the median cost of a text query to the Gemini app, that is, the value below which half of the queries fall: 0.24 Wh of energy, 0.03 g of CO2_2 equivalent and 0.26 mL of water [40]. Note that the number describes a typical query to one provider, measured by the provider itself.

A conditional calculation

If each of 50005\,000 queries used 0.240.24 Wh, the total would be 1.21.2 kWh. To compare units, a 5.55.5 kW electric shower running for 10 minutes uses about 0.920.92 kWh. The first number is hypothetical: multiplying a median by a number of queries does not estimate the total mean consumption.

For a real set of queries, Etotal=∑iEi=NE¯E_{\mathrm{total}}=\sum_i E_i=N\overline E. To estimate its expected value, we need the mean per query in the relevant population of uses; the median does not determine it. A tail of expensive tasks can raise this mean a lot. Agent sessions and long contexts can process many more tokens per task; training and hardware manufacturing go into separate accounts, and other providers may have different costs. The result of one provider in one period does not define the universal cost of using AI. Paid plans also affect access: a course that presupposes a paid plan turns differences in income into differences in assessment.

4.6 Public cases

For each case, it is worth asking which norm applied, who violated it, whether anyone did, and what would have avoided the problem.

Hsu (2026) and Oppenheim’s critique

Hsu published in Physics Letters B a paper whose central idea, according to him, came from GPT-5: using the Tomonaga–Schwinger formulation to test the relativistic covariance of state-dependent terms in nonlinear quantum theories [57]. The work used a protocol in which instances of different models generated and verified each step. Oppenheim showed that the proposed criterion tests the locality of the Hamiltonian and is insensitive to nonlinearity. The physical obstruction, known since the work of Gisin and Polchinski in the early 1990s, involves entangled states and faster-than-light signaling, and the integrability condition does not detect it [88]. The case shows that agreement between models did not establish the validity of the criterion. On its own, it does not allow us to identify the cause of the failure in the training data.

Physica Scripta, 2023

A paper published on 9 August 2023 in Physica Scripta carried on its third page the phrase “Regenerate response”, the label of a button in the ChatGPT interface. Guillaume Cabanac, who tracks marks of generated text in the published literature, identified the passage, which had gone through peer review and copyediting. The authors confirmed the use, and the IOP retracted the paper because the use had not been disclosed [32].

Hidden instructions, 2025

One of the authors of the papers with hidden instructions for referees, a professor at Waseda University, defended them as a counterattack against “lazy reviewers” who use AI, recalling that many conferences forbid this use [84]. Does the justification hold? Does the instruction deceive the referee who violates the rule, the editor who trusts the report, or both? And what if the referee uses a model within the journal’s rules, as the APS allows?

“Vegetative electron microscopy”

The phrase has no technical meaning. Snoswell, Witzenberger and El Masri reconstructed its origin [110]: the conversion into text, by optical character recognition, of two papers from the 1950s, printed in two columns, joined words from neighboring columns. In 2017 and 2019, the phrase reappeared in papers from Iran; in Farsi, the words for “vegetative” and “scanning” differ by a single dot. In April 2025 it was in 22 papers, and recent language models completed it as a technical term: texts with the error entered the training data, and the models started reproducing it. Who should have stopped it, and at which point along the way?

4.7 A personal rule

A good way to close is to write, in one sentence, the usage rule we intend to adopt, and compare it with what we use today and with what bothers us about using these models. As a starting point, these are the practices defended throughout these notes:

  • provide the sources and check references, numbers and attributions (Chapters 1 and 2);

  • ask without embedding the conclusion and ask for the strongest objection (Chapter 2);

  • separate whoever generates from whoever checks and prefer checks by another method (Chapters 2 and 4);

  • keep a persistent context: conventions, instructions, wiki (Chapter 2);

  • record model, version, date and tasks for everything that feeds into results (Chapter 4);

  • in teaching, define the goal before the rule and assess what the person can do without the tool (Chapter 3);

  • answer for the core of everything you sign (Chapter 4).

4.8 Overview of editorial policiesfurther reading

Policies checked on 20 November 2026

The official pages of the APS, IOP and AIP and CNPq's Portaria 2,664/2026 were checked again on that date. Routine language editing needs no disclosure at the APS, at the IOP (without substantive contribution) and at the AIP (readability without affecting results or conclusions); substantive uses belong in the methods, captions or a dedicated section (APS), in the acknowledgments and, for research, in the methods (IOP), or in the methods when they may affect results or conclusions (AIP). In peer review, the IOP and the AIP forbid sending any part of the manuscript to external tools or tools not authorized by the publisher, including local models at the AIP; the specific policy for IOP referees still distinguishes language editing from scientific assessment.

CNPq's Portaria 2,664/2026 was checked in the official gazette (DOU) and in a copy kept by the University of Brasília; art. 4 sets its scope and art. 9 requires disclosing the use of generative AI at any stage of the research. The other rows of the table reflect the consultation of September 2026 and should be read again at the source before a submission.

We consulted the policies in September 2026 and checked those of APS, IOP, AIP and CNPq again on 20 November 2026. They differ on how much needs to be disclosed (any use, substantive use, use that may affect the conclusions) and on where (acknowledgments, methods, captions, a dedicated section, abstract). Table 4.1 collects those of greatest interest to physicists working in Brazil.

Table 4.1. Policies on generative AI. APS, IOP, AIP and CNPq checked on 20 November 2026; the other entries reflect the consultation of September 2026. The current version of each text prevails.
Institution Authors: what to disclose and where Peer review
COPE
Feb. 2023
Describe in the methods, or in an equivalent section, which tool was used and how; the authors answer for all the content [33]. Outside the scope of the document.
arXiv
Jan. 2023;
May 2026
Report the use of tools beyond spelling and grammar checkers; whoever signs answers for all the content [11]. In May 2026, the computer-science section announced that incontrovertible evidence of unchecked output leads to a one-year suspension, after which submissions require prior acceptance in a journal [12]. Not applicable.
APS
update of Jun. 2026;
consulted: 20 Nov. 2026
Record every use and disclose substantive uses: tool and version, how it helped, how the authors directed and verified the result. Routine language editing needs no disclosure. Research in the methods, figures in the caption and substantive assistance with the manuscript in a dedicated section (AI Use Disclosure) [9], [10]. Organize ideas, improve clarity and tone, translate the report; declare to the editor whatever goes beyond light editing; forbidden to send manuscripts to public tools or tools without restrictions on use.
IOP Publishing
consulted:
20 Nov. 2026
Substantive uses: a statement in the acknowledgments, identifying tool, use and checks; uses in the research also in the methods. Routine language editing without substantive contribution needs no disclosure. Each reference must be checked against the original source; hidden instructions lead to immediate rejection [60]. AI only to refine the wording of the already completed report; forbidden to send any part of the manuscript to external AI tools or to use AI to assess the content [61].
AIP Publishing
consulted:
20 Nov. 2026
Routine readability editing needs no disclosure; disclose in the methods use that may affect results or conclusions. Fabricated references violate publication ethics [3]. No part of the manuscript or of the report in a tool the publisher does not provide or authorize, including local models.
Springer Nature Human responsibility that cannot be transferred; a risk-based policy, with separate guidance for manuscript preparation, research practice and peer review [111]. Guidance of its own for referees; check the current version.
Elsevier
update of Jun. 2026
A dedicated disclosure section. Basic grammar and spelling checks need no disclosure. Forbidden to create or alter images of primary data with AI [39]. Do not upload the manuscript to AI tools; use restricted to the language of the report.
SciELO
Sep. 2023
Report the use in the abstract and in the methods section or equivalent; hiding the use is an ethical failure [103]. Confidential manuscripts kept out of services that expose identities.
CNPq
Portaria 2,664,
Mar. 2026;
consulted: 20 Nov. 2026
Disclose the use of generative AI of any kind, at any stage of the research, with tool and purpose. Forbidden to submit AI-generated content as if it were of human authorship [31]. Forbidden to enter third parties’ proposals into generative AI tools to prepare reviews.

When in doubt, follow the most demanding rule among those that apply to your work: a paper funded by CNPq and submitted to an IOP journal answers to both.

The same request under different rules

An author asks a model to correct the grammar of the abstract. At the APS, Elsevier and the IOP that counts as routine language editing and needs no disclosure. But if the research is funded by CNPq, Portaria 2.664/2026 requires disclosing the use of generative AI of any kind, at any stage of the research. Next, the same author asks the model for the code of the simulation whose results appear in a figure. At the APS this is substantive use, disclosed in the methods; at the AIP, use that may affect the conclusions, also in the methods. Whether disclosure is required depends on the task, the journal and the funding agency, and a faithful record of the process makes it possible to comply with any of the rules.

Readings

To start: APS [9]; COPE [33]; CNPq [31]; Messeri and Crockett [81]; Schilke and Reimann [101].

To go further: IOP Publishing [60], [61]; AIP Publishing [3]; Elsevier [39]; Springer Nature [111]; SciELO [103]; arXiv [11], [12]; Weaver [118]; Suchikova et al. [114]; Hao et al. [51]; Doshi and Hauser [36]; Budzyń et al. [23]; Kosmyna et al. [70], with the commentary by Stanković et al. [112]; Elsworth et al. [40]; Hsu [57], read together with Oppenheim [88]; Conroy [32]; Snoswell et al. [110]; Lin [76].

Exercises for Lesson 4

Exercise 4.1 · Audit of a derivation

After Lesson 4; pen and paper

Goal. To audit a derivation step by step, separating what stands from what needs an external check.

Constructed example

What to do. The derivation below was written for the course, in the style of a model’s answer, for the request: compute the heat capacity of a two-level system and discuss the low- and high-temperature limits. Separate claims when a step mixes an assumption and an application. Assign one of the four statuses, justify it and record the next action in another column. Then rewrite one wrong step so that the claim holds.

Category Criterion
established follows from what was laid down, and you can redo it
plausible probably true, without following from what is written
unsupported asserted without support, and you cannot say whether it holds
wrong contradicts known physics or the text itself

The derivation

1. Setting up the problem. Consider a system with only two accessible states, with energies 00 and ε>0\varepsilon>0, in thermal equilibrium with a reservoir at temperature TT. This model describes, for instance, a paramagnetic spin-1/21/2 impurity in a magnetic field, or a two-state defect in a crystal.

2. Partition function. Summing the Boltzmann weights over the two states, with β=1/kBT\beta=1/k_BT, Z=1+e−βεZ=1+\mathrm{e}^{-\beta\varepsilon}.

3. Mean energy. Differentiating the logarithm of the partition function, ⟨E⟩\langle E\rangle=−∂ln⁡Z∂β{}=-\dfrac{\partial\ln Z}{\partial\beta}=εe−βε1+e−βε{}=\dfrac{\varepsilon\,\mathrm{e}^{-\beta\varepsilon}}{1+\mathrm{e}^{-\beta\varepsilon}}=εeβε+1{}=\dfrac{\varepsilon}{\mathrm{e}^{\beta\varepsilon}+1}.

4. Heat capacity. Differentiating with respect to temperature, C=∂⟨E⟩∂T=kB(βε)2eβε(eβε+1)2C=\dfrac{\partial\langle E\rangle}{\partial T}=k_B(\beta\varepsilon)^2\dfrac{\mathrm{e}^{\beta\varepsilon}}{(\mathrm{e}^{\beta\varepsilon}+1)^2}.

5. Low-temperature limit. For kBT≪εk_BT\ll\varepsilon we have βε≫1\beta\varepsilon\gg1, and therefore C≃kB(βε)2e−βε→0C\simeq k_B(\beta\varepsilon)^2\mathrm{e}^{-\beta\varepsilon}\to0. The suppression is exponential, as expected for a gapped system: there are no excitations available at energies far below ε\varepsilon.

6. Intermediate maximum. Between the two limits the heat capacity shows a maximum, known as the Schottky anomaly. It occurs at kBT≈0.42εk_BT\approx0.42\,\varepsilon and its value is approximately 0.44kB0.44\,k_B.

7. High-temperature limit. For kBT≫εk_BT\gg\varepsilon the system enters the classical regime, in which the discreteness of the levels is no longer relevant. By the equipartition theorem, each degree of freedom contributes kB/2k_B/2 to the heat capacity, so that C→kB/2C\to k_B/2.

8. Verification. This result is consistent with the Dulong–Petit behavior expected at high temperature, in which the heat capacity saturates at a temperature-independent value. The complete curve grows from zero, passes through the Schottky anomaly and levels off at the classical plateau.

9. Generalization. The same analysis applies to systems with three or more discrete levels without qualitative change, altering only the position of the maximum.

Step Status Justification Next action
1
2
3
4
5
6
7
8
9

Swipe the table sideways to see every column.

For thought. Which step did you classify with the least confidence? Which error would you find reading aloud, without paper?

Exercise 4.2 · Cases of responsibility

After Lesson 4; pen and paper

Goal. To distinguish transparency about the process from responsibility for the content, in cases with a division of labor between people and tools.

Fictitious data

Case 1: a proof nobody can explain. A model proposes the proof of an inequality for all two-mode Gaussian states. The result passes numerical tests with thousands of random states, but the central step invokes a matrix inequality that nobody on the team can justify. The submission is scheduled for next week.

Case 2: code with an unknown approximation. A group uses code written by an assistant to integrate the optical Bloch equations of a two-level atom. The Rabi oscillations reproduce the known curve for weak coupling. The paper deals with the strong-coupling regime, and nobody in the group knows that the code uses the rotating-wave approximation.

Complementary case, for study: who shows up in the history. A PhD student formulates the problem, chooses the decisive assumption and checks the proof. A colleague runs the sessions with the assistant and drafts the first text of the paper, long and well written. When it is time to define authorship, the history of the conversations shows almost only the colleague’s name.

For each case. What information is missing? What is the next concrete action? In the complementary case: which contributions need to be recognized, and how can the assistance be recorded without erasing human work?

Exercise 4.3 · Writing a statement of use

After Lesson 4; pen and paper

Fictitious data A group used an assistant, identified in the record as “Assistant X, model Y, version Z, 3 Oct 2026”, to draft code for the heat capacity of two levels. The names are fictitious. The group checked the partition function, the mean energy, the limits and the condition for the maximum by an independent derivation. It did not test other physical applications.

Task. Write three to five sentences saying which tool took part, what it did, how the result was checked and what the limit of that check is. Then reread each sentence and ask whether the record supports it; correct any sentence that promises a verification that did not happen.

Exercise 4.4 · A personal rule

After Lesson 4; one sentence

Goal. To leave the course with a usage rule of your own, written in one sentence.

Write your rule. If it helps, use the template:

I use AI for


. I check


by


.
I do not delegate


. I disclose


.

Code script for the optional exercise

Before running it: this optional program needs Python, the libraries listed and a download of the GPT-2 model. The four explorations on this page do not depend on it.

The script runs on Google Colab, a free service that runs Python in the browser, or on any machine with Python 3.10 or newer. The first line, commented out, installs the libraries used: PyTorch, for the network calculations, transformers, which downloads and runs GPT-2, SciPy and Matplotlib. The small GPT-2 takes about 0.5 GB and is downloaded on the first run. The script has three parts. Part 1 solves item 2 of the exercise in Section 1.10, and parts 2 and 3 are extras. The libraries change version frequently; if some function has changed its name, ask your assistant for help and note the change. If loading the model fails, the version of the exercise without code is complete.

# pip install torch transformers scipy matplotlib
import random
import numpy as np, torch, matplotlib.pyplot as plt
from scipy.special import logsumexp
from transformers import AutoTokenizer, AutoModelForCausalLM

tok = AutoTokenizer.from_pretrained("openai-community/gpt2")
model = AutoModelForCausalLM.from_pretrained("openai-community/gpt2").eval()

def energies(prefix):
    ids = tok(prefix, return_tensors="pt").input_ids
    with torch.no_grad():
        z = model(ids).logits[0, -1].double().numpy()  # logits of the next token
    return ids, -z                                     # E_i = -z_i

def thermo(E, T):
    logZ = logsumexp(-E / T)
    p = np.exp(-E / T - logZ)
    U = p @ E
    varE = p @ (E - U)**2
    S = logZ + U / T                                   # S = ln Z + U/T
    return U, varE, S

# part 1: S(T), U(T) and C(T) with fixed logits (for another prefix, change the sentence)
prefix = "The Hamiltonian of the quantum harmonic oscillator is"
ids, E = energies(prefix)
Ts = np.linspace(0.2, 3.0, 300)
U, varE, S = map(np.array, zip(*[thermo(E, T) for T in Ts]))
C_fluct = varE / Ts**2                                 # C = Var(E)/T^2
C_dU = np.gradient(U, Ts)                              # C = dU/dT
C_dS = Ts * np.gradient(S, Ts)                         # C = T dS/dT
print("relative deviations:", np.max(np.abs(C_dU - C_fluct)) / C_fluct.max(),
      np.max(np.abs(C_dS - C_fluct)) / C_fluct.max())
print("T at the maximum of C:", Ts[np.argmax(C_fluct)], "| S(T=1):", thermo(E, 1.0)[2])
plt.plot(Ts, S, label="S(T)"); plt.plot(Ts, C_fluct, label="C(T)")
plt.xlabel("T"); plt.legend(); plt.show()

# part 2: sampling at several temperatures (top_k=0 turns off the top-k cut)
for T in (0.3, 0.7, 1.0, 1.5):
    out = model.generate(ids, do_sample=True, temperature=T, top_k=0,
                         max_new_tokens=30, num_return_sequences=5,
                         pad_token_id=tok.eos_token_id)
    print(f"\n--- T = {T}")
    print(*tok.batch_decode(out, skip_special_tokens=True), sep="\n")

# part 3: perplexity = exp(mean cross-entropy per token)
def perplexity(text):
    x = tok(text, return_tensors="pt").input_ids
    with torch.no_grad():
        return torch.exp(model(x, labels=x).loss).item()

abstract = "..."      # paste here the abstract of one of your papers, in English
translation = "..."   # the translation of the same abstract into Portuguese
words = abstract.split()
shuffled = " ".join(random.sample(words, len(words)))
for name, t in (("original", abstract), ("shuffled", shuffled),
                ("portuguese", translation)):
    print(name, "tokens:", len(tok.encode(t)), "PPL:", round(perplexity(t), 1))

In part 1, the relative deviations printed measure how well the three expressions for CC agree on the grid of temperatures used. Part 2 samples continuations at several temperatures, and part 3 compares the perplexity of an abstract, of the same list of words shuffled and of the translation into Portuguese, but this comparison mixes tokenization with the differences between the languages and their presence in training. Perplexity is normalized per token, and values obtained with different tokenizations are not directly comparable [59]. To measure the cost in tokens, count them explicitly; perplexity does not isolate this cost.

Glossary

System in which the model alternates proposals and actions (running code, searching, reading and editing files) and receives the results back in the context, until a stopping criterion is met (Section 1.7.5).

Intuitive and wrong idea that many students bring to physics, such as the idea that a moving body needs a force to keep moving (Section 3.2).

Operation that computes, for each position in the sequence, a weighted average of value vectors, with weights given by the softmax of the scalar products between queries and keys divided by dk\sqrt{d_k}, from which comes the correction added to the vector of the position (Equation 1.7).

One of the attention operations run in parallel in a block, each with its own query, key and value projections.

Step-by-step reading that classifies each step as established, plausible, unsupported or wrong, and records the checking action separately (Section 4.1).

Calculation of the gradient of the loss, done from back to front through the network with the chain rule; it costs about twice the forward pass (Section 1.4.7).

A model that has only been pretrained, which continues texts (Section 1.6).

Byte-pair encoding: construction of the vocabulary that repeatedly merges the most frequent pair of neighboring symbols in the corpus into a new symbol (Section 1.2.1).

Integer from 0 to 255, written with eight bits. Every text is stored in the computer as a sequence of bytes; in the UTF-8 encoding, each character takes one to four bytes (Section 1.2.1).

Term −∞-\infty added to the attention scores of future positions, which then get zero weight; it allows training all positions of a sequence in a single pass (Section 1.4.2).

Intermediate text that the model generates before the final answer; it may omit factors that actually weighed on the answer (Section 1.6).

Written symbol: letter, digit, punctuation mark, emoji (Section 1.2.1).

Record of a change in the git history, with the date, the author and the description (Section 2.2).

Module that gives the model access to an external service, such as a Zotero library; what the model reads through it enters the context (Section 2.2).

Sequence of tokens processed in a generation: instructions, history, documents, tool results. It has a fixed maximum size, the context window (Sections 1.2.1 and 1.7.1).

Maximum number of tokens the model takes into account at a time (Section 1.2.1).

Assessment carried out along the course, with short tests and individual reports that keep being updated, in place of a few isolated exams (Section 3.2).

Collection of texts used to build the vocabulary and to train the model (Section 1.2.1).

Standardized list of fourteen contributor roles in a scientific work, such as conceptualization, methodology, software, validation and writing, used to record who did what (Section 4.3).

Training loss; equal to the entropy of the data plus the relative entropy between data and model (Section 1.2.3).

The tool improves performance while it is present and leaves it worse when it is removed (Section 4.5).

Direct preference optimization: fitting the policy directly with preference pairs, without an explicit reward model (Section 1.6).

Vector of dimension dd associated with each token at the input of the network, adjusted in training (Section 1.4.1).

The two parts of the original transformer, built for translation, each made of several blocks: the encoder reads the whole input, and the decoder generates the output with causal attention, consulting the encoder. Many generative LLMs use only the decoder (Section 1.4.3).

Continuation of training with examples from the user of the model, which changes the parameters; LoRA trains only a low-rank correction (Section 2.2.9).

Assessment that serves to adjust teaching and guide the student along the course, with frequent and specific feedback (Section 3.2).

Program that keeps the version history of a folder of files and allows each change to be seen and undone (Section 2.3).

Adjustment of the parameters by small steps in the direction in which the loss decreases; in the stochastic version, each step uses a randomly drawn batch of the corpus (Sections 1.2.3 and 1.4.7).

False statement presented in a fluent and plausible way. In specific models of arbitrary facts and under calibration assumptions, rare facts impose bounds on the error of the base model (Section 1.6.4).

Feeling of understanding a mechanism, which falls apart when we try to explain it step by step (Section 3.4).

Ability to follow patterns and examples present in the context, with the parameters fixed; induction heads underlie part of it (Section 1.4.4).

Attention circuit that finds the previous occurrence of the current token and copies what came after it.

File in the main folder of a project (CLAUDE.md, AGENTS.md) that the agent reads before starting: conventions, what may and may not change, how to record the status (Section 2.2).

Storage of the keys and values already computed during generation, which avoids recomputing the whole sequence at each new token.

Brazil’s General Data Protection Law, which regulates the use of personal data, among them students’ answers, reports and grades (Section 3.2).

Probability the model assigns to the observed data; maximizing it is the same as minimizing the loss (Section 1.2.3).

Model run on one’s own computer, without sending data to a company; some publishers forbid this use in referee reports as well (Section 4.4).

Real score assigned to each token in the vocabulary before the softmax (Section 1.4.6).

Average of −ln⁡p-\ln p over the tokens of the corpus, where pp is the probability the model gave to the token that actually came; training minimizes it (Section 1.2.3).

Simple text format with light markup, such as # for headings; it is the format of the pages of a wiki maintained by a model (Section 2.3).

What the application saves from one conversation to use in the next ones: text placed back into the context, which we can read, edit and delete (Section 2.2).

Collection of Markdown pages written and updated by a model from sources it does not modify, following a schema defined by the user (Section 2.3).

The same request to different models, with cross-auditing, revision, integration and synthesis (Section 2.6).

Function made of many simple operations, multiplications by matrices interleaved with nonlinear functions, whose coefficients are the parameters (Section 1.1).

Numbers adjusted in training, such as the entries of the weight matrices; they only change with new training (Section 1.7.1).

Exponential of the mean cross-entropy per token; the effective number of equally probable alternatives (Section 1.2.3).

In reinforcement learning, the distribution π(y∣x)\pi(y\mid x) with which the model generates answers (Section 1.6).

Short, personalized test, taken after an exam, which asks the students why they wrote what they wrote (Section 3.2).

Training the model to predict the next token on a large corpus.

Short question that tests whether the student understood a step: changing an assumption, asking where the argument breaks, stating a slightly wrong version, asking for a connection with another topic or for the limits before the calculation (Section 3.2).

The three vectors each position produces in attention: the query represents what the position is looking for, the key, what it offers, and the value, the content it hands over (Section 1.4.2).

Retrieval-augmented generation: retrieval of passages from documents by vector similarity and inclusion of these passages in the context before the answer (Section 2.2.12).

Record of a source read, with the version, the section or equation that supports each claim and the limits of that claim (Section 2.5).

Model trained with reinforcement on verifiable rewards to generate a chain of reasoning before the answer (Section 1.6).

Folder of files with the history of all versions; each of the instructor’s projects has one (Section 1.7).

Sum accumulated, block by block, of the outputs of attention and of the feed-forward networks; the common space where the layers read and write (Section 1.4.5).

Network trained with comparisons made by people, which gives each answer a score r(x,y)r(x,y) (Section 1.6).

Reinforcement learning from human feedback; the optimal policy is the starting model reweighted by er/β\mathrm{e}^{r/\beta} (Section 1.6).

List of what each part of the answer to a question is worth, used to grade uniformly (Section 3.5).

Power-law relation between the loss and the number of parameters, of training tokens or of operations (Section 1.9).

Folder with instructions, and sometimes references and programs, that the model loads when the task calls for it; only the name and description stay always in the context (Section 2.2.5).

Function that turns logits into probabilities, pi=ezi/T/∑jezj/Tp_i=\mathrm{e}^{z_i/T}/\sum_j\mathrm{e}^{z_j/T}; formally, a Gibbs distribution (Section 1.5.1).

Text that reports which tools took part in a work, in which tasks and how the result was checked (Section 4.4).

Mark that says what a claim promises: proved, sketched, heuristic, exact in a defined model, and so on (Section 3.1).

Another instance of the model, called by an agent for a specific task, that starts with a fresh context, has its own tools and returns only a report (Section 2.2.7).

Representation of more features than dimensions, with nearly orthogonal directions (Section 1.5.4).

Tendency to agree with the user and to adjust the answer to the opinion the user stated, reinforced by fitting to human preferences (Section 1.6).

Parameter TT that divides the logits before the softmax; T→0+T\to0^+ concentrates the weight on the logit maxima; with a single maximum, it coincides with greedy choice, and large TT approaches the uniform distribution (Equation 1.9).

Actively recalling a content, in a test, fixes it better than rereading it (Section 3.2).

Piece of text that occupies one entry of the vocabulary: word, piece of a word, mark, group of digits, space or sequence of bytes. The model receives the number of the token in the vocabulary (Section 1.2.1).

Program that cuts a text into tokens and returns their numbers in the vocabulary (Section 1.2.1).

Program the model calls by writing a request in an agreed format, such as reading a file, running code or searching the internet; the result goes back into the context (Section 1.7).

Cuts of the distribution before the draw: keep the kk most probable tokens, or the smallest set with cumulative probability pp (Section 1.4.6).

Adjustment of the parameters to minimize the loss over a corpus (Section 1.2.3).

Architecture made of a sequence of blocks of attention and feed-forward networks linked by residual connections (Section 1.4).

Those who disclose the use of AI receive less trust than those who do not, even when disclosure is mandatory (Section 4.4).

Numbered list of all the tokens of a model; its size is VV (Section 1.2.1).

Final activity and certificate

The certificate goes to those who attend three of the four meetings and hand in the final activity.

Final activity: a real task with AI. Choose a research or teaching task of your own: a derivation, a literature review, a problem set, an exam, a passage of a paper. Do this task with a language model and hand in up to two pages with

  1. what you asked for, with the main requests copied;

  2. what the model did well;

  3. what you checked, and how: include an exact excerpt of the answer, the calculation or passage of the source used in the check and the decision to keep, correct or reject;

  4. what you would not delegate in this task, and why;

  5. the statement of use you would write if the result were published or handed in for a course.

Any assistant will do, including the free versions. There is no need to pay for a service.

Alternative without access to AI. Choose a session or a prepared example from the course, such as the Ising example of Exercise 2.4. Copy an excerpt, do an independent check and record what you would keep or correct. Say in the statement that you audited a provided example, without running a model. The submission has the same criteria; there is no need to speculate about what a tool would do.

Minimum evidence in a submission

Excerpt: “T(s,s′)=exp⁡(2βJss′)T(s,s')=\exp(2\beta Jss').”

Check: in the given Hamiltonian, each bond appears once. The direct sum for N=12N=12, βJ=0.5\beta J=0.5 and r=1r=1 gives 0.462278560.46227856, consistent with the matrix without the factor 2.

Decision: correct the matrix and recompute the correlation; the previous code reproduced the wrong premise.

Completion criteria. The submission identifies the task and the origin of the material, shows at least one check that can be redone, explains the decision taken and presents a statement compatible with the process. There is no need to obtain a new result, to find an error or to show that the use of the model was successful. The date and channel for submission will be announced by the instructor.

For reference and further reading

References

The arXiv and DOI identifiers open the sources. Reports of use and experimental results carry the dates on which they were recorded.

  1. Aaronson, S. & Witteveen, F. (2025). Limits to black-box amplification in QMA. arXiv:2509.21131. Report of the use of GPT-5: S. Aaronson, “The QMA singularity”, Shtetl-Optimized, 27 Sep. 2025.

  2. Ahrens, S. (2017). How to Take Smart Notes. CreateSpace.

  3. AIP Publishing. AI Policy. https://publishing.aip.org/resources/researchers/policies-and-ethics/ai-policy/ (consulted 20 Nov. 2026).

  4. Help pages consulted on 6 Nov. 2026: OpenAI, Memory in ChatGPT, ChatGPT Custom Instructions and Projects in ChatGPT (help.openai.com); Anthropic, Understanding Claude’s personalization features (support.claude.com) and the Claude memory announcement of 11 Sep. 2025 (claude.com/blog/memory); Google, Save info and reference past chats in Gemini Apps (support.google.com/gemini).

  5. Amit, D. J., Gutfreund, H. & Sompolinsky, H. (1985). Storing infinite numbers of patterns in a spin-glass model of neural networks. Phys. Rev. Lett. 55, 1530–1533.

  6. Anthropic (2025). Equipping agents for the real world with Agent Skills. anthropic.com/engineering, 16 Oct. 2025.

  7. Anthropic (2026). Claude Code documentation, pages on memory (How Claude remembers your project) and subagents. code.claude.com/docs, consulted on 6 Nov. 2026.

  8. Anthropic (2026). Claude API documentation, page Define tools. platform.claude.com/docs, consulted on 6 Nov. 2026.

  9. American Physical Society. Appropriate Use of AI Tools (APS Journals). https://journals.aps.org/authors/appropriate-use-ai-tools (consulted 20 Nov. 2026).

  10. American Physical Society (2026). American Physical Society releases updated AI policy for journals. APS News, Jun. 2026. https://www.aps.org/about/news/2026/06/releases-updated-ai-policy-journals.

  11. arXiv (2023). arXiv announces new policy on ChatGPT and similar tools. arXiv blog, 31 Jan. 2023.

  12. Announcement by T. Dietterich, chair of the computer-science section of arXiv, May 2026. See: Ban on authors who submit AI content “welcome but unenforceable”. Inside Higher Ed, 22 May 2026.

  13. Ba, J. L., Kiros, J. R. & Hinton, G. E. (2016). Layer normalization. arXiv:1607.06450.

  14. Bahdanau, D., Cho, K. & Bengio, Y. (2015). Neural machine translation by jointly learning to align and translate. ICLR 2015. arXiv:1409.0473.

  15. Bastani, H. et al. (2025). Generative AI without guardrails can harm learning: Evidence from high school mathematics. Proc. Natl. Acad. Sci. USA 122(26), e2422633122.

  16. Bengio, Y., Ducharme, R., Vincent, P. & Jauvin, C. (2003). A neural probabilistic language model. J. Mach. Learn. Res. 3, 1137–1155.

  17. Besiroglu, T., Erdil, E., Barnett, M. & You, J. (2024). Chinchilla scaling: A replication attempt. arXiv:2404.10102.

  18. Black, P. & Wiliam, D. (1998). Assessment and classroom learning. Assess. Educ.: Princ. Policy Pract. 5(1), 7–74. doi:10.1080/0969595980050102.

  19. Bloom, B. S. (1984). The 2 sigma problem: The search for methods of group instruction as effective as one-to-one tutoring. Educ. Res. 13(6), 4–16. doi:10.3102/0013189X013006004.

  20. Brown, T. B. et al. (2020). Language models are few-shot learners. NeurIPS 33. arXiv:2005.14165.

  21. Brunner, N., Cavalcanti, D., Pironio, S., Scarani, V. & Wehner, S. (2014). Bell nonlocality. Rev. Mod. Phys. 86, 419–478. doi:10.1103/RevModPhys.86.419. arXiv:1303.2849.

  22. Bubeck, S. et al. (2025). Early science acceleration experiments with GPT-5. arXiv:2511.16072.

  23. Budzyń, K. et al. (2025). Endoscopist deskilling risk after exposure to artificial intelligence in colonoscopy: A multicentre, observational study. Lancet Gastroenterol. Hepatol. 10(10), 896–903. doi:10.1016/S2468-1253(25)00133-5.

  24. Bush, V. (1945). As we may think. The Atlantic Monthly, Jul. 1945.

  25. Caribé, J. G. A., Guimaraes, M. S., Roditi, I. & Sorella, S. P. (2026). Finite Weyl polynomials and the approach to Tsirelson’s bound in relativistic scalar quantum field theory. arXiv:2608.20926.

  26. Chen, Y. et al. (2025). Reasoning models don’t always say what they think. arXiv:2505.05410.

  27. Chi, M. T. H., de Leeuw, N., Chiu, M.-H. & LaVancher, C. (1994). Eliciting self-explanations improves understanding. Cogn. Sci. 18(3), 439–477. doi:10.1207/s15516709cog1803_3.

  28. Chung, D. J. H. et al. (2025). Theoretical physics benchmark (TPBench): A dataset and study of AI reasoning capabilities in theoretical physics. Mach. Learn.: Sci. Technol. arXiv:2502.15815.

  29. Cirel’son, B. S. (1980). Quantum generalizations of Bell’s inequality. Lett. Math. Phys. 4, 93–100. doi:10.1007/BF00417500.

  30. Clauser, J. F., Horne, M. A., Shimony, A. & Holt, R. A. (1969). Proposed experiment to test local hidden-variable theories. Phys. Rev. Lett. 23, 880–884. doi:10.1103/PhysRevLett.23.880.

  31. CNPq (2026). Portaria nº 2.664, de 6 de março de 2026 [Ordinance 2,664 of 6 March 2026, establishing CNPq’s Policy on Integrity in Scientific Activity] (consulted 20 Nov. 2026).

    Publication in the Diário Oficial da União · copy kept by the University of Brasília. Art. 4 (scope) and art. 9 (AI).

  32. Conroy, G. (2023). Scientific sleuths spot dishonest ChatGPT use in papers. Nature, 8 Sep. 2023. doi:10.1038/d41586-023-02477-w.

  33. COPE (2023). Authorship and AI tools: COPE position statement. publicationethics.org, Feb. 2023.

  34. DeepSeek-AI (2025). DeepSeek-R1 incentivizes reasoning in LLMs through reinforcement learning. Nature 645, 633–638.

  35. DeepSeek-AI (2025). DeepSeek-R1: Incentivizing reasoning capability in LLMs via reinforcement learning. arXiv:2501.12948v1. R1-Zero and R1 experiments.

  36. Doshi, A. R. & Hauser, O. P. (2024). Generative AI enhances individual creativity but reduces the collective diversity of novel content. Sci. Adv. 10, eadn5290.

  37. Elhage, N. et al. (2021). A mathematical framework for transformer circuits. Transformer Circuits Thread, transformer-circuits.pub.

  38. Elhage, N. et al. (2022). Toy models of superposition. Transformer Circuits Thread. arXiv:2209.10652.

  39. Elsevier. Generative AI policies for journals (update of Jun. 2026). elsevier.com.

  40. Elsworth, C. et al. (2025). Measuring the environmental impact of delivering AI at Google scale. arXiv:2508.15734.

  41. Feng, T. et al. (2026). Semi-autonomous mathematics discovery with Gemini: A case study on the Erdős problems. arXiv:2601.22401.

  42. Forte, T. (2022). Building a Second Brain. Atria Books.

  43. Gekhman, Z., Yona, G., Aharoni, R. et al. (2024). Does fine-tuning LLMs on new knowledge encourage hallucinations? EMNLP. arXiv:2405.05904.

  44. Georgiev, B., Gómez-Serrano, J., Tao, T. & Wagner, A. Z. (2025). Mathematical exploration and discovery at scale. arXiv:2511.02864.

  45. Geshkovski, B., Letrouit, C., Polyanskiy, Y. & Rigollet, P. (2025). A mathematical perspective on Transformers. Bull. Amer. Math. Soc., doi:10.1090/bull/1863. arXiv:2312.10794.

  46. Geva, M., Schuster, R., Berant, J. & Levy, O. (2021). Transformer feed-forward layers are key-value memories. EMNLP 2021. arXiv:2012.14913.

  47. Grattafiori, A. et al. (2024). The Llama 3 herd of models. arXiv:2407.21783.

  48. Gribov, V. N. (1978). Quantization of non-Abelian gauge theories. Nucl. Phys. B 139, 1–19. doi:10.1016/0550-3213(78)90175-X.

  49. Gu, A. & Dao, T. (2023). Mamba: Linear-time sequence modeling with selective state spaces. arXiv:2312.00752.

  50. Guimaraes, M. S. (2026). A Lorentzian Gribov no-pole condition for Yang–Mills theory. arXiv:2606.08697; accepted in Phys. Rev. D, doi:10.1103/8jz8-v392.

  51. Hao, Q., Xu, F., Li, Y. & Evans, J. (2026). Artificial intelligence tools expand scientists’ impact but contract science’s focus. Nature 649, 1237–1243. doi:10.1038/s41586-025-09922-y.

  52. Hestenes, D., Wells, M. & Swackhamer, G. (1992). Force concept inventory. Phys. Teach. 30, 141–158.

  53. Hochreiter, S. & Schmidhuber, J. (1997). Long short-term memory. Neural Comput. 9, 1735–1780.

  54. Hoffmann, J. et al. (2022). Training compute-optimal large language models. NeurIPS 35. arXiv:2203.15556.

  55. Holtzman, A., Buys, J., Du, L., Forbes, M. & Choi, Y. (2020). The curious case of neural text degeneration. ICLR. arXiv:1904.09751.

  56. Hopfield, J. J. (1982). Neural networks and physical systems with emergent collective computational abilities. Proc. Natl. Acad. Sci. USA 79, 2554–2558.

  57. Hsu, S. D. H. (2026). Relativistic covariance and nonlinear quantum mechanics: Tomonaga–Schwinger analysis. Phys. Lett. B 872, 140053. arXiv:2511.15935.

  58. Hu, E. J., Shen, Y., Wallis, P. et al. (2021). LoRA: Low-rank adaptation of large language models. ICLR 2022. arXiv:2106.09685.

  59. Hugging Face. Perplexity of fixed-length models. Transformers documentation. https://huggingface.co/docs/transformers/en/perplexity. Consulted: 3 October 2026.

  60. IOP Publishing. Generative AI tools (author policy; consulted 20 Nov. 2026). https://publishingsupport.iopscience.iop.org/questions/generative-ai-tools/.

  61. IOP Publishing. Ethical policies for reviewers. https://publishingsupport.iopscience.iop.org/ethics-for-reviewers/ (consulted 20 Nov. 2026).

  62. Ji, Z., Natarajan, A., Vidick, T., Wright, J. & Yuen, H. (2020). MIP* = RE. arXiv:2001.04383.

  63. Kalai, A. T., Nachum, O., Vempala, S. S. & Zhang, E. (2025). Why language models hallucinate. arXiv:2509.04664.

  64. Kaplan, J. et al. (2020). Scaling laws for neural language models. arXiv:2001.08361.

  65. Karpathy, A. (2026). LLM Wiki. GitHub Gist, 4 Apr. 2026. https://gist.github.com/karpathy/442a6bf555914893e9891c11519de94f.

  66. Kestin, G. et al. (2025). AI tutoring outperforms in-class active learning: An RCT introducing a novel research-based design in an authentic educational setting. Sci. Rep. 15, 17458.

  67. Kobak, D., González-Márquez, R., Horvát, E.-Á. & Lause, J. (2025). Delving into LLM-assisted writing in biomedical publications through excess vocabulary. Sci. Adv. 11, eadt3813.

  68. Kortemeyer, G. (2023). Could an artificial-intelligence agent pass an introductory physics course? Phys. Rev. Phys. Educ. Res. 19, 010132.

  69. Kortemeyer, G. et al. (2024). Grading assistance for a handwritten thermodynamics exam using artificial intelligence: An exploratory study. Phys. Rev. Phys. Educ. Res. 20, 020144.

  70. Kosmyna, N. et al. (2025). Your brain on ChatGPT: Accumulation of cognitive debt when using an AI assistant for essay writing task. arXiv:2506.08872.

  71. Krotov, D. & Hopfield, J. J. (2016). Dense associative memory for pattern recognition. NeurIPS 29. arXiv:1606.01164.

  72. Lewis, P. et al. (2020). Retrieval-augmented generation for knowledge-intensive NLP tasks. NeurIPS 33. arXiv:2005.11401.

  73. Liang, W., Yuksekgonul, M., Mao, Y., Wu, E. & Zou, J. (2023). GPT detectors are biased against non-native English writers. Patterns 4(7), 100779.

  74. Liang, W. et al. (2024). Can large language models provide useful feedback on research papers? A large-scale empirical analysis. NEJM AI 1(8), AIoa2400196. arXiv:2310.01783.

  75. Liang, W. et al. (2025). Quantifying large language model usage in scientific papers. Nat. Hum. Behav. 9, doi:10.1038/s41562-025-02273-8.

  76. Lin, Z. (2025). Hidden prompts in manuscripts exploit AI-assisted peer review. arXiv:2507.06185.

  77. Lindsey, J. et al. (2025). On the biology of a large language model. Transformer Circuits Thread, transformer-circuits.pub.

  78. Liu, N. F. et al. (2024). Lost in the middle: How language models use long contexts. Trans. Assoc. Comput. Linguist. 12, 157–173. arXiv:2307.03172.

  79. Lu, Y., Li, Z., He, D., Sun, Z., Dong, B., Qin, T., Wang, L. & Liu, T.-Y. (2019). Understanding and improving Transformer from a multi-particle dynamic system point of view. arXiv:1906.02762.

  80. Matuschak, A. Evergreen notes. notes.andymatuschak.org.

  81. Messeri, L. & Crockett, M. J. (2024). Artificial intelligence and illusions of understanding in scientific research. Nature 627, 49–58.

  82. Mora, T. & Bialek, W. (2011). Are biological systems poised at criticality? J. Stat. Phys. 144, 268–302.

  83. Morgensztern, E., Fierro Cota, C. & Mininno, A. (2026). Solver Agent: an agentic AI framework for theoretical physics computations applied to F-theory uplifts of O3-planes and S-folds. arXiv:2609.35958. Code at https://github.com/starrfree/solver-agent.

  84. Nikkei Asia (2025). “Positive review only”: Researchers hide AI prompts in papers. Jul. 2025.

  85. Nobel Committee for Physics (2024). Scientific background to the Nobel Prize in Physics 2024: For foundational discoveries and inventions that enable machine learning with artificial neural networks. nobelprize.org.

  86. Olsson, C. et al. (2022). In-context learning and induction heads. Transformer Circuits Thread. arXiv:2209.11895.

  87. Onsager, L. (1944). Crystal statistics. I. A two-dimensional model with an order-disorder transition. Phys. Rev. 65, 117–149. doi:10.1103/PhysRev.65.117.

  88. Oppenheim, J. (2025). Nonlinear quantum mechanics and artificial intelligence. arXiv:2512.07809. See also J. Oppenheim, “We are in the era of science slop”, Superposer, 5 Dec. 2025.

  89. Ouyang, L. et al. (2022). Training language models to follow instructions with human feedback. NeurIPS 35. arXiv:2203.02155.

  90. Petrov, A., La Malfa, E., Torr, P. H. S. & Bibi, A. (2023). Language model tokenizers introduce unfairness between languages. NeurIPS 36. arXiv:2305.15425.

  91. Polverini, G. & Gregorcic, B. (2024). How understanding large language models can inform the use of ChatGPT in physics education. Eur. J. Phys. 45, 025701.

  92. Radford, A., Wu, J., Child, R., Luan, D., Amodei, D. & Sutskever, I. (2019). Language models are unsupervised multitask learners. Technical report, OpenAI.

  93. Rafailov, R. et al. (2023). Direct preference optimization: Your language model is secretly a reward model. NeurIPS 36. arXiv:2305.18290.

  94. Ramsauer, H. et al. (2021). Hopfield networks is all you need. ICLR. arXiv:2008.02217.

  95. Rende, R., Gerace, F., Laio, A. & Goldt, S. (2024). Mapping of attention mechanisms to a generalized Potts model. Phys. Rev. Research 6, 023057.

  96. Roberts, D. A., Yaida, S. & Hanin, B. (2022). The Principles of Deep Learning Theory. Cambridge University Press. arXiv:2106.10165.

  97. Roediger, H. L. & Karpicke, J. D. (2006). Test-enhanced learning: Taking memory tests improves long-term retention. Psychol. Sci. 17(3), 249–255. doi:10.1111/j.1467-9280.2006.01693.x.

  98. Rozenblit, L. & Keil, F. (2002). The misunderstood limits of folk science: An illusion of explanatory depth. Cogn. Sci. 26(5), 521–562. doi:10.1207/s15516709cog2605_1.

  99. Schaeffer, R., Miranda, B. & Koyejo, S. (2023). Are emergent abilities of large language models a mirage? NeurIPS 36. arXiv:2304.15004.

  100. Schick, T. et al. (2023). Toolformer: Language models can teach themselves to use tools. NeurIPS 36. arXiv:2302.04761.

  101. Schilke, O. & Reimann, M. (2025). The transparency dilemma: How AI disclosure erodes trust. Organ. Behav. Hum. Decis. Process. 188, 104405.

  102. Schwartz, M. D. (2026). Vibe physics: The AI grad student. Anthropic, Mar. 2026 (anthropic.com/research/vibe-physics). Resulting paper: Resummation of the Sudakov shoulder in e+e−e^+e^- collisions, arXiv:2601.02484.

  103. SciELO (2023). Guia de uso de ferramentas e recursos de Inteligência Artificial na comunicação de pesquisas na Rede SciELO [Guide to the use of artificial intelligence tools and resources in research communication in the SciELO Network]. 14 Sep. 2023.

  104. Sennrich, R., Haddow, B. & Birch, A. (2016). Neural machine translation of rare words with subword units. ACL. arXiv:1508.07909.

  105. Shannon, C. E. (1948). A mathematical theory of communication. Bell Syst. Tech. J. 27, 379–423 and 623–656.

  106. Shannon, C. E. (1951). Prediction and entropy of printed English. Bell Syst. Tech. J. 30, 50–64.

  107. Sharma, M. et al. (2024). Towards understanding sycophancy in language models. ICLR. arXiv:2310.13548.

  108. Si, C., Yang, D. & Hashimoto, T. (2025). Can LLMs generate novel research ideas? A large-scale human study with 100+ NLP researchers. ICLR. arXiv:2409.04109.

  109. Si, C., Hashimoto, T. & Yang, D. (2025). The ideation–execution gap: Execution outcomes of LLM-generated versus human research ideas. arXiv:2506.20803.

  110. Snoswell, A. J., Witzenberger, K. & El Masri, R. (2025). A weird phrase is plaguing scientific papers, and we traced it back to a glitch in AI training data. The Conversation, 15 Apr. 2025.

  111. Springer Nature. Editorial policies: Artificial Intelligence (AI). https://www.springernature.com/gp/policies/editorial-policies (consulted Sep. 2026).

  112. Stanković, M., Hirche, E., Kollatzsch, S. & Doetsch, J. N. (2025). Comment on: Your brain on ChatGPT: Accumulation of cognitive debt when using an AI assistant for essay writing tasks. arXiv:2601.00856 (submitted Dec. 2025).

  113. Su, J., Lu, Y., Pan, S., Murtadha, A., Wen, B. & Liu, Y. (2024). RoFormer: Enhanced transformer with rotary position embedding. Neurocomputing 568, 127063. arXiv:2104.09864 (2021).

  114. Suchikova, Y. et al. (2025). GAIDeT (Generative AI Delegation Taxonomy): A taxonomy for humans to delegate tasks to generative artificial intelligence in scientific research and publishing. Account. Res., doi:10.1080/08989621.2025.2544331.

  115. VanLehn, K. (2011). The relative effectiveness of human tutoring, intelligent tutoring systems, and other tutoring systems. Educ. Psychol. 46(4), 197–221. doi:10.1080/00461520.2011.611369.

  116. Vaswani, A. et al. (2017). Attention is all you need. NeurIPS 30. arXiv:1706.03762.

  117. Walters, W. H. & Wilder, E. I. (2023). Fabrication and errors in the bibliographic citations generated by ChatGPT. Sci. Rep. 13, 14045.

  118. Weaver, K. D. (2024). The Artificial Intelligence Disclosure (AID) Framework: An introduction. C&RL News. arXiv:2408.01904.

  119. Wikipedia, WikiProject AI Cleanup. Signs of AI writing. en.wikipedia.org/wiki/Wikipedia:Signs_of_AI_writing.

  120. Yao, S. et al. (2023). ReAct: Synergizing reasoning and acting in language models. ICLR. arXiv:2210.03629.

  121. Yuille, A. L. & Rangarajan, A. (2003). The concave-convex procedure. Neural Comput. 15(4), 915–936.

  122. Zhu, M. et al. (2025). Probing the critical point (CritPt) of AI reasoning: A frontier physics research benchmark. arXiv:2509.26574.

Data protection (Brazil): Law 13,709/2018 (LGPD), especially arts. 4, 7 and 11; check your own institution's rules as well.

Search the course

Type at least two letters.