Algorithm Search⌘K

Data structureadvanced

Version space algebra

Also called version space.

A shared DAG of union and join nodes that stores all programs consistent with some examples, often exponentially many in polynomial space, with intersection and counting.

Time
O(s^2 d^2) expected buildO(e) countO(e^2) expected intersect
Space
O(s^2 d^2) buildO(e^2) intersect
Where
d = the largest number of distinct outputs of programs of one size on the example input; e = the number of nodes and edges of the larger operand; s = the size bound on programs
Origin
Tessa Lau, Pedro Domingos, Daniel S. Weld, 2000

A version space algebra (VSA) stores the set of all programs that agree with some examples, in a language given by a grammar. It is a shared graph with two kinds of inner nodes. A union node holds the programs of any of its kids, and a join node holds every program that applies one operator to a program from each kid. Because the kids are shared, a graph with a few hundred nodes can hold millions of programs. Synthesizers for programming by example build one VSA for each example, intersect them, and then count, rank or list the programs. This page is about the data structure; string transformation synthesis is one algorithm that uses it.

In plain words

Suppose that the answer must be "something plus something". You do not need to write every full answer. You can write one box of choices for the left side and one box for the right side. Two boxes with ten choices each stand for a hundred answers.

A version space algebra does this again and again, at every level of the program. Boxes can be shared, so the same box of small programs is used in many places. The whole structure stays small while it stands for a huge number of programs.

When a second example arrives, the tool keeps only the programs that fit both examples. It does this box by box, and it never lists the programs one by one. At the end it can count the programs, pick the best one, or show a few of them.

The abstract type

A version space NN stands for a finite set R(N)R(N) of programs. The operations are:

  • BUILD(i,o,S)(i, o, S): a version space for all programs of size at most SS whose output on the input ii is oo.
  • INTERSECT(a,b)(a, b): a version space for R(a)∩R(b)R(a) \cap R(b).
  • COUNT(n)(n): the number ∣R(n)∣|R(n)|, without listing the programs.
  • BEST(n)(n): a program of R(n)R(n) with the best rank, for a rank that is computed from the ranks of the parts.
  • LIST(n)(n): all programs of R(n)R(n), one at a time.

With examples (i1,o1),…,(ik,ok)(i_1, o_1), \ldots, (i_k, o_k), the set of consistent programs is

V=R(BUILD(i1,o1,S))∩⋯∩R(BUILD(ik,ok,S)).V = R(\mathrm{BUILD}(i_1, o_1, S)) \cap \cdots \cap R(\mathrm{BUILD}(i_k, o_k, S)).

Representation

A VSA is a directed acyclic graph with three kinds of nodes:

  • LEAF(A)(A), with R=AR = A, a finite set of programs without parts, such as variables and constants.
  • UNION(k1,…,kr)(k_1, \ldots, k_r), with R=R(k1)∪⋯∪R(kr)R = R(k_1) \cup \cdots \cup R(k_r).
  • JOIN(op,a,b)(\mathit{op}, a, b), with R={op(p,q):p∈R(a),q∈R(b)}R = \{ \mathit{op}(p, q) : p \in R(a), q \in R(b) \}. Operators with other arities have one kid for each argument.

EMPTY is the union with no kids. The constructors never build another node with an empty set: a join with an EMPTY kid is EMPTY, and a union drops EMPTY kids. A union with one kid is the kid itself.

A union is disjoint when its kids have pairwise disjoint sets. All unions built below are disjoint, and this makes COUNT exact.

The language on this page, and in the code, is

E→x∣y∣1∣2∣E+E∣E−E∣E×EE \to x \mid y \mid 1 \mid 2 \mid E + E \mid E - E \mid E \times E

over pairs of integers (x,y)(x, y). The size of a program is the number of nodes of its tree, so it is odd. There are 44, 4848, 11521152 and 3456034560 programs of size 11, 33, 55 and 77.

Operations

  1. BUILD(i, o, S) ▷ all programs of size at most S with output o on input i
  2. 1for each terminal t: add t to T[value of t on i]
  3. 2vals[1] ← the keys of T
  4. 3for s = 3, 5, …, S do
  5. 4for each split s1 + s2 = s - 1, a ∈ vals[s1], b ∈ vals[s2], op ∈ {+, -, ×} do
  6. 5append (op, s1, a, b) to how[s][op(a, b)]
  7. 6vals[s] ← the keys of how[s]
  8. 7return UNION(NODE(s, o) for each odd s ≤ S with o ∈ vals[s])
  9. NODE(s, v) ▷ memoized: one node for each pair (s, v)
  10. 8if s = 1 then return LEAF(T[v])
  11. 9return UNION(JOIN(op, NODE(s1, a), NODE(s - 1 - s1, b)) for each (op, s1, a, b) in how[s][v])
  12. INTERSECT(a, b) ▷ memoized on the pair of nodes
  13. 10if a = EMPTY or b = EMPTY then return EMPTY
  14. 11if a = UNION(k1, …, kr) then return UNION(INTERSECT(kj, b) for j = 1 … r)
  15. 12if b = UNION(k1, …, kr) then return UNION(INTERSECT(a, kj) for j = 1 … r)
  16. 13if a = LEAF(A) and b = LEAF(B) then return LEAF(A ∩ B)
  17. 14if a = JOIN(op, a1, a2) and b = JOIN(op, b1, b2) then return JOIN(op, INTERSECT(a1, b1), INTERSECT(a2, b2))
  18. 15return EMPTY ▷ a leaf and a join, or two joins with different operators
  19. COUNT(n) ▷ memoized
  20. 16if n = LEAF(A) then return |A|
  21. 17if n = UNION(k1, …, kr) then return COUNT(k1) + … + COUNT(kr)
  22. 18if n = JOIN(op, a, b) then return COUNT(a) · COUNT(b)

