An Automated Deductive Verification Framework for Circuit-building Quantum Programs

While recent progress in quantum hardware open the door for significant speedup in certain key areas, quantum algorithms are still hard to implement right, and the validation of such quantum programs is a challenge. In this paper we propose Qbricks, a formal verification environment for circuit-building quantum programs, featuring both parametric specifications and a high degree of proof automation. We propose a logical framework based on first-order logic, and develop the main tool we rely upon for achieving the automation of proofs of quantum specification: PPS, a parametric extension of the recently developed path sum semantics. To back-up our claims, we implement and verify parametric versions of several famous and non-trivial quantum algorithms, including the quantum parts of Shor’s integer factoring, quantum phase estimation (QPE) and Grover’s search.


INTRODUCTION
1.1 Quantum computing.Quantum computing is a young research field: its birth act is usually dated in 1982, when Feynman [25] raised the idea of simulating the quantum mechanics phenomena by storing information in particles and controlling them according to quantum mechanics laws.This initial idea has become one over many application fields for quantum computing, along with cryptography [66], deep learning [9], optimization [23,24], solving linear systems [36], etc.In all these domains there are now quantum algorithms beating the best known classical algorithms by either quadratic or even exponential factors.In parallel to the rise of quantum algorithms, the design of quantum hardware has moved from labbenches [15] to programmable, 50-qubits machines designed by industrial actors [4,42] reaching the point where quantum computers would beat classical computers for specific tasks [4].This has stirred a shift from a theoretical standpoint on quantum algorithms to a more programming-oriented view with the question of their concrete coding and implementation [60,70,72].
In this context, a particularly important problem is the adequacy between the mathematical description of an algorithm and its concrete implementation as a program.
1.2 The hybrid model.The vast majority of quantum algorithms are described within the quantum co-processor model [47], i.e. an hybrid model where a classical computer controls a quantum co-processor holding a quantum memory (cf. Figure 1).The co-processor is able to apply a fixed set of elementary operations (buffered as quantum circuits) to update and query (measure) the quantum memory.Importantly, while measurement allows to retrieve classical (probabilistic) information from the quantum memory, it also modifies it (destructive effect).The state of the quantum memory is represented by a linear combination of possible concrete values -generalizing the classical notion of probabilities to the complex case, and the core of a quantum algorithm consists in successfully setting the memory in a specific quantum state.
Outputs: The least integer r > 0 such that x r = 1 (mod N ).

Procedure:
1 Major quantum programming languages such as Quipper [33], Liqui|⟩ [73], Q# [69], ProjectQ [68], Silq [10], and the rich ecosystem of existing quantum programming frameworks [60] follow this hybrid model and provide dedicated features for interacting with the quantum memory and well-suited for implementing quantum algorithms.They usually embed these features within a standard classical programming language, with forth (send quantum instructions) and backs (get measurement results) between the classical control loop (classical computer) and the quantum part (co-processor).Such circuitbuilding quantum languages are the current consensus for highlevel executable quantum programming languages.
the algorithm is therefore both the specification -the global memory-state transformation -and the way to realize it -the list of elementary operations, or quantum circuit.
A major issue is then to verify that the circuit generated by the code written as an implementation of a given algorithm is indeed a run of this algorithm, and that the circuit has indeed the specified size.
1. 4 The case for quantum formal verification.While testing and debugging are the common verification practice in classical programming, they become extremely complicated in the quantum case.Indeed, debugging and assertion checking are essentially impossible due to the destructive aspect of quantum measurement.Moreover, the probabilistic nature of quantum algorithms seriously impedes system-level quantum testing.Finally, classical emulation of quantum algorithms is (strongly believed to be) intractable.
On the other hand, nothing prevents a priori the formal verification of quantum programs.Formal methods and formal verification [16] design a wide range of techniques aiming at proving the correctness of a system with absolute, mathematical guarantee -reasoning over all possible inputs and paths of the system, with methods drawn from logic, automated reasoning and program analysis.The last two decades have seen an extraordinary blooming of the field, with significant case-studies ranging from pure mathematics [32] to complete software architectures [46,49] and industrial systems [7,19].In addition to offering an alternative to testing, formal verification has in principle the decisive additional advantages to both enable parametric proof certificates and offer once-for-all absolute guarantees for the correctness of programs.
1.5 Goal and challenges.Our goal is to provide a formal development framework for circuitbuilding quantum programs, including specification, programming and verification.Such a framework should satisfy the following principles.Close to algorithmic description.It should enable to specify and code algorithms in a way that directly matches their usual description from the literature, in order both to lower implementation & certification time and to increase confidence in the specification.Separation of concerns.It should enable a clear distinction between code and specification, in order to decouple implementation from certification -in particular, specification should be optional and it should be possible to add it to a program at a later stage.Parametricity.It should allow parametric (i.e.scale-invariant) specifications and proofs, so as to enable the generic specification and verification of parametrized algorithms.This is crucial as quantum algorithms always describe parametrized families of circuits.Proof automation.It should, as far as possible, provide automatic proof means.Indeed, program verification should be as painless as possible to the programmer in order to be adopted.
These requirements raise several challenges from the formal verification point of view.Indeed, while questions about semantics, properties, specification and efficient verification algorithms have been largely investigated in the standard case, everything remains to be done in the quantum case.For example: Non-standard data: Quantum algorithms rely heavily on amplitudes (generalization of probabilities to arbitrary complex numbers), not studied at all in standard verification; Second-order reasoning: We are interested here in parametrized circuit-building programs, i.e.
programs that describe families of circuits meeting some postcondition -this is somehow akin to addressing dynamic code (i.e., jit) in the classical case.The major scientific questions at stake here are: (1) How to specify quantum programs in a natural way?(2) How to support efficient proof automation for quantum programs?1. QHL [50] 2. QMC [29,76] 3. [12] 4. Qwire [37,58,63] 5. Path-sums [1,2] We omit [50] as their high-level formalism is not circuit-based As a matter of fact, prior works on quantum formal verification do not fully reach these goals.
1.6 Prior attempts.We summarize in Table 3 the state of the art against the requirements laid above for proving properties of quantum programs, while Figure 4 plots the success of the existing methods against scale-sensitivity and algorithm difficulty.Model-checking approaches [29,76] are fully automatic but highly scale-sensitive.Other methods are based on interactive proofs through proof assistants, for instance Coq.One can cite the approach of Boender et al. [12] or Qwire [58,63].These however lack automation and deeply mix code and specification.Moreover, the underlying matrix semantics impedes scalability of the approach -so far it came only with small case-studies: coin_flip [61], teleportation [12], and (recently) Deutsch-Josza1 algorithm [37].Recently, Amy [1,2] developed a powerful framework for reasoning over quantum circuits, the path-sums symbolic representation.Thanks to their good closure properties, reasoning with path-sums is well automated and can scale up to large problem instances (up to 100 qubits).Yet, the method is not parametric and only addresses fixed-size circuits.
Another explored direction tackles the formalization of quantum programs with classical control, where the input/outputs from the quantum co-processor are taken as oracles.Initiated by [74], this line of work does not consider circuit-building languages but rather high-level algorithmic models where quantum circuits are directly given as partial density operators of arbitrary size rather than built from elementary components -somehow, this is akin to verifying an algorithm expressed over sets versus verifying an implementation of the said algorithm working over red-black trees.It uses an extension of Hoare Logic, called Quantum Hoare Logic and designed for the specification of quantum programs as mathematical objects.Recently, the authors focused on the definition, automatic generation [77] and proof support [51,75] for loop invariants in quantum programs invariants.In [50] the authors present a formalization of QHL in Isabelle/HOL and illustrate it on a restricted case of Grover algorithm.

