Tomáš Skřivan
Carnegie Mellon University
9.1.2024
What is Automatic Differentiation?
def foo (x : Float) : Float := x^2
def foo' (x : Float) : Float := 2*x
AD
Why Lean for Automatic Differentiation?
def fast_sin (x : Float) : Float :=
if x = 0 then
0
else
sin x
def fast_sin' (x : Float) : Float :=
if x = 0 then
0
else
cos x
AD
incorrect
Why Lean for Automatic Differentiation?
noncomputable
def odeSolve (f : X → X) (t : ℝ) (x₀ : X) : X :=
if h : ∃ x : ℝ → X,
∀ t', deriv x t' = f (x t')
∧
x 0 = x₀
then choose h t
else 0
theorem odeSolve_deriv
(...)
: let x := fun t' => odeSolve f t' x₀
deriv x t
=
f (x t) := ...
theorem odeSolve_approx
(...)
: odeSolve f t x₀
=
limit n → ∞,
let mut Δt := t/n
let mut x := x₀
for i in [0:n] do
x := x + Δt * f x
x
Bigger goal: Lean for Scientific Computing
def update (x v : Array Vec3) :=
v := v + Δt * force x
x := x + Δt * v
(x,v)
+
+
+
Back to Automatic Differentiation
How to implement AD in Lean?
FTrans: General Function Transformation
example (x : ℝ)
: fderiv ℝ (fun x : ℝ => x^2) x
=
fun dx =>L[ℝ] 2 * dx * x := by ftrans
example
: (adjoint (fun x : ℂ =>L[ℂ] I*x))
=
fun y =>L[ℂ] -I * y := by ftrans
FTrans: General Function Transformation
theorem fderiv_comp
{g : E → F} {f : F → G}
(hg : Differentiable 𝕜 g) (hf : Differentiable 𝕜 f) :
: fderiv 𝕜 (fun x => (f (g x)))
=
fun x => fun dx =>L[K] fderiv K f (g x) (fderiv K g x dx) := ...
theorem fderiv_id
: (fderiv K fun x : X => x) = fun _ => fun dx =>L[K] dx := ...
T fun x => x = ...
T fun x => y = ...
T fun f => f i = ...
T fun x => f (g x) = ...
T fun x => let y := g x; f x y = ...
T fun x i => f i x = ...
FTrans: General Function Transformation
FTrans: General Function Transformation
@[ftrans]
theorem fderiv_add
(f g : X → Y) (hf : Differentiable K f) (hg : Differentiable K g)
: (fderiv K fun x => f x + g x)
=
fun x => fderiv K f x + fderiv K g x := ...
FProp: Proving General Function Property
example : Continuous fun x : ℝ => x^2 := by fprop
example : Differentiable ℝ fun x : ℝ => x^2 := by fprop
example : Continuous fun x : ℝ =>
let x1 := x * x
let x2 := x1 * x1
let x3 := x2 * x2
let x4 := x3 * x3
let x5 := x4 * x4
x5 := by fprop
FProp: Proving General Function Property
FProp: Proving General Function Property
example
: Continuous
fun x : ℝ =>
let x1 := x + x
let x2 := x1 + x1
let x3 := x2 + x2
let x4 := x3 + x3
let x5 := x4 + x4
let x6 := x5 + x5
x6:= by ...
FProp: Proving General Function Property
example (f : ℝ → ℝ → ℝ) (hf : Continuous (fun (x,y) => f x y))
: Continuous (λ x => f x x) := by fprop
example {n} (f : ℝ → (Fin n → ℝ)) (g : ℝ → ℝ)
(hf : Continuous f) (hg : Continuous g)
: Continuous (λ x => (f (g x))) := by fprop
FProp: Proving General Function Property
@[fprop]
theorem Differentiable.add
(f g : X → Y) (hf : Differentiable R f) (hg : Differentiable R g)
: Differentiable R fun x => f x + g x := ...
Demo
Demo
Conclusion