arjun10g commited on
Commit
cb432a6
·
verified ·
1 Parent(s): 7983336

Sync 20 audio file(s) and transcripts

Browse files
README.md ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ pretty_name: Papers, as Audio
3
+ tags:
4
+ - audio
5
+ - lectures
6
+ - text-to-speech
7
+ ---
8
+
9
+ # Papers, as Audio
10
+
11
+ Narrated long-form lectures on statistics and machine learning, streamed by the
12
+ [Papers, as Audio](https://arjun10g.github.io/Papers_Audio/) phone app.
13
+
14
+ - `library.json` — the catalog the app reads (titles, durations, chapter markers, file paths)
15
+ - `audio/<id>.mp3` — one file per lecture (Kokoro-82M `af_heart`, 96 kbps mono)
16
+ - `lectures/<id>.md` — transcripts
17
+
18
+ Published automatically from https://github.com/Arjun10g/Papers_Audio.
audio/boosting.mp3 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:398db81fda21a959f0f038d92a6e0f257af3d3f6f0afaf01bd63448ea5e298cd
3
+ size 22136876
audio/decomposed-tree.mp3 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5638289339a11d2c1e32c597aff8aeb936a1cb1f050eca3ff22c8440b9967471
3
+ size 17074604
audio/embedders.mp3 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e966867b3f5ef2137771b4f9c2f478eadfaee89b97102fd5fdc3c383dbc153ad
3
+ size 9554924
audio/hardware-ouro.mp3 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:71b34e853828d442f4873df79f13151459edb46dd91cea397cb0f2661c8b163d
3
+ size 15037868
audio/inference-serving.mp3 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5a1899680325c2aeb423c7ec23d77080c2c9a0c48a1aeea3039b86149d330f6e
3
+ size 26284460
audio/intro-ml.mp3 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9efbb908f39cd57c37b86b95334816f983df875de2ee9c0df0dde9fe972c795f
3
+ size 5967884
audio/longitudinal.mp3 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fd3321f169aac2aca8f281b9a9f7a1f5d8add8f2c35c7d5d385c195a77c1e1db
3
+ size 12232172
audio/model-comparison.mp3 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8029d1f76844cb783e41d531af0cf1b5cd41607e3fad45b7eacbbc985ca269d4
3
+ size 8733740
audio/neural-networks.mp3 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:61ad753a471fc50a7c6b0efcb254a50475b5bfbe5ce71f7cfe3b2f89f8cb87aa
3
+ size 12943340
audio/nonlinearity.mp3 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:464f7eae3ef24e9f71e27ce76127736df503b2c10f79d94261d6124f7887e778
3
+ size 10247852
audio/ouro-implementation.mp3 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fa8aa9dda5214af0c0021d0deb2f43d15be3c1d5e66c12bc6045c8dd0b6cab75
3
+ size 28273772
audio/rashomon-instability.mp3 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1a34b934439c32384b383e99bfe6a67f90cb5457f64f7f1f942b93ffaf3745ad
3
+ size 8578988
audio/rashomon.mp3 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e8fda516cf88d88ac3556c6ab5bfe23dc338a206f6b042cb46b01799e3d532e5
3
+ size 8536556
audio/recurrent-depth.mp3 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8e784872809b61d1bc1b43dfae83be96a938c3b497a7ce72e838695d5bb85024
3
+ size 22617836
audio/spline-interpretation.mp3 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:002761e38dc8d0474819351677c8cc8c5edc268fbf10aa61dfce1469b20f3e32
3
+ size 5822348
audio/splines.mp3 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6d130a7fd8182894c3ad32a284bc60a77ce855cda4cf353ccf5f3c49c39e565f
3
+ size 5695244
audio/svm.mp3 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e59e0cee0b9301e0b19087e710335d9bd96fc5c8892d9371aa876d1ab6b2d85e
3
+ size 5926412
audio/throughput.mp3 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d9be5224448dfdb67f253859ed56a8739b3ea07ca9645a12b86d9733eb152590
3
+ size 24726956
audio/transformers.mp3 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ff3b0bc7fe4aee4d3ac09417243c294fbcf90de908e3a7879278594369c40341
3
+ size 20098796
audio/trees.mp3 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:541e3b26dbccac143d2f3ff7ed92a31d83161005c68f7d3386a60b29f000c428
3
+ size 10599116
lectures/boosting.md ADDED
@@ -0,0 +1,393 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Ensemble Learning & Gradient Boosting
2
+
3
+ *Ensemble Learning and Gradient Boosting: A Comprehensive Guide*
4
+
5
+ ## Part 1: Foundations and Intuition
6
+
7
+ ## Section 1.1. What Is Ensemble Learning?
8
+
9
+ Ensemble learning is a meta-strategy in machine learning that combines the predictions of multiple individual models, called base learners or weak learners, to produce a single, superior prediction. The fundamental insight is that a collection of imperfect models, when combined intelligently, can dramatically outperform any single model in the collection.
10
+
11
+ There are three dominant paradigms in ensemble learning.
12
+
13
+ First, Bagging, or Bootstrap Aggregating. Train multiple models independently on bootstrapped, meaning random with replacement, subsets of the data, then average for regression or vote for classification their predictions. The canonical example is Random Forests. Bagging primarily reduces variance while leaving bias relatively unchanged.
14
+
15
+ Second, Boosting. Train models sequentially, where each new model is specifically designed to correct the errors of the previous ensemble. Models are combined through a weighted sum. Boosting primarily reduces bias, and can also reduce variance in many practical settings.
16
+
17
+ Third, Stacking, or Stacked Generalization. Train multiple diverse base models, then train a meta-learner on top that learns how to optimally combine their predictions. This can capture complex nonlinear relationships between base model outputs and the true target.
18
+
19
+ ## Section 1.2. The Core Idea of Boosting
20
+
21
+ Boosting rests on a deceptively simple question posed by Michael Kearns and Leslie Valiant in 1989: Can a set of weak learners be combined to create a single strong learner? A weak learner is any model that performs only slightly better than random guessing. For binary classification, this means a model with accuracy just above 50 percent. The remarkable answer, proven by Robert Schapire in 1990, is yes, and this equivalence between weak and strong learnability is one of the most important results in computational learning theory.
22
+
23
+ The boosting procedure works as follows, at the highest level. You start with your training data and fit a weak learner. You then examine what that learner got wrong, and somehow emphasize those mistakes. You fit a second weak learner, but now it pays more attention to the previously misclassified examples. You repeat this process many times. Finally, you combine all these weak learners into a single prediction by taking a weighted vote or weighted sum of their outputs, where better-performing learners get more weight.
24
+
25
+ The key insight is that each new learner in the sequence is not trying to solve the entire problem from scratch. Instead, it is specifically targeting the residual errors of the current ensemble. This sequential error-correction mechanism is what gives boosting its extraordinary power.
26
+
27
+ ## Section 1.3. Weak Learners: The Building Blocks
28
+
29
+ A weak learner, formally, is a classifier whose expected error rate is bounded below one half, that is, it does better than a fair coin flip, even if only marginally. In practice, the most common weak learner used in boosting is the decision stump: a decision tree with a single split, or depth 1. Decision stumps partition the feature space with a single threshold on a single feature, producing two leaf nodes.
30
+
31
+ Why stumps? They are extremely fast to train, have very low variance since they are so constrained, and they have very high bias, which is exactly what boosting is designed to reduce. Each stump captures one small axis-aligned rule, and boosting assembles hundreds or thousands of these micro-rules into a complex, expressive model.
32
+
33
+ In modern gradient boosting frameworks such as XGBoost, LightGBM, and CatBoost, the base learners are typically shallow decision trees with depths between 3 and 8, not just stumps. These slightly more complex base learners can capture feature interactions within a single tree, which accelerates convergence and often improves performance. However, the fundamental boosting logic remains the same.
34
+
35
+ ## Section 1.4. The Bias-Variance Lens
36
+
37
+ Every predictive model's error can be decomposed into three components: bias, which is systematic error from simplifying assumptions; variance, which is sensitivity to fluctuations in the training set; and irreducible noise. Bagging and boosting attack different sides of this tradeoff.
38
+
39
+ Bagging takes high-variance, low-bias models like deep trees and averages them to reduce variance. The averaging process smooths out the instability. Boosting takes high-bias, low-variance models like stumps or shallow trees and sequentially reduces the bias. Each new learner is fitted to the residual errors, gradually chipping away at the systematic mistakes.
40
+
41
+ This is why boosting is so effective on underfitting problems. If your base learner is too simple to capture the underlying pattern, boosting will correct that by iteratively building complexity. The total model complexity grows with the number of boosting rounds, the depth of the base trees, and the learning rate.
42
+
43
+ An important nuance: boosting can also reduce variance in practice, particularly with regularization techniques like shrinkage, which is the learning rate, subsampling, and early stopping. Pure, unregularized boosting with many rounds can overfit, increasing variance. The art of applied boosting lies in balancing enough rounds to reduce bias against regularization to control variance.
44
+
45
+ ## Part 2: AdaBoost, or Adaptive Boosting
46
+
47
+ ## Section 2.1. Historical Context
48
+
49
+ AdaBoost was introduced by Yoav Freund and Robert Schapire in 1995 and formalized in their 1997 paper titled A Decision-Theoretic Generalization of On-Line Learning and an Application to Boosting. It was the first practical, provably effective boosting algorithm and won the Goedel Prize in 2003. AdaBoost transformed boosting from a theoretical curiosity into a practical powerhouse.
50
+
51
+ ## Section 2.2. The Algorithm, Step by Step
52
+
53
+ Consider a binary classification problem with training examples x 1 y 1 through x n y n, where y i is in the set negative 1, positive 1. AdaBoost proceeds as follows.
54
+
55
+ Initialization: Assign equal weights to all training examples. w 1 of i equals 1 over n for i equals 1 through n. These weights represent how much attention each example should receive.
56
+
57
+ For each boosting round t equals 1, 2, up to T:
58
+
59
+ Step 1, fit a weak learner. Train a base classifier h t on the training data using the current sample weights w t. The weak learner should minimize the weighted classification error.
60
+
61
+ Step 2, compute weighted error. Epsilon t equals the sum over i of w t of i times the indicator that h t of x i does not equal y i. That is, the sum of weights of misclassified examples. If epsilon t is greater than or equal to 0.5, stop, because the learner is worse than random.
62
+
63
+ Step 3, compute learner weight. Alpha t equals one half times the natural log of the quantity 1 minus epsilon t divided by epsilon t. This is the weight assigned to this learner in the final ensemble. Better learners with lower epsilon get higher weight. A learner with epsilon equals 0 gets alpha equals infinity. A learner with epsilon equals 0.5 gets alpha equals 0.
64
+
65
+ Step 4, update sample weights. w t plus 1 of i equals w t of i times the exponential of negative alpha t times y i times h t of x i. If example i was correctly classified, y i times h t of x i equals positive 1, so the weight is multiplied by e to the negative alpha t, which is less than 1, decreasing it. If misclassified, y i times h t of x i equals negative 1, so the weight is multiplied by e to the alpha t, which is greater than 1, increasing it.
66
+
67
+ Step 5, renormalize weights. Divide all weights by their sum so they form a valid distribution: w t plus 1 of i equals w t plus 1 of i divided by the sum over j of w t plus 1 of j.
68
+
69
+ Final Prediction: H of x equals the sign of the sum over t of alpha t times h t of x. The ensemble prediction is the sign of the weighted majority vote of all T weak learners.
70
+
71
+ ## Section 2.3. The Mathematics: Exponential Loss Minimization
72
+
73
+ AdaBoost can be derived as forward stagewise additive modeling under the exponential loss function. L of y and F of x equals e to the negative y times F of x, where F of x equals the sum over t of alpha t times h t of x, which is the ensemble's output.
74
+
75
+ At round t, we want to find the learner h t and weight alpha t that minimize the sum over i of e to the negative y i times the quantity F t minus 1 of x i plus alpha t times h t of x i. Define w t of i equals e to the negative y i times F t minus 1 of x i, the effective weight of example i based on the current ensemble. The objective becomes the sum over i of w t of i times e to the negative alpha t times y i times h t of x i.
76
+
77
+ For any fixed alpha t greater than 0, the optimal h t is the one minimizing the weighted classification error epsilon t. Given the optimal h t, differentiating with respect to alpha t and setting to zero yields alpha t equals one half times the natural log of 1 minus epsilon t divided by epsilon t. This derivation reveals that AdaBoost is performing coordinate descent in function space, greedily adding one basis function, or weak learner, at a time to minimize the exponential loss.
78
+
79
+ ## Section 2.4. Theoretical Guarantees
80
+
81
+ AdaBoost has several remarkable theoretical properties.
82
+
83
+ Training Error Bound: The training error of the ensemble decreases exponentially with the number of rounds. Specifically, the training error is bounded by the product over t of 2 times the square root of epsilon t times 1 minus epsilon t. If each weak learner has weighted error at most one half minus gamma, meaning it is at least gamma-better than random, the training error is at most e to the negative 2 gamma squared T, which goes to zero exponentially fast.
84
+
85
+ Margin Theory: The margin of an example x, y is defined as y times F of x divided by the sum of the absolute values of alpha t. Schapire and others in 1998 showed that AdaBoost tends to increase the margins of training examples, and that the generalization error is bounded in terms of the margin distribution. This explains why AdaBoost can continue to improve test error even after achieving zero training error, because it is still increasing margins.
86
+
87
+ Relationship to Logistic Regression: The exponential loss is an upper bound on the zero-one loss. Minimizing it is closely related to maximizing the log-likelihood under a logistic model. In fact, AdaBoost's update rule can be seen as a form of iteratively reweighted logistic regression.
88
+
89
+ ## Section 2.5. Strengths and Weaknesses
90
+
91
+ AdaBoost's primary strengths are its simplicity, its strong theoretical guarantees, its ability to work with any weak learner, and its excellent performance on many datasets. It requires essentially no hyperparameter tuning beyond the number of rounds T and the choice of base learner.
92
+
93
+ Its primary weakness is its extreme sensitivity to noise and outliers. Because AdaBoost exponentially upweights misclassified examples, noisy examples or mislabeled data points receive enormous weight over many rounds. The algorithm will contort itself trying to classify these noisy points correctly, leading to overfitting. This motivated the development of noise-tolerant variants like BrownBoost and the shift toward gradient boosting with more robust loss functions.
94
+
95
+ ## Part 3: Gradient Boosting
96
+
97
+ ## Section 3.1. The Paradigm Shift: Boosting as Gradient Descent in Function Space
98
+
99
+ Jerome Friedman's 2001 paper Greedy Function Approximation: A Gradient Boosting Machine fundamentally reframed boosting. Instead of viewing it as a reweighting scheme like AdaBoost, Friedman showed that boosting can be understood as performing gradient descent in the space of functions.
100
+
101
+ The key insight: we want to find a function F of x that minimizes some loss function, the sum over i of L of y i and F of x i. Instead of parameterizing F as a neural network or a single model, we build F additively: F of x equals the sum over t of f t of x, where each f t is a base learner, typically a decision tree. At each step, we compute the negative gradient of the loss with respect to the current prediction F t minus 1 of x i, and fit a new base learner to approximate this negative gradient. This is analogous to gradient descent, but instead of updating parameters in a fixed-dimensional space, we are adding functions to our model.
102
+
103
+ ## Section 3.2. The General Framework
104
+
105
+ The general gradient boosting algorithm works as follows.
106
+
107
+ Initialize: F 0 of x equals the argmin over gamma of the sum over i of L of y i and gamma. This is typically the mean of the target for regression or the log-odds for classification.
108
+
109
+ For each round t equals 1 through T:
110
+
111
+ Step 1, compute pseudo-residuals. r i t equals negative the partial derivative of L of y i and F of x i with respect to F of x i, evaluated at F equals F t minus 1. These pseudo-residuals are the negative gradient of the loss evaluated at each training point. They tell us the direction in which we should adjust our predictions to reduce the loss.
112
+
113
+ Step 2, fit a base learner. Fit a regression tree h t to the pseudo-residuals, the pairs x i and r i t. The tree approximates the negative gradient function.
114
+
115
+ Step 3, compute optimal leaf values. For each terminal region R j of tree h t, compute the optimal constant gamma j equals the argmin over gamma of the sum over x i in R j of L of y i and F t minus 1 of x i plus gamma. This is a one-dimensional optimization within each leaf.
116
+
117
+ Step 4, update the model. F t of x equals F t minus 1 of x plus nu times the sum over j of gamma j times the indicator that x is in R j, where nu in the interval 0 to 1 is the learning rate or shrinkage parameter.
118
+
119
+ ## Section 3.3. Pseudo-Residuals for Common Loss Functions
120
+
121
+ The beauty of gradient boosting is its modularity. You can plug in any differentiable loss function. Here are the pseudo-residuals for the most common losses.
122
+
123
+ Squared Error or L2 Loss: L equals one half times the quantity y minus F, squared. Pseudo-residual equals y minus F t minus 1 of x i. These are the literal residuals, the difference between the true value and the current prediction. This is the simplest case and gives standard gradient boosted regression.
124
+
125
+ Absolute Error or L1 Loss: L equals the absolute value of y minus F. Pseudo-residual equals the sign of y minus F t minus 1 of x i. The pseudo-residuals are just the signs of the residuals, making this loss more robust to outliers than squared error.
126
+
127
+ Huber Loss: A hybrid that acts like L2 for small residuals and L1 for large residuals, controlled by a threshold parameter delta. This provides a smooth transition between sensitivity and robustness.
128
+
129
+ Log Loss or Binary Cross-Entropy: L equals the log of 1 plus e to the negative 2 y F. Pseudo-residual equals 2 y divided by the quantity 1 plus e to the 2 y times F t minus 1 of x i. This is the standard loss for gradient boosted classification. The pseudo-residuals are the gradient of the logistic loss.
130
+
131
+ ## Section 3.4. Shrinkage or Learning Rate
132
+
133
+ Friedman introduced the learning rate, also called shrinkage, parameter nu, which scales the contribution of each new tree: F t of x equals F t minus 1 of x plus nu times h t of x. A smaller nu means each tree makes a smaller contribution, requiring more trees to achieve the same training loss. Empirically, smaller learning rates of 0.01 to 0.1 combined with more trees almost always produce better generalization than larger learning rates with fewer trees. The reason is that smaller learning rates provide a form of regularization. The model explores the function space more slowly and smoothly, avoiding sharp jumps that might overfit.
134
+
135
+ ## Section 3.5. Stochastic Gradient Boosting
136
+
137
+ Friedman also proposed stochastic gradient boosting, where at each round, only a random subsample of the training data, typically 50 to 80 percent, is used to fit the new tree. This introduces randomness similar to bagging, which reduces variance and often improves generalization. It also speeds up training since each tree is fitted on a smaller dataset. Column subsampling, using a random subset of features per tree or per split, provides additional regularization and is now standard in XGBoost, LightGBM, and CatBoost.
138
+
139
+ ## Part 4: XGBoost
140
+
141
+ ## Section 4.1. Overview and Historical Impact
142
+
143
+ XGBoost, which stands for eXtreme Gradient Boosting, was introduced by Tianqi Chen and Carlos Guestrin in 2016. It became the dominant machine learning algorithm for structured and tabular data. It won virtually every Kaggle competition involving structured data for several years and remains one of the most widely deployed ML algorithms in industry. XGBoost's contribution is twofold: a more principled algorithmic formulation with explicit regularization, and engineering innovations that made training orders of magnitude faster.
144
+
145
+ ## Section 4.2. The Regularized Objective
146
+
147
+ XGBoost adds explicit regularization to the boosting objective. At round t, the objective is: Obj t equals the sum over i of L of y i and y hat i t minus 1 plus f t of x i, plus Omega of f t, where Omega of f equals gamma times T plus one half lambda times the sum over j of w j squared. This penalizes model complexity. Here, T is the number of leaves in the tree, w j is the weight or prediction value of leaf j, gamma controls the minimum gain required to make a split and acts as pruning, and lambda is the L2 regularization on leaf weights. An optional L1 regularization alpha on leaf weights can also be added.
148
+
149
+ ## Section 4.3. Second-Order Taylor Expansion
150
+
151
+ XGBoost's key algorithmic innovation is using a second-order Taylor expansion of the loss function. For each training example, define g i equals the partial derivative of L with respect to y hat i, which is the gradient or first derivative of the loss with respect to the prediction, and h i equals the second partial derivative of L with respect to y hat i squared, which is the Hessian or second derivative.
152
+
153
+ Using a second-order approximation, the loss becomes: L of y i and y hat i plus f t of x i is approximately L of y i and y hat i, plus g i times f t of x i, plus one half h i times f t of x i squared.
154
+
155
+ After dropping the constant terms and substituting the tree structure, the objective becomes a sum over leaves: Obj t equals the sum over j of one half times the quantity sum of g i squared, divided by the quantity sum of h i plus lambda, plus gamma. From this, we derive two critical formulas.
156
+
157
+ Optimal leaf weight: w j star equals negative the sum of g i divided by the sum of h i plus lambda, where the sums are over examples in leaf j. The Hessian in the denominator acts as a natural adaptive learning rate, automatically adjusting the step size based on the curvature of the loss.
158
+
159
+ Optimal objective value: Obj star equals negative one half times the sum over j of the quantity sum of g i squared divided by the quantity sum of h i plus lambda, plus gamma times T. This is used to evaluate how good a particular tree structure is.
160
+
161
+ ## Section 4.4. Split Finding
162
+
163
+ To find the best split, XGBoost computes the gain for each candidate split. The gain from splitting a leaf into left and right children is: Gain equals one half times the quantity G L squared divided by H L plus lambda, plus G R squared divided by H R plus lambda, minus the quantity G L plus G R squared divided by H L plus H R plus lambda, minus gamma. Where G L and H L are the sum of gradients and Hessians in the left child, and similarly for the right. The gamma term acts as a minimum gain threshold. If no split achieves positive gain, the leaf is not split, which is pre-pruning.
164
+
165
+ The exact greedy algorithm sorts all examples by each feature's value, then scans left to right, computing the gain at each possible split point.
166
+
167
+ For large datasets, XGBoost uses an approximate split-finding algorithm based on weighted quantile sketches, where the quantiles are weighted by the Hessians h i, because examples with larger Hessians contribute more to the objective.
168
+
169
+ XGBoost also has sparsity-aware split finding. For each split, it learns a default direction for missing values. The algorithm tries sending all missing examples to both the left and right child, and chooses whichever direction gives higher gain. This default direction is stored and used at prediction time. This is much more principled than imputing missing values before training.
170
+
171
+ ## Section 4.5. System Design Innovations
172
+
173
+ XGBoost's engineering was as important as its algorithm. It uses a column block structure where data is stored in compressed column format, sorted by feature value, enabling parallelization across features. It uses cache-aware access patterns that prefetch gradient statistics into CPU cache. It supports out-of-core computation for datasets that do not fit in memory. And it supports parallel and distributed training using a RABIT-based all-reduce framework.
174
+
175
+ ## Section 4.6. Advanced Features
176
+
177
+ Monotonic Constraints force the model's prediction to be monotonically increasing or decreasing with respect to a specific feature. Critical for business applications where domain knowledge requires monotonicity.
178
+
179
+ Interaction Constraints restrict which features can appear together in a tree.
180
+
181
+ Custom Objectives allow any twice-differentiable loss function to be used by providing the gradient and Hessian functions.
182
+
183
+ ## Part 5: LightGBM
184
+
185
+ ## Section 5.1. Motivation and Overview
186
+
187
+ LightGBM, introduced by Ke and others at Microsoft Research in 2017, was designed to handle the computational bottleneck of gradient boosting on large datasets. LightGBM introduces two novel techniques, Gradient-based One-Side Sampling or GOSS, and Exclusive Feature Bundling or EFB, along with a histogram-based split-finding approach, to achieve dramatic speedups while maintaining accuracy.
188
+
189
+ ## Section 5.2. Leaf-Wise versus Level-Wise Tree Growth
190
+
191
+ Most boosting implementations grow trees level-wise, meaning breadth-first: at each step, all leaves at the current depth are split. This produces balanced trees but wastes computation on splits that contribute little gain.
192
+
193
+ LightGBM uses leaf-wise or best-first growth: at each step, it splits the leaf with the highest loss reduction, regardless of depth. This produces unbalanced trees that can be much deeper on one side, but each split is maximally useful. Leaf-wise growth converges faster but is more prone to overfitting on small datasets, which is why the max depth and num leaves parameters become critical for regularization.
194
+
195
+ ## Section 5.3. Gradient-Based One-Side Sampling
196
+
197
+ The key insight behind GOSS is that not all training examples contribute equally to the gradient computation. Examples with large gradients, meaning large residuals, are more informative because they are the ones the model is currently getting most wrong. Examples with small gradients are already well-predicted.
198
+
199
+ GOSS keeps all examples with large gradients, the top a percent, and randomly samples from examples with small gradients, keeping b percent of them. To compensate for the sampling bias, the small-gradient examples are upweighted by a factor of 1 minus a divided by b when computing gradient sums.
200
+
201
+ In practice, typical values are a equals 20 percent and b equals 10 percent, meaning only about 28 percent of the data is used for split finding at each node, yielding roughly a 3.5 times speedup.
202
+
203
+ ## Section 5.4. Exclusive Feature Bundling
204
+
205
+ Many real-world datasets have sparse features that rarely take nonzero values simultaneously, especially after one-hot encoding categorical variables. EFB identifies features that are exclusive, meaning they rarely conflict, and bundles them into a single feature. This reduces the effective number of features from d to the number of bundles, often dramatically.
206
+
207
+ The bundling problem is NP-hard since it's equivalent to graph coloring, so LightGBM uses a greedy approximation.
208
+
209
+ ## Section 5.5. Histogram-Based Split Finding
210
+
211
+ Instead of examining every unique feature value as a potential split point, LightGBM bins continuous features into a fixed number of discrete buckets, with a default of 255 bins. During tree construction, the gradient sums for each bin are accumulated in a histogram, and splits are evaluated only at bin boundaries.
212
+
213
+ This has several advantages. It reduces split finding from O of n to O of bins per feature, a massive speedup. The histogram is a compact array that fits in CPU cache. And it enables the histogram subtraction trick: if you know the histogram of the parent and one child, the other child's histogram is just the difference, halving the work.
214
+
215
+ ## Section 5.6. Categorical Feature Handling
216
+
217
+ LightGBM supports categorical features natively without one-hot encoding. For a categorical feature with k categories, it sorts the categories by their gradient statistics, specifically the sum of gradients divided by the sum of Hessians, and finds the optimal split in O of k log k time. This is far more efficient and effective than one-hot encoding.
218
+
219
+ ## Part 6: CatBoost
220
+
221
+ ## Section 6.1. The Problem CatBoost Solves
222
+
223
+ CatBoost, introduced by Prokhorenkova and others at Yandex in 2018, addresses two fundamental issues in gradient boosting: target leakage in categorical encoding and prediction shift from sequential training.
224
+
225
+ ## Section 6.2. Target Leakage and Prediction Shift
226
+
227
+ In standard gradient boosting, at round t, the pseudo-residuals are computed from the current model F t minus 1, which was trained on the same data. When we then fit a new tree to these pseudo-residuals, we are training on labels that were computed using the same data points. This creates a subtle but systematic bias called prediction shift.
228
+
229
+ This problem is amplified when categorical features are encoded using target statistics like target means. If you compute the mean target for category k using all examples with that category, then use that statistic as a feature to train the model, you have leaked the target into the feature. This leads to overfitting, especially for rare categories.
230
+
231
+ ## Section 6.3. Ordered Boosting
232
+
233
+ CatBoost's solution is ordered boosting, which uses a principled permutation-based scheme to eliminate prediction shift. The training data is randomly permuted. For each example x i at position sigma of i in the permutation, its model prediction is computed using only the examples that appear before it in the permutation. This ensures that the pseudo-residual for x i is computed from a model that never saw x i during training, eliminating the bias.
234
+
235
+ ## Section 6.4. Ordered Target Statistics for Categorical Features
236
+
237
+ CatBoost applies the same permutation principle to categorical encoding. For each example x i with category k, the target statistic is computed using only examples of category k that appear before x i in the permutation. The formula is: TS of x i equals the sum of y j for all j where sigma of j is less than sigma of i and x j is in category k, plus a times the prior, all divided by the count prior plus a. Where a is a smoothing parameter and prior is typically the global mean of the target.
238
+
239
+ ## Section 6.5. Oblivious or Symmetric Decision Trees
240
+
241
+ CatBoost uses oblivious decision trees as its base learner. In an oblivious tree, the same split condition is applied at all nodes of a given level. A depth-d oblivious tree has exactly d splits and 2 to the d leaves. This structure enables fast inference since the leaf index can be computed as a d-bit binary number, provides regularization through the symmetric constraint, and allows highly optimized memory access patterns.
242
+
243
+ ## Part 7: Mathematical Deep Dive
244
+
245
+ ## Section 7.1. PAC Learning and Weak Learnability
246
+
247
+ In the Probably Approximately Correct, or PAC, learning framework, a concept class C is efficiently learnable if there exists a polynomial-time algorithm that, for any distribution D over examples and any target concept c in C, produces a hypothesis h with error at most epsilon with probability at least 1 minus delta, using polynomially many examples. A concept class is weakly learnable if such an algorithm exists with error bounded by one half minus gamma for some fixed gamma greater than 0.
248
+
249
+ ## Section 7.2. The Equivalence Theorem
250
+
251
+ Schapire in 1990 proved the Boosting Theorem: a concept class is weakly PAC-learnable if and only if it is strongly PAC-learnable. This means that if you can do even slightly better than random guessing, you can be amplified to arbitrary accuracy. The proof is constructive, showing how to build a strong learner from weak learners.
252
+
253
+ The proof works by running the weak learner three times on carefully constructed distributions. The majority vote of the three hypotheses has error at most 3 gamma squared minus 2 gamma cubed, which for small gamma is approximately a cubic improvement. Repeated application drives the error to zero.
254
+
255
+ ## Section 7.3. Boosting as Coordinate Descent in Function Space
256
+
257
+ Let H be the space of all possible ensemble functions H of x equals the sum over t of alpha t times h t of x. The objective is to minimize the empirical risk: R of H equals 1 over n times the sum over i of L of y i and H of x i. Boosting performs coordinate descent in this infinite-dimensional function space. At each step, it identifies the basis function and coefficient that most reduce the objective, then adds it to the ensemble.
258
+
259
+ ## Section 7.4. Margin Theory
260
+
261
+ The margin of a training example x i, y i with respect to ensemble F is defined as: margin i equals y i times F of x i divided by the sum over t of the absolute value of alpha t. A positive margin means correct classification; a larger margin means more confidence.
262
+
263
+ The margin theory of boosting provides generalization bounds in terms of the margin distribution. This explains why even after training error reaches zero, boosting continues to improve test error because it is still increasing the margins.
264
+
265
+ ## Section 7.5. Generalization Bounds
266
+
267
+ Modern generalization theory for boosting uses Rademacher complexity. The Rademacher complexity of the class of T-round boosted ensembles is bounded by O of the square root of T times the Rademacher complexity of the base class. These bounds provide important qualitative insights: larger margins lead to better generalization, the complexity of the base learner matters, and boosting is implicitly regularized by using simple base learners.
268
+
269
+ ## Part 8: Regularization and Overfitting Control
270
+
271
+ ## Section 8.1. Learning Rate or Shrinkage
272
+
273
+ The learning rate nu in the interval 0 to 1 controls how much each tree contributes to the ensemble. Smaller values require more trees but almost always yield better generalization. Values between 0.01 and 0.1 are most common in practice.
274
+
275
+ ## Section 8.2. Early Stopping
276
+
277
+ Early stopping monitors the performance on a held-out validation set during training. If the validation metric does not improve for a specified number of consecutive rounds, training is halted. This is arguably the single most important regularization technique in practice. A common approach is to set a large number of maximum rounds, such as 10,000, and use early stopping with 50 to 200 patience rounds.
278
+
279
+ ## Section 8.3. Tree Constraints
280
+
281
+ Max Depth limits the maximum depth of each tree. Shallow trees of depth 3 to 6 capture low-order feature interactions and are less likely to overfit.
282
+
283
+ Max Leaves or num leaves is an alternative to max depth. Setting num leaves less than 2 to the power of max depth provides finer control.
284
+
285
+ Min Child Weight is the minimum sum of Hessians required in a child node. Larger values prevent the model from learning overly specific patterns.
286
+
287
+ Min Split Gain or gamma is the minimum gain required for a split to be made. It acts as a pruning threshold.
288
+
289
+ ## Section 8.4. L1 and L2 Regularization
290
+
291
+ All major frameworks support L1 and L2 regularization on the leaf weights. L2 regularization shrinks leaf weights toward zero, reducing the model's sensitivity to any single tree. L1 regularization encourages sparse leaf weights, effectively reducing the capacity of each tree. L2 is used more frequently, with typical values between 0 and 10.
292
+
293
+ ## Section 8.5. Subsampling
294
+
295
+ Row Subsampling uses a random subset of training examples per tree, with values of 0.5 to 0.8 being common. This introduces bagging-like randomness that reduces variance.
296
+
297
+ Column Subsampling uses a random subset of features per tree, also with values of 0.5 to 0.8 being common. This decorrelates the trees, similar to Random Forest's feature randomization.
298
+
299
+ ## Section 8.6. DART: Dropouts Meet Boosting
300
+
301
+ DART, which stands for Dropouts meet Multiple Additive Regression Trees, was proposed by Vinayak and Gilad-Bachrach in 2015. It applies the dropout idea from deep learning to boosted trees. At each round, a random subset of previously trained trees is dropped or excluded, and the new tree is trained to fit the residuals of the remaining ensemble.
302
+
303
+ DART addresses the shrinkage dilemma. With a standard learning rate, later trees contribute progressively less because earlier trees have already reduced the residuals. DART ensures that later trees have larger residuals to work with, leading to more balanced tree contributions.
304
+
305
+ ## Part 9: Hyperparameter Tuning
306
+
307
+ ## Section 9.1. Critical Hyperparameters Ranked by Impact
308
+
309
+ The hyperparameters roughly rank in order of impact as follows.
310
+
311
+ First, number of rounds with early stopping. This is by far the most impactful. Too few rounds means underfitting; too many means overfitting.
312
+
313
+ Second, learning rate. Controls the tradeoff between number of rounds and per-tree contribution.
314
+
315
+ Third, max depth or num leaves. Controls the complexity of each tree and the order of feature interactions.
316
+
317
+ Fourth, subsampling for both rows and columns. Provides regularization and speedup.
318
+
319
+ Fifth, min child weight or min data in leaf. Prevents overfitting to small subsets.
320
+
321
+ Sixth, L1, L2, and gamma regularization. Fine-tuning knobs that provide incremental improvements.
322
+
323
+ ## Section 9.2. Practical Tuning Strategy
324
+
325
+ Phase 1, Baseline: Set learning rate to 0.1, max depth to 6, subsample to 0.8, column sample by tree to 0.8, and n estimators to 10,000 with early stopping rounds of 50.
326
+
327
+ Phase 2, Tree Structure: Tune max depth and min child weight together.
328
+
329
+ Phase 3, Subsampling: Tune subsample and column sample by tree with values from 0.5 to 1.0.
330
+
331
+ Phase 4, Regularization: Tune gamma, lambda, and alpha.
332
+
333
+ Phase 5, Learning Rate: Reduce to 0.01 or 0.05 and increase n estimators. Retrain with early stopping.
334
+
335
+ ## Section 9.3. Bayesian Optimization
336
+
337
+ Bayesian optimization, implemented in libraries like Optuna, Hyperopt, and scikit-optimize, is the preferred method for hyperparameter tuning. It builds a probabilistic surrogate model of the objective function and uses an acquisition function to decide which configuration to try next. This is far more sample-efficient than grid search or random search, typically finding near-optimal configurations in 50 to 200 trials.
338
+
339
+ ## Part 10: Loss Functions and Custom Objectives
340
+
341
+ ## Section 10.1. Regression Losses
342
+
343
+ Mean Squared Error or L2: L equals the quantity y minus F, squared. Gradient equals negative 2 times y minus F. Hessian equals 2. The default for regression. Sensitive to outliers because errors are squared.
344
+
345
+ Mean Absolute Error or L1: L equals the absolute value of y minus F. Gradient equals negative sign of y minus F. Hessian equals 0. More robust to outliers.
346
+
347
+ Huber Loss: L equals one half times y minus F squared for absolute y minus F less than or equal to delta, and delta times absolute y minus F minus one half delta squared otherwise. Combines L2 stability for small errors with L1 robustness for large errors.
348
+
349
+ Quantile Loss: Used for predicting specific quantiles. Training with tau equals 0.5 gives the median, tau equals 0.9 gives the 90th percentile. Essential for prediction intervals and risk modeling.
350
+
351
+ ## Section 10.2. Classification Losses
352
+
353
+ Log Loss or Binary Cross-Entropy: L equals negative the quantity y times log p plus 1 minus y times log of 1 minus p, where p equals the sigmoid of F. The standard loss for binary classification.
354
+
355
+ Focal Loss: L equals negative the quantity 1 minus p t to the gamma times log of p t, where p t is the probability of the correct class. Down-weights easy examples and focuses on hard ones. Useful for class imbalance.
356
+
357
+ ## Section 10.3. Ranking Losses
358
+
359
+ LambdaMART is LambdaRank implemented with gradient boosted trees. It is the core algorithm behind many production search ranking systems. The key trick weights each pair of documents by the change in NDCG if the pair were swapped, making the gradients directly optimize the ranking metric.
360
+
361
+ ## Part 11: Feature Engineering and Interpretation
362
+
363
+ ## Section 11.1. Feature Importance Methods
364
+
365
+ Gain-Based Importance measures the total gain contributed by all splits on a feature across all trees. Split Count measures the number of times a feature is used as a split. Cover measures the average number of examples affected by splits on a feature. Permutation Importance randomly shuffles one feature's values and measures the decrease in model performance, and is model-agnostic.
366
+
367
+ ## Section 11.2. The Bias of Gain-Based Importance
368
+
369
+ Gain-based importance is biased toward high-cardinality features. A continuous feature with many unique values has more potential split points, giving it more opportunities to achieve high gain purely by chance. Permutation importance and SHAP values do not suffer from this bias.
370
+
371
+ ## Section 11.3. SHAP or SHapley Additive exPlanations
372
+
373
+ SHAP values, introduced by Lundberg and Lee in 2017, provide a theoretically grounded way to explain individual predictions. The SHAP value of feature j for prediction i is the average marginal contribution of feature j across all possible orderings of features, based on Shapley values from cooperative game theory.
374
+
375
+ TreeSHAP is an efficient algorithm for computing exact SHAP values for tree ensembles in polynomial time. SHAP provides local explanations for individual predictions, global importance via mean absolute SHAP values, interaction effects, and dependence plots revealing nonlinear effects.
376
+
377
+ ## Section 11.4. Partial Dependence and ICE Plots
378
+
379
+ Partial Dependence Plots show the marginal effect of one or two features on the model's prediction, averaged over all other features. Individual Conditional Expectation or ICE plots show one curve per training example, revealing heterogeneous effects and interactions.
380
+
381
+ ## Part 12: Boosting Beyond Trees
382
+
383
+ ## Section 12.1. Boosting with Linear Learners
384
+
385
+ While trees are the dominant base learner, boosting can use any model. Boosting with linear models produces a final model that is itself linear, useful when interpretability or regulatory compliance requires linearity.
386
+
387
+ ## Section 12.2. AdaBoost Variants
388
+
389
+ LogitBoost uses Newton steps on the logistic loss instead of the exponential loss, and is more robust to noise.
390
+
391
+ GentleBoost uses weighted least-squares regression as the weak learner, producing gentler updates than AdaBoost.
392
+
393
+ BrownBoost is designed to be noise-tolerant. Examples that are consistently misclassified get their time used up faster and stop influencing the algorithm, preventing the runaway weight explosion that plagues AdaBoost on noisy data.
lectures/decomposed-tree.md ADDED
@@ -0,0 +1,337 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Decomposed Random-Effects Tree
2
+
3
+ The Decomposed Random-Effects Tree: Dissolving Mixed Effects into Tree Structure. What We Built, Why It Works, and What We Proved.
4
+
5
+ But first, let us carefully walk through the full mathematics of XGBoost, step by step.
6
+
7
+ Current XGBoost: The Full Math.
8
+
9
+ We begin with the global objective at round t. This is the function that XGBoost tries to minimize when adding a new tree to the ensemble.
10
+
11
+ The objective at round t, written Obj t, equals the sum over all observations i of the loss L of y i and y hat i at round t minus 1 plus f t of x i, plus the regularizer Omega of f t.
12
+
13
+ Let us unpack each piece of this equation.
14
+
15
+ L of y i and y hat i t minus 1 plus f t of x i is the loss function. It measures how bad our prediction is for observation i. The input y i is the true value we are trying to predict. The input y hat i t minus 1 is our current prediction from the ensemble so far, meaning all the trees we have already built up to round t minus 1. And f t of x i is the correction that the new tree we are adding proposes for observation i. So we are measuring: if we take our current prediction and add the new tree's correction, how far off are we from the truth?
16
+
17
+ The sum over i means we add up this loss across every single observation in the training data. We want the total error to be small.
18
+
19
+ Omega of f t is the regularizer. It penalizes complexity in the new tree. Without it, the tree could become arbitrarily complex to fit the data perfectly, which would overfit.
20
+
21
+ The regularizer is defined as: Omega of f equals gamma times T plus one half lambda times the sum over j of w j squared.
22
+
23
+ Let us explain each part.
24
+
25
+ Gamma times T: T is the number of leaves in the tree. Gamma is a penalty coefficient. This term says: every additional leaf costs you gamma units of objective. It discourages the tree from having too many leaves. More leaves means a more complex tree, which means higher risk of overfitting.
26
+
27
+ One half lambda times the sum of w j squared: w j is the prediction value, also called the weight, of leaf j. This is the number that every observation landing in leaf j receives as its prediction from this tree. The sum of w j squared is the L2 norm of the leaf weights. Lambda controls how strongly we penalize large leaf weights. This term says: don't make any leaf's prediction too extreme. Pull the weights toward zero. It is the same idea as ridge regression.
28
+
29
+ Together, the regularizer balances model fit against model complexity. The tree must earn every leaf and every unit of prediction magnitude by sufficiently reducing the loss.
30
+
31
+ Now, the Taylor Expansion. This is the critical step.
32
+
33
+ The problem with the raw objective is that L can be any loss function, and minimizing it directly over the space of all possible trees is computationally intractable. XGBoost's key insight is to approximate the loss with a second-order Taylor expansion, which turns it into a simple quadratic that we can solve in closed form.
34
+
35
+ Define the per-sample loss as a function of the correction delta. We write: ell i of delta equals L of y i and y hat i t minus 1 plus delta.
36
+
37
+ Here, delta represents how much we adjust the prediction for observation i. When delta equals zero, we are making no adjustment, which means we are sticking with our current prediction. When delta equals f t of x i, we are applying the new tree's correction.
38
+
39
+ XGBoost approximates ell i of delta with a second-order Taylor expansion around delta equals zero.
40
+
41
+ The approximation is: ell i of delta is approximately equal to ell i of 0 plus g i times delta plus one half h i times delta squared.
42
+
43
+ Let us explain each term in this approximation.
44
+
45
+ ell i of 0 is the loss at the current prediction, before any correction. This is a constant. It does not depend on the new tree at all, so it cannot be changed by anything we do. We will drop it shortly.
46
+
47
+ g i times delta is the first-order term. g i is the gradient, defined as the partial derivative of L with respect to y hat, evaluated at y hat equals y hat t minus 1. The gradient tells us: in which direction and how steeply does the loss change if we nudge the prediction slightly? If g i is negative, increasing the prediction would decrease the loss. If g i is positive, increasing the prediction would increase the loss.
48
+
49
+ One half h i times delta squared is the second-order term. h i is the Hessian, defined as the second partial derivative of L with respect to y hat squared, evaluated at y hat equals y hat t minus 1. The Hessian tells us about the curvature of the loss. It measures how quickly the gradient itself is changing. A large Hessian means the loss curves steeply, so the optimal correction is well-determined. A small Hessian means the loss is relatively flat, so the optimal correction is less certain.
50
+
51
+ Why do we use a second-order approximation instead of just first-order? Because with only the gradient, we would know which direction to move but not how far. The Hessian gives us the curvature, which tells us the optimal step size. This is the same reason Newton's method converges faster than gradient descent: it uses curvature information.
52
+
53
+ Now, dropping the constant ell i of 0 since it does not depend on the new tree, and substituting delta equals f t of x i, the objective becomes:
54
+
55
+ Obj t is approximately equal to the sum over i of g i times f t of x i plus one half h i times f t of x i squared, plus gamma times T plus one half lambda times the sum over j of w j squared.
56
+
57
+ This is now a quadratic function of the tree's outputs. Quadratics are easy to optimize.
58
+
59
+ Next, we rewrite by grouping samples into leaves. Let I j denote the set of samples that land in leaf j. Since every sample in the same leaf gets the same prediction w j, we can replace f t of x i with w j for all i in I j.
60
+
61
+ The objective becomes: Obj t equals the sum over leaves j of the quantity G j times w j plus one half times the quantity H j plus lambda times w j squared, plus gamma times T.
62
+
63
+ Where G j equals the sum of g i over all i in I j, and H j equals the sum of h i over all i in I j.
64
+
65
+ G j is the total gradient for leaf j. It summarizes how all the observations in this leaf want the prediction to change.
66
+
67
+ H j is the total Hessian for leaf j. It summarizes how confident we are about the optimal correction for this leaf.
68
+
69
+ This is a sum of independent quadratics in each w j. Each leaf's optimal weight can be found independently of every other leaf. That is why everything is so clean. The tree structure determines which observations go to which leaf, and then each leaf's weight is a separate one-variable quadratic optimization.
70
+
71
+ Optimal leaf weight. We take the derivative of the leaf j objective with respect to w j and set it to zero.
72
+
73
+ The derivative is G j plus the quantity H j plus lambda times w j. Setting this to zero and solving gives:
74
+
75
+ w j star equals negative G j divided by the quantity H j plus lambda.
76
+
77
+ This is just the vertex of a parabola. One line of algebra. The optimal leaf weight is the negative total gradient divided by the total Hessian plus the regularization parameter. The gradient tells you which direction and how much. The Hessian plus lambda tells you how confident to be. More data in the leaf means larger H j, which means a more precise estimate. Lambda adds caution on top of that.
78
+
79
+ Optimal objective value. Substituting the optimal w j star back into the objective gives:
80
+
81
+ Obj star equals negative one half times the sum over j of G j squared divided by the quantity H j plus lambda, plus gamma times T.
82
+
83
+ This formula scores any tree structure. Given a tree's partition of the data into leaves, we can compute its optimal objective value directly from the gradient and Hessian sums. We do not need to actually fit the weights. This makes comparing different tree structures extremely efficient.
84
+
85
+ Split gain. The split gain measures the improvement in objective from splitting a leaf into two children. It is the difference in objective before and after splitting.
86
+
87
+ Gain equals one half times the quantity G L squared divided by H L plus lambda, plus G R squared divided by H R plus lambda, minus the quantity G L plus G R squared divided by H L plus H R plus lambda, minus gamma.
88
+
89
+ The first term, G L squared over H L plus lambda, is the optimal objective contribution from the left child.
90
+
91
+ The second term, G R squared over H R plus lambda, is the optimal objective contribution from the right child.
92
+
93
+ The third term, G L plus G R squared over H L plus H R plus lambda, is the optimal objective contribution from the parent before splitting. Note that G L plus G R equals G parent and H L plus H R equals H parent.
94
+
95
+ So the gain is: how much better can we do with two specialized leaves compared to one general leaf? If the gain is positive, the split is worth making. If negative, the parent leaf is already doing fine.
96
+
97
+ Minus gamma penalizes the split for adding an extra leaf to the tree. The split must earn at least gamma units of improvement to be accepted.
98
+
99
+ Everything flows from one assumption: the loss is locally quadratic in delta. That single assumption gives you closed-form leaf weights, closed-form objective, closed-form split criterion, and separability across leaves. This is the mathematical engine that makes XGBoost fast and effective.
100
+
101
+ Now we move to the main contribution.
102
+
103
+ ## Part 1: The Core Idea
104
+
105
+ ## Section 1.1. The Problem in One Sentence
106
+
107
+ Every existing method for combining gradient boosting with mixed effects treats them as two separate modules that alternate during training. We asked: what if we dissolve the random effects directly into the tree itself, so each leaf simultaneously estimates a population-level prediction and group-specific deviations?
108
+
109
+ ## Section 1.2. What a Normal Tree Leaf Does
110
+
111
+ In a standard gradient boosting tree, each leaf is simple. The data gets partitioned by the tree's splits, and every observation that lands in leaf j receives the same prediction: a single number w j. Student i from school 3 and student k from school 7, if they have similar covariate values and land in the same leaf, get the same predicted test score. The tree has no idea they come from different schools.
112
+
113
+ ## Section 1.3. What Our Leaf Does
114
+
115
+ In our decomposed tree, leaf j does not output a single number. It outputs a population-level prediction mu j plus a group-specific deviation b j g for each group g present in that leaf.
116
+
117
+ The prediction for observation i belonging to group g in leaf j is: prediction i equals mu j plus b j g.
118
+
119
+ mu j is the fixed component. It represents the population-average prediction for any observation landing in this leaf, regardless of which group it belongs to. It captures the covariate-driven signal: the effect of study hours, age, income, or whatever features the tree has split on.
120
+
121
+ b j g is the random effect for group g within this leaf. It captures how group g deviates from the population average in this region of covariate space. School 3 might be 2 points above average in this leaf, while school 7 is 1 point below.
122
+
123
+ The sum mu j plus b j g gives a group-personalized prediction that reflects both what the covariates say, through mu, and what the group membership says, through b.
124
+
125
+ Each leaf is, in effect, its own tiny mixed model. The tree structure handles the non-linear fixed effects by choosing where to split, and the within-leaf decomposition handles the group structure by estimating mu and b jointly.
126
+
127
+ ## Part 2: The Mathematics Inside the Leaf
128
+
129
+ ## Section 2.1. Setting Up the Leaf-Level Objective
130
+
131
+ Recall from gradient boosting that each leaf minimizes an objective built from the gradients g i and Hessians h i of the loss function. For a standard tree, the leaf objective is quadratic in the single weight w j. For our decomposed leaf, we need an objective that is quadratic in both mu j and all the b j g values.
132
+
133
+ The objective for leaf j is: Obj j equals the sum over groups g of the quantity G j g times the quantity mu j plus b j g, plus one half times H j g times the quantity mu j plus b j g squared, plus one half lambda times mu j squared, plus one over two sigma squared times the sum over g of b j g squared.
134
+
135
+ There are four distinct pieces. Let us go through each one carefully.
136
+
137
+ Piece 1: The Gradient Term. G j g times the quantity mu j plus b j g.
138
+
139
+ G j g is the sum of all gradients from observations belonging to group g in leaf j. Formally, G j g equals the sum of g i where the sum is over all observations i that are both in leaf j and in group g.
140
+
141
+ The gradient g i for each observation tells us the direction and magnitude of the error at the current prediction. For squared loss starting from the mean, g i equals negative y i minus y bar, so G j g is essentially the negative total residual for group g in this leaf.
142
+
143
+ Multiplying by the quantity mu j plus b j g means the contribution of this term depends on how large our prediction is. This is the linear term of the quadratic. It determines the direction of the optimum: should mu and b be positive or negative?
144
+
145
+ Piece 2: The Hessian Term. One half times H j g times the quantity mu j plus b j g, squared.
146
+
147
+ H j g is the sum of all Hessians from group g in leaf j. For squared loss, every h i equals 1, so H j g is just the count of observations from group g in the leaf.
148
+
149
+ This term is the curvature of the loss. Because it multiplies the prediction squared, it creates a bowl shape. The objective curves upward as the prediction moves away from the optimum in either direction.
150
+
151
+ The Hessian sum acts as a confidence measure: more observations from group g, meaning a larger H j g, means a steeper bowl, which means the optimum is more precisely located. Fewer observations means a flatter bowl, and the optimum is less certain.
152
+
153
+ Piece 3: The Fixed Effect Penalty. One half lambda times mu j squared.
154
+
155
+ Lambda is the L2 regularization parameter, the same one used in standard gradient boosting. This term penalizes large values of mu j, pulling the population-level prediction toward zero. It prevents the fixed component from overfitting. Without this penalty, mu j could take on extreme values, especially in leaves with few observations.
156
+
157
+ Piece 4: The Random Effects Penalty. This is the new ingredient. One over two sigma squared times the sum over g of b j g squared.
158
+
159
+ This is what makes our tree different from a standard tree. It penalizes the group-specific deviations.
160
+
161
+ Sigma squared is the random effects variance, a single number that controls how much groups are allowed to deviate from the population mean. It is the same concept as the variance component in a standard mixed model.
162
+
163
+ When sigma squared is large, the penalty 1 over sigma squared is small, so groups are allowed to deviate freely. The model trusts that groups genuinely differ.
164
+
165
+ When sigma squared is small, the penalty 1 over sigma squared is large, so group deviations are crushed toward zero. The model thinks groups are all similar, and individual group estimates are mostly noise.
166
+
167
+ The sum over g of b j g squared sums the squared deviations across all groups in the leaf. This is an L2 penalty on the random effects, which is mathematically equivalent to assuming the random effects are drawn from a normal distribution with mean zero and variance sigma squared. The penalty strength 1 over sigma squared is the precision, or inverse variance, of that prior.
168
+
169
+ This is the mechanism of shrinkage: group estimates are pulled toward zero by an amount that depends on how much data the group has versus how large sigma squared is.
170
+
171
+ ## Section 2.2. Solving for the Group Deviations b j g
172
+
173
+ The beautiful property of our objective is that it is quadratic in every variable. Quadratic functions have a unique minimum that can be found by taking the derivative, setting it to zero, and solving. No iterative algorithm is needed.
174
+
175
+ First, we solve for each group's deviation b j g, treating mu j as temporarily fixed. Take the partial derivative of the objective with respect to b j g and set it to zero.
176
+
177
+ The partial derivative of Obj j with respect to b j g equals G j g plus H j g times the quantity mu j plus b j g, plus 1 over sigma squared times b j g, and we set this equal to zero.
178
+
179
+ The first term G j g comes from differentiating the gradient term. It is the raw error signal from group g.
180
+
181
+ The second term H j g times the quantity mu j plus b j g comes from differentiating the Hessian term. It is the curvature pulling the prediction back.
182
+
183
+ The third term 1 over sigma squared times b j g comes from differentiating the random effects penalty. It is the shrinkage, pulling b toward zero.
184
+
185
+ Rearranging to isolate b j g, the optimal value is:
186
+
187
+ b j g star equals negative the quantity G j g plus H j g times mu j, all divided by the quantity H j g plus 1 over sigma squared.
188
+
189
+ The numerator is the adjusted error signal: the group's total gradient G j g, adjusted for the fixed component that mu j already explains, via H j g times mu j. If mu j already explains most of the signal, the residual for b j g is small.
190
+
191
+ The denominator has two parts that compete. H j g is the data signal. 1 over sigma squared is the shrinkage. When the data signal is strong, meaning many observations and a large H j g, the data wins and b j g reflects the group's true deviation. When the data signal is weak, meaning few observations, the shrinkage wins and b j g is pulled toward zero.
192
+
193
+ This is the James-Stein shrinkage phenomenon, emerging naturally from the penalized objective. A group with 3 observations cannot be estimated precisely, so the model relies on the prior that all groups are similar. A group with 200 observations can be estimated precisely, so the model trusts the data.
194
+
195
+ ## Section 2.3. Solving for the Fixed Component mu j
196
+
197
+ Now we substitute the optimal b j g back into the objective and solve for mu j. The algebra involves a key intermediate quantity.
198
+
199
+ Alpha g equals H j g divided by the quantity H j g plus 1 over sigma squared.
200
+
201
+ Alpha g is the fraction of the group's signal that gets absorbed by the random effect. It is always between 0 and 1.
202
+
203
+ When sigma squared is large, meaning groups vary a lot, alpha g is close to 1. The random effect absorbs nearly all the group-specific signal, and mu j only captures what is common across groups.
204
+
205
+ When sigma squared is small, meaning groups are similar, alpha g is close to 0. The random effect is suppressed, and nearly all signal flows into mu j.
206
+
207
+ When a group has many observations, meaning a large H j g, alpha g is larger. The model trusts the group estimate more. When a group has few observations, alpha g is smaller, and shrinkage is stronger.
208
+
209
+ The optimal mu j is:
210
+
211
+ mu j star equals negative the sum over g of G j g times the quantity 1 minus alpha g, all divided by the sum over g of H j g times the quantity 1 minus alpha g, plus lambda.
212
+
213
+ Each group's contribution to mu is weighted by 1 minus alpha g, the fraction of signal not absorbed by the random effect.
214
+
215
+ The numerator sums up the leftover gradient from all groups, the signal that the random effects did not claim.
216
+
217
+ The denominator sums up the leftover Hessians plus the regularization lambda.
218
+
219
+ The structure is exactly the standard leaf-weight formula negative G over H plus lambda, but with every quantity reweighted by the shrinkage factor 1 minus alpha g. The random effects have taken their share of the signal, and mu gets what remains.
220
+
221
+ ## Section 2.4. Why This Is Elegant
222
+
223
+ The entire within-leaf computation is a closed-form solution to a convex quadratic problem. No iterations, no convergence issues, no numerical instabilities. For each leaf, we compute mu j and all the b j g values in a single pass through the group-level statistics. The computational cost is proportional to the number of groups in the leaf, which is typically small.
224
+
225
+ ## Part 3: Sanity Checks. What Happens at the Extremes
226
+
227
+ A mathematical formula is only trustworthy if it behaves sensibly in extreme cases. We verified four critical limits.
228
+
229
+ ## Section 3.1. When sigma squared goes to zero: No Group Variation
230
+
231
+ If there is no between-group variation, meaning sigma squared equals zero, the penalty 1 over sigma squared becomes infinite, crushing every b j g to exactly zero. The formula for mu j reduces to: mu j star equals negative G j divided by the quantity H j plus lambda.
232
+
233
+ This is exactly the standard gradient boosting leaf weight formula. When there is no group structure, our tree becomes a normal tree. The decomposition adds nothing and subtracts nothing. The standard case is recovered as a special case.
234
+
235
+ ## Section 3.2. When sigma squared goes to infinity: Unrestricted Groups
236
+
237
+ If groups are allowed to vary without limit, the penalty vanishes, alpha g approaches 1 for all groups, and each b j g absorbs all the group-specific signal with no shrinkage. The leaf effectively fits separate constants for each group, with mu j becoming the unweighted grand mean.
238
+
239
+ This is a per-group model with no borrowing of strength. It overfits when groups are small, which is exactly why sigma squared should be finite in practice.
240
+
241
+ ## Section 3.3. When a Group Has One Observation in the Leaf
242
+
243
+ If group g has a single observation in leaf j, then H j g is just h i for that one point, which equals 1 for squared loss. The denominator H j g plus 1 over sigma squared is dominated by the shrinkage term 1 over sigma squared whenever sigma squared is not too large. The group deviation b j g is heavily shrunk toward zero.
244
+
245
+ The model does not overfit to a single data point. The shrinkage automatically distrusts small-sample group estimates. This is the James-Stein phenomenon: borrowing strength from the population to improve individual estimates.
246
+
247
+ ## Section 3.4. When All Observations Come from One Group
248
+
249
+ If leaf j contains observations from only one group, then mu j and b j g are not identifiable from data alone. Any amount can be shifted between them. But the two penalties resolve the ambiguity: lambda penalizes mu j and 1 over sigma squared penalizes b j g, so the model allocates signal between them according to the relative strength of the two penalties.
250
+
251
+ The system does not crash or produce nonsense when identification is weak. The penalties serve as priors that give a well-defined answer even in degenerate cases.
252
+
253
+ ## Part 4: How the Tree Decides Where to Split
254
+
255
+ ## Section 4.1. The Modified Gain Formula
256
+
257
+ A tree grows by evaluating candidate splits and choosing the one that improves the objective most. In a standard tree, the gain from splitting leaf j into left child L and right child R is:
258
+
259
+ Standard Gain equals one half times the quantity G L squared over H L plus lambda, plus G R squared over H R plus lambda, minus G j squared over H j plus lambda, minus gamma.
260
+
261
+ In our decomposed tree, each of the three terms is replaced by the full mixed-effects objective value, which accounts for the group structure and the random effects penalty.
262
+
263
+ Mixed Gain equals Obj j star minus Obj L star minus Obj R star, minus gamma.
264
+
265
+ Obj j star is the optimal objective value for the parent leaf before splitting, computed using the full mu and b solution. Obj L star and Obj R star are the optimal objective values for the left and right children after splitting, each computed with their own mu, b, and group compositions. If the gain is positive, the split improves the joint objective. If negative or zero, the split is not worth the added complexity.
266
+
267
+ ## Section 4.2. What the Modified Gain Captures That Standard Gain Misses
268
+
269
+ The standard gain measures one thing: does splitting reduce the total squared error? The mixed gain measures three things simultaneously.
270
+
271
+ First, fixed effects improvement. Does splitting create more homogeneous covariate regions? This is the same as standard.
272
+
273
+ Second, random effects allocation. Does splitting separate groups in a way that produces cleaner group estimates? A split might put mostly school 3 students on the left and mostly school 7 students on the right, allowing each child to estimate its group effects with less interference.
274
+
275
+ Third, penalty change. Does splitting increase or decrease the total random effects penalty? If a split creates a child where one group has very few observations, the shrinkage will be very strong for that group in that child, changing the objective.
276
+
277
+ ## Part 5: How This Fits into a Boosted Ensemble
278
+
279
+ ## Section 5.1. The Learning Rate Applies to Everything
280
+
281
+ In a boosted ensemble, each tree's contribution is multiplied by a learning rate nu, typically between 0.01 and 0.3. For our decomposed tree, nu multiplies the entire leaf output.
282
+
283
+ y hat i at round t equals y hat i at round t minus 1, plus nu times the quantity mu j plus b j g.
284
+
285
+ Both mu and b are shrunk by the same learning rate. This is essential. If only mu were shrunk, the random effects would dominate after a few rounds and absorb everything. If only b were shrunk, the fixed effects would dominate and the random effects would never express themselves.
286
+
287
+ ## Section 5.2. What Later Trees See
288
+
289
+ At round t, the pseudo-residuals are computed from the current total prediction, which includes all previous shrunken mu and b contributions. Early trees see large group-level variation in the residuals and allocate substantial b values. Later trees see smaller group residuals and allocate smaller b values. The random effects contribution naturally decays as the ensemble matures.
290
+
291
+ ## Section 5.3. Emergent Random Effects Structure
292
+
293
+ Across the full ensemble, the effective random effect for group g at observation i is the sum of all the leaf-local b values from every tree, each scaled by nu. Because different trees partition the covariate space differently, this sum can vary by observation within the same group.
294
+
295
+ This is not a bug. It is a generalization. A standard random intercept model says school 7 is 3 points above average for all its students. Our decomposed approach says school 7 is 4 points above average for its high-performing students and 1 point below average for its struggling students. Random slopes and random interactions emerge automatically from the tree structure without being parametrically specified.
296
+
297
+ ## Section 5.4. Updating Sigma Squared
298
+
299
+ After each boosting round, we update the global sigma squared estimate from the collection of b values. The estimate feeds into the next tree's shrinkage calibration. This creates a self-correcting feedback loop: if sigma squared is overestimated, meaning too little shrinkage, the b values will be noisy, residuals will not improve much, and subsequent trees will correct. If sigma squared is underestimated, meaning too much shrinkage, residuals retain group structure that later trees pick up.
300
+
301
+ ## Part 6: Experimental Validation
302
+
303
+ ## Section 6.1. Base Case: Recovering a Known Signal
304
+
305
+ We generated data from a known process: y equals 3 times sine of x 1 plus 2 times x 2 plus 1.5 times x 1 times x 2 plus b g plus epsilon, with 30 groups, 40 observations per group, true sigma squared equals 4.0, and noise variance 1.0.
306
+
307
+ The mixed tree recovered the total signal with MSE of 1.00, essentially the irreducible noise floor. The standard tree was at 3.83, meaning nearly 3 units of MSE were group variation it could not capture. The mixed tree's fixed effects were also cleaner because the group variation was properly separated, freeing the tree structure to focus on the covariate signal.
308
+
309
+ ## Section 6.2. Stress Tests: Nine Scenarios
310
+
311
+ We tested the decomposed tree under nine increasingly difficult scenarios. The mixed tree outperformed the standard tree in every single test.
312
+
313
+ Random slopes: standard MSE 9.87, mixed MSE 1.35, an 86 percent improvement. Complex non-linear fixed effects: 70 percent improvement. Severely unbalanced groups with sizes from 3 to 200: 87 percent improvement. 200 groups with only 5 observations each: 82 percent improvement. Group-covariate confounding: 53 percent improvement. Crossed effects with an unmodeled site variable: 71 percent improvement. 50 features with only 2 carrying signal: 85 percent improvement. Weak signal with strong groups: 99 percent improvement. Non-Gaussian random effects: 90 percent improvement.
314
+
315
+ ## Section 6.3. Key Findings from the Stress Tests
316
+
317
+ Random slopes emerged naturally. When the true group effect varied with a covariate, the tree captured this by assigning different b values to the same group in different leaves. The correlation with the true group effects was 0.993. Random slopes were never specified. They emerged from the interaction of tree structure and local group estimation.
318
+
319
+ Unbalanced groups were handled by shrinkage. Groups with 3 observations had their b values heavily shrunk toward zero, appropriately distrusting the noisy estimate. Groups with 200 observations were estimated with high fidelity. No manual tuning was needed.
320
+
321
+ Confounding was the hardest case. When group effects correlated 0.87 with a covariate, the improvement was only 53 percent. This is expected: when b and x are entangled, the boundary between fixed and random is genuinely ambiguous.
322
+
323
+ Non-Gaussian random effects did not matter much. With skewness of 2.73, the recovery was 90 percent. The Gaussian shrinkage assumption is violated but the per-group, per-leaf estimation is flexible enough to absorb non-Gaussian shapes.
324
+
325
+ ## Part 7: Why This Architecture Solves the Known Problems
326
+
327
+ Problem Solved: Fixed-Random Competition. In existing methods like mboost and MERF, fixed and random effects compete for selection at each iteration. In our approach, there is no competition. Every leaf always computes both mu and b jointly. The fixed component and the random component are solved simultaneously from the same objective.
328
+
329
+ Problem Solved: Cluster-Constant Confounding. In MERMBoost, a special correction is needed for covariates that are constant within clusters. In our approach, this correction is structural. The tree splits on covariates, never on the group identifier. Every leaf therefore contains a mix of groups. Within each leaf, mu captures what is common across groups and b captures what is group-specific.
330
+
331
+ Problem Solved: Covariance Estimation. Standard boosting packages that include random effects estimate b values but not the covariance structure. Our approach produces b values at every leaf, and sigma squared is estimated directly from these values.
332
+
333
+ Problem Addressed: Sequential Bias. GPBoost and MEGB alternate between boosting the fixed effects and estimating the variance parameters, creating sequential bias because each step uses a stale estimate from the other. In our approach, each tree's within-leaf optimization solves for mu and b jointly, conditional on the current sigma squared. This substantially reduces though does not completely eliminate the sequential dependence.
334
+
335
+ Theoretical Foundation. The within-leaf optimization is convex quadratic with a unique closed-form solution. The splitting criterion directly measures improvement in the joint objective. Each split provably decreases the penalized loss, providing the monotonicity condition needed for formal convergence analysis. No other existing method has all three of these properties.
336
+
337
+ End of document.
lectures/embedders.md ADDED
@@ -0,0 +1,224 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # How Embedder Models Are Trained
2
+
3
+ *A step-by-step walkthrough of the pipeline that turns a pretrained transformer into a semantic search workhorse.*
4
+
5
+ ---
6
+
7
+ ## Opening Framing
8
+
9
+ When you use a chat model like GPT or Claude, you're talking to a **generative transformer**. But quietly running alongside those flashy models is a whole other class of transformer — the **embedder**. Embedders are the workhorses of semantic search, retrieval-augmented generation, clustering, duplicate detection, and almost any task where you need to compare two pieces of text by meaning rather than by exact words. And they're trained in a way that's quite different from how generative models are trained.
10
+
11
+ ---
12
+
13
+ ## 1. What an Embedder Actually Is
14
+
15
+ An embedder takes a piece of text — anywhere from a single word to a long document — and produces a **fixed-length vector** of numbers. The vector is usually somewhere between 300 and 4,000 numbers long. That's it. No next token, no generated text, no probability distribution. Just one vector per input.
16
+
17
+ The magic isn't in the vector itself. It's in what the **vector space** means. An embedder is trained so that texts with similar meanings produce nearby vectors, and texts with different meanings produce distant vectors. You measure similarity with **cosine similarity** (the angle between two vectors) or **dot product**.
18
+
19
+ Once you have that, remarkable things become possible:
20
+
21
+ - Embed a user question, compare against embedded documents, find the most relevant.
22
+ - Cluster a million customer reviews by topic without defining the topics.
23
+ - Detect duplicates across different phrasings.
24
+
25
+ The embedder is a machine that **compresses meaning into geometry**.
26
+
27
+ ---
28
+
29
+ ## 2. The Core Training Goal
30
+
31
+ The goal is simple:
32
+
33
+ > Given two pieces of text that ought to be similar, make their vectors close. Given two pieces of text that ought to be different, make their vectors far apart.
34
+
35
+ Every technical decision in embedder training is in service of this one idea.
36
+
37
+ ---
38
+
39
+ ## 3. Architecture: From Tokens to a Single Vector
40
+
41
+ Almost every modern embedder **starts from a pretrained transformer** — usually an encoder-style one like BERT, though decoder-style transformers are increasingly used too. The pretrained model already knows grammar, word meanings, and context. We're teaching it to produce useful summary vectors.
42
+
43
+ A transformer outputs one vector **per token**. We need a single vector per input. So we **pool**:
44
+
45
+ | Pooling method | How it works |
46
+ |---|---|
47
+ | **CLS pooling** | Use the representation of the special `[CLS]` token (BERT's original approach) |
48
+ | **Mean pooling** | Average all output token vectors — often works surprisingly well |
49
+ | **Max pooling** | Take the element-wise max across tokens |
50
+ | **Attention pooling** | A small learned mechanism weights the tokens |
51
+
52
+ After pooling, many embedders add a small **projection head** (a couple of linear layers) to map to the final embedding dimension. Finally, the output is **L2 normalized** (divided by its own length) so every vector has magnitude 1. Once vectors are unit length, dot product and cosine similarity become the same thing.
53
+
54
+ ---
55
+
56
+ ## 4. Contrastive Learning: The Core Training Trick
57
+
58
+ The dominant training technique is **contrastive learning**. You need:
59
+
60
+ - **Positive pairs** — two pieces of text that belong together semantically
61
+ - **Negative pairs** — two pieces of text that don't
62
+
63
+ ### Where positive pairs come from
64
+
65
+ You can't get them from humans at scale, so researchers mine them in the wild:
66
+
67
+ - **Q&A sites** (Stack Exchange, Reddit): question + accepted answer
68
+ - **Wikipedia**: article title + opening paragraph
69
+ - **Research papers**: title + abstract, or citation pairs
70
+ - **Search logs**: query + click (gold standard — a human thought it was relevant)
71
+ - **Products**: title + description
72
+
73
+ ### In-Batch Negatives
74
+
75
+ Instead of curating negatives explicitly, use the **other examples in the training batch**. With a batch of 128 positive pairs, for any given pair the positive is its partner and the 127 other second-elements serve as negatives. You get 127 negatives for free per positive.
76
+
77
+ ---
78
+
79
+ ## 5. The InfoNCE Loss
80
+
81
+ The standard contrastive loss is **InfoNCE** (noise contrastive estimation), also called **NT-Xent** (normalized temperature-scaled cross-entropy).
82
+
83
+ For each anchor query:
84
+ 1. Compute its similarity to every candidate in the batch.
85
+ 2. Divide by a **temperature parameter** τ.
86
+ 3. Apply softmax.
87
+ 4. The loss is the negative log probability of the correct positive.
88
+
89
+ In plain language: *"Here's a query. Which of these 128 candidates is its true partner? Pick one."*
90
+
91
+ ### Temperature Matters
92
+
93
+ | τ value | Effect |
94
+ |---|---|
95
+ | **0.02 – 0.05** (low) | Peaky softmax — forces the model to discriminate between similar candidates |
96
+ | **0.1 – 0.2** (higher) | Softer softmax — more forgiving, trains stably, less final sharpness |
97
+
98
+ Production embedders typically use **τ ∈ [0.02, 0.1]**. One of the most important hyperparameters.
99
+
100
+ ### Why Batch Size Is Huge
101
+
102
+ Because negatives come from inside the batch, **bigger batch = more negatives per step = stronger training signal**. Small batches (64–128) work okay. Large batches (8K–64K) produce dramatically better embedders. This is why top embedder models train on large clusters with aggressive memory optimization.
103
+
104
+ ---
105
+
106
+ ## 6. The Multi-Stage Training Pipeline
107
+
108
+ Training a modern embedder is not one run. It's a **pipeline of stages**.
109
+
110
+ ### Stage 1: Weakly Supervised Contrastive Pretraining
111
+
112
+ - **Data**: hundreds of millions to billions of noisy pairs mined from the open web
113
+ - **Sources**: Reddit, Stack Exchange, Wikipedia, academic papers, product catalogs
114
+ - **Duration**: hundreds of thousands of steps, batch sizes in the thousands
115
+ - **Result**: a model that knows the broad shape of semantic space
116
+
117
+ The pairs are noisy. Many are imperfect. But the dataset is huge and diverse, so the model learns the general contours of meaning.
118
+
119
+ ### Stage 2: Supervised Fine-Tuning
120
+
121
+ - **Data**: much smaller (few hundred thousand to a few million), but cleaner
122
+ - **Popular datasets**: MS MARCO (Bing query-document), Natural Questions (Google), SNLI, MultiNLI
123
+ - **Result**: specific task competence — e.g., excellent passage ranking for queries
124
+
125
+ Pretraining gave general semantic sense. Fine-tuning gives specific behavior.
126
+
127
+ ### Stage 3: Hard Negative Mining (Iterative)
128
+
129
+ In-batch negatives are cheap but often **too easy**. A Python question vs. a lasagna recipe is trivial to distinguish. The informative negatives are the **almost-right** ones:
130
+
131
+ - Python question paired with a JavaScript answer
132
+ - Medical query paired with a veterinary document
133
+
134
+ **How to mine them:**
135
+
136
+ 1. Use the current embedder.
137
+ 2. For each query in the training set, retrieve the top 100 most similar documents.
138
+ 3. The true positive is somewhere in the top results. Everything else in the top 100 is a plausible-but-wrong match — a hard negative.
139
+ 4. Add them to training. Retrain.
140
+ 5. Repeat 3–4 times. Each round the model's judgment of "hard" gets sharper.
141
+
142
+ Top embedders (BGE, E5, Jina) all use multi-round hard negative mining as a core part of their recipe. Recent work also uses LLMs to **generate synthetic hard negatives**.
143
+
144
+ ### Stage 4: Task-Specific Fine-Tuning (Optional)
145
+
146
+ If you know the domain (legal docs, scientific papers, code), one final tune on a small amount of in-domain data produces significant gains.
147
+
148
+ ---
149
+
150
+ ## 7. Evaluation: MTEB and Its Subtleties
151
+
152
+ The dominant benchmark is **MTEB** (Massive Text Embedding Benchmark). It aggregates dozens of tasks:
153
+
154
+ - Retrieval
155
+ - Classification
156
+ - Clustering
157
+ - Reranking
158
+ - Pair classification
159
+ - Summarization similarity
160
+ - Semantic textual similarity (STS)
161
+
162
+ ### The Key Insight
163
+
164
+ **These tasks don't all want the same thing.**
165
+
166
+ | Task | What it wants |
167
+ |---|---|
168
+ | Retrieval | Precisely calibrated query-document matching |
169
+ | Classification | Embeddings that linearly separate class labels |
170
+ | Clustering | Tight, intuitive groups |
171
+ | STS | Fine-grained similarity judgments between pairs |
172
+
173
+ There is no single best embedder. An embedder amazing at retrieval might be merely okay at clustering. Modern releases often include several sizes and variants — small fast, big accurate, specialized.
174
+
175
+ ---
176
+
177
+ ## 8. Modern Wrinkles
178
+
179
+ ### Matryoshka Embeddings
180
+
181
+ Train the model so that the **first N dimensions** of the output are themselves a valid, shorter embedding. A model produces a 4000-D vector, but the first 2000 work, and the first 1000 work, and the first 500 work — all the way down. Done by computing the contrastive loss on truncated versions as well as the full vector and averaging.
182
+
183
+ Result: **trade quality for speed at inference time by just truncating the vector**. Huge win for production, where storage and compute scale linearly with dimension.
184
+
185
+ ### Instruction-Tuned Embeddings
186
+
187
+ The same text might need to be embedded differently depending on the downstream task. Instruction-tuned embedders accept a natural-language prefix:
188
+
189
+ > `"Represent this sentence for retrieving related Wikipedia articles: climate change"`
190
+
191
+ The model uses the instruction to shape the embedding. One model usable across many tasks without retraining. Pioneered by the **E5** and **Instructor** families.
192
+
193
+ ### Late Interaction (ColBERT)
194
+
195
+ All the embedders above produce **one vector per document**. ColBERT keeps **one vector per token**. At query time it matches each query token to its best document token and sums.
196
+
197
+ | | Single-vector | ColBERT (late interaction) | Cross-encoder |
198
+ |---|---|---|---|
199
+ | Expressiveness | Low | Medium | High |
200
+ | Storage | Small | Large | N/A (scores at query time) |
201
+ | Query speed | Fast | Medium | Slow |
202
+
203
+ ColBERT sits in the middle ground between fast single-vector retrieval and slow-but-accurate cross-encoder reranking.
204
+
205
+ ---
206
+
207
+ ## 9. Tying It Together
208
+
209
+ We started with a goal: train a model that maps text to vectors where similar meanings are close and different meanings are far.
210
+
211
+ We took a pretrained transformer → added pooling → trained with **contrastive learning** → used **positive pairs** from naturally occurring sources → used **in-batch negatives** scaled by a **temperature parameter** → ran a **multi-stage pipeline** (weak pretraining → supervised fine-tune → hard negative mining → optional task tune) → evaluated on **MTEB** → layered on **Matryoshka**, **instruction tuning**, and **late interaction** as needed.
212
+
213
+ Every step was a decision. Every decision a tradeoff:
214
+
215
+ | Decision | Tradeoff |
216
+ |---|---|
217
+ | Bigger batch | Better negatives ↔ more memory |
218
+ | Harder negatives | Better discrimination ↔ expensive to mine |
219
+ | Larger dimension | Richer embeddings ↔ more storage |
220
+ | Instruction tuning | Task flexibility ↔ more complexity |
221
+
222
+ The next time you use semantic search, RAG, or any system that compares text by meaning, there's an embedder underneath doing the work — and it got good at its job through this exact pipeline: a pretrained language model, taught by contrast, refined by mining, evaluated against a dozen notions of "good."
223
+
224
+ That's how you train a machine to understand meaning well enough to put it on a map.
lectures/hardware-ouro.md ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Making Ouro Fast
2
+
3
+ ### A technical lecture on optimizing a recurrent-depth model for GPU inference
4
+
5
+ *Approx. 30–35 minutes spoken. Written to be listened to — the numbers and the reasoning are spoken aloud rather than rendered in tables, so it reads cleanly through a text-to-speech engine. A hardware companion to "Thinking in the Dark": that lecture is about why recurrent-depth models think the way they do; this one is about making them run fast without changing a single answer.*
6
+
7
+ ---
8
+
9
+ ## Cold open
10
+
11
+ Welcome back. Today I want to walk you through a piece of systems work: the effort to make a recurrent-depth language model run faster on a GPU, without changing a single one of its answers. That last part is the whole discipline. It is easy to make a model faster if you are allowed to make it a little bit wrong. The hard, honest game is to make it faster while proving, at every step, that the output is exactly what it was before.
12
+
13
+ The model at the center of this is Ouro, ByteDance's family of recurrent-depth models. And to understand why the optimizations look the way they do, you first have to understand the one strange thing Ouro does differently from an ordinary transformer. So let's start there, and then I'll take you through what we built, in the order we built it, and where the work goes next.
14
+
15
+ ---
16
+
17
+ ## Part one — why a looping model is expensive
18
+
19
+ Here is the core idea. A normal transformer runs each token through its stack of layers exactly once. Ouro does not. Ouro takes its stack of layers and runs it in a loop, several times, for every single token, before it emits anything. The config has a knob for this called total-u-t-steps, the number of universal-transformer steps, and you can set it to one, two, four, and so on. So when we talk about a ninety-six-layer effective forward pass at four steps, what is physically there is twenty-four layers, replayed four times over.
20
+
21
+ Now, why does that matter for hardware? Two consequences, and they drive everything.
22
+
23
+ The first consequence is the key-value cache. In any transformer, as you generate, you cache the keys and values from previous positions so you don't recompute them. But because Ouro replays its layers, the effective number of cache layers is the number of loop steps multiplied by the number of physical layers. For the one-point-four-billion parameter Ouro at four steps, that is ninety-six cache layers. Concretely, that works out to about seven hundred and eighty-six kilobytes of cache for every single token, which climbs to roughly three gigabytes once you are a few thousand tokens into a context. The loop multiplies your memory footprint.
24
+
25
+ The second consequence is latency, and this is the one we measured directly, so hold onto it. Decode time — the time to produce each new token — scales almost linearly with the loop depth. At one loop step, producing a token took about thirteen milliseconds. At two steps, about twenty-five. At four steps, about forty-nine. The loop is not a detail. The loop is the cost.
26
+
27
+ So the whole project is, in one sentence: pay that loop tax more cheaply, and never change the answer while doing it.
28
+
29
+ Hold onto that framing. Everything from here follows from it.
30
+
31
+ ---
32
+
33
+ ## Part two — the method, which matters more than any single trick
34
+
35
+ Before I show you a single optimization, I want to talk about how we work, because the discipline explains the shape of everything else.
36
+
37
+ The first principle is exact-first, approximate-later. The default path is exact. Every optimization has to first prove it produces identical output — the same generated tokens, and ideally the prefill logits are bit-for-bit identical, a maximum absolute difference of exactly zero — before it is allowed to count as done. Only after the exact paths are built and measured do we allow ourselves to reach for approximate tricks, like quantization or cache reuse or parallel sampling. And when we do, those live behind an explicit switch, with a way to fall straight back to exact. A speedup that is bit-exact is a free speedup. A speedup that is only approximately correct is a quality-gated speedup, and it is never, ever allowed to become the default silently. You will hear that distinction over and over.
38
+
39
+ The second principle is that every optimization is reversible. We apply changes as patches — little functions that wrap or swap parts of the model — and every patch has a matching restore function, or it is simply a command-line flag you can choose not to pass. Nothing rewrites the model permanently. There is always a documented way back.
40
+
41
+ The third principle is about the hardware itself. GPU runs go out to a rented instance on a marketplace — mostly an RTX PRO six-thousand Blackwell card, some earlier runs on an H100. And the rule there is strict: rent the machine, run one bounded job, and then tear the instance and its temporary key down immediately, in a cleanup block that runs whether the job succeeded or failed. We track the cost to the cent. Local development uses tiny models on the CPU so that nothing paid ever runs by accident.
42
+
43
+ And the fourth principle is simply: write everything down. Every phase records its goal, the files it changed, the exact commands, the verification result, the numbers, the rollback path, and the follow-ups. That written ledger is the reason we can trust any of the numbers I'm about to give you.
44
+
45
+ So the rule, in a breath: prove it's exact, keep it reversible, measure it on a machine you immediately give back, and log all of it. The kernels are almost the easy part.
46
+
47
+ ---
48
+
49
+ ## Part three — build the ruler before you cut
50
+
51
+ You cannot optimize what you cannot measure, so the very first work was not a kernel at all. It was a measurement harness.
52
+
53
+ There are two halves to the codebase. One half is the performance library, which knows how to time things and count things: it measures time-to-first-token, time-per-output-token, end-to-end latency, tokens per second, peak GPU memory, and it has an estimator for how many bytes the key-value cache will consume. The other half is the optimization library, which holds the actual patches — and at the start it was mostly empty, waiting to be filled one phase at a time.
54
+
55
+ Let me give you the vocabulary you'll need for the rest of this lecture, because I'll lean on three numbers. Time-to-first-token is dominated by prefill, the processing of the prompt. Time-per-output-token is dominated by decode, the generation loop — and that is where the loop depth hurts. And end-to-end is just the whole thing, start to finish.
56
+
57
+ The point of this phase was to build a trustworthy ruler and prove it read correctly. As a sanity check, the cache estimator predicted seven hundred eighty-six thousand four hundred and thirty-two bytes per token for the one-point-four-billion model at four steps — the same number I quoted you earlier, now coming out of the tool rather than off a napkin.
58
+
59
+ ---
60
+
61
+ ## Part four — the measurement that set the whole agenda
62
+
63
+ With the ruler built, we ran the model across a grid: a few prompt lengths, a couple of output lengths, and loop depths of one, two, and four. Fifty-four measurements on an H100, and then, as always, we deleted the machine.
64
+
65
+ And here is the result that shaped everything after it. Time-per-output-token scaled almost perfectly with loop depth: about thirteen milliseconds at one step, twenty-five at two, forty-nine at four. Meanwhile, the prompt length barely moved the per-token decode time at all — longer prompts mostly cost more at prefill and in memory, not in the steady-state generation loop.
66
+
67
+ Think about what that tells you. The profitable place to cut is the per-decode-step work, the thing that gets replayed once for every loop step. That is the cache growth, the linear projections, the normalization layers, and the sheer overhead of launching kernels. That ranking — attack the decode step, leave prefill alone — is exactly the order the rest of the work follows.
68
+
69
+ ---
70
+
71
+ ## Part five — the exact optimizations, one at a time
72
+
73
+ The plan lists the exact optimizations in a deliberate order: first a flat cache, then packed projections, then fused normalization, then CUDA graphs, and finally an exact paged cache — which we have now built, and then fused with the graphs to unlock the biggest decode win yet. Let me tell you the story of each, because each one taught us something.
74
+
75
+ ### The flat cache
76
+
77
+ Start with the cache. The standard Hugging Face cache grows its key and value tensors by concatenation — every new token, it glues a slice onto the end, which quietly reallocates and copies the whole thing. Because Ouro loops, that happens a staggering number of times. In one short baseline workload, we counted fourteen hundred and forty of those concatenation calls.
78
+
79
+ The fix is to stop growing and start writing into place. We preallocate one big arena, sized to the full prompt-plus-output length up front, and each step simply writes into the correct slice of it. No concatenation, ever.
80
+
81
+ And here is the honest part of the story, the part I want you to remember. The correctness was perfect on the first try: the generated tokens matched, the logits differed by exactly zero, and those fourteen hundred and forty concatenation calls dropped to zero. But the first version was slower. Slower, despite doing less allocation, because the Python-side bookkeeping and the strided views into that big preallocated block cost more than they saved. It was correct immediately and fast not at all.
82
+
83
+ So there was a grind — several sub-phases of it. We built a dedicated micro-benchmark just for the cache-update hot path, so we could iterate cheaply in isolation instead of spinning up the whole model. We rejected one tempting shortcut that would have compromised exactness. And we ground the write path down with more direct views and lower-level indexing, tracked in a whole series of before-and-after measurements. That is the real texture of optimization: exactness is a gate you pass once, but performance is a hill you climb over several attempts.
84
+
85
+ ### Packed projections
86
+
87
+ Next, the projections. In each decode step, the model does separate matrix multiplies for the query, the key, and the value — and separately again for the two halves of its gated feed-forward network, the gate and the up projection. On a single-token decode, each of those separate matmuls is its own kernel launch, and the overhead of launching them dominates the tiny amount of actual math.
88
+
89
+ So we pack them. Concatenate the weight matrices, do one larger matmul, then slice the result back apart. We did this first for the query-key-value projection, then for the feed-forward gate and up projection, and then combined both in one full-model test.
90
+
91
+ The result was a clean, exact win: roughly seven percent faster decode, with the generated tokens and prefill logits still bit-identical. But there was a catch worth naming, because it is a consequence of our own rules. Peak memory went up by about one-point-six gigabytes. Why? Because the reversible patch keeps the original separate weight matrices registered alongside the new packed ones, so that you can always roll back and so the saved-model format stays compatible. Reversibility is not free — you are, in effect, keeping the old parts in the drawer so you can always put them back. A follow-up that is not reversible could reclaim that memory once we trust the exactness enough to stop hedging.
92
+
93
+ ### Fused normalization
94
+
95
+ Now the normalization layers. Each decoder layer normalizes twice, and each normalization is paired with a residual add. On a single-token decode, that is a swarm of tiny elementwise operations, each one too small to keep the GPU busy. The idea is to fuse them into a single custom kernel.
96
+
97
+ We built this in two stages. First a scaffold: a plain reference implementation in the framework's own math, matching Ouro's normalization exactly, plus optional hand-written Triton kernels for the standalone norm and for the fused residual-plus-norm. On the kernel in isolation, the fused Triton version was about two-point-three times faster than the naive path.
98
+
99
+ Then we promoted it to a full-model test with strict parity checks — and this is the most instructive result in the whole project, so let me slow down. There were two backends. The framework-math backend was bit-exact: identical tokens, logits differing by exactly zero. But it gave no real speedup at the full-model level. The Triton backend was the opposite: it produced the same generated tokens and it was about twenty-five percent faster end-to-end — but its prefill logits were not bit-exact. They differed by about one-eighth in absolute terms.
100
+
101
+ Under our rules, that difference is disqualifying for a default path. So the fast kernel does not get promoted. It survives only as an opt-in, quality-gated branch, something you can turn on deliberately if you have decided the small numerical drift is acceptable for your use. The exact framework-math version, meanwhile, gets carried forward as a parity-proven, reversible hook — not as a performance win, but as a correct building block.
102
+
103
+ This is the clearest illustration of the entire philosophy. A twenty-five percent speedup that is not bit-exact does not get to be the default. Speed never quietly overrules correctness.
104
+
105
+ ### CUDA graphs
106
+
107
+ The last of the finished work, and the biggest decode win so far, is CUDA graphs. Even with fused kernels, launching hundreds of GPU operations per decode step from Python carries overhead — and remember, Ouro pays that overhead once per loop step. A CUDA graph records a fixed sequence of GPU operations one time, and then replays the whole thing with a single launch, erasing the per-launch cost. The price of admission is rigidity: a graph demands static shapes and static memory addresses, which is exactly what variable-length text generation does not naturally give you.
108
+
109
+ So this phase climbed a ladder of increasing realism, five rungs.
110
+
111
+ First, a synthetic gate: prove the mechanism on a fake Ouro-shaped decode loop. The replay was exact, and about one-point-three times faster. That established that capture and replay work at all, and that they have to be bucketed by shape.
112
+
113
+ Second, a full-model, single-token feasibility test on the real one-point-four-billion model. Exact replay again, and now about two-and-a-half times faster on the decode. This rung also surfaced a real discovery: the ordinary all-ones attention mask breaks graph capture inside the framework's mask-creation code — it hits an operation that CUDA graph capture simply does not support. So we switched to a no-padding decode bucket, and we keep the padded-mask path flagged as known-unsafe.
114
+
115
+ Third, an advancing multi-token chain. Rather than one token, we generate a short chain by capturing one graph per fixed cache position, and feeding each step's chosen token into the next. Exact chain, about two-and-a-half times faster again.
116
+
117
+ Fourth, we refactored that prototype out of the benchmark and into a real, reusable generation helper, with proper prompt-length and output-length bucket metadata. On the bucket we tested, this reached about three-point-seven times faster on decode. This rung also caught a measurement bug in ourselves — the graph timing had accidentally been including a reference check, which we corrected by snapshotting the replay time before the check runs. Worth saying out loud: measuring honestly includes catching your own measurement mistakes.
118
+
119
+ And the fifth rung extended that single bucket into a sweep across many prompt and output lengths, so we could study how the one-time cost of capturing a graph gets amortized as the output grows.
120
+
121
+ So the summary on CUDA graphs, as of that stage: the largest exact decode win we had, somewhere between two-and-a-half and three-point-seven times, but bucketed and fragile. Static shapes only, no-padding masks only, and one captured graph *per decode position*. A single reusable graph, with a cache-write offset driven by a tensor, was still unproven — and that was precisely the open research edge. Which brings us to the piece that closed it.
122
+
123
+ ### The paged cache, and the reusable graph it unlocked
124
+
125
+ The last exact optimization on the list was the paged cache. Instead of one giant preallocated block, store the memory in fixed-size pages, like the pages of a real book, tracked by a little index that says which page holds which position. On its own this is about flexibility — it makes variable lengths and batching far cleaner. We built it, we gave it a proper full-model exactness gate against the baseline, and it passed at exactly zero difference. Worth being honest, though: in plain step-by-step decoding the paged cache is currently *slower* than the baseline, just as the flat cache was at first. Exact, but not yet a speed win by itself.
126
+
127
+ The payoff is what the pages unlock. Because each page sits at a fixed address, you can finally record **one** graph and, between replays, just point it at the next page by writing a couple of small position tensors — instead of recording a separate graph for every position. We wired the paged cache into the graph path and added exactly that mode. It captures a single graph, replays it down the chain by updating token and position tensors, and it matches the plain version at zero difference, about three-and-a-half times faster than eager. One capture instead of many. And a bonus fell out: the all-ones attention mask that used to crash graph capture is, on these no-padding buckets, equivalent to having no mask at all — so routing it through the no-mask path made it graph-safe. Two of the open edges, closed in one phase.
128
+
129
+ ---
130
+
131
+ ## Part six — where we stand
132
+
133
+ Let me give you the scoreboard in plain words. Every phase I'm about to name cleared the exactness bar unless I say otherwise.
134
+
135
+ The benchmark harness and the baseline matrix are done — and they are what told us the loop depth is the enemy. The flat preallocated cache is done and exact; it took the concatenation calls from fourteen hundred and forty down to zero, and its performance was tuned over several follow-on phases. The packed query-key-value and feed-forward projections are done and exact, buying about seven percent on decode; the extra memory they used to cost from staying reversible has since been cleaned up, so the packed path is memory-neutral by default and still rebuilds the originals on rollback. The normalization work is done, with the framework-math version exact and the faster Triton version deliberately held back behind a quality gate. The CUDA graph decode replay is done and exact on no-padding buckets, worth somewhere from two-and-a-half to three-point-seven times. And the paged cache is now done and exact too — with a full-model gate that passed at zero difference — and, most importantly, fused with the graphs to give a single reusable recording that runs about three-and-a-half times faster than eager. That completes the exact roadmap. Every landed optimization matches the original bit-for-bit, and at that point the local test suite stood at a hundred and one passing — it has since grown well past two hundred as the frontier work in the coming parts landed.
136
+
137
+ A few standing decisions anchor all of this. Exact behavior comes before any kernel work or any approximate shortcut. The cache math is always the loop steps times the layer count. Rented machines are always bounded and always torn down immediately. And we pin the framework versions so that a run today is comparable to a run last week.
138
+
139
+ ---
140
+
141
+ ## Part seven — a surprise about what "exact" really has to mean
142
+
143
+ With the exact roadmap essentially complete, we opened the door we'd kept shut on purpose: the approximate frontier. And the very first thing we did there was interrogate our own central rule.
144
+
145
+ We had been treating "not bit-exact" as "disqualified." But step back and ask the honest question. When a faster kernel produces a number that differs in the eighth decimal place, is that a *worse* answer — or just a *different, equally good* one? We had been assuming the former. So we built a probe to actually measure it, and pointed it at the two inexact things we had on hand: the faster Triton normalization, and the occasional rounding flips inside the parallel decoder we'll get to in a moment.
146
+
147
+ The results were clarifying. On a corpus of text, perplexity — the standard measure of how well the model predicts — barely moved. A quarter of one percent, sitting inside the noise, and if anything slightly *better*. The full probability distributions the two versions produced were nearly identical: a Kullback-Leibler divergence of eight ten-thousandths of a nat, which is to say, almost nothing. On open-ended greedy generation, the exact and the inexact versions produced byte-for-byte identical text. And the parallel decoder's occasional flipped token never once changed a final math answer across the set we tried.
148
+
149
+ So the discipline matured, and this is the important beat of the whole second half. Bit-exactness was only ever a *proxy* for the thing we actually care about, which is that the quality didn't change. And it turns out to be an over-strict proxy. The honest gate is not "are the bits identical," it is "did the quality measurably degrade" — measured on perplexity and task accuracy, not assumed from a logit difference. This did not loosen the rule. It sharpened it. We could now promote a numerically-inexact optimization if, and only if, we could *prove* it costs nothing that matters. Hold onto that, because it is the license for everything that follows.
150
+
151
+ ---
152
+
153
+ ## Part eight — emitting more than one token per expensive loop
154
+
155
+ Here is the single biggest idea in the second half of the work. Ouro pays its loop tax once per token. So the question that dominates everything is: could we emit *several* tokens per expensive forward pass?
156
+
157
+ The technique is called speculative decoding, and the trick is beautiful. You cheaply *guess* a few future tokens, then *verify* all of them in one full-depth forward pass, and you keep the longest run that matches what plain greedy decoding would have produced. Because the verification is full-depth, every token you emit is exactly the token greedy would have emitted. You get the parallelism for free, in exact arithmetic. The only thing that changes between methods is where the cheap guess comes from.
158
+
159
+ Our first guess source was prompt-lookup. When the model is about to repeat something already in its context — a summary quoting its passage, code echoing a function it defined earlier — you can just copy the continuation from where that phrase appeared before, and verify it. On grounded, repetitive text this was a genuine win, up to three-and-a-half times faster. But on generic, open-ended text, where nothing repeats, it collapsed back to roughly one times. No repetition, nothing to copy.
160
+
161
+ So we added a second guess source that doesn't need repetition at all: Jacobi decoding, sometimes called lookahead. Instead of copying, it guesses a whole window of future tokens and refines them all in parallel, iterating toward the fixed point that greedy would eventually reach. On a factual prompt it hit three-point-two times, right where prompt-lookup had managed barely more than one. And here is the elegant part: the two methods are complementary. Prompt-lookup wins when the output copies the context; Jacobi wins when the output is predictable but not copied. So we fused them into a single decoder that decides, every round, which strategy is actually paying off — it measures tokens-per-forward and leans into whichever arm is winning, wasting no work on the other. That adaptive decoder beats a simpler router that just picks one method up front and commits. Neither, honestly, quite reaches the theoretical best-of-both, because any adaptation costs a little to run — but the online version gets closest.
162
+
163
+ We also chased the obvious compounding idea. Prompt-lookup spends its time in a *wide* verify forward, so could we make that forward itself cheaper, with packed matrix multiplies and a recorded CUDA graph? Packing helped a little, for free. But the graph wants a constant shape, and fixing the verify block to a constant width padded it wider than it needed to be, which roughly ate the packing gain. And the graph itself demands the special graph-safe paged cache, not the simpler flat one — because the flat cache, deep in its bookkeeping, briefly copies a length back from the GPU to the CPU, and a graph capture forbids exactly that. So that particular multiplier turned out to be real but scoped: a concrete piece of future plumbing, and we wrote down precisely why it's blocked and what unblocks it. Honest dead-ends are results too.
164
+
165
+ ---
166
+
167
+ ## Part nine — teaching Ouro to speculate on its own depth
168
+
169
+ Now the most Ouro-native version of the whole idea, and the one that pays off biggest. Ouro loops its layers four times. So ask: what if a *shallower* loop — just one or two passes — is a good enough *draft* of what the full four passes would eventually say?
170
+
171
+ That's depth-speculative decoding. You draft cheaply at low loop depth, verify at full depth, and keep the matches. On the real two-point-six-billion Ouro, drafting at a single loop step and verifying at four ran nearly twice as fast — one-point-nine times — and, crucially, the perplexity did not move: zero percent median change. The emitted tokens were not always bit-identical to the full-depth run; about five out of eight matched exactly. But the quality-first gate we had earned back in Part seven is exactly what gave us permission here. As long as the perplexity holds, a token that differs but is equally good is allowed.
172
+
173
+ So the promotion rule became perplexity-first. Block a route only if it is both faster *and* measurably worse on perplexity. On that basis, the router shipped speculation on most workloads and held back only one — code generation — where the shallow draft genuinely regressed perplexity, by a little under two percent, just enough to trip the gate. That is the mature form of the discipline in action: not "is it identical," but "is it faster without being worse," proven case by case.
174
+
175
+ ---
176
+
177
+ ## Part ten — a small looped model against the giants
178
+
179
+ Which brings us to the comparison we are running as I record this, and to the paper's central, audacious claim: a two-point-six-billion *looped* model matching or beating eight-billion dense models on reasoning. We wanted to see that on our own hardware — and, just as importantly, to price it.
180
+
181
+ So we built a benchmark suite that stands four models side by side: our optimized Ouro-2.6B, the raw Ouro-2.6B, a thirty-billion-parameter Qwen mixture-of-experts, and an eight-billion Llama. Across three tasks — grade-school math, broad knowledge recall, and science reasoning — each run both plainly and with chain-of-thought, and for Ouro across one, two, and four loops. And through all of it we measure the hardware story: peak memory, tokens per second, time to first token, and the inter-token latency.
182
+
183
+ Even the tiny validation run made the trade vivid. Ouro-2.6B lives in about five gigabytes of memory. The Llama needs fifteen. The Qwen mixture needs fifty-seven — eleven times Ouro's footprint. Our exact optimizations hand the little Ouro about a thirty-seven percent throughput gain over its raw self, and the speculative decoder stacks more on top of that. The full accuracy numbers are landing as I speak. But the shape of the story is already the paper's story, seen from the hardware side: the looped model's entire pitch is doing more *thinking* per parameter — and thinking, unlike raw size, is cheap in memory.
184
+
185
+ Getting there also meant hardening the plumbing. A four-model, three-benchmark sweep is a multi-hour job on rented machines, and a long-lived remote connection will drop over that span. So the runner now launches its work detached on the box and polls for the result over short, fresh connections, so a dropped link can never lose a completed run. Boring infrastructure, but it is the difference between an answer and a wasted afternoon.
186
+
187
+ ---
188
+
189
+ ## Recap, in six breaths
190
+
191
+ Ouro loops its layers several times per token, so both the decode cost and the cache size scale with the loop depth — and that single fact is the entire problem.
192
+
193
+ We built the measurement harness before anything else, and it told us to attack the decode step and leave prefill alone.
194
+
195
+ Then we did decode surgery in a strict order — flat cache, packed projections, fused normalization, CUDA graphs, and a paged cache — and every one had to prove it was bit-exact and reversible before it counted. That exact roadmap came together into a paged cache whose fixed-address pages let us record a single reusable CUDA graph, about three-and-a-half times faster than eager.
196
+
197
+ Then we crossed into the approximate frontier, and the first thing we found was that our own rule needed sharpening: bit-exact was a proxy for "the quality didn't change," and when we actually measured, the numerically-inexact paths were quality-lossless. So the gate became perplexity, not identical bits.
198
+
199
+ That license unlocked parallel decoding — guess several tokens, verify them all in one expensive loop, keep the greedy-matching run. Prompt-lookup for repetitive text, Jacobi for predictable text, a fused decoder that picks between them, and, most powerfully, depth-speculation that drafts Ouro at a shallow loop and verifies deep, nearly doubling throughput with no perplexity cost.
200
+
201
+ And now we are pricing the whole thesis: a five-gigabyte looped model against a fifty-seven-gigabyte mixture and a fifteen-gigabyte dense model, on real reasoning benchmarks, with the hardware numbers measured throughout. The local test suite is well past two hundred passing. The discipline never changed — a fast wrong answer is still not an answer — we just learned to measure "wrong" honestly.
202
+
203
+ That's the state of the work. Thanks for listening.
lectures/inference-serving.md ADDED
@@ -0,0 +1,239 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # The Model Is No Longer Just the Model
2
+
3
+ ### Model–serving co-design in August 2026
4
+
5
+ *Approx. 25 minutes spoken. A companion to "Same Model, Twice as Fast": that lecture takes a fixed model and squeezes it; this one is about how the model and the machine that serves it are increasingly designed together.*
6
+
7
+ August 2026 gives us a useful window into where large language model architecture is heading, because the most important developments are no longer about making the neural network smarter. Increasingly, the architecture of the model and the architecture of the serving system are being designed together.
8
+
9
+ That is the idea to keep in mind throughout.
10
+
11
+ If you want to understand modern inference, do not begin by asking how many parameters the model has. Ask what has to move through the system every time it produces a token. Ask where the weights live. Ask what has to be remembered about the conversation. Ask how many GPUs have to talk to each other. And ask whether the infrastructure serving the model actually matches the shape of the model.
12
+
13
+ Those questions explain a remarkable amount of what happened in August.
14
+
15
+
16
+ ## The Sequential Problem
17
+
18
+ Start with the fundamental problem of inference.
19
+
20
+ When we train a language model, we already know the whole sequence the model is supposed to process, so we can parallelize enormously. During generation we cannot. The model produces one token, uses it to help produce the next, and repeats.
21
+
22
+ That sequential loop gives inference a completely different performance profile from training.
23
+
24
+ When serving one user or a few users, the hardware is usually limited not by how much arithmetic it can do, but by how fast it can move weights and state to the places where the arithmetic happens. A modern GPU can execute a staggering number of operations, but if every new token requires dragging huge quantities of weights out of memory, the arithmetic units spend much of their time waiting.
25
+
26
+ So the theme of the month is reducing how much information has to move per useful generated token.
27
+
28
+
29
+ ## Qwen3.8 and Mixture of Experts
30
+
31
+ The Qwen3.8 family is the clearest example of the co-design philosophy.
32
+
33
+ The largest model has roughly two point four trillion parameters in total, which sounds absurd. But it does not use all of them for every token. Only about ninety-five billion are active at a time.
34
+
35
+ The mechanism is mixture of experts. Instead of one enormous general-purpose block, the model contains hundreds of specialist sub-networks called experts. When a token arrives, a small routing network decides which few experts should handle it. The model can hold an enormous amount of total capacity without executing all of it for every token.
36
+
37
+ That sounds like a pure win, and it creates a new problem, because the experts have to live somewhere. Spread hundreds of experts across many GPUs and tokens now have to be routed across the machine or the cluster. One token wants expert fourteen, another wants expert two hundred and seven, another wants a different combination entirely. The system has to ship tokens to the right experts, run them, and gather the results back.
38
+
39
+ So mixture of experts reduces computation and increases communication.
40
+
41
+ This is the principle that governs everything that follows: when you remove one bottleneck, another becomes visible. Reduce arithmetic and communication starts to dominate. Reduce weight traffic and the cache starts to dominate. Reduce the cache and synchronization starts to dominate. No optimization exists independently of the full system.
42
+
43
+
44
+ ## The KV Cache
45
+
46
+ To see why, we need the key-value cache.
47
+
48
+ When a Transformer generates text, it needs information about the tokens that came before. Recomputing the entire conversation for every new token would be disastrous, so the model stores intermediate information about previous tokens — the keys and values — and attends to those instead. This is what makes autoregressive generation practical.
49
+
50
+ The catch is that the cache grows with the conversation. A context of a hundred thousand tokens means retaining information for a hundred thousand tokens across many attention layers. Multiply by thousands of simultaneous users, and memory capacity becomes the primary limit on how many people you can serve.
51
+
52
+ This is why recurrent architectures are interesting again. A recurrent layer does not keep a separate entry for every token in history; it maintains a fixed-size internal state that gets updated as new information arrives.
53
+
54
+ The analogy is the difference between carrying the complete transcript of a meeting and carrying an evolving summary. The transcript is expensive to store, but you can retrieve precise details from it. The summary is small and cheap, but exact details get compressed away. Full attention is the transcript. Recurrent state is the summary.
55
+
56
+ Qwen3.8 uses both. Most layers use recurrent state, which is memory-efficient. Periodically, the architecture uses full attention, which restores high-fidelity access across the whole sequence.
57
+
58
+ That matters because it suggests the future is not a contest between Transformers and recurrent models. It is memory hierarchies inside the neural network itself — some layers offering cheap compressed memory, others offering expensive precise access. The neural-network equivalent of registers, cache, main memory and storage.
59
+
60
+
61
+ ## Typed Model State
62
+
63
+ Here is where serving gets genuinely harder.
64
+
65
+ A server built for a conventional Transformer can think about request state as essentially one thing: KV cache. A hybrid model like Qwen3.8 has several kinds. There is full-attention KV state. There is recurrent state. There is short sliding-window or convolutional state. There may be speculative-decoding state.
66
+
67
+ These cannot be treated identically. Some state is reusable whenever two prompts share a prefix. Some recurrent state is only valid at a particular checkpoint. Some can be shared safely; some must be copied before a conversation branches.
68
+
69
+ So serving frameworks are developing what you might call typed model state. SGLang's Unified Radix Cache is one example. The underlying idea — prefix sharing — is already familiar: if a thousand requests begin with the same ten-thousand-token system prompt, it would be absurd to process those ten thousand tokens a thousand times, so the server stores the state for the shared prefix and reuses it.
70
+
71
+ The new difficulty is that a hybrid architecture requires the cache to understand semantics, not just matching. The server cannot say "these tokens match, therefore everything is reusable." It has to say: this attention state is reusable, this recurrent state is reusable only to this checkpoint, this sliding-window component needs this trailing region, and this mutable component needs a private copy before we touch it.
72
+
73
+ That is a much more sophisticated abstraction, and it is one of the biggest conceptual developments of the month. The server is no longer executing a neural network. It is becoming a state-management system for a continuously evolving process.
74
+
75
+
76
+ ## Prefill and Decode as Separate Services
77
+
78
+ There are really two computational phases behind every request.
79
+
80
+ Prefill processes the prompt you supplied. Twenty thousand prompt tokens can be processed with enormous parallelism; the system is reading the input and building the state it needs before generation starts. Decode is the generation phase: produce a token, update state, produce the next one.
81
+
82
+ These are very different workloads. Prefill handles many tokens at once. Decode handles a tiny number of new tokens while repeatedly touching a very large model and an ever-growing context.
83
+
84
+ Historically, serving systems ran both on the same hardware layout. Qwen3.8 and SGLang show why that is becoming unattractive, because the best parallel configuration differs between them.
85
+
86
+ For prefill you may want pipeline parallelism — divide the model by layers, with one GPU running the early layers, another the next group, and so on. Large batches of prompt tokens flow through that pipeline efficiently.
87
+
88
+ For decode, mixture of experts makes expert parallelism more attractive, spreading the experts across GPUs so no single GPU has to hold or repeatedly load the entire expert bank.
89
+
90
+ So the best physical representation of the model can genuinely differ between the two phases. Which leads to a striking idea: treat them as separate services. The prefill service reads the prompt and constructs state. That state transfers to a decode service with a completely different layout tuned for token generation.
91
+
92
+ Instead of one model server executing one model, we start thinking about a pipeline of specialized services that exchange model state — one for ingesting context, one for generating tokens, perhaps others for speculative drafting, retrieval, or long-term memory.
93
+
94
+
95
+ ## Speculative Decoding
96
+
97
+ Return to the fundamental problem: generation is sequential, and normally the large model runs once per token.
98
+
99
+ Speculative decoding asks whether we can avoid that. A smaller, cheaper model — the drafter — quickly proposes several future tokens, say six. The large model evaluates all six together. If it agrees with the first four, those four are accepted; at the first disagreement, the rest is discarded and generation resumes from the corrected point.
100
+
101
+ Four output tokens from roughly one large-model verification, instead of four separate large-model steps. That can be a dramatic speedup.
102
+
103
+ But it depends entirely on acceptance rate. If the drafter proposes eight tokens and only one survives, most of that work was wasted.
104
+
105
+ August research adds an important observation: the optimal number of speculative tokens is not fixed. Under light load there is spare compute, verifying extra possibilities is cheap, and speculating aggressively pays. Under heavy load those extra positions compete for scarce resources, and the server wants shorter drafts.
106
+
107
+ Adaptive systems like DSpark act on this. Rather than fixing a speculative length, the scheduler weighs the probability that each proposed token survives verification against the current cost of verifying it — a token near the start of the draft is likely to be accepted, one far out much less so — and prioritizes accordingly.
108
+
109
+ That is a real shift. Speculative decoding stops being purely a model algorithm and becomes a scheduling algorithm. The correct policy depends on current server load, which means generation behavior is now dynamically controlled by the serving system.
110
+
111
+ A related direction is training models to speculate well together. Normally you train a large model and separately find a drafter, which may disagree with it often. Matryoshka model suites instead nest smaller models inside the larger one, so a small, medium and large model are literally subsets of the same network, trained together. The drafter and the verifier are aligned because they were designed as a family rather than introduced after the fact.
112
+
113
+ Once again, serving requirements are reaching back into training.
114
+
115
+
116
+ ## Long-Context Serving
117
+
118
+ As contexts stretch toward a million tokens, the cache becomes enormous.
119
+
120
+ Decode Context Parallelism attacks this directly. Ordinary tensor parallelism divides computation by attention heads or model dimensions — but newer attention architectures have very few distinct key-value heads, which can leave duplicated KV state on every GPU. Decode Context Parallelism instead divides the context itself. Given a two-hundred-thousand-token conversation and four GPUs, each GPU owns one section of the history rather than a redundant copy of all of it, and attention combines information across devices when needed.
121
+
122
+ That costs communication, and it dramatically reduces the KV memory each GPU must hold.
123
+
124
+ The result is worth noticing carefully, because the individual model operation may not get much faster — but the server fits far more concurrent requests, so total system throughput rises enormously.
125
+
126
+ That distinction is essential, and it is where most benchmark confusion comes from.
127
+
128
+
129
+ ## Cerebras and Where Weights Live
130
+
131
+ Cerebras illustrates the hardware side of the same memory-movement problem.
132
+
133
+ Conventional accelerators use relatively small chips attached to large external high-bandwidth memory, and the compute units repeatedly read weights and state from it. Cerebras instead occupies an enormous portion of a silicon wafer and carries a very large quantity of fast on-chip SRAM, so far more of the model's working data stays physically close to the compute.
134
+
135
+ Why that matters: if generating a token requires pulling enormous quantities of weights through a memory interface, then no matter how fast the arithmetic is, the token cannot be produced until the weights arrive. Keep the weights near the processors and that bottleneck shrinks. This is why wafer-scale inference can hit extremely high interactive token rates.
136
+
137
+ The lesson is not that everyone will build wafer-scale processors. It is that the physical placement of weights has become part of the serving algorithm. Where do parameters live? How often do they move? Across what interconnect? At what precision? Are inactive experts sitting in host memory? Can weights be pulled from another tier?
138
+
139
+ Mixture of experts makes this vivid. If a model has hundreds of experts but needs only a few per token, keeping every expert permanently in expensive GPU memory is wasteful. ExactMoE explores keeping some expert weights outside the GPU and bringing them in on demand — frequently used experts stay resident, rarer ones live in host memory and transfer in when required. The benefit is much lower GPU memory use. The danger is transfer latency: if the router asks for an absent expert, a large amount of weight data has to move before computation continues.
140
+
141
+ So minimizing GPU memory is not the same as maximizing serving quality. You have to weigh footprint against throughput and latency together.
142
+
143
+ DeaMoE asks a different question: what if many experts share common structure? Separate the shared components from the expert-specific ones and the system stops reloading the same information for every expert. Again the theme holds — the unit that matters is not operations, but useful computation per byte transferred.
144
+
145
+
146
+ ## Recurrent Depth
147
+
148
+ Traditional Transformers give every layer its own parameters. Recurrent-depth architectures reuse the same block many times — instead of twenty-four unique floors, a smaller number of modules that the representation passes through repeatedly. A system like RecurrentGPT can use far fewer unique parameters while still doing substantial computation.
149
+
150
+ Why does that help inference? Because unique parameters have to be stored and moved. Reusing the same weights several times shrinks the parameter footprint even when total computation is similar. On hardware where bandwidth is expensive relative to arithmetic, that is a very attractive trade: rather than continuously loading new weights, do more work with weights you already hold.
151
+
152
+ But it creates its own serving problem. What happens to the cache? If every recurrent pass stores its own keys and values, the cache can grow substantially even though unique weights shrank — and you can lose through recurrent KV storage most of what you saved on parameters.
153
+
154
+ So recurrent depth needs more than weight sharing. It needs a serving-aware state design: share some recurrent KV, compress it, replace some attention-based steps with fixed-size recurrent state, or let only selected loops retain full cache entries. Recurrent depth cannot be judged by parameter count alone. Its real value depends on what happens to persistent inference state.
155
+
156
+
157
+ ## The Full-bandwidth Transformer
158
+
159
+ One of the most interesting architecture papers of the month starts from an odd observation.
160
+
161
+ In a normal autoregressive Transformer, an enormous amount of internal computation happens before the model picks a token — and then all of that richness collapses into one discrete token, which is what the next step receives.
162
+
163
+ A Full-bandwidth Transformer also feeds part of the previous step's hidden representation directly into the next step. The model does not communicate with its future self only through words; it can pass forward a richer internal representation as well.
164
+
165
+ Think about solving a hard problem in your head. If you had to fully verbalize your entire mental state after every small reasoning step and then erase everything except those words, that would be enormously wasteful. Human reasoning does not appear to work that way — we hold continuous internal representations carrying far more than whatever sentence we say aloud.
166
+
167
+ The emitted token still matters. But a latent state continues forward alongside it. The reported experiments suggest better training efficiency at very little generation-time cost.
168
+
169
+ And it introduces yet another serving object. The server may now have to carry a persistent latent feedback state between tokens, on top of everything else — exact recent memory, compressed recurrent memory, latent reasoning state, retrieved memory, speculative state, tool state, session state. Managing a portfolio of state types is becoming the job.
170
+
171
+
172
+ ## Sessions, Not Requests
173
+
174
+ That brings us to GPT-Live and continuous inference.
175
+
176
+ Traditional APIs encourage us to imagine interaction as independent requests: a prompt arrives, the server answers, the request ends. An always-on voice agent is not shaped like that at all. It may be listening while speaking. The user can interrupt. Audio arrives continuously. The model may call another model or tool, hold state for hours, and migrate to different hardware without the conversation restarting.
177
+
178
+ So the abstraction changes. Instead of requests, sessions. Instead of request latency, continuous real-time deadlines. Instead of rebuilding state from a transcript, preserving active model state. Instead of asking how many requests per second a server handles, asking how many simultaneous live conversations the infrastructure can hold.
179
+
180
+ Agent serving starts to look less like a web server answering calls and more like an operating system managing long-running processes. A live agent has state. It occupies resources. It may migrate, need more compute temporarily, delegate work, compact its memory, suspend, resume, or fork. Those are operating-system concepts.
181
+
182
+ Which leads to another intriguing idea: cross-model KV transfer. Suppose a conversation starts on a small, cheap model, most turns are easy, and then a genuinely hard question arrives. Normally the larger model would have to reread the entire conversation to build its own cache — expensive at a hundred thousand tokens. Cross-model KV transfer tries instead to translate the small model's internal state into the large model's format.
183
+
184
+ If that becomes reliable, routing changes character. You could start sessions cheaply, escalate only when necessary, keep most of the computational history, and drop back down afterwards. That is stateful model routing rather than picking a model per request.
185
+
186
+ Now combine everything. A conversation begins on a small model. Exact KV covers recent history, compressed recurrent state covers older history, and a shared cache holds the system prompt across thousands of sessions. When something hard arrives, state moves to a larger model, which decodes speculatively with a nested drafter whose depth varies with cluster load. The model uses sparse experts, placed near the compute that needs them. Prefill runs on one group of hardware, decode on another, and long contexts are split across GPUs by position — and the session can migrate between workers without losing continuity.
187
+
188
+ At that point, what exactly is "the model"? The intelligence is no longer identifiable with one checkpoint. The effective system is the checkpoint plus the drafter, the cache policy, the quantization format, the expert placement, the state-transfer mechanism, the scheduler, and the topology of the cluster.
189
+
190
+
191
+ ## Quantization
192
+
193
+ Quantization reduces the number of bits used for weights or activations, and August systems increasingly use four-bit formats such as NVFP4.
194
+
195
+ The obvious benefit is that the model occupies less memory. For inference, the more important benefit is that fewer bits means fewer bytes have to move. If a weight takes four bits instead of sixteen, you can push far more weights through the same memory interface in the same time — which is exactly what a bandwidth-limited decode needs.
196
+
197
+ Done badly it costs accuracy, so modern quantization is not simply shrinking numbers; the calibration process has to preserve the most important information while cutting representation cost. The serving checkpoint becomes a deliberately engineered artifact rather than a generic compressed copy.
198
+
199
+ It gets powerful in combination with speculation. Meta's Muse Glimmer is a dense multimodal model built to run on a high-end consumer GPU: quantize the target aggressively, pair it with a separate speculative model, and the reported setup generates above two hundred tokens per second for a single user on an RTX 5090. Very high interactive rates are not a datacenter privilege any more.
200
+
201
+ But do not attribute that number to the base architecture. It is a system result. Remove the drafter, change the precision, change the runtime or the workload, and the number moves.
202
+
203
+
204
+ ## Reading Benchmark Claims
205
+
206
+ Which brings us to interpreting performance claims. When somebody advertises an enormous tokens-per-second figure, ask six questions.
207
+
208
+ Is that output tokens or total processed tokens? Is it one user or aggregated across many? What is the concurrency? What are the input and output lengths? What hardware and precision? And what happened to time to first token and per-user latency?
209
+
210
+ Those answers can invert the meaning of a benchmark. In August, OpenAI and Cerebras demonstrated GPT-5.6 Sol Ultrafast at roughly seven hundred and fifty generated tokens per second — an interactive, single-stream claim. Meanwhile vLLM demonstrated Qwen3.5 at more than twenty-five thousand total tokens per second per GPU under very high concurrency — a fleet-throughput claim. Both are impressive. They answer different questions, and each individual user on the second system experiences only moderate speed.
211
+
212
+ So a single number is never enough. You need the Pareto frontier: the tradeoff surface across per-user speed, total throughput, memory, quality, power and cost, where improving one thing costs you another. The best serving reports show several operating points — tuned for fast individual generation at low concurrency, trading responsiveness for aggregate throughput at high concurrency.
213
+
214
+ If you are building an interactive coding agent, the first number is what you care about. If you run a batch platform, the second is.
215
+
216
+
217
+ ## What It All Adds Up To
218
+
219
+ Three architectural movements are happening at once, and each attacks a different kind of waste.
220
+
221
+ Sparse computation says we should not activate every parameter for every token. Compressed or hierarchical state says we should not store every detail of every previous token forever. Amortized generation says we should not need one full expensive model step per accepted output token.
222
+
223
+ All three push complexity into the serving layer. Sparse experts need routing and placement. Recurrent state needs lifecycle management. Speculation needs drafting, verification, acceptance logic and adaptive scheduling. That is why serving has moved to the center of architecture research. The interesting question is no longer which network achieves the best loss, but which combination of architecture and runtime achieves the most intelligence per dollar, per watt, per byte moved, and per millisecond the user actually perceives.
224
+
225
+ The durable lessons are these. Full attention does not disappear, but we use less of it, invoking it periodically when precise global access is worth paying for. Sparse mixture of experts is now inseparable from systems engineering — the hard part is placing experts and moving their weights, not choosing them. Prefill and decode are separate workloads. Speculation becomes adaptive, tuned to confidence and load rather than fixed. And inference state is a first-class computational resource that has to be managed explicitly.
226
+
227
+ One sentence for the whole month: the frontier of inference is moving from optimizing calculations to optimizing movement and state.
228
+
229
+ The winning systems ask which parameters truly need to activate, which bytes truly need to move, which history truly needs to stay exact, which computation can be reused, and how many accepted tokens can be extracted from each expensive pass.
230
+
231
+ That is why Qwen3.8 is instructive — not because it has trillions of parameters, but because sparse experts, recurrent state, occasional full attention, low precision, speculative generation, typed caches and split prefill and decode are coordinated into one working system. It is why the Cerebras result matters: hardware redesigned around the memory behavior of autoregressive inference. And it is why Full-bandwidth Transformers and recurrent-depth models deserve attention despite being less mature, because they question two assumptions we rarely examine — that information between steps should travel as discrete tokens, and that more depth requires more unique weights.
232
+
233
+ So when you evaluate a future architecture, do not just ask whether it has a cleverer attention mechanism. Ask what happens when ten thousand concurrent users sit behind it. What state does each one create, how fast does it grow, and where does it live? Can prefixes be shared? Can sessions migrate? Can the weights stay close to the compute, and the inactive ones somewhere cheaper? Can one expensive invocation yield several accepted tokens?
234
+
235
+ That is the difference between an architecture that looks impressive in a paper and one that becomes a usable platform.
236
+
237
+ Because the model no longer ends at the edge of the neural network. The cache is part of the model. The scheduler is part of the model. The drafter, the precision format, the memory hierarchy, and increasingly the topology of the cluster are all part of the effective architecture.
238
+
239
+ That is the shift worth watching.
lectures/model-comparison.md ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Four Models, One GPU
2
+
3
+ ### A technical lecture comparing recurrent-depth, dense, and mixture-of-experts language models on real hardware
4
+
5
+ *Approx. 20–25 minutes spoken. Written to be listened to — the numbers and the reasoning are spoken aloud rather than rendered in tables, so it reads cleanly through a text-to-speech engine. A companion to "Making Ouro Fast": that lecture was about squeezing a single recurrent-depth model; this one puts four very different models on the same GPU and asks a simpler question — which architecture actually earns its keep?*
6
+
7
+ ---
8
+
9
+ ## Cold open
10
+
11
+ Welcome back. Today I want to do something concrete. I want to take four language models that are built on genuinely different ideas, put them on the exact same graphics card, feed them the exact same questions, and measure what happens — not just whether they get the answers right, but what they cost you in memory, in latency, and in tokens per second. Because the marketing conversation about models is almost always about accuracy alone, and accuracy alone is a deeply misleading way to choose a model. The honest question is accuracy per gigabyte, accuracy per millisecond, accuracy for the hardware you can actually afford to run.
12
+
13
+ The four models are these. First, Ouro, a two-point-six-billion parameter recurrent-depth model from ByteDance — a model that loops its layers many times per token. Second, Huginn, a three-and-a-half-billion parameter recurrent-depth model from a university group — same core idea, different implementation. Third, Llama three-point-one, the eight-billion parameter instruct model from Meta — a conventional dense transformer, the workhorse baseline. And fourth, Qwen three, a thirty-billion parameter mixture-of-experts model that only activates about three billion parameters per token — the clever, sparse heavyweight.
14
+
15
+ So we have two recurrent-depth models, one dense model, and one mixture-of-experts model. Everything ran on a single RTX PRO six-thousand card, in sixteen-bit precision, one request at a time, on fifty questions each from three benchmarks: grade-school math, broad knowledge recall, and science reasoning. Let me take you through what we found, starting with the one architectural idea you have to understand before any of the numbers make sense.
16
+
17
+ ---
18
+
19
+ ## Part one — the looping trick, and why it changes the economics
20
+
21
+ Here is the strange thing that both Ouro and Huginn do, and that Llama and Qwen do not. A normal transformer runs each token through its stack of layers exactly once, top to bottom, and then predicts. A recurrent-depth model takes a small stack of layers and runs it in a loop, over and over, refining a hidden state each time, before it commits to an answer.
22
+
23
+ Ouro does this by taking its forty-eight physical layers and replaying the whole stack four times for every token. Four loops times forty-eight layers is one hundred and ninety-two effective layer-passes — that is the actual sequential compute each token goes through. Huginn does it a little differently: it has a small two-layer prelude that reads the input, then a four-layer core that it loops thirty-two times, then a two-layer coda that produces the output. Two, plus thirty-two times four, plus two, comes to one hundred and thirty-two effective layer-passes.
24
+
25
+ So both of these models are deep — well over a hundred layer-passes of compute per token. And here is the beautiful part: the weights are shared across every loop. Ouro is not storing one hundred and ninety-two layers of parameters; it is storing forty-eight and reusing them four times. Huginn is not storing a hundred and thirty-two; it stores eight and reuses the core. That is the entire trick, and it is why the memory story, which I'll come to, is so lopsided.
26
+
27
+ Now, why go to all this trouble? Because depth is where reasoning comes from. And we can watch it happen. When we sweep Ouro's loop count from one to two to four, its accuracy climbs monotonically. On the knowledge benchmark it goes from fifty percent at one loop, to sixty-eight percent at two loops, to seventy-four percent at four. On science reasoning, sixty-eight, then eighty-two, then eighty-six. On grade-school math, twenty-six percent, then sixty-two, then seventy. More loops, more thinking, more correct answers, every single time. Huginn shows the same shape on science reasoning — its accuracy rises from fourteen percent at eight loops, to twenty-six at sixteen, to thirty-four at thirty-two. The loop is not decoration. The loop is the reasoning, and you can turn it up like a dial.
28
+
29
+ Hold onto that: depth costs you speed, and buys you accuracy. Everything downstream is a negotiation over that trade.
30
+
31
+ ---
32
+
33
+ ## Part two — the accuracy scoreboard, told honestly
34
+
35
+ Let me give you the headline accuracy numbers, and then immediately complicate them, because the complication is the whole point.
36
+
37
+ On grade-school math, Qwen, the thirty-billion mixture-of-experts, wins at ninety percent. Llama, the eight-billion dense model, gets eighty. Ouro, at two-point-six billion, gets seventy-two. Huginn is very weak here, near two percent — I'll explain that in a moment. So on raw math, the bigger conventional models win. No spin: Ouro trails them on arithmetic reasoning.
38
+
39
+ But now look at knowledge recall. Qwen gets seventy-six percent. Ouro gets seventy-four. Llama, the eight-billion model, gets only sixty-six. Read that again — the two-point-six-billion recurrent model beats the eight-billion dense model on broad knowledge, and lands within two points of the thirty-billion mixture-of-experts. And on science reasoning it is even starker: Ouro scores eighty-six percent, beating Llama's seventy-four handily, and trailing Qwen's ninety-two by only six points, at roughly a twelfth of the active-parameter budget of the comparison.
40
+
41
+ So the fair summary of Ouro is not "it wins." It is "it punches wildly above its weight." It is competitive-to-winning against a model three times its size, and within a few points of one more than ten times its size, on everything except pure math. That is the accuracy story: strong-for-its-size, not dominant.
42
+
43
+ Huginn is the honest disappointment on task accuracy — around thirty percent on knowledge, thirty-four on science, and effectively zero on grade-school math in our zero-shot setup. And that is real, not a bug; it matches the paper's own reporting. Huginn is a research model whose gains on knowledge tasks are modest and whose math ability really needs few-shot prompting to show up. So why keep it in the comparison at all? Because Huginn is not here to win on accuracy. Huginn is here for the second half of this lecture — it is the vehicle for showing that these looping models are not just efficient, they are improvable. Keep it in your pocket.
44
+
45
+ ---
46
+
47
+ ## Part three — the memory headline, which is the whole argument
48
+
49
+ Now the hardware, and this is where the recurrent-depth models stop being an underdog story and start being an obvious win.
50
+
51
+ Let me give you four numbers, all peak memory during generation. Ouro, at its full four-loop depth, uses about six gigabytes. Huginn uses seven to ten, depending on how many loops. Llama, the eight-billion dense model, uses just over fifteen gigabytes. And Qwen, the thirty-billion mixture-of-experts, uses fifty-seven gigabytes.
52
+
53
+ Sit with that. Ouro is roughly two-and-a-half times lighter than the eight-billion Llama, and about nine-and-a-half times lighter than the thirty-billion Qwen — while matching or beating both on knowledge and reasoning. That is the shared-weight trick paying off in the most direct way imaginable. A hundred and ninety-two layer-passes of compute, from six gigabytes of footprint, because it is forty-eight layers wearing four different hats. You could run Ouro comfortably on a consumer card that would not even load Qwen.
54
+
55
+ The prefill latency — the time to digest the prompt before the first token appears — tells a related story. Ouro, Huginn, and Llama all prefill in a comfortable twenty to seventy milliseconds. Qwen pays five hundred and twelve milliseconds. Half a second, just to read the prompt, before it says a single word. That is the mixture-of-experts tax: the model is enormous and its routing machinery is expensive to spin up, and it shows up as latency even on the benchmarks where Qwen wins on accuracy.
56
+
57
+ Now, the recurrent-depth models do pay for their depth in raw decode speed, and I won't hide it. Llama, being a shallow single-pass model, is the fastest decoder at about sixty-eight tokens per second. Ouro at four loops does about twenty-one. Huginn at thirty-two loops does about ten. The loop tax is real. But notice — Qwen, despite ten times the parameters, only decodes at about seventeen tokens per second, barely faster than Ouro, because its half-second prefill and its size drag it down. So the picture is not "conventional models are fast, recurrent models are slow." The picture is: Llama is fast and heavy, Qwen is slow and enormous, and Ouro is a little slower than Llama at decode but a fraction of the memory of either. For most real deployments, where memory is the constraint that actually stops you, that trade is very attractive.
58
+
59
+ So the memory argument, in a breath: recurrent depth gives you deep reasoning from a tiny, shared parameter footprint. That is the efficiency-per-parameter case, and it is strong.
60
+
61
+ ---
62
+
63
+ ## Part four — the improvable story, part one: accelerating without losing quality
64
+
65
+ Here is the pivot. If a recurrent-depth model's only weakness is decode speed, and decode speed comes from the loop, then the interesting question becomes: can you make the loop cheaper without giving up the accuracy the loop buys you? And the answer, it turns out, is yes — several different ways. This is the "improvable" story, and it is the reason to be excited about this architecture rather than just impressed by it.
66
+
67
+ Let me walk you through the accelerators, from the boring-but-free to the genuinely surprising.
68
+
69
+ The first is exact kernel optimization. This is unglamorous plumbing: you take all the tiny operations inside each loop — the separate query, key, and value projections, the separate parts of the feed-forward block, the normalization steps — and you fuse them into fewer, larger GPU operations. Same arithmetic, exactly the same output, just packed into fewer kernel launches so the graphics card spends less time idling between tiny jobs. On Ouro this gives about a one-point-three-six times speedup, and it is bit-exact — the output is provably identical. A free lunch, if an undramatic one.
70
+
71
+ The second is prompt-lookup speculation. This one is clever and almost embarrassingly cheap. As the model generates, a lot of what it is about to say has already appeared — a number from the question, a name, a repeated phrase. So instead of generating those tokens one expensive loop at a time, you draft them by copying chunks of text the model has already seen, and then you verify the whole draft in a single forward pass. When the draft is right, you got several tokens for the price of one. When it is wrong, you fall back. It is lossless — you only ever accept tokens the full model agrees with — and on the math benchmark it is the fastest Ouro path, about one-point-six-four times faster.
72
+
73
+ The third is depth-speculative decoding, and this is the one that generalizes to the loop directly. The idea: drafting a token at full depth is expensive, so draft it cheaply at shallow depth — one loop instead of four — and then verify the drafted block at full depth in one pass, committing whatever prefix the full-depth model agrees with. You get full-depth quality, because the full-depth model is the one that signs off, but you pay mostly shallow-depth cost. On Ouro this gives about one-point-four-one times; on Huginn, drafting at eight loops and verifying at thirty-two, also about one-point-four-one. Quality-preserved, meaningfully faster.
74
+
75
+ So already, before we do anything exotic, recurrent depth is accelerable in the range of one-point-three-six to one-point-six-four times, with the answer either provably identical or verified by the full model. That alone answers the "is it improvable" question. But the last accelerator is a different order of thing entirely, and it is worth slowing down for.
76
+
77
+ ---
78
+
79
+ ## Part five — the improvable story, part two: sampling the loop in parallel
80
+
81
+ Everything so far has still been fundamentally sequential: one token, then the next, then the next. The last idea breaks that assumption, and it comes from a lovely observation in a recent paper — that a recurrent-depth model, refining a hidden state through many steps, is mathematically close cousin to a diffusion model, which refines a noisy signal through many steps. And diffusion models can be sampled in parallel.
82
+
83
+ So here is the sampler, called the efficient parallel sampler, or the diffusion-forcing sampler. Instead of finishing all the loops for one token before starting the next, you maintain a whole moving front of tokens at once — a wavefront. Every forward pass, you advance the loops on all of the active tokens together, and you let each one keep refining. As soon as a token at the left edge of the wavefront settles — as soon as its hidden state stops changing much between steps — you freeze it, commit it to the output, and add a fresh token at the right edge. The compute is still recurrent, still deep, but instead of a long chain of tiny one-token steps, the graphics card sees a wide batch of positions and can work on them all at once. Small-batch decoding, which normally wastes a GPU, suddenly becomes a fat, efficient matrix problem.
84
+
85
+ And when we ran the paper authors' own implementation of this sampler on Huginn, here is what happened. The ordinary sequential decoder, at thirty-two loops, ran at about ten tokens per second. The parallel diffusion sampler ran at about forty-four tokens per second — a four-point-two-four times speedup — and it produced coherent output, matching the sequential decoder token-for-token on several of the test problems and staying close on the rest, exactly as an approximate-but-verified parallel sampler should. Four times faster, same quality. And that number, four-point-two-four, lands right on top of the four-point-three-six the paper reports for the same benchmark. It reproduces.
86
+
87
+ Now let me be scrupulously honest about the road here, because it is a good lesson. Our own first attempt to build this sampler from scratch failed — the parallel tokens collapsed into repetitive garbage. And chasing that down taught us exactly why the method is subtle: it needs a very specific cache strategy for handling tokens that are at different stages of refinement, and it needs each new token to start from a fresh random state rather than a copy of its neighbor, or the whole wavefront collapses into a symmetric heap. Once we ran the authors' actual code, with their actual cache, it worked immediately and reproduced their result. The lesson is not "we failed." The lesson is that the four-times speedup is real and reproducible, and that the details of a research method are load-bearing — you cannot eyeball them.
88
+
89
+ ---
90
+
91
+ ## Part six — the verdict
92
+
93
+ So let me put the whole comparison in one frame.
94
+
95
+ On accuracy, the bigger conventional models win on pure math, but the two-point-six-billion recurrent model beats the eight-billion dense model on knowledge and science, and comes within a few points of a thirty-billion mixture-of-experts — at a fraction of the size. On memory, it is not close: the recurrent models run in six to ten gigabytes where the dense model needs fifteen and the mixture-of-experts needs fifty-seven. And on the question of whether the architecture's one real weakness, decode speed, can be fixed — the answer is a clear yes, from one-point-three-six times with a free bit-exact kernel, to one-point-four-one with depth-speculation at preserved quality, all the way to four-point-two-four times with a parallel diffusion sampler at coherent quality.
96
+
97
+ The honest positioning of recurrent-depth models is therefore not "they beat everything." It is two things at once. First, efficiency per parameter: they reach the reasoning depth of a much larger model from a tiny shared footprint. And second, accelerability: their single weakness, the sequential loop, is exactly the thing that a growing family of samplers knows how to speed up — because a looping model, it turns out, is a diffusion model wearing a transformer's clothes.
98
+
99
+ If you take one thing from this, take that pairing. Not raw superiority — efficiency, plus a real and reproducible path to being made several times faster without giving up the answers. That is a very good place for an architecture to be. Thanks for listening, and I'll see you in the next one.
lectures/ouro-implementation.md ADDED
@@ -0,0 +1,1043 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Ouro in Practice.
2
+
3
+ A Lecture on Implementing and Optimizing a Looped Language Model.
4
+
5
+ What this is.
6
+
7
+ Lecture notes covering the implementation program laid out in this folder: the nine-phase execution plan in Ouro execution phase plans for measuring, accelerating, adapting, and compressing the Ouro looped language model, with field context from the companion R D T Guide.
8
+
9
+ Prerequisites.
10
+
11
+ Working PyTorch and Hugging Face Transformers knowledge; familiarity with K V caching, LoRA, and post-training quantization at the level of having used them once.
12
+
13
+ How to read.
14
+
15
+ Sections 1 - 3 build the conceptual foundation.
16
+
17
+ Sections 4 - 12 walk the nine phases in execution order - each one answers why this phase exists, what the core mechanism is, and how you know it worked.
18
+
19
+ Section 13 extracts the engineering lessons that repeat across phases.
20
+
21
+ Section 14 is a self-test.
22
+
23
+ 1.
24
+
25
+ Motivation: why loop a transformer at all?.
26
+
27
+ A standard transformer runs each of its layers exactly once per forward pass.
28
+
29
+ A looped (recurrent-depth) transformer takes a smaller stack of layers and runs it k times, feeding the output hidden state back in as input.
30
+
31
+ The weights are shared across iterations; the computation is not.
32
+
33
+ This buys one unconditional win and creates two conditional costs.
34
+
35
+ Keep this ledger in your head for the entire lecture - every phase in the implementation plan is an entry in it.
36
+
37
+ Here is the same table in spoken form.
38
+
39
+ First: Ledger item: Weight memory.
40
+
41
+ Effect of looping k times: L unique layers do the work of a k times L layer stack so you store one over k of the weights.
42
+
43
+ Status: Always a win.
44
+
45
+ This is the reason looped models fit on hardware their dense-quality peers don't.
46
+
47
+ Second: Ledger item: K V cache.
48
+
49
+ Effect of looping k times: Naively, each loop iteration writes its own keys and values, creating up to k times decode cache.
50
+
51
+ Status: Conditional cost.
52
+
53
+ Phases 3 and 8 exist to erase it.
54
+
55
+ Third: Ledger item: Latency.
56
+
57
+ Effect of looping k times: k loops = k sequential passes per generated token.
58
+
59
+ Status: Always paid, unless you exploit early exit, drafting, or routing.
60
+
61
+ Phases 1, 2, 4, and 7 exist to reduce it.
62
+
63
+ Why would running the same weights repeatedly add quality at all? The intuition, supported by the mechanistic literature the guide surveys, is that the loop performs iterative refinement: each pass moves the hidden state closer to a fixed point that encodes the answer.
64
+
65
+ Easy inputs converge in one or two passes; hard inputs need all of them.
66
+
67
+ That variability is not a nuisance - it is the entire optimization surface this implementation plan exploits.
68
+
69
+ Key idea number one.
70
+
71
+ A looped model turns "how much compute does this input get?" into a runtime knob.
72
+
73
+ Everything in this folder is about measuring that knob, then monetizing it.
74
+
75
+ 2.
76
+
77
+ Meet the model: Ouro's control surface.
78
+
79
+ Ouro (ByteDance, Apache-2.0) is the flagship looped checkpoint family and the target of the entire plan: Checkpoints: ByteDance Ouro-1.4 billion and ByteDance Ouro-2.6 billion, plus -Thinking variants (reasoning S F T on the base models).
80
+
81
+ Training: 7.7 trillion tokens, trained at 4 recurrent steps (you will see this written as R4 or T equals 4).
82
+
83
+ Headline claim: the 2.6 billion looped model rivals about 8 billion dense models on reasoning - large-model quality at small-model weight memory, which is exactly the ledger from Section 1 paying out.
84
+
85
+ The plan targets Ouro-1.4 billion for development and 2.6 billion for confirmation runs, with the Thinking variants deferred until the harness works.
86
+
87
+ This ordering is deliberate: iterate where each experiment is cheap, confirm where it matters.
88
+
89
+ 2.1 The two knobs.
90
+
91
+ Ouro exposes its loop behavior through two config fields: The two control fields are config dot total U T steps, which sets the recurrent depth, and config dot early exit threshold, where one point zero means always run the full configured depth.
92
+
93
+ ut stands for universal transformer steps.
94
+
95
+ These two fields are the control surface every phase manipulates.
96
+
97
+ 2.2 The three environment landmines.
98
+
99
+ The plan treats these as first-class engineering facts, and so should you: 1.
100
+
101
+ Pin transformers equals 4.54.1.
102
+
103
+ The model ships custom code (trust remote code equals true), and the model card warns that transformers greater than or equal to 4.56.0 breaks it.
104
+
105
+ A community cache fix was merged upstream, but the pin remains the documented safe path.
106
+
107
+ 2.
108
+
109
+ Set loop config before from pretrained. The loop count is baked into the model at load time.
110
+
111
+ Editing config.total U T steps after loading silently does nothing - one of the most common failure modes in Phase 0's table.
112
+
113
+ 3.
114
+
115
+ v L L M or S G Lang always run full depth.
116
+
117
+ Official serving integrations exist, but they do not support Ouro's adaptive early exit - they execute all total U T steps every time.
118
+
119
+ Any experiment that depends on average-case early exit must use the Hugging Face path.
120
+
121
+ This single engine limitation motivates the entire router design in Phase 7.
122
+
123
+ 2.3 The extrapolation ceiling.
124
+
125
+ You might hope to "think harder" at inference by setting T equals 8 on a model trained at T equals 4.
126
+
127
+ Empirically this fails: base Ouro peaks at its trained depth (T equals 4) and degrades at T equals 5 - 8, and the Thinking variants are near-useless at T equals 1, peaking around T equals 3 - 5.
128
+
129
+ Independent scaling analyses (Parcae) confirm test-time looping follows a saturating curve whose ceiling sits near the mean training recurrence.
130
+
131
+ Key idea number two.
132
+
133
+ You cannot loop your way past what training established.
134
+
135
+ The realistic optimization direction is downward - finding inputs that need fewer than 4 loops - not upward.
136
+
137
+ 3.
138
+
139
+ The implementation philosophy.
140
+
141
+ The phase plans compress their strategy into one sentence, which is worth memorizing because it explains the ordering of everything that follows: First measure loop behavior, then reduce memory or latency, then train small loop-aware adapters, then compress with loop-aware calibration.
142
+
143
+ Measurement (Phases 0 - 2) comes before optimization (3 - 4), which comes before training (5), which comes before compression (6), which comes before productization (7).
144
+
145
+ The stretch goal (8) branches off after Phase 3.
146
+
147
+ The dependency order is phase zero for environment, phase one for loop sweeps, phase two for trajectory diagnostics, then phase three for cache policy and phase four for self-speculative decoding.
148
+
149
+ From there, phase five handles per-loop LoRA, phase six handles loop-aware quantization, phase seven handles routing and serving, and phase eight is the MELT-lite stretch goal.
150
+
151
+ The README is blunt about why the ordering is non-negotiable: without loop-depth and trajectory baselines, you will not know whether a training or compression change improved reasoning or merely changed surface likelihood.
152
+
153
+ 3.1 The global acceptance rule.
154
+
155
+ Every phase must produce five artifacts before you move on: 1.
156
+
157
+ A reproducible script or config.
158
+
159
+ 2.
160
+
161
+ A machine-readable output file (JSONL or Parquet).
162
+
163
+ 3.
164
+
165
+ A human-readable summary Markdown.
166
+
167
+ 4.
168
+
169
+ A test that prevents the same bug from silently recurring.
170
+
171
+ 5.
172
+
173
+ A regression comparison against the Phase zero or Phase one baseline.
174
+
175
+ Item 4 is the one teams skip and regret.
176
+
177
+ Notice as we go how each phase converts its scariest failure mode into a permanent unit test.
178
+
179
+ 3.2 The repository as a map of the plan.
180
+
181
+ The proposed repo layout mirrors the phase structure - each ouro extension module is one phase's mechanism: The proposed repository mirrors the plan.
182
+
183
+ The model loader belongs to phase zero, instrumentation to phase two, cache policies to phase three, speculative decoding to phase four, per-loop LoRA to phase five, quantization to phase six, and routing to phase seven.
184
+
185
+ The evals and tests folders are the permanent measurement harness.
186
+
187
+ 3.3 Measurement discipline.
188
+
189
+ Two global standards apply to every experiment: Log everything that could explain a difference later: model revision, transformers or torch or CUDA versions, G P U name, dtype, total U T steps, early exit threshold, seed, git commit, plus per-run latency (TTFT, inter-token mean or p fifty and p ninety five), tokens per second, and peak V RAM.
190
+
191
+ Evaluate on a small, fixed suite built for loop sensitivity, not leaderboard breadth: short factual QA (should not need loops), G S M eight K-style arithmetic and MATH five hundred-style problems (loop-depth sensitive), synthetic multi-hop facts, small code tasks (regression canary), and long-context retrieval snippets (cache canary).
192
+
193
+ Iterate on the small suite; lock a larger one only once the harness is stable, and never tune on the locked suite.
194
+
195
+ 3.4 Hardware: running the plan on Shadeform.
196
+
197
+ Every phase is single-G P U, and each phase file now pins the cheapest Shadeform marketplace tier that fits its peak V RAM: an R T X fifty ninety (32 gigabytes card, plan to about 29 gigabytes usable) by default, escalating to an RTX A six thousand (48 gigabytes card, about 46 gigabytes usable) only where measured need demands it.
198
+
199
+ The full assignment table and operational checklist live in the phase-plan README; the shape of the result is worth internalizing: Here is the same table in spoken form.
200
+
201
+ First: Work: Phases 0 - 4, 6, 7 - all measurement, inference, cache, self-spec, quantization, and routing work.
202
+
203
+ Instance: R T X fifty ninety.
204
+
205
+ Why: Peaks top out near 18 gigabytes.
206
+
207
+ Weights are small (1.4 billion about 2.8 gigabytes, 2.6 billion about 5.3 gigabytes B F sixteen); even two resident copies (Phase 4) or three replicas (Phase 7) fit.
208
+
209
+ Caches and traces dominate and are controllable.
210
+
211
+ Second: Work: Phases 5 and 8 on Ouro-1.4 billion.
212
+
213
+ Instance: R T X fifty ninety.
214
+
215
+ Why: 4-loop BPTT plus large-vocab F P thirty-two loss spikes land at about 12 - 20 gigabytes with the fit rules in each phase file: gradient checkpointing, micro-batch 1, shared teacher or student weights, capped attention alignment.
216
+
217
+ Third: Work: Phases 5 and 8 on Ouro-2.6 billion; full-resolution attention alignment; quantization-kernel fallback.
218
+
219
+ Instance: A six thousand.
220
+
221
+ Why: Training-loss logit spikes and the O of sequence length squared alignment term can exceed 32 gigabytes, and Blackwell (sm120) wheels for G P T Q or A W Q toolchains may lag - the A six thousand's Ampere sm86 is universally supported.
222
+
223
+ Two disciplines carry over from the rest of the lecture.
224
+
225
+ First, the assignments are estimates until measured: the harness logs peak V RAM in gigabytes on every run, and Phase zero or Phase one numbers should overwrite the table.
226
+
227
+ Second, latency results are G P U specific - a Pareto frontier (Section 5) or speculative-decoding speedup (Section 8) measured on the 5090 must never be merged with A six thousand rows; G P U name sits in the logging schema precisely so this mistake is catchable.
228
+
229
+ One operational habit matters more than any number here: Shadeform instances are ephemeral and billed hourly, so sync outputs folder off-instance after every step and tear the instance down when idle - the Phase 0 snapshot manifest is what makes re-provisioning cheap.
230
+
231
+ 4.
232
+
233
+ Phase 0 - Reproducibility before experimentation.
234
+
235
+ Source file: phase zero, environment and baseline.
236
+
237
+ Risk: Low 4.1 Why this phase exists.
238
+
239
+ Ouro is custom remote code with version-sensitive behavior.
240
+
241
+ The failure mode Phase 0 prevents is subtle and expensive: a later "speedup" that is actually broken generation, an incompatible library, or an untracked patch.
242
+
243
+ Every result in Phases 1 - 8 is only as trustworthy as this baseline.
244
+
245
+ 4.2 Snapshot the model source like it's your own code.
246
+
247
+ Because the modeling files arrive via trust remote code equals true, the plan's first move is to make them inspectable and diffable: 1.
248
+
249
+ snapshot download the full repo locally.
250
+
251
+ 2.
252
+
253
+ Write a manifest with SHA-256 hashes of every file (model snapshot manifest dot json).
254
+
255
+ 3.
256
+
257
+ Patch only local copies, keeping a reproducible diff against the original snapshot.
258
+
259
+ This turns "mystery remote code" into a pinned, auditable dependency.
260
+
261
+ When Phase 2 patches the recurrent loop and Phase 3 patches the cache path, the diff against this snapshot is the record of exactly what changed.
262
+
263
+ 4.3 The config-before-load pattern.
264
+
265
+ The loader (ouro extension model loader) encodes landmine number two from Section 2.2 structurally, so nobody can get it wrong: The two control fields are config dot total U T steps, which sets the recurrent depth, and config dot early exit threshold, where one point zero means always run the full configured depth.
266
+
267
+ Every later phase loads the model through this one function.
268
+
269
+ Centralizing the pattern is what makes "loop count is a config knob" actually true in practice.
270
+
271
+ 4.4 Smoke tests and the acceptance gate.
272
+
273
+ Run greedy generation on a fixed math prompt at T equals 1, T equals 2, and T equals 4, logging elapsed time, generated tokens, and peak V RAM for each.
274
+
275
+ You proceed only when: all three depths load and generate, V RAM or time are logged, the snapshot manifest exists, the unit tests pass (model loads at T equals 1; config exposes both knobs), and you have known-good outputs for the same prompt at multiple depths.
276
+
277
+ That last item seems trivial but is the first scientific artifact: three depths, one prompt, visible behavioral difference - the null hypothesis everything later is compared against.
278
+
279
+ 5.
280
+
281
+ Phase 1 - Mapping the loop-depth Pareto frontier.
282
+
283
+ Source file: phase one, loop depth benchmarking.
284
+
285
+ Risk: Low 5.1 The questions.
286
+
287
+ Before modifying anything, establish what the knob is worth in its factory state: Which tasks actually benefit from loops, and which tolerate shallow ones? What does each extra loop cost in latency and V RAM? Is adaptive exit (via the Hugging Face path) worth it versus fixed depth? Do base and Thinking variants behave differently? (Yes - evaluate them separately; a Thinking model collapsing at T equals 1 is expected, not a bug.) 5.2 Design.
288
+
289
+ Sweep fixed depths T in one through six on both model sizes with deterministic greedy decoding (do sample equals false), warmup generations before timing, and repeats for latency stability.
290
+
291
+ Note the sweep deliberately includes T equals 5 and T equals 6 - expected to be useless per Section 2.3 - because confirming the ceiling on your tasks is cheap and definitive.
292
+
293
+ Then sweep early exit threshold values of one point zero, zero point eight, zero point six, zero point four, and zero point two at T equals 4 on the Hugging Face path (threshold one point zero means full depth baseline).
294
+
295
+ One row per example per setting, flushed incrementally so a crash can't erase completed work.
296
+
297
+ Each row carries quality (exact match for math, regex-normalized answers for QA, pass or fail for code), runtime (TTFT, ITL percentiles, tokens per second, peak V RAM), and the realized loop count when the model exposes it - configured and realized depth can differ under adaptive exit.
298
+
299
+ 5.3 Pareto analysis and the decision document.
300
+
301
+ A setting is Pareto-optimal if no other setting has both higher-or-equal quality and lower-or-equal latency with at least one strict improvement.
302
+
303
+ The phase's real deliverable is not the parquet file - it's a decision memo: recommended T per task bucket, best exit threshold, average realized loops, and an explicit "do not use" list (settings that regress past tolerance, or that "win" latency only through truncated or broken generation - always check the cutoff rate before believing a speedup).
304
+
305
+ The tolerances are written down before results arrive, e.g.
306
+
307
+ product-like QA accepts less than or equal to 0.5 - 1 point quality loss for greater than or equal to 10% latency reduction.
308
+
309
+ Pre-committing to thresholds is what keeps the analysis honest.
310
+
311
+ Key idea number three.
312
+
313
+ Phase 1 converts "Ouro has a loop knob" into "for this task, T equals 2 is free money; for that task, never go below 4." Every subsequent phase spends from this map.
314
+
315
+ 6.
316
+
317
+ Phase 2 - Opening the loop: trajectory diagnostics.
318
+
319
+ Source file: phase two, loop trajectory diagnostics.
320
+
321
+ Risk: Low-Medium 6.1 From black box to dynamical system.
322
+
323
+ Phase 1 told you what depth does to accuracy.
324
+
325
+ Phase 2 instruments why, by recording the model's internal trajectory across loop iterations.
326
+
327
+ For each prompt and each loop index t: Here are the entries in spoken form.
328
+
329
+ First: Metric: Logit entropy.
330
+
331
+ Definition: H(p sub t).
332
+
333
+ What it tells you: Is the model getting more confident per loop?.
334
+
335
+ Second: Metric: Top-1 token & margin.
336
+
337
+ Definition: argmax, p one minus p two.
338
+
339
+ What it tells you: Is the answer readout stable?.
340
+
341
+ Third: Metric: K L and J S divergence to next loop.
342
+
343
+ Definition: K L divergence from p at loop t to p at loop t plus one.
344
+
345
+ What it tells you: Is the prediction distribution converging?.
346
+
347
+ Fourth: Metric: Hidden cosine.
348
+
349
+ Definition: cosine between h at loop t and h at loop t plus one.
350
+
351
+ What it tells you: Is the latent state converging?.
352
+
353
+ Fifth: Metric: Relative update norm.
354
+
355
+ Definition: the norm of the current hidden update divided by the previous hidden norm.
356
+
357
+ What it tells you: Are updates shrinking (converging) or exploding?.
358
+
359
+ Sixth: Metric: Answer-at-loop.
360
+
361
+ Definition: parsed answer per t.
362
+
363
+ What it tells you: Would exiting at loop t have been correct?.
364
+
365
+ Start with the final-answer-token logits only; expand to all generated tokens later.
366
+
367
+ Compute divergences in float32 via log softmax - never clip probabilities inside the model path itself.
368
+
369
+ 6.2 Two instrumentation strategies.
370
+
371
+ Strategy A (preferred): patch the local model snapshot (from Phase 0) so the recurrent loop optionally returns loop logits and loop hidden lists, gated by a return loop diagnostics flag.
372
+
373
+ One forward pass yields the whole trajectory.
374
+
375
+ Strategy B (fallback): run the same prompt at total U T steps equal to one, two, three, and four and treat the four final outputs as trajectory proxies.
376
+
377
+ Easy and patch-free, but about 4 times the compute and not guaranteed identical to in-loop states if gates or caches behave differently.
378
+
379
+ Explicitly a temporary baseline.
380
+
381
+ The non-negotiable safety rail for Strategy A: with diagnostics disabled, logits must match the unpatched model to less than one E minus five.
382
+
383
+ This "no-op equivalence" test is the pattern to internalize - every observation tool must prove it doesn't perturb the system when off, and the proof lives in the test suite forever.
384
+
385
+ 6.3 Early-exit rules, and the wrong-attractor trap.
386
+
387
+ From the trajectory metrics, five candidate exit rules are evaluated offline (no serving risk - just replay the recorded trajectories under each rule): 1.
388
+
389
+ K L between consecutive loops below epsilon for m consecutive loops.
390
+
391
+ 2.
392
+
393
+ Parsed answer unchanged for m consecutive loops.
394
+
395
+ 3.
396
+
397
+ Entropy plateau and top one margin above threshold.
398
+
399
+ 4.
400
+
401
+ Hidden update norm shrinkage below epsilon.
402
+
403
+ 5.
404
+
405
+ Conservative combination: K L small AND answer stable AND update small - the recommended first production candidate.
406
+
407
+ Why insist on combining signals? Because of the most instructive failure mode in the phase's table: K L tiny but answer wrong - the model has converged to a wrong attractor.
408
+
409
+ Convergence and correctness are different properties; a stability-only exit rule will confidently early-exit on exactly the examples where extra loops were needed.
410
+
411
+ Related: intermediate readouts can look healthy while the final answer degrades (the literature calls this the readout blind spot), so always validate exit rules against the final task metric, not per-loop proxies.
412
+
413
+ 6.4 Phase 2 is the load-bearing phase.
414
+
415
+ Its outputs feed almost everything downstream - this is why the plan forbids starting Phases 5, 6, or 8 without it: Phase 3 uses trajectories to verify cache reuse doesn't distort loop states.
416
+
417
+ Phase 4 uses loop stability to choose the draft depth.
418
+
419
+ Phase 5 uses trajectory failures (examples where shallow loops flip the answer) as training signal.
420
+
421
+ Phase 6 turns trajectory fidelity into its quantization safety metric.
422
+
423
+ Phase 7 uses trajectory features as router inputs.
424
+
425
+ 7.
426
+
427
+ Phase 3 - K V cache: the prefill or decode asymmetry.
428
+
429
+ Source file: phase three, K V cache optimization.
430
+
431
+ Risk: Medium 7.1 The problem and the empirical anchor.
432
+
433
+ Naive looped decoding stores a K V cache per loop: at T equals 4, roughly 4 times the loop-related decode cache.
434
+
435
+ The guide's empirical anchor (Ouro-1.4 billion) says most of that is waste: Here are the entries in spoken form.
436
+
437
+ First: Decode-time policy: Full per-loop cache (baseline).
438
+
439
+ G S M eight K: 78.92.
440
+
441
+ MATH five hundred: 82.40.
442
+
443
+ Verdict: reference.
444
+
445
+ Second: Decode-time policy: Reuse final loop's K V only.
446
+
447
+ G S M eight K: 78.85.
448
+
449
+ MATH five hundred: 80.40.
450
+
451
+ Verdict: near-lossless, 4 times decode-cache cut.
452
+
453
+ Third: Decode-time policy: Reuse averaged K V.
454
+
455
+ G S M eight K: works.
456
+
457
+ MATH five hundred: works.
458
+
459
+ Verdict: viable ablation.
460
+
461
+ Fourth: Decode-time policy: Reuse first loop's K V.
462
+
463
+ G S M eight K: about 18.7.
464
+
465
+ MATH five hundred: -.
466
+
467
+ Verdict: collapse.
468
+
469
+ Fifth: Decode-time policy: Any reuse during prefill.
470
+
471
+ G S M eight K: -.
472
+
473
+ MATH five hundred: -.
474
+
475
+ Verdict: costs more than 10 points - never.
476
+
477
+ Hence the implementation rule, verbatim from the plan: In plain terms: Prefill: keep full per-loop cache.; Decode: reuse only the final loop K V cache by default.
478
+
479
+ Why the asymmetry? During prefill the model is still building its representation of the prompt - intermediate loops genuinely read intermediate-loop context, and collapsing them corrupts the refinement process itself.
480
+
481
+ By decode time, the prompt representation has converged; the final loop's K V is the converged reading, so new tokens attending only to it lose almost nothing.
482
+
483
+ And first-loop reuse fails for the mirror-image reason: loop 1's K V is a rough draft that later loops were supposed to refine.
484
+
485
+ 7.2 Implementation shape.
486
+
487
+ A CachePolicy enum: fullloopcache, finalloopdecode (target), averageloopdecode (ablation), first-loop decode (negative control - never ship), no cache (debugging).
488
+
489
+ Inspect pastkeyvalues before assuming anything - remote-code cache objects need not follow Hugging Face's standard tuple format.
490
+
491
+ Print the structure after prefill and after one decode step first.
492
+
493
+ If Hugging Face generate() hides the cache handoff, write a minimal explicit greedy loop: prefill with full policy to transform cache to feed one token at a time.
494
+
495
+ Owning the loop makes the prefill or decode boundary impossible to blur - and a test (testprefillusesfullcacheevenwhenpolicyfinal loop) pins that boundary permanently.
496
+
497
+ 7.3 Detecting silent damage: logit drift.
498
+
499
+ Exact-match accuracy is too coarse to catch early corruption, so the phase compares full-cache versus policy runs token by token: max or mean absolute logit difference, K L, and top one agreement (target greater than or equal to 95% on deterministic short generations).
500
+
501
+ A divergence spike at the first decode token is the signature failure - it means the cache transform fired during prefill or selected the wrong loop.
502
+
503
+ Acceptance: memory reduction visible and monotonic with generation length (if memory doesn't fall, the transform likely still holds references to the old loop tensors - a pure Python-object-graph bug that quality metrics will never reveal), quality within the Phase 1 tolerance, and no drift spikes.
504
+
505
+ Notice the epistemic role of first-loop decode: it's kept because it's known-bad.
506
+
507
+ If your harness doesn't show first-loop reuse collapsing, your harness is broken - a built-in positive control for the measurement apparatus itself.
508
+
509
+ 8.
510
+
511
+ Phase 4 - Self-speculative decoding: the loop as its own draft model.
512
+
513
+ Source file: phase four, self-speculative decoding.
514
+
515
+ Risk: Medium 8.1 The idea.
516
+
517
+ Classical speculative decoding needs a separate small draft model.
518
+
519
+ A looped model carries its own draft family inside: the same weights at lower loop count.
520
+
521
+ The self-speculative flow is: draft cheaply with T equals one or T equals two, verify with T equals four, and accept the longest prefix that exactly matches the verifier.
522
+
523
+ The greedy algorithm: draft block size tokens cheaply; run the T equals 4 verifier once over prompt plus block; accept the longest prefix where the verifier's greedy choices match the draft; if nothing matches, emit the verifier's first token (guaranteeing greater than or equal to 1 token of progress per iteration); repeat.
524
+
525
+ 8.2 The exactness contract.
526
+
527
+ The phase's central discipline is a provable correctness property: In plain terms: self-spec text must equal the full T equals four greedy text (exactly, token for token).
528
+
529
+ Under greedy decoding, strict prefix-verification must reproduce the full-depth output exactly - every emitted token is either verified as the T equals 4 greedy choice or produced directly by the verifier.
530
+
531
+ If outputs differ, you don't have a quality trade-off; you have a bug.
532
+
533
+ Only after exact mode works may you explore approximate acceptance rules for extra speed - and then results from the two modes must never be mixed in the same chart.
534
+
535
+ 8.3 An engineering ladder, not a single build.
536
+
537
+ The plan sequences three implementations by risk: Option A - two model instances (one at T equals 2, one at T equals 4): trivially correct, doubles weight V RAM.
538
+
539
+ Correctness prototype only.
540
+
541
+ Option B - one model with mutable per-forward loop count: requires understanding Ouro's custom forward path; the production direction.
542
+
543
+ Option C - shared weights under two lightweight wrappers: most engineering, best serving shape.
544
+
545
+ Prototype where correctness is easy to establish, then migrate the validated behavior toward efficiency - with the exactness test guarding every migration step.
546
+
547
+ 8.4 What decides success.
548
+
549
+ Speedup here is not free; it's an economics question measured by acceptance rate, mean accepted prefix length, and verifier-call count.
550
+
551
+ Two failure modes matter most: acceptance about 0 (draft too shallow for the task - use T equals 2 or smaller blocks; Phase 2 already told you which tasks stabilize early) and negative speedup (verification overhead exceeds drafting savings).
552
+
553
+ Hard math may simply route to full depth - which is fine, because Phase 7 will formalize exactly that.
554
+
555
+ After exact-mode acceptance, re-run the ablation with Phase 3's finalloopdecode policy - the wins compound.
556
+
557
+ A stretch probe for Efficient-Parallel-Samplers-style decoding is explicitly fenced off as a research branch: prototype tiny, and stop if correctness demands architecture surgery deeper than cache or loop wrappers.
558
+
559
+ 9.
560
+
561
+ Phase 5 - Per-loop LoRA: breaking weight-tying symmetry cheaply.
562
+
563
+ Source file: phase five, per-loop LoRA S F T.
564
+
565
+ Risk: Medium-High 9.1 Why loops might want to differ.
566
+
567
+ Weight sharing is the source of the memory win, but it imposes a symmetry: loop 1 (rough encoding) and loop 4 (final refinement) plausibly want different computation, yet must use identical weights.
568
+
569
+ The literature's standard fix: keep the shared backbone frozen and attach small loop-indexed LoRA deltas - loop i gets its own low-rank adapter, so each pass can specialize for a few megabytes instead of unsharing gigabytes.
570
+
571
+ The per-loop LoRA wrapper chooses an adapter by loop index, applies that low-rank delta to the shared linear layer, and leaves the frozen base projection intact.
572
+
573
+ Practical starting point: rank 8, alpha equals sixteen, on query projection, output projection, up projection, and down projection; raise rank or retarget modules only if the adapter underfits.
574
+
575
+ The wiring challenge is real but shallow: the loop index must be plumbed into the adapted linears - exactly the loop-context plumbing Phase 2's instrumentation already built.
576
+
577
+ 9.2 The zero-init gate.
578
+
579
+ Because B matrices start at zero, the wrapped model must be bitwise-boring before training: At zero initialization, the base logits and LoRA logits must match to less than one E minus five before training starts.
580
+
581
+ If this fails, do not train.
582
+
583
+ A wiring mistake that shifts outputs at zero-init would otherwise be laundered into the trained weights, and every downstream eval would measure the bug.
584
+
585
+ Same pattern as Phase 2's no-op test: prove the intervention is invisible when off.
586
+
587
+ 9.3 Controlled experiment design.
588
+
589
+ Five variants, each isolating one question - is any tuning enough (B: shared LoRA)? does loop-indexing add anything over it (C)? does sampling T sampled from two, three, and four per sequence during training buy depth robustness (D)? does distilling from the frozen T equals 4 teacher rescue shallow-loop quality (E: cross-entropy plus a beta-weighted K L distillation term from the T equals four teacher)? Variant E is the strategically interesting one: it doesn't chase peak quality - it purpose-builds a better cheap model at T equals 2 or T equals 3, which is precisely what Phase 4's drafter and Phase 7's router want to buy.
590
+
591
+ An optional stability regularizer penalizes exploding update norms - gently; the goal is preventing explosive loop dynamics, not making loops identical (identical loops would defeat the point of depth).
592
+
593
+ 9.4 Evaluate off the training point.
594
+
595
+ Everything is evaluated at T equals one through six, never just the trained depth, with three named deltas: low-loop recovery (score at T equals two minus frozen score at T equals two), full-depth preservation (score at T equals four minus frozen score at T equals four), and over-loop robustness (T equals five and T equals six).
596
+
597
+ The rejection criteria bite: reject if full-depth quality drops on the locked suite, if the adapter only helps the training distribution, or - importantly - if per-loop LoRA merely ties shared LoRA while adding complexity.
598
+
599
+ Complexity must pay rent.
600
+
601
+ 10.
602
+
603
+ Phase 6 - Loop-aware quantization: error compounds along the trajectory.
604
+
605
+ Source file: phase six, loop-aware quantization.
606
+
607
+ Risk: Medium-High 10.1 Why dense-model PTQ recipes mislead here.
608
+
609
+ Three independent 2026 results (LoopQ; Hyperloop's loop-aware G P T Q; the ML Collective edge study) converge on one message: in a looped model, quantization error is recursive - the same quantized layer's error feeds back into its own next-iteration input.
610
+
611
+ Three loop-specific failure modes follow: (1) one shared layer sees different activation distributions at loop 1 versus loop 4, so single-role calibration fits none of them; (2) state reuse across loop transitions propagates error; (3) errors accumulate along the trajectory.
612
+
613
+ Baseline W four A four doesn't degrade gracefully - it collapses (greater than 200 perplexity on LAMBADA, with spikes at loop transitions).
614
+
615
+ The edge study adds the most deceptive finding: aggressive compression can preserve local token predictions while destroying global reasoning - per-token accuracy holds while exact-solution accuracy collapses to zero.
616
+
617
+ Hence the phase's evaluation dogma: exact match on end tasks, never perplexity alone.
618
+
619
+ Perplexity is a local metric; looped reasoning is a global property.
620
+
621
+ 10.2 The one-sentence fix, and the safety metric.
622
+
623
+ Never calibrate a shared layer as if it were used once.
624
+
625
+ Collect activation statistics per loop index, then calibrate each shared layer on the union across all its loop roles - Hyperloop's version for G P T Q: aggregate the Hessian estimate over all iterations of the layer (their reference recipe: INT4, 1024 calibration sequences, group size 128).
626
+
627
+ Per-loop stats also serve as a risk map: layers whose loop one versus loop four distributions differ most are flagged as fragile before any quantization runs.
628
+
629
+ The safety metric generalizes Phase 2's machinery - trajectory fidelity: Trajectory fidelity is the cosine similarity between the full-precision hidden state and the quantized hidden state, measured by layer and by loop index.
630
+
631
+ aggregated by layer, by loop, and - most diagnostic of all - across loop transitions (t to t plus one), because that's where recursive error spikes first.
632
+
633
+ Safety thresholds are pre-committed: quality drop less than or equal to 1 point, mean fidelity greater than or equal to 0.98 with no catastrophic layer or loop dips, top one agreement greater than or equal to 95%.
634
+
635
+ 10.3 The ladder and the rescue playbook.
636
+
637
+ Compression proceeds in strictly increasing aggressiveness - do not start at W four A four: Here are the entries in spoken form.
638
+
639
+ First: Stage: Q0.
640
+
641
+ Format: B F sixteen.
642
+
643
+ Role: baseline.
644
+
645
+ Second: Stage: Q1.
646
+
647
+ Format: W eight A sixteen.
648
+
649
+ Role: sanity compression.
650
+
651
+ Third: Stage: Q2.
652
+
653
+ Format: W four A sixteen, standard calibration.
654
+
655
+ Role: negative or standard control.
656
+
657
+ Fourth: Stage: Q3.
658
+
659
+ Format: W four A sixteen, loop-aware calibration.
660
+
661
+ Role: first real target.
662
+
663
+ Fifth: Stage: Q4.
664
+
665
+ Format: Q three plus per-layer rescue.
666
+
667
+ Role: safer target.
668
+
669
+ Sixth: Stage: Q5.
670
+
671
+ Format: W four A four loop-aware.
672
+
673
+ Role: stretch only.
674
+
675
+ Q2 plays the same role as first-loop decode in Phase 3: the expected-worse control that proves the loop-aware treatment (Q3) actually causes the improvement.
676
+
677
+ For layers that stay fragile, the rescue ladder is graded - keep B F sixteen, drop to W8, shrink group size, per-channel scales, loop-aware activation scaling - and the plan explicitly permits the first accepted checkpoint to be mixed precision.
678
+
679
+ A uniformly-INT4 model that fails reasoning is worth less than a mixed model that works.
680
+
681
+ One caveat carried from the guide: compression (smaller checkpoint, less V RAM) and latency are separate wins - without hardware-suited kernels, INT4 can run no faster than B F sixteen.
682
+
683
+ 11.
684
+
685
+ Phase 7 - The hardness router: adaptive compute without engine support.
686
+
687
+ Source file: phase seven, hardness router and serving.
688
+
689
+ Risk: Medium 11.1 Reframing early exit as a systems problem.
690
+
691
+ Recall landmine number three: production engines run Ouro at fixed full depth - the model's internal adaptive exit is unusable there.
692
+
693
+ Phase 7's move is to hoist the depth decision out of the model and into the serving layer: a request-level router picks, per prompt, In plain terms: T star is the smallest loop count whose answer matches the full-depth answer (or the target).
694
+
695
+ Labels come free from Phase 1's sweep (every example already has outcomes at every T - when no ground truth exists, T equals 4 serves as pseudo-teacher, flagged as a weaker label).
696
+
697
+ Request-level routing is chosen deliberately over token-level: it needs no model surgery, works with any engine, and is auditable.
698
+
699
+ Token-level adaptivity is the literature's frontier, not a first implementation.
700
+
701
+ 11.2 Features and models: buy signal only when needed.
702
+
703
+ Three feature tiers, in increasing cost: A - prompt-only (length, math-symbol density, code-likeness, question type; zero model cost), B - one-loop probe (run T equals 1, read entropy or top one margin or answer-parse confidence - a hardness measurement, since Phase 2 showed easy prompts converge almost immediately), C - two-loop stability (K L between T equals 1 and T equals 2 outputs, answer stability; strongest and priciest).
704
+
705
+ Start with A plus B.
706
+
707
+ The same escalation logic governs the classifier: rules to logistic regression or GBDT to small MLP only if tabular fails.
708
+
709
+ The recommended first router is prompt-only gradient-boosted trees plus a conservative fallback to T equals 4 whenever confidence less than 0.75.
710
+
711
+ 11.3 Asymmetric loss - the ethical core of the router.
712
+
713
+ The two error types are not symmetric: undercompute that flips a correct answer to wrong is strictly worse than overcompute that wastes loops.
714
+
715
+ The config makes the asymmetry explicit - loss weight undercorrect: one point zero versus loss weight overcompute: 0.25 - and the eval tracks undercorrect rate (router chose cheap-and-wrong where T equals 4 was right) as a first-class metric, with the acceptance gate requiring those cases be manually reviewed, not just counted.
716
+
717
+ Acceptance targets: quality within less than or equal to 0.5 - 1 point of always-T equals 4 while cutting average loop count greater than or equal to 15%.
718
+
719
+ 11.4 Serving topologies.
720
+
721
+ Three deployment shapes, exploiting that fixed-depth Ouro is engine-supported: 1.
722
+
723
+ Hugging Face dynamic server - one process, per-request depth; flexible, slower per token.
724
+
725
+ 2.
726
+
727
+ Fixed-depth replicas - ouro-t2-server, ouro-t3-server, ouro-t4-server behind the router; each replica is a plain fixed-depth model, so v L L M or S G Lang work fine.
728
+
729
+ The engine limitation is routed around, not waited on.
730
+
731
+ 3.
732
+
733
+ Hybrid - v L L M replicas for easy high-throughput traffic, Hugging Face path for uncertain or diagnostic traffic.
734
+
735
+ Production logging closes the loop (selected depth, confidence, fallback flag, latency, answer hash - with prompt hashes rather than raw text unless privacy policy allows), turning every served request into future router training data.
736
+
737
+ 12.
738
+
739
+ Phase 8 - MELT-lite: one gated cache (stretch goal).
740
+
741
+ Source file: phase eight, MELT-lite single-cache stretch.
742
+
743
+ Risk: High 12.1 From selection to fusion.
744
+
745
+ Phase 3 selected one loop's K V cache, a zero-training inference trick).
746
+
747
+ MELT (the paper this phase miniaturizes) changes the model's memory design: a single K V cache per layer, shared across all loops, updated each iteration by a learned gate - constant memory in reasoning depth.
748
+
749
+ That is a change to recurrent dynamics, which is why it needs training and sits at the end of the dependency graph, gated on Phase 3's cache understanding.
750
+
751
+ MELT-lite strips the idea to its cheapest testable form: In plain terms: The new shared K V cache equals alpha times the old shared K V cache, plus one minus alpha times the current loop K V cache.
752
+
753
+ with alpha a learned scalar per (layer, loop) - sigmoid-parameterized, initialized near 0.8 (biased toward retaining memory).
754
+
755
+ Vector (per-channel) gates only if scalars demonstrably underfit.
756
+
757
+ 12.2 Minimal-intervention training.
758
+
759
+ Three stages, each adding trainable surface only if the previous underfits - with the base model frozen throughout: 1.
760
+
761
+ Gate-only distillation: train just the alpha parameters (dozens of them!) to match the full-cache teacher: K L from student to teacher logits, plus lambda times hidden-state mean squared error.
762
+
763
+ This is a pure hypothesis test: is cache interpolation enough? 2.
764
+
765
+ Then add tiny LoRA on attention output projections - reusing Phase 5's machinery - if gates alone can't match the teacher.
766
+
767
+ 3.
768
+
769
+ Then add task cross-entropy loss on final answers, only once distillation is stable.
770
+
771
+ The unit tests are boundary-condition proofs: alpha equals one must reproduce pure old-cache behavior, alpha equals zero pure current-cache; the gated cache must remain structurally valid for the next decode step.
772
+
773
+ And the trained gate values are themselves an interpretability artifact - alpha near 1 in some layer says "long-term memory layer"; alpha near 0 says "recompute every loop." 12.3 Kill criteria as a feature.
774
+
775
+ The phase pre-declares when to stop: gate-only training can't match teacher logits; memory reduction doesn't beat Phase 3's final-loop reuse in your actual serving mode; or quality losses concentrate on exactly the reasoning tasks Ouro exists to be good at.
776
+
777
+ A stretch goal with explicit kill criteria is research; one without them is a sunk-cost trap.
778
+
779
+ 13.
780
+
781
+ The through-lines: ten engineering lessons.
782
+
783
+ Zoom out and the nine phases repeat a small set of moves.
784
+
785
+ These generalize far beyond Ouro: 1.
786
+
787
+ Measure before modifying.
788
+
789
+ Three full phases of measurement precede the first optimization.
790
+
791
+ The plan's own words: without baselines you can't distinguish "improved reasoning" from "changed surface likelihood." 2.
792
+
793
+ Reproducibility is an artifact, not a habit.
794
+
795
+ Pinned versions, SHA-256 manifests, logged revisions or seeds or commits - all machine-checkable, none aspirational.
796
+
797
+ 3.
798
+
799
+ Every intervention ships an equivalence proof.
800
+
801
+ Diagnostics off implies logits match (Phase 2).
802
+
803
+ LoRA at zero-init implies logits match (Phase 5).
804
+
805
+ Full-cache policy implies identity (Phase 3).
806
+
807
+ Greedy self-spec implies exact T equals 4 output (Phase 4).
808
+
809
+ B F sixteen versus B F sixteen fidelity implies about 1.0 (Phase 6).
810
+
811
+ alpha at zero or one implies pure endpoints (Phase 8).
812
+
813
+ 4.
814
+
815
+ Carry negative and positive controls.
816
+
817
+ first-loop decode should collapse; standard G P T Q should underperform loop-aware.
818
+
819
+ If your controls don't behave, distrust the harness before the treatment.
820
+
821
+ 5.
822
+
823
+ Local metrics lie about global properties.
824
+
825
+ Perplexity and per-token agreement survive compressions that zero out exact-match reasoning.
826
+
827
+ Evaluate the property you actually care about.
828
+
829
+ 6.
830
+
831
+ Loop transitions are where things break.
832
+
833
+ Cache handoffs, quantization error spikes, drift at the first decode token - instrument boundaries hardest.
834
+
835
+ 7.
836
+
837
+ Exploit asymmetries.
838
+
839
+ Prefill is not the same as decode (Phase 3).
840
+
841
+ Undercorrect is not the same as overcompute (Phase 7).
842
+
843
+ Draft is not the same as verify (Phase 4).
844
+
845
+ Uniform treatment of asymmetric situations leaves value on the table.
846
+
847
+ 8.
848
+
849
+ Convergence is not the same as correctness.
850
+
851
+ A stable trajectory can be stably wrong.
852
+
853
+ Exit rules and routers must consult answer-level signals, not just dynamics.
854
+
855
+ 9.
856
+
857
+ Escalate complexity only against demonstrated need.
858
+
859
+ Rank 8 before 16; scalar gates before vector; rules before GBDT before MLP; two-model prototype before shared-weight production build.
860
+
861
+ Each rung must beat the previous one to justify itself.
862
+
863
+ 10.
864
+
865
+ Pre-commit tolerances and kill criteria.
866
+
867
+ Every phase states its acceptance numbers - and its rejection conditions - before results exist.
868
+
869
+ That is what separates an execution plan from a hopeful roadmap.
870
+
871
+ 14.
872
+
873
+ Check your understanding.
874
+
875
+ Work these before peeking at the answers.
876
+
877
+ Q1.
878
+
879
+ Why must total U T steps be modified on the config object before from pretrained rather than on model dot config afterward? Q2.
880
+
881
+ Final-loop K V reuse at decode is near-lossless (G S M eight K 78.85 vs 78.92) while first-loop reuse collapses ( about 18.7), and any reuse during prefill costs more than 10 points.
882
+
883
+ Explain all three facts with one mechanism.
884
+
885
+ Q3.
886
+
887
+ In Phase 2, a batch of failing examples shows K L between consecutive loops falling below epsilon by loop 2, yet the answers are wrong.
888
+
889
+ What is happening, and which exit rule component protects against it? Q4.
890
+
891
+ State the correctness invariant of Phase 4's greedy self-speculative decoder, and explain why violating it indicates a bug rather than a quality trade-off.
892
+
893
+ Q5.
894
+
895
+ Your Phase 7 router keeps sending hard MATH five hundred prompts to T equals 2.
896
+
897
+ Which two config values would you adjust first? Q6.
898
+
899
+ Why does Phase 6 require calibrating each shared layer on activations aggregated across all loop indices, and what metric detects when this wasn't done properly? Q7.
900
+
901
+ Why is "loop to T equals 8 at inference for extra quality" not a viable plan for Ouro? Answers.
902
+
903
+ A1.
904
+
905
+ The remote modeling code consumes the loop configuration when the model object is constructed.
906
+
907
+ from pretrained with the modified config bakes the depth in; editing model dot config afterward changes a bookkeeping attribute the already-built forward path may never re-read.
908
+
909
+ Phase 0 centralizes the correct order in load Ouro so it can't be done wrong ad hoc.
910
+
911
+ A2.
912
+
913
+ The loop performs iterative refinement of the context representation.
914
+
915
+ During prefill, intermediate loops must read their own intermediate-quality K V to perform the refinement - collapsing caches corrupts the process itself (more than ten-point loss).
916
+
917
+ By decode time the prompt representation has converged, and the final loop's K V is that converged representation, so new tokens attending to it alone lose almost nothing.
918
+
919
+ First-loop K V is the unrefined draft - attending to it discards precisely the refinement the model's quality depends on.
920
+
921
+ A3.
922
+
923
+ The model has converged to a wrong attractor: the trajectory is stable but the fixed point encodes an incorrect answer.
924
+
925
+ Pure stability rules (K L, update norm) would exit early with confidence.
926
+
927
+ The conservative combined rule adds answer-level signals - parsed-answer stability plus confidence margin - and the phase's guidance is to validate every rule against the final task metric, never trajectory dynamics alone.
928
+
929
+ A4.
930
+
931
+ self-spec text must equal the full T equals four greedy text, token for token.
932
+
933
+ Every emitted token is either a draft token verified to equal the verifier's greedy choice at that position, or the verifier's own first token after a rejection - so by construction the output sequence is exactly what greedy T equals 4 decoding would have produced.
934
+
935
+ Any mismatch means the verification logic (positions checked, cache state, prefix acceptance) is implemented incorrectly.
936
+
937
+ A5.
938
+
939
+ Raise loss weight undercorrect relative to loss weight overcompute (making cheap-but-wrong routing more expensive during training), and raise minimum confidence so low-confidence predictions fall back to T equals 4.
940
+
941
+ If the misrouting persists, escalate the feature set from prompt-only to the one-loop probe, since hardness may only be visible after the model starts working.
942
+
943
+ A6.
944
+
945
+ A shared layer plays a different role at each loop index and sees a different activation distribution at each (LoopQ's "distribution shift across loop roles").
946
+
947
+ Calibrating on one role fits none of the others, and the resulting per-iteration error compounds recursively.
948
+
949
+ The detection metric is trajectory fidelity - cosine similarity between B F sixteen and quantized hidden states per (layer, loop) - with special attention to loop-transition fidelity, where recursive error spikes first; the acceptance gate demands mean fidelity greater than or equal to 0.98 with no catastrophic dips.
950
+
951
+ A7.
952
+
953
+ Ouro was trained at T equals 4, and quality peaks at the trained depth, degrading at T equals 5 - 8; scaling analyses independently show test-time loop gains saturate near the mean training recurrence.
954
+
955
+ Extra inference loops move the model off its training distribution rather than buying more refinement.
956
+
957
+ The exploitable direction is downward - spending fewer loops on easy inputs via exit rules and routing.
958
+
959
+ 15.
960
+
961
+ Where to go next.
962
+
963
+ Within this folder.
964
+
965
+ The phase plans are execution-ready: start at phase zero, environment and baseline and respect the dependency graph in Section 3.
966
+
967
+ The R D T Guide supplies the surrounding field: Track B (converting a standard pretrained model to recurrent depth), the ecosystem or tooling status matrix, and the July 2026 open-problems watchlist - of which two directly gate this plan's ceiling: adaptive-exit-aware serving engines, and a packaged loop-aware quantization library.
968
+
969
+ Primary literature anchoring the phases (arXiv IDs as cited in the plans): Here are the entries in spoken form.
970
+
971
+ First: Topic: The model itself.
972
+
973
+ Paper: Ouro, also called LoopLM.
974
+
975
+ ID: 2510.25741.
976
+
977
+ Second: Topic: Recurrent-depth reference architecture.
978
+
979
+ Paper: Huginn.
980
+
981
+ ID: 2502.05171.
982
+
983
+ Third: Topic: Per-loop LoRA precedent (Phase 5).
984
+
985
+ Paper: Relaxed Recursive Transformers.
986
+
987
+ ID: 2410.20672.
988
+
989
+ Fourth: Topic: Constant-memory cache target (Phase 8).
990
+
991
+ Paper: MELT.
992
+
993
+ ID: 2605.07721.
994
+
995
+ Fifth: Topic: Loop-aware PTQ (Phase 6).
996
+
997
+ Paper: LoopQ.
998
+
999
+ ID: 2605.16343.
1000
+
1001
+ Sixth: Topic: Loop-aware G P T Q recipe (Phase 6).
1002
+
1003
+ Paper: Hyperloop Transformers.
1004
+
1005
+ ID: 2604.21254.
1006
+
1007
+ Seventh: Topic: Compression failure modes + fidelity metric (Phase 6).
1008
+
1009
+ Paper: "What Survives.Edge".
1010
+
1011
+ ID: 2606.26488.
1012
+
1013
+ Eighth: Topic: Stability + loop scaling ceiling (section 2.3).
1014
+
1015
+ Paper: Parcae.
1016
+
1017
+ ID: 2604.12946.
1018
+
1019
+ Ninth: Topic: Token-adaptive recursion context (Phase 7).
1020
+
1021
+ Paper: Mixture-of-Recursions.
1022
+
1023
+ ID: 2507.10524.
1024
+
1025
+ Tenth: Topic: Cross-loop parallel latency fix.
1026
+
1027
+ Paper: Parallel Loop Transformer.
1028
+
1029
+ ID: 2510.24824.
1030
+
1031
+ Community index: github.com or huskydoge or Awesome-Loop-Models - the field's de-facto tracker, with dated briefings.
1032
+
1033
+ Closing thought.
1034
+
1035
+ Nothing in this plan invents a new architecture.
1036
+
1037
+ Its value is the discipline: a fixed measurement foundation, an equivalence test guarding every intervention, controls that validate the harness, and pre-committed numbers deciding what ships.
1038
+
1039
+ The loop knob makes adaptive compute possible; the engineering method is what makes it trustworthy.
1040
+
1041
+ Lecture notes prepared July 7, 2026, from the materials in this folder: R D T Guide (snapshot date July 7, 2026) and Ouro execution phase plans phases 00 - 08.
1042
+
1043
+ Author-reported figures cited here (G S M eight K or MATH five hundred cache numbers, quantization collapse statistics) inherit the confidence labels of the source guide.
lectures/rashomon-instability.md ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Rashomon Analysis & Model Instability
2
+
3
+ Paper 1. When Many Models Fit Equally Well: Rashomon Analysis, the Noise-Simplicity Connection, and a Taxonomy of Model Instability for Psychology.
4
+
5
+ Target: Psychological Methods or Psychological Review.
6
+
7
+ Executive Summary: Three Contributions.
8
+
9
+ First, psychological outcomes are noisy. Noisy outcomes produce large Rashomon sets, as shown by Semenova and others in 2023. Large Rashomon sets mean many models fit equally well. Therefore, single-model reporting in psychology is formally expected to be inadequate. This is not an empirical observation but a theoretical prediction.
10
+
11
+ Second, model instability comes in two types: epistemic and representational, with different consequences. This taxonomy is novel.
12
+
13
+ Third, jointly examining feature-level instability using MCR and predictive multiplicity provides an empirical diagnostic for partially separating the two types.
14
+
15
+ ## Section 1. Introduction: The Problem Is Theoretically Predictable
16
+
17
+ Machine learning methods have been rapidly adopted in psychology. Studies report a single best model and derive conclusions from it. We argue this is formally expected to fail. The argument has three steps, each grounded in existing theory.
18
+
19
+ Step 1, from Semenova and others 2023: Outcome noise expands the Rashomon set. Noisier data leads to a flatter loss surface, which leads to more near-optimal models. This is not a conjecture; it is a proven mathematical result.
20
+
21
+ Step 2, an empirical fact: Psychological outcomes are among the noisiest in science. Self-report measures have test-retest reliabilities of 0.7 to 0.85. Behavioral outcomes have substantial day-to-day variability. Signal-to-noise ratios are typically low.
22
+
23
+ Step 3, the logical consequence: Psychology should exhibit large Rashomon sets. Many structurally different models will achieve near-identical performance. Conclusions drawn from any single model are one of many equally valid explanations.
24
+
25
+ This three-step argument makes a specific, falsifiable prediction: the Rashomon ratio for typical psychological datasets should be large. We test this prediction empirically in Section 6. If confirmed, the implication is stark: the single-model reporting convention is not just a practical weakness but a theoretically predicted failure mode for noisy applied domains.
26
+
27
+ ## Section 2. The Rashomon Framework: Formal Foundations
28
+
29
+ ## Section 2.1. The Rashomon Set
30
+
31
+ Let F be a function class, ell a loss function, S a dataset, and f star the empirical risk minimizer. The Rashomon set, as defined by Fisher and others in 2019, is: R of epsilon, F, and S equals the set of all f in F such that L of f on S is less than or equal to L of f star on S plus epsilon.
32
+
33
+ ## Section 2.2. The Rashomon Ratio
34
+
35
+ The Rashomon ratio, from Semenova and others 2022, is the volume of the Rashomon set relative to the hypothesis space: R ratio of F and theta equals the volume of R divided by the volume of F. It ranges from 0 to 1. A large ratio means many models achieve near-optimal performance. The Rashomon ratio is fundamentally different from standard complexity measures such as VC dimension and Rademacher complexity. It depends on both the function class and the dataset, capturing the specific degree of model ambiguity for the problem at hand.
36
+
37
+ Cheap diagnostic: Semenova and others showed that if several different ML algorithms achieve similar performance on a dataset, this is evidence of a large Rashomon ratio. Before building the full Rashomon set, researchers can check: do linear regression, random forest, XGBoost, and a GAM all achieve roughly the same test loss? If yes, the Rashomon ratio is likely large, and single-model conclusions are likely fragile. This check costs minutes, not hours.
38
+
39
+ ## Section 2.3. Model Reliance and Model Class Reliance
40
+
41
+ Fisher and others in 2019 defined Model Reliance, or MR, for a model f as the ratio of f's expected loss when covariate X 1 is permuted to its loss without permutation. They proved that MR estimators are U-statistics, enabling finite-sample inference. This is their Theorem 5. This gives the diagnostics a rigorous statistical foundation. MR is not a heuristic but an estimator with known bias, variance, and convergence properties.
42
+
43
+ Model Class Reliance, or MCR, extends MR across the Rashomon set: MCR minus equals the minimum of MR of f, and MCR plus equals the maximum of MR of f, over all f in the Rashomon set R of epsilon. The MCR range width, which is MCR plus minus MCR minus, is the primary estimand of feature-level instability. Fisher and others provide finite-sample bounds for MCR using covering numbers.
44
+
45
+ ## Section 2.4. The MR-Causal Connection
46
+
47
+ Fisher and others, in their Proposition 19, proved that for binary covariates, MR can be written as a function of conditional causal effects of X 1 on Y. This is not merely an analogy. It is a formal mathematical relationship. For binary treatment indicators, clinical group assignments, and diagnostic categories, which are common in psychology, model reliance directly encodes causal effect information. This substantially strengthens the argument that Rashomon stability serves as indirect evidence of structural plausibility: when MR is mathematically linked to causal effects, MCR minus greater than zero means that every near-optimal model encodes a non-zero causal-adjacent quantity.
48
+
49
+ ## Section 2.5. Rashomon Importance Distribution, or RID
50
+
51
+ Donnelly and others at NeurIPS 2023 addressed MCR's instability under resampling by bootstrapping the dataset B times, computing the Rashomon set for each, and averaging importance CDFs. RID has proven exponential convergence via Hoeffding's inequality. The HIV viral load application discovered the gene LINC00486 as robustly important, a finding that single-model importance and even MCR without bootstrapping missed. This serves as a template for what Rashomon analysis could discover in psychological data.
52
+
53
+ ## Section 2.6. The Noise-Simplicity Theorem
54
+
55
+ This is a key theorem for psychology. Semenova and others in 2023 proved that Rashomon sets constructed from noisy data tend to contain simpler models than corresponding sets from non-noisy data. Noise expands the set of good features and enlarges the set of models using at least one good feature. For psychology, this means: the noisier your outcome measure, and psychological outcomes are very noisy, the more models fit it well, and the more likely that a simple interpretable model is among them. The complexity premium of boosted models over linear models is theoretically expected to be small for noisy psychological outcomes.
56
+
57
+ ## Section 2.7. The Covering Argument: Why Simpler Models Exist
58
+
59
+ Semenova and others in 2022 proved: if a simpler function class F 1, for example sparse linear models, serves as a delta-cover for a complex class F 2, for example all boosted models, meaning for every f in F 2 there exists g in F 1 within delta in prediction space, then a sufficiently large Rashomon set in F 2 must contain models from F 1. Rudin and others in 2024 noted that any boosted decision tree is equivalent to a single tree of greater depth, so sparse trees naturally cover boosted ensembles. This provides formal mathematical justification for testing whether simpler model classes fall within the Rashomon threshold. It is not a heuristic. It is a consequence of the covering number structure of the hypothesis spaces.
60
+
61
+ ## Section 3. Two Types of Model Instability. This is the novel theoretical contribution
62
+
63
+ The distinction between epistemic and representational instability has not been formalized in the Rashomon literature. Fisher and others discuss MCR ranges. Donnelly and others discuss importance stability. RashomonGB discusses predictive multiplicity. None distinguish why models in the Rashomon set disagree. This section provides that distinction and proposes an empirical diagnostic using the joint examination of MCR and predictive multiplicity.
64
+
65
+ ## Section 3.1. Epistemic Instability
66
+
67
+ The data genuinely underdetermines the model. Different near-optimal models produce different predictions for the same individuals and different feature importance rankings. Both interpretations and decisions are unstable. Epistemic instability arises when signal-to-noise ratio is low, sample size is moderate, and the predictive surface admits multiple functional forms.
68
+
69
+ ## Section 3.2. Representational Instability
70
+
71
+ Different models encode the same underlying function through different parameterizations. They produce similar predictions but differ in which features they credit. This arises when the function class is over-parameterized, features are correlated enabling substitution, or the model class permits multiple decompositions of the same joint surface.
72
+
73
+ ## Section 3.3. The Two-by-Two Diagnostic Matrix
74
+
75
+ The two types can be partially distinguished by jointly examining feature-level instability, measured by MCR range width, and predictive multiplicity, the established term from RashomonGB for disagreement in individual predictions across the Rashomon set.
76
+
77
+ When predictive multiplicity is low and MCR range is narrow, the situation is stable. Low instability overall. Single-model reporting is adequate.
78
+
79
+ When predictive multiplicity is high and MCR range is narrow, this is unusual. Models agree on importance but disagree on predictions. This may indicate sensitivity to outliers.
80
+
81
+ When predictive multiplicity is low and MCR range is wide, this indicates representational instability. Explanations differ but decisions are robust. Follow-up should use functional distance analysis.
82
+
83
+ When predictive multiplicity is high and MCR range is wide, this indicates epistemic instability. Both explanations and decisions are fragile. This is the most concerning case. Follow-up requires more data or accepting ambiguity.
84
+
85
+ ## Section 3.4. Consequences Differ by Type
86
+
87
+ For epistemic instability: feature importance rankings are unstable, individual predictions are unstable, risk classifications are unstable, clinical decisions are undermined, scientific interpretation is undermined, and the required follow-up is more data, a stronger design, or accepting ambiguity.
88
+
89
+ For representational instability: feature importance rankings are unstable, but individual predictions are stable, risk classifications are stable, clinical decisions are likely safe, scientific interpretation is still undermined, and the required follow-up is functional distance metrics, where a prediction-level audit may suffice.
90
+
91
+ ## Section 4. Rashomon Stability as Indirect Evidence of Structural Plausibility
92
+
93
+ This argument is stronger than previously framed. Fisher and others' Proposition 19 proves that for binary covariates, MR is a function of conditional causal effects. This is not an analogy. It is a theorem. When X 1 is binary, such as a treatment indicator, clinical group assignment, or diagnostic category, MCR minus greater than zero means every near-optimal model encodes a non-zero causal-adjacent quantity.
94
+
95
+ For continuous covariates, the connection is weaker. MR reflects predictive, not causal, contribution. But the logic still applies directionally: genuinely causal mechanisms impose functional constraints that should be harder to substitute away than noise artifacts.
96
+
97
+ Boundary conditions: The connection is strongest for binary covariates, via the formal causal connection in Proposition 19. It is moderate for continuous covariates with low-to-moderate inter-predictor correlation, meaning rho less than 0.4. It weakens as correlation increases, since substitution enables real effects to appear dispensable. And it is not a substitute for causal identification strategies, but rather a complement to them.
98
+
99
+ ## Section 5. Formal Comparison to Existing Stability Approaches
100
+
101
+ Compared to bootstrap importance, stability selection, multiverse analysis, and specification curve analysis, Rashomon analysis uniquely provides: feature instability assessment, predictive multiplicity measurement, cross-model comparison, cross-class comparison via the covering argument, partial epistemic versus representational distinction, and formal inference since MR is a U-statistic with known finite-sample properties.
102
+
103
+ ## Section 6. Empirical Demonstration
104
+
105
+ ## Section 6.1. Step 0: The Rashomon Ratio Diagnostic
106
+
107
+ Before any formal Rashomon analysis, apply Semenova and others' cheap diagnostic: fit 4 to 5 structurally different ML algorithms, such as linear regression, regularized regression, random forest, XGBoost, and GAM, on the same psychological dataset. If they achieve similar test performance, the Rashomon ratio is likely large. Report the inter-algorithm performance range as the first empirical result. If this range is small, for example delta R squared less than 0.03, the single-model convention is immediately suspect.
108
+
109
+ ## Section 6.2. Rashomon Ratio Estimation
110
+
111
+ Using depth-bounded decision trees as a surrogate, following Semenova and others 2022, estimate the Rashomon ratio directly. Compare the estimated ratio for the psychological dataset to the ratios reported by Semenova and others for their benchmark datasets, providing context for whether the psychological data exhibits an unusually large or small Rashomon effect.
112
+
113
+ ## Section 6.3. The Instability Taxonomy in Practice
114
+
115
+ Construct the within-class Rashomon set for XGBoost. Compute MCR range width for each variable and predictive multiplicity, including individual prediction range and classification disagreement rate, across the Rashomon set. Apply the two-by-two diagnostic matrix. Target: identify at least one variable in each cell, stable, representationally unstable, and epistemically unstable.
116
+
117
+ ## Section 6.4. TreeFARMS Calibration
118
+
119
+ On a simplified version of the problem using sparse decision trees of bounded depth, apply TreeFARMS from Xin and others 2022 for exact Rashomon set enumeration. Compare MCR ranges from the exact set to those from the approximate retraining-based set. This quantifies the undercoverage bias of the approximation, the degree to which retraining underestimates the true range of model reliance. This calibration step is unique to this paper and provides the first empirical measurement of approximation quality for a psychological dataset.
120
+
121
+ ## Section 6.5. The Bootstrap-Stable but Rashomon-Unstable Case
122
+
123
+ Demonstrate at least one feature whose importance is stable under bootstrap resampling, seed perturbation, and stability selection, but whose MCR range is wide. This is the core justification for Rashomon analysis beyond existing methods.
124
+
125
+ ## Section 7. Limitations of Paper 1
126
+
127
+ First, the epistemic-representational distinction is partially separable. The two-by-two matrix is a diagnostic heuristic, not a formal decomposition.
128
+
129
+ Second, the MR-causal connection in Proposition 19 holds exactly only for binary covariates. For continuous covariates, the link is directional, not formal.
130
+
131
+ Third, the noise-simplicity theorem predicts large Rashomon sets for noisy data but does not guarantee that the specific simple models psychologists want, meaning interpretable and clinically meaningful models, will be among them.
132
+
133
+ Fourth, TreeFARMS calibration is limited to sparse decision trees. It validates the approximation for one function class, not all.
lectures/rashomon.md ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # The Rashomon Effect
2
+
3
+ *The Rashomon Effect in Machine Learning*
4
+
5
+ ## The Core Idea
6
+
7
+ The term comes from Leo Breiman in 2001, who named it after Akira Kurosawa's 1950 film Rashomon, where four witnesses give contradictory but equally plausible accounts of the same event. The Rashomon Effect describes the phenomenon that there exist many equally good predictive models for the same dataset, and when it happens, it sparks both magic and consternation, but mostly magic.
8
+
9
+ The formal definition is straightforward. Given a loss function ell, a reference model f star (typically the best-performing one), and a threshold epsilon, the Rashomon set is all models f in your function class F whose loss is within epsilon of the best.
10
+
11
+ The Rashomon set R of epsilon and F equals all models f in F such that the loss of f is less than or equal to the loss of f star plus epsilon.
12
+
13
+ This sounds simple, but the implications are profound for the original question about underfitting and complexity gaps.
14
+
15
+ ## Why This Matters for the Linear Versus Boosting Question
16
+
17
+ When you fit a linear model and a boosted model and see a performance gap, the natural question is: is that gap real signal, or could a simpler model close it? The Rashomon perspective reframes this. Semenova, Rudin, and Parr hypothesize that there is an important reason simple yet accurate models often exist: the Rashomon set is often large, and if it's large, it contains numerous accurate models, and perhaps at least one of them is the simple model we desire. Their key result is that problems where the outcome is uncertain or noisy tend to admit large Rashomon sets and simpler models, which has significant policy implications as it undermines the main reason for using black box models for decisions that deeply affect people's lives.
18
+
19
+ So rather than asking how much extra variance does boosting capture, the Rashomon perspective asks how large is the set of near-optimal models, and does it contain something interpretable? If it does, the complexity gap might be an artifact of search, not a fundamental feature of the data.
20
+
21
+ ## The Key Tools That Have Been Developed
22
+
23
+ Model Class Reliance, or MCR, by Fisher, Rudin, and Dominici in 2019. This framework describes how much any model class, any model-fitting algorithm, or any individual model relies on covariates of interest. The key quantity is a range: MCR minus is the minimum reliance across all good models, MCR plus is the maximum. A feature with a large MCR minus is important in all well-performing models; a feature with a small MCR plus is unimportant to every well-performing model. This directly connects to the question: if the nonlinear interaction terms have low MCR minus, meaning some good models don't need them at all, then the extra variance your boosting model captures via interactions might not be essential.
24
+
25
+ TreeFARMS, by Xin, Zhong, Chen, and others in 2022. This provides the first technique for completely enumerating the Rashomon set for sparse decision trees, in fact the first complete enumeration of any Rashomon set for a non-trivial problem with a highly nonlinear discrete function class. Before this, people could talk about Rashomon sets theoretically but couldn't actually look inside them. TreeFARMS changed that, enabling three concrete applications: studying variable importance across all near-optimal trees, translating Rashomon sets across different metrics such as accuracy to F1, and examining stability under data subsetting.
26
+
27
+ The Rashomon Importance Distribution, or RID, by Donnelly, Katta, Rudin, and Browne, presented as a NeurIPS 2023 Spotlight. This addresses a critical flaw in existing variable importance methods. For a given dataset, there may be many models that explain the target outcome equally well; without accounting for all possible explanations, different researchers may arrive at many conflicting yet equally valid conclusions given the same data. The specific problem they identified is that even MCR is unstable across bootstrap iterations. For a given variable, one bootstrap might suggest it's completely unimportant while another suggests it's essential to all good models. RID fixes this by averaging the importance distribution across bootstrapped Rashomon sets, producing stable estimates. They demonstrated its utility with a case study exploring which genes are important for predicting HIV load, highlighting an important gene called LINC00486 that had not previously been studied in connection with HIV.
28
+
29
+ RashomonGB, presented at NeurIPS 2024. This paper systematically analyzes the Rashomon effect specifically for gradient boosting, providing rigorous theoretical derivations and an information-theoretic characterization of the Rashomon set for boosting algorithms. This is directly relevant to the setup, since you can now formally characterize how many equally good boosted models exist and how much their reliance on interactions varies.
30
+
31
+ ## The Amazing Things Perspective by Rudin and Colleagues at ICML 2024
32
+
33
+ The most comprehensive statement of the research program is the 2024 ICML paper by Rudin and colleagues. They address how the Rashomon Effect impacts: first, the existence of simple yet accurate models; second, flexibility to address user preferences such as fairness and monotonicity without losing performance; third, uncertainty in predictions, fairness, and explanations; fourth, reliable variable importance; fifth, algorithm choice; and sixth, public policy.
34
+
35
+ The theoretical backbone is an elegant covering argument: larger Rashomon sets tend to contain multiple simpler models because for every model in the more complex space, there exists a close model from the simpler space. Sparse decision trees serve as a cover for deeper, more complex decision trees, and trees are universal function approximators. So if your Rashomon set is large, which it tends to be for noisy real-world problems, a simple model almost certainly exists within it.
36
+
37
+ ## The Interactive Paradigm
38
+
39
+ What makes this practical rather than purely theoretical is the tooling. Instead of finding one optimal model, the algorithms find many good models and visualize them, so the user can interact with them to choose among them. This is the Rashomon set paradigm. Tools like TimberTrek let domain experts browse hundreds of millions of near-optimal decision trees, filtering by properties they care about such as fairness constraints, specific feature inclusions or exclusions, and monotonicity. Even if the Rashomon set contains hundreds of millions of models, when they are organized effectively, humans can navigate them in real time.
40
+
41
+ ## How This Connects Back to the Original Question
42
+
43
+ Here's the synthesis. The original question was about decomposing the variance gap between a linear model and a complex model. The Rashomon perspective adds a crucial dimension: is that gap stable? Specifically:
44
+
45
+ Step one. Fit your linear model and your boosted model. Observe the R squared gap.
46
+
47
+ Step two. Compute the Rashomon set for the boosted model class, meaning all boosted models within epsilon of optimal.
48
+
49
+ Step three. Within that Rashomon set, compute MCR for the interaction terms. If MCR minus for interactions is near zero, there exist near-optimal boosted models that barely use interactions, meaning the complexity premium is fragile.
50
+
51
+ Step four. Check whether the Rashomon set contains models from your simpler class, such as linear or GAM. If it does, the gap isn't structural, it's a search artifact.
52
+
53
+ Step five. Use RID to check whether these conclusions are stable across bootstrap resamples.
54
+
55
+ This gives you not just how much variation does complexity capture, but how robust is that finding, and could a simpler model do almost as well, which is arguably the more important applied question.
56
+
57
+ The key papers to read in order would be: Semenova and others 2022 on existence of simpler models, Fisher and others 2019 on MCR, Donnelly and others 2023 on RID, and Rudin and others 2024 Amazing Things as the synthesis piece.
58
+
59
+ ## Applied Workflow Example
60
+
61
+ Let's say your dataset is something like predicting depression severity using a PHQ-9 score from a battery of psychological, demographic, and behavioral predictors, including sleep quality, rumination, social support, age, income, childhood adversity, exercise frequency, and so on. Maybe 500 to 1,000 participants with 15 to 20 predictors. This is typical of clinical psychology research.
62
+
63
+ Step 1: Establish the Complexity Gap. Fit your linear regression, either OLS or regularized, and your gradient boosted model such as XGBoost or LightGBM. Use proper cross-validation. Suppose you get R squared linear equals 0.38 and R squared boost equals 0.46. That's an 8 percentage point gap. The traditional interpretation would be that nonlinearity and interactions account for 8 percent of additional variance in depression scores. But is that robust?
64
+
65
+ Step 2: Define the Rashomon Set. Choose a loss threshold epsilon. A common choice is a percentage of the best model's loss, say models within 5 percent of the best test loss. For your boosted model with MSE equals 12.4, you'd include all boosted models with MSE less than or equal to 13.02. Generate the Rashomon set by retraining with different hyperparameter configurations including learning rate, max depth, subsample ratio, number of trees, and regularization, as well as different random seeds. Collect every model that falls below the threshold. In practice, you might retrain 500 to 1,000 times and keep those that qualify. The RashomonGB framework from the NeurIPS 2024 paper provides a more principled way to characterize this set for boosting specifically.
66
+
67
+ Step 3: Characterize Structural Complexity Within the Rashomon Set. For each model in the Rashomon set, measure its effective complexity. For tree-based models, useful proxies include average tree depth, where shallow trees approximate main effects and deeper trees approximate higher-order interactions; the number of splits that involve more than one feature along a path, which serves as an interaction proxy; and SHAP interaction values aggregated to get the total variance attributable to interactions versus main effects. Plot the distribution: what fraction of near-optimal models are simple, meaning shallow with low interaction reliance, versus complex? If most near-optimal boosted models are shallow with minimal interaction terms, your 8 percent gap is likely inflated. Much of it can be recovered with nonlinear main effects alone using a GAM, not interactions.
68
+
69
+ Step 4: Compute Model Class Reliance for Specific Interaction Terms. Suppose the single best boosted model suggests a rumination times sleep quality interaction drives predictions. Compute model reliance using permutation importance for that interaction across every model in the Rashomon set. If MCR minus is near zero, meaning some near-optimal models don't rely on that interaction at all, you cannot confidently claim this interaction is a real structural feature of the data. It might be a quirk of one particular fit. Conversely, if MCR minus is high, every good model needs it, and you can be more confident it's genuine.
70
+
71
+ Step 5: Test Whether Simpler Model Classes Fall Within the Rashomon Set. This is the critical test. Fit a series of increasingly simple models and check whether any of them achieve loss below your Rashomon threshold of MSE less than or equal to 13.02. First, a GAM with nonlinear main effects and no interactions, which isolates whether the gap is about nonlinearity versus interactions. Second, a GAM with the top 2 to 3 detected interactions, which tests whether a small number of interactions closes the gap. Third, a linear model with polynomial terms for the most nonlinear features. Fourth, a plain linear model. If the GAM alone falls inside the Rashomon set, your conclusion changes dramatically: the complexity gap between linear and boosted models is primarily due to nonlinear main effects, not interactions. A GAM with interpretable shape functions is statistically indistinguishable from the best boosted model. If even the linear model falls inside, the gap was essentially noise. The boosted model was fitting to sampling variability, and a linear model is defensible.
72
+
73
+ Step 6: Stability Analysis via the Rashomon Importance Distribution. The Rashomon set from a single dataset can be unstable. Apply the RID framework: bootstrap your 800 participants, say 200 times, recompute the Rashomon set for each bootstrap, and compute the variable importance distribution for each predictor across all Rashomon sets across all bootstraps. This gives you a full probability distribution over importance values. For your interaction of interest, rumination times sleep, if the RID shows most of its mass near zero, the interaction is not a stable finding. If it shows a clear mode away from zero with tight spread, it's robust.
74
+
75
+ Step 7: Report and Interpret. Your results section in a psychology paper would now look fundamentally different from the standard approach of using XGBoost and SHAP. Instead, you could report something like: The best boosted model achieved R squared equals 0.46 compared to R squared equals 0.38 for the linear model. However, examination of the Rashomon set, containing 517 models within 5 percent of optimal loss, revealed that 73 percent of near-optimal models relied minimally on interaction terms, with interaction-attributed variance less than 1 percent. A GAM with nonlinear main effects achieved R squared equals 0.44, falling well within the Rashomon set. Model Class Reliance analysis showed that the rumination times sleep interaction had MCR minus equals 0.002, indicating it is dispensable in nearly all good models. The Rashomon Importance Distribution confirmed that the importance of this interaction was not stable across bootstrap resamples. We conclude that the apparent complexity gap is driven primarily by nonlinear dose-response relationships in individual predictors, particularly a threshold effect in sleep quality below 5 hours, not by interactions. A GAM is sufficient and preferred for interpretability.
76
+
77
+ Step 8: The Practical Payoff for Psychology. This matters enormously in clinical psychology for a few specific reasons. First, treatment targeting: if interactions are real, you'd tailor treatment differently for different subgroups, for example a sleep intervention specifically for high ruminators. If interactions are artifacts, subgroup-specific treatment protocols are unjustified. Second, replication: psychology's replication crisis is partly driven by unstable findings from single models on noisy data. The Rashomon approach explicitly quantifies this instability. Third, clinical deployment: a GAM can be turned into a clinician-facing scoring tool. A boosted model with 500 trees cannot.
78
+
79
+ ## What You'd Need Computationally
80
+
81
+ For tree-based Rashomon sets, the TreeFARMS algorithm handles sparse decision trees exactly. For boosted models, the practical approach is the retraining strategy, varying hyperparameters and seeds systematically. The InterpretML package from Microsoft gives you Explainable Boosting Machines that naturally decompose into main effects and interactions. The SHAP library provides interaction values. The Rashomon Importance Distribution GitHub repository from Donnelly and others implements RID directly.
82
+
83
+ The whole pipeline is feasible with standard computing resources for a dataset of the size typical in psychology. It adds maybe a day of computation and a week of analysis time, but the inferential gains are substantial. You go from boosting beats linear by 8 percent to a nuanced understanding of where that 8 percent comes from and whether it's real.
lectures/recurrent-depth.md ADDED
@@ -0,0 +1,235 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Thinking in the Dark
2
+ ### A technical lecture on recurrent-depth models
3
+ *Approx. 45–55 minutes spoken. Written to be listened to — the math is spoken aloud rather than rendered, so it should read cleanly through a text-to-speech engine.*
4
+
5
+ ---
6
+
7
+ ## Cold open
8
+
9
+ Welcome back. Today I want to talk about one of the stranger, and I think more underrated, ideas in modern deep learning: the idea that a neural network can *think* by running the same computation over and over, in the dark, inside its own latent space, before it ever emits a single word.
10
+
11
+ Here's the framing I want you to hold onto for the whole lecture. There are basically three ways you can spend more compute on a language model. The first is the one everyone knows: make the model *bigger*. More parameters, more data, more pretraining FLOPs. That's the Kaplan-style scaling story, and it's expensive and it's hitting diminishing returns. The second axis is newer and it's what the reasoning-model wave of the last couple of years has been about: spend more compute *at test time* by having the model write out a long chain of thought. It talks to itself on the page, token after token, and somewhere in that monologue the answer falls out.
12
+
13
+ Recurrent-depth models are a bet on a *third* axis. Instead of making the model wider, and instead of making it talk more, you make it *iterate*. You take a block of layers and you run it in a loop — five times, thirty times, a hundred times — refining a hidden state each pass, and only at the end do you decode that state into a token. The reasoning happens in a continuous vector space, not in words. It's silent. And the depth of that reasoning — the number of loops — is something you can crank up or down at test time, per token, without retraining anything.
14
+
15
+ That's the whole idea in one breath. The rest of this lecture is about *why* that works, *how* you actually train such a thing without it blowing up, the beautiful mathematics of differentiating through a fixed point, and the genuinely weird things that emerge when you scale it up — models that trace orbits in latent space to do arithmetic, that spend more "thinking time" on a morally ambiguous question than on a high-school algebra problem, entirely on their own.
16
+
17
+ Let's build it from the ground up.
18
+
19
+ ---
20
+
21
+ ## Part 1 — What depth buys you, and why you'd ever share weights
22
+
23
+ Start with the basic question: what is *depth* doing in a transformer? Each layer reads the residual stream, does a little attention, does a little feedforward computation, and writes something back. Stacking layers lets the model compose operations — early layers resolve tokens into concepts, middle layers do the heavy relational work, late layers shape things into a prediction. More depth means longer chains of composed computation, which means the model can express more complex functions and, loosely, run "more steps" of whatever algorithm it has implicitly learned.
24
+
25
+ Now here's the key observation that the whole field rests on. In a standard transformer, every one of those layers has *its own* parameters. Layer twelve and layer thirteen are different functions with different weights. But there's no law of nature that says they have to be. What if layers twelve through twenty were all *the same function*, applied repeatedly? You'd be tying the weights across depth. You'd have one block of parameters, and "depth" would just be how many times you chose to apply it.
26
+
27
+ The moment you do that, something important decouples. In an ordinary network, effective depth and parameter count are welded together — sixty layers means sixty layers' worth of weights. But with a weight-tied, looped block, those two quantities come apart. You can have a tiny number of *actual* parameters and an enormous *effective* depth, because the same parameters get reused on every pass.
28
+
29
+ The paper at the center of this lecture has a lovely way of talking about this. They distinguish the model's real parameters from its *materialized* parameters — the parameter count you'd need in a normal feedforward network to do the same amount of computation. Their big model has about three and a half real parameters, but when you run the recurrence thirty-two times, it chews through FLOPs comparable to what a thirty-two-billion-parameter dense transformer would burn, and at higher iteration counts it reaches compute loads equivalent to a fifty-billion-parameter model. Same weights. Far more thinking.
30
+
31
+ And notice the inversion this sets up against mixture-of-experts models, which we'll come back to at the end. A mixture-of-experts model is *parameter-heavy* but *compute-light* — it stores a huge number of weights and activates only a few per token. A recurrent-depth model is the mirror image: *compute-heavy* but *parameter-light*. It stores few weights and runs them many times. Those two designs are duals of each other, and that duality is going to matter for hardware.
32
+
33
+ So weight-tying in depth is the foundational move. Everything else is about making it actually train, actually converge, and actually get smarter when you give it more loops.
34
+
35
+
36
+
37
+ ## Part 2 — The ancestors
38
+
39
+ This idea is old. It's one of those ideas that gets rediscovered every decade — as recurrent neural networks, as diffusion models, as looped transformers. Let me walk through the direct ancestors, because each one contributes a piece of machinery we'll need.
40
+
41
+ **First: cross-layer parameter sharing.** The cleanest early example in the transformer world is ALBERT, which simply shared one layer's parameters across all the layers of a BERT-style encoder. The motivation there was mostly parameter efficiency — a smaller model that performs comparably. But the number of layers was fixed. It wasn't a knob you turned at test time; it was just a way to compress. Still, it's the proof of concept that weight-tying across depth doesn't destroy a transformer.
42
+
43
+ **Second, and more important: the Universal Transformer, with Adaptive Computation Time.** This is where the recurrence becomes genuinely dynamic. Take a single transformer block, share its weights, and apply it repeatedly — recurrent in depth. To each position, on each step, you add a timestep embedding alongside the usual positional embedding, so the block knows *which iteration* it's on and *where* it is in the sequence.
44
+
45
+ But the clever part is the halting mechanism, which comes from Alex Graves's Adaptive Computation Time. The idea: not every token needs the same amount of processing. So at each position, on each step, the model emits a little scalar halting probability through a sigmoid. You accumulate those probabilities across steps, and as soon as the running sum at a given position crosses one minus a small epsilon, you *stop* updating that position — you freeze its state. The leftover probability mass, the "remainder," is used to weight the final contribution so the whole thing stays differentiable. And you add a "ponder cost" to the loss, a penalty proportional to how many steps each position took, so the model is pressured not to think forever. The dream behind the Universal Transformer was explicit and ambitious: by recurring in depth with dynamic halting, you're reaching toward a *Turing-complete* machine, something that can in principle run arbitrary-length computations.
46
+
47
+ Hold onto two ideas from this: *per-position adaptive depth*, and *a halting criterion*. Both come back, in a much simpler form, at the end.
48
+
49
+ **Third: the "deep thinking" literature.** This is a line of work — Schwarzschild, Bansal, and collaborators — that asked a sharp question. If you train a recurrent network on *easy* instances of a problem, using a small number of iterations, can it solve *harder* instances at test time just by iterating *more*? Can it extrapolate along the compute axis? And the answer, with the right setup, is yes — and they figured out *what* the right setup is. Two ingredients turned out to be essential.
50
+
51
+ One: **input injection.** You don't just feed the input in at the start and let the recurrence run free. You re-inject the embedded input into the block on *every single iteration*. We'll see in a moment why that's not optional — it's what makes the iteration mathematically well-behaved.
52
+
53
+ Two: **randomized unrolling.** During training you don't use a fixed number of iterations. You sample the iteration count randomly for each example. This teaches the network to make progress at *any* depth, rather than memorizing a fixed-length computation, which is exactly what lets it extrapolate to more steps later.
54
+
55
+ And there's a third property that this community identified, which is going to be a recurring character: **path independence**, in the sense of Anil and collaborators. A path-independent recurrent model converges to the same answer *regardless of where it started* — regardless of the random initial state. Different starting points, same destination. That's a stability property, and it turns out you can encourage it precisely through random initialization plus input injection.
56
+
57
+ So the ancestors hand us four tools: weight-tying, dynamic per-position halting, input injection every step, and randomized unrolling for extrapolation. Now let's get to the mathematically deepest ancestor, because it's where the most beautiful trick lives.
58
+
59
+ ---
60
+
61
+ ## Part 3 — The fixed-point view, and the implicit-function-theorem magic
62
+
63
+ Here's a thought. If you're going to apply the same function over and over — call it *f*, taking the current hidden state and the input — what happens if you just... keep going? Forever? In many cases the state stops moving. It settles. You reach a *fixed point*: a state, call it *z-star*, where applying *f* to it gives you back *z-star* again. The function maps it to itself. Nothing changes.
64
+
65
+ Deep Equilibrium Models — this is Bai, Kolter, and Koltun — take that observation and run with it about as far as it can go. Their move is radical: don't pick a number of iterations at all. Instead, *define* the network's output to be the fixed point of *f*. The output is the solution to the equation "*z* equals *f* of *z* and *x*." An infinitely deep, weight-tied network, represented not by unrolling but by the equilibrium it converges to.
66
+
67
+ The forward pass, then, isn't "run thirty steps." It's "find the root." And you can use any black-box root-finding solver to do it — Broyden's method, Anderson acceleration, whatever converges fastest. You don't care how many solver steps it takes; you just want the equilibrium.
68
+
69
+ But now you hit the obvious problem, and this is the part I really want you to sit with, because the solution is gorgeous. *How do you backpropagate through this?* If the forward pass was a black-box solver that took some unknown number of iterations, you absolutely do not want to store every one of those iterations and backprop through all of them. That would cost memory proportional to the number of solver steps, which is exactly what we're trying to avoid.
70
+
71
+ The escape is the implicit function theorem. Watch.
72
+
73
+ At the fixed point, we have the identity: *z-star* equals *f* of *z-star* and *x*, where the model's weights are *theta*. This holds *at the solution*. Now, differentiate both sides with respect to *theta*, treating *z-star* as an implicit function of *theta* — because it is; move the weights, the equilibrium moves. By the chain rule, the change in *z-star* equals the partial of *f* with respect to its first argument — that's the Jacobian of *f* at the fixed point, call it *J* — times the change in *z-star*, plus the partial of *f* with respect to *theta* directly.
74
+
75
+ Rearrange. Bring the *J* term to the left. You get: the quantity "identity matrix minus *J*," times the derivative of *z-star* with respect to *theta*, equals the partial of *f* with respect to *theta*. So the derivative of the fixed point with respect to the weights is "identity minus *J*," *inverted*, times that partial.
76
+
77
+ And therefore the gradient of your loss with respect to the weights is: the gradient of the loss with respect to *z-star*, times "identity minus *J*" inverse, times the partial of *f* with respect to *theta*.
78
+
79
+ Stare at that for a second. The entire dependence on *how you got to the fixed point* has vanished. The solver's trajectory is gone. The gradient depends *only* on quantities evaluated *at the equilibrium itself* — the Jacobian there, and the partial derivatives there. You never unroll. Memory is constant — order one — in the number of solver iterations. That's the headline result of Deep Equilibrium Models: implicit differentiation gives you constant-memory backprop through an effectively infinite-depth network.
80
+
81
+ Now, the one piece that looks scary is that inverse Jacobian, "identity minus *J*" inverse. You're not going to form that matrix explicitly — it's enormous. But you don't have to. Look at the vector you actually need: the loss gradient times that inverse. Call it *u*. Then *u* satisfies its own equation: *u* equals the loss gradient with respect to *z-star*, plus *u* times *J*. And *that* is itself a fixed-point equation. You can solve it with the *same* kind of iteration you used on the forward pass, using only vector-Jacobian products — which automatic differentiation gives you cheaply, without ever materializing *J*. So you solve one fixed point going forward, and a second, linear fixed point coming back. Elegant, and entirely practical.
82
+
83
+ So why isn't every model just a DEQ? Because that inverse is exactly where the trouble lives. If the Jacobian *J* has eigenvalues near one, then "identity minus *J*" is nearly singular — ill-conditioned — and your backward solve becomes unstable and slow. The forward root-find can also fail to converge if *f* isn't contractive enough. People patch this with Jacobian regularization — literally adding a penalty on the norm of *J* to the training loss to keep the dynamics tame — and with careful solver choices. But it's *finicky*. Driving a big language model to a clean fixed point on every forward pass, stably, at scale, is hard. And that fragility is the opening that the modern approach walks through. Keep DEQ in mind as the *clean mathematical ideal* — the elegant limit — and remember that the scalable system we're about to build deliberately *doesn't* take that limit.
84
+
85
+ ---
86
+
87
+ ## Part 4 — How you actually get gradients through a loop
88
+
89
+ Before we assemble the modern model, let's lay out the menu of ways to differentiate through a recurrence, because the central design decision is *which one you pick*.
90
+
91
+ **Option one: full backpropagation through the unrolled computation.** Just treat the *r* iterations as a deep network and backprop through all of them. This is backpropagation through time, the classic RNN approach, repurposed for depth. It's exact. And it costs memory proportional to *r*, because you have to cache the activations of every iteration for the backward pass. If you want to iterate a hundred times, you pay for a hundred layers' worth of stored activations. For a big model with a heavy-tailed distribution of iteration counts, that's a non-starter — your peak memory is set by your worst-case longest unroll.
92
+
93
+ **Option two: gradient checkpointing.** Don't store every iteration's activations; store a few checkpoints and *recompute* the rest during the backward pass. This trades compute for memory — you do the forward work twice — but it lets you fit longer unrolls. It softens the memory problem without solving the fundamental scaling-with-*r* issue.
94
+
95
+ **Option three: the implicit gradient we just derived.** Constant memory, but it assumes you've actually reached a fixed point and inherits all the conditioning headaches. The clean ideal.
96
+
97
+ **Option four: truncated backpropagation.** Run the recurrence forward for the full *r* steps — that part is cheap, it's just inference — but only backpropagate through the *last k* of them, for some small fixed *k*. You throw away the gradient signal from the early iterations. This is biased — you're not computing the true gradient — but in practice the recent steps carry most of the useful signal, and crucially your backward memory and compute become *independent of r*. You can sample a wild, heavy-tailed number of forward iterations and your training cost per step doesn't budge.
98
+
99
+ That fourth option — truncated backprop through depth — is the pragmatic choice the modern model makes, and it's worth appreciating *why* it's the right call. DEQ solves what you might call the "direct" problem — it commits to the fixed point and pays for that commitment in stability. Diffusion models, another iterative paradigm, train against a surrogate objective. Truncated unrolling is a third path: don't force a fixed point, don't use a surrogate, just unroll a random amount and learn through the tail end. The bet — and it's an empirical bet that pays off — is that this is the *scalable* option, the one that survives contact with a real billion-parameter training run on a real supercomputer.
100
+
101
+ ---
102
+
103
+ ## Part 5 — The modern synthesis: latent recurrent depth at scale
104
+
105
+ Now we build the actual model. This is the Geiping and collaborators work from early 2025 — "Scaling up Test-Time Compute with Latent Reasoning: A Recurrent Depth Approach" — and the model they release is called Huginn, after one of Odin's ravens, the one whose name means "thought." I'll describe it piece by piece, and I'll flag *why* each choice is made, because almost every design decision is a scar from something that broke.
106
+
107
+ ### The macroscopic shape: prelude, core, coda
108
+
109
+ The model has three functional groups. First, the **prelude** — a couple of ordinary transformer layers whose job is to take the input tokens and embed them into the latent space. Call its output *e*, the embedded input. Second, the **core recurrent block** — this is the engine, the part that loops. Third, the **coda** — a couple of layers at the end that take the final latent state and un-embed it, projecting back out to vocabulary logits, the next-token prediction.
110
+
111
+ The forward pass goes like this, in words. Run the prelude on the input to get the embedding *e*. Initialize a latent state — call it *s-naught* — by drawing it from a Gaussian, random noise. Then loop: the *i*-th state is the core block applied to two things, the embedding *e* and the previous state. Do that *r* times. Take the final state, run it through the coda, and out come your token probabilities.
112
+
113
+ They summarize the architecture with a triplet of numbers — layers in the prelude, layers in the core, layers in the coda. The big model is two, four, two. Two prelude layers, four in the recurrent core, two in the coda. That's *eight real layers* of weights. But run the core thirty-two times and the effective depth is: two, plus four times thirty-two, plus two — a hundred and thirty-two layers. From eight layers' worth of parameters, you've materialized a hundred-and-thirty-two-layer computation, deeper than essentially any fixed-depth transformer anyone trains. The hidden dimension is five thousand two hundred and eighty, which works out to fifty-five attention heads of size ninety-six. About one and a half billion parameters live in the non-recurrent prelude and head, about one and a half billion in the recurrent core, and another half-billion in the tied input embeddings.
114
+
115
+ ### Why you inject the input every single step
116
+
117
+ This is the most conceptually important design choice, so let me give it real time. Why feed *e* into the core on *every* iteration, instead of just once at the start?
118
+
119
+ The paper's intuition is a gradient-descent analogy, and it's exactly right. Imagine the iterative process you'd most want the model to be able to imitate: gradient descent minimizing some function that depends on both a variable and the *data*. You start from a random point, and you repeatedly take a step — and that step is the gradient of the objective, which *depends on the data*. The data shows up in *every* update. It has to. If the data only entered at initialization and then you iterated a data-independent map, you couldn't be doing data-dependent optimization at all.
120
+
121
+ The same logic applies here. If you only set the initial state equal to *e* and then iterated a block that *didn't* see *e* again, the final answer would depend only on the boundary condition — the starting point — and the fixed map. The block couldn't represent something like gradient descent on a data-dependent objective, because, formally, it couldn't be the kind of monotone operator that such optimization requires. The recurrence wouldn't be stable in the relevant sense. So you re-inject *e* every step. Mechanically, the core starts with an adapter — a learned matrix that takes the *concatenation* of the current state and the embedding, both of dimension *h*, and maps that two-*h*-dimensional vector back down to *h*. At small scale you can get away with just *adding* the embedding back in; at scale, *concatenation* works better.
122
+
123
+ ### Why you start from random noise — path independence again
124
+
125
+ Why initialize *s-naught* as random Gaussian noise instead of something deterministic? Because random initialization, combined with input injection, is what drives the model toward *path independence* — convergence to a steady behavior that's independent of where you started. During training, the random start forces the model to learn dynamics that work from *anywhere*, not from one privileged initialization. And the payoff is verified empirically at the end: if you re-run the trained model from several different random starting states, it traces *similar trajectories* and lands in the same attractors. Same fixed points, same orbits, regardless of the seed. That robustness is not decorative — it's what makes "just iterate more at test time" a sane thing to do.
126
+
127
+ There's a nice aside in the paper here: isn't this basically a diffusion model? Random initial state, iterative refinement — it rhymes. They tried making it *more* diffusion-like, injecting fresh noise at every step, and also tried letting the block condition on the step index the way diffusion models condition on the timestep. Both *hurt*. The step-conditioning in particular broke path independence and wrecked the model's ability to extrapolate to more iterations than it saw in training — which makes sense, because if the block knows "I am on step seventeen of thirty-two," it can specialize to that schedule rather than learning a step-agnostic operator you can run as long as you like.
128
+
129
+ ### The norm placement and the initialization — the part that kept breaking
130
+
131
+ Here is where I want to be honest about how fragile this is at scale, because the paper is unusually candid about its failures, and the failures are instructive.
132
+
133
+ The layers inside each block use a specific normalization layout they call a "sandwich" — RMSNorm placed both before *and* after each sub-layer, attention and feedforward alike. Concretely, you normalize the input to attention, add the residual, normalize again; then normalize the input to the feedforward, add the residual, normalize again. At small scale, this barely matters — pre-norm, post-norm, sandwich, they all train fine. At scale, it's the difference between a working model and a dead one.
134
+
135
+ What goes wrong? **Representation collapse.** Their first big run used a more conventional setup, and it stalled almost immediately. When they looked at why, they found that the correlation between the hidden states of *different tokens* in the sequence shot up toward one. The model was predicting *the same hidden state for every token*. The sequence had homogenized into mush. And the recurrence was the culprit — every iteration of the block nudged the token representations closer together, and over many iterations they collapsed completely. The loop *amplifies* this pathology in a way a fixed-depth network never would.
136
+
137
+ They tried to fix it — added an embedding scale factor, switched to a learned adapter, went back to pre-norm — and the second run *looked* fixed at first. Token correlation spiked but then recovered. But it landed in a different trap: that model couldn't *use* test-time compute at all. Its validation perplexity was identical whether you ran the core once or thirty-two times. It had learned, early, to *ignore the incoming state* — to treat the recurrence as decorative. A local minimum where the loop does nothing.
138
+
139
+ Only the third configuration worked: back to the sandwich norm, plus a careful initialization, plus cutting the peak learning rate hard — roughly an order of magnitude, down to about four-times-ten-to-the-minus-five. On the initialization: they use a scheme that sets the weight variance to two-fifths over the hidden size, draws everything from a truncated normal, and critically sets the *output projection* layers to a much *smaller* variance — scaled by the number of *effective* layers, which is over a hundred. Small output projections mean each layer makes a gentle contribution, which keeps a very deep unrolled computation from exploding. With that combination, the third run started clean, never approached token collapse, and actually improved as you gave it more iterations. They trained it for seven hundred and fifty billion more tokens without a single loss spike.
140
+
141
+ The lesson I want you to take from this isn't the specific recipe — it's that recurrence is a *stability amplifier*. Any small pathology in the dynamics — a tendency to collapse, a tendency to ignore inputs — gets compounded across iterations. Designing one of these models is, to a large degree, the art of designing a *stable* iterated operator. The norm placement and the small output-projection initialization are both, at bottom, about keeping the per-step map well-behaved enough to apply a hundred times.
142
+
143
+ ### The training objective — sampling how long to think
144
+
145
+ Now, how do you train across a *range* of iteration counts so the model works at any depth? You make the loss an expectation. You minimize the *expected* next-token loss, where the expectation is over both your data and a *random iteration count r*, drawn fresh for each sequence from some distribution.
146
+
147
+ What distribution? They use a **log-normal Poisson**. The construction: pick a target mean number of iterations — for the big model it's thirty-two — then sample a log-normal variable, exponentiate it, and use that as the rate of a Poisson, plus one. With their variance setting, this gives a distribution that *most often* samples *fewer* than thirty-two iterations — the mode is around twenty-four, the median around twenty-nine — but has a long, heavy *tail* that occasionally demands many more. Why that shape? The bulk of cheap samples keeps average training cost down. The heavy tail occasionally exposes the model to deep unrolls, which is what teaches it to keep making progress far beyond the typical depth — that's the extrapolation property from the deep-thinking literature, baked directly into the sampling distribution.
148
+
149
+ And here's where truncated backprop earns its keep. They run the full sampled *r* iterations forward, but they only backpropagate through the **last eight**. *k* equals eight, fixed. Because backward memory and compute depend only on *k* and not on *r*, that heavy Poisson tail is *free* on the backward pass — a sample that happens to demand ninety forward iterations costs the same to train on as one that demands ten. One subtlety: even though gradients only flow through the last eight core iterations, the *prelude* still gets a gradient on *every* step, because its output *e* is injected into the core at every iteration and therefore participates in all of them. So the input embedding is trained against the full depth even while the core's backward pass stays cheap.
150
+
151
+ There's also a distributed-systems wrinkle that I love because it shows how the math meets the metal. If every worker in a data-parallel cluster sampled its *own* random *r*, then on each step all the fast workers would sit idle waiting for the unlucky one that drew a huge iteration count to finish its backward pass. So they use **locked-step sampling**: one *r* per micro-batch, synchronized across all workers, so everyone unrolls the same depth and nobody stalls. It's a small compromise on faithfully modeling the expectation, in exchange for not wasting thousands of GPUs.
152
+
153
+ ### The scale and the hardware, because it's the point
154
+
155
+ This was trained on Frontier, the Oak Ridge supercomputer, on AMD MI250X GPUs — and the hardware story is not incidental, it's *the whole pitch* for this architecture. Remember: recurrent-depth models do many FLOPs per parameter. The weights are small and reused. That means the model is small enough to train with *pure data parallelism* — no tensor parallelism, no model sharding across devices — because the weights fit comfortably and you're just doing a lot of compute on them. Pure data parallelism means *minimal communication between GPUs*. And on a cluster with slower interconnects, communication is exactly what kills you. So an architecture that is compute-heavy and parameter-light is *precisely* the architecture you want when your bottleneck is the network between accelerators rather than the accelerators themselves. They ran on up to four thousand and ninety-six GPUs, with global batches around sixteen million tokens, pushing on the order of a million tokens a second, and trained the final model on about eight hundred billion tokens — most of it scheduled in twelve-hour chunks across December of 2024.
156
+
157
+ This is the deeper argument for the third axis. It's not only "thinking in latent space is nice." It's that the resulting compute profile maps beautifully onto hardware where bandwidth, not raw FLOPs, is the constraint.
158
+
159
+ ---
160
+
161
+ ## Part 6 — The free lunch at inference
162
+
163
+ Here's the genuinely delightful part. Because the model was trained to operate at a *range* of depths, and because it's path-independent, a whole menu of capabilities that normally require dedicated engineering just... fall out. Zero-shot. No extra training. Let me go through them.
164
+
165
+ **Test-time compute scaling.** The headline. You give the model a hard problem, you let it iterate more, and it gets better. On reasoning benchmarks, accuracy climbs with iteration count — and the climb is *task-dependent*, which is the beautiful part. Easy tasks saturate fast: something like HellaSwag, a commonsense-completion task, basically maxes out by eight iterations. Harder tasks keep improving much longer — grade-school math word problems keep getting better as you add compute. And here's a really telling result: the more *in-context examples* you give it, the more iterations it *chooses* to use before saturating. With no examples, it plateaus around eight to twelve iterations; with one example, around twenty; with twenty-five or fifty examples in context, it keeps using compute out to thirty-two iterations. It's spending more thinking time to actually digest the additional context. The three-and-a-half-billion-parameter model, given enough iterations, reaches reasoning performance competitive with the compute of a fifty-billion-parameter dense model.
166
+
167
+ **Per-token adaptive compute, for free.** This is the Universal Transformer's dream, achieved without any of the machinery. Remember adaptive computation time — the halting units, the ponder cost, the accumulator? You don't need any of it. Here's their entire halting criterion: at each iteration, look at the output distribution the coda *would* produce. Compare it to the previous iteration's output distribution using KL divergence. When the KL between successive steps drops below a small threshold — they use five-times-ten-to-the-minus-four — the state has stopped meaningfully changing, so you stop, decode the token, and move on. That's it. No exit heads trained at every layer, no auxiliary losses. And when you measure how many steps different tokens take, the structure is striking: on high-school math questions the model exits quickly; on moral-scenario questions it takes several steps *more* on average before it's confident. The model is spending more silent deliberation on the harder, fuzzier questions, entirely on its own, even though it was only ever trained with a *single* fixed depth per whole sequence. Per-token variation was never in the training objective. It emerged.
168
+
169
+ Now, you'd think per-token early exit would break the KV cache — that's the standard objection. If token thirty exits after five iterations but token thirty-one wants to run twenty iterations, then when token thirty-one's attention reaches back to token thirty, the deep KV entries it wants simply *don't exist* — token thirty stopped early. The fix is clean: you just attend to the *deepest available* cached state for each previous token. And the reason this works is subtle and specific to the architecture — because every recurrent step uses the *same* key and value projection matrices, the cache entries from different depths are mutually compatible. They live in the same space. A token computed to depth five and a token computed to depth twenty produce keys and values that "match" well enough to attend across. The weight-tying that defines the architecture is exactly what makes the cache forgiving.
170
+
171
+ **KV-cache sharing, for free.** Same flavor of trick. Normally, sharing a KV cache across layers is something you have to train for from scratch. Here, because all recurrent steps share projections, you can just set a fixed cache budget — say sixteen slots — and have iteration *i* read and write slot *i* modulo sixteen. The seventeenth iteration overwrites the first iteration's entry, and so on. Cuts memory, barely touches quality.
172
+
173
+ **Self-speculative decoding, for free.** Speculative decoding normally needs a separate, smaller draft model to propose tokens that the big model then verifies. Here you don't need one. You *draft* with a few iterations — cheap, fast — and then *verify* with more iterations. The model is its own draft model, just run shallower. And the states you computed while drafting aren't wasted; they're the early iterations of the verification pass, so you reuse them. The single architecture gives you the draft-and-verify pair for nothing.
174
+
175
+ **Continuous chain-of-thought, for free.** And this one closes a loop with the reasoning-model world. Instead of re-initializing *s-naught* to fresh random noise for every new token, you can *warm-start* it with the *final* state from the *previous* token. Now the latent computation carries forward across tokens — the model's "thoughts" about token thirty inform its thinking about token thirty-one, building a computational graph deeper than any single token's iteration count. This is the same idea as the "continuous thought" line of work — Coconut and relatives — where you feed a model's last hidden state back in as the input for the next reasoning step. The interesting observation is what *distinguishes* the approaches: that other line *finetunes existing fixed-depth transformers* on chain-of-thought data to accept their own hidden states as input, effectively retrofitting a limited depth-recurrence onto a model that wasn't born with it. This work pretrains for recurrence from scratch. Same destination — reasoning in continuous latent space — approached from opposite directions: build it in, versus bolt it on. And the from-scratch version needs no chain-of-thought data at all.
176
+
177
+ ---
178
+
179
+ ## Part 7 — What's actually happening in there
180
+
181
+ So the model is silently iterating a hidden state and getting smarter. The obvious, slightly unnerving question is: *what is it doing* during all those loops? You can't read it. There's no transcript. But you can *watch the state move*. You track the trajectory of the latent state across iterations and look at its geometry. And what they find, when they project these high-dimensional trajectories down with PCA and plot them, is genuinely surprising, and it emerges *purely from scale and the plain truncated-unrolling objective* — there is nothing in the loss that asks for any of this.
182
+
183
+ Most tokens do the boring, expected thing: the state spirals in and *converges* to a fixed point. The model thinks for a bit and settles. Fine.
184
+
185
+ But some tokens **orbit**. The state falls into a closed, periodic loop and circles — it doesn't converge, it cycles. And this isn't noise; the orbits show up consistently on specific *kinds* of tokens. Tokens doing arithmetic. The paper has a lovely concrete example: a grade-school math problem that begins "Claire makes a three-egg omelette," and the token for "three" — the number being operated on — falls into a clean orbit across multiple PCA planes. The interpretation they offer is that these multidimensional orbits might serve the same role as the periodic, circular structures people have found inside fixed-depth transformers trained to do modular arithmetic — except here the periodicity isn't confined to arithmetic; it shows up on tokens like "makes" or "thinks" that *determine the structure of the answer*. The model appears to have discovered, on its own, that cyclic dynamics in a continuous space are a useful way to compute certain things.
186
+
187
+ And some tokens **slide**. The state doesn't converge and doesn't orbit — it *drifts*, steadily, in a single consistent direction across iterations. The speculation, and it's a good one, is that a slider could be a *counter* — a way for the model to keep track of how many iterations have elapsed, since the magnitude of the drift encodes the step number. Remember, the model was deliberately *denied* explicit step information to preserve path independence. A drifting latent direction would be how it reconstructs a sense of time for itself, when it needs one.
188
+
189
+ The big-picture contrast I want to draw is with Deep Equilibrium Models. A DEQ has the fixed point *written into its training objective* — it's optimized to converge. This model has *no such prior*. It's only ever trained with truncated unrolling. And yet fixed points emerge, *and* orbits emerge, *and* sliders emerge — a richer repertoire of dynamics than the DEQ objective would ever permit, because the DEQ insists on convergence and these orbits explicitly *don't* converge. Letting go of the fixed-point requirement didn't give you *less* structure. It gave you *more*. The model organizes its computation *spatially*, in the geometry of a high-dimensional space, in ways that have no clean analogue in the linear, one-word-after-another structure of verbalized chain-of-thought. That's the sense in which this might capture reasoning that "doesn't fit into words" — spatial intuition, the rotation of a shape, the kind of thinking that happens before language.
190
+
191
+ And path independence holds through all of it. Re-initialize from different random states and the *same* orbits, the *same* fixed points, the *same* drifts reappear. The dynamics are a property of the *learned operator and the input*, not of the accident of where you started.
192
+
193
+ ---
194
+
195
+ ## Part 8 — Tradeoffs, tensions, and the honest accounting
196
+
197
+ Let me not oversell this. Here's the balanced ledger.
198
+
199
+ **On the positive side.** No bespoke chain-of-thought data — you train on ordinary text and the reasoning ability comes from the architecture, not from curated reasoning demonstrations. Small context windows suffice, because the thinking happens in the hidden state rather than by filling the context with a long monologue, which also means much lower memory at inference than a model generating thousands of reasoning tokens. The capacity to capture non-verbal reasoning. A compute profile — many FLOPs per parameter — that's ideal for bandwidth-limited clusters. And that whole suite of inference capabilities that come for free.
200
+
201
+ **On the negative side, and these are real.** First, *training fragility* — we spent a whole section on it. The norm placement, the initialization, the learning rate, the input injection: get any of them wrong and you get representation collapse or a model that ignores its own recurrence. This is a less forgiving thing to train than a standard transformer.
202
+
203
+ Second, *convergence is not guaranteed and arguably not even the goal*. Truncated unrolling doesn't force a fixed point. Sometimes you get orbits, which are fine — even useful — but they complicate any clean story about "the model converging to an answer," and they make a naive convergence-based stopping rule trickier than it sounds.
204
+
205
+ Third — and to me this is the most important one — *interpretability*. A chain-of-thought model, whatever its flaws, leaves a trace you can *read*. You can audit the reasoning, catch a mistake, notice when it's rationalizing. A recurrent-depth model does its reasoning in an opaque latent space. There is no transcript. We can plot trajectories and label them "orbit" or "slider" after the fact, but we cannot read the model's thinking the way we can read a chain of thought. For a capability whose entire premise is *more reasoning we can't see*, that's a genuine and safety-relevant cost, and it deserves to be named plainly rather than buried.
206
+
207
+ Fourth, *latency*. The iterations are inherently *sequential* — iteration *i* needs the output of iteration *i*-minus-one. You can't parallelize across depth the way a transformer parallelizes across the token dimension during training. Deep thinking means a long serial dependency chain, and that has wall-clock consequences.
208
+
209
+ **The honest framing**, which the authors are careful about, is this: recurrent depth is *not a replacement* for the other two axes. It's a *third axis*. It composes with scaling parameters in pretraining, and it composes with scaling verbalized inference. The interesting future is probably *all three together*, not a winner.
210
+
211
+ ---
212
+
213
+ ## Part 9 — The frontier, and where this is heading
214
+
215
+ Let me end by pointing at the open horizon, because this is very much a live area.
216
+
217
+ There's a rich body of *theory* on looped and weight-tied transformers framing them as something like *programmable computers* — the looped structure, with the right setup, can express general computation, which is the formal backbone under the Universal Transformer's Turing-completeness dream. There's a growing *survey literature* on "latent reasoning" as its own category, placing recurrent depth alongside the continuous-thought finetuning methods and the latent-space approaches in the big labs' systems. The two cultures — pretrain-for-recurrence versus finetune-an-existing-model-into-recurrence — are converging on the same target from both ends.
218
+
219
+ On *post-training*, almost everything is open. Can you take one of these models and *compress* the recurrence — distill a thirty-two-iteration behavior into eight? Can you use reinforcement learning, feeding the model problems of graded difficulty so it learns to allocate the right amount of latent thinking to each? Can you *internalize* chain-of-thought data *into* the recurrence, so that reasoning that used to be verbalized becomes silent latent computation? Each of those is a paper waiting to happen.
220
+
221
+ On *architecture*, there's a natural marriage with efficient attention. Linear-attention variants are fast but limited in how many pairwise comparisons they can make in a single pass — but with recurrent depth, you can just *repeat* the block until all the necessary comparisons have been computed. The loop buys back the expressivity that the efficiency sacrificed. And there's the duality I promised at the very start: mixture-of-experts is parameter-heavy and compute-light; recurrent depth is compute-heavy and parameter-light. They are two ways of decoupling cost from capability, pulling in opposite directions, and the obvious question is what happens when you *combine* them — a model that is both broad in stored knowledge and deep in silent computation.
222
+
223
+ ---
224
+
225
+ ## Closing
226
+
227
+ So here's the whole arc, one more time, compressed.
228
+
229
+ Depth in a transformer is composed computation. Tie the weights across depth and effective depth comes unwelded from parameter count — you can be small in weights and enormous in computation. The Universal Transformer made that loop dynamic with per-position halting; the deep-thinking literature found that input injection every step and randomized unrolling let such a model extrapolate to harder problems by simply thinking longer; Deep Equilibrium Models showed the gorgeous mathematical limit, where you define the output as a fixed point and differentiate through it for free with the implicit function theorem, paying only in stability. The modern synthesis — Huginn — declines that fragile limit, chooses truncated backpropagation through the last few iterations, samples a heavy-tailed number of loops during training, and scales the whole thing to billions of parameters on a supercomputer where its compute-heavy, communication-light profile is a feature rather than a cost. And in exchange you get test-time compute scaling, per-token adaptive thinking, self-speculative decoding, and KV-cache tricks all for free — plus a model that, when you watch it think, traces orbits and drifts and fixed points in a latent space, organizing its reasoning *spatially* in a way no chain of thought ever could.
230
+
231
+ The bet underneath all of it is a simple and slightly profound one. We've spent a few years assuming that for a model to think harder, it has to think *out loud* — to spell its reasoning into tokens. Recurrent-depth models propose that thinking can instead be a *loop*: a quiet, iterated refinement in the dark, with depth as a dial you turn at the moment you need it.
232
+
233
+ Whether that becomes a pillar of how we build these systems, or a beautiful idea that keeps getting rediscovered every decade and never quite takes over — that's genuinely unsettled. Which is exactly what makes it worth understanding now.
234
+
235
+ That's the lecture. Thanks for listening.
lectures/throughput.md ADDED
@@ -0,0 +1,211 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Same Model, Twice as Fast
2
+
3
+ ### How to optimize an existing Transformer for throughput, without changing what it knows
4
+
5
+ *Approx. 20–25 minutes spoken. Narrated in the original Speechify voice, to match the earlier chapters. A companion to "The Model Is No Longer Just the Model": that lecture was about how models and serving systems are being designed together; this one assumes the model is already fixed and asks the narrower engineering question — how do we make exactly this thing run faster?*
6
+
7
+ ---
8
+
9
+ ## Cold open
10
+
11
+ Welcome back. Today's setup is simple. Somebody hands us a trained Transformer and tells us we are not allowed to change it. We cannot redesign its attention, we cannot retrain it, we cannot delete half its layers, we cannot turn it into a mixture of experts. The weights are the weights.
12
+
13
+ Our job is only this: make it execute faster.
14
+
15
+ That sounds like a narrow problem, and it is one of the richest problems in the field, because there are about six different levels at which we can attack it. At the very bottom we can optimize a single matrix multiplication. Above that, we can fuse operations together and move less data. Above that, we can rewrite attention and the key-value cache. Above that, we can change how requests get batched and scheduled. And above that, we can change how the model is spread across GPUs, and even put prefill and decoding on separate machines.
16
+
17
+ All of those levels interact, which means the first thing we need is not a kernel. It is a mental model of what we are actually optimizing.
18
+
19
+ ---
20
+
21
+ ## Part one — what "fast" even means
22
+
23
+ When someone says a model does one hundred tokens per second, that number is close to meaningless on its own, because there are three different things we might care about.
24
+
25
+ The first is time to first token. That is dominated by processing the user's prompt, which we call prefill.
26
+
27
+ The second is time per output token, which is dominated by the generation loop, which we call decode.
28
+
29
+ The third is total throughput — all the output tokens per second, summed across every user on the machine.
30
+
31
+ Here is the awkward part: these fight each other. If I have one request and I generate its next token immediately, latency is excellent and the GPU might be ten or twenty percent utilized. If I wait until sixty-four requests have arrived and process them together, GPU utilization and total throughput go way up, but every individual user waited longer.
32
+
33
+ This is why modern serving systems have mostly stopped chasing raw tokens per second and started optimizing what people call goodput — how much useful throughput you deliver while still meeting a latency target.
34
+
35
+ And the single most useful idea in this whole lecture is the one that falls out of this immediately: prefill and decode are not two phases of one workload. They are two different workloads that happen to share a set of weights. Systems like DistServe and Mooncake take that so seriously that they run them on separate machines.
36
+
37
+ ---
38
+
39
+ ## Part two — why decode is so much harder than it looks
40
+
41
+ Let us see why they are different, using the simplest possible layer: an output equals an input times a weight matrix.
42
+
43
+ During prefill, the input contains the whole prompt at once — maybe four thousand tokens. So we are multiplying a four-thousand-row matrix by a weight matrix. That is a big, fat matrix-matrix multiply. GPUs adore this. There is plenty of independent work, the weights get reused across thousands of rows, the Tensor Cores stay busy, and we get close to being limited by arithmetic — which is exactly where we want to be, because arithmetic is the thing the hardware is best at.
44
+
45
+ Now decode. Every active sequence contributes exactly one new token. With a single user, our input has one row. That beautiful matrix-matrix multiply has collapsed into something much closer to a matrix-vector multiply.
46
+
47
+ And notice what did not change: the entire weight matrix still has to participate. We still drag hundreds of megabytes, or gigabytes, of weights out of high-bandwidth memory — and then we do almost nothing with each number before moving on.
48
+
49
+ So decode is usually limited by memory traffic, not by arithmetic. That is the reason an H100 capable of an absurd number of operations per second can look embarrassingly idle while generating tokens for one user.
50
+
51
+ ---
52
+
53
+ ## Part three — arithmetic intensity, the one number to keep in your head
54
+
55
+ There is a single ratio that explains most of this. Arithmetic intensity asks: how much computation do I do for every byte I move?
56
+
57
+ Work through it roughly. The multiply-add count for our layer scales with the number of tokens times the two weight dimensions. The bytes we move, if weights dominate, scales with just the two weight dimensions. Divide one by the other, and both weight dimensions cancel.
58
+
59
+ What survives is the number of tokens.
60
+
61
+ That is a genuinely surprising result. The size of the weight matrix drops out. The thing that determines whether you are memory-bound or compute-bound is how many tokens you are pushing through at once.
62
+
63
+ One token in flight: intensity of about one, deeply memory-bound. One hundred and twenty-eight tokens in flight: every weight value gets reused a hundred and twenty-eight times, and intensity goes up by the same factor.
64
+
65
+ This is why batching is one of the most powerful optimizations ever applied to Transformers. We are not making the matrix multiply cleverer. We are changing the shape of the work into something the hardware likes.
66
+
67
+ And it is why quantization is so effective during low-batch decode. Take weights from sixteen bits down to four, and weight traffic drops roughly fourfold, so arithmetic intensity rises roughly fourfold. Quantization is not really "making the model smaller." It is moving the operation across the roofline, from bandwidth-limited toward compute-limited.
68
+
69
+ Every optimization decision in the rest of this lecture is really the question: which resource am I currently limited by, and am I attacking that one?
70
+
71
+ ---
72
+
73
+ ## Part four — inside the matrix multiply
74
+
75
+ Let us go one level down, into how a fast matrix multiply is actually built, because the same idea reappears at every level above it.
76
+
77
+ The naive version is three nested loops: for each row, for each column, walk the inner dimension and accumulate. Mathematically perfect, and a terrible way to feed a GPU — because the same values get fetched from main memory over and over.
78
+
79
+ So real kernels tile. A block of threads takes responsibility for, say, a one-hundred-and-twenty-eight by one-hundred-and-twenty-eight tile of the output. It does not do the whole inner dimension at once; it pulls in a narrow slice of each input, copies those slices from far-away global memory into fast on-chip shared memory, multiplies them, accumulates the partial result, then pulls the next slice.
80
+
81
+ So the flow is: main memory feeds shared-memory tiles, shared memory feeds per-warp tiles, those feed register fragments, and the fragments feed the Tensor Cores. The partial output sits in registers the entire time and only gets written back at the very end. That hierarchy is essentially what libraries like CUTLASS are built around.
82
+
83
+ And the reason it works is exactly arithmetic intensity again. One value fetched once and reused a hundred times instead of fetched a hundred times.
84
+
85
+ The obvious follow-up question is: why not use enormous tiles, and get enormous reuse? Because tiles cost resources. A bigger tile needs more shared memory and more registers for its accumulators. Push far enough and only one block fits on a processor at a time, occupancy collapses, and there is no longer enough independent work to hide stalls.
86
+
87
+ So tile size is a balance — enough area for reuse, not so much that you kill concurrency. That is why high-performance libraries ship dozens of kernels rather than one, and it matters enormously here: prefill produces huge token counts, decode produces tiny ones, and the same kernel is almost never right for both.
88
+
89
+ One more trick worth knowing, because it is the seed of everything in part seven. While the Tensor Cores chew on the current slice, we do not want the memory system sitting idle. So kernels use two buffers: one being consumed, one being filled. When compute finishes, they swap. That is double buffering, and instead of load, wait, compute, load, wait, compute, we get loading and computing happening on top of each other. On Hopper-class hardware, dedicated machinery for asynchronous copies and asynchronous Tensor Core operations lets this go further, with some warps acting purely as data movers and others purely as compute — a pattern called warp specialization.
90
+
91
+ ---
92
+
93
+ ## Part five — stop writing things down you are about to read back
94
+
95
+ A Transformer layer is not just matrix multiplies. There is normalization, the query-key-value projection, rotary embeddings, attention, the output projection, a residual add, another normalization, a gate projection, an up projection, an activation, a down projection, another residual.
96
+
97
+ A naive framework launches a separate GPU kernel for each of those. That costs us twice. Every launch has overhead, and — much worse — each kernel writes its output to main memory purely so the next kernel can immediately read it back.
98
+
99
+ Kernel fusion is the fix, and the mental rule is beautifully simple: every time you see an intermediate tensor, ask whether it actually needs to exist in memory. Very often it does not. A fused kernel does the matrix multiply and then, while the result is still sitting in registers, applies the bias, the activation, and the quantization before writing once. That trailing work is called the epilogue.
100
+
101
+ Transformers hand us obvious opportunities. Query, key and value all read the same input, so we can do one bigger projection instead of three separate ones. In the feed-forward block, the gate and up projections also read the same hidden state, so they merge too, and the activation and elementwise multiply fuse on afterwards. Normalization plus the residual update is another standard target.
102
+
103
+ And then there is the famous one.
104
+
105
+ ---
106
+
107
+ ## Part six — FlashAttention, and what it was really about
108
+
109
+ Standard attention multiplies queries by keys, takes a softmax, and multiplies by values. Conceptually there is an attention matrix whose size is sequence length by sequence length. At long context, that object is enormous, and traditional implementations wrote it to memory.
110
+
111
+ FlashAttention's insight was that this was never a compute problem. It was an input-output problem.
112
+
113
+ So instead of materializing that matrix, it tiles. A block of queries comes on chip. Blocks of keys and values stream past it. Running attention statistics accumulate, and an online softmax keeps the normalization correct as new blocks arrive. The answer is mathematically the same, and the giant intermediate never touches main memory at all.
114
+
115
+ What happened next is the most instructive part. FlashAttention-3 mapped that algorithm onto Hopper by leaning on asynchrony — overlapping Tensor Core work with data movement, splitting warps into producers and consumers, interleaving softmax with matrix multiplication — and reported roughly one-and-a-half to two times the speed of its predecessor.
116
+
117
+ Then FlashAttention-4 arrived on Blackwell and found something telling. Tensor Core arithmetic had gotten so much faster that the matrix multiplies were no longer the problem. The new bottlenecks were the exponential function inside softmax, and shared-memory traffic.
118
+
119
+ Watch the sequence there. First we optimized operations. Then main-memory traffic. Then shared memory. Then the special-function units that compute exponentials. Every time you kill a bottleneck, you promote the next one. That is not a failure of optimization. That is what optimization is.
120
+
121
+ ---
122
+
123
+ ## Part seven — the key-value cache is the real long-context story
124
+
125
+ Decode attention is its own beast. During prefill we have thousands of queries at once. During decode we have one query per sequence — but that one query has to attend over everything that came before it. Two thousand tokens. Thirty-two thousand. A hundred thousand.
126
+
127
+ So decode attention is another streaming problem: pull in the cache, compute the interactions, softmax, combine. And the amount of data grows with context length, which is why cache engineering matters so much.
128
+
129
+ The first big idea is PagedAttention. Suppose every user had to reserve a contiguous block of memory big enough for their longest possible sequence. We would waste an enormous amount, because sequences have wildly different lengths and finish at different times, and memory fragments.
130
+
131
+ PagedAttention treats cache memory the way an operating system treats virtual memory. A sequence's cache is chopped into fixed-size blocks, and those blocks do not need to be physically adjacent. A request logically owns blocks one, two, three, four, while physically those blocks are scattered across the pool. Near-zero waste, which means more sequences fit, which means bigger batches, which — back to part three — means higher arithmetic intensity. PagedAttention is not attention with fewer operations. It is memory virtualization that buys you batch size.
132
+
133
+ Block size is, once again, a tiling trade. Small blocks waste almost nothing when a sequence ends mid-block, but need more bookkeeping and give more scattered access. Large blocks are simpler and more local, but waste more at the tail. As always: tile size is a negotiation, never a direction.
134
+
135
+ The second idea is prefix caching, and it might be the highest-value item on this entire list for anything agentic. Imagine a thousand requests that share the same five-thousand-token system prompt. Why run prefill on those five thousand tokens a thousand times? Compute the cache once and reuse it. Automatic prefix caching does exactly this, and SGLang's RadixAttention generalizes it, storing reusable prefixes in a radix tree so overlapping — not just identical — prompts can share work. System prompts stay constant. Tool descriptions stay constant. Conversation histories overlap. The fastest token is the one you never compute.
136
+
137
+ The third idea is shrinking each cached element. Production stacks support eight-bit caches; research has pushed to two and three bits, with the nice finding from KIVI that keys and values want different treatment — keys quantized per channel, values per token.
138
+
139
+ But there is a systems lesson here that generalizes far beyond caches, so let me state it loudly: compression does not automatically mean acceleration. If I save four bytes and then burn a long sequence of instructions unpacking, rescaling and rearranging them, my theoretically superior format can be slower. The format and the kernel have to be designed together.
140
+
141
+ ---
142
+
143
+ ## Part eight — the same trap in weight quantization
144
+
145
+ That exact trap catches weight quantization too. Take sixteen-bit weights down to four bits and weight bandwidth drops fourfold. Wonderful. But the Tensor Cores cannot eat the packed representation directly. Something has to unpack the four-bit values, apply zero points, multiply by scales, convert formats, and rearrange the data before the arithmetic units see it. Do that clumsily and you hand back most of your gains.
146
+
147
+ This is why kernels like MARLIN matter — they treat low-bit inference as a kernel-scheduling problem rather than a numerical one, and hold onto close to the ideal bandwidth advantage across real batch sizes. So when you evaluate a quantization scheme for speed, the interesting question is not "how many bits." It is "what instructions actually execute between memory and the Tensor Core."
148
+
149
+ Which precision to pick follows straight from part three. At small batch, weight bandwidth dominates, so weight-only quantization is the win. As batch grows, weights get amortized across more tokens and arithmetic starts to dominate, so quantizing activations too begins to pay, because now you get genuinely lower-precision matrix multiplies. At long context, cache traffic can dominate everything, and you should be quantizing the cache instead.
150
+
151
+ There is no universally correct precision. Quantize whichever thing is currently responsible for the bytes or the operations that are limiting you.
152
+
153
+ ---
154
+
155
+ ## Part nine — scheduling is a hardware optimization in disguise
156
+
157
+ Back to that token count. One user gives us one row. Sixty-four users decoding at once give us sixty-four rows, and one fetch of a weight tile now serves all sixty-four. That is why throughput climbs so steeply with batch size, right up until some other resource saturates.
158
+
159
+ But naive batching wastes that. Take thirty-two requests: some finish after twenty tokens, some run five hundred. If we hold the whole batch until the slowest one finishes, we are burning capacity. So modern servers use continuous batching, sometimes called in-flight batching. At every single decode step, finished requests leave, waiting requests join, and the batch is rebuilt.
160
+
161
+ Chunked prefill is the companion trick. If one user submits a hundred-thousand-token prompt and we prefill it in one giant operation, every decode already in flight stalls, and their per-token latency explodes. So we cap how many prompt tokens are admitted per iteration and interleave prefill work with decode work. Larger budgets mean healthier matrix shapes and better throughput; too large and time-to-first-token suffers.
162
+
163
+ Notice what scheduling has become. By choosing how many tokens enter each iteration, we are directly choosing the shape of every matrix multiply in the model. Scheduling is a kernel optimization.
164
+
165
+ Then there is pure overhead, which becomes more embarrassing the faster your kernels get. Decode launches many tiny kernels thousands of times over, and the CPU has to submit each one. CUDA Graphs fix this by capturing a whole chunk of GPU work and replaying it as one unit. When NVIDIA did this for llama.cpp, they got up to about a one-point-two times improvement — biggest on small models, where launch overhead is the largest fraction of the runtime.
166
+
167
+ Think about what that means. No layers removed. No arithmetic reduced. They deleted the *nothing* in between the kernels, and it got faster.
168
+
169
+ The same logic explains why serving runtimes obsess over the host side: sampling on the CPU, Python scheduling, metadata rebuilds, memory allocation. The faster the GPU gets, the more the CPU becomes the problem — which is also why "GPU utilization" is a misleading metric. The GPU can be busy doing bad work, or idle because nobody is feeding it.
170
+
171
+ ---
172
+
173
+ ## Part ten — speculative decoding, and scaling outward
174
+
175
+ Everything so far still assumes one expensive model pass yields exactly one token. Speculative decoding attacks that assumption directly. A cheap draft mechanism proposes several likely next tokens, the big model verifies all of them in a single wider pass, and the ones that survive are kept. We have converted the pathological one-row workload into something with actual width.
176
+
177
+ But it is not free. If the draft is bad, we pay to generate candidates, the target rejects them, and we end up slower. What matters is average accepted length weighed against draft and verification cost. Medusa reported over two times speedups with lightweight prediction heads, and EAGLE-3 reports higher peaks still — but recent systematic evaluations are blunt that production-scale gains are much smaller than the headline numbers, and the documentation of major serving frameworks describes speculation as a low-batch optimization. That makes sense: at high concurrency, batching is already consuming the spare compute that speculation was hoping to borrow.
178
+
179
+ Scaling across GPUs has the same character. Tensor parallelism splits each weight matrix across devices, giving us more compute and more memory, but inserting a collective communication into essentially every layer. For big prefill multiplies there is enough arithmetic to hide that cost. For single-user decode it hurts: tiny multiply, synchronize, tiny multiply, synchronize. Sometimes a quantized model that fits on one GPU beats the same model split across four.
180
+
181
+ Pipeline parallelism instead gives different layers to different GPUs, which cuts the frequency of collectives but turns the model into a pipeline that only stays full if you have enough concurrent work. It is a throughput strategy, not a latency one.
182
+
183
+ And for mixture-of-experts models, the difficulty changes shape entirely. Routing sends different token counts to each expert — seventeen here, three there, forty-nine somewhere else, zero for that one — so instead of one large multiply you have many small irregular ones. Grouped matrix multiplication kernels handle a whole set of experts in one coordinated launch. And once experts live on different GPUs, tokens have to travel, so libraries like DeepEP exist specifically to make dispatch and combine cheap and to keep communication from stealing the processors that should be computing. The goal is that while one expert computes, the next expert's tokens are already arriving and the previous expert's results are already leaving.
184
+
185
+ The frontier here is fusing that entire chain — dispatch, first expert projection, activation, second projection, combine — into one overlapped pipeline. Not "make the multiply faster," but "schedule the whole layer as dataflow."
186
+
187
+ ---
188
+
189
+ ## Part eleven — what to actually do on Monday morning
190
+
191
+ If someone hands you a model tomorrow, do not start by writing a CUDA kernel. Start by measuring, in roughly this order.
192
+
193
+ Establish the workload first. Benchmark prefill and decode separately, across realistic prompt lengths, output lengths and concurrency levels. One tokens-per-second number is not a measurement.
194
+
195
+ Then make the model fit efficiently — choose a precision suited to your hardware and your accuracy budget, without assuming smallest equals fastest. Use the best available attention implementation for your GPU generation. Turn on paged cache management and continuous batching, which routinely deliver far more than hand-tuning any single kernel. Tune the chunked-prefill token budget until the matrix shapes are healthy but latency is still acceptable. Strip launch and framework overhead with graphs and memory pools. Only then start inspecting individual matrix shapes and using separate kernels for prefill and decode. Optimize the cache path — prefix reuse and cache precision — if your contexts are long. Try speculation if your concurrency is low enough for it to help. And only after all of that, scale outward.
196
+
197
+ When you do profile, look at the timeline before you look at any single kernel. Measure achieved memory bandwidth. Measure Tensor Core utilization. Look for gaps between kernels, stray memory copies, host stalls, collective traffic, expert imbalance. If a feed-forward multiply is already near the hardware limit, rewriting it is a waste of your life. If attention is sixty percent of decode time at long context, no amount of matrix-multiply tuning will save you. Optimize by wall-clock contribution, not by intellectual appeal.
198
+
199
+ ---
200
+
201
+ ## The one idea underneath all of it
202
+
203
+ Let me collapse this whole lecture into a single sentence, because everything we discussed is the same sentence wearing different hats.
204
+
205
+ **Increase the useful work done per expensive movement or synchronization.**
206
+
207
+ That is it. A tiled matrix multiply fetches data once and reuses it many times. Batching fetches weights once and uses them for many tokens. FlashAttention loads a block of keys and values and consumes it on chip instead of writing an attention matrix. Fusion keeps intermediates next to the arithmetic. Quantization moves fewer bytes per useful operation. Prefix caching refuses to recompute a prompt it has already seen. Speculative decoding extracts several tokens from one expensive verification. Expert-parallel overlap hides the network behind the math. CUDA Graphs collapse thousands of launches into one submission. Memory pools reuse buffers instead of rebuilding them.
208
+
209
+ Every single one is an attack on wasted movement or wasted waiting.
210
+
211
+ And that is why an unchanged Transformer — same weights, same architecture, same everything it knows — can end up dramatically faster than it was when someone handed it to you. You never made the model smarter. You just stopped making the hardware wait.
lectures/transformers.md ADDED
@@ -0,0 +1,248 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Transformers & LLM Design Decisions
2
+
3
+ *A guided tour through the chain of decisions that make modern language models what they are.*
4
+
5
+ ---
6
+
7
+ ## Opening Framing
8
+
9
+ Let's talk about transformers, the architecture that powers every large language model you've probably used in the past few years. If you've chatted with a model, had it write code for you, summarize a document, or answer a question, there was a transformer doing the heavy lifting underneath. But I don't want to just define what a transformer is. What I want to do is walk you through the chain of design decisions that make one transformer different from another, because that chain is where all the interesting behavior actually comes from. Every stage, from how text becomes numbers, to how those numbers get mixed together, to how the final answer is chosen, is a tradeoff. Someone sat in a room and said "we could do it this way, which is faster but loses some information, or we could do it that way, which is slower but more expressive." And those tiny choices, stacked on top of each other, are why one model can write poetry and another can't, why one handles a hundred languages and another only English, why one fits on your laptop and another needs a data center.
10
+
11
+ So think of what follows as a guided tour through the decisions. We'll start at the very beginning, with a raw string of characters sitting in memory, and we'll follow it all the way through to a sampled word coming back out the other end. Along the way, I'll try to make clear not just what each piece does, but why engineers picked one option over another, and what the downstream consequences are.
12
+
13
+ ---
14
+
15
+ ## 1. Tokenization
16
+
17
+ Our first topic is tokenization. Tokenization is the process of taking raw text and breaking it into the units that the model actually sees. And the reason it has to happen is simple. A neural network doesn't understand letters or words in any direct sense. It understands numbers, specifically vectors of numbers. So before we can feed a sentence to the model, we have to chop it up into pieces, assign each piece an integer identifier, and then look up a vector for each integer. Tokenization is the chopping step, the step where we decide what counts as a unit.
18
+
19
+ The most obvious approach is to split on whitespace and treat every word as a token. This is called **word-level tokenization**. It's simple and it matches how humans think about language. But it has a brutal problem. Natural language has an essentially unlimited vocabulary. There are always new words, misspellings, technical jargon, proper nouns, and slang. If your vocabulary is fixed, every unknown word has to be replaced with a special "unknown" token, and the model loses all information about it. Word-level vocabularies also explode in size for morphologically rich languages, where "run," "running," "ran," and "runner" are all different tokens even though they share a root.
20
+
21
+ The opposite extreme is **character-level tokenization**, where every letter, digit, and punctuation mark is its own token. This has no vocabulary problem at all. You can represent anything. But now your sequences are extremely long, because "internationalization" becomes twenty tokens instead of one, and transformers have a cost that grows with sequence length. Characters also carry almost no meaning on their own. The letter "t" appears in "tomorrow" and "the" and "anticipate," and the model has to do a lot of work to assemble meaning from the ground up.
22
+
23
+ Because neither extreme works well, modern systems use **subword tokenization**. The idea is to have tokens that are often smaller than a word but bigger than a character. Common words like "the" or "and" get to be single tokens, while rare or compound words get broken into familiar pieces. The dominant algorithms for building these vocabularies are byte pair encoding (BPE), WordPiece, and SentencePiece. The details differ but they all share the same logic. Start with characters as your smallest units, and then greedily merge the most frequent adjacent pairs until you hit your target vocabulary size. What you end up with is a vocabulary where common words are whole and rare words are assembled from subword pieces.
24
+
25
+ Most modern models go one step further and operate on **bytes** rather than characters. Byte-level tokenization treats every possible byte value as a starting unit, which means the model can in principle ingest any text in any language, any emoji, any binary blob, without ever hitting an unknown token. This is the approach used in the GPT family and many open models.
26
+
27
+ Now, here's why tokenization decisions quietly shape what a model is good at. If your tokenizer was trained mostly on English, then Chinese text, Arabic text, or code will get broken into more pieces per meaningful unit, which makes those domains more expensive and harder for the model to learn from. The way numbers get tokenized famously affects arithmetic. If "123" is one token but "124" is three tokens because it happened to be rarer in training, the model has to learn to treat them as related through a much more indirect path. If code gets poorly tokenized, code performance suffers. So when people say a model is "better at code" or "better at French," part of the reason, maybe a surprising amount of the reason, is that the tokenizer was designed with those languages in mind.
28
+
29
+ ---
30
+
31
+ ## 2. Vocabulary Size
32
+
33
+ Now that we have tokens, let's talk about vocabulary size, because this is a distinct decision that follows from tokenization. Typical modern vocabularies range from around thirty thousand tokens on the small end to over two hundred thousand on the high end. You might think "just make it bigger, it's more expressive." And you'd be partly right. A larger vocabulary means each token carries more meaning, which means sequences are shorter, which means the model has to process fewer tokens per document.
34
+
35
+ But there's a cost. The embedding matrix, which maps every token to a vector, scales linearly with vocabulary size. So does the output layer, which has to produce a probability distribution over every possible next token. Doubling the vocabulary roughly doubles the size of those two components. For large models this can be a meaningful chunk of total parameters. It also affects training efficiency. Rare tokens see very little signal during training, so the embedding matrix is crowded with entries the model barely knows what to do with.
36
+
37
+ Vocabulary size also interacts with multilingual capability. If you want a model to handle a hundred languages well, you need enough vocabulary budget to cover character sets and common sequences in all of them. The move from thirty thousand to a hundred thousand or more in recent models is partly driven by wanting better performance on code and on non-English text, where the older tokenizers were wasting a lot of tokens on predictable patterns.
38
+
39
+ ---
40
+
41
+ ## 3. Embedding Dimensions
42
+
43
+ Building on that, let's move into embedding dimensions. Once a token has an integer identifier, the model looks it up in a table and retrieves a vector. That vector is the token's embedding, and its length, the number of numbers inside it, is called the **embedding dimension** or the **model width**. Typical sizes today range from a few hundred, in small models, to over ten thousand, in the largest.
44
+
45
+ An embedding is a learned vector that places each token in a high-dimensional space. During training, the model gradually shapes this space so that tokens with related meanings end up near each other, and so that the vector for a token can encode all the subtle things about it that the rest of the network will need. The word "bank" might have an embedding that lives somewhere between financial terms and geographical terms, letting context pick it apart later.
46
+
47
+ Now the tradeoff. A larger embedding dimension gives the model more room to represent nuance. There's a well-known pattern where doubling the width of a transformer gives you more benefit per parameter than making it twice as deep, up to a point. But width is expensive. The attention mechanism, which we'll get to, has costs that scale with width. The feed forward layers, which are usually four times as wide as the embedding, scale by that same factor. Every layer reads from and writes to the embedding dimension, so it sets the size of the central highway that runs through the whole model. Engineers call this the **residual stream**. Make it too narrow and the model can't represent enough. Make it too wide and the parameter count explodes and the model becomes slow and expensive to train and run.
48
+
49
+ The embedding dimension also tends to be tied to the attention head configuration, since the model typically splits that dimension across multiple heads. A model with dimension 1024 might have 16 heads of 64 each, or 8 heads of 128 each. These ratios all need to fit together cleanly.
50
+
51
+ There are also deeper geometric issues hiding inside “embedding dimension.” The nominal dimension, such as 768, 4096, or 16,384, is only the maximum space available; the model may use a much smaller effective or intrinsic dimension. One way to understand this is through anisotropy: if representations are spread evenly across many directions, the space is more isotropic; if most variation is concentrated along a few dominant directions, like a covariance matrix with a few large eigenvalues and many small ones, the space is anisotropic. Recent work on transformer geometry suggests that this structure changes across layers and training. Encoders often show relatively uniform anisotropy across depth, while decoders can show a bell-shaped pattern, with middle layers becoming especially anisotropic. In other words, decoder middle layers may rely heavily on a smaller number of learned principal directions, not raw embedding coordinates. Intrinsic dimension can also rise and fall during training: early on, representations may spread into a higher-dimensional space as the model fits distinctions in the data, while later they may compress into more compact, reusable concepts, echoing ideas from the Information Bottleneck literature (Shwartz-Ziv & Tishby) and critical learning periods (Achille et al.). This helps explain why d_model should be understood as capacity, not as a guarantee that all dimensions are equally useful. The same issue appears in attention heads. Because transformers usually split d_model across heads, adding more heads can make each head narrower and lower-rank. A head with dimension 64 only sees a limited projected subspace, while a wider or full-rank head can compare tokens using much more of the representational space. Recent theory argues that some tasks, such as nearest-neighbor-style lookup, are easy for one full-rank head but can require many narrow low-rank heads to approximate, suggesting that more heads are not automatically better (Amsel, Yehudai & Bruna, 2025).
52
+
53
+ Embedding size also matters at the vocabulary level: the input/output embedding table has shape V × d, where V is vocabulary size and d is model width. Scaling work suggests that larger models may benefit from larger vocabularies because bigger vocabularies let the model store common words, subwords, and phrases more directly instead of rebuilding them from many smaller tokens (Tao et al., 2024). But larger embeddings are not always better downstream. In noisy regression tasks, such as predicting stock returns from news, full 768-dimensional sentence embeddings can overfit irrelevant variation, while compressed embeddings, sometimes as small as 8 dimensions, can perform better by acting as regularization (Drinkall, Pierrehumbert & Zohren, 2025). This means that hand-built sentiment or emotion features may not win because they are uniquely meaningful; they may win partly because they are low-dimensional and therefore harder to overfit. Matryoshka Representation Learning offers one elegant solution: train embeddings so that the first 64 dimensions, first 128 dimensions, first 256 dimensions, and full vector are all useful (Kusupati et al., 2022). Then early dimensions carry broad semantic information, while later dimensions add finer distinctions, enabling fast low-dimensional retrieval followed by higher-dimensional reranking. Finally, input length can interact with embedding dimension. For very long texts, attention can behave like a smoothing or low-pass filter, causing different long-document embeddings to become too similar to each other and reducing effective dimensionality (Length-Induced Embedding Collapse, 2025). The overall lesson is that embedding dimension is not just “how many numbers a token gets.” It shapes the model’s representational highway, the rank available to attention heads, the size of vocabulary memory, the risk of compression or overfitting in downstream tasks, and the geometry of what the model can actually represent.
54
+
55
+ Most embeddings have many more dimensions than they actually use. A model might have 768 or 4096 dimensions available, but the useful information often lives in a much smaller hidden structure inside that space. Still, the full dimension matters because it gives the model enough room to learn before it compresses information into cleaner concepts. This is why smaller embeddings can work better for noisy tasks, while larger embeddings can help when the signal is strong. It also explains why attention-head size, vocabulary size, and retrieval design matter: the model needs enough space to represent the right patterns, but too much unused space can add noise. Many standard choices, like 64 dimensions per attention head or fixed vocabulary sizes, are more historical habits than final answers. Open questions remain about how much rank attention really needs, how to scale embedding tables, whether non-Euclidean spaces help, and whether we can train models wide and then compress them efficiently.
56
+
57
+ ---
58
+
59
+ ## 4. Positional Encoding
60
+
61
+ Let's move on to positional encoding, which is one of my favorite topics because a lot of recent progress in long-context models comes from improvements here. The reason positional encoding is necessary at all is that attention, the mechanism at the heart of a transformer, is **permutation invariant**. If you feed the same set of tokens in in a different order, attention by itself will give you the same answer. Which is obviously a problem, because "the dog chased the cat" means something different from "the cat chased the dog." So we have to inject position information somehow.
62
+
63
+ The original transformer paper used **sinusoidal position encodings**. The idea was to give each position in the sequence a fixed vector, made of sines and cosines at different frequencies, and add that vector to the token embedding at that position. It worked. It had the nice property that it could in principle generalize to sequences longer than anything seen in training, since the functions are defined everywhere. In practice, that generalization was weak.
64
+
65
+ A later approach was **learned absolute positions**. Instead of using a fixed formula, you give each position a trainable vector, just like token embeddings. This works well up to the context length you trained on, but it completely fails past that point, because there's no learned vector for position ten thousand if you only trained up to position two thousand.
66
+
67
+ **Relative position methods** moved in a different direction. Instead of encoding the absolute position of a token, they encoded the relative offset between pairs of tokens during attention. This tends to generalize better because the model cares about distances, not absolute locations.
68
+
69
+ Then came **ALiBi**, short for attention with linear biases. This is a remarkably simple idea. Don't add anything to the embeddings at all. Instead, when you compute attention scores, apply a linear penalty that decreases with the distance between tokens. Closer tokens get higher scores, all else equal, and the penalty grows linearly as you look further away. ALiBi has surprisingly strong length generalization.
70
+
71
+ But the dominant approach in modern models is **rotary position embeddings (RoPE)**. This is worth lingering on. RoPE encodes position not by adding a vector, but by rotating the query and key vectors by an angle that depends on their position. The rotation is done in pairs of dimensions, like rotating a point in two dimensional space. When you then take the dot product of a query and a key to compute attention, the result naturally depends on the relative rotation, which means on the relative distance. The math works out so that RoPE gives you relative position behavior without needing a separate step, and it composes cleanly with the attention operation.
72
+
73
+ RoPE became dominant for a few reasons. It's simple. It interacts well with attention. And crucially, it can be extended to longer contexts after training by rescaling the rotation frequencies, a technique often called **RoPE scaling** or **position interpolation**. This is how models trained on 4K token contexts can sometimes be stretched to handle 100K or more, with relatively light additional fine-tuning. The choice of positional encoding, which might have seemed like a detail, turned out to silently determine how far the context window could grow. Every time you hear about a model with a million token context, there's a good chance that clever position encoding work is what made it possible.
74
+
75
+ RoPE, or Rotary Position Embedding, is the main positional method used in many modern LLMs. Instead of adding a position vector, RoPE rotates the query and key vectors by an amount based on their positions. When the model compares two tokens, the absolute positions largely cancel out, so the attention score captures relative position. The old explanation was that RoPE works because attention naturally decays with distance, but newer mechanistic work argues this is not really what trained models are doing. Instead, high RoPE frequencies help build precise positional circuits, like heads that attend to the current or previous token, while low frequencies act more like stable semantic channels that preserve meaning across longer spans. This also explains why changing RoPE’s base wavelength can help with longer contexts: slower rotations keep those semantic channels stable for more tokens. Context-extension methods build on this. Position Interpolation squeezes long positions back into the range the model saw during training; NTK-aware scaling stretches low-frequency, long-range dimensions more while preserving high-frequency local detail; YaRN applies this more carefully frequency by frequency and adjusts attention sharpness; and LongRoPE searches for the best scaling pattern automatically. The shared goal is to make long positions look less out-of-distribution while preserving the model’s original short-context abilities. More recent alternatives go beyond token counting: NoPE uses no explicit positional encoding and relies partly on the causal mask, while CoPE learns to count contextually meaningful units like sentences or events. In vision and multimodal models, positional encoding becomes 2D or 3D because images and videos have spatial and temporal structure. The big takeaway is that positional encoding is not just a minor implementation detail; it controls how the model understands order, distance, locality, long-context behavior, and modality-specific geometry.
76
+
77
+ Position Interpolation:
78
+ squeeze long positions into the old range
79
+
80
+ NTK-aware:
81
+ stretch mostly the long-range frequencies, preserve local ones
82
+
83
+ YaRN:
84
+ frequency-aware stretching + attention correction
85
+
86
+ LongRoPE:
87
+ search for the best scaling pattern automatically
88
+
89
+
90
+ ---
91
+
92
+ ## 5. Attention Heads
93
+
94
+ Moving on to attention heads. Attention is the operation that lets tokens look at each other and decide how to update themselves based on context. **Multi-head attention** means doing this operation several times in parallel, with different learned projections each time, so that different heads can track different kinds of relationships. One head might learn to track syntax, attending to the verb from its subject. Another might track coreference, attending to the noun that a pronoun refers back to. Another might attend broadly to the topic of the paragraph.
95
+
96
+ There are two design decisions here. How many heads, and how wide should each head be. The total attention width is usually equal to the embedding dimension, so it's a partition. A model with dimension 1024 and 16 heads gives each head a dimension of 64. You could instead have 8 heads of 128, and the total is the same, but the behavior differs. More heads of smaller dimension give the model more parallel perspectives but each perspective has less internal capacity. Fewer heads of larger dimension let each head do richer computation but you have fewer independent viewpoints.
97
+
98
+ Modern architectures introduced a new twist called **grouped-query attention** and its extreme cousin **multi-query attention**. The intuition here is about inference speed. At inference time, the keys and values for every head have to be stored in memory and re-read every time the model generates a new token. This **key-value cache**, as it's called, is one of the biggest memory costs of running a large model. Grouped-query attention reduces this cost by having groups of query heads share the same key and value projections. Multi-query attention takes the extreme position that all query heads share a single set of keys and values. You lose a little bit of expressiveness, because the heads can no longer have fully independent views of the sequence, but you gain dramatic speedups and memory reductions at inference time. Most recent large models use some form of grouped-query attention as a sensible middle ground.
99
+
100
+ Attention heads are the parts of a transformer that decide which tokens should look at which other tokens. The original design split the model width evenly across heads, so a model with d_model = 512 and 8 heads gives each head 64 dimensions. This became standard, but it is not obviously optimal: adding more heads makes each head narrower and lower-rank, which can limit what attention patterns it can represent, especially for long sequences. At the same time, many trained heads turn out to be redundant. Studies show that large fractions of heads can be pruned with little quality loss, while a smaller set of specialized heads does the important work: positional heads track order, syntactic heads follow grammar, induction heads support in-context pattern completion, and retrieval heads help long-context models pull facts from earlier in the prompt.
101
+
102
+ The practical bottleneck is the KV cache: during generation, the model stores keys and values for all previous tokens, and this memory grows with sequence length, number of layers, heads, and head size. Long contexts make this expensive, so newer architectures try to reduce the cache. Multi-query attention shares one key/value set across all query heads, saving memory but sometimes hurting quality. Grouped-query attention is the common compromise: groups of query heads share key/value heads, giving large cache savings with smaller quality loss. Multi-head latent attention goes further by caching compressed latent key/value representations, though it is more complex. The overall lesson is that heads are not interchangeable: some are crucial and should be protected, while others can be shared, pruned, or compressed. Future attention design will likely be more head-aware rather than blindly following the old “many heads of size 64 or 128” convention.
103
+
104
+ ---
105
+
106
+ ## 6. Attention Mechanism Details
107
+
108
+ Now let's go deeper into the attention mechanism itself, because understanding what's happening inside attention is the key to understanding the whole transformer. At each position, the model produces three vectors. A **query**, a **key**, and a **value**. Think of it as a soft dictionary lookup. The query is what this position is looking for. The keys are the advertised labels of every other position. The values are what those positions actually contain. The model compares the query against every key, computes a score for each, turns those scores into weights that sum to one using the softmax function, and then takes a weighted sum of the values. That weighted sum is the new representation of the current position.
109
+
110
+ The specific form is called **scaled dot-product attention**. You take the dot product of the query and the key, divide by the square root of the key dimension, and apply softmax. The division by the square root of the key dimension is a small technical detail that matters. Without it, the dot products get large when the dimension is large, which pushes the softmax into saturation, where one term dominates and the gradients vanish. Dividing rescales the scores so the softmax stays in a usable range no matter how wide the model is.
111
+
112
+ Attention comes in two flavors depending on what the model is for. In a **decoder**, which is what all the chat models and text generators use, attention is **causal**, meaning each position can only attend to positions that came before it. You enforce this with a mask that zeros out the future. In an **encoder**, like the one used in BERT, attention is **bidirectional** — every position can see every other position. Encoders are great for understanding, decoders are necessary for generation, and some models use both.
113
+
114
+ There's been a lot of work on making attention more efficient, because the raw cost of attention grows with the **square of the sequence length**. If you double the context, you quadruple the attention cost. This is why long context was hard for so long. The biggest implementation breakthrough of recent years is **FlashAttention**, which doesn't change the math but restructures the computation so that it uses GPU memory much more efficiently. It keeps intermediate values in fast on-chip memory instead of writing them out and reading them back, and it achieves the same answer in a fraction of the time with a fraction of the memory. FlashAttention alone unlocked contexts that were previously impractical.
115
+
116
+ Then there are approximation methods that change the math itself. **Sliding window attention** has each token attend only to a fixed window of recent tokens, which makes cost linear in sequence length. **Sparse attention patterns** let tokens attend to a chosen subset of the sequence. **Linear attention** replaces the softmax with a kernel that can be computed in linear time. Each of these gives up some expressiveness, some information, in exchange for speed. Models that use them usually combine them with some form of global attention so that at least some tokens can still see the whole sequence. The design decision is always about which information you can afford to lose.
117
+
118
+ ---
119
+
120
+ ## 7. Feed Forward Layer
121
+
122
+ Now we transition to the feed forward layer, the other half of every transformer block. After attention mixes information across tokens, the feed forward network processes each token independently. It takes the token's vector, expands it to a larger dimension, applies a nonlinearity, and projects back down to the original dimension. The **expansion ratio** is almost always around four times, so a model with embedding dimension 4000 might expand to 16,000 in the middle of its feed forward layer.
123
+
124
+ The intuition, which is supported by a growing body of interpretability research, is that the feed forward layer is where a lot of the model's **factual knowledge** lives. Attention moves information around, deciding what's relevant. Feed forward layers do lookups and transformations on that information, using patterns baked into their weights. When you ask a model to recall a fact, there's a good chance a feed forward layer is doing most of the retrieval work.
125
+
126
+ The activation function choice in the middle of the feed forward layer has evolved. The original transformer used **ReLU**, the rectified linear unit, which passes positive numbers through and zeros out negatives. Then **GeLU**, a smoother variant, became popular because it trained a bit better. More recently, a family called **gated linear units** took over, and in particular a version called **SwiGLU**. SwiGLU splits the expansion into two parallel paths, applies a swish activation to one, and multiplies them together elementwise. The gating gives the network a learnable way to decide which features to pass through at each position. It costs a bit more compute because you're computing two projections instead of one, but the quality gain has been consistent, which is why virtually all modern open models now use SwiGLU or a close relative.
127
+
128
+ The expansion ratio itself is a design choice. Four times is the traditional default, but some models have experimented with larger or smaller ratios. And **mixture of experts (MoE)** is a major modern development in this space. Instead of having one feed forward network that every token passes through, you have many feed forward networks, called experts, and a small router that sends each token to only one or a few of them. You get the parameter count of a very large model, because all the experts exist, but the inference cost of a much smaller one, because each token only uses a couple of experts. The tradeoff is that training gets harder because of load balancing, routing decisions, and the need to keep all the experts useful. But mixture of experts is how several recent frontier models manage to be enormous and still serveable.
129
+
130
+ ---
131
+
132
+ ## 8. Normalization and Residual Connections
133
+
134
+ Let's talk about normalization and residual connections. These are less glamorous topics than attention, but they're what makes deep networks actually trainable. If you just stacked fifty attention and feed forward blocks on top of each other without any stabilization, gradients would explode or vanish before they could teach the early layers anything useful.
135
+
136
+ The **residual connection** is the main trick. At every block, instead of the block replacing the input with its output, the block's output is added back to the input. This means the network is learning a correction, not a wholesale transformation. It also means gradients can flow directly from the loss at the output all the way back to the input without having to pass through every nonlinearity on the way. The **residual stream**, the running sum of all these corrections, is the central highway of the transformer. Everything gets written into it and read from it.
137
+
138
+ Normalization is the other essential ingredient. **Layer normalization** rescales the vector at each position so that its values have a standard distribution. This keeps activations from drifting into bad regimes as the network gets deeper. There was a subtle but important shift, a few years ago, from applying normalization after each block, called **post-norm**, to applying it before, called **pre-norm**. Pre-norm makes training much more stable, especially in deep models, because the residual stream stays numerically well-behaved. Post-norm can give slightly better final quality if you can get it to train, but pre-norm is so much easier to scale that it won out.
139
+
140
+ The other development is the replacement of layer norm with **RMSNorm**, which drops the mean-centering step and only rescales by the root mean square. It's slightly cheaper and performs just as well or better. Most modern models use RMSNorm rather than full layer norm. Again, a small change, but the kind of small change that adds up when you multiply it across dozens of layers and billions of tokens of training.
141
+
142
+ ---
143
+
144
+ ## 9. Training Objectives
145
+
146
+ Now let's move into training objectives, which is where we go from "here is a network" to "here is a useful model." Modern large language models are trained in two big stages. First, **pretraining** on a huge amount of text, where the model learns general language and knowledge. Then **post-training**, where the model is shaped into something actually useful and safe to interact with.
147
+
148
+ The core pretraining objective for almost every generative model is **next-token prediction**. You take a sequence of tokens, feed them in, and ask the model to predict the next token at every position. The loss is the average negative log probability of the true next token. That's it. You do this on a vast amount of text, and the model ends up learning grammar, facts, reasoning patterns, coding conventions, all of it, as a byproduct of trying to guess what comes next.
149
+
150
+ There are alternatives. BERT-style models use **masked language modeling**, where random tokens are replaced with a mask and the model is asked to fill them in. This is bidirectional, so it reads the whole context, but it can't generate text naturally. T5 and some other models use **span corruption**, where whole contiguous spans are masked and the model has to predict them. Each of these objectives shapes what the model is good at. Next-token prediction won for generative models because it's simple, it scales beautifully, and a model trained to predict the next token can just generate by repeatedly predicting and appending.
151
+
152
+ But a raw pretrained model is not what you want to talk to. It completes text, but it has no instinct for following instructions or being helpful. That's what post-training fixes. The first step is usually **supervised fine-tuning (SFT)** on a curated set of instructions and their ideal responses. This teaches the model the shape of helpfulness, the format of dialog, the habit of actually answering what was asked.
153
+
154
+ Then comes **reinforcement learning from human feedback (RLHF)**, where humans rate model outputs and the model learns to prefer the kinds of responses that got higher ratings. This is where a lot of the personality and safety behavior comes from. The model learns to be careful, to follow instructions, to not say certain things, to say other things politely.
155
+
156
+ A newer approach called **direct preference optimization (DPO)** simplifies the process. Instead of training a separate reward model and then optimizing against it, DPO directly optimizes the model to prefer chosen responses over rejected ones. It's mathematically equivalent to the reward learning approach under some assumptions, and it's much simpler to implement, so it's become very popular.
157
+
158
+ There are also **constitutional methods**, pioneered by Anthropic, where the model is guided by written principles and in some cases trained to critique and revise its own responses according to those principles. This reduces the need for continuous human feedback at every step and gives more explicit control over what behaviors are encouraged.
159
+
160
+ Each of these stages reshapes the model. Pretraining gives it capability, supervised fine-tuning gives it the format of helpfulness, and preference optimization gives it the judgment to choose the right kind of response. A raw pretrained model and its fully post-trained descendant can behave so differently that you'd hardly recognize them as the same network.
161
+
162
+ ---
163
+
164
+ ## 10. Decoding
165
+
166
+ Our next topic is decoding, which is how a trained model actually produces text at inference time. The model outputs a probability distribution over the vocabulary at every step. Decoding is the strategy for turning that distribution into a concrete sequence of tokens.
167
+
168
+ The simplest strategy is **greedy decoding**. At each step, pick the token with the highest probability. This is fast and deterministic, but it tends to produce repetitive and bland text, because the locally best token isn't always the right one for the bigger picture.
169
+
170
+ **Beam search** improves on greedy by keeping several candidate sequences alive at once and expanding the best few. Beam search is useful for tasks with a narrow correct answer, like translation or code completion, but it's rarely used for open-ended generation. The reason is that beam search tends to find the most likely sequence, and the most likely sequence in a real language model is often something short, generic, and boring. For creative or open-ended output, you don't want the most likely continuation. You want a good continuation.
171
+
172
+ So for chat and creative generation, we use **sampling**. Sampling means you actually draw from the distribution rather than taking the argmax. The parameters are knobs on how that sampling works.
173
+
174
+ **Temperature** is the first knob. It's a single number that rescales the model's logits before the softmax. At temperature 1, you sample from the true distribution. At lower temperatures, the distribution gets sharper, concentrating probability on the top options, which makes output more predictable and focused. At higher temperatures, the distribution flattens, which makes output more random and varied. Temperature 0 is equivalent to greedy decoding.
175
+
176
+ **Top-k sampling** truncates the distribution to the k most likely tokens and samples from among those. This prevents the very long tail of rare tokens from occasionally producing something bizarre.
177
+
178
+ **Top-p sampling**, also called **nucleus sampling**, does something subtler. Instead of a fixed number of tokens, it keeps the smallest set of tokens whose probabilities together sum to at least p, say 90 percent, and samples from that set. This adapts to the sharpness of the distribution. When the model is very confident, maybe only two tokens reach 90 percent. When the model is uncertain, twenty tokens might be needed. Nucleus sampling generally produces more natural text than top-k because it respects the shape of the distribution.
179
+
180
+ **Min-p** is a newer variant that sets a minimum probability threshold relative to the top token. Any token below that threshold is excluded. This is a simpler knob that often behaves well with less tuning.
181
+
182
+ The choice of sampling parameters silently shapes everything about the output. A low temperature with top-p at 90 gives you focused, coherent, slightly dull text. A high temperature with top-p at 95 gives you creative, varied, occasionally incoherent text. For code you usually want low temperature. For poetry you usually want high. The same model can feel like two different products depending on how you decode from it.
183
+
184
+ **Speculative decoding** is a recent technique for speeding up inference. It uses a small, fast draft model to propose several tokens at a time, and then the big model verifies them in parallel. If the big model agrees, you got several tokens for the cost of one forward pass. If it disagrees, you fall back to one. On average, speculative decoding can double or triple throughput without changing what the big model would have produced.
185
+
186
+ ---
187
+
188
+ ## 11. Meta-Level Insights
189
+
190
+ Let's step back for a meta-level reflection, because it's worth pausing to see how all these decisions compound. A tokenization decision affects vocabulary size, which affects the embedding matrix and output layer, which affects parameter count and memory footprint. The embedding dimension sets the width of the residual stream, which sets the cost of every single layer. Attention head configuration affects parallelism and interpretability. Positional encoding determines context length, which determines what tasks are even possible. Normalization and residual choices determine whether you can train a hundred-layer model at all. Training objectives determine what the model fundamentally knows how to do, and post-training determines how it actually behaves.
191
+
192
+ All of these interact. A model that wants long context needs good position encoding, efficient attention, and likely grouped-query attention to keep the key-value cache manageable. A model that wants to be great at code needs a tokenizer that handles code well, enough vocabulary budget, and training data that's code-rich. A model that wants to be cheap to run needs to think carefully about width, depth, attention costs, and whether mixture of experts is worth the training complexity.
193
+
194
+ There's a set of empirical relationships called **scaling laws** that describe how compute, data, and parameters trade off. Roughly, if you want the best model for a fixed compute budget, you should scale parameters and data together, in a known ratio, rather than making a very large model trained on too little data or a small model trained on far more data than it can absorb. The Chinchilla paper from a few years ago made this point forcefully and reshaped how people train frontier models. These scaling laws are not iron laws, but they're a good starting map.
195
+
196
+ And then there's the question of **emergent capabilities**. At some scales, some tasks suddenly become possible where they were impossible before. Chain of thought reasoning, in-context learning from examples in the prompt, certain kinds of tool use, all seem to appear or improve sharply at certain scales. Whether these are true phase transitions or artifacts of how we measure them is debated in the research community. But the qualitative experience, talking to a small model versus a large one, is dramatic, and a lot of what makes modern large models feel different from their predecessors is that something emerged along the way.
197
+
198
+ The point of this meta-level view is that modern large language models are not the result of any one clever idea. They are the result of thousands of small decisions, most of which seemed minor at the time, that together shaped what the model can do. When you notice that a model is weirdly bad at some specific thing, or weirdly good at another, there's almost always a decision somewhere in the chain that explains it.
199
+
200
+ ---
201
+
202
+ ## 12. Fine-Tuning
203
+
204
+ Moving on to fine-tuning. Fine-tuning is taking a pretrained model and adapting it to a specific task, style, or domain. The question is how to do this without wrecking what the model already knows.
205
+
206
+ **Full fine-tuning** means you continue training all the weights, with a lower learning rate and usually a smaller dataset. This works but has big downsides. It's expensive, because you're training a model with billions of parameters. It's memory-hungry, because you need optimizer state for every parameter. And it risks **catastrophic forgetting**, where the model gets good at the new task but loses the general capability it started with.
207
+
208
+ The big development in recent years is **parameter-efficient fine-tuning**. The idea is to leave the base weights frozen and add a small number of new, trainable parameters that can steer the model's behavior. **LoRA**, short for low-rank adaptation, is the dominant technique. The insight is that most useful fine-tuning changes to a model lie in a low-dimensional subspace. You can capture those changes by adding, to each weight matrix you want to adapt, a product of two small matrices, one that projects down to a low rank and one that projects back up. These two small matrices have far fewer parameters than the full weight matrix. You only train these small matrices. At inference, you either add their product into the original weights or keep them separate.
209
+
210
+ LoRA is cheap. Training LoRA adapters on a big model might require one percent or less of the memory of full fine-tuning. You can train dozens of adapters for different tasks and swap them in and out. You can share them. You can merge them. The whole ecosystem of custom fine-tuned models that people can run on their own hardware is built on LoRA and its variants like **QLoRA**, which combines LoRA with quantization to make it even cheaper.
211
+
212
+ But when should you fine-tune at all? Fine-tuning is good at teaching a model a new **format**, a new **style**, or a narrow task it needs to do reliably. If you need it to always output JSON in a specific schema, or always answer in a particular tone, or always classify into your specific categories, fine-tuning shines.
213
+
214
+ Fine-tuning is bad at teaching **new facts**. A pretrained model's factual knowledge is distributed across millions of parameter updates during pretraining. Trying to add facts by fine-tuning on a small dataset tends to make the model confidently wrong, because it learns the surface pattern of your training examples without really integrating the knowledge. Fine-tuning is also bad at keeping knowledge current, because every time the facts change you'd have to retrain.
215
+
216
+ So the rough rule is: **fine-tune for behavior, not for knowledge**. For knowledge, you want retrieval.
217
+
218
+ ---
219
+
220
+ ## 13. RAG Pipelines
221
+
222
+ Which brings us to our final major topic, **retrieval-augmented generation (RAG)**. RAG is the complement to fine-tuning. Where fine-tuning changes the model, retrieval injects fresh knowledge at query time, without changing the model at all. When a user asks a question, you first look up relevant documents in a knowledge store, paste them into the prompt along with the question, and let the model answer with those documents as context. It's the architecture behind almost every production system that answers questions about specific corporate data, recent events, or custom documentation.
223
+
224
+ A RAG pipeline has several stages, and the design decisions at each stage quietly determine whether the whole thing works. First comes **ingestion**. You take your source documents, whatever they are, and you process them into a form that can be retrieved. This usually means breaking them into chunks. **Chunk size** and **chunk overlap** are the first big decisions. Chunks that are too small lose context. Chunks that are too large dilute relevance and waste the model's context window. Typical chunk sizes range from a few hundred to a couple thousand tokens, with some overlap between consecutive chunks so that relevant information doesn't get split across a boundary.
225
+
226
+ For each chunk, you compute an **embedding** using an embedding model. These are specialized transformer models whose job is to map a chunk of text into a fixed-length vector where semantic similarity corresponds to vector distance. The choice of embedding model matters more than people often realize. A general-purpose embedding model might fail to distinguish between subtle technical concepts that a domain-specific model would separate cleanly.
227
+
228
+ The embeddings go into a **vector database**, which lets you look up nearest neighbors quickly. At query time, you embed the query with the same embedding model and ask the database for the k nearest chunks. This is called **dense retrieval**.
229
+
230
+ Dense retrieval is powerful but it isn't always enough. **Sparse retrieval**, the classic keyword-based methods like BM25, is better at matching exact terms, proper nouns, and identifiers. **Hybrid retrieval** combines both, running dense and sparse in parallel and fusing the results. Hybrid tends to outperform either alone because it catches both semantic matches and literal keyword matches.
231
+
232
+ After retrieval, many pipelines add a **reranking** step. The initial retrieval is fast but rough. A reranker, which is usually a smaller language model fine-tuned for relevance, looks more carefully at each retrieved chunk in the context of the query and rescores them. Reranking is expensive per item but much more accurate, so the typical pattern is to retrieve a hundred candidates with fast dense retrieval and then rerank the top twenty with a slower, more careful model.
233
+
234
+ Finally, the top chunks are assembled into the context and presented to the model. How you present them matters. The order can affect which ones the model actually pays attention to. The amount of context around each chunk affects whether the model has enough information to use it. And if you stuff too many chunks in, you run into the **context stuffing** problem, where the model's attention gets diluted and quality drops.
235
+
236
+ There are several common failure modes. **Irrelevant retrievals**, when the retrieval returned something that matched on a superficial word but doesn't actually help. **Context stuffing**, when so much potentially relevant material is included that the model can't tell what's important. And the **needle-in-a-haystack** problem, where a critical piece of information is buried deep in a long context and the model misses it. This last one has driven a lot of evaluation work. A model's ability to actually use information in long contexts is not the same as its ability to accept long contexts, and many models degrade significantly as the context grows, even when they technically support it.
237
+
238
+ So the punchline on RAG is that it's often better than fine-tuning for knowledge tasks, but it has its own stack of decisions that silently determine quality. Chunk size, embedding model, retrieval method, number of results, reranking, and context assembly. Get those right and RAG feels like the model really knows your data. Get them wrong and it feels like a search engine glued to a chatbot.
239
+
240
+ ---
241
+
242
+ ## 14. Closing
243
+
244
+ Let's close by tying the whole chain together. We started with a raw string of characters sitting in memory. That string got tokenized, broken into pieces shaped by someone's choice of algorithm and vocabulary. Each token became an integer, then got looked up in an embedding table and became a vector of a certain width. Position information got injected, probably by some form of rotary embedding, so the model could tell order from disorder. Those vectors then flowed through dozens of transformer blocks, each one alternating attention, which let them look at each other, with a feed forward network, which processed them independently. At every block, normalization kept things stable, and residual connections kept gradients flowing. At the top, the final vectors got projected back out into vocabulary-sized logits. A temperature was applied, a top-p cutoff, and a token was sampled. That token was appended to the sequence, and the whole loop ran again, one token at a time, until the model produced a stopping signal.
245
+
246
+ And behind all of that, a training pipeline had shaped every weight in the network. Pretraining on a vast corpus taught it language and knowledge. Supervised fine-tuning gave it the shape of an assistant. Preference optimization refined its judgment. Maybe LoRA adapters were loaded for a specific task. Maybe a retrieval system was pulling in documents to ground it in your data. Every stage of that pipeline was full of decisions, each with tradeoffs, each with consequences.
247
+
248
+ The thing I hope you take away from all of this is not any specific technical detail. It's the sense that the model you're using is not a black box pulled out of the ether. It is the accumulated result of thousands of choices, and each one of those choices was someone balancing capability against cost, generality against specialization, simplicity against expressiveness. Once you can see those decisions, you can reason about why a model behaves the way it does, when it will succeed, and when it will fail. And you can start to see how the next model, the one that's about to be released, will probably improve, and where the boundary between what's possible and what isn't still lies.