Proposal and contributions.
We propose Qbricks, the first formal verification environment for circuit-building quantum programs, featuring clear separation between code and proof, parametric specification and proof, high degree of proof automation and allowing to encode quantum programs in a natural way, i.e. close to textbook style.Qbricks builds on best practice from formal verification for the classical case (separation of concerns, flexible logical specification language, proof automation, domain-based specialization) and tailors them to the quantum case.
More precisely, while relying on the general framework of deductive verification, we tailor it to the specific needs of quantum, bringing several key innovations along the road.Qbricks builds upon the circuit-building, first-order functional language Qbricks-DSL together with the logical specification language Qbricks-Spec.While minimal, Qbricks-DSL can express implementations of existing non-trivial quantum algorithms and Qbricks-Spec is expressive enough to offer higherorder specification (parametrized circuit production).The two key cornerstones behind Qbricks are: (1) a new Hoare-style proof system, called Hybrid Quantum Hoare Logic (HQHL) dedicated to circuit-building quantum languages, and (2) the new higher-order path-sums (HOPS) symbolic representation of quantum states, extending path-sums Amy [1] to the parametric case while keeping good closure properties -HOPS prove extremely useful both as a specification mechanism and as an automation mechanism.
In the end, we bring the following contributions.
Framework.A programming and verification framework, that is: on one hand, a core domainspecific language (Qbricks-DSL, Section 5) for describing families of quantum circuits, with enough expressive power to describe parametric circuits from non-trivial quantum algorithm; on the other hand, a logical, domain-specific, specification language (Qbricks-Spec, Section 6), tightly integrated with Qbricks-DSL to specify properties of parametrized programs representing families of quantum circuits.
Higher-Order Path-Sums.A flexible symbolic representation for reasoning about quantum states, integrated withing Qbricks-Spec and building upon the recent path-sum symbolic representation [1,2].Our representation, called higher-order path-sums (HOPS), retains the compositional and closure properties of regular path-sums while allowing genericity and parametricity of both specifications and proofs: HOPS expressions not only contain regular path-sum constructs but also terms from Qbricks-DSL.Especially, HOPS provides a unified and powerful way to reason about many essential quantum concepts (Section 6).
Dedicated Proof Engine.We introduce the Hybrid Quantum Hoare Logic (HQHL) deduction system for deductive verification over circuit-building quantum programs -tightly coupled with HOPS and producing proof obligations in the Qbricks-Spec logic, together with deduction abilities dedicated to standard quantum structures (Section 7).
Implementation.This framework is embedded in the Why3 deductive verification tool [11,27] as a DSL, and provides proof automation mechanisms dedicated to the quantum case -this material is grounded in standard mathematics theories -linear algebra, arithmetic, complex numbers, binary operations, etc.-with 450+ definitions and 1,000+ lemmas (Table 23).The Why3 embedding comes with a series of semantic shortcuts designed to increase the overall level of proof automation, based on high-level composition rules and circuit subclasses with simple HOPS semantics (Section 8).
Case studies.We present in Section 9 verified parametric implementations of the quantum part of [66]'s factoring algorithm (Order Finding -Shor-OF), Quantum Phase Estimation (QPE) [17,45] 2 , Grover algorithm [34] (search) and Quantum Fourier Transform (QFT) -all of them being much more complex than previous formally verified circuit-building implementations.Comparison with alternative approaches demonstrate a clear gain in proof effort (on Grover, factor 5 vs. the restricted proof on a high-level algorithm model [50]), while our method achieves a high level of proof automation (95% on Shor-OF).Moreover, we are also able for Shor-OF to prove the polynomial complexity of the circuits produced by our implementation.
1.8 Discussion.The scope of this paper is limited to proving properties of circuit-building quantum programs.We do not claim to support right now the interactions between classical data and quantum data (referred to as "classical control" in the literature), nor the probabilistic side-effect resulting from the measurement.Still, we are already able to target realistic implementations of famous quantum algorithms, and thanks to equational theories for complex and real number we can reason on the probabilistic outcome of a measurement.Also, we do not claim any novelty in the proofs for Shor-OF, QPE or Grover by themselves, but rather the first parametric correctness proofs of the circuits produced by programs implementing Shor-OF, QPE or Grover.
That said, we present the first non trivial, automated, parametric proofs of significant circuit-building quantum programs, where prior works were limited to toy examples, establishing a new baseline for quantum verification of realistic programs.

