Lecture 20 · Program Synthesis, and the Course in Review

Introduction to Automated Reasoning · Lecture 20。个人学习讲义与配套实验,按主题整理并持续修订。

课程源码 ZIP ↓

个人整理的学习笔记,非官方讲义;课程来源与整理说明见课程介绍。配套示例未逐一运行验证。

本篇目录

Maps to: Stanford CS 257 Introduction to Automated Reasoning (Winter 2026), Lecture 20 · Thu 03/12/2026 · Schedule buffer: applications (program synthesis), finish theory combination, project office hours (Caroline Trippel). Reading: none listed. Basis: No slides are public for this session. Theory combination is covered in Lecture 18. This lecture is written from:

  • Solar-Lezama et al. (ASPLOS 2006) and Solar-Lezama’s thesis (2008): sketching and CEGIS;
  • Alur et al. (FMCAD 2013): syntax-guided synthesis (SyGuS);
  • Udupa et al. (PLDI 2013) and Albarghouthi, Gulwani and Kincaid (CAV 2013): observational equivalence;
  • Alur, Radhakrishna and Udupa (TACAS 2017): EUSolver;
  • Jha, Gulwani, Seshia and Tiwari (ICSE 2010): synthesis of bit-manipulating programs;
  • Reynolds et al. (CAV 2015): synthesis inside an SMT solver;
  • Warren’s Hacker’s Delight.

These notes add one module, synth.py, with:

  • grammars, and enumeration with observational equivalence;
  • CEGIS with Lecture 16’s bit-vector solver as verifier;
  • sketching, and the expansion of ∀;
  • certificates for every program.

A closing script runs one problem through every solver the course built. The experiments were designed for these notes and do not reflect what was said in class. Code: code/lecture20/ (3 scripts + 1 module; Python standard library only; about 3 to 7 seconds of CPU time each) Reading time: 2 hours including running the code


0. How to read this lecture

0.1 Learning goals

After this lecture you should be able to:

  1. State program synthesis as an ∃∀ problem, and say why the quantifier alternation makes it hard.
  2. Write a syntax-guided synthesis problem: a grammar of allowed programs and a specification.
  3. Run bottom-up enumeration with observational equivalence by hand, and explain why its pruning is safe in a CEGIS loop.
  4. Explain CEGIS: synthesizer, verifier, counterexamples. Say why it converges quickly in practice, and connect it to Lecture 17’s model-based instantiation.
  5. Use sketches: holes filled by a solver. Prove that a sketch is impossible.
  6. Place every solver of the course on one map, and explain what each one’s certificate is.

0.2 Prerequisites and scope

AssumedIntroduced hereDeveloped elsewhere
bit-vectors, bit-blasting, DRUP (Lectures 5, 16)synthesis, grammars, CEGIS, sketches—
quantifier instantiation, MBQI (Lecture 17)CEGIS as lazy instantiation of ∀—
counterexample databases, generate-and-verify (Lecture 19)the verifier as teacherLLM-based generation (outside this course)

0.3 Map

§1  synthesis: from checking to inventing
§2  specifications and grammars (SyGuS)
§3  enumeration with observational equivalence             ← code 01
§4  CEGIS: the verifier as teacher                          ← code 01
§5  sketching: the solver fills holes                       ← code 02
§6  synthesis in practice (overview)
§7  the course in review                                    ← code 03
§8  summary   §9 common pitfalls   §10 exercises   §11 further reading

0.4 Notation

SymbolMeaning
∃f ∀xˉ. φ(xˉ,f(xˉ))\exists f\, \forall \bar x.\ \varphi(\bar x, f(\bar x))the synthesis problem: a program ff meeting spec φ\varphi on every input
GGa grammar: the programs allowed
EEthe current finite set of example inputs
signature of ppthe tuple (p(e))e∈E(p(e))_{e \in E} of its outputs on the examples
≫\gg, ≫s\gg_slogical and arithmetic right shift (8-bit)
∼\sim, −-bitwise complement, two’s-complement negation

0.5 The code of this lecture

One module, synth.py:

  • programs: evaluate, to_bv, show, size;
  • problems: Grammar, Spec, equals_reference;
  • enumeration: enumerate_programs;
  • CEGIS: cegis, verify, exhaustive_check, random_examples_synthesis;
  • sketching: Sketch, sketch_cegis, sketch_all_inputs;
  • benchmarks: BENCHMARKS.

The verifier is Lecture 16’s bit-blaster with Lecture 5’s CDCL. Its UNSAT answers carry checked DRUP proofs.


1. Synthesis: from checking to inventing

Every earlier lecture asked a solver to check something. Is this formula satisfiable? Is this circuit’s output always correct? Do these two queries agree on every database? Synthesis asks it to invent a program that is correct:

∃f ∀xˉ. φ(xˉ,f(xˉ))\exists f\ \forall \bar x.\ \varphi(\bar x, f(\bar x))

An example. Find ff such that f(x,y)=⌊(x+y)/2⌋f(x, y) = \lfloor (x + y) / 2 \rfloor for all 8-bit unsigned x,yx, y, without the overflow of (x+y)≫1(x + y) \gg 1 (Lecture 16). Hacker’s Delight’s answer is (x & y)+((x⊕y)≫1)(x \,\&\, y) + ((x \oplus y) \gg 1): the common bits, plus half the differing ones.

Why it is hard.

  • The quantifier alternation. ∃f\exists f ranges over programs, an infinite space; ∀xˉ\forall \bar x ranges over all inputs. Lecture 17 showed that ∀\forall is where solvers struggle, and here it sits under an existential over functions.
  • Undecidability. In general the problem is undecidable.
  • The search space. Even over finite inputs and a bounded program size, the space of programs grows exponentially with size (§3).

A short history.

  • Church’s problem (1957). Synthesize a circuit from a logical specification.
  • Deductive synthesis (Manna and Waldinger, 1980). Extract the program from a constructive proof of ∀x∃y. φ\forall x \exists y.\ \varphi.
  • Superoptimization (Massalin, 1987). Enumerate machine-code sequences and test them.

Today’s methods. Today’s methods are inductive: they generalize from examples and use a solver to check and to find counterexamples. Two ideas make this work, and they are the subject of this lecture:

  • the syntactic restriction of the program space (SyGuS);
  • the counterexample-guided loop (CEGIS).

2. Specifications and grammars (SyGuS)

2.1 The two parts of a problem

A syntax-guided synthesis problem (Alur et al. 2013) has two parts:

  • a specification φ(xˉ,out)\varphi(\bar x, \mathit{out}): a formula in a background theory, here bit-vectors;
  • a grammar GG: the programs allowed.

Specifications come in two kinds:

  • Reference implementation: out=ref(xˉ)\mathit{out} = \mathit{ref}(\bar x), for example out=x & (x−1)\mathit{out} = x \,\&\, (x - 1). This asks for a different (smaller, faster) program with the same behavior.
  • Relational: a property, for example for the maximum out≥sx∧out≥sy∧(out=x∨out=y)\mathit{out} \ge_s x \wedge \mathit{out} \ge_s y \wedge (\mathit{out} = x \vee \mathit{out} = y). No program is given.

Grammars. The benchmark grammars are:

BITS     S -> x | 0 | 1 | S op S, op in {+, -, &, |, ^}, | ~S | -S              (one input)
BITS2    S -> x | y | 0 | 1 | S op S, op in {+, -, &, |, ^, >>}  | ~S          (two inputs)
SHIFTS   BITS plus >>, >>s and the constant 7
CHOICE   S -> x | y | 0 | 1 | ite(B, S, S);  B -> S <s S | S <u S | S = S

The grammar is part of the problem. It keeps the search small and expresses what kind of answer is wanted, for example “branch-free”.

2.2 The benchmarks

specificationkindknown solution
turn off the rightmost 1-bitreferencex & (x−1)x \,\&\, (x - 1)
isolate the rightmost 1-bitreferencex & −xx \,\&\, {-x}
right-propagate the rightmost 1-bitreferencex∣(x−1)x \mid (x - 1)
isolate the rightmost 0-bitreference∼x & (x+1){\sim}x \,\&\, (x + 1)
average without overflowreference, 9-bit sum(x & y)+((x⊕y)≫1)(x \,\&\, y) + ((x \oplus y) \gg 1)
absolute valuereference(x⊕(x≫s7))−(x≫s7)(x \oplus (x \gg_s 7)) - (x \gg_s 7)
signed max, signed minrelationalif-then-else

They come from Hacker’s Delight and from Jha, Gulwani, Seshia and Tiwari’s benchmarks.


3. Enumeration with observational equivalence

3.1 Bottom-up enumeration

Generate programs by size. Start with the leaves (size 1). Then build size nn from smaller pieces:

  • op(a)\mathrm{op}(a) with ∣a∣=n−1|a| = n - 1;
  • op(a,b)\mathrm{op}(a, b) with ∣a∣+∣b∣=n−1|a| + |b| = n - 1;
  • ite(c,a,b)\mathrm{ite}(c, a, b) with ∣c∣+∣a∣+∣b∣=n−1|c| + |a| + |b| = n - 1.

The first program that satisfies the specification is the smallest.

The space explodes. Script 01, Part 1, uses the one-variable grammar BITS:

programs up to sizeall programsgenerated with pruningkept
1333
2997
3666215
428815037
51,93841884
611,2861,100193

Without pruning the count grows by a factor of about 4 to 7 per extra node.

3.2 Observational equivalence

The idea. The signature of a program is its tuple of outputs on the current examples. Two programs with the same signature are interchangeable as far as the examples can tell. So the enumerator keeps only the first one, and builds bigger programs only from kept ones.

An example. With examples x∈{3,12,200}x \in \{3, 12, 200\}:

  • x & xx \,\&\, x, x∣xx \mid x, x+0x + 0 and xx all have the signature (3,12,200)(3, 12, 200), and only xx is kept;
  • up to size 6, 193 of the 1,100 generated programs survive.

The pruning compounds. Every discarded program would have been combined into countless bigger ones.

Is it sound? For the question “find a program consistent with the examples”, yes. Any program built from a discarded pp has a twin built from the kept p′p' with the same signature.

Is it complete for correctness? No. Two programs may agree on the examples and differ elsewhere:

  • −∼(x⊕1)-{\sim}(x \oplus 1) (that is, (x⊕1)+1(x \oplus 1) + 1) and x∣−∼1x \mid -{\sim}1 (that is, x∣2x \mid 2) both map 3,12,2003, 12, 200 to 3,14,2023, 14, 202;
  • but at x=1x = 1 they give 1 and 3.

The enumerator may keep the wrong one. CEGIS repairs exactly this: the verifier’s counterexample becomes an example, and the next enumeration keeps both twins apart.


4. CEGIS: the verifier as teacher

4.1 The loop

The two sides. CEGIS (Solar-Lezama et al. 2006) splits ∃f ∀xˉ\exists f\, \forall \bar x into two quantifier-free questions:

E := {an initial input}
repeat:
    SYNTHESIZE: f := the smallest program in G with φ(e, f(e)) for every e in E       (∃f, finitely many e)
    VERIFY:     is ¬φ(x, f(x)) satisfiable?                                         (∃x, f fixed)
                UNSAT -> return f (with the DRUP proof that no counterexample exists)
                SAT   -> the model is a counterexample input c;  E := E ∪ {c}
  • Synthesizer: enumeration. It never sees a quantifier.
  • Verifier: bit-blasting plus CDCL. It never sees an unknown function.

The connection to Lecture 17. This is model-based quantifier instantiation, for functions: the verifier finds the instance of ∀xˉ\forall \bar x that the current candidate violates.

4.2 Results

Script 01, Part 2:

specificationprogram foundsizeroundsprograms generatedcertificate
turn off rightmost 1x & ~-x54261DRUP ok + exhaustive
isolate rightmost 1x & -x43120DRUP ok + exhaustive
right-propagate rightmost 1x | ~-x54346DRUP ok + exhaustive
isolate rightmost 0~x & -~x641,049DRUP ok + exhaustive
average without overflow(x & y) + ((x ^ y) >> 1)97253,748DRUP ok + exhaustive
absolute value(x >> 7) + (x ^ (x >>s x))97162,713DRUP ok + exhaustive
signed max (relational)(x <s y ? y : x)6347DRUP ok + exhaustive
signed min (relational)(x <s y ? x : y)6373DRUP ok + exhaustive

Every answer is checked twice.

  • The final verification is UNSAT, with a checked DRUP proof.
  • An exhaustive run over all 282^8 or 2162^{16} inputs agrees, using no solver at all.

The smallest program is not always the textbook one.

  • x & ∼−xx \,\&\, {\sim}{-x} is x & (x−1)x \,\&\, (x - 1), because ∼−x=x−1{\sim}{-x} = x - 1 in two’s complement (Exercise 2).
  • For the absolute value the enumerator found (x≫7)+(x⊕(x≫sx))(x \gg 7) + (x \oplus (x \gg_s x)). It shifts xx by itself, using SMT-LIB’s rule that a shift by ≥w\ge w fills with the sign bit (Exercise 3). It is correct on all 256 inputs, and nobody would write it.

Specifications define correctness, not readability. To get readable programs, restrict the grammar (no variable shift amounts) or use a sketch (§5).

4.3 One run

Script 01, Part 3, traces the average:

round 1: x                               -- counterexample x = 0, y = 128
round 2: y >> 1                          -- counterexample x = 128, y = 0
round 3: (x + y) >> 1                    -- counterexample x = 128, y = 128        (the overflow of Lecture 16)
round 4: (x >> 1) + (y >> 1)             -- counterexample x = 223, y = 95         (both odd: a lost carry)
round 5: x + ((y >> 1) - (x >> 1))       -- counterexample x = 241, y = 204
round 6: y + ((x >> 1) - (y >> 1))       -- counterexample x = 204, y = 241
round 7: (x & y) + ((x ^ y) >> 1)        -- verified