BUILD. Lines L1 to L6 run forward over sizes. They compute, for each size, the set of outputs that programs of that size can have on the input ii, and for each output, the ways to get it from two smaller outputs. This is dynamic programming over pairs (size, output), with memoization of the nodes. Line L9 makes one union for each pair, with one join for each way. The node NODE(s,v)(s, v) is made once and shared by every join that needs a program of size ss with output vv. Line L7 joins the sizes up to SS.

INTERSECT. Lines L11 and L12 push the intersection into the kids of a union. Line L14 is the key step: two joins with the same operator meet in a join of the pairwise intersections, because two trees with the same root are equal exactly when their subtrees are equal. The memo table makes each pair of nodes cost one call.

COUNT, BEST and LIST. COUNT adds over unions and multiplies over joins. BEST works the same way with the rule "best of the kids" at a union and "combine the best parts" at a join. This is exact when the rank of op(p,q)\mathit{op}(p, q) grows with the ranks of pp and qq, as size does. LIST walks the graph and yields the programs one by one.

Other ways to build. FlashFill and FlashMeta build the VSA top-down from the output. A witness function for an operator gives, from the wanted output, the outputs that its arguments must have, for example all ways to split a string into a prefix and a suffix for concatenation. This needs no forward table of values and works for infinite value domains, but it needs one witness function for each operator. The forward method above needs only the semantics.

Example

Take the examples (1,2)↦3(1, 2) \mapsto 3, (2,1)↦3(2, 1) \mapsto 3 and (0,0)↦0(0, 0) \mapsto 0, and the size bound S=3S = 3.

The first example. On (x,y)=(1,2)(x, y) = (1, 2), the terminals have the outputs x=1x = 1, y=2y = 2, 1=11 = 1, 2=22 = 2, so T[1]={x,1}T[1] = \{x, 1\} and T[2]={y,2}T[2] = \{y, 2\}. No terminal has the output 3. Of size 3, the output 3 comes only from 1+21 + 2 and 2+12 + 1. So

V1=UNION(JOIN(+,{x,1},{y,2}), JOIN(+,{y,2},{x,1})),V_1 = \mathrm{UNION}(\mathrm{JOIN}(+, \{x, 1\}, \{y, 2\}),\ \mathrm{JOIN}(+, \{y, 2\}, \{x, 1\})),

which holds 2⋅2+2⋅2=82 \cdot 2 + 2 \cdot 2 = 8 programs with 5 nodes.

The second example. On (2,1)(2, 1), T[1]={y,1}T[1] = \{y, 1\} and T[2]={x,2}T[2] = \{x, 2\}, and

V2=UNION(JOIN(+,{y,1},{x,2}), JOIN(+,{x,2},{y,1})).V_2 = \mathrm{UNION}(\mathrm{JOIN}(+, \{y, 1\}, \{x, 2\}),\ \mathrm{JOIN}(+, \{x, 2\}, \{y, 1\})).

The intersection. Lines L11 and L12 give four pairs of joins. All have the operator ++, so line L14 intersects the leaves:

join of V1V_1 join of V2V_2 result
{x,1}+{y,2}\{x, 1\} + \{y, 2\} {y,1}+{x,2}\{y, 1\} + \{x, 2\} 1+21 + 2
{x,1}+{y,2}\{x, 1\} + \{y, 2\} {x,2}+{y,1}\{x, 2\} + \{y, 1\} x+yx + y
{y,2}+{x,1}\{y, 2\} + \{x, 1\} {y,1}+{x,2}\{y, 1\} + \{x, 2\} y+xy + x
{y,2}+{x,1}\{y, 2\} + \{x, 1\} {x,2}+{y,1}\{x, 2\} + \{y, 1\} 2+12 + 1

COUNT gives 4. The third example has T[0]={x,y}T[0] = \{x, y\} and keeps only x+yx + y and y+xy + x, because 1+21 + 2 and 2+12 + 1 output 3 on (0,0)(0, 0).