BACKGROUND: QUANTUM ALGORITHMS AND PROGRAMS
While in classical computing, the state of a bit is either 0 or 1, in quantum computing [54] the state of a quantum bit (or qubit) is described by amplitudes over the two elementary values 0 and 1 (denoted in the Dirac notation with |0⟩ and |1⟩), i.e. linear combinations α 0 |0⟩ + α 1 |1⟩ where α 0 and α 1 are any complex values satisfying |α 0 | 2 + |α 1 | 2 = 1.In a sense, amplitudes are generalization of probabilities.
2.1 Quantum Data Manipulation.The core of a quantum algorithm consists in manipulating a qubit register through two main classes of operations.(1) Quantum gate.Local operation on a fixed number of qubits, whose action consists in the application of a unitary map to the corresponding quantum state vector i.e. a linear and bijective operation preserving norm and orthogonality.The fact that unitary maps are bijective ensures that every unitary gate admits an inverse.Unitary maps over n qubits are usually represented as 2 n × 2 n matrices.(2) Measurement.The retrieval of classical information out of the quantum memory.This operation is probabilistic and modifies the global state of the system: measuring the n-qubit Quantum gates might be applied in sequence or in parallel: sequence application corresponds to map composition (or, equivalently, matrix multiplication), while parallel application corresponds to the Kronecker product, or tensor product, of the original maps -or, equivalently, the Kronecker product of their matrix representations.
Fig. 5.The circuit for QPE As an example of a quantum circuit, we show in Figure 5 the bird-eye view of the circuit of QPE, the (quantum) phase estimation algorithm, a standard primitive in many quantum algorithms.QPE is parametrized by n (a number of wires) and U (a unitary -the oracle) and is built as follows.First, a register of n qubits is initialized in state |0⟩, while another one is initialized in state |v⟩ n .Then comes the circuit itself: a structured sequence of quantum gates, using the unary Hadamard gate H and the circuits U 2 i (realizing U to the power 2 i ) and inverse(QFT (n)) -the reversed Quantum Fourier Transform.Both are defined as sub-circuits in a similar way.
For the purpose of the current discussion, one should simply note two things: (1) the circuit is made of parallel compositions of Hadamard gates and of sequential compositions of controlled U 2 i (the controlled operation is depicted with vertical lines and symbol •); (2) the circuit is parametrized by n and by U .This is very common: in general, a quantum algorithm constructs a circuit whose size and shape depend on the parameters of the problem.It describes a family of quantum circuits.
2.3 Quantum algorithms.Quantum algorithms intend to solve classical problems in a probabilistic way, but with better performance than with classical algorithms.They generally consist in the generation of a quantum circuit based on the problem parameters (e.g. the size of the instance), usually followed by iterating the following three steps: (1) memory initialization, (2) run of the quantum circuit, (3) measure of the memory to retrieve a classical piece of data.
The quantum circuit is seen as a predictive tool that probabilistically gives some (classical) information from which one can infer the targeted result.The fact that the probability is high enough is a direct consequence of the mathematical properties of the unitary map described by the quantum circuit.The essence of the quantum algorithm -and the reason for its efficiencyconsists in describing an efficient circuit realizing this unitary map.
Obtaining guarantees on the families of circuits realized by quantum programs is therefore of uttermost importance.
We use the following famous quantum algorithms throughout the article: • Phase Estimation algorithm (QPE) [17,45]: takes as parameter a matrix U , an eigenvector |v⟩ and answers the eigenvalue of U corresponding to |v⟩.While the algorithm answers in a deterministic way for some sub-cases, in general it only answers up to some probability.• Grover [34]'s search algorithm: given a sparse non-zero function f : {0 . . . 2 n − 1} → {0, 1}, Grover's algorithm outputs one value x such that f (x) = 1 with a probability high-enough to beat brute-force search.• Shor [66]'s factoring algorithm: We consider the quantum part of the algorithm: the Order Finding algorithm.We shall refer to it as Shor-OF.Concretely, given a non prime integer N and a co-prime x, it outputs a period for x modulo N , in time PolyLog(N ) and probability of success O(1).It is based on an application of QPE with a modular multiplication operator as oracle.
2.4 Existing quantum programming languages: the circuit-building paradigm.The standard model for quantum computation is the quantum co-processor model: the quantum memory is stored in a dedicated co-processor that the classical computer accesses through a dedicated interface.This distinction between purely classical computation and manipulation of quantum data is well-suited for most of the existing quantum algorithms.Indeed, they usually consist in two main parts: a classical part, for dealing with classical information and circuit-building, and a quantum part, where the circuit is sent to the quantum co-processor.Quantum programming languages follow this pattern: they usually come up as domain-specific languages embedded in a classical computing framework: The interaction with the quantum coprocessor is handled through an interface allowing for qubit initializations, measurements and elementary quantum gates.Elementary quantum gates are usually buffered into circuits before being sent to the co-processor.Each language then has its own design-choices on how to present the circuit to the programmer and which native circuit-manipulation library to offer.
The bottom line is that, regardless of the language-design choices, the core of a quantum programming language is to offer circuit-building and circuit manipulation operators in order to build as naturally as possible the circuits given in the descriptions of quantum algorithms from the literature.
2.5 Path-Sum Representation.Historically the semantics for quantum circuits has been given in term of unitary matrices [54] acting on Hilbert spaces, that is, the canonical mathematical formalism for quantum computation.If this semantics is well-adapted for representing simple high-level circuit combinators such as the action of control or inversion, it is cumbersome for specifying the semantics of general circuits.
Path sums [1,2] is a recent symbolic representation that has been shown successful for proving equivalence of general quantum circuits.Its strength is to formalize the notation used in e.g. Figure 2. The path-sum of a unitary matrix U is then written as U : |x⟩ → PS(x) where x is a list of booleans.PS(x) is defined with the syntax of Figure 6.The P k (x) are called phase polynomials while the |ϕ k (x)⟩ are basis-kets.
This representation is closed under functional composition and Kronecker product.For instance, if V sends y to PS ′ (y that is in the form shown in Figure 6.However, if it has been shown successful to prove the equivalence of large circuit instances [2], its main limitation stands in the fact that path-sum only address fixed-size circuits.Albeit a useful, compositional tool, it cannot be used for proving properties of parametrized circuit-building quantum programs.
This paper proposes an extension of path-sum semantics to address the parametric verification of general quantum programs.

MOTIVATING EXAMPLE
Let us consider the n-indexed family of circuits consisting of n Hadamard gates, in sequence, as shown in Figure 7. Sequencing two Hadamard gates can easily be shown equivalent to the identity operation.In other word, when fed with |0⟩, if n is even the circuit outputs |0⟩.Albeit small, this circuit family together with its simple specification exemplifies the typical framework we aim at in the context of certification of circuit-building quantum programs:

Post-conditions:
C n sends |x⟩ to |x⟩ C n consists on n gates.

Fig. 7. Motivating Example
• The description of the circuit family is parametrized by a classical parameter (here, the non-negative integer n); • The pre-condition imposes both constraints (here, the evenness of n) and soundness conditions (here, the non-negativeness of n) on the parameters; • The post-condition can both refer to the semantics of the circuit result and to its form and shape (here, its size).
Shortcomings of existing approaches.In order to prove program specifications, the literature offers several methods and tools, yet none of them fits our needs here.
(1) In the expressive Qwire environment [58,63] embedded in Coq, the semantics of quantum programs is based on matrices over complex numbers.If this toy motivating example would be definable, the drawbacks of this approach is in general its lack of scalability and automation.(2) The quantum Hoare logic environment embedded in Isabelle/HOL [50] offers a high-level abstract view of quantum programs -especially it does not offer circuits per se.It is thus not well-suited to detail the fine-grained description of circuit-building implementations, in particular the procedural description of a purely unitary circuit.Coding the toy example in Figure 7 would be extremely ad-hoc and complicated as the framework does not natively offer elementary gates nor iteration over classical integers.(3) The last possibility would be to use path-sums [2]: this framework is scalable and well-suited for sequence of gates, but limited to fixed-size circuits, while we target programs building families of circuits.
It is to be noted that none of these approaches offer the possibility to reason about the size of the produced circuit: either there is no such notion of circuit [50], or the circuit is not an object one can reason on [2,58,63].
By contrast, our own method allows to encode the Hadamard example in Qbricks with 2 lines of codes and 11 lines of specification.Our deduction verification engine then produces 18 proof obligations (ensuring the contract and circuit well-formedness) simple enough so that all of them are automatically discharged by automated provers.
The circuit family presented in Figure 7 will be used in the rest of the paper as a running, toy example for Qbricks.In particular, we show in Example 5.1 how to code it in our framework and how to express the specification in Example 6.2.
Target for Qbricks.The goal of Qbricks is to offer a formal verification framework for realistic circuit-building quantum programs, including parametric specification and proofs.We ultimately demonstrate this ability in Section 9 on implementations of Grover, QPE and Shor-OF -the experimental data are discussed in Section 9.

OUR PROPOSAL FOR CERTIFIED QUANTUM PROGRAMS
A common way to describe quantum algorithms in the literature is to declare, or describe, either semi-formally or in natural language, a sequence of unitary operations to be implemented, intercrossed with a sequence of formal assertions describing the evolution of the state of the system along the performance of these functions.The example in Figure 2 illustrates this case: it corresponds to the exact description of the circuit for Shor's algorithm at it is written in [54, p. 232].The formal description of state, left column in Figure 2, is interpretable as specifications for the operations declared in the right column.For example, operation create superposition is declared on the right column, line 1.We interpret the formal expression of line 1, left (framed in blue), as its precondition and the one of line 2, left (framed in red), as its post-condition.
Our key observation is that standard quantum algorithm descriptions match perfectly with the process of deductive program verification [26,39], a well established formal method.[5,26,27,39] is probably the oldest formal method technique, dating back to 1969 [39].In this approach, programs are annotated with logical assertions, such as pre-and post-conditions for operations or loop invariants, then so-called proof obligations are automatically generated (e.g., by the weakest precondition algorithm) in such a way that proving (a.k.a.discharging) them ensures that the logical assertions hold along any execution of the program.These proof obligations are commonly proven by help of proof assistants or automatic solvers.

Deductive verification for quantum programs. Deductive program verification
In more details, for any function f , annotations by precondition pre and postcondition post are to be understood as a contract for the implementation: the programmer commits to ensuring that the output of f satisfies post for any input satisfying pre, which, in essence, translates into Suppose that the function f is defined, specified and verified.And suppose one defines and specifies a further function д, using a call f (a) to f .This generates a new proof obligation .To fulfill it, the already verified proof obligation for f is assumed as an hypothesis.
This compositional reasoning method is particularly well-suited to the compositional nature of circuits.
4.2 Rational for the design of Qbricks.We adopt the methodology presented in Section 4.1 and adapt the key ingredients of deductive verification to the case of circuit-building quantum programs.Hence, Qbricks is equipped with: a domain specific language (DSL) for building circuit families, a dedicated logical specification language, a novel symbolic representation (HOPS) and a new Hoare-style logic -called Hybrid Quantum Hoare Logic (HQHL).
Circuit representation.The language Qbricks-DSL is only aimed at implementing quantum algorithms and specifications provided in the form of Figure 2. The circuits used in quantum algorithms act in general on contiguous blocks of memory registers and consist of simple compositions and hierarchical descriptions.Thus, unlike existing quantum programming languages such as Quipper [33] or Qwire [58], for Qbricks there is no need for complex wire manipulation.
Following this analysis, the low-level circuit-representation we choose as a target Qbricks is akin to the one of qPCF [56]: a circuit is a simple compositional structure consisting of base gates and circuit combinators such as sequential and parallel composition, control, inversion, etc.These constructions are packaged withing a domain-specific language (DSL) aimed at describing families of circuits.
Symbolic representation of quantum circuits.As mentioned in Section 2.5, if path-sums offer a compositional specification framework, they address the case of fixed-size circuits.In particular, one cannot give specification to general, parametrized programs describing families of circuits.
Qbricks proposes a solution to this limitation, by unifying what can be done with the matrix and the path-sum semantics.Our proposal is a higher-order path-sum semantics (HOPS).On one hand, we keep the functional view on the action of circuits on quantum registers, making it suitable for deductive verification.On the other hand, we extend its syntax to support parametric circuit construction, high-level circuit combinators and reference to Qbricks-DSL constructs.
Specification and verification.It turns out that HOPS offer a very convenient specification mechanism for quantum programs.They form the bedrock of the Qbricks-DSL specification language -together with a few other theories such as bit-vectors, integers or complex values.
It also turns out that HOPS are convenient for verification purpose too: we design a proofobligation generation procedure within HQHL dedicated to circuit-building quantum languages, yielding proof obligations in the Qbricks-DSL (first-order) logic.
Finally, while part of the Qbricks-DSL logic can be directly handled by automated solvers (such as SMT), we add dedicated equational theories and axioms for those parts of the logic (e.g., HOPS manipulation or complex values).
Implementation.We implement Qbricks as a domain-specific language embedded in the Why3 deductive verification tool [11,27], allowing to take advantage of its advanced programming, specification and verification features for classical programs.We add all quantum-related features on top of it.
An overview of Qbricks certified implementation process is depicted in Figure 8: the user writes a Qbricks-DSL programs together with Qbricks-Spec specifications.Our HQHL engine produces proof obligations in Qbricks-DSL logic.Taking advantage of the interface provided by Why3 embedding, the user can either directly send these proof obligations to a series of SMT-solvers for validation, together with our circuits specifications equational theories, or facilitate solving by use of a series of interactive predicate transformation commands (such as introduction of lemmas or hypotheses, beta-reduction, etc).
5 Qbricks-DSL Qbricks is structured as a domain-specific language (DSL), called Qbricks-DSL, and a domainspecific logical specification language called Qbricks-Spec.The language is targeted for circuit description: measurement is out of the scope of the language, and all Qbricks-DSL expressions are terminating.We follow a very simple strategy for circuit building: we use a regular inductive datatype for circuits, where the data constructors are elementary gates, sequential and parallel composition, and ancilla creation.In particular, unlike e.g.Quipper or Qwire, a quantum circuit is not a function acting on qubits: it is a simple, static object.Nonetheless, for the sake of implementing Fig. 9. Circuit combinators quantum circuits from the literature this does not restrict expressivity as they are usually precisely represented as sequences of blocks.
Even if the language does not feature measurement, it is nonetheless possible to reason on probabilistic outputs of circuits, if we were to measure the result of a circuit.Indeed, this can be expressed in a regular theory of real and complex numbers.
Qbricks-DSL is designed as a first-order, functional language: for the purpose of circuit construction, this is enough and designing a deductive system for it can then be done in a canonical way, following e.g.Why3 strategy.Similarly, the specification language Qbricks-Spec is a first-order predicate language, equipped with various equational theories.This makes proof-obligations more easily amenable to automated solvers.
In the rest of this section, we present the language Qbricks-DSL.Section 6 is then devoted to Qbricks-Spec while Section 7 to the deduction rules.
5.1 Syntax of Qbricks-DSL.The DSL Qbricks-DSL is a small first-order functional, call-byvalue language with a special datatype circ as the media to build and manipulate circuits.The core of Qbricks-DSL can be presented as a simply-typed calculus, presented in Figure 10.The basic data constructors for circ are CNOT, SWAP, ID, H, Ph(e) and R z (e) (see Table 16 in the Appendix for their semantics).The constructor for high-level circuit operations are sequential composition SEQ, parallel composition PAR and ancilla creation/termination ANC (see Figure 9 for details).
On top of circ, the type system of Qbricks-DSL features the type of integers int (with constructors n, one for each integer n), booleans bool (with constructors tt and ff), and n-ary products (with constructor ⟨e 1 , . . ., e n ⟩).This type system is not meant to be exhaustive and it can be extended with usual constructs such as floats, lists and other user-defined inductive datatypesits embedding into WhyML makes it easy to use such types.The term constructs are limited to function calls, let-style composition, test with if-then-else and simple iteration: , with n calls to f .We again stress out that this could easily be extended -we just do not need it for our purpose.
The language is essentially first-order: this is reflected by the types A of expressions.The type of a function is given by the types of its arguments and the type of its output.By abuse of notation, the type of a function with inputs of types A i and output of type B is written A function f is either a function f d defined with a declaration d or a constant function f c .The functions defined by declarations must not be mutually recursive: this small, restricted language only features iteration.Constant functions consist in integer operators (+, * , −, etc), boolean operators (∧, ∨, ¬, →, etc), Comparison operators (<, ≤, ≥, > ,=, : int × int → bool) and high-level circuit operators: ctl, invert : circ → circ for controlling and inverting circuits, and width, size : circ → int for counting the number of input and output wires, and the number Function f The typing rules are the usual ones (summarized for convenience in Table 11).

Operational semantics.
As any other regular functional programming language, Qbricks-DSL is equipped with an operational semantics based on beta-reduction and substitution.We define a notion of value and applicative context as in Table 10.We then define a rewriting strategy as the relation defined with C[e] → C[e ′ ] whenever e → e ′ is one of the rule of Table 12.The table is split into the rules for the language constructs and the rules defining the behavior of the constant functions.We only give a subset of the latter rules.For instance, the arithmetic operations are defined in a canonical manner, and the boolean and comparison operators are defined in a similar manner on values of type int and bool.The rules for the constant functions acting on circuits are also for the most part straightforward: the size of a sequence is the sum of the sizes of the compounds for instance.The rules which we do not provide are the ones for the control operation ctl: the intuition behind their definition can be found in Figure 9.For the elementary gates, any definition can be used (see e.g.[54]), as long as it can be written with the chosen set of gates.One just has to then adjust the lemmas referring to ctl in Qbricks-Spec.Similarly, the invert Language constructs Assuming that there is a declaration f (x 1 , . . ., if tt then e 1 else e 2 → e 1 if ff then e 1 else e 2 → e 2 when n ≤ 0: iter f n a → a when n > 0: Constant functions (subset of the rules) Table 12.Operational semantics for Qbricks-DSL of elementary gates are not given: we can choose the usual ones from the litterature -and this definition is then parametrized by the choice of gates.
5.3 Properties.Note that the target low-level representation for an expression of type circ is a value made of the circuit data constructors.This is derived from the safety properties of the language: Property 5.3.1 (Safety properties and normalization).Provided that Γ ⊢ e : A and e → e ′ , then Γ ⊢ e ′ : A. Provided that ⊢ e : A is a closed expression, and provided that all the function in e recursively admits (external) definitions, then either e is a value or it reduces.Finally, the reduction strategy (→) is normalizing: there does not exist an infinite reduction sequence e 1 → e 2 → . . .□ Example 5.1.The motivating example of Section 3 can be written in Qbricks-DSL as The function aux inputs a circuit and append a Hadamard gate at the end.The function main then input an integer parameter n and iterate the function aux to obtain n Hadamard in sequence.In particular, one can show that for instance that is, a sequence of 4 Hadamard gates.
5.4 Universality and usability of the chosen circuit constructs.In Qbricks-DSL, we use a restricted, small set of elementary circuit building blocks.For instance, we have not included the NOT-gate ( 0 1 1 0 ) .This is a design choice: the chosen elementary gates are not meant to be convenient but simple to specify yet forming a universal set of gates: A universal (resp.pseudo-universal) set of elementary gates is such that they can be composed thanks to sequence or parallelism so as to perform (resp.approach arbitrarily close) any quantum unitary matrix.
Other, maybe more convenient gates can then be defined as macros on top of them.If one aims at using Qbricks inside a verification compilation tool-chain, these macros can for instance be the gates of the targeted architecture.

Validity of circuits.
A circuit is represented as a rigid rectangular shape with a fixed number of input and output wires.In particular, there is a notion of validity: a circ object only makes sense provided two constraints: • in SEQ(C 1 , C 2 ), the two circuits C 1 and C 2 should have the same number of wires (i.e. the same size).For instance, SEQ(CNOT, H) is not valid: one cannot put in sequence a 2-qubit gates with a 1-qubit gate.This is a simple syntactic constraint; • in ANC(C), the circuit C should have n + 1 wires.Moreover, if given as input a vector where the last qubit is in state |0⟩, its output should also leave this qubit in state |0⟩.This condition is on the other hand a semantic constraint.Note that even the syntactic constraints cannot be checked by a simple typing procedure, because of the higher-order reasoning involved here: the constraints must hold for any value of the parameters.All these syntactic and semantic constraints are thus expressed in Qbricks-Spec, our domainspecific logical specification language, and meant to be sent as proof obligations to a proof engine.
Example 5.2.Note how the circuit generated by main in Example 5.1 is not necessarily a valid circuit (although in this case it is).This is one of the constraints that can be handled by Qbricks-Spec, as shown in Example 6.2.

Denotational semantics.
As all expressions in Qbricks-DSL are terminating, one can use regular sets as denotational semantics for the language.In order to be able to handle the partial definitions coming up in Section 6, we include in the denotation of each type an "error" element ⊥ We therefore define the denotation of basic types as the set of their values: Finally, functions are defined as set-functions from the input set to the output set.The denotation of the language constructs are the usual one in a semantics based on sets ; for the constant functions, the definitions are the canonical ones: arithmetic operations maps to arithmetic operations for instance.In Qbricks-DSL, everything is well-defined and ⊥ is only attainable from ⊥ -so for instance, ⊥ + x = ⊥.
Note that in the denotational semantics one can build non-valid circuits.For instance, the circuit SEQ(CNOT, H) is a member of [|circ| ].This is to be expected as we aim at the following property: 6 Qbricks-SPEC In term of semantics of quantum circuits, the main novelty of Qbricks is to be able to reason on open terms seen as circuit description, parametrized programs.To do so, we build upon the recent proposal of path-sums [1,2].In Qbricks-Spec, we define the notion of higher-order pathsums (HOPS).Original path-sums in [1] are fixed functionals, computed from concrete, fixed-size circuits.In HOPS, the phase polynomials, ranges and basis kets are instead written as open terms from Qbricks-DSL, parametrized with term variables.This correspondence.This integration with Qbricks-DSL brings two decisive advantages compared to the original path-sums: • Parametricity and compositionality.Because of the sharing of term variables between Qbricks-DSL terms and HOPS, Qbricks-Spec gives the ability to give specification to general programs describing families of circuits instead of fixed-size circuits.Qbricks-Spec opens path-sums to higher-order specification and verification while retaining the vertical and horizontal compositional properties; • Versatility.Thanks to the integration within a logical framework, Qbricks-Spec gives the ability to define -and reason-upon logical macros asserting useful constraints related to probabilities, eigenvalues, etc (See Section 7.4.
6.1 Syntax of Qbricks-Spec.Qbricks-Spec consists of a set of dedicated relations and functions, together with a language of algebraic expressions on top of a first-order logic, together with logical libraries to express constraints.We define Qbricks-Spec as a first-order, predicate logic with the following syntax.
Formula ϕ,ψ : The first-order expressions ê form a subset of Qbricks-DSL: they are restricted to variables and (formal) function calls to other first-order expressions.Unlike regular, general expressions -meant to be computational vehicles-these first-order expressions only aim at being reasoned upon.The functions names are then expanded with logic functions f ℓ with no computational content.Among these new functions, we introduce one function iter f : int × A → A for each function f : A → A, standing for the equational counterpart of the iteration.The logic functions are defined equationally in the logic: see Section 7 for details.The relation R ranges over a list of constant relations over first-order expressions.An important one is circ_valid : circ → bool, expressing the syntactic property V syntax of Definition 5.3.In Qbricks-Spec, we identify relations and functions of return type bool.Constant relations are therefore simply constant functions of output type bool.
The type system of Qbricks-Spec is extended with opaque types, equipped with constant functions and relations to reason upon them.They come with no computational content: the aim is purely to be able to express and prove specification properties of programs.This is why we did not incorporate them in Qbricks-DSL's type system.
The opaque types we consider in Qbricks-Spec are complex, real, bitvector, hops and ket.The operators and relations for these new types are given in Table 13.Note that in the rest of the paper, by abuse of notation we shall omit the casting operations i_to_r and r_to_c.We shall also use a declared exponentiation function [−] [−] overloaded by abuse of notation with type complex × int → complex and real × int → real.The three types complex, real and bitvector are standard; the types hops and ket are novel and form the main reasoning vehicle in Qbricks-Spec.

6.2
The types hops and ket.In short, the type hops encodes our higher-order path sum (HOPS) representation for expressions of type circ in Qbricks-DSL, while ket encodes the notion of ket-vector.As these types are pure reasoning apparatus, we only need them in Qbricks-Spec and they are defined uniquely though an equational theory.
As shown in Figure 6, a regular path-sum is a static abstract object consisting of 4 pieces: a global range (the value n), what we shall be calling its width, i.e. the size of the bit-vector x, and the phase polynomial 2 m and the ket vector ϕ k (x), functions of both the input x and the index k.To reflect this structure, the type hops is equipped with 4 constant functions acting on an HOPS (see Table 13): hops_width, yielding its width, hops_range, yielding its range, hops_angle, complex and real i, π : complex i_to_r : int → real r_to_c : real → complex Re, Im, abs Table 13.Primary operators for Qbricks-Spec yielding the real number corresponding to P k (x ) 2 m , and hops_ket yielding the ket-vector ϕ k (x).Note how the two last functions also inputs two bit-vectors, corresponding to k and x.If path-sums compose nicely, a given linear map does not have a unique representative path-sum (partly due to the fact that phase polynomials are equal modulo 2π ).To capture this equivalence, we introduce the constant relation hops_equiv.In order to relate circuits and HOPS, we introduce the constant function circ_to_hops: it returns one possible HOPS that represents the input circuit.The chosen HOPS is built in a constructive manner on the structure of the circuit.A useful relation is (− ▷ −) relating a circuit and a HOPS: it is defined as (c ▷ h) ≜ hops_equiv(circ_to_hops(c), h).Another useful macro is the function circ_apply : circ × ket → ket, defined as circ_apply(C, k) ≜ hops_apply(circ_to_hops(C), k).
The type ket is a handle to easily manipulate ket-vectors, and Table 13 presents the constant functions meant to manipulate it.bv_to_ket builds a basis ket-vector out of the input bit vector ; ket_length returns the number of qubits in the ket ; ket_get returns the amplitude of the corresponding basis ket-vector.The other operations are the usual operations on vectors: addition, subtraction, tensors, scalar multiplication.Finally, the function hops_apply relates hops and ket: it identifies the input HOPS to a functional and applies it to the input ket-vector.

Denotational semantics of the new types.
The denotational semantics of real and complex are respectively the sets R ∪ {⊥} and C ∪ {⊥}, and the denotation of the operators are the canonical ones.As for Section 5, ⊥ maps to ⊥, so for instance ⊥ + r x = ⊥.
The denotation of bitvector is defined as the set of all bit-vectors, together with the "error" element ⊥.The constant functions are mapped to their natural candidate definition, using ⊥ as the default result when they should not be defined.So for instance, An element of ket is meant to be a ket-vector: we defined [|ket| ] as the set of all possible ketvectors 2 n i=0 α n |b n ⟩ m , for all possible m, n ∈ N, α n ∈ C and bit-vectors b n of size m, together with the error element ⊥.
Finally, hops is defined as the set of formal path-sums, as defined in Table 6, together with the error element ⊥.The denotation of the constant functions are defined as discussed in Section 6.2.As an example, [|hops_range| ] returns the range of the corresponding HOPS.The map circ_to_hops builds a valid HOPS out of the input circuit, or ⊥ if the circuit is not valid.The defined HOPS follows the structure of the circuit.For instance, circ_to_hops(SEQ(C 1 , C 2 )) is the sequential composition of the two HOPS circ_to_hops(C 1 ) and circ_to_hops(C 2 ) (as shown in Equation ( 1)).

Parametricity of HOPS.
A regular path-sum is not parametric: it represents one fixed functional.So why did we chose [|hops| ] to be a set of path-sums?Let us consider an example.Example 6.1.Consider the motivating example of Section 3 and its instantiation in Example 5.1.The function main describes a family of circuits indexed by an integer parameter n.Now, consider the typing judgment h : hops, n : int ⊢ (main(n) ▷ h) : bool.It can be regarded as a relation between HOPS h and integers n, valid whenever h represents main(n).Technically, this relation is not quite the graph of a function (since several HOPS might match the circuit main(n)).Nonetheless, to each n is associated a different set of HOPS h: in this sense, one can say that h is "higher-order", as it is parametrized by n.Thus the "HOPS" terminology.
6.5 Regular sequents and HQHL sequents in Qbricks-Spec.Formulas in Qbricks-Spec are typed objects -and to a certain extent one can identify them with first-order expressions of type bool.Due to this correspondence, we shall only say that logic judgments in Qbricks-Spec are well-formed judgments of the form ∆ ⊢ ϕ where the well-formedness means that ∆ ⊢ ϕ : bool is a valid typing judgment in Qbricks-DSL.That being said, a well-formed judgment ∆ ⊢ ϕ is valid whenever it holds in the denotational semantics: for every instantiation σ sending x : A in ∆ to [|A| ], the denotation [|ϕ | ] σ is valid.In particular, the (free) variables of ϕ can be regarded as universally quantified by the context ∆.
Another useful kind of judgment is one allowing equational reasoning on terms: if ∆ ⊢ e 1 : A and ∆ ⊢ e 2 : A are valid Qbricks − DSL typing judgments, the judgment ∆ ⊩ e 1 = e 2 : A is valid whenever for every instantiation σ sending x : B in ∆ to [|B| ], the denotations of e 1 and e 2 with respect to σ are equal (as set-elements).
In order to be able to express program specifications with pre-and post-conditions, we finally define a HQHL sequent of the form ∆ ⊩ {ϕ}e{ψ } : A (we omit the type A when irrelevant or clear).The formula ψ can make use of a reserved free variable result of type A. Such a sequent is then well-formed provided that ∆ ⊢ ϕ : bool, ∆, result : A ⊢ ψ : bool and ∆ ⊢ e : A are valid typing judgments.Note how the reserved free variable result is being added to ∆ for typing ψ .For convenience, we also extend the notation to result i to stand for the ith projection of result when A is of the form Then the point is that first, families of quantum circuits can be described in Qbricks-DSL and specifications in Qbricks-Spec, and second, that one can come up with a set of meaningful axioms that are enough to derive these specifications.This is the goal of Section 7.
Example 6.2.Consider the motivating example of Section 3 and its instantiation in Example 5.1.We can now give a specification to the function main, as follows: The fact that circ_apply is well-defined implies that C is valid.

THE HQHL DEDUCTION SYSTEM
Thanks to the logic judgments presented in Section 6.5, it is possible to reason with Qbricks-Spec formulas on expressions written in Qbricks-DSL.If we showed how to give a semantical meaning to the validity of a judgment, we have not explained how to derive such a validity from first principles.This is the purpose of the current section.
Property 7.0.1 (Validity of the deduction rules).All of the deduction rules that we add in this section are sound with respect to the semantics.□ Note that we do not aim in this section at being exhaustive: we only aim at giving an intuition as of how and why one can rely on an automated deductive system to derive Qbricks-Spec judgments.In particular, we show how to break down a program specification into a set of proof obligations that can be sent to an SMT solver to be automatically discharged.
7.1 Deriving HQHL judgments.In Example 6.2, we were able to state a HQHL judgment for the motivating example of Section 3. Using a bottom-up strategy, it is possible to use the deduction rules of Figure 14 to break down the judgments into pieces reasoning on smaller terms.Along the way, there is the need for introducing invariants and assertions.As usual, some of these assertions can be derived by computing the weakest-preconditions: we do not necessarily have to introduce every single one.
In the deduction rule (iter) of Figure 14, the first-order expression ê1 is mechanically built from e 1 by inlining function calls, replacing P[if e 1 then e 2 − else e 3 ] with the equivalent formulation (e 1 ∧ P[e 2 ]) ∨ (¬e 1 ∧ P[e 3 ]), changing let's with calls to projections, and replacing each iter f a i with its functional counterpart iter f (a, i).The deduction rule (eq) states that whenever one can show that two expressions are equal one can substitute one for the other inside a HQHL judgment.Finally, we can derive from the semantics the usual substitution rules.For instance, provided that Γ, x : A ⊢ ψ and Γ ⊢ e : The rules of Figure 14 make it possible to break an expression down to a first-order expression from Qbricks-Spec.When such a case is attained one can rely on the rule to generate a proof obligation as a regular sequent in Qbricks-Spec.Of course, there is no guarantee that any such proof-obligation can automatically be discharged.However, our work show that this strategy can successfully be applied, as exemplified by the non-trivial case studies we considered in Section 9.
7.2 Deduction rules for hops.The main tools to relate circuits and HOPS are the constant function circ_to_hops, its relational counterpart (− ▷ −), and the declared function circ_apply.
They can be specified inductively on the structure of the input circuit.As an example of a lemma to be added for reasoning on (− ▷ −), consider the case of the Hadamard gate.The sequent Γ ⊢ (H ▷ h) can be derived from This simply states that the HOPS of the Hadamard gate is of the form |x⟩ 1 → 1 j=0 (−1) ì x 0 * ì y 0 |y⟩ 1 .For the circuit combinator PAR, one can state the rule where hops_par(h 1 , h 2 , h 3 , ì x, ì y) is a formula encapsulating the relationship between the phase polynomials, the kets, the ranges and the widths of h 1 , h 2 and h 3 , as shown in Equation (1) in Section 2.5.The complete set of rules for (− ▷ −) can be found in Appendix C 7.3 Equational reasoning.The SMT solvers we aim at using to discharge proof obligations requires equational theories describing how to reason on the constant functions that were introduced.Some of these equational theories are standard and well-known in verification: for instance, bit-vectors and algebraic fields.Together with a few properties on square-root, exponentiation, real and imaginary parts, the latter is all we need for real and complex: in quantum computation, the manipulations of real and complex numbers turns out to be quite limited.In particular, we do not need anything related to real or complex analysis.The main difficulty in the design of Qbricks has been to lay out equational theories and lemmas for circ, hops and ket that can efficiently help in automatically discharging proof obligations.Many of these equations and lemmas are quite straightforward.For instance, we turn the rewriting rules of Table 12 into equations, such as (x, y : circ) ⊩ width(PAR(x, y)) = width(x) + width(y), or n : int ⊩ iter f (a, n + 1) = f (iter f (a, n)).These equations maps the (syntactic) computational behavior of expressions into the logic.Other equations are expressing purely semantic properties.For instance, the equation is correct with respect to the semantics and is part of the equational theory.
Circuit size.An important equational theory that we need in Qbricks-Spec is one for reasoning on the size of circuits.Being able to reason on circuit size is one of the important feature for the certifying an quantum algorithm implementation: one of its main point is for instance the polynomiality of the number of gates over the size of the input.We again stress out that this aspect of certification is not addressed by existing approaches [1,37,50].
As we discussed above, the equational theory for circuits reflects the rewrite rules.For instance, we have (x, y : circ) ⊩ size(PAR(x, y)) = size(x) + size(y).A complete set of rules can be found in Appendix, in Figure 18.We can specify the size of the resulting circuit, as follows: 7.4 Specialized libraries.For Qbricks we also derived more specialized, non-trivial libraries of lemmas.In particular: Subclasses of circuits.Shortcuts for reasoning on specific classes of circuits.Among them are, in particular, the circuits with an hops of range (1).We call them flat circuits.Flat circuits enjoy a number of simplifying properties that are exposed in Section D. Section D also introduce a further simplified subclass of circuits, called diagonal circuits.Eigenvectors and eigenvalues.One of the common need in the specification of quantum programs (and in particular in the case of QPE) is the need for asserting that a particular ket k is a eigenvector of the unitary map described by some circuit c, with eigenvalue the complex number ρ.In Qbricks-Spec we define the relation eigen(c, k, ρ) as circ_apply(c, k) = ρ * k k Probabilities.A quantum program is usually a probabilistic program: it returns the desired result with a probability that depends on the problem parameters (number of iteration, structure of the problem, etc).If one aims at fully specifying such programs, this probability therefore needs to be expressible as post-condition.
As recalled in Section 2.1, the probability of obtaining a result by a measurement is correlated with the amplitudes of the corresponding ket-basis vectors in the quantum state of the memory.In Qbricks-Spec we define a relation proba_partial_measure : circ × |×⟩ bitvector → Re meaning that when the input circuit is applied to the input ket, if we were to measure the result the probability of obtaining the given vector would be the result of the function.We define it as proba_partial_measure(c, k, x) = (abs(ket_get(circ_apply(c, k), x))) 2 .In the specifications of Grover, QPE and Shor-OF we define specialized functions based on proba_partial_measure specifying the constraints specific to each algorithm.Algebraic operations on operators.In the course of the proof of quantum specification, it is sometimes useful to be able to manipulate algebraic expressions containing building blocks such as rotations or projectors.In Qbricks-Spec, with the use of HOPS it is possible to define such objects as macros, and then prove algebraic equalities between them, that we then add as auxiliary lemmas to be used by the automated provers.The use of HOPS gives us the possibility to specify -and proveequalities parametrized by problem instances.This is for instance used extensively in the proof of the Grover specification.

IMPLEMENTATION
The Qbricks framework described so far is implemented as a DSL embedded inside the Why3 deductive verification platform [11,28], written in the WhyML programming language. 4This allows us to benefit from several strengths of Why3, such as efficient code extraction toward Ocaml, generation of proof obligations (to implement the HQHL mechanism) and access to several proof means.Indeed, a dedicated interface enables direct access to proof obligations and either send them to a set of automatic SMT-solvers (CBC4, Alt-Ergo, Z3, etc.), or enter a number of interactive proof transformation commands (calls for lemmas or hypotheses, term substitutions, etc.) or even send them towards proof assistants (Coq, Isabelle/HOL) -we do not use this option in our case-studies.
The development itself counts 17,000+ lines of code, including 400+ definitions and 1700+ lemmas, all proved within Why3.Most of the development concerns the (verified) mathematical libraries (14,000+ loc for a total of 17,000+ loc -see Table 23 in Appendix, Section E).They cover the mathematical structures at stake in quantum computing (complex, Kronecker product, bit-vectors, etc.), together with a formally verified collection of mathematical results concerning them.They count 14,000+ lines of code: 300+ definitions, 1600+ lemmas and 32 axiomatic definitions.

CASE STUDIES AND EXPERIMENTAL EVALUATION
Thanks to our implementation of Qbricks, we could develop and prove parametric implementations of several emblematic quantum algorithms, namely Grover search, QFT, QPE and Shor-OF.We also implemented Deutsch-Jozsa for the sake of comparison with prior work.9.1 Case studies.Before discussing the experimental evaluation in Section 9.2, let us first introduce our implementations of QPE, Shor-OF and Grover algorithms 5 .
Quantum Phase Estimation (QPE).Developed by Cleve et al. [17], Kitaev [45], this procedure inputs a unitary operator U and an eigenvector |v⟩ of U and finds the eigenvalue e 2π iΦ v associated with |v⟩.It is a central piece in many emblematic algorithms, such as quantum simulation [30] or HHL algorithm [36] -resolution of linear systems of equations in time PolyLog.We implemented two different versions of QPE: • In the first case (core case) we assume that Φ v admits a binary writing with n bits.Then there is 2 n , and the eigenvalue associated with |v⟩ is e 2π iΦ v (also written ω φ v n ).The goal is to seek this value φ v and the algorithm deterministically outputs this value.• In the second version (general case), no assumption is made over Φ v which can take any real value such that 0 ≤ Φ < 1.The goal is to seek the value k ∈ 0, 2 n that minimizes the distance Φ − k 2 n (modulo 1).The output of the algorithm is non deterministic.The proved specification is that it outputs k with probability at least 4 π 2 .
Shor [66]'s algorithm.Certainly the most emblematic of all quantum algorithms, it implements integer factoring by polynomial reduction to Order Finding.The quantum circuit -the quantum part of the algorithm, the one we are certifying-consists in an application of QPE to the unitary operator U : |y⟩ → |x • y mod N ⟩.We developed a certified concrete implementation following the implementation proposed in [6] -a reference in term of complexity.Besides proving the functional requirements of the order-finding problem (including achieving it with probability O( 1)), we also prove some appreciable complexity results: our implementation requires applying O(Log 2 (N )) 4  quantum gates and requires 4Log 2 (N ) + 2 qubits. 6rover search algorithm.Developed by Grover [34], in its first version, it enables to find a distinguished element in an unstructured data base with a quadratic speedup with regards to the best known equivalent classical approaches.It was then generalized by Boyer et al. [13] to the similar problem with a parameterized number k of distinguished elements.We implemented this most general case, without any restriction over k.
9.2 Experimental evaluation.In addition to QPE, Shor-OF and Grover algorithm, we also consider implementations of the Quantum Fourier Transform (QFT) and the Deutsch-Josza algorithm.
We have been successful on all the cases, providing the first verified parametric implementation of QFT, QPE, Shor-OF and Grover.
Different metrics about our formal developments are reported in Table 15 7 : lines of decorated code, lemmas, proof obligations (PO), automatically proven PO (within time limit 5 seconds), remaining POs and the number of interactive commands we entered to discharge them -this last metric is detailed in Table 29 in Appendix, Section F.2.
Note that metrics for each implementation strictly concern the code that is proper to it (eg., QPE contains calls to QFT but QPE line in Table 15 does not include the QFT implementation.Similarly, Shor-OF calls both QPE and QFT) -the whole Shor-OF development is reported in the "Shor-OF full" row and row "Total" sums it with lines DJ and Grover.Result.Qbricks did allow us to implement and verify in a parametric manner the Shor-OF, QPE and Grover algorithms, at a rather smooth cost and with high proof automation (94% in average, 95% for full Shor-OF).
Interestingly, it should be noted that while Grover relies on mechanisms and arguments significantly different from those of QPE or Shor-OF, we were able to implement, specify and prove it without adding anything new to Qbricks -demonstrating the genericity of our approach.
A last interesting observation concerns the time we spent on the different implementations of these case studies, given in chronological order: 1.5 person.year to build Qbricks and be able to implement, specify and prove QFT and a restricted case of QPE -1 person.dayfor DJ -2 person.weeksfor each of QPE (full case) and Grover -and finally 10 person.days to add Shor-OF on top of QPE.Considering how significantly the initial development effort factorizes over further developments, we have good reasons to believe that Qbricks provides a generic and convenient environment for specifying, developing and proving quantum programs in a reasonably fast and easy way.9.3 Comparison with prior works.Table 30 in Appendix (Section F.2) provides a summary of the comparison with these preexisting formal verification efforts for quantum programs.
Regular path-sums.Amy [1,2] uses path sums for the verification of several circuits of complexity similar to that of QFT (QFT, Hidden shift, Toffoli generalized, etc).Yet, these experiments consider fixed circuits (up to 100 qubits) and the technique cannot be applied to parametric families of circuits or circuit-building languages.
QHL. Liu et al. [50] report about the parametric verification of Grover search algorithm, on a restricted case8 and in the high-level algorithm description formalism of QHL -especially QHL has no notion of circuit.Interestingly, the generic verification of our low-level implementation is 5× smaller than theirs: 3184 total lines vs 583 total lines (416 lines + 167 commands).
Qwire.Finally, Hietala et al. [37] have presented in their 2019 preprint a fully verified parametric (circuit-building) implementation of the Deutsch-Josza algorithm in Coq.This implementation is given two independent correction proofs.As already pointed out, DJ is more a standard teaching example (with no practical application) than a representative quantum algorithm -roughly speaking, 10× smaller than Grover and 20× smaller than (full) Shor-OF.Moreover, our development requires significantly less efforts than theirs: less code (53 vs 74 lines) and 5.5× less proof commands (39 vs 222) for their textbook-style version -the one closest to our own version9 .9.4 Summary.It appears that Qbricks provides a powerful framework for the development of formally verified parametric implementations of realistic quantum algorithms, setting up a new baseline in terms of quantum program formal proofs and achieving high scores in terms of proof automation.

RELATED WORKS
Formal verification of quantum circuits.In the last couple of years, several efforts have been led toward introducing formal methods in quantum programming.Prior efforts regarding quantum circuit verification [1,2,12,29,50,58,61,63,76] have been described throughout the paper, especially in Sections 1, 3 and 9.
We build on top of these seminal works and propose the first deductive verification framework for circuit-building quantum programs -the current consensus in quantum programming languages, featuring clear separation between code & proof, parametric specifications & proofs and a high degree of proof automation.
Especially, our technique is more automated than those based on interactive proving [37,63] thanks to the new HQHL Hoare-style deduction system, borrows and extends the path sum representation [2] to the parametric case, and do consider a circuit-building language rather than a high-level algorithm description language [50].
Quantum Languages and Deductive Verification.Liu et al. [50] introduce Quantum Hoare Logic for high-level description of quantum algorithms.QHL and our own HQHL are very different, as the underlying formalisms are very different.Combining the two approaches on a combined formalism is an exciting research direction.
Optimized compilation of circuits.Formal methods and other program analysis techniques are also used in quantum compilation, in order to build highly optimized circuits [3,8,35,38,57,62,67].This is a crucial current research area.Indeed, the quantum hardware available in the near future is expected to be highly constrained in terms of qubits, connectivity and quality: the so-called NISQ era [55,59,71].
Especially, the ZX-calculus [18] represents quantum circuits by diagrams, amenable to automatic simplification through dedicated rewriting rules.This framework leads to a graphical proof assistant [44] geared at certifying the semantic equivalence between circuit diagrams, with application to circuit equivalence checking and certified circuit compilation and optimization [21,22,43].Yet, ZX-calculus is restricted to fixed circuits and cannot handle parametrized families of circuits or circuit-building languages.
Other quantum applications of formal methods.Huang et al. [40,41] proposes a "runtimemonitoring like" verification method for quantum circuits, with an annotation language restricted to structural properties of interest (e.g., superposition or entanglement).Verification of these assertions is led by statistical testing instead of formal proofs.The recent Silq language [10] also represents an advance in the way toward automation in quantum programming.It automatizes uncomputation operations, enabling the programmer to abstract from low level implementation details.Another line of research is concerned with the development of specialized type systems for quantum programming languages.In particular, frameworks based on linear logic [48,64,65] and dependent types [56,58] have been developed to tackle the non-duplicability of qubits and the constraints on the structure of circuits.Finally, formal methods are also at stake for the verification of protocols using quantum information, such as cryptographic protocols [14,20,31,52,53].

CONCLUSION
We have presented Qbricks, the first formal verification environment for circuit-building quantum programs -featuring clear separation between code and proof, parametric specifications and proofs, high degree of proof automation and allowing to encode quantum programs in a natural way.We build on best practices of formal verification for the classical case and tailor them to the quantum case.Especially, while relying on the general framework of deductive verification, we design a new domain-specific circuit-building language Qbricks-DSL for quantum programs together with a new logical specification language Qbricks-Spec and the novel Hybrid Quantum Hoare Logic.Finally, we introduce and intensively build upon higher-order path sums (HOPS), a symbolic representation convenient for both specification (parametricity) and automation (closure).
In order to demonstrate the interest of the full framework, we develop the first verified parametric implementations of three famous non-trivial quantum algorithms (namely Shor-OF, QPE and Grover search), proving by fact that applying formal verification to realistic (circuit-building) quantum programs is possible and should be further developed.

A MATRIX SEMANTICS FOR GATES
The following Table gives the matrix semantics for gates that are used in this article, bringing complements to Section 5.1.
Table 16.Matrix semantics for gates In this section we first introduce some additional definitions and notations about bit-vectors and kets, completing Section 6.1.Here and in the following we commit the abuse to treat boolean values tt and ff as, respectively, 0 and 1, omitting the call for the required cast function.We usually abbreviate bv_get(ì x, i) by ì x i .Type bitvector is given with constructors bv_set and bv_cst Let f be an integer function with values in {0, 1} and let n be a positive integer.Then we define make_bv(f , n) as the sequence (f (0))(f (1)) . . .(f (n − 1)).Formally, let us first introduce predicate binary: We also define concatenation of bit vectors ì x and ì y.It satisfies: Let ì x be a bit vector and let i, j integers 0, bv_length(ì x) such that i < j, then we introduce sections of ì x in, respectively, 0, i , i + 1, bv_lengthì x and i + 1, j .They satisfy the following rules: At last we introduce two functions bv_to_int and int_to_bv, from bit vectors to integers and back, enabling the interpretation of a bit vector as a binary integer : B.2 Kets.Type ket is an opaque type, similar as bit-vectors with complex values.Kets have a number of cells equal to 2 n , for a positive integer n called its logarithmic length (also called, for simplicity, its length).They are defined without norm restriction.Usually, we designate kets using the standard Dirac notation |v⟩ n , with n being the logarithmic length of |v⟩.We drop this n index when unnecessary.Dirac notation is also used as notation for functions casting integers and bit vectors to kets : let k, n be integers such that k ∈ 0, 2 n and let ì x be a bit vector.Then: Functions +, −, ⊗ are introduced and used the usual way over kets : In this section, we complete the introduction of deductive rules for relation (_ ▷ _) from Section 7.2.We first give rules for gates, then rules for composed circuits.
C.1 Gates hops characterization predicates.For any gate in the language, we first introduce a specific predicate characterizing an hops for this gate.Predicate hops_had, for Hadamard gate, was given in Section 7.2, below are similar predicates for the additional gates; C.2 Combining circuits.We also introduce binary and ternary relations between hops, so as to characterize the conditions for relation (_ ▷ _) in combined circuits.This induces one hops relation per circuit combinator: Parallel composition C.3 Deduction rules.As introduced in Section 7.2, the characterization predicates introduced so far serve as hypotheses for compositional deduction rules for relation (▷).These rules are given in Table 17.
C.4 Circuit size deduction rules.We end up this section by providing the compositional deduction rules for circuit sizes, in Figure 18 : SWAP and ID gates have size 0, the other gates have size 1, composing two circuits either in sequence or in parallel adds up their sizes, controlling a circuit raises its size by factor at most constant ctl-size-const and discarding an ancilla qubit does not affect the size of a circuit.

D REASONING ABOUT HOPS: SPECIAL CIRCUIT SUBCLASSES
In this section, we complement Section 7.4 by presenting reasoning rules dedicated to specific cases of circuits, namely flat and diagonal circuits.D.1 Flat circuits.Observe from definitions in Section C.1 that all gates but Hadamard have a correct hops with hops_range equal to 0. We call an hops with range 0 an hop, and we call the circuit property of admitting a correct hop being flat.
One easily observes that flatness is stable through sequence, parallel, control and ancilla composition.In an hop h, function hops_apply is a pseudo-sum of one term, indexed by the only bit-vector ì y of length 0 (written (ì • 0 )).Then we defined functions flat_h_ket and flat_h_angle and we have: Furthermore, for any given flat circuit C, functions flat_h_angle and flat_h_ket are actually independent of the choice of an hop correct for C. Formally, we have the following theorem : Thus, we can directly use functions flat_angle : circ → bitvector → complex and flat_ket : circ → bitvector → ket for flat circuits: Hence, for the semantics of flat circuits, one can reason directly with functions flat_angle and flat_ket, along the rules given in Figures 19 (flat gates), 20 (flat combined circuits) and 21 (interpreting flat_ket and flat_angle characterizations in terms of hops).
Fig. 19.Deduction rules for Qbricks: Flat gates D.2 Diagonal circuits.A further refinement of the semantics is possible for flat circuits whose function flat_ket behaves as the identity.These circuits are called diagonal circuits.Since this Fig. 20.Deduction rules for Qbricks: Flat circuits property is again preserved through sequence, parallel, control and ancilla composition, we can reason about the semantics of diagonal circuits without care for function flat_ket.

E IMPLEMENTATION: MORE DETAILS
We provide here more details about the implementation, complementing Section 8.
E.1 Framework overview.The overall Qbricks verification chain is depicted in Figure 22.
Implementation.The first step concerns the design of an algorithm A with parameters − → p thanks to Qbricks-DSL and Qbricks-Spec.Qbricks is embedded in the Why3 programming language (called WhyML).We provide for it a set of mathematical libraries, enabling reasoning about Qbricks-Spec formulas (see Section E.2 below for further details about these).Note that specifications are inserted within the implementation, as decorations for functions.The specification material may also contain, still within the implementation, intermediary lemmas and ghost material (either ghost definition for functions objects that are used exclusively for the specifications, or ghost elements inserted as parameters for non-ghost functions).
Code extraction, PO generation.Next, we can perform two different Why3 compilation operations: • Code extraction, which basically consists in deleting all the ghost material from the implementation.It results in a simple Ocaml implementation of A with parameters − → p .
• Compilation of the specification code, generating: first order logic proof obligations (POs).
first order logic axioms, formalizing definitions from the algorithm implementation.They contribute to the logical context to evaluate PO satisfaction, together with, for any function f , specifications for functions above f or from imported files.
Solving.Then Qbricks takes advantage of various means to prove the generated POs modulo our equational theories.A dedicated interface enables to directly access them and either send them to a set of automatic SMT-solvers (CVC4, Alt-Ergo, Z3, etc.), or enter a number of interactive proof transformation commands (calls for lemmas or hypotheses, term substitutions, etc.) or even to proof assistants (Coq, Isabelle/HOL) -we do not use this option in our case-studies.
Statistics about Qbricks implementation are given in Table 23.The development itself counts 17,000+ lines of code, including 400+ definitions and 1700+ lemmas -all proved within Why3 but 32 axioms in the mathematical libraries (see next section).Notice the volume of (verified) mathematical libraries in the overall development (14,695 loc for a total of 17,313 loc).These libraries are described in the next section.E.2 Mathematical libraries.When we began developing Qbricks, there was no native automated support for data-types commonly manipulated in quantum, such as complex numbers, angles, matrices, kets, vectors, etc.Hence, aside the implementation of Qbricks-DSL and Qbricks-Spec, Qbricks development also required the development of a WhyML library for these data-types in the quantum context.
The goal, for this specific part, was to provide the mathematical structures at stake in quantum computing, together with a formally verified collection of mathematical results concerning them.Then these developments are led as mathematical theories, elaborating proofs from a restricted number of axiomatic definitions.
As shown Table 23, this library contains 14,000+ lines of code: 300+ definitions, 1600+ lemmas and 32 axioms.Most of the axioms are actually axiomatic definitions giving structure for data types complex and angle.These are listed in Table 24: F EXPERIMENTAL EVALUATION: MORE DETAILS This section complements Section 9, with both more detailed commented descriptions of casestudies (Section F.1) and additional statistics (Section F.2).
F.1 Case studies: description and comments.This section complements Section 9.1.We introduce and comment the specifications for our implementations of QPE, Shor-OF, Deutsch-Josza and Grover search algorithms.
Quantum Phase Estimation.All the eigenvalues of a unitary operator U are equal to e 2π iΦ for a given real Φ such that 0 ≤ Φ < 1. Phase estimation (QPE) [17,45] is a procedure that, given a unitary operator U and an eigenvector |v⟩ of U , finds the eigenvalue e 2π iΦ v associated with |v⟩.It is a central piece in many emblematic algorithms, such as quantum simulation [30] or HHL algorithm [36]   An overall view on the circuit for QPE is given on Figure 25 and the successive intermediary register states are given in Table 26.It uses two registers, one of size n and initialized to |0⟩ n and one of size s and initially in state |v⟩ s : First, we superpose the first register of the entry state, by applying an Hadamard gate H to each of its qubits.It results in state s 1 .Then we perform, on the second register, a sequence of U circuits elevated to the successive powers of 2 and controlled by qubits from the first register.It results in state s 2 .At last, we apply the reversed quantum Fourier transformation, QFT −1 (n), to the first register and get state s 3 .
The specifications for this algorithm are given in Figure 27.It inputs an oracle HOPS f together with a circuit C implementing it, an eigenvector |v⟩ of f together with the associated ghost eigenvalue e 2π i * θ and two register length parameters k and n.The first postcondition then certifies that, in the general case, the probability to find an x such that x − θ < 1 2 n+1 after applying circuit QPE(C, k, n) on entry |0⟩ k |v⟩ and measuring qubits 0 to n is at least 4 π 2 .The second postcondition concerns the particular case when θ is a multiple of 1  2 n .Then this probability rises to 1. Shor-OF.[66]'s Order Finding is the central procedure in Shor's integer prime factor decomposition algorithm.It consists in a particular instantiation of QPE.This algorithm is certainly the most  famous of all quantum computing existing algorithm, raising worldwide interest for the domain.
Given a non prime integer N , it outputs a factor of it in time PolyLog(N ).Its most spectacular application is that it enables to break the RSA encryption protocol in polynomial time.
As a result from Bézout's identity, for any integer a < N co-prime with N , if r is the modular order of a in N (that is the least integer such that mod a r N = 1) and if r is even (which happens with probability O(1)), then either gcd(a r /2 − 1) or gcd(a r /2 + 1) divides N .Furthermore, if U is an unitary implementing the multiplication modulo N then for any k ≤ r , e −2i π * s k r is an eigenvalue of U .The quantum part of Shor-OF algorithm then consists in: • implementing, for each j < k, the circuit U 2 j , • applying quantum phase estimation, with oracle these U 2 j , on input ket |1⟩ n (which is the uniform superposition of U eigenstates).
Note the importance of the implementation of U 2 j circuits.In particular, a naive implementation of them as iterative sequences of 2 j instances of U would introduce an exponential complexity factor and loose any advantage of using a quantum computer.Hence, the functional correction of an implementation is not enough.In the case of Shor-OF for example, a relevant implementation must also certify the PolyLog complexity requirement.
We implemented the version of the oracle U j described in the reference implementation [6].The overall specification for our implementation is given in Figure 25.In this specification, we used expression proba_partial_measure f (result, bv_cst (n, 0), f ) as a syntactic sugar for j ∈ 0, 2 n f (j) = tt proba_partial_measure(result, bv_cst (n, 0), int_to_bv(n, i)) F.2 Case studies: metrics.This section complements Section 9.2.
Details on interactive proof commands.As a complement to these figures, it should be mentioned that the specifications for these algorithms all contain some pure mathematical proofs which are not directly linked to circuit composition.For example, 198 out of the 321 lines of decorated code declared for QPE in Table 15 concerns rewriting lemmas for the measurement outcomes.Also, our implementation for Grover follows the standard algorithm explanation.Doing so, it introduces, in addition to circuit building and hops specifications, vectorial space embedding and geometry material which, again, actually represents the major part of the proof effort.

3
Given two matrices A and B with respectively r (A) and r (B) rows and c(A) and c(B) columns, their Kronecker product is the matrix A ⊗ B = a 11 B . . .a c (A) B . . . . . . . . .a r (A)1 B . . .a r (A)c (A) B .This operation is central in quantum information representation.It enjoys a number of useful algebraic properties such as associativity, bilinearity or the equality (A ⊗ B) • (C ⊗ D) = (A • C) ⊗ (B • D) for any matrices A, B, C, D of adequate sizes -where • denotes matrix multiplication.

Example 7 . 1 .
Consider the motivating example of Section 3 and its instantiation in Example 5.1.

Fig. 26 .
Fig. 26.Successive states of the register along QPE circuit

Fig. 27 .
Fig. 27.Specification for our implementation of Quantum Phase estimation

Fig. 28 .
Fig. 28.Specification for our implementation of Shor-OF algorithm 2.2 Quantum Circuits.In a way similar to classical Boolean functions, the application of quantum gates can be written in a diagrammatic notation: quantum circuits.Qubits are represented with horizontal wires and gates with boxes.Circuits are built compositionally, from a given set of atomic gates and by a small set of circuit combinators, including: parallel and sequential compositions, circuit inversing, controlling, iteration, etc.

Table 15 .
Implementation & verification for case studies with Qbricks -resolution of linear systems of equations in time PolyLog.
Table 29 reports a classification of the interactive (proof) commands used in our case-studies to discharge the remaining PO.Interactive commands divide mainly into:• calls for deduction rules (Rules),• calls for hypotheses from the context (Hyp.),•β−reductions,•splittingcommands (splitting conjunction in either goal or context and elimination of case distinctions), • and substitutions (Subst).Column Misc.contains introduction of constant values for existential quantification, case distinctions and intermediate assertions.#Rules#Hyp.#β-red.#Split.#Subst.Misc.

Table 29 .
Verification for case studies: repartition of interactive commands