Each counterexample is chosen by the solver to break the current candidate. Seven examples pin down a function on 65,536 inputs.

4.4 Why it converges quickly in practice

Script 01, Part 4, compares counterexamples with random examples. The table shows, of 5 random example sets of each size, how many led to a correct program:

specification124816CEGIS: examples used
turn off rightmost 13/53/54/55/55/54
isolate rightmost 13/54/55/55/55/53
right-propagate rightmost 13/53/54/55/55/54
isolate rightmost 00/52/53/53/55/54
signed max0/54/55/55/55/53

Random examples need luck. They rarely hit the corner cases where small candidates differ: 0, 128, the sign bit, ties. CEGIS needs 3 or 4 examples because each one is targeted.

There is no general bound. A single counterexample can rule out only one candidate, so the worst case is one round per wrong candidate. In practice small programs are separated by few inputs, and the smallest-first order means the true answer is reached early.

Pruning inside CEGIS (Part 5): on the small benchmarks, the unpruned enumeration generates up to about five times more programs per run (1,346 against 261 for the rightmost-bit benchmark).


5. Sketching: the solver fills holes

5.1 Holes as selectors

A sketch (Solar-Lezama) is a program with holes: unknown constants or operator choices. The programmer supplies the shape. For the average:

(x  OP1  y)+((x  OP2  y)≫C),OP1,OP2∈{&,∣,⊕,+}, C∈{0,1,2,3}(x \;\mathit{OP1}\; y) + ((x \;\mathit{OP2}\; y) \gg C),\qquad \mathit{OP1}, \mathit{OP2} \in \{\&, \mid, \oplus, +\},\ C \in \{0, 1, 2, 3\}

Holes as selectors. Each hole becomes a small bit-vector selector. An operator hole becomes an if-then-else over its choices. Filling the holes so that the sketch meets the specification on the examples is a quantifier-free formula: one SAT call. So the solver is on both sides of CEGIS (script 02, Part 1):

round 1: OP1 = and, OP2 = and, C = 0  ->  (x & y) + ((x & y) >> 0)   -- counterexample x = 0, y = 128
round 2: OP1 = and, OP2 = xor, C = 1  ->  (x & y) + ((x ^ y) >> 1)   -- verified (DRUP ok; exhaustive ok)

The absolute value. The sketch (x OP1 (x≫sC)) OP2 (x≫sC)(x\ \mathit{OP1}\ (x \gg_s C))\ \mathit{OP2}\ (x \gg_s C) is filled in 4 rounds as (x+(x≫s7))⊕(x≫s7)(x + (x \gg_s 7)) \oplus (x \gg_s 7), the other textbook branch-free form.

5.2 Proving a sketch impossible

Restrict the average sketch’s operators to &\& and ∣\mid (script 02, Part 2):

round 1: OP1 = and, OP2 = and, C = 0  -> ... -- counterexample x = 0, y = 128
round 2: OP1 = and, OP2 = or,  C = 1  -> ... -- counterexample x = 128, y = 254
round 3: no hole values fit the 3 examples -- the sketch cannot do it        (UNSAT, DRUP ok)

The UNSAT answer is a proof of impossibility. Every example is an input the specification constrains, so no completion of the sketch can be correct. Enumeration can only report “nothing up to size nn”.

5.3 Why loop? Expanding the ∀

Expansion. Over ww-bit inputs the ∀\forall ranges over a finite set, so it can be expanded: one constraint per input, and a single SAT call. This is Herbrand instantiation over a finite universe (Lecture 17). Script 02, Part 3:

problemmethodinstances of ∀xclausesprogram
absolute value (8 bits)CEGIS4 examples304 (last check)(x + (x >>s 7)) ^ (x >>s 7)
expand ∀256 constraints162,210the same
average (4 bits)CEGIS2 examples119 (last check)(x & y) + ((x ^ y) >> 1)
expand ∀256 constraints4,368the same

The answers agree, but the expansion is exponential in the input bits. It needs 65,536 constraints for the 8-bit average and 2642^{64} for two 32-bit inputs. CEGIS instantiates the ∀\forall lazily, only where a candidate fails: Lecture 17’s model-based instantiation, for programs.

5.4 Enumeration or sketching?

specificationenumeration findsroundssearchsketch findsrounds
average(x & y) + ((x ^ y) >> 1)7253,748 programsthe same2
absolute value(x >> 7) + (x ^ (x >>s x))7162,713 programs(x + (x >>s 7)) ^ (x >>s 7)4