Growth. The code builds the VSA of the single example (1,2)↦3(1, 2) \mapsto 3 for larger bounds. The number of programs grows much faster than the graph:

bound SS programs nodes edges
5 144 26 59
7 3,552 103 267
9 98,816 282 775
11 3,071,552 653 1,850
13 102,003,648 1,315 3,789

Here a leaf counts its programs as edges. With all three examples and S=9S = 9, the intersection holds 7,284 programs in 1,098 nodes, and BEST returns x+yx + y.

Correctness

The proof is in proofs/correctness.md. By induction on the size, NODE(s,v)(s, v) holds exactly the programs of size ss with output vv, and its unions are disjoint, because two ways to get vv differ in the operator, in the size of the left part or in the output of a part. INTERSECT is correct by induction on the two graphs, with line L14 as the main case, and it keeps unions disjoint. COUNT is then exact: the sum is right for disjoint unions, and the product is right because (p,q)↦op(p,q)(p, q) \mapsto \mathit{op}(p, q) is one to one. So the intersection of the BUILD results for all examples holds exactly the consistent programs up to the bound.

Proof: BUILD, INTERSECT and COUNT give exactly the consistent programs and their numberfull

Setting. Programs are the trees of the language E→x∣y∣1∣2∣E+E∣E−E∣E×EE \to x \mid y \mid 1 \mid 2 \mid E + E \mid E - E \mid E \times E. The size ∣P∣|P| of a program is its number of nodes. Two programs are equal when their trees are equal. The set R(n)R(n) represented by a node nn is defined by R(LEAF(A))=AR(\mathrm{LEAF}(A)) = A, R(UNION(k1,…,kr))=R(k1)∪⋯∪R(kr)R(\mathrm{UNION}(k_1, \ldots, k_r)) = R(k_1) \cup \cdots \cup R(k_r) and R(JOIN(op,a,b))={op(p,q):p∈R(a),q∈R(b)}R(\mathrm{JOIN}(\mathit{op}, a, b)) = \{ \mathit{op}(p, q) : p \in R(a), q \in R(b) \}. EMPTY is the union with no kids, so R(EMPTY)=∅R(\mathrm{EMPTY}) = \emptyset. A node is disjoint when every union node below it, itself included, has kids with pairwise disjoint sets. Line numbers refer to the pseudocode on the page.

Lemma 1: the values

Claim. After line L6, for each odd s≤Ss \le S, vals[s]={[ ⁣[P] ⁣](i):∣P∣=s}\mathit{vals}[s] = \{ [\![P]\!](i) : |P| = s \}, and for each vv, how[s][v]\mathit{how}[s][v] holds exactly the tuples (op,s1,a,b)(\mathit{op}, s_1, a, b) with s1+s2=s−1s_1 + s_2 = s - 1, a∈vals[s1]a \in \mathit{vals}[s_1], b∈vals[s2]b \in \mathit{vals}[s_2] and op(a,b)=v\mathit{op}(a, b) = v.

Proof. By induction on ss. For s=1s = 1 the programs are the terminals, and line L1 puts each one under its value. For s≥3s \ge 3, a program of size ss is op(p,q)\mathit{op}(p, q) with ∣p∣+∣q∣=s−1|p| + |q| = s - 1, and its value is op([ ⁣[p] ⁣](i),[ ⁣[q] ⁣](i))\mathit{op}([\![p]\!](i), [\![q]\!](i)). By the hypothesis, the values of pp and qq range exactly over vals[∣p∣]\mathit{vals}[|p|] and vals[∣q∣]\mathit{vals}[|q|], and line L4 tries every split, every pair of values and every operator. So the keys of how[s]\mathit{how}[s] are exactly the values of programs of size ss. □\square

Lemma 2: BUILD

Claim. For each odd s≤Ss \le S and each v∈vals[s]v \in \mathit{vals}[s], NODE(s,v)(s, v) is not EMPTY, it is disjoint, and

R(NODE(s,v))={P:∣P∣=s, [ ⁣[P] ⁣](i)=v}.R(\mathrm{NODE}(s, v)) = \{ P : |P| = s,\ [\![P]\!](i) = v \}.

Proof. By induction on ss. For s=1s = 1, line L8 returns the leaf of the terminals with value vv, and the set is not empty because v∈vals[1]v \in \mathit{vals}[1].

