Quantum Hoare Type Theory: Extended Abstract

09/06/2021
by   Kartik Singhal, et al.
0

As quantum computers become real, it is high time we come up with effective techniques that help programmers write correct quantum programs. In classical computing, formal verification and sound static type systems prevent several classes of bugs from being introduced. There is a need for similar techniques in the quantum regime. Inspired by Hoare Type Theory in the classical paradigm, we propose Quantum Hoare Types by extending the Quantum IO Monad by indexing it with pre- and post-conditions that serve as program specifications. In this paper, we introduce Quantum Hoare Type Theory (QHTT), present its syntax and typing rules, and demonstrate its effectiveness with the help of examples. QHTT has the potential to be a unified system for programming, specifying, and reasoning about quantum programs. This is a work in progress.

READ FULL TEXT VIEW PDF

Authors

page 1

page 2

page 3

page 4

12/03/2020

Quantum Hoare Type Theory

As quantum computers become real, it is high time we come up with effect...
05/20/2019

Statistical Assertions for Validating Patterns and Finding Bugs in Quantum Programs

In support of the growing interest in quantum computing experimentation,...
11/13/2018

QDB: From Quantum Algorithms Towards Correct Quantum Programs

With the advent of small-scale prototype quantum computers, researchers ...
10/04/2021

Formal Verification of Quantum Programs: Theory, Tools and Challenges

Over the past 27 years, quantum computing has seen a huge rise in intere...
05/04/2022

Twist: Sound Reasoning for Purity and Entanglement in Quantum Programs

Quantum programming languages enable developers to implement algorithms ...
04/14/2022

A Formally Certified End-to-End Implementation of Shor's Factorization Algorithm

Quantum computing technology may soon deliver revolutionary improvements...
04/08/2019

A HoTT Quantum Equational Theory (Extended Version)

This paper presents an equational theory for the QRAM model of quantum c...
This week in AI

Get the week's most popular data science and artificial intelligence research sent straight to your inbox every Saturday.

1 Introduction

It is difficult to reason about the correctness of quantum programs. Sound static type systems help prevent a huge class of bugs from occurring but since the realm of quantum programming is still new there is not a lot of consensus on what kind of types make the most sense. Further, it is unclear how much they help programmers reason about the semantic properties associated with the quantum algorithms that they are implementing.

Recent work [HM18, HM19] as part of EPiQC222EPiQC: Enabling Practical-Scale Quantum Computation: https://epiqc.cs.uchicago.edu has identified several classes of bugs in quantum programs and proposed approaches to tackle them. The technique that holds the most promise is assertion checking using preconditions and postconditions. But assertions are usually checked dynamically during runtime, which can be wasteful of precious quantum computing or simulation resources.

As programming languages researchers, we think it will be better to encode such assertions into a static type system both for formal verification and to aid the programmers in writing correct programs from the start. Inspired by the use of Hoare triples in the verification of imperative programs and building on the idea of Hoare Type Theory (HTT) for classical programming languages [NMB08], we extend the Quantum IO Monad interface [AG09] and propose Quantum Hoare Type Theory aimed at enabling both sound static type checking and formal verification of quantum programs.

The main idea is that instead of just indexing the QIO monad type with the type of computation result, we can also index it with preconditions and postconditions so as to integrate Hoare-style reasoning into the type system itself. The resulting Quantum Hoare Type, , specifies the preconditions, , that hold on the quantum state before execution; the result, , and its type, ; and, the postconditions, , that are true for the quantum state after successful execution. In this way the effectful quantum fragment of the program is effectively encapsulated inside the Quantum Hoare monad. Our theory, like HTT, allows the usual equational reasoning for the pure classical fragments of the program and uses syntax-directed type checking for generating strongest postconditions for the quantum fragment.

This paper is organized as follows. We discuss some related work and background in the next section, section 2; specifically, Hoare Type Theory in the classical setting (section 2.1) and then the Quantum IO Monad interface (section 2.2). Then we introduce our contributions in merging these ideas together for specification and enforcement of useful semantic properties in section section 3 along with its syntax (section 3.1), typing rules (section 3.2) and, some examples (section 3.3). Finally, we conclude and share ideas for future work in the final section (section 4).

