noncomputable sectionattribute [local instance] Lean.Grind.Semiring.natCast Lean.Grind.Ring.intCastvariable {R : Type} [RealNumbers R]

Deep Learning Speedrun

When asked about the mathematics of LLMs, Terence Tao noted that "any undergraduate Math major would have all the prerequisites." It's a funny quote, like saying any Biologist has all the prerequisites to be a sprinter. Still, the idea of the prerequisites of Deep Learning is kind of interesting. What if you took seriously the idea that there was a minimal formal curriculum between Peano and LeCun that you had to follow (I'm picturing this being taught in a French university). For instance, I see no reason you need anything at all from Linear Algebra.

So what are the prerequisites for speedrunning Deep Learning? The answer is 1/2 of one freshman semester -- if you are already really smart. This estimate comes from taking the textbook from a really hard math class, Harvard Math 55, and removing all the parts that are not useful (who needs integrals). I'm not sure what to make of this. On the one hand, it's pretty nice that you can formally derive MNIST from first principles. On the other hand, it is about 3,000 lines of Lean, which seems like a lot of machinery just to get to "move towards the downwards direction". Would be quite curious if someone can do this much faster.

Caveat: This blog is AI slop. The math is aligned to "Baby Rudin" -- Principles of Mathematical Analysis with pointers to the relevant theorems. Hug your local mathematician, they are having a hard year.

Metric spaces, limits, series, and derivatives lead to exp and neural networks.

Basic Topology

Metric Spaces

Three points form a triangle inside an open Euclidean ball; smaller balls show neighborhoods.

The blue segment is the direct route; amber goes via a third point. Dashed circles mark open neighborhoods.

structure Metric (X : Type) where dist : X → X → R nonneg : ∀ x y, 0 ≤ dist x y zero_iff : ∀ x y, dist x y = 0 ↔ x = y symm : ∀ x y, dist x y = dist y x triangle : ∀ x y z, dist x z ≤ dist x y + dist y z

Open and Closed Sets

Left: an open disk with neighborhoods inside it. Right: a closed disk contains a boundary limit point, whose neighborhoods extend outside the disk. Dashed boundaries are excluded; solid boundaries are included.

Left: small neighborhoods stay inside the open disk. Right: the closed disk includes its boundary limit point, although its neighborhood extends outside.

abbrev PointSet (X : Type) := X → Prop-- Points less than r away from x; the boundary is excluded. def Neighborhood (M : Metric (R := R) X) (x : X) (r : R) : PointSet X := fun y => M.dist x y < r-- Every point has a small neighborhood entirely inside the set. def IsOpen (M : Metric (R := R) X) (E : PointSet X) : Prop := ∀ x, E x → ∃ r, 0 < r ∧ ∀ y, Neighborhood M x r y → E y-- Every neighborhood of p contains a different point of E. def LimitPoint (M : Metric (R := R) X) (E : PointSet X) (p : X) : Prop := ∀ r, 0<r → ∃ q, E q ∧ q≠p ∧ Neighborhood M p r q-- The set contains all of its limit points. def IsClosed (M : Metric (R := R) X) (E : PointSet X) : Prop := ∀ p, LimitPoint M E p → E p-- Rudin Theorem 2.19: every neighborhood is open. theorem neighborhood_open (M : Metric (R := R) X) (x : X) (r : R) : IsOpen M (Neighborhood M x r) := refine ⟨r - M.dist x y, , ?_⟩ -- Rudin Theorem 2.24(c), two-set case of finite intersections of open -- sets. theorem open_inter (M : Metric (R := R) X) (E F : PointSet X) (hE : IsOpen M E) (hF : IsOpen M F) : IsOpen M (fun x => E x ∧ F x) := refine ⟨smaller r s, , ?_⟩ exact ⟨hEr y ( ; ), hFs y ( ; )⟩-- Rudin Theorem 2.24(a): arbitrary unions of open sets are open. theorem open_union (M : Metric (R := R) X) (E : ι → PointSet X) (h : ∀ i, IsOpen M (E i)) : IsOpen M (fun x => ∃ i, E i x) :=

Closures

Closing a punctured open disk adds its boundary and its missing center point, highlighted in amber.

Closing the punctured disk fills its missing center and adds its outer boundary, shown in amber.