The trade-off.

  • Enumeration needs only a grammar, and finds the smallest program. It pays with a search over hundreds of thousands of programs.
  • Sketching needs human insight into the shape. It then searches the holes symbolically, with a few small SAT calls.

Both are syntax-guided: the grammar or sketch restricts the space, the specification defines correctness, and the verifier connects them.


6. Synthesis in practice (overview)

  • SyGuS solvers. cvc5 and its predecessor CVC4 (Reynolds et al. 2015) solve SyGuS problems inside the SMT solver. They use enumeration with observational equivalence, and also quantifier instantiation on the ∃∀\exists\forall formula. EUSolver (Alur, Radhakrishna and Udupa 2017) enumerates small terms and conditions separately, then combines them by decision-tree learning (“divide and conquer”). The SyGuS competition compares such tools on a common format.
  • Programming by example. FlashFill (Gulwani 2011) synthesizes spreadsheet string transformations from a few input–output examples. Ranking chooses among the many consistent programs.
  • Superoptimization. From Massalin’s exhaustive search to STOKE’s stochastic search (Schkufza, Sharma and Aiken 2013): find the shortest or fastest code equivalent to a given one. The verifier is a bit-vector solver, exactly as here.
  • Language models as synthesizers. A model proposes code, and a verifier or test harness checks it and returns counterexamples. This is the loop of §4 with a neural generator. Lecture 19’s counterexample databases are one instance: the solver supplies the precise, minimal feedback that makes the loop converge, and the certificate.

7. The course in review

7.1 One problem per solver

Script 03 runs one small problem through every solver the course built, and checks every answer with independent code:

lecturemoduledecidesproblemanswercheck
1logic, semantic_argumentpropositional validityPeirce’s lawVALIDtruth table agrees
2cnf, resolutionresolution refutations{1,2} {1,¬2} {¬1,3} {¬1,¬3}UNSATrefutation re-checked
3proof_systemsproof-system derivationsb ⇒ c, ¬b ⇒ c, ¬crefutationevery leaf closed
4dpllSAT by DPLLthe slides’ DPLL exampleUNSATtree-like resolution proof re-checked
5cdcl, drup_checkSAT by CDCLpigeonhole PHP(5) (153 conflicts)UNSATDRUP proof checked
6–7fol, fol_semanticsfinite models (FOL)∀x ∃y q(x, y) ∧ ¬∃x q(x, x)model with 2 elementssentences evaluated in the model
7unifyunificationQ(a, f(y)) and Q(z, f(b)){y ← b, z ← a}both sides equal under σ
8proverFOL by resolutionPelletier 18PROVEDresolution proof re-checked
9mcsafety: BMC, k-induction, IC34-bit counter x += 2 never reaches 1SAFE, invariant ¬x0initiation, consecution, safety by SAT
10smtEUF in CDCL(T)g(a) = c ∧ (f(g(a)) ≠ f(c) ∨ g(a) = d) ∧ c ≠ dUNSATlemmas + DRUP checked
11simplexlinear real arithmeticx + y ≤ 3 ∧ 2x − y ≤ −5 ∧ (x > 0 ∨ y > 4)SATrational model evaluated
12lialinear integer arithmetic6a + 9b + 20c = 44 over ℕSAT a = 4, b = 0, c = 1integer model evaluated
13arraysarraysread(write(a, i, e), j) ≠ read(a, j) ∧ i ≠ jUNSATrefutation ok
13stringsstringsx·“ab” = “ba”·y ∧ |x| = 1SAT x = y = “b”model checked on the constraints
14(notes only)symbolic execution——examples checked with Lectures 12, 16
15kernelLCF proof kernelPeirce’s law as a theorem⊢ ((p ⇒ q) ⇒ p) ⇒ pproof replayed by the kernel (62 steps)
16bitvecbit-vectorsx + 1 > x (8 bits); (x ^ y) ^ y = x (32 bits)counterexample x = 255; validmodel ok; DRUP ok
17quantifiersquantifiersP(a), ∀x. P(x) ⇒ P(s(x)), ¬P(s³(a))UNSAT (3 instances)instances + lemmas + DRUP checked
18combinetheory combinationf(f(x) − f(y)) = a ∧ f(0) > a + 2 ∧ x = yUNSATper-theory lemmas + DRUP checked
19sqlcheckSQL query equivalenceMAX subquery vs ORDER BY … LIMIT 1different (2 rows)counterexample re-run on SQLite
20synthprogram synthesis⌊(x + y)/2⌋ without overflow(x & y) + ((x ^ y) >> 1)DRUP ok + all 65,536 inputs run

All 20 solvers run in about 2 seconds of CPU in total.

7.2 The thread

Unit I: propositional logic and SAT (Lectures 1–5).

  • Truth tables are exponential. Proof systems trade search for structure: tableaux, resolution, Hilbert systems.
  • DPLL searches smartly, and CDCL learns from its conflicts.
  • The SAT solver of Lecture 5 runs underneath almost everything that follows, and its UNSAT answers produce DRUP proofs that a small, separate checker replays.

Unit II: first-order logic (Lectures 6–8).

  • Quantifiers, structures and unification.
  • Undecidability bounds what any procedure can promise.
  • Resolution is refutationally complete, and Herbrand’s theorem reduces FOL to SAT, in principle.

Unit III: model checking (Lecture 9). Systems over time are SAT problems unrolled (BMC) or folded into invariants (k-induction, IC3). An invariant is a certificate checked by three SAT queries.

Unit IV: satisfiability modulo theories (Lectures 10–13).

  • CDCL(T) splits work between a SAT solver and theory solvers: congruence closure, the simplex method, branch and bound, arrays, strings.
  • Theory lemmas are re-checked by naive procedures, and models are evaluated on the input.

Unit V: programs and proofs (Lectures 14–15).

  • Symbolic execution turns programs into solver queries.
  • Proof kernels turn untrusted automation into trusted theorems.

Unit VI: more theories and their combination (Lectures 16–18).

  • Bit-vectors by bit-blasting.
  • Quantifiers by instantiation, which needs heuristics and an honest “unknown”.
  • Theories by combination: equalities between shared variables.

Unit VII: applications (Lectures 19–20).

  • Text-to-SQL checked by bounded equivalence.
  • Programs synthesized by CEGIS.
  • The solver acts as the teacher: its counterexamples drive the search.

7.3 What runs through all of it

One habit runs through the whole course. A solver is a search procedure; a certificate is the reason to believe its answer. The certificates of this course are:

  • UNSAT: a proof replayed by small code (resolution, DRUP, an LCF kernel), with theory lemmas re-checked by naive procedures;
  • SAT: a model evaluated on the original input;
  • safety: an inductive invariant checked by SAT;
  • differences: a counterexample re-run on an independent engine.

Several lectures found errors this way: in their own code, and in published examples, slides and gold queries. That is the practical case for automated reasoning with certificates.


8. Summary

  1. Synthesis is ∃f ∀xˉ. φ(xˉ,f(xˉ))\exists f\, \forall \bar x.\ \varphi(\bar x, f(\bar x)). The quantifier alternation and the space of programs make it hard. SyGuS restricts programs by a grammar.
  2. Bottom-up enumeration finds the smallest program. Observational equivalence keeps one program per signature on the examples: 193 of 1,100 up to size 6, out of 11,286 programs.
  3. CEGIS alternates a synthesizer on finitely many examples with a verifier for all inputs; counterexamples become examples. All 8 benchmarks are solved in 3–7 rounds, each certified by DRUP and by an exhaustive check.
  4. Counterexamples are targeted. CEGIS uses 3–4 examples where random examples often mislead with 1 or 2. CEGIS is lazy instantiation of ∀\forall, Lecture 17’s MBQI for programs. Expanding ∀\forall over all inputs works but is exponential in the input bits.
  5. Sketches put the solver on both sides of CEGIS: holes become selectors, and an UNSAT hole-filling call proves the sketch impossible.
  6. The course built every solver it used, from truth tables to synthesis, and every answer of every solver can be checked by independent code.

9. Common pitfalls

  • Trusting a program that fits the examples. Without a verifier, it is a guess.
  • Specifications that say too little. “out ≥ x ∧ out ≥ y” alone admits 127; a relational spec must pin down the answer.
  • Grammars that are too big or too small. Too big and enumeration drowns. Too small and the answer is not in it; a sketch makes this provable.
  • Expecting readable output. The smallest program in a grammar can be strange (x >>s x). Restrict the grammar to what you want to read.
  • Forgetting the verifier’s semantics. Shifts by ≥w\ge w, overflow, signed vs unsigned. The synthesizer will exploit every corner of the semantics the verifier uses.

10. Exercises

1. (CEGIS by hand) Run CEGIS for “isolate the rightmost 1-bit” (out=x & −x\mathit{out} = x \,\&\, {-x}) on grammar BITS, starting from E={0}E = \{0\}. Which candidates and counterexamples do you expect?

Answer

The run. The smallest program consistent with x=0↦0x = 0 \mapsto 0 is xx itself (size 1, enumerated first). The verifier refutes it with some xx that has more than one bit set; cegis reports x=192x = 192.

The next smallest program consistent with {0,192}\{0, 192\} is −x-x, since −192=64=192 & −192-192 = 64 = 192 \,\&\, {-192} on 8 bits. It is refuted by x=64x = 64, where −64=192≠64-64 = 192 \ne 64.

