ScarletNX / From Derivatives to Attention
From Derivatives to Attention
Mathematics for programmers, from undergraduate calculus to a 2026 paper on attention.
Preface
This book is for programmers who know machines well and theory less. If you can schedule a Pentium Pro's micro-ops by hand but freeze when asked to balance an AVL tree on paper, it is for you. It starts at derivatives and ends at [refinekv], a paper that speeds up language-model inference by bounding the error of a cheap attention, and it covers each idea that paper uses on the way.
How it is written:
- Intuition first, few proofs. Each result comes with why it holds, usually a picture or a short derivation. A full proof appears only where the paper leans on it.
- Math first, code as illustration. Each idea is stated in mathematical language: what it is, what it is for, when it applies, what it costs. You already read code; what code does not show is why it is shaped as it is. So a program appears only where running it shows something, and is then taken apart in the language of the math: which symbol each part computes and why it is there. Early chapters have little code; the later ones, on floating point, softmax and attention, more. The programs are C99 (
cc -std=c99 -O2 file.c -lm), and the output under each is what it printed.
- Exercises with answers end each chapter. The answers are folded: try first.
- References end each chapter, naming the sections to read in fuller books. All of them are in References.
The formulas are TeX, typeset by MathJax. Without JavaScript you see the TeX itself, which reads as it is: \(\frac{a}{b}\) is a fraction, \(x^2\) a power, \(\sum_{i=1}^{n}\) a sum over \(i = 1\) to \(n\).
Contents
- Part I. Calculus of one variable
- 1. Numbers, functions and limits: reals and floats; functions as programs; limits; continuity; sequences; big-O and little-o.
- 2. Derivatives: the slope of a curve; the rules; the chain rule; the linear approximation; finite differences and their error; Newton's method; maxima and minima; the mean value theorem.
- 3. Integrals: area as a sum; the definite integral; the fundamental theorem; antiderivatives and substitution; integration by parts; improper integrals; numerical integration.
- 4. Exponential, logarithm and the hyperbolic functions: growth that is its own rate; the exponential; the logarithm; inequalities of exp; cosh, sinh and tanh; their identities and bounds; computing exp.
- 5. Sequences, series and Taylor polynomials: convergence; geometric series; power series; Taylor polynomials; the remainder; how a libm approximates.
- 6. Ordinary differential equations: what an ODE is; separable equations; linear first-order equations; second-order linear equations; systems; Euler's method; Runge–Kutta; stability and step size.
- 7. Functions of several variables: partial derivatives; the gradient; the Jacobian; the chain rule and backpropagation; gradient descent; the gradient of log-sum-exp.
- Part II. Linear algebra
- 8. Vectors and the dot product: vectors as arrays; linear and convex combinations; the dot product; length and angle; projection; the mean of vectors.
- 9. Matrices: matrices as linear maps; matrix multiplication; its cost and blocking; transpose and inverse; diagonal matrices; orthogonal matrices and rotations.
- 10. Norms, distances and inequalities: norms; the triangle inequality; Cauchy–Schwarz; weighted Cauchy–Schwarz; Hölder; bounding a dot product over a box and an ellipsoid.
- Part III. Convexity, probability and statistics
- 11. Convexity and Jensen's inequality: convex sets and functions; chords and tangents; the second-derivative test; Jensen's inequality; log-sum-exp; bounding exp on an interval.
- 12. Probability on finite sets: distributions as arrays; expectation; variance; conditioning and mixtures; total variation distance; softmax as a distribution; random vectors and their dot products; densities and the normal distribution.
- 13. Statistics: describing and comparing measurements: mean, median and percentiles; spread; Pearson correlation; Spearman rank correlation; partial correlation; summarizing benchmarks.
- Part IV. Computing it
- Part V. Transformers
- 16. Attention: tokens and embeddings; attention as a soft lookup; queries, keys and values; why divide by \(\sqrt{d}\); the causal mask; heads, MQA and GQA; positions and RoPE; attention in C.
- 17. Decoding and the KV cache: generating one token at a time; prefill and decode; the KV cache and its size; why decoding is memory-bound; evicting entries; query-aware access.
- 18. Clustering and approximate attention: partitions; representatives; k-means; contiguous blocks; attention over representatives; how spread makes error.
- Part VI. The paper
- 19. RefineKV's error bound, step by step: the setup; splitting the error; the mass correction; the cosh lemma; the tanh lemma; value distortion; the risk score; computable bounds for \(\delta_C\).
- 20. RefineKV in practice: the algorithm; grouped queries; the kernel; reading the experiments; limits; a toy RefineKV in C.
- References
Notation
| Written | Read | In C |
| \(x \in S\) | \(x\) is a member of the set \(S\) | |
| \(\mathbb{R}\), \(\mathbb{R}^d\) | the real numbers; arrays of \(d\) reals | double, double x[d] |
| \(f : A \to B\) | \(f\) takes an \(A\), gives a \(B\) | B f(A) |
| \(\sum_{i=1}^{n} a_i\) | the sum of \(a_1, \dots, a_n\) | for (i = 1; i <= n; i++) s += a[i]; |
| \(\prod_{i=1}^{n} a_i\) | the product of \(a_1, \dots, a_n\) | p *= a[i] |
| \(\max_{i \in C} a_i\) | the largest \(a_i\) with \(i\) in \(C\) | |
| \(|x|\), \(\|v\|\) | absolute value; length (norm) of a vector | fabs(x) |
| \(q^\top k\) | the dot product of \(q\) and \(k\) | for (j...) s += q[j]*k[j]; |
| \(\bar{k}\), \(\hat{p}\) | a mean (bar); an estimate (hat) | |
| \(:=\) | is defined as | = |
| \(\approx\), \(\le\), \(\ge\) | approximately; at most; at least | |
| \(\Rightarrow\), \(\iff\) | implies; if and only if | |
Greek letters used: \(\alpha\) alpha, \(\beta\) beta, \(\gamma\) gamma, \(\delta, \Delta\) delta, \(\varepsilon\) epsilon, \(\theta\) theta, \(\lambda\) lambda, \(\mu\) mu, \(\pi\) pi, \(\rho\) rho, \(\sigma, \Sigma\) sigma, \(\tau\) tau, \(\phi\) phi.