-- The points of E together with all of its limit points. def Closure (M : Metric (R := R) X) (E : PointSet X) : PointSet X := fun p => E p ∨ LimitPoint M E p-- Rudin Definition 2.26 and the proof of Theorem 2.27(a): neighborhood -- characterization of closure; extracted helper. theorem closure_neighborhood (M : Metric (R := R) X) (E : PointSet X) (p : X) : Closure M E p ↔ ∀ r, 0<r → ∃ q, E q ∧ M.dist p q<r := exact ⟨p,hp, ⟩ -- Rudin Theorem 2.27(c): every closed superset contains the closure. theorem closure_minimal (M : Metric (R := R) X) (E F : PointSet X) (hF : IsClosed M F) (hEF : ∀ p, E p → F p) : ∀ p, Closure M E p → F p := -- Consequence of Rudin Theorem 2.27(c): closure preserves inclusion; -- not a separately numbered theorem. theorem closure_mono (M : Metric (R := R) X) (E F : PointSet X) (hEF : ∀ p, E p → F p) : ∀ p, Closure M E p → Closure M F p := closure_minimal M E (Closure M F) (closure_closed M F) (fun p hp => Or.inl (hEF p hp))

Compact Sets

A closed disk covered by open balls. The right-hand picture retains a finite subcover and discards redundant balls.

The dashed balls cover the solid disk. Removing redundant balls leaves a finite subcover on the right. Compactness requires this for every open cover.

-- Every open cover has a finite subcover drawn from that same cover. def IsCompact (M : Metric (R := R) X) (K : PointSet X) : Prop := ∀ (I : Type) (U : I → PointSet X), (∀ i, IsOpen M (U i)) → (∀ x, K x → ∃ i, U i x) → ∃ selected : List I, ∀ x, K x → ∃ i, i ∈ selected ∧ U i x refine ⟨smaller r (rs i), ,?_⟩ ; ; cases i with -- Finite-index helper for the corollary to Rudin Theorem 2.36; no -- separate Rudin theorem. theorem list_le_max (ns : List Nat) : ∀ n, n∈ns → n≤ns.foldr max 0 := induction ns with ; ;

Nested Intervals

Compactness of an Interval

Planar illustration of Rudin's nested-cell argument: nested squares share a point and eventually fit inside an open ball around it.

Nested squares shrink around a common point until they fit inside its amber neighborhood. This is the planar analogue of nested intervals.

-- Finitely many of the given sets cover the whole closed interval. def FiniteSubcover (U : I → PointSet R) (a b : R) : Prop := ∃ selected : List I, ∀ x, a≤x → x≤b → ∃ i, i∈selected ∧ U i x -- Proof step in Rudin Theorem 2.40, real interval case: one half still -- has no finite subcover. theorem interval_bad_half (U : I → PointSet R) (a b : R) (hab : a≤b) (bad : ¬FiniteSubcover U a b) : ∃ q : R×R, a≤q.1 ∧ q.2≤b ∧ q.2-q.1=(b-a)/2 ∧ q.1≤q.2 ∧ ¬FiniteSubcover U q.1 q.2 := refine ⟨((a+b)/2,b), , , , ,?_⟩ exact ⟨(a,(a+b)/2), , , , ,hl⟩ exact ⟨n, ; ⟩; exact Scalar.mul_pos ih ( ) exact ⟨[],fun x hax hxb => False.elim (hab ( ))⟩ -- Consequence of Rudin Theorem 2.41, (a) implies (b), for k = 1; used -- explicitly in the proof of Theorem 3.11(c). theorem bounded_closure_compact (E : PointSet R) (a b : R) (bounded : ∀ p, E p → a≤p ∧ p≤b) : IsCompact realMetric (Closure realMetric E) := compact_closed_subset realMetric (fun x => a≤x ∧ x≤b) (Closure realMetric E) (interval_compact a b) (closure_closed realMetric E) (closure_minimal realMetric E _ (interval_closed a b) bounded)

Numerical Sequences and Series

Convergent Sequences

A sequence approaches a fixed limit inside successively smaller balls.

The sequence eventually stays inside each smaller ball around the dark limit point.

-- Eventually every term is as close as desired to the fixed limit x. def ConvergesTo (M : Metric (R := R) X) (s : Nat → X) (x : X) : Prop := ∀ ε : R, 0 < ε → ∃ N : Nat, ∀ n, N ≤ n → M.dist (s n) x < ε

The Arithmetic of Limits

-- Rudin Definition 3.1, constant-sequence example (e), generalized to -- any real constant. theorem seq_const (a : R) : ConvergesTo realMetric (fun _ => a) a := -- Rudin Theorem 1.33(a), real case: a nonzero number has positive -- absolute value. theorem abs_pos (a : R) (ha : a ≠ 0) : 0 < abs a :=