2 Related Work and Background

Previous work, such as Proto-Quipper [Ros15, RS17] and QWire [PRZ17, RPZ18, Ran18], utilize a linear type system and dependent types to enforce a small subset of semantic properties, such as the no-cloning restriction and whether a unitary gate is of the right dimension. These advances in quantum type systems, although helpful, still fall short in encoding and enforcing even more useful properties that one would like to be able to express for the purpose of verification.

Our approach builds upon previous work in reasoning about quantum programs such as Quantum Weakest Preconditions [DP06] and Quantum Hoare Logic [Yin12] in the spirit of Hoare [Hoa69] and Dijkstra [Dij76] but attempts to bring those reasoning techniques into the type system. The hope is that programmers will be able to encode some of the semantic properties that they expect of their programs as specifications in their code and type checking will ensure correctness of some of those properties. In the classical setting, Hoare Type Theory [NMB08] accomplishes exactly this goal. Our attempt is to merge these ideas for the quantum realm.

In the rest of this section, we provide background on the core ideas from existing literature that form the foundation for our work — Hoare Type Theory (HTT) and the Quantum IO Monad interface. We assume background in basics of quantum computing and refer the reader to Nielsen’s excellent series of essays [MN19] for a first introduction and to the standard textbook [NC10] for advanced material.

2.1 Hoare Type Theory

A Hoare type, , encodes preconditions and postconditions in the same spirit as Hoare triples to allow both specification and verification of effectful classical programs. It can be read as ‘for a stateful computation executed in a heap that satisfies precondition , return a value of type in a heap that satisfies postcondition .’ The contexts, and , contain the variables and heap variables that may appear in both and . In this presentation, we will omit the contexts in the Hoare type when they are unneeded. We show an example to demonstrate the expressiveness of a Hoare type — the alloc primitive from HTT [NMB08]: alloc : ∀α. Πx:α. {emp}  y:nat  {y ↦α x}

This type specifies that alloc is a polymorphic function that takes as input a variable, , of any simple type, , that is executed in an empty heap (meaning it does not affect existing heap), returns a new location bound by a fresh variable, , of type nat and initializes it with the supplied value of type .

Type checking in HTT involves generation of strongest postconditions at each step of the program. Verification is a two-step process: the first phase does basic type checking and verification condition generation which is decidable, the second phase needs to show the validity of the generated verification conditions, which can be undecidable. This second phase can be deferred to an automated theorem prover.

We provide more details when we introduce QHTT in section section 3. An accessible introduction to Hoare Type Theory is available in the lecture notes by Perconti [Per12].

2.2 Quantum IO Monad

The Quantum IO (QIO) monad [AG09] is a purely functional interface for quantum programming that provides a separation between the unitary (reversible) and non-unitary (irreversible) fragments of quantum computation. It provides isolation of quantum effects inside a monad similar to what we need to provide in our Quantum Hoare monad.

QIO interface was developed as a library for the Haskell programming language but its design was influenced [Gre10] by the category FQC of finite quantum computations (where computations are interpreted as superoperators) as explored by the authors in previous work [GA08]. This is the most we will say about the relation of QIO monad to category theory in this paper.

Here we discuss the relevant bits from the QIO interface. QIO provides a type for referring to qubits,

Qbit; a type for unitary operations, U; and, the QIO type operator which is a monad indexed by the result of the quantum computation. The primitive quantum operations defined using the QIO monad below (Haskell syntax) are:

mkQbit :: Bool -> QIO Qbit       -- initialization
applyU :: U -> QIO ()            -- apply a unitary to quantum state
measQbit :: Qbit -> QIO Bool     -- measurement

Further, U is defined as a monoid with neutral element, mempty, and operation, mappend, that encodes reversible operations on quantum state. The core unitary primitives that we will need are:

