### Exploration and extraction

←Return to chapter

## 5.4. Exploration and extraction

In the previous section, we proposed a data structure D\mathcal{D}D that is confluently persistent and can be used to explore the space of all possible transformations of a graph transformation system (GTS). We are now interested in using D\mathcal{D}D to solve optimisation problems over the space of reachable graphs in the GTS. Following the blueprint of equality saturation (see section 5.2), we proceed in two phases:

1. Exploration.Given an input graph G GG, populate D\mathcal{D}D with events that correspond to rewrites applicable to graphs reachable from G GG,
2. Extraction.Given a cost function f f f, extract the optimal graph in D\mathcal{D}D, i.e. the graph that is a flattening of a set of compatible edits D⊆D D \subseteq \mathcal{D}D⊆D and minimises f f f.

Each phase comes with its respective challenges, which we discuss in this section. We will first look at the exploration phase, which requires a way to find and construct new events δ\delta δ that can be added to D\mathcal{D}D. We will consider the extraction phase in the second part of this section and see that the problem of optimisation over the power set P(D)\mathcal P(\mathcal D)P(D) can be reduced to boolean satisfiability formula that admit simple cost functions in the use cases of interest.

There is an additional open question that we do not cover in this section and would merit a study of its own: the choice of heuristics that guide the exploration phase to ensure the “most interesting parts” of the GTS rewrite space are explored. We propose a very simple heuristic to this end in the benchmarks of section 5.5, but further investigations are called for.

### Exploring the data structure with pattern matching #

We established in the previous section that rewrites that apply on G GG can equivalently be added as events to D\mathcal{D}D. In other words, a graph G′G'G′ is reachable from G GG using the rewrites of a GTS if and only if there is a set of compatible events D⊆D D \subseteq \mathcal{D}D⊆D such that G′G'G′ is the graph obtained from `FlattenHistory` on input D D D.

To expand D\mathcal{D}D to a larger set D′⊇D\mathcal{D}' \supseteq \mathcal{D}D′⊇D, we must find all applicable rewrites on all graphs within D\mathcal{D}D. A naive solution would iterate over all subsets of D⊆D D \subseteq \mathcal{D}D⊆D, check whether they form a compatible set of events, compute `FlattenHistory` if they do, and finally run pattern matching on the obtained graph to find the applicable rewrites. We can do better.

The idea is to traverse the set of events in D\mathcal{D}D using the glueing relations μ\muμ that connect vertices between events. Define the function μ ˉ: V(D)→P(V(D))\bar{\mu}: V(\mathcal{D}) \to \mathcal{P}(V(\mathcal{D}))μ ˉ​:V(D)→P(V(D)) that is the union of all glueing relations μ\muμ in events in D\mathcal{D}D:

μ ˉ(v)={μ c(v)∣δ c=(V c, V c−,μ c)∈P−1(δ v)}.\bar\mu(v) = \{\mu_c(v) \mid \delta_c = (V_c, V^-_c, \mu_c) \in P^{-1}(\delta_v)\}.μ ˉ​(v)={μ c​(v)∣δ c​=(V c​,V c−​,μ c​)∈P−1(δ v​)}.

where we write δ v\delta_v δ v​ for the owner of v v v, i.e. the (unique) event δ v∈D\delta_v \in \mathcal{D}δ v​∈D such that v∈V(δ v)v \in V(\delta_v)v∈V(δ v​). We define the set E D(v)\mathcal{E}_D(v)E D​(v) of equivalent vertices of v v v that are compatible with D D D by applying μ ˉ(v)\bar\mu(v)μ ˉ​(v) recursively and filtering out vertices whose owner is not compatible with D D D. It is easiest to formalise this definition using pseudocode for the `EquivalentVertices` procedure. The set of vertices in E D(v)\mathcal{E}_D(v)E D​(v) are vertices of descendant events of δ v\delta_v δ v​.

    def EquivalentVertices(
        v: Vertex, events: Set[Event]
    ) -> Set[Vertex]:
        all_vertices = set({v})
        for w in mu_bar(v):
            new_events = union(events, {owner(w)})
            if AreCompatible(new_events):
                all_vertices = union(all_vertices,
                    EquivalentVertices(w, new_events)
                )
        return all_vertices