For s≥3s \ge 3, take a program P=op(p,q)P = \mathit{op}(p, q) of size ss with value vv. Let s1=∣p∣s_1 = |p|, a=[ ⁣[p] ⁣](i)a = [\![p]\!](i) and b=[ ⁣[q] ⁣](i)b = [\![q]\!](i). By Lemma 1 the tuple (op,s1,a,b)(\mathit{op}, s_1, a, b) is in how[s][v]\mathit{how}[s][v], and by the hypothesis p∈R(NODE(s1,a))p \in R(\mathrm{NODE}(s_1, a)) and q∈R(NODE(s−1−s1,b))q \in R(\mathrm{NODE}(s - 1 - s_1, b)). So PP is in the set of the join that line L9 builds for this tuple. In the other direction, each join of line L9 holds programs op(p,q)\mathit{op}(p, q) with ∣p∣=s1|p| = s_1, ∣q∣=s−1−s1|q| = s - 1 - s_1, [ ⁣[p] ⁣](i)=a[\![p]\!](i) = a and [ ⁣[q] ⁣](i)=b[\![q]\!](i) = b. Such a program has size ss and value op(a,b)=v\mathit{op}(a, b) = v. The kids of the join are not EMPTY by the hypothesis, so the join is not EMPTY, and how[s][v]\mathit{how}[s][v] is not empty by Lemma 1.

Disjointness: two different tuples of how[s][v]\mathit{how}[s][v] differ in the operator, in s1s_1, or in aa or bb. Programs from the two joins then differ in the root symbol, in the size of the left subtree, or in the value of one subtree. In each case they are different trees. The kids are disjoint by the hypothesis. □\square

Corollary. BUILD(i,o,S)(i, o, S) represents exactly the programs of size at most SS with output oo on ii. Line L7 joins the nodes of different sizes, whose sets are disjoint. If no program has output oo, the union has no kids and BUILD returns EMPTY.

Lemma 3: INTERSECT

Claim. For all nodes aa and bb, R(INTERSECT(a,b))=R(a)∩R(b)R(\mathrm{INTERSECT}(a, b)) = R(a) \cap R(b). If aa and bb are disjoint, the result is disjoint.

Proof. By induction on the sum of the heights of aa and bb in their DAGs. The memo table returns a result computed earlier for the same pair, so it does not change the result.

  • Line L10: one set is empty.
  • Line L11: R(a)∩R(b)=⋃j(R(kj)∩R(b))R(a) \cap R(b) = \bigcup_j (R(k_j) \cap R(b)), and each kjk_j is lower than aa. Each new kid is a subset of R(kj)R(k_j), so the kids stay pairwise disjoint.
  • Line L12: the same with the roles swapped. The new kids are subsets of the pairwise disjoint sets R(kj)R(k_j), so they are disjoint.
  • Line L13: both sets are explicit.
  • Line L14: a tree op(p,q)\mathit{op}(p, q) is in both sets if and only if p∈R(a1)∩R(b1)p \in R(a_1) \cap R(b_1) and q∈R(a2)∩R(b2)q \in R(a_2) \cap R(b_2), because two trees with the same root are equal exactly when their subtrees are equal.
  • Line L15: a leaf holds only terminals and a join only compound trees, and two joins with different operators hold trees with different roots. So the intersection is empty.

Unions are made only at lines L11 and L12, and their kids are disjoint, as shown. Other unions in the result come from recursive calls, and they are disjoint by the hypothesis. □\square

The recursion stops: each call goes down at least one edge in aa or in bb, and the DAGs have no cycles.

Lemma 4: COUNT

Claim. For a disjoint node nn, COUNT(n)=∣R(n)∣(n) = |R(n)|.

Proof. By induction on the height. A leaf has ∣A∣|A| programs. The kids of a disjoint union have disjoint sets, so the size of the union is the sum. For a join, the map (p,q)↦op(p,q)(p, q) \mapsto \mathit{op}(p, q) from R(a)×R(b)R(a) \times R(b) is one to one, so the size is the product. □\square

Theorem

For examples (i1,o1),…,(ik,ok)(i_1, o_1), \ldots, (i_k, o_k) and a size bound SS, the node

INTERSECT(…INTERSECT(BUILD(i1,o1,S),BUILD(i2,o2,S))…,BUILD(ik,ok,S))\mathrm{INTERSECT}(\ldots \mathrm{INTERSECT}(\mathrm{BUILD}(i_1, o_1, S), \mathrm{BUILD}(i_2, o_2, S)) \ldots, \mathrm{BUILD}(i_k, o_k, S))

represents exactly the programs of size at most SS that are consistent with all kk examples, and COUNT gives their number.

Proof. By the corollary of Lemma 2, each BUILD represents the programs consistent with its example. By Lemma 3, applied k−1k - 1 times, the result represents the intersection of these sets, and it is disjoint. Lemma 4 gives the count. □\square

Size of the structure

Claim. Let dd be the largest ∣vals[s]∣|\mathit{vals}[s]|. BUILD makes at most S+12d\frac{S+1}{2} d nodes of the form NODE(s,v)(s, v), and at most 3(S+12)2d23 \bigl(\frac{S+1}{2}\bigr)^2 d^2 join nodes. A chain of kk joins over one leaf with two terminals represents 2k+12^{k+1} programs with k+1k + 1 nodes.