Cauchy Sequences

Two late terms lie in a ball around the limit; the triangle inequality bounds their distance.

Late terms cluster together. The amber distance between two terms is bounded by the two blue distances through the limit.

-- Any two sufficiently late terms are as close as desired. def IsCauchy (M : Metric (R := R) X) (s : Nat → X) : Prop := ∀ ε : R, 0 < ε → ∃ N : Nat, ∀ m n, N ≤ m → N ≤ n → M.dist (s m) (s n) < ε

Diameter

Nested disks and successively shorter diameter segments.

Nested closed disks shrink to one point; their diameters tend to zero.

-- The least upper bound of all distances between points of E. def IsDiameter (M : Metric (R := R) X) (E : PointSet X) (d : R) : Prop := (∀ p q, E p → E q → M.dist p q≤d) ∧ ∀ b, (∀ p q, E p → E q → M.dist p q≤b) → d≤b-- Rudin Definition 3.9 with the least-upper-bound property: existence -- of a finite diameter for a nonempty bounded set. theorem diameter_exists (M : Metric (R := R) X) (E : PointSet X) (nonempty : ∃ p, E p) (bounded : ∃ b, ∀ p q, E p → E q → M.dist p q≤b) : ∃ d, IsDiameter M E d := -- Rudin Theorem 3.10(a): taking the closure preserves diameter, -- expressed through the IsDiameter predicate. theorem diameter_closure (M : Metric (R := R) X) (E : PointSet X) (d : R) (hd : IsDiameter M E d) : IsDiameter M (Closure M E) d :=

Cauchy Sequences in a Compact Set

def Tail (s : Nat → X) (N : Nat) : PointSet X := fun p => ∃ n, N≤n ∧ s n=p

Completeness of the Real Line

-- Every Cauchy sequence has a limit in the space. def IsComplete (M : Metric (R := R) X) : Prop := ∀ s, IsCauchy M s → ∃ x, ConvergesTo M s x

Monotonic Sequences

def Increasing (s : Nat → R) : Prop := ∀ m n, m ≤ n → s m ≤ s n

Series

Shrinking terms add to partial sums that approach a finite limit.

The blocks are successive terms. Their cumulative lengths give the dots below, approaching the dashed limit.

def partialSum (a : Nat → R) : Nat → R | 0 => 0 | n + 1 => partialSum a n + a n-- Finite-sum identity underlying Rudin Theorem 3.47; this is not yet -- the infinite-series limit statement. theorem partialSum_scale (c : R) (a : Nat → R) (n : Nat) : partialSum (fun k => c * a k) n = c * partialSum a n := induction n with ; ; -- The partial sums are Cauchy: far-out finite blocks have small sums. def CauchySeries (a : Nat → R) : Prop := IsCauchy realMetric (partialSum a)-- Rudin Theorem 3.22: the Cauchy criterion for series, expressed as the -- Cauchy property of partial sums (Definition 3.21). theorem series_cauchy_iff_converges (a : Nat → R) : CauchySeries a ↔ ∃ l, ConvergesTo realMetric (partialSum a) l := -- Rudin Theorem 3.24, bounded-partial-sums implies convergence -- direction. theorem nonnegative_series_converges (a : Nat → R) (ha : ∀ n, 0≤a n) (bounded : ∃ B, ∀ n, partialSum a n≤B) : ∃ l, ConvergesTo realMetric (partialSum a) l := increasing_bounded_converges _ (partialSum_increasing a ha) bounded -- Consequence of Rudin Theorem 1.33(c), real case, by induction on the -- exponent. theorem abs_pow (x : R) (n : Nat) : abs (x^n)=(abs x)^n := induction n with ; ; -- Elementary ordered-arithmetic helper; no separate Rudin theorem is -- claimed. theorem pow_nonneg (x : R) (hx : 0≤x) (n : Nat) : 0≤x^n := induction n with ;

Series of Nonnegative Terms

Increasing partial sums stay below a fixed upper bound.

Nonnegative terms make the partial sums rise. Here they remain below the dashed upper bound and settle toward a limit.

-- Finite geometric-sum identity in the proof of Rudin Theorem 3.26, -- multiplied by 1 - q. theorem geometric_sum_mul (q : R) (n : Nat) : (1-q)*partialSum (fun k => q^k) n=1-q^n := induction n with ; -- Partial-sum estimate from Rudin Theorem 3.26; this lemma does not -- assert the infinite sum's value. theorem geometric_partial_bound (q : R) (hq : 0≤q) (hqlt : q<1) (n : Nat) : partialSum (fun k => q^k) n≤1/(1-q) := apply (Lean.Grind.Field.IsOrdered.mul_le_mul_iff_of_pos_right (show 0<1-q from )).mp