Then x & −xx \,\&\, {-x} (size 4) is consistent with {0,192,64}\{0, 192, 64\} and verified: three rounds, as cegis reports.

2. (two’s complement) Prove that ∼−x=x−1{\sim}{-x} = x - 1 and −∼x=x+1{-{\sim}x} = x + 1 on ww-bit vectors. Deduce that the synthesized x & ∼−xx \,\&\, {\sim}{-x} and ∼x & −∼x{\sim}x \,\&\, {-{\sim}x} are the textbook programs.

Answer

The identity. In two’s complement ∼a=−a−1{\sim}a = -a - 1 (all bits flipped is 2w−1−a2^w - 1 - a).

The two rules.

  • ∼−x=−(−x)−1=x−1{\sim}{-x} = -(-x) - 1 = x - 1.
  • −∼x=−(−x−1)=x+1{-{\sim}x} = -(-x - 1) = x + 1.

So x & ∼−x=x & (x−1)x \,\&\, {\sim}{-x} = x \,\&\, (x - 1) and ∼x & −∼x=∼x & (x+1){\sim}x \,\&\, {-{\sim}x} = {\sim}x \,\&\, (x + 1).

3. (a strange absolute value) Explain why (x≫7)+(x⊕(x≫sx))(x \gg 7) + (x \oplus (x \gg_s x)) computes ∣x∣|x| (two’s complement) on all 8-bit xx.

Answer

x≥128x \ge 128 (negative). x≫7=1x \gg 7 = 1. The shift amount x≥8x \ge 8, so x≫sxx \gg_s x fills with the sign bit: all ones. Then x⊕0xFF=∼xx \oplus 0xFF = {\sim}x, and ∼x+1=−x{\sim}x + 1 = -x.

8≤x<1288 \le x < 128. The shift fills with the sign bit 0, so x⊕0=xx \oplus 0 = x, plus 0.

1≤x<81 \le x < 8. x≫sx=x≫x=0x \gg_s x = x \gg x = 0, because x<2xx < 2^x. The result is xx.

x=0x = 0. The result is 0. The exhaustive check confirms all 256 cases.

4. (observational equivalence) With examples {3,12,200}\{3, 12, 200\}, show that −∼(x⊕1)-{\sim}(x \oplus 1) and x∣−∼1x \mid -{\sim}1 have the same signature but are different functions. What does CEGIS do if the enumerator keeps the wrong one?

Answer

The two functions. −∼a=a+1-{\sim}a = a + 1, so the first is (x⊕1)+1(x \oplus 1) + 1. The second is x∣2x \mid 2.

The same signature. On 3, 12, 200 both give 3, 14, 202: 3 is odd, so 3⊕1=23 \oplus 1 = 2 and 2+1=3=3∣22 + 1 = 3 = 3 \mid 2; 12 and 200 are even, so x⊕1=x+1x \oplus 1 = x + 1, plus 1, equals x+2=x∣2x + 2 = x \mid 2 because bit 1 is 0.

Different functions. At x=1x = 1 they give 1 and 3.

What CEGIS does. If the kept one is wrong, the verifier returns a distinguishing input, for example 1, and the next enumeration separates them.

5. (an impossible sketch) For the average sketch with OP1,OP2∈{&,∣}\mathit{OP1}, \mathit{OP2} \in \{\&, \mid\} and C∈0..3C \in 0..3, check that every one of the 16 completions fails on one of the inputs (0,128)(0, 128) or (128,254)(128, 254).

Answer

On (0,128)(0, 128) the average is 64, and x & y=0x \,\&\, y = 0, x∣y=128x \mid y = 128.

  • OP1=∣\mathit{OP1} = \mid gives 128+…≥128128 + \ldots \ge 128: all 8 such completions fail.
  • With OP1=&\mathit{OP1} = \&, the result is 0+(⋅≫C)0 + (\cdot \gg C). OP2=&\mathit{OP2} = \& gives 0, which fails for every CC. OP2=∣\mathit{OP2} = \mid gives 128≫C128 \gg C, which is 64 only for C=1C = 1.

The survivor is (x & y)+((x∣y)≫1)(x \,\&\, y) + ((x \mid y) \gg 1). On (128,254)(128, 254) it gives 128+(254≫1)=128+127=255128 + (254 \gg 1) = 128 + 127 = 255, while the average is 191.

This matches the script’s run, and the final UNSAT call is the solver’s proof of the same fact.

6. (expansion vs CEGIS) How many constraints does expanding ∀\forall need for kk inputs of ww bits? For which sizes is expansion still reasonable?

Answer

The count. 2wk2^{wk}: 256 for one 8-bit input or two 4-bit inputs, 65,536 for two 8-bit inputs, 2642^{64} for two 32-bit inputs.