rot :: Qbit -> ((Bool, Bool) -> C) -> U
cond :: Qbit -> (Bool -> U) -> U

rot

takes a qubit and a two-by-two complex-valued unitary matrix (represented as a function from the matrix indices to

) and lets one define arbitrary rotation on a single qubit. rot can then be used to define standard gates such as the Hadamard, H, and the Pauli gates, X, Y and Z. cond is the unitary conditional that is used to perform branching unitary operations. For the present paper, we use a simpler conditional, ifQ, that is defined as follows:

ifQ :: Qbit -> U -> U
ifQ q u = cond q (\x -> if x then u else mempty)

That is, ifQ acts as the standard control operator in the quantum circuit model that runs its second argument based on the truth value of its first argument. Then, it is easy to define controlled gates such as CNOT with the expression .

Quantum state in the QIO interface is modeled as a normalized vector that stores pairs representing complex amplitudes associated with each basis state (represented as a map from Qbit to Bool types). The operations defined over the vector class ensure that the quantum state is kept normalized throughout.

QIO further ensures that the monoidal structure of unitary operations lets one run a unitary operation over the complete quantum state. We elide details here and refer the reader to [AG09] for more.

3 Quantum Hoare Type Theory

In this section, we introduce the Quantum Hoare Type inspired by the QIO monad and its type theory (QHTT) by replacing the classical effectful portion of Hoare Type Theory with quantum effects. The core idea is to encapsulate any quantum effect inside a monadic Quantum Hoare type, , and formalize reasoning of quantum effects using strongest postconditions in a similar fashion as HTT in the classical setting.

The next two sections discuss the syntax and typing of QHTT. The last section show examples written in QHTT.

3.1 Syntax

Figure 1 shows the syntax of Quantum Hoare Type Theory. Our presentation closely follows that of HTT [NMB08].

Types ::=
Assertions ::=
Q. Heaps ::=
Elim terms ::=
Intro terms ::=
Q. Commands ::=
Computations ::=
Variable context ::=
Q. Heap context ::=
Assertion context ::=
Figure 1: Syntax of Quantum Hoare Type Theory
Types

We include primitive types for unit, booleans, qubits and unitary operations, and a type Pure for representing pure quantum state vectors (complex valued vectors in Hilbert space); these correspond to similar types in the QIO work. There are also type constructors for pairs, dependent functions and the Hoare type from HTT.

Assertions

Apart from the usual first order logic, we have assertions for reasoning about propositional equality of terms, , and heaps, .

As done in HTT, some common convenience assertions can be defined using the base primitives. Particularly, denotes that the current heap, say , is empty, that is, . represents the only mapping in the (singleton) heap. says that looking up in the heap returns which can be more explicitly written as .

Quantum State

We use the terms quantum state and quantum heaps interchangeably throughout. A quantum heap is a partial function from qubits (that can in turn be thought of as locations, represented using natural numbers) to at most one quantum state vector.

For the purpose of the type theory, heaps are functional, so that, for example, returns a new heap after updating heap at location with .

Terms

The terms are divided into introduction and elimination sorts for the purpose of bidirectional typechecking like in HTT.

The pure fragment allows higher-order functions while the impure (effectful) fragment is encapsulated within the monadic do construct and supports a simple imperative quantum language inspired by QIO constructs. It is worth noting that do represents suspended computation and is considered pure.

Quantum Commands

These are the quantum-specific effectful commands from QIO for initialization, unitary application and measurement of qubits. We also support classical control using the if then else construct similar to HTT.

Computations

The computations are the usual monadic return and three sequencing operations that bind their result to a variable similar to HTT. The first, , executes a suspended computation (such as applying a function that includes a do in its body); the second, executes a primitive command ; and the last, , is just syntactic sugar for let-binding.

Contexts

Contexts are modelled exactly the same way as in HTT. The only difference is that instead of classical heaps, we have quantum heaps.

3.2 Typing Rules

In this section, we provide some details about type checking in HTT and how it is different in the quantum case.

3.2.1 Judgments