Proof. There is one NODE(s,v)(s, v) for each odd ss and each v∈vals[s]v \in \mathit{vals}[s], by the memo table. Each join comes from one tuple of how\mathit{how}, and there are at most S+12\frac{S+1}{2} splits, d2d^2 pairs of values and 3 operators for each odd ss. For the chain, let LL be the leaf {x,y}\{x, y\}, J0=LJ_0 = L and Jt=JOIN(+,L,Jt−1)J_{t} = \mathrm{JOIN}(+, L, J_{t-1}). Then ∣R(Jt)∣=2⋅∣R(Jt−1)∣|R(J_t)| = 2 \cdot |R(J_{t-1})| by Lemma 4, so ∣R(Jk)∣=2k+1|R(J_k)| = 2^{k+1}, and the DAG has the nodes L,J1,…,JkL, J_1, \ldots, J_k. □\square

Complexity

Let ss be the size bound, dd the largest number of different outputs of the programs of one size on the input, and ee the number of nodes and edges of a version space.

  • BUILD. There is one node NODE(s′,v)(s', v) for each odd size s′≤ss' \le s and each output vv, so at most s+12d\frac{s+1}{2} d union nodes. Each join comes from one split, one pair of outputs and one operator, so there are at most 3(s+12)2d23 \bigl(\frac{s+1}{2}\bigr)^2 d^2 joins. With a hash table, the time is O(s2d2)O(s^2 d^2) expected.
  • INTERSECT. Each pair of nodes is handled once. A pair with a union costs the number of kids, and a pair of joins costs a constant. The total is O(eaeb)O(e_a e_b), which is O(e2)O(e^2) for the larger operand. The result can have this many nodes, so intersecting kk examples one after the other can grow like a product. In practice most pairs are empty.
  • COUNT and BEST. One pass over the graph, O(e)O(e) arithmetic operations. The counts are big integers with O(s)O(s) digits, because there are at most csc^s programs of size at most ss for some constant cc.
  • Compactness. A version space can hold exponentially more programs than it has nodes. A chain Jk=JOIN(+,L,Jk−1)J_k = \mathrm{JOIN}(+, L, J_{k-1}) over the leaf L={x,y}L = \{x, y\}, with J0=LJ_0 = L, holds 2k+12^{k+1} programs with k+1k + 1 nodes. The table above shows the same effect for a real example.

The bound on dd depends on the language. Here dd is at most the number of programs of one size, but it is far smaller in practice, because most outputs are reached in many ways. Over the integers, dd can grow quickly when multiplication is allowed. FlashFill keeps dd small because every value is a substring or a position of the given strings.

Variants

  • Mitchell's version spaces. The first version spaces were sets of hypotheses ordered from specific to general. Mitchell (1982) stores such a set by its two boundary sets: SS, the most specific consistent hypotheses, and GG, the most general ones. The candidate elimination algorithm updates SS and GG for each positive or negative example. This needs a partial order of generality on the hypotheses; a version space algebra needs none.
  • Composite version spaces. Lau, Domingos and Weld (2000, 2003) build version spaces of programs from smaller version spaces by union and join, with a transform that maps the hypotheses of one space into another. They used them to learn text edits from demonstrations in SMARTedit.
  • FlashFill and FlashMeta. Gulwani (2011) stores all consistent string programs in a graph of this kind and intersects the graphs of the examples. Polozov and Gulwani (2015) give the general form with union and join nodes and witness functions, for any domain-specific language.
  • Cycles. Without a size bound, a recursive grammar can give infinite sets. A graph with cycles can represent them, as a context-free grammar does, but COUNT and LIST then need a bound.
  • Close structures. A shared packed parse forest stores all parse trees of one string in the same way, with union nodes for the choices and packed nodes for the parts. An e-graph stores classes of equal terms, not of terms with a fixed output. A binary decision diagram shares subgraphs to store a Boolean function.

When to use it

Use a VSA when the language is a small domain-specific language, each operator can be inverted or the outputs of small programs can be listed, and the user wants all consistent programs, not just one. It is the right choice when the examples arrive one at a time, when the tool must rank many candidates, or when it must find an input on which two candidates disagree. For a single smallest program in a language with large or infinite value domains, bottom-up enumerative synthesis is simpler.

Pitfalls

  • Counting with overlapping unions. COUNT adds over unions, so it counts a program twice if two kids hold it. Keep unions disjoint, as BUILD and INTERSECT do here, or count with another method.
  • Growth under intersection. The intersection of two version spaces can have as many nodes as the product of their sizes. Drop EMPTY nodes at once, or the graph fills with dead parts.
  • Ranks that are not compositional. BEST at a union takes the best kid, which is correct only when the rank of a program is computed from the ranks of its parts. A rank that looks at the whole program needs the programs listed.
  • Equal values are not equal programs. Two programs with the same outputs on all examples are both kept. A VSA does not merge programs by behaviour; that is what observational equivalence does in bottom-up enumerative synthesis.
  • A size bound hides programs. A program longer than the bound is not in the set, even if it is the intended one. The empty result means "none up to this bound", not "none".

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

version_space_algebra.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/version-space-algebra/. The authors are listed in prov/4T1SEM.jsonl.
"""A version space algebra over a small arithmetic language.

Programs of the language:
    "x", "y", "1", "2"        terminals; the input is a pair (x, y) of ints
    (op, p, q)                 op is "+", "-" or "*"; p and q are programs
The size of a program is the number of nodes of its tree, so sizes are odd.

A version space is a DAG of three kinds of nodes:
    Leaf(progs)       a finite set of terminal programs
    Union(kids)       the union of the sets of the kids
    Join(op, a, b)    all programs (op, p, q) with p in a and q in b
EMPTY is the union with no kids. The constructors make_leaf, make_union and
make_join never build any other node with an empty set.

build(inp, out, max_size) returns the version space of all programs of size
at most max_size whose output on inp is out. intersect(a, b) returns a
version space for the intersection of the two sets. count(n) gives the
number of programs without listing them. The unions that build and
intersect make have kids with disjoint sets, so count(n) is exact.
"""

TERMINALS = ("x", "y", "1", "2")
OPS = ("+", "-", "*")


def apply_op(op, a, b):
    if op == "+":
        return a + b
    if op == "-":
        return a - b
    if op == "*":
        return a * b
    raise ValueError(f"unknown operator {op!r}")


def evaluate(p, inp):
    """The output of program p on the input pair inp = (x, y)."""
    if p == "x":
        return inp[0]
    if p == "y":
        return inp[1]
    if p == "1":
        return 1
    if p == "2":
        return 2
    return apply_op(p[0], evaluate(p[1], inp), evaluate(p[2], inp))


def size(p):
    if isinstance(p, str):
        return 1
    return 1 + size(p[1]) + size(p[2])


def show(p):
    if isinstance(p, str):
        return p
    return f"({show(p[1])} {p[0]} {show(p[2])})"


class Leaf:
    __slots__ = ("progs",)

    def __init__(self, progs):
        self.progs = progs


class Union:
    __slots__ = ("kids",)

    def __init__(self, kids):
        self.kids = kids


class Join:
    __slots__ = ("op", "left", "right")

    def __init__(self, op, left, right):
        self.op = op
        self.left = left
        self.right = right


EMPTY = Union(())


def make_leaf(progs):
    progs = frozenset(progs)
    return Leaf(progs) if progs else EMPTY


def make_union(kids):
    kids = tuple(k for k in kids if k is not EMPTY)
    if not kids:
        return EMPTY
    if len(kids) == 1:
        return kids[0]
    return Union(kids)


def make_join(op, left, right):
    if left is EMPTY or right is EMPTY:
        return EMPTY
    return Join(op, left, right)


def build(inp, out, max_size):
    """The version space of the programs of size <= max_size with output out on inp."""
    by_value = {}
    for t in TERMINALS:  # @line L1
        by_value.setdefault(evaluate(t, inp), []).append(t)
    vals = {1: set(by_value)}  # @line L2
    how = {}
    for s in range(3, max_size + 1, 2):  # @line L3
        table = {}
        for s1 in range(1, s - 1, 2):  # @line L4
            s2 = s - 1 - s1
            for a in vals[s1]:
                for b in vals[s2]:
                    for op in OPS:
                        table.setdefault(apply_op(op, a, b), []).append((op, s1, a, b))  # @line L5
        how[s] = table
        vals[s] = set(table)  # @line L6

    memo = {}

    def node(s, v):
        key = (s, v)
        if key not in memo:
            if s == 1:
                memo[key] = make_leaf(by_value.get(v, ()))  # @line L8
            else:
                memo[key] = make_union(  # @line L9
                    make_join(op, node(s1, a), node(s - 1 - s1, b))
                    for (op, s1, a, b) in how[s].get(v, ())
                )
        return memo[key]

    return make_union(node(s, out) for s in range(1, max_size + 1, 2) if out in vals[s])  # @line L7


def intersect(a, b, memo=None):
    """A version space whose set is the intersection of the sets of a and b."""
    if memo is None:
        memo = {}
    key = (id(a), id(b))
    if key in memo:
        return memo[key]
    if a is EMPTY or b is EMPTY:  # @line L10
        r = EMPTY
    elif isinstance(a, Union):  # @line L11
        r = make_union(intersect(k, b, memo) for k in a.kids)
    elif isinstance(b, Union):  # @line L12
        r = make_union(intersect(a, k, memo) for k in b.kids)
    elif isinstance(a, Leaf) and isinstance(b, Leaf):  # @line L13
        r = make_leaf(a.progs & b.progs)
    elif isinstance(a, Join) and isinstance(b, Join) and a.op == b.op:  # @line L14
        left = intersect(a.left, b.left, memo)
        r = EMPTY if left is EMPTY else make_join(a.op, left, intersect(a.right, b.right, memo))
    else:
        r = EMPTY  # @line L15
    memo[key] = r
    return r


def synthesize(examples, max_size):
    """The version space of the programs of size <= max_size consistent with all examples."""
    root = None
    for inp, out in examples:
        v = build(inp, out, max_size)
        root = v if root is None else intersect(root, v)
        if root is EMPTY:
            break
    return root


def _nodes(n):
    """All nodes reachable from n, each once."""
    seen = {}
    stack = [n]
    while stack:
        m = stack.pop()
        if id(m) in seen:
            continue
        seen[id(m)] = m
        if isinstance(m, Union):
            stack.extend(m.kids)
        elif isinstance(m, Join):
            stack.append(m.left)
            stack.append(m.right)
    return list(seen.values())


def dag_size(n):
    """(number of nodes, number of edges) of the DAG; a leaf counts its programs as edges."""
    nodes = _nodes(n)
    edges = 0
    for m in nodes:
        if isinstance(m, Union):
            edges += len(m.kids)
        elif isinstance(m, Join):
            edges += 2
        else:
            edges += len(m.progs)
    return len(nodes), edges


def count(n, memo=None):
    """The number of programs in the set of n, without listing them."""
    if memo is None:
        memo = {}
    if id(n) in memo:
        return memo[id(n)]
    if isinstance(n, Leaf):
        c = len(n.progs)  # @line L16
    elif isinstance(n, Union):
        c = sum(count(k, memo) for k in n.kids)  # @line L17
    else:
        c = count(n.left, memo) * count(n.right, memo)  # @line L18
    memo[id(n)] = c
    return c


def programs(n):
    """Yield every program of the set of n."""
    if isinstance(n, Leaf):
        yield from sorted(n.progs)
    elif isinstance(n, Union):
        for k in n.kids:
            yield from programs(k)
    else:
        rights = list(programs(n.right))
        for p in programs(n.left):
            for q in rights:
                yield (n.op, p, q)


def smallest(n, memo=None):
    """A program of least size in the set of n, or None if the set is empty."""
    if memo is None:
        memo = {}
    if id(n) in memo:
        return memo[id(n)]
    if isinstance(n, Leaf):
        best = min(n.progs)
    elif isinstance(n, Union):
        cands = [smallest(k, memo) for k in n.kids]
        cands = [c for c in cands if c is not None]
        best = min(cands, key=size) if cands else None
    else:
        best = (n.op, smallest(n.left, memo), smallest(n.right, memo))
    memo[id(n)] = best
    return best
test_version_space_algebra.py 146 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/version-space-algebra/. The authors are listed in prov/4T1SEM.jsonl.

import random

from version_space_algebra import (
    EMPTY, OPS, TERMINALS, Join, Leaf, build, count, dag_size, evaluate, intersect,
    make_leaf, make_union, programs, size, smallest, synthesize,
)


def all_programs(max_size):
    """Brute force: every program of size <= max_size, listed by size."""
    by_size = {1: list(TERMINALS)}
    for s in range(3, max_size + 1, 2):
        out = []
        for s1 in range(1, s - 1, 2):
            for p in by_size[s1]:
                for q in by_size[s - 1 - s1]:
                    for op in OPS:
                        out.append((op, p, q))
        by_size[s] = out
    return [p for s in sorted(by_size) for p in by_size[s]]


ALL7 = all_programs(7)


def consistent(examples, max_size, pool=ALL7):
    return {p for p in pool if size(p) <= max_size and all(evaluate(p, i) == o for i, o in examples)}


def random_example(rng, max_size):
    inp = (rng.randint(-3, 3), rng.randint(-3, 3))
    if rng.random() < 0.8:
        p = rng.choice([q for q in ALL7 if size(q) <= max_size])
        return inp, evaluate(p, inp)
    return inp, rng.randint(-20, 20)


def test_brute_force_counts():
    assert len(ALL7) == 4 + 48 + 1152 + 34560


def test_single_example_equals_enumeration():
    rng = random.Random(1)
    for max_size in (1, 3, 5, 7):
        for _ in range(4):
            ex = random_example(rng, max_size)
            root = build(ex[0], ex[1], max_size)
            listed = list(programs(root))
            want = consistent([ex], max_size)
            assert len(listed) == len(set(listed))
            assert set(listed) == want
            assert count(root) == len(want)


def test_intersection_equals_enumeration():
    rng = random.Random(2)
    for max_size in (3, 5, 7):
        for _ in range(4):
            target = rng.choice([q for q in ALL7 if size(q) <= max_size])
            examples = []
            for _ in range(rng.randint(2, 3)):
                inp = (rng.randint(-3, 3), rng.randint(-3, 3))
                examples.append((inp, evaluate(target, inp)))
            root = synthesize(examples, max_size)
            want = consistent(examples, max_size)
            assert target in want
            listed = list(programs(root))
            assert len(listed) == len(set(listed)) == count(root)
            assert set(listed) == want
            best = smallest(root)
            assert size(best) == min(size(p) for p in want)
            assert all(evaluate(best, i) == o for i, o in examples)


def test_pairwise_intersection():
    rng = random.Random(3)
    for _ in range(6):
        e1 = random_example(rng, 5)
        e2 = random_example(rng, 5)
        a = build(e1[0], e1[1], 5)
        b = build(e2[0], e2[1], 5)
        r = intersect(a, b)
        want = consistent([e1], 5) & consistent([e2], 5)
        assert set(programs(r)) == want
        assert count(r) == len(want)
        if not want:
            assert r is EMPTY


def test_count_without_enumeration_size_9():
    # Compare the count of size 9 with a count over the brute force of the values only.
    inp, out = (1, 2), 3
    vals = {1: {}}
    for t in TERMINALS:
        v = evaluate(t, inp)
        vals[1][v] = vals[1].get(v, 0) + 1
    for s in range(3, 10, 2):
        table = {}
        for s1 in range(1, s - 1, 2):
            for a, ca in vals[s1].items():
                for b, cb in vals[s - 1 - s1].items():
                    for op in OPS:
                        v = {"+": a + b, "-": a - b, "*": a * b}[op]
                        table[v] = table.get(v, 0) + ca * cb
        vals[s] = table
    want = sum(vals[s].get(out, 0) for s in vals)
    root = build(inp, out, 9)
    assert count(root) == want
    # The size-7 part agrees with the explicit enumeration.
    assert count(build(inp, out, 7)) == len(consistent([(inp, out)], 7))


def test_compact_representation():
    # A chain of k joins over a two-program leaf holds 2^(k+1) programs in k + 1 nodes.
    leaf = make_leaf(["x", "y"])
    n = leaf
    for _ in range(10):
        n = Join("+", leaf, n)
    nodes, _ = dag_size(n)
    assert nodes == 11
    assert count(n) == 2 ** 11
    # The version space of one example holds far more programs than it has nodes and edges.
    root = build((1, 2), 3, 11)
    nodes, edges = dag_size(root)
    assert count(root) > 100 * (nodes + edges)


def test_union_and_join_semantics():
    a = make_leaf(["x", "1"])
    b = make_leaf(["y"])
    u = make_union([Join("+", a, b), Join("*", a, b)])
    assert set(programs(u)) == {("+", "x", "y"), ("+", "1", "y"), ("*", "x", "y"), ("*", "1", "y")}
    v = make_union([Join("+", make_leaf(["x"]), b), make_leaf(["x"])])
    assert set(programs(intersect(u, v))) == {("+", "x", "y")}
    assert intersect(Join("+", a, b), Leaf(frozenset(["x"]))) is EMPTY
    assert intersect(Join("+", a, b), Join("-", a, b)) is EMPTY


def test_no_consistent_program():
    examples = [((0, 0), 1000)]
    assert synthesize(examples, 5) is EMPTY
    assert smallest(EMPTY) is None
    assert count(EMPTY) == 0

History

Mitchell (1982) defined the version space of a learning problem as the set of hypotheses that agree with all examples, and stored it by its boundary sets. Lau, Domingos and Weld (2000) turned version spaces into an algebra, so that a space of programs is built from spaces of smaller programs by union and join. Lau, Wolfman, Domingos and Weld (2003) give the full account and the SMARTedit editor. Gulwani (2011) used the same idea for FlashFill, which stores all consistent string programs and intersects them over the examples. Polozov and Gulwani (2015) stated version space algebras in general for any domain-specific language, built top-down by witness functions, in the FlashMeta framework.

References

  1. Tom M. Mitchell, Generalization as search, Artificial Intelligence 18(2), 1982, pp. 203-226, version spaces of consistent hypotheses, the boundary sets S and G, and the candidate elimination algorithm
  2. Tessa Lau, Steven A. Wolfman, Pedro Domingos and Daniel S. Weld, Programming by demonstration using version space algebra, Machine Learning 53(1-2), 2003, pp. 111-156, the version space algebra with union and join of version spaces, and its use in the SMARTedit text editor
  3. Tessa Lau, Pedro Domingos and Daniel S. Weld, Version space algebra and its application to programming by demonstration, Proceedings of the 17th International Conference on Machine Learning (ICML 2000), pp. 527-534, the first description of composite version spaces
  4. Sumit Gulwani, Automating string processing in spreadsheets using input-output examples, Principles of Programming Languages (POPL 2011), pp. 317-330, the shared data structure for all consistent string programs and its intersection over several examples
  5. Oleksandr Polozov and Sumit Gulwani, FlashMeta, a framework for inductive program synthesis, Object-Oriented Programming, Systems, Languages and Applications (OOPSLA 2015), pp. 107-126, version space algebras with union and join nodes in general, intersection, ranking, and their construction by witness functions

Where this leads

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.build
  • a full proof of time.count
  • a full proof of time.intersect
  • a full proof of space.build
  • a full proof of space.intersect
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/4T1SEM/text.yaml