When it is reasonable. Each constraint copies the sketch’s circuit: 162,210 clauses already for the 8-bit absolute value. Expansion is reasonable up to a few thousand instances. Beyond that only lazy instantiation (CEGIS) works.

7. (specifications) Weaken the maximum’s specification to out≥sx∧out≥sy\mathit{out} \ge_s x \wedge \mathit{out} \ge_s y, dropping out=x∨out=y\mathit{out} = x \vee \mathit{out} = y. What does CEGIS return with grammar CHOICE, and what if the constant 127 is added to the grammar?

Answer

With CHOICE. The constants are only 0 and 1, and there is no arithmetic, so no constant is ≥s\ge_s every input. CEGIS returns the maximum (x<sy ? y:x)(x <_s y\ ?\ y : x) after 3 rounds: xx and yy are refuted first, by (0,64)(0, 64) and (0,128)(0, 128).

With 127 in the grammar. The third round returns the constant 127, which is ≥s\ge_s every 8-bit signed value, and it is verified. The weakened specification was satisfied, but not as intended.

The lesson. A specification that leaves freedom invites the synthesizer to use it. Both runs were made with cegis.

8. (programming) Add max of three with a relational specification to BENCHMARKS (grammar CHOICE). How far does enumeration get? Then write a sketch ite(x CMP1 y, ite(…),ite(…))\mathrm{ite}(x\ \mathit{CMP1}\ y,\ \mathrm{ite}(\ldots), \mathrm{ite}(\ldots)) and compare.

Answer sketch

Enumeration. The smallest max-of-three program has two nested if-then-else levels, 16 nodes. Expect enumeration with observational equivalence to slow down sharply: it must build every distinct condition and branch up to that size.

The sketch. It fixes the nesting and leaves only the comparisons and branches as holes: a few SAT calls. This is the typical case where a human’s shape makes synthesis feasible.

9. (programming) Implement EUSolver’s divide-and-conquer idea for CHOICE. Enumerate small terms until every example is covered by some term that is correct on it. Enumerate small conditions. Combine them into an if-then-else that sends each example to a correct term. Test it on signed max and min.

Answer sketch

What the two enumerations find. Terms xx and yy each cover part of the examples. The condition x<syx <_s y separates the two parts.

The combination. The resulting decision tree ite(x<sy,y,x)\mathrm{ite}(x <_s y, y, x) is found without enumerating if-then-else terms at all. The verifier then checks it as usual.


11. Further reading

  • A. Solar-Lezama, L. Tancau, R. Bodík, S. Seshia, V. Saraswat, “Combinatorial Sketching for Finite Programs”, ASPLOS 2006; A. Solar-Lezama, Program Synthesis by Sketching, PhD thesis, UC Berkeley, 2008.
  • R. Alur, R. Bodík, G. Juniwal, M. M. K. Martin, M. Raghothaman, S. A. Seshia, R. Singh, A. Solar-Lezama, E. Torlak, A. Udupa, “Syntax-Guided Synthesis”, FMCAD 2013.
  • A. Udupa, A. Raghavan, J. V. Deshmukh, S. Mador-Haim, M. M. K. Martin, R. Alur, “TRANSIT: Specifying Protocols with Concolic Snippets”, PLDI 2013.
  • A. Albarghouthi, S. Gulwani, Z. Kincaid, “Recursive Program Synthesis”, CAV 2013.
  • R. Alur, A. Radhakrishna, A. Udupa, “Scaling Enumerative Program Synthesis via Divide and Conquer”, TACAS 2017.
  • S. Jha, S. Gulwani, S. A. Seshia, A. Tiwari, “Oracle-Guided Component-Based Program Synthesis”, ICSE 2010.
  • A. Reynolds, M. Deters, V. Kuncak, C. Tinelli, C. Barrett, “Counterexample-Guided Quantifier Instantiation for Synthesis in SMT”, CAV 2015.
  • S. Gulwani, “Automating String Processing in Spreadsheets Using Input-Output Examples”, POPL 2011.
  • H. Massalin, “Superoptimizer: A Look at the Smallest Program”, ASPLOS 1987; E. Schkufza, R. Sharma, A. Aiken, “Stochastic Superoptimization”, ASPLOS 2013.
  • Z. Manna, R. Waldinger, “A Deductive Approach to Program Synthesis”, ACM TOPLAS 2(1), 1980.
  • H. S. Warren, Hacker’s Delight, 2nd ed., 2012.
  • S. Gulwani, O. Polozov, R. Singh, “Program Synthesis”, Foundations and Trends in Programming Languages 4(1–2), 2017 (a survey).
← 返回课程目录