Whilst it looks as though `EquivalentVertices` does not depend on D\mathcal{D}D, it does so through the use of the function calls to `mu_bar`.

We use `EquivalentVertices` to repeatedly extend a set of pinned vertices π⊆V(D)\pi \subseteq V(\mathcal{D})π⊆V(D). A set of pinned vertices must satisfy two properties:

- the set D π={δ v∣v∈π}D_\pi = \{\delta_v \mid v \in \pi \}D π​={δ v​∣v∈π} is a set of compatible events,
- there is no vertex v∈π v \in \pi v∈π and event δ∈D\delta \in D δ∈D such that v∈V−(δ)v \in V^-(\delta)v∈V−(δ).

As a result, for the flattened graph G=f l a t(D π)G = flat(D_\pi)G=f l at(D π​), it always holds that π⊆V(G)\pi \subseteq V(G)π⊆V(G). Furthermore, if G(π)⊆G G(\pi) \subseteq GG(π)⊆G is the subgraph of G GG induced by π\pi π, then for any superset of pinned vertices π′⊇π\pi' \supseteq \pi π′⊇π, we have G(π)⊆G′(π′)G(\pi) \subseteq G'(\pi')G(π)⊆G′(π′) where G′=f l a t(D π′)G' = flat(D_{\pi'})G′=f l at(D π′​). In other words: extending a set of pinned vertices results in an extension of the flattened graph – a very useful property when pattern matching. This property follows from the second property above and the definition of `FlattenHistory`.

This gives us the following simple procedure for pattern matching:

1. Start with a single pinned vertex π={v}\pi = \{v\}π={v}.
2. Construct partial embeddings P⇀G(π)P \rightharpoonup G(\pi)P⇀G(π) for patterns P P P.
3. Pick a new vertex v v v in G=f l a t(D π)G = flat(D_\pi)G=f l at(D π​) but not in G(π)G(\pi)G(π) (that we would like to extend the domain of definition of our pattern embeddings to).
4. For all vertices v′∈E D(v)v' \in \mathcal{E}_D(v)v′∈E D​(v), build new pinned vertex sets π′=π∪{v′}\pi' = \pi \cup \{v'\}π′=π∪{v′}, filter out the sets π′\pi'π′ that are not valid pinned vertex sets.
5. Repeat steps 2–4 until all pattern embeddings have been found.

Step 1 is straightforward – notice that pattern matching must be started at a vertex in V(D)V(\mathcal{D})V(D), so finding all patterns will require iterating over all choices of v v v. The pattern embeddings are constructed over iterations of step 2: each iteration can be seen as one step of the pattern matcher – for instance, as presented in chapter 4 – extending the pattern embeddings that can be extended and discarding those that cannot. If all possible pattern embeddings have been discarded, then matching can be aborted for that π\pi π set.

How step 3 should be implemented depends on the types of graphs and patterns that are matched on. It is straightforward in the case of computation graphs with only linear values, i.e. hypergraphs with hyperedges that have directed, ordered endpoints and vertices that are incident to exactly one incoming and one outgoing edge. In that case, v v v can always be chosen in such a way as to ensure progress on the next iteration of step 2, i.e. the domain of definition of at least one partial pattern embedding P↪G(π)P \hookrightarrow G(\pi)P↪G(π) will be extended by one vertex. The text in the blue box below explains this case in more detail.

Step 4 produces all possible extensions of π\pi π to pinned vertex sets π′\pi'π′ that include a descendant v′v'v′ of v v v (or v v v itself). All vertices in E D(v)\mathcal{E}_D(v)E D​(v) are in events compatible with D D D by definition, so to check that π′\pi'π′ is a valid pinned vertex set, we only need to check the second property of pinned vertices. Let P P P be a pattern, let S S S be the set of all π\pi π sets under consideration. Step 4 increments the sizes of all pinned vertex sets π∈S\pi \in S π∈S whilst maintaining the following invariant.

Invariant for step 4.If there is a superset D′⊇D π D' \supseteq D_\pi D′⊇D π​ of compatible events such that P P P embeds in G′=f l a t(D′)G' = flat(D')G′=f l at(D′), then there is a superset π′⊇π\pi' \supseteq \pi π′⊇π of vertices such that P P P embeds in f l a t(D π′)flat(D_{\pi'})f l at(D π′​).

Finally, step 5 ensures the process is repeated until, for all partial pattern embeddings, either the domain of definition is complete, or the embedding of P P P is not possible. Given that step 4 increments the size of π\pi π sets at each iteration, this will terminate as long as the vertex picking strategy of step 3 selects vertices that allow to extend (or refute) the partial pattern embeddings constructed and extended in step 2. This is satisfied, for example, in the case of linear minIR graphs, as explained in the box.

> Choosing the next vertex to pin in linear minIR (step 3). Assuming patterns are connected, for any partial pattern embedding P↪G(π)P \hookrightarrow G(\pi)P↪G(π) there is an edge e P∈E(P)e_P \in E(P)e P​∈E(P) with no image in G(π)G(\pi)G(π) but such that at least one of the endvertex v P v_P v P​ of e P e_Pe P​ has an image v G v_G v G​ in π\pi π – say, e P e_Pe P​ is the outgoing edge of v P v_P v P​. Let v P′v'_P v P′​ be an endvertex of e P e_Pe P​ in P P P that has no image in G(π)G(\pi)G(π) – and say, it is the i ii-th outgoing endvertex of e P e_Pe P​ in P P P.

> Then v P v_P v P​ uniquely identifies an edge e G e_Ge G​ in G=f l a t(D π)G = flat(D_\pi)G=f l at(D π​) – the unique outgoing edge of v G v_G v G​ – which, in turn, uniquely identifies a vertex v G′∈V(G)v'_G \in V(G)v G′​∈V(G) – the i ii-th outgoing endvertex of e G e_Ge G​. By choosing v G′v'_G v G′​ in step 3, step 4 will create pinned vertex sets that include all possible vertices equivalent to v G′v_G'v G′​, which are all vertices that v G v_G v G​ might be connected to through its outgoing edge1. The next iteration of step 2 will then either extend the partial pattern embedding to v P v_P v P​ or conclude that an embedding of P P P is not possible.

Using the approach just sketched, pattern matching can be performed on the persistent data structure D\mathcal{D}D. The runtime of steps 2 and 3 depend on the type of graphs and patterns that are matched on – these are, however, typical problems that appear in most instances of pattern matching, independently of the data structure D\mathcal{D}D used here. A concrete approach to pattern matching and results for the graph types of interest to quantum compilation was presented in chapter 4.

The runtime of step 4 and the number of overall iterations of steps 2–4 required for pattern matching will depend on the number of events in D\mathcal{D}D (`AreCompatible` runs in runtime linear in the number of ancestors), the number of equivalent vertices that successive rounds of step 4 will return and the types of patterns and pattern matching strategies.

### Extraction using SAT #

Moving on to the extraction phase, we are now interested in extracting the optimal graph from D\mathcal{D}D, according to some cost function of interest. Unlike exploring the “naive” search space of all graphs reachable in the GTS, the optimal solution within the persistent data structure D\mathcal{D}D cannot simply be read out.

We showed in section 5.3 that finding an optimal graph G′G'G′ that is the result of a sequence of rewrites on an input graph G GG is equivalent to finding an optimal set of compatible events D∈Γ(D)⊆P(D)D \in \Gamma(\mathcal{D}) \subseteq \mathcal{P}(\mathcal{D})D∈Γ(D)⊆P(D) – the optimal graph G′G'G′ is then recoved by taking G′=f l a t(D)G' = flat(D)G′=f l at(D).

There are 2∣D∣2^{|\mathcal{D}|}2∣D∣ elements in P(D)\mathcal{P}(\mathcal{D})P(D), which we encode as a boolean assignment problem by introducing a boolean variable x δ x_\deltax δ​ for all events δ∈D\delta \in \mathcal{D}δ∈D. The set of events D D D is then given by

D={δ∈D∣x δ}∈P(D).D = \{\delta \in \mathcal{D} \mid x_\delta\} \in \mathcal{P}(\mathcal{D}).D={δ∈D∣x δ​}∈P(D).

We can constrain the boolean assignments to compatible sets D D D by introducing a boolean formula

¬(x δ∧x δ′)\neg (x_\delta \land x_{\delta'})¬(x δ​∧x δ′​)

for all δ, δ′∈D\delta,\delta' \in \mathcal{D}δ, δ′∈D such that their vertex deletion sets intersect V−(δ)∩V−(δ′)≠∅V^-(\delta) \cap V^-(\delta') \neq \varnothing V−(δ)∩V−(δ′)=∅. Any assignment of {x δ∣δ∈D}\{x_\delta \mid \delta \in \mathcal{D}\}{x δ​∣δ∈D} that satisfies all constraints of this format defines a compatible set of events.

How many such pairs of events (δ, δ′(\delta,\delta'(δ, δ′) are there? By definition of parents, two events δ\delta δ and δ′\delta'δ′ can only have overlapping vertex deletion sets if they share a parent. Assuming all events have at most s ss children, ensuring D D D is a set of compatible events requires at most O(s 2⋅∣D∣)O(s^2 \cdot |\mathcal{D}|)O(s 2⋅∣D∣) constraints.

To further restrict to D∈Γ(D)D \in \Gamma(\mathcal{D})D∈Γ(D), i.e. to sets of compatible events D=⌊D⌋D = \lfloor D \rfloor D=⌊D⌋ that contain all ancestors, we can add the further constraints: δ∈D\delta \in D δ∈D implies P(δ)⊆D P(\delta) \subseteq D P(δ)⊆D. This introduces up to s⋅∣D∣s \cdot |\mathcal{D}|s⋅∣D∣ implication constraints

x δ∨(¬x δ′),x_\delta \lor (\neg x_{\delta'}),x δ​∨(¬x δ′​),

for all δ, δ′∈D\delta,\delta' \in \mathcal{D}δ, δ′∈D such that δ′∈c h i l d r e n(δ)\delta' \in children(\delta)δ′∈chi l dren(δ).

For any set of events D\mathcal{D}D, the conjunction of all constraints presented above, i.e. the event compatibility constraints (1) and the parent-child relation constraints (2), defines a boolean satisfiability problem (SAT) with variables x δ x_\deltax δ​. We have shown:

Proposition 5.4Extraction as SAT problem

Consider a GTS with a constant upper bound s ss on the number of rewrites that may overlap any previous rewrite.

The set of valid sequences of rewrites that can be extracted from a set of events D\mathcal{D}D in the GTS is given by the set of satisfying assignments of a SAT problem Cook, 1971Stephen A. Cook. 1971. The complexity of theorem-proving procedures. In Proceedings of the third annual ACM symposium on Theory of computing - STOC ’71. ACM Press, 151--158. doi: 10.1145/800157.805047 Moskew., 2001Matthew W. Moskewicz, Conor F. Madigan, Ying Zhao, Lintao Zhang and Sharad Malik. 2001. Chaff: engineering an efficient SAT solver. In Proceedings of the 38th conference on Design automation - DAC ’01. ACM Press, 530--535. doi: 10.1145/378239.379017 with ∣D∣|\mathcal{D}|∣D∣ variables of size O(∣D∣)O(|\mathcal{D}|)O(∣D∣).

#### Finding the optimal assignment #

We now have to find the optimal assignment among all satisfiable assignments for the SAT problem given above. In the most general case where the cost function f f f to be minimised is given as a black box oracle on the graph G′G'G′, i.e. on the flattened history of the solution set D⊆D D \subseteq \mathcal{D}D⊆D, this optimisation problem is hard2.

However, if f f f can be expressed as a function of x δ x_\deltax δ​ instead of the flattened history G′=f l a t(D)G' = flat(D)G′=f l at(D), then the ‘hardness’ can be encapsulated within an instance of a SMT problem (satisfiability modulo theories Nieuwe., 2006Robert Nieuwenhuis and Albert Oliveras. 2006. On SAT Modulo Theories and Optimization Problems. In Theory and Applications of Satisfiability Testing - SAT 2006. Springer Berlin Heidelberg, 156--169. doi: 10.1007/11814948_18 Barrett, 2018Clark Barrett and Cesare Tinelli. 2018. Satisfiability Modulo Theories), a well-studied generalisation of SAT problems for which highly optimised solvers exist Moura, 2008Leonardo de Moura and Nikolaj Bjørner. 2008. Z3: An Efficient SMT Solver. In Tools and Algorithms for the Construction and Analysis of Systems. Springer Berlin Heidelberg, 337--340. doi: 10.1007/978-3-540-78800-3_24 Sebast., 2015Roberto Sebastiani and Patrick Trentin. 2015. OptiMathSAT: A Tool for Optimization Modulo Theories. In Computer Aided Verification. Springer International Publishing, 447--454. doi: 10.1007/978-3-319-21690-4_27. A class of cost functions for which the SMT encoding of the optimisation problem becomes particularly simple are local cost functions:

Definition 5.1Local cost function

A cost function f f f on graphs is local if for all rewrites r r r there is a cost Δ f r\Delta f_rΔ f r​ such that for all graphs G GG that r r r applies to

f(r(G))=f(G)+Δ f r. f(r(G)) = f(G) + \Delta f_r. f(r(G))=f(G)+Δ f r​.

The cost Δ f r\Delta f_rΔ f r​ of a rewrite r r r also immediately defines a cost to the event that r r r defines δ=r\delta = r δ=r. We can thus associate a cost Δ f δ\Delta f_\deltaΔ f δ​ with each event δ∈D\delta \in \mathcal{D}δ∈D, given by the cost of any of the rewrites that δ\delta δ defines.

An instance of such a local cost function often used in the context of the optimisation of computation graphs are functions of the type

f(G)=∑v∈V(G)w(v)f(G) = \sum_{v \in V(G)} w(v)f(G)=v∈V(G)∑​w(v)

for some vertex weight function w w w – i.e. cost functions that can be expressed as sums over the costs w(⋅)w(\cdot)w(⋅) associated to individual vertices in G GG3. Indeed, it is easy to see that in this case we can write

f(r(G))=∑v∈r(V(G))w(v)=∑v∈V(G)w(v)−∑v∈V−w(v)+∑v∈V R w(v)⏟:=Δ f r=f(G)+Δ f r,\begin{aligned}f(r(G)) &= \sum_{v \in r(V(G))} w(v)\\&= \sum_{v\in V(G)} w(v) - \underbrace{\sum_{v \in V^-} w(v) + \sum_{v \in V_R} w(v)}_{:= \Delta f_r}\\&= f(G) + \Delta f_r,\end{aligned}f(r(G))​=v∈r(V(G))∑​w(v)=v∈V(G)∑​w(v)−:=Δ f r​
v∈V−∑​w(v)+v∈V R​∑​w(v)​​=f(G)+Δ f r​,​

where V−V^-V− and V R V_R V R​ are the vertex deletion set and replacement graph of r r r respectively.

As discussed in section 2.2, many of the most widely used cost functions in quantum compilation are local, as the cost of a quantum computation is often estimated by the required number of instances of the most expensive gate type (such as \texttt{CX} gates on noisy devices, or \texttt{T} gates for hardware with built-in fault tolerance protocols).

In these cases, the cost function is integer valued and the extraction problem is indeed often sparse:

Definition 5.2Sparse cost function

The local cost function f f f is said to be ε\varepsilonε-sparse on D\mathcal{D}D if

∣{δ∈D ∣ Δ f δ=0}∣≥(1−ε)∣D∣.\big|\{\delta \in \mathcal{D}\,|\,\Delta f_\delta = 0 \}\big| \geq (1 - \varepsilon) |\mathcal{D}|.
​{δ∈D∣Δ f δ​=0}
​≥(1−ε)∣D∣.

In case of ε\varepsilonε-sparse local cost functions, the SAT problem on D\mathcal{D}D can be simplified to only include

D≠0={δ∈D∣Δ f δ≠0}\mathcal{D}_{\neq 0} = \{\delta \in \mathcal{D} \mid \Delta f_\delta \neq 0\}D=0​={δ∈D∣Δ f δ​=0}

by repeatedly applying the following constraint simplification rules on any δ 0∈D\delta_0 \in \mathcal{D}δ 0​∈D such that Δ f δ 0=0\Delta f_{\delta_0} = 0Δ f δ 0​​=0:

- for every parent δ p∈p a r e n t s(δ 0)\delta_p \in parents(\delta_0)δ p​∈parents(δ 0​) and child δ c∈c h i l d r e n(δ 0)\delta_c \in children(\delta_0)δ c​∈chi l dren(δ 0​), remove the parent-child constraints between δ p\delta_p δ p​ and δ 0\delta_0 δ 0​ and between δ 0\delta_0 δ 0​ and δ c\delta_c δ c​. Insert in their place a parent-child constraint between δ p\delta_p δ p​ and δ c\delta_c δ c​.
- for every non-compatible sibling event δ s∈D, δ s≠δ 0\delta_s \in \mathcal{D}, \delta_s \neq \delta_0 δ s​∈D, δ s​=δ 0​, remove the compatibility constraint between δ 0\delta_0 δ 0​ and δ s\delta_s δ s​. Insert in its place a compatibility constraint between δ s\delta_s δ s​ and δ c\delta_c δ c​ for all δ c∈c h i l d r e n(δ s)\delta_c \in children(\delta_s)δ c​∈chi l dren(δ s​).

This reduces the SAT or SMT problem to a problem with ∣D≠0∣=ε∣D∣|\mathcal D_{\neq 0}| = \varepsilon |\mathcal{D}|∣D=0​∣=ε∣D∣ variables and at most O(m i n(∣D∣,ε 2∣D∣2)O(min(|\mathcal{D}|, \varepsilon^2|\mathcal{D}|^2)O(min(∣D∣,ε 2∣D∣2) constraints.

With the completion of this section, we have described an equivalent computation on D\mathcal{D}D for every step of a GTS-based optimisation problem:

1. a rewrite that can be applied on a graph G GG can be added as an event to D\mathcal{D}D,
2. a graph G′G'G′ that results from a sequence of rewrites can be recovered from D\mathcal{D}D using `FlattenHistory`,
3. the set of all graphs reachable from events in D\mathcal{D}D can be expressed as a SAT problem; depending on the cost function, the optimisation over that space can then take the form of an SMT problem.

In essence, using the confluently persistent data structure D\mathcal{D}D we replace a naive, exhaustive search over the space G\mathcal{G}G of all graphs reachable in the GTS with a SAT (or SMT) problem – solvable using highly optimised dedicated solvers that could in principle handle search spaces with up to millions of possible rewrites Zulkos., 2018Edward Zulkoski. 2018. Understanding and Enhancing CDCL-based SAT Solvers. PhD Thesis. University of Waterloo.

1. To realise this, notice that all vertices equivalent to v G′v_G'v G′​ are vertices that will be merged with v G′v_G'v G′​. Hence, they will all be attached to the outgoing edge of v G v_G v G​ at its i ii-th outgoing endvertex. ↩︎

2. Hardness can be seen by considering the special case of the extraction problem in which all events are compatible and no two events have a parent-child relation: then there are no constraints on the solution space and the optimisation problem requires finding the minimum of an arbitrary oracle over 2∣D∣2^{|\mathcal{D}|}2∣D∣ inputs. ↩︎

3. A similar argument also applies to cost functions that sum over graph edges, as would be the case in minIR, where operations are modelled as hyperedges. ↩︎

←Return to chapter