Factorial Coefficients

def factorial : Nat → Nat | 0 => 1 | n + 1 => (n + 1) * factorial ndef reciprocalFactorial : Nat → R | 0 => 1 | n + 1 => reciprocalFactorial n / (n + 1 : Nat)-- Representation helper for Rudin Definition 3.30: the recursively -- defined coefficient equals 1/n!. theorem reciprocalFactorial_eq (n : Nat) : (reciprocalFactorial n : R)=1/(factorial n : R) := induction n with ; -- Factorial identity used after Rudin Definition 3.30; extracted -- arithmetic helper. theorem reciprocalFactorial_step (n : Nat) : reciprocalFactorial (n + 1) * (n + 1 : Nat) = (reciprocalFactorial n : R) := exact Scalar.div_mul_cancel ( ; )

The Ratio Test

A row of disks whose radii shrink by a fixed factor.

A fixed ratio below one gives a geometric bound on the tail.

-- Finite-sum indexing helper for Rudin Theorem 3.34(a); no separate -- numbered theorem. theorem partialSum_shift (a : Nat → R) (N k : Nat) : partialSum a (N+k)=partialSum a N+partialSum (fun j => a (N+j)) k := induction k with ; ; -- Rudin Theorem 3.34(a), sufficient fixed-ratio form for nonnegative -- terms; the limsup formulation and divergence clause are not -- formalized here. theorem ratio_test (a : Nat → R) (ha : ∀ n, 0≤a n) (N : Nat) (q : R) (hq : 0≤q) (hqlt : q<1) (ratio : ∀ n, N≤n → a (n+1)≤q*a n) : ∃ l, ConvergesTo realMetric (partialSum a) l := nonnegative_series_converges a ha (series_bounded_of_ratio a ha N q hq hqlt ratio)-- Special case of the estimate for Rudin Theorem 3.34(a), with eventual -- ratio at most 1/2. theorem series_bounded_of_half (a : Nat → R) (ha : ∀ n, 0≤a n) (N : Nat) (half : ∀ n, N≤n → 2*a (n+1)≤a n) : ∃ B, ∀ n, partialSum a n≤B := apply series_bounded_of_ratio a ha N (1/2) ( ) ( )

Power Series

Exponential partial sums approaching the exponential curve.

Adding more terms brings the amber partial sums toward the blue exponential curve.

def expPartial (x : R) (n : Nat) : R := partialSum (fun k => x ^ k * reciprocalFactorial k) n

Absolute Convergence

Alternating signed terms above, and their absolute values below.

Taking absolute values removes cancellation. If the lower series converges, so does the upper one.

-- Rudin Theorem 3.45, real case: absolute convergence implies -- convergence. theorem absolute_convergence (a : Nat → R) (ha : ∃ l, ConvergesTo realMetric (partialSum (fun n => abs (a n))) l) : ∃ l, ConvergesTo realMetric (partialSum a) l := series_comparison a (fun n => abs (a n)) 0 (fun _ _ => Std.le_refl _) ha

Convergence of the Exponential Series

