Verifying Equivalence of Parallel Program and its Sequential Counterpart — in Lean 4
Anirudh Gupta
4th-year B.Tech Mathematics and Computing
Indian Institute of Science, Bengaluru
ISP - I Presentation
Advised by Prof. Siddhartha Gadgil
Motivation
Independence and Wellformedness of Parallel Programs
Paralever Language
Proof of Equivalence
Parallel Programs are Faster
Examples
Autoparallelization
Races
MLIR
Performance of Paralever
Limitations
Paralever is BMW's rear drive architecture of most modern BMW shaft-driven motorcycles… But it runs sequentially…
BMW R 1250 GS · Cjp24, CC BY-SA 4.0, via Wikimedia CommonsConsider the two jobs run sequentially separately or parallely(in arbitrary order). Does the memory come out the same?
Clearly the two parallel executions do not yield the same heap.
Under what conditions can we guarantee that the parallel execution is equivalent to the sequential execution?
We define every symbol the statement uses.
| l : Loc | A Memory Location. Locations are numbered 0, 1, 2, …, etc. |
| v : Val | A value. What a single location holds. |
| σ : Loc → Val | A heap. One value for every location at once; σ l is what location l holds. |
| p : ParM α | A program. Built from four constructors: a finished value, a read, write and a parallel composition of finitely many programs. Running it returns a value of type α. |
| c | A configuration. The whole state of a run: a pair (p, σ) — the program still to run, and the heap as it stands. |
| wrong | The racy outcome. The one other configuration. A race steps to it; it is terminal and absorbing, so nothing leaves it. |
| c → c' | One step. c' is one of the finitely many successors of c. A read or a write has exactly one; a parallel composition has one per branch ready to move, and that choice is the only nondeterminism in the model. |
| Reaches c c' | An interleaving. A finite chain c → c₁ → ⋯ → c'. To quantify over interleavings is to quantify over these chains. |
| seq p q | Sequential composition. Run p to completion, then q. Exactly one chain, no choice anywhere. |
| par p q | Parallel composition. Run both branches, interleaved in any order, and join once each has finished. Many chains. |
| R(p), W(p) | The footprint. The locations p reads, and the locations p writes. |
| WellFormed p σ | The hypothesis. At every parallel composition reached while running p from σ, the branches' footprints are pairwise independent, and each branch is itself well formed. |
def Indep (f₁ f₂ : Footprint) : Prop :=
Disjoint f₁.writes f₂.writes ∧ Disjoint f₁.writes f₂.reads ∧ Disjoint f₂.writes f₁.readsThe footprint of a program is a pair of finite sets of locations: R(p), those it reads, and
W(p), those it writes. It is computed from the program, never supplied by hand.
Two programs are independent when the three clauses above hold of their footprints. This is Bernstein's condition, and it is decidable.
Scroll Down ↓ for more details
def WellFormed {τ : Type} : ParM τ → State → Prop
| .pure _, _ => True
| .read l k, σ => WellFormed (k (σ l)) σ
| .write l v k, σ => WellFormed (k ()) (σ.update l v)
| .par cs k, σ =>
let r := runChilds cs σ
IndepAll (childFootprints cs σ) ∧ WellFormedChilds cs σ ∧ WellFormed (k r.1) r.2p is well formed from heap σ if, at every parallel composition reached while running p
from σ, its branches are pairwise independent, each branch is itself well formed, and what
follows the join is well formed too.
Each branch is checked against the heap the branch before it left during the execution.
Paralever provides a small imperative language which has shared buffers, private registers, loops, branches, parallel composition, synchronizations and other features needed for realistic programs.
Every program denotes two executions — a parallel one and a sequential one.
Well-formedness is decided on the program as written, and it implies the two executions agree.
DESIGN PRINCIPLE: to allow ease to parallel sequential equivalence, and mimic hardware and compiler behaviors.
Example 1: Registers are firstprivate, which means any changes to registers within parallel threads are discarded at the join.
Example 2: Synchronizations are used to ensure that certain operations are completed before others, mimicking the behavior of real hardware.
Scroll Down ↓ for more details
inductive ParM : Type → Type 1 where
| pure {α : Type} : α → ParM α
| read {α : Type} : Loc → (Val → ParM α) → ParM α
| write {α : Type} : Loc → Val → (Unit → ParM α) → ParM α
/-- Fork every child at once, then continue with all their results. The only constructor whose
meaning Lean does not already fix: `run` interprets it by interleaving, which is what makes the
sequentialization theorem non-vacuous. -/
| par {β : Type} {αs : List Type} : Childs ParM αs → (Results αs → ParM β) → ParM βBuffers are shared and registers are not: out[i] := %s is what Indep measures, %s and %k
are invisible to it.
Registers are firstprivate, at every depth. All four threads read %k = 10 — which is why
out[2] is 60. Thread 0 sets %k := 99 and the join discards it.
if … else branches per location; print is erased from both interpreters, and is a barrier the
parallelizer may not cross.
def step {α : Type} : ParM α → State → List (Conf α)
| .pure _, _ => []
| .read l k, σ => [.run (k (σ l)) σ]
| .write l v k, σ => [.run (k ()) (σ.update l v)]
| .par cs k, σ =>
if racingAll (nextAccsChilds cs) then [.wrong]
else match allPure cs with
| some vs => [.run (k vs) σ]
| none => (stepChilds cs σ).map fun r =>
match r with
| some x => .run (.par x.1 k) x.2
| none => .wronginductive Childs (Node : Type → Type 1) : List Type → Type 1 where
| nil : Childs Node []
| cons {α : Type} {αs : List Type} : Node α → Childs Node αs → Childs Node (α :: αs)step returns a list: empty is terminal, a singleton is deterministic, and a fork returns one
entry per ready child. That list is where every schedule comes from.
racingAll is checked before the children move, so a fork with two conflicting next actions goes
to wrong and stays there.
def ParSeqEq {α : Type} (parProgram seqProgram : ParM α) (σ : State) : Prop :=
∀ r σ', Reaches (.run parProgram σ) (.run (.pure r) σ')
↔ Reaches (.run seqProgram σ) (.run (.pure r) σ')theorem par_seq_eq {s : ParProg} (h : wfB s = true) (ρ : Regs) (σ : State) :
ParSeqEq (execPar s ρ) (execSeq s ρ) σ := bys:ParProgh:s.wfB = trueρ:Regsσ:State⊢ s.execPar ρ ∥≡ s.execSeq ρ from σwfB s = truedecided by decide: list intersections on footprintss ends where execSeq s endsstated as an iff on reachable outcomesParSeqEq compares two whole programs, not the two branches of one fork: ParSeqEq p q σ holds when,
for every result r and heap σ', some schedule of p ends in pure r with heap σ' exactly when some schedule
of q does. The theorem par_seq_eq takes p to be the parallel execution of a ParProg s and q its
sequential execution, for every s that wfB accepts, every register file ρ and every initial heap σ.
Under WellFormed each execution — parallel or sequential — reaches exactly one outcome, and
those two outcomes are equal. Without it the program is refused and the racing schedule is exhibited.
So ParSeqEq reduces to WellFormed for all programs.
par p qWellFormed ⇒ no wrongseq p qScroll Down ↓ for more details
def step {α : Type} : ParM α → State → List (Conf α)
| .pure _, _ => []
| .read l k, σ => [.run (k (σ l)) σ]
| .write l v k, σ => [.run (k ()) (σ.update l v)]
| .par cs k, σ =>
if racingAll (nextAccsChilds cs) then [.wrong]
else match allPure cs with
| some vs => [.run (k vs) σ]
| none => (stepChilds cs σ).map fun r =>
match r with
| some x => .run (.par x.1 k) x.2
| none => .wrongThere is no scheduler in the development. A schedule is a path through these lists, and
Reaches is the transitive closure of membership in them.
So quantifying over schedules is quantifying over ∈.
n statements · (2n)!/(n!)² interleavings · 184 756 at n = 10 · and the two sides do not even take the same number of stepsrunSeq p σ — a function, not a relation: no schedule, no choice, no wrongrfl, and freethe measuring stick reads the same on both. It says nothing yet about either one under a scheduler.theorem step_combined {τ : Type} (P : ParM τ) :
∀ σ, WellFormed P σ → ∀ P3 σ3, Conf.run P3 σ3 ∈ stepC (Conf.run P σ) →
runSeq P3 σ3 = runSeq P σ ∧
(∀ F, FDisjoint F (accesses P σ) → FDisjoint F (accesses P3 σ3)) :=
step_combined_all.1 PP3 is any member of the successor list, under ∀ — one statement per scheduler choicethe proof rcases on List.mem_append: head moved, 10 lines · tail moved, 45 lines and the hard caseWhy the tail case commutes. Its step changed one location in W₂. By C3 that location is outside R₁,
so the head reads the same values — accesses_runSeq_locality. By C1 it is outside W₁, so the
head does not overwrite it — runSeq_frame.
Why it can be done again. The second conjunct: a step only shrinks a footprint, so the sibling is still independent of the residue, and the invariant chains.
theorem wellFormed_canonical {τ : Type} (p : ParM τ) :
∀ σ r σ', WellFormed p σ → (Reaches (.run p σ) (.run (.pure r) σ') ↔ (r, σ') = runSeq p σ) :=
wellFormed_canonical_all.1 pp from σ }every terminating schedule, however the scheduler movedThe invariant chained along a Reaches derivation, with WellFormed_preserved re-establishing the
hypothesis at each link. runSeq is constant along the chain, and at the end it is (r, σ′).
Uniqueness is →; existence is ←, from no_race_of_indep. Without existence a racy program
reaches nothing and would satisfy the theorem vacuously on both sides.
The theorem is not two left-to-right runs compared. That is step 4, and it is rfl. The work is
in 2 and 3: each is wellFormed_canonical, a whole set of schedules collapsing to a point.
Nothing after step 1 mentioned p or q. So ParSeqEq reduces to WellFormed — proved once,
for every program there will ever be.
theorem time_le {s : ParProg} (h : wfB s = true) (ρ : Regs) (σ : State) :
time (execPar s ρ) σ ≤ time (execSeq s ρ) σ := time_execPar_le_all.1 s ρ σ htime counts rounds: one round is every running thread taking one step. The same Bool that
proves the two readings agree also orders their spans.
Parallelism reorders memory operations and removes none, so work is unchanged and only time
falls. The inequality is not conditional on a machine, a scheduler or a core count.
Time model is not real, but based on Paralever modelling
We exclude synchronization costs, thread initialization costs, and other overheads. The model is a simplification to focus on the theoretical aspects of parallel execution.
The Proof idea is very simple:
Consider arbitrary 2 nodes(use induction for proof). 2 parallel nodes take 1 round to execute while the sequential nodes take 2 rounds. It is possible no parallelism can exist due to data dependency. Hence the parallel execution is not slower than the sequential execution.
Matrix multiply — disjoint writes over overlapping reads.
Summing an array — quantified over the chunk plan.
Merge sort — the fork is the recursion.
A neural net — layers in sequence, threads inside each.
Scroll Down ↓ for more details
example : ParProg.wfB (matmul 2) = true := by⊢ (matmul 2).wfB = true decideAll goals completed! 🐙
example : ParProg.wfB (matmul 3) = true := by⊢ (matmul 3).wfB = true decideAll goals completed! 🐙
/-- …and the equivalence follows with nothing further to supply. -/
theorem par_seq_eq_2 (ρ : Regs) (σ : State) :
ParSeqEq (ParProg.execPar (matmul 2) ρ) (ParProg.execSeq (matmul 2) ρ) σ :=
ParProg.par_seq_eq (byρ:Regsσ:State⊢ (matmul 2).wfB = true decideAll goals completed! 🐙) ρ σThread i writes row i of C and reads row i of A and all of B. (C1) holds because
i ↦ i*n + j is injective across threads; (C2) and (C3) hold because A and B are never written.
The file above carries the same theorem as matmul_parseqeq, read through prl_file.
theorem seq_eq_par (chunks : ChunkPlan) (σ : State) :
sumRangePar chunks ∥≡ sumRangeSeq chunks from σ :=
parAll_par_seq_eq (chunks.map sumRange) σ (wellFormed_sumRangePar chunks σ)Universally quantified over the chunk plan and the heap. This is the shape ∗-disjointness cannot
state at all: four threads reading one array.
theorem seq_eq_par (N lo hi : Nat) (hhiN : hi ≤ N) (σ : State) :
mergeSortPar N lo hi ∥≡ mergeSortSeq N lo hi from σ := byN:Natlo:Nathi:NathhiN:hi ≤ Nσ:State⊢ mergeSortPar N lo hi ∥≡ mergeSortSeq N lo hi from σQuantified over the array size and over every range, with no decide: each level's obligation is
one interval fact, and the recursion carries it down.
/-- **The theorem.** Under every schedule, the net with all its layers' threads running at once
reaches exactly the outcomes it reaches run thread-by-thread. -/
theorem forward_par_seq_eq (ρ : Regs) (σ : State) :
ParSeqEq (ParProg.execPar forward ρ) (ParProg.execSeq forward ρ) σ :=
ParProg.par_seq_eq (byρ:Regsσ:State⊢ forward.wfB = true decideAll goals completed! 🐙) ρ σThe weights are shared reads, so (C2) and (C3) are free inside a layer. Between layers the
composition is sequential, and wfB recurses into each arm.
A sequential program is a chain of statements.
We compute its dependences: here, five units and four dependences.
The chain is rebuilt as three parallel groups, and the rebuilding is proved sound with no hypothesis.
Scroll Down ↓ for more details
ParProg.block [s₀, …, s₈] is seq s₀ (seq s₁ (…)), so the order the statements were written in is
the tree's right spine. The pass first cuts that spine into five register-closed units — %0 := a[0]
and a[2] := %0 * %0 may not be separated, because a register is thread-private — and one scoreboard
pass reads every dependence off them: [[], [], [0], [1], [2, 3]].
A register is thread-private, so %0 := a[0] and a[2] := %0 * %0 may not be separated: the unit,
not the statement, is what a thread is built from. One left-to-right scoreboard pass then reads
every dependence off the units' footprints — [[], [], [0], [1], [2, 3]]. Four of the ten pairs
carry one; u0, u1 share no location, as do u2, u3. That is the whole of the parallelism this program has.
example (ρ : Regs) (σ : State) :
(runSeq (ParProg.execPar (rewrite p) ρ) σ).2 = (runSeq (ParProg.execSeq p ρ) σ).2 :=
rewrite_sound p ρ σ
-- and because the rewrite stays well-formed, `par_seq_eq` lifts that from one schedule to all
example (ρ : Regs) (σ : State) :
ParSeqEq (ParProg.execPar (rewrite p) ρ) (ParProg.execSeq (rewrite p) ρ) σ :=
rewrite_parSeqEq p (byρ:Regsσ:State⊢ p.wfB = true decideAll goals completed! 🐙) ρ σrewrite checks its own gate and hands back the program unchanged when it fails, which is why
rewrite_sound carries no hypothesis. Nothing is ever reordered, so no commutation lemma is needed.
We search for a data race whenever the independence test refuses, and we return the interleaving that disagrees.
Scroll Down ↓ for more details
| step | thread | action | heap after |
|---|---|---|---|
| 0 | T0 | write log[0] ← 1 | log ↦ [1, 0], x ↦ [0] |
| 1 | T1 | write log[1] ← 1 | log ↦ [1, 1], x ↦ [0] |
| 2 | T1 | write x[0] ← 9 | pending |
| 2 | T0 | write x[0] ← 7 | pending |
findWrongFrom fuel p σ: -- phase 1
sites ← raceSites p σ every par node failing Bernstein,
if sites = [] then none measured along the canonical run
else findWrongGuided (targetsOf sites) fuel (run p σ)
findWrongGuided targets fuel c: -- phase 2
if 0 then none
if some successor of c is wrong then [its index]
else let (keep, hold) = partition (successors of c)
by "does this step move a thread PAST a flagged location?"
first i in keep ++ hold with
findWrongGuided targets (fuel-1) c′ = some s ⇒ i :: sPhase 1 names the locations; phase 2 is depth-first over step's successor list, trying last any
step that moves a thread past one of them — a reordering, so nothing becomes unfindable.
Whatever comes back is re-run by follow and turned into a Reaches proof by follow_sound,
so the counterexample is checked rather than trusted.
-- and the theorem the verdict stands for, on the program the deck prints
theorem square_par_seq_eq (ρ : Regs) (σ : State) :
ParSeqEq (Lang.ParProg.execPar square.prog ρ) (Lang.ParProg.execSeq square.prog ρ) σ :=
Lang.ParProg.par_seq_eq (byρ:Regsσ:State⊢ square.prog.wfB = true decideAll goals completed! 🐙) ρ σA memref.global becomes a buffer, an affine.map is already a footprint function, and the three
iterations become three threads of one fork. Nine labelled pilots are #guarded as a confusion
matrix — tp = 3, fp = 0, fn = 0, tn = 4 over the seven generic-form ones — and emitting the
program back as MLIR compares memory, footprint, verdict and heap.
We measure how long the check takes on matrix multiplication, and what speedup it certifies.
On a program with no structure the pass runs to completion and finds almost nothing.
We place a race at the very bottom of a run and measure what reaching it costs.
Scroll Down ↓ for more details
n | locations | threads | rounds par | rounds seq | speedup | check |
|---|---|---|---|---|---|---|
| 2 | 12 | 2 | 10 | 20 | 2× | 0 ms |
| 4 | 48 | 4 | 36 | 144 | 4× | 0 ms |
| 8 | 192 | 8 | 136 | 1 088 | 8× | 20 ms |
| 12 | 432 | 12 | 300 | 3 600 | 12× | 120 ms |
| 16 | 768 | 16 | 528 | 8 448 | 16× | 520 ms |
| 20 | 1 200 | 20 | 820 | 16 400 | 20× | 1 600 ms |
The verdict is every heap · Proved: Yes at every size: wfB accepts, so the threads'
footprints are pairwise independent whatever the heap holds.
The speedup is exactly n, the thread count, and it is certified rather than measured —
these are the two time values the cost theorem orders, not a wall clock.
The check grows with the iteration space it writes out, not with the speedup: n = 20 is 1 200
locations and 1.6 s.
equiv.prl — 36 lines, 224 sequential rounds, a serial chain of dependences rather than a
loop nest.
autopar takes 1.63 s and returns 2 threads at 196 parallel rounds: a speedup of
1.14×, against 4× on phases.prl, which is the same length and does split.
The pass is sound either way. Where the dependences forbid a split it finds nothing, and says so, rather than reporting a parallelism that is not there.
d | instructions | as written | autopar, markers off | regions only |
|---|---|---|---|---|
| 32 | 63 234 | 3 ms | 19 ms — 0.15× | 5 ms — 0.60× |
| 128 | 173 826 | 9 ms | 22 ms — 0.40× | 8 ms — 1.12× |
| 512 | 616 194 | 36 ms | 36 ms — 1.00× | 21 ms — 1.71× |
| 2048 | 2 385 666 | 142 ms | 91 ms — 1.56× | 73 ms — 1.94× |
chaos.prl — a thousand lines, nothing in it parallel. Forking every statement puts 2 072 children
in and does not break even until d = 512; forking only inside the marked regions puts 280 in and
is ahead from d = 128. n = 8, m = 32, sixteen cores, median of five runs; planning is a
compile-time cost and is in neither column.
Two arms each do k independent writes, then both write one shared location: the only race is the
very last statement either arm runs, at step 2k.
The search reaches it in every case — it replays the schedule against the semantics rather than guessing, so the depth is the cost.
k | race at step | found | search |
|---|---|---|---|
| 2 | 4 | yes | 0 ms |
| 8 | 16 | yes | 0 ms |
| 32 | 64 | yes | 0 ms |
| 128 | 256 | yes | 80 ms |
| 512 | 1 024 | yes | 3 420 ms |
On race.prl the two readings are separated as well as refused: parallel leaves x[0] ↦ 7,
sequential leaves x[0] ↦ 9, and the refusal names the locations and the threads —
T0, T1 write to: {x[0]}.
Non-terminating programs are unrepresentable.
ParM is an inductive type, so every program it can express terminates.
A computed address widens the footprint.
A[B[i]] has a subscript the text does not determine, so the syntactic footprint might claim all of A.
TODO: Expand the "program" representation for practical usage.
Introduce locks, atomics annd other synchronization primitives.
Expand memory model to generalized conditions so that any backend memory model(like stack-heap, any memory hierarchy, counting sheeps, etc.) can be supported.
Expand the thread model to support a generalized conditions, so that any model satisfying them like grids and blocks, similar to CUDA and TPU frameworks, will work.
Any questions?
Bernstein, Analysis of Programs for Parallel Processing, IEEE TEC 1966.
Reynolds, Toward a Grainless Semantics for Shared-Variable Concurrency, FSTTCS 2004.
Brookes, A Semantics for Concurrent Separation Logic, CONCUR 2004.
de Moura and Ullrich, The Lean 4 Theorem Prover and Programming Language, CADE 28, 2021.