We explain the main judgments used in HTT that are required to understand the typing rules in the next section. The type system is designed to be bidirectional and syntax directed and hence includes separate judgments for intro and elim terms. We are able to use them unchanged for QHTT. A recent survey provides accessible introduction to bidirectional typing [DK19].

The type checking process also involves generating canonical forms for each term. A canonical form in HTT means a beta-normal (containing no beta-redexes) and eta-long (all intro terms are eta-expanded) form. We elide much detail here.

As usual, elim terms synthesize types () and intro terms are checked against the given type (). Canonical forms are always synthesized. For the pure fragment:

Elim term K has type A and canonical form
Intro term M has type A and canonical form

Note that the blue colored symbol we use in the typing rules lives in a different syntactic category from the symbol used in the syntax (fig. 1) that binds the output of primitive commands.

The judgments for computations involve synthesizing the strongest postconditions and checking whether a given postcondition applies:

Computation E with precondition P has strongest postcondition Q
and returns value x of type A. Its canonical form is .
Computation E with precondition P has postcondition Q
and returns value x of type A. Its canonical form is .

Even though, we have shown the full forms of these judgments above, we will omit the canonical forms while presenting typing rules in the next section as they crowd the rules and do not affect the insight to be gained from them.

Finally, the judgment encodes the sequent calculus for the assertion logic. Recall that , , and denote the variable context, the quantum heap context and the assertion context, respectively.

The type system includes rules for primitive effectful commands and those for structuring composition such as monadic unit and bind. We reuse most of the HTT rules except those for primitives for quantum effects that need to specify the strongest postconditions for each primitive, we discuss that next.

3.2.2 Strongest Postconditions

Here we show the strongest postconditions for the primitive quantum commands of QHTT encoded in their typing rules. Given a quantum command for initialization, unitary application or measurement, its strongest postcondition is an assertion that most precisely captures the relationship between the initial state and the modified state after the execution. These rules along with the consq (consequent) rule of HTT (that ensures weakening of the given strongest postcondition to an arbitrary postcondition) work together to ensure composition of verification.

We need to use the relational composition connective from HTT () that captures how heap evolves with computation. It basically reads: holds of the current heap which is obtained after modification of a prior heap for which P holds.

We also use HTT’s difference operator () below that captures changes to only the interesting fragment of the heap without modifying the rest of the heap.

We can now state some typing rules:

Initialization

Δ⊢M  Bool
Δ, x : Qbit; P ∘(x ↦ state (M)) ⊢E   y:B . Q Δ; P ⊢x ⇐ mkQbit  M; E   y:B. (∃x:Qbit.Q) where x is fresh and state is a function that translates a classical representation of quantum state (such as boolean here) to the equivalent quantum state vector.

Initialization can only be performed for a term that can be type checked as a Bool. Then, we look at the rest of the computation, , in a context that adds of type Qbit under a precondition that extends the previous precondition, , with the strongest postcondition for initialization, that is, the newly bound variable points to the representation of a new qubit state; this should synthesize the strongest postcondition (with respect to the expanded precondition in the context), , for .

To avoid dangling variables, we need to existentially quantify in the postcondition, , of the conclusion.

Measurement

Δ⊢M  Qbit
Δ; Ψ; P ⟹(M ↪-)
Δ, x:Bool; P ∘((M ↦-) ⊸ emp ) ⊢E   y:B . Q Δ; P ⊢x ⇐ measQbit  M; E   y:B. (∃x:Bool.Q)

The measurement rule can be read in a similar way as the previous rule. But in measurement, we need to additionally prove that the verification condition (written as a sequent), the precondition implies that the qubit is allocated, holds in the heap context . The strongest postcondition here is that the fragment of heap that only refers to location M becomes empty.