def expSeries (x : R) : R := Classical.choose (exp_series_exists x)-- Rudin Chapter 8, (25), p. 178: the exponential series defines E(x); -- Lean choice records its established limit. theorem expSeries_limit (x : R) : ConvergesTo realMetric (expPartial x) (expSeries x) := Classical.choose_spec (exp_series_exists x)-- Special case of the observation after Rudin Definition 3.5: a -- subsequence of a convergent sequence has the same limit. theorem seq_succ (s : Nat → R) (a : R) (hs : ConvergesTo realMetric s a) : ConvergesTo realMetric (fun n => s (n+1)) a := exact ⟨N,fun n hn => hN (n+1) ( )⟩ rwa [ at hi

Continuity

Limits of Functions

A punctured input neighborhood maps inside a prescribed ball around the output limit.

A small punctured input neighborhood maps inside the requested output ball. The hollow input point is excluded.

-- Near p, but excluding p, the outputs approach q. def HasLimit (M : Metric (R:=R) X) (N : Metric (R:=R) Y) (E : PointSet X) (f : X → Y) (p : X) (q : Y) : Prop := ∀ ε, 0<ε → ∃ δ, 0<δ ∧ ∀ x, E x → 0<M.dist x p → M.dist x p<δ → N.dist (f x) q<ε exact (spec K).2.2.2 (hK K ( )) -- Rudin, corollary to Theorem 4.2: uniqueness of a function limit at a -- limit point of its domain. theorem function_limit_unique (M : Metric (R:=R) X) (N : Metric (R:=R) Y) (E : PointSet X) (f : X → Y) (p : X) (q r : Y) (hp : LimitPoint M E p) (hq : HasLimit M N E f p q) (hr : HasLimit M N E f p r) : q=r :=

Arithmetic of Limits

-- Immediate consequence of Rudin Definition 4.1 for a constant -- function; no separate theorem. theorem hasLimit_const (M : Metric (R:=R) X) (E : PointSet X) (p : X) (a : R) : HasLimit M realMetric E (fun _ => a) p a := exact ⟨1, ,fun _ _ _ _ => ; ⟩-- Rudin Theorem 4.4(a), real case, expressed with the punctured -- HasLimit predicate. theorem hasLimit_add (M : Metric (R:=R) X) (E : PointSet X) (f g : X → R) (p : X) (a b : R) (hf : HasLimit M realMetric E f p a) (hg : HasLimit M realMetric E g p b) : HasLimit M realMetric E (fun x => f x+g x) p (a+b) := -- Rudin Theorem 4.4(b), real case, expressed with the punctured -- HasLimit predicate. theorem hasLimit_mul (M : Metric (R:=R) X) (E : PointSet X) (f g : X → R) (p : X) (a b : R) (hf : HasLimit M realMetric E f p a) (hg : HasLimit M realMetric E g p b) : HasLimit M realMetric E (fun x => f x*g x) p (a*b) := -- Rudin Theorem 4.4(c), real case with numerator 1; eventual -- nonvanishing suffices for Lean's total reciprocal. theorem hasLimit_inv (M : Metric (R:=R) X) (E : PointSet X) (f : X → R) (p : X) (a : R) (hf : HasLimit M realMetric E f p a) (ha : a≠0) : HasLimit M realMetric E (fun x => 1/f x) p (1/a) :=

Continuous Functions

Three neighborhoods illustrate the composition of two continuous functions.

Each map sends a small neighborhood into the next. Passing through both maps keeps the final outputs close together.

-- Inputs close to p have outputs close to f(p). def ContinuousAt (M : Metric (R:=R) X) (N : Metric (R:=R) Y) (E : PointSet X) (f : X → Y) (p : X) : Prop := ∀ ε, 0<ε → ∃ δ, 0<δ ∧ ∀ x, E x → M.dist x p<δ → N.dist (f x) (f p)<ε-- Forward direction of Rudin Theorem 4.6, expressed with the punctured -- HasLimit predicate. theorem continuous_to_limit (M : Metric (R:=R) X) (N : Metric (R:=R) Y) (E : PointSet X) (f : X → Y) (p : X) (hf : ContinuousAt M N E f p) : HasLimit M N E f p (f p) := -- Reverse direction of Rudin Theorem 4.6, expressed with the punctured -- HasLimit predicate. theorem continuous_of_limit (M : Metric (R:=R) X) (N : Metric (R:=R) Y) (E : PointSet X) (f : X → Y) (p : X) (hf : HasLimit M N E f p (f p)) : ContinuousAt M N E f p := ; -- Rudin Theorem 4.6: at a limit point, continuity is equivalent to the -- function limit equaling the value. theorem continuous_iff_limit (M : Metric (R:=R) X) (N : Metric (R:=R) Y) (E : PointSet X) (f : X → Y) (p : X) (_hp : LimitPoint M E p) : ContinuousAt M N E f p ↔ HasLimit M N E f p (f p) := ⟨continuous_to_limit M N E f p,continuous_of_limit M N E f p⟩-- Rudin Theorem 4.7: composition of continuous functions, with the -- outer function continuous on the inner function's image. theorem continuous_comp (M : Metric (R:=R) X) (N : Metric (R:=R) Y) (P : Metric (R:=R) Z) (E : PointSet X) (f : X → Y) (g : Y → Z) (p : X) (hf : ContinuousAt M N E f p) (hg : ContinuousAt N P (fun y => ∃ x, E x ∧ f x=y) g (f p)) : ContinuousAt M P E (fun x => g (f x)) p := rwa [-- Rudin Theorem 4.9, sum clause, in pointwise real form. theorem continuous_add (M : Metric (R:=R) X) (E : PointSet X) (f g : X → R) (p : X) (hf : ContinuousAt M realMetric E f p) (hg : ContinuousAt M realMetric E g p) : ContinuousAt M realMetric E (fun x => f x+g x) p := continuous_of_limit M realMetric E _ p (hasLimit_add M E f g p (f p) (g p) (continuous_to_limit M realMetric E f p hf) (continuous_to_limit M realMetric E g p hg))-- Rudin Theorem 4.9, product clause, in pointwise real form. theorem continuous_mul (M : Metric (R:=R) X) (E : PointSet X) (f g : X → R) (p : X) (hf : ContinuousAt M realMetric E f p) (hg : ContinuousAt M realMetric E g p) : ContinuousAt M realMetric E (fun x => f x*g x) p := continuous_of_limit M realMetric E _ p (hasLimit_mul M E f g p (f p) (g p) (continuous_to_limit M realMetric E f p hf) (continuous_to_limit M realMetric E g p hg))-- Rudin Theorem 4.9, quotient clause, in pointwise real form with a -- nonzero denominator at the point. theorem continuous_div (M : Metric (R:=R) X) (E : PointSet X) (f g : X → R) (p : X) (hf : ContinuousAt M realMetric E f p) (hg : ContinuousAt M realMetric E g p) (hgp : g p≠0) : ContinuousAt M realMetric E (fun x => f x/g x) p := continuous_of_limit M realMetric E _ p (hasLimit_div M E f g p (f p) (g p) (continuous_to_limit M realMetric E f p hf) (continuous_to_limit M realMetric E g p hg) hgp)

Continuity and Compactness

A closed disk maps continuously to a closed oval.

A continuous map carries a compact set to a compact image.

-- Rudin Theorem 4.14: the continuous image of a compact space is -- compact. theorem continuous_image_compact (M : Metric (R:=R) X) (N : Metric (R:=R) Y) (f : X → Y) (hf : ∀ p, ContinuousAt M N (fun _ => True) f p) (compact : IsCompact M (fun _ => True)) : IsCompact N (fun y => ∃ x, f x=y) := -- The outputs approach a as h approaches zero, including f(0) = a. def LimitAtZero (f : R → R) (a : R) : Prop := ∀ ε, 0 < ε → ∃ δ, 0 < δ ∧ ∀ h, abs h < δ → abs (f h - a) < ε -- Constant-function case of Rudin Definition 4.5, expressed using -- LimitAtZero; no separate theorem. theorem limit_const (a : R) : LimitAtZero (fun _ => a) a := (limitAtZero_iff _ _).mpr ⟨hasLimit_const realMetric (fun _ => True) 0 a,rfl⟩ ⟩⟩⟩⟩

Differentiation

The Derivative of a Real Function

Secant lines through nearby curve points approach a tangent.

As the second point approaches the amber point, the pale secant lines approach the amber tangent.

-- The slope between nearby points approaches the fixed value d. def HasDerivative (f : R → R) (x d : R) : Prop := HasLimit realMetric realMetric (fun _ => True) (fun t => (f t-f x)/(t-x)) x d def Secant (f : R → R) (x d h : R) : R := classical -- Algebraic helper for the increment factorization in Rudin Theorem -- 5.5, (4)-(5); the secant is filled in at zero. theorem secant_increment (f : R → R) (x d h : R) : f (x+h)-f x=h*Secant f x d h :=

The Arithmetic of Derivatives

A rectangle grows by two thin strips and a small corner.

The product changes by two thin strips; the corner is second-order.

-- Rudin Theorem 5.3(a): derivative of a sum, for functions on the real -- line. theorem derivative_add (f g : R → R) (x a b : R) (hf : HasDerivative f x a) (hg : HasDerivative g x b) : HasDerivative (fun t => f t+g t) x (a+b) :=

Elementary Examples

A line, parabola, and reciprocal curve with tangent segments.

A line keeps the same slope; the parabola and reciprocal curve have changing slopes.

-- Rudin Examples 5.4: derivative of a constant. theorem derivative_const (c x : R) : HasDerivative (fun _ => c) x 0 := ; -- Rudin Examples 5.4: derivative of the identity function. theorem derivative_id (x : R) : HasDerivative (fun t => t) x 1 := ; -- Affine-polynomial case of Rudin Examples 5.4, using Theorem -- 5.3(a),(b). theorem derivative_affine (w b x : R) : HasDerivative (fun t => w * t + b) x w := ;

The Chain Rule

A small displacement is rescaled by two successive maps.

A small displacement is stretched at each stage. The two local scale factors multiply.

Some Special Functions

Differentiation of the Exponential Series

An exponential curve and tangent, beside the remainder and a quadratic upper bound.

The curve meets its tangent on the left. On the right, the blue error stays below an amber quadratic bound.

-- Consequence of Rudin Theorem 3.3(a),(b), real case: subtraction of -- sequence limits. theorem seq_sub (s t : Nat → R) (a b : R) (hs : ConvergesTo realMetric s a) (ht : ConvergesTo realMetric t b) : ConvergesTo realMetric (fun n => s n-t n) (a-b) := -- Consequence of the real absolute-value formula after Rudin Definition -- 1.32; no separate numbered theorem. theorem abs_le (x ε : R) : abs x≤ε ↔ -ε≤x ∧ x≤ε := ; -- Consequence of Rudin Examples 4.11, inequality (11): absolute value -- preserves sequential limits. theorem seq_abs (s : Nat → R) (a : R) (hs : ConvergesTo realMetric s a) : ConvergesTo realMetric (fun n => abs (s n)) (abs a) :=

A Positive Exponential

def exp (x : R) : R := classical exact hg' h hp ( ) exact hg' h hp ( )-- Rudin Examples 5.4, linear polynomial with slope -1. theorem derivative_negative (x : R) : HasDerivative (fun t => -t) x (-1) := ;

Sigmoid and Two-Class Softmax

A sigmoid curve with its bell-shaped derivative.

The blue sigmoid flattens at both ends; its amber derivative peaks in the middle.

Backpropagation

Scalar Expressions

inductive Expr (R : Type) where | const : R → Expr R | param : Nat → Expr R | add : Expr R → Expr R → Expr R | mul : Expr R → Expr R → Expr R | inv : Expr R → Expr R | exp : Expr R → Expr Rdef eval (exponential : R → R) (θ : Nat → R) : Expr R → R | .const c => c | .param i => θ i | .add a b => eval exponential θ a + eval exponential θ b | .mul a b => eval exponential θ a * eval exponential θ b | .inv a => 1 / eval exponential θ a | .exp a => exponential (eval exponential θ a)def Regular (exponential : R → R) (θ : Nat → R) : Expr R → Prop | .const _ | .param _ => True | .add a b | .mul a b => Regular exponential θ a ∧ Regular exponential θ b | .inv a => Regular exponential θ a ∧ eval exponential θ a ≠ 0 | .exp a => Regular exponential θ a

Forward Differentiation

An input perturbation travels forward through a branching computation.

An input perturbation travels forward. Each operation combines the changes arriving from its inputs.

def tangent (exponential : R → R) (θ seed : Nat → R) : Expr R → R | .const _ => 0 | .param i => seed i | .add a b => tangent exponential θ seed a + tangent exponential θ seed b | .mul a b => tangent exponential θ seed a * eval exponential θ b + eval exponential θ a * tangent exponential θ seed b | .inv a => -(tangent exponential θ seed a) / (eval exponential θ a * eval exponential θ a) | .exp a => exponential (eval exponential θ a) * tangent exponential θ seed a

Reverse Accumulation

def backward (exponential : R → R) (θ : Nat → R) : Expr R → R → Nat → R | .const _, _ => fun _ => 0 | .param j, bar => fun i => if i = j then bar else 0 | .add a b, bar => fun i => backward exponential θ a bar i + backward exponential θ b bar i | .mul a b, bar => fun i => backward exponential θ a (bar * eval exponential θ b) i + backward exponential θ b (bar * eval exponential θ a) i | .inv a, bar => backward exponential θ a (-bar / (eval exponential θ a * eval exponential θ a)) | .exp a, bar => backward exponential θ a (bar * exponential (eval exponential θ a))-- Additional backpropagation algorithm identity; no corresponding Rudin -- theorem. theorem backward_eq_tangent (exponential : R → R) (θ : Nat → R) (expression : Expr R) (bar : R) (i : Nat) : backward exponential θ expression bar i = bar * tangent exponential θ (fun j => if i = j then 1 else 0) expression := induction expression generalizing bar with ; ; ; ; ; ; -- Additional example of accumulation for a shared parameter; no -- corresponding Rudin theorem. theorem shared_parameter (exponential : R → R) (θ : Nat → R) (i : Nat) : backward exponential θ (.mul (.param i) (.param i)) 1 i = θ i + θ i := def neg (a : Expr R) : Expr R := .mul (.const (-1)) adef sum : List (Expr R) → Expr R | [] => .const 0 | a :: rest => .add a (sum rest)

Softmax

Three scores become positive exponential weights and then normalized shares.

Scores become positive weights, then shares that sum to one.

def softmax (first : Expr R) (rest : List (Expr R)) : Expr R := let weight := Expr.exp first .mul weight (.inv (.add weight (sum (rest.map Expr.exp))))

A Multilayer Perceptron

def sigmoid (a : Expr R) : Expr R := .inv (.add (.const 1) (.exp (neg a)))def affine (w x b : Expr R) : Expr R := .add (.mul w x) bstructure Parameters where w₀ : Expr R b₀ : Expr R w₁ : Expr R b₁ : Expr R v₀₀ : Expr R v₀₁ : Expr R c₀ : Expr R v₁₀ : Expr R v₁₁ : Expr R c₁ : Expr Rdef parameterLeaves : Parameters (R := R) := ⟨.param 0, .param 1, .param 2, .param 3, .param 4, .param 5, .param 6, .param 7, .param 8, .param 9⟩def mlp (p : Parameters (R := R)) (x : Expr R) : Expr R := let h₀ := sigmoid (affine p.w₀ x p.b₀) let h₁ := sigmoid (affine p.w₁ x p.b₁) let z₀ := .add (.add (.mul p.v₀₀ h₀) (.mul p.v₀₁ h₁)) p.c₀ let z₁ := .add (.add (.mul p.v₁₀ h₀) (.mul p.v₁₁ h₁)) p.c₁ softmax z₀ [z₁]def squaredLoss (prediction : Expr R) (target : R) : Expr R := let error := .add prediction (.const (-target)) .mul (.const (1 / 2)) (.mul error error)def trainingLoss (x y : R) : Expr R := squaredLoss (mlp parameterLeaves (.const x)) y

Backpropagation Gives the Derivative

def perturb (θ seed : Nat → R) (t : R) : Nat → R := fun i => θ i+seed i*t-- Implementation identity for scalar parameter perturbations; no -- corresponding Rudin theorem. theorem perturb_zero (θ seed : Nat → R) : perturb θ seed 0=θ := ; ; -- Implementation helper for expression-domain conditions; no -- corresponding Rudin theorem. theorem regular_sum (θ : Nat → R) (xs : List (Expr R)) (hx : ∀ a, a∈xs → Regular Speedrun.exp θ a) : Regular Speedrun.exp θ (sum xs) := induction xs with exact ⟨hx a ( ),ih (fun b hb => hx b ( ))⟩-- Finite-sum consequence of exponential positivity, Rudin Theorem -- 8.6(c); formulated for this article's expression evaluator. theorem sum_exp_nonneg (θ : Nat → R) (xs : List (Expr R)) : 0≤eval Speedrun.exp θ (sum (xs.map Expr.exp)) := induction xs with ; -- Additional sigmoid denominator check using exponential positivity; no -- direct Rudin counterpart. theorem regular_sigmoid (θ : Nat → R) (a : Expr R) (ha : Regular Speedrun.exp θ a) : Regular Speedrun.exp θ (sigmoid a) := exact ⟨⟨trivial,⟨trivial,ha⟩⟩, ; ⟩-- Implementation helper for the squared-loss expression; no -- corresponding Rudin theorem. theorem regular_squaredLoss (θ : Nat → R) (p : Expr R) (y : R) (hp : Regular Speedrun.exp θ p) : Regular Speedrun.exp θ (squaredLoss p y) := ⟨trivial,⟨⟨hp,trivial⟩,⟨hp,trivial⟩⟩⟩-- Additional domain check for the MLP training loss; no corresponding -- Rudin theorem. theorem trainingLoss_regular (θ : Nat → R) (x y : R) : Regular Speedrun.exp θ (trainingLoss x y) :=

Blue arrows carry values forward; amber arrows carry sensitivities backward through branching paths.

Blue carries values forward; amber carries sensitivities backward. Contributions add where paths meet.

A small neural network with one amber weight, beside a loss curve and its amber tangent.

Vary the amber weight while holding the others fixed. Backpropagation gives the slope of the resulting loss curve.

-- Additional correctness theorem for the MLP's parameter derivatives; -- no corresponding Rudin theorem. theorem mlp_backward_is_derivative (θ : Nat → R) (x y : R) (i : Nat) : HasDerivative (fun t => eval Speedrun.exp (perturb θ (fun j => if i=j then 1 else 0) t) (trainingLoss x y)) 0 (backward Speedrun.exp θ (trainingLoss x y) 1 i) := backward_is_derivative θ _ i (trainingLoss_regular θ x y)