As may be apparent, initialization is analogous to alloc and measurement to dealloc and lookup primitives of HTT. We are working out precise details for unitary application, but at a high-level, they involve ensuring that the given unitary term actually represents a unitary matrix and updating the quantum state with the result of unitary application. This involves incorporating the monoidal structure of unitaries into our theory (as is done in QIO). This step also involves generating verification conditions that cannot be checked during this first phase of typechecking. We are also considering more tractable alternatives such as the sum-over-paths action semantics [Amy18] based on the Feynman path integral formulation.333We ended up taking a different approach in subsequent work [Sin20].

3.3 Sample programs

In this section, we show some simple examples from the QIO work [AG09] translated in our language and annotated with their program specifications using their Quantum Hoare types. An observation is that translating the programs was a very simple process except for coming up with the right specifications for the programs. We provide some commentary on assertions specified for these programs.

At the end of this section, we show a sample verification using QHTT for Bell pair generation.

Hello Quantum World

hqw : {emp} r : Bool {emp /\ Id(r, false)}
    = do q <= mkQbit false;
         measQbit q

In this trivial program where we initialize a new qubit with false and then immediately measure it, we assert that the result is equal to false. The complete specification also implicitly says that the existing quantum state is not affected in any way as both the pre- and postcondition include the emp assertion.

Coin Toss

rnd : {emp} r : Bool {emp}
    = do q <= mkQbit false;
         applyU (H q);
         measQbit q

In the case of quantum coin toss, the result can be in either of its two boolean values false or true, hence, we need not specify any special postcondition as type checking the result will be sufficient for correctness.

Testing Bell Pair

testBell : {emp} (a, b) : (Bool, Bool) {emp /\ Id(a, b)}  -- a,b \in {true, false}
         = do qa <= mkQbit false;
              applyU (H qa);
              qb <= mkQbit false;
              applyU (ifQ qa (X qb));
              (measQbit qa, measQbit qb)

Here, we are asserting that the returned booleans and hold the same value, which is what we expect from the first Bell state prepared in this program.

Verification

We would like to describe how QHTT lets us verify the correctness of the above program based on the specification provided as the type of the function. For illustration, we show the assertions annotated as comments as we step through the testBell program below. We have elided specific details about unitary application as they are still being worked out.

testBell : {emp} (a, b) : (Bool, Bool) {emp /\ Id(a, b)}
              -- P0: emp
         = do qa <= mkQbit false;
              -- P1: P0 \o (qa |-> |0\>)
              applyU (H qa);
              -- P2: P1 \o ((qa |-> |0\>) -o (qa |-> |+\>))
              qb <= mkQbit false;
              -- P3: P2 \o (qb |-> |0\>)
              applyU (ifQ qa (X qb));
              -- P4: P3 \o ((qa |-> |+\>, qb |-> |0\>) -o (qa, qb) |-> |\Phi+\>)
              (measQbit qa, measQbit qb)
              -- P5: P4 \o ((qa |-> -) -o emp) \o ((qb |-> -) -o emp)

In the assertion P2, we show that only the portion of the quantum state referred to by the applyU command is affected. Similarly, in P4 we see that only the relevant portion of the heap containing the control and target qubits used in the CNOT operation are affected. In this case, we also needed to combine the two qubit state as they are now entangled. The last assertion, P5, merely encodes the strongest postcondition for measurement for each of the two qubits.

Finally, the consq rule of HTT ensures that the assertion P5 leads to the specified postcondition in the type of the program.

We show some two more examples in the appendix for a modular version of Bell pair generation (Appendix A) that shows use of higher-order features of QHTT and another for teleportation protocol (Appendix B). Both of these involve specifying assertions over quantum state whose theory we still need to work out.

4 Conclusions and Future Work

In this paper, we have described our ongoing work on Quantum Hoare Type Theory, which modifies HTT for quantum computing using ideas from the Quantum IO monad work. This approach has the potential to be a unified system for programming, specification, and reasoning about quantum programs. This is active work in progress and more details will be available in a forthcoming technical report [Sin20].


There are several avenues of future work to explore:

Mechanization

There are multiple implementations of HTT in Coq such as Ynot [NMS08]. We are similarly working on mechanizing QHTT in Coq for higher assurance of the usefulness and soundness of our theory. This will also enable us to extract verified circuits in a lower level quantum language such as OpenQASM for execution on real machines.

Quantum Assertion Logic

An obvious need is to come up with an assertion logic similar to Separation Logic [Rey02] for quantum computing so as to be able to reason about only the interesting portions of the quantum state while still ensuring correctness of non-local effects such as entanglement. Various Quantum Hoare Logics that exist [Yin12] currently do not support frame rules that provide Separation Logic its power.444Since the time of this writing, we learned about Unruh’s work [Unr19] that we use in subsequent work [Sin20].

Linearity

Peter Selinger and collaborators have recently proposed a linear dependent typed version of Proto-Quipper (dubbed Proto-Quipper-D) [Sel20, FKS20]. It is an interesting challenge to reconcile linearity in our theory based on their proposal.

Circuits as Arrows

Further, Proto-Quipper treats quantum circuits as first class citizens of the language. We would like to explore modifying our theory to treat Quantum Hoare types as arrows instead of as monads as was suggested by Vizzotto et al [VAS06]. It makes sense from the perspective of sequential composition as arrows can have an arbitrary number of input/outputs as opposed to monads.

Behavioral Types

Another venue for exploration is to incorporate more precise types that can distinguish between qubits in pure classical state vs. those in superposition vs. those in entanglement [JP09] such as those inspired by the various quantum resource theories or the Heisenberg representation of quantum mechanics [RSSL19, RSSL20]. This may help us provide more specific postconditions that quantum programmers expect to hold true of their programs.

Classical Effects

Finally, it will be an interesting challenge to reconcile both classical and quantum effects together in a single grand unified theory for effects.

Acknowledgments

We thank Robert Rand and the anonymous reviewers for their feedback on a previous draft of this paper. This work is funded by EPiQC, an NSF Expedition in Computing, under grant CCF-1730449.

References

Appendix A Modular Bell Pair

Writing a modular version of testBell.

a.1 Hadamard basis states

qplus : {emp} r : Qbit {Id(r, |+\>)}
      = do q <= mkQbit false;
           applyU (H q);
           return q
qminus : {emp} r : Qbit {Id(r, |-\>)}
       = do q <= mkQbit true;
            applyU (H q);
            return q

a.2 Creating entanglement

share : \Pi a : Qbit.
        {a \in {|+\>, |-\>}}   -- a \in {b, c} is short for Id(a,b) \/ Id(a,c)
           b : Qbit
        {Id(a, b) /\ a \in {|0\>, |1\>}}
      = \a.do b <= mkQbit false;
              applyU (ifQ a (X b));
              return b

a.3 Bell pair

bell : {emp} (a, b) : (Qbit, Qbit) {Id(a, b) /\ a \in {|0\>, |1\>}}
     = do qa <- qplus;
          qb <- share qa;
          return (qa, qb)

a.4 Testing modular Bell pair

testBell : {emp} (a, b) : (Bool, Bool) {emp /\ Id(a, b)}
         = do (qa, qb) <- bell;
              (measQbit qa, measQbit qb)

Appendix B Teleportation

b.1 Alice’s circuit

alice : \Pi a : Qbit. \Pi e : Qbit
        {(Id(a, -) /\ entangled(e)}
           r : (Bool, Bool)
        {emp}
      = \a.\e.do applyU (ifQ a (X e));
                 applyU (H a);
                 (measQbit a, measQbit e)

b.2 Bob’s circuit

bob : \Pi m1 m2 : Bool. \Pi e : Qbit
      {entangled(e)}
         r : Qbit
      {(Id(r, -)}
    = \m1.\m2.\e.do if m1 then applyU (Z e) else ();
                    if m2 then applyU (X e) else ();
                    return e

b.3 Teleport

teleport : \Pi q : Qbit. x : Pure.
           {Id(q, x)}
              r : Qbit
           {Id(r, x)}
         = \q.do (a, b) <- bell;
                 (m1, m2) <- alice q a;
                 tq <- bob m1 m2 b;
                 return tq