The post Festivus: Azure Quantum Feats of Strength appeared first on Q# Blog.

]]>How about you – what is your favorite thing about Azure Quantum?

- $500 free Azure Quantum credits, because they allow me to use Azure Quantum to teach a quantum computing course without making my students pay for their homework! –
*Mariia Mykhailova* - Credits and Quotas view that gives you a clear understanding of your spending and how many credits you have left! –
*Fabrice Frachon* - I love that I can instantly spin up an interactive Jupyter environment and run quantum programs for demos and exploration, directly in my web browser with no installation required! –
*Anita Ramanan* - I like that I can use Q# within Python through Jupyter notebooks, to both concisely express my quantum algorithms in Q# and make use of Python’s rich ecosystem for post processing and data analysis. –
*Mathias Soeken* - Can be hard to pick just one favorite thing…
- As a researcher it’s really great to have a single platform from which I can explore different hardware technologies such as ion traps and superconductors.
- To meet the future quantum hardware capabilities it will be crucial to continuously keep improving the quantum algorithms that we have. The freely available Azure Quantum Resource Estimator is a unique and powerful tool to help us with this challenge.

*Wim van Dam*

The post Festivus: Azure Quantum Feats of Strength appeared first on Q# Blog.

]]>The post Teaching Quantum Computing with Q# and Azure Quantum at Northeastern University appeared first on Q# Blog.

]]>This fall I taught an “Introduction to Quantum Computing” course at Northeastern University. It was my second time teaching this course at NEU, after the first run in spring 2020. As always, it was a unique experience that taught me a lot – though, hopefully, it taught my students more! – so I decided to share the highlights of my experience with you.

In this course, I introduce quantum computing to graduate students at the College of Engineering at Northeastern University who pursue a non-physics major. This allowed me to teach the contents through the lens of software engineering rather than physics, spending only a bit of time on an overview of physical implementations of quantum devices and instead spend more time on the algorithm implementation and quantum software stack. In fact, my approach was based on the one our team took when teaching at University of Washington back in 2019: introduce the basic concepts of quantum computing and simple algorithms, focusing on using them for solving problems and implementing and evaluating algorithms. Same as back then, I used Q# and Microsoft Quantum Development Kit as the software tools for the course, adding Azure Quantum for running programs on cloud simulators and hardware.

The three-month course consisted of two parts:

- In the first two months, we went through the typical introductory topics – the basics of single- and multi-qubit systems, quantum communication algorithms (teleportation, superdense coding, and BB84 protocol), oracular algorithms such as Deutsch-Jozsa and Bernstein-Vazirani, reversible computing, and Grover’s search algorithm. Each week the lecture was followed by a set of practice exercises from the Quantum Katas – an open-source collection of tutorials and programming problems on quantum computing – and a graded programming assignment (more on the assignments later).
- During the last month, the students worked on their final projects, choosing a problem to solve using Grover’s search, implementing the solution, and evaluating it. In the lectures we reviewed more advanced topics, such as Shor’s algorithm, the software and hardware stacks required for building a quantum computer, and fault-tolerant quantum computing, without accompanying weekly assignments.

Let’s take a closer look at the three different kinds of assignments that the course offered: solving programming problems, debugging code, and running code on Azure Quantum.

This type of assignment requires the students to apply the theoretical concepts and algorithms they have learned to solve simple programming problems. To give you some examples,

- When we discuss single- and multi-qubit quantum systems and gates, the problems might ask to prepare a certain quantum state or to run a measurement to figure out which of the given quantum states you are given.
- In the communication algorithms week, the problems require to implement the last step of a variation of teleportation or superdense coding algorithms that used a different entangled state than the standard 1/√2 (|00⟩ + |11⟩).
- For the topics of oracular algorithms and reversible computing, the problems focus on implementing oracles of different types for the given classical functions.

Same as in the exercises in the Quantum Katas, each problem describes the task and provides the signature of a Q# operation that matches the description of the given problem. The student has to implement the operation that solves the task and turn in their code. The grading is done automatically using a testing harness – Q# code that runs the solutions on a set of tests using quantum simulators and checks that their results match the expected ones.

We’ve used similar assignments in the past courses as well, but this time I took them one step further. In the past we didn’t share the testing harnesses with the students, since they often included solutions to the problems (see “Inside the Quantum Katas” blog series for examples of testing code that relies on reference solutions), and you don’t really want to include the solution as part of the graded assignment! This meant that the instructors and teaching assistants could use the testing harness to automate the grading process, but the students had to come up with other ways to test their work. This could be challenging at times, especially in the first weeks when the students were exposed to a lot of completely new concepts at once.

For this course, I took the feedback from the past courses to heart and modified the projects to conceal the testing code while allowing the students to execute it. This allowed me to share it with my students without revealing the solutions, and my students – to test their code themselves and to figure out which tasks they needed to focus on.

Debugging assignments offer the students a quantum program that has a number of bugs of different kinds and ask them to identify and fix them. They aim to improve the students’ familiarity with the software tools they use and with the algorithms covered in the course. I used them during the weeks that covered well-studied algorithms such as BB84 quantum key distribution protocol or Grover’s search, when the students are already familiar with the basics of quantum programming and can focus on the logic behind the program.

Tracking down different types of errors emphasize different aspects of writing and running quantum programs:

- Syntax errors allow the instructor to bring attention to the common mistakes made when writing the code, such as the syntax of the Controlled functor.
- Runtime errors can highlight the requirements to the behavior of quantum programs, for example, the need to measure or uncompute all qubits before releasing them.
- Tracking down logical errors requires the student to focus on understanding the expected algorithm behavior and identifying the deviations from it, such as unexpected results of the key distribution protocol in a small percentage of cases.

The final type of assignment encourages the students to explore the behavior of quantum programs on the cloud simulators and quantum devices available via Azure Quantum using the free Azure Quantum credits. The tasks were mostly introductory, teaching the students to run Q# programs on cloud targets and to interpret the results rather than diving deep into the hardware.

- For the first two assignments the students had to run a quantum random number generator on the IonQ simulator and quantum device, and to observe the difference between the results: the IonQ simulator produces a perfect 50-50 distribution of probabilities based on the quantum state of the program before measurement, and the quantum device runs the program multiple times and aggregates the outcomes, resulting in a slightly uneven distribution.
- The next assignment introduced the concept of noise in quantum systems, asking the students to run a program that prepared a Bell state and measured both qubits on a quantum device. In addition to the uneven frequencies of 00 and 11 measurement outcomes, the results included non-zero probabilities of 01 and 10 outcomes, which are not possible theoretically and only appear due to the existence of noise.
- In the last assignment the students further explored the behavior of the program on a noisy device, running Grover’s search algorithm for problem instances of increasing size and observing the increasing levels of noise that eventually rendered the correct answers undetectable from the noise-induced ones.

This semester was the first time I introduced Azure Quantum-based assignments. I’m looking forward to improving them and including new tools, such as the recently released Azure Quantum resource estimation tool, in the course!

Check out Azure Quantum for Educators page to see examples of materials developed for the course.

The post Teaching Quantum Computing with Q# and Azure Quantum at Northeastern University appeared first on Q# Blog.

]]>The post Q# Holiday Calendar 2022 appeared first on Q# Blog.

]]>The rules are simple:

- Reserve a slot by leaving a comment on this post. (You can also tweet about it, but you’ll have to mention @tcNickolas to make sure we’ve seen it!) The slots are assigned on the first come, first serve basis. You do not have to announce the topic of your blog post until you’re ready to publish it, but we’d really love to hear it beforehand. (This also helps other bloggers to pick a topic that is not too close to the ones already covered.)
- Prepare a blog post (in English) about Q#, Azure Quantum, a cool project you’ve done with them, using Q# and Azure Quantum for research or education, tools for working with them… You got the idea!
*Note that Q# Holiday Calendar accepts only original content.*Don’t forget to check out the previous calendars for inspiration! - Publish your blog post on your assigned date. Don’t forget to link back to the Q# Holiday Calendar from your post, so that your readers can find the entire calendar!
- Leave the link to your blog post in a comment to this post, and we’ll add it to the calendar. If you share a link to your post on Twitter, use hashtags #qsharp or #AzureQuantum.

Looking forward to reading your Q# and Azure Quantum stories!

The post Q# Holiday Calendar 2022 appeared first on Q# Blog.

]]>The post Microsoft Quantum is hiring software engineers and software researchers! appeared first on Q# Blog.

]]>Apply for the Quantum Educator job posting

In this role, you will work on education and outreach, creating quantum computing learning materials, running all kinds of events from workshops to hackathons, and empowering other quantum computing educators.

This is the role I’m personally most excited about since it involves working directly with me!

Apply for the Senior Software Engineer – Quantum Compiler and Runtime job posting

In this role, you will work on the compiler and runtime side of Azure Quantum, in areas such as low-level intermediate representations (for example, QIR), programming language design & implementation, compiler optimizations & code translation, and quantum software development tools.

Apply for the Software Engineer 2 – Azure Quantum Services job posting

In this role, you will be building our Azure Quantum service infrastructure, collaborating with our partner providers to enable increasingly advanced quantum software workloads. We’re looking for someone with online services/cloud computing experience who is excited to learn more about quantum computing as they go!

Apply for the Quantum Software Researcher job posting

In this role, you will develop new software tools to explore new capabilities in quantum computing research and create new content to showcase and explain current quantum research to various communities.

Interested in other job postings from Microsoft Quantum? Stay up to date with the latest job postings using the #Quantum tag!

Looking for a summer internship for 2023? Check out our open internship positions!

The post Microsoft Quantum is hiring software engineers and software researchers! appeared first on Q# Blog.

]]>The post Interning at Microsoft Quantum – 2023 appeared first on Q# Blog.

]]>We are excited to announce that applications for Microsoft Quantum’s research, chemistry, and program management internships 2023 are open! (Stay tuned for the news about our software engineering internships.)

This year, our Intern Program will return to an in-person format, and we are thrilled to be able to host these again at our offices in Redmond, WA, USA. We invite interested students worldwide to apply!

**Apply for the Microsoft Quantum research internship**

**Application deadline: November 18, 2022**

Research internships are the most traditional of our internships, typically targeting graduate students pursuing a PhD in quantum computing. These internships focus on the exploration of new research directions under guidance of full-time researchers on our team. This position covers multiple projects that can include research on quantum algorithms, machine learning and optimization (classical and/or quantum), quantum error-correction and fault-tolerance, and physics device modeling.

While several 2022 internship projects are still ongoing, here are some highlights from research projects that wrapped up earlier this year:

**Shreya Nagpal**developed Python code that helps to visualize data structures related to quantum error correction, such as circuits and decoding graphs.**Troy Sewell**collected experimental and benchmarking data around quantum optimization algorithms for Set Covering Problem, and validated solutions using actual IonQ hardware.**Kunal Marwaha**studied local classical algorithms for optimization that are similar in performance to local Quantum Approximate Optimization Algorithms.**Maxwell Levatich**explored the usage of the Z3 SMT solver to solve complex scheduling problems.

You can find more examples of research internship projects from earlier years and the papers written about them in last year’s internships announcement.

**Apply for the Microsoft Quantum chemistry internship**

**Application deadline: December 2, 2022**

The chemistry internship will be very similar to the other research internships, but with a focus on computational chemistry: it might include advanced quantum chemistry calculations, high throughput computations, scientific software development, or machine learning-accelerated chemistry/materials computations.

**Apply for the Microsoft Quantum program management internship**

**Application deadline: December 2, 2022**

This year we are bringing back the program management internship, which was first piloted in 2021. Last year, Michelle Gelman worked on user research into the Azure Quantum partner experience to understand main friction points and identify the areas of focus necessary to improve and scale the program. This year’s project provides an opportunity for an intern to drive programs focused on expanding our Quantum community.

Our internships are a great opportunity to meet the Microsoft Quantum team and to contribute to our work. Of course, they also offer a lot of fun experiences as part of the greater Microsoft Internship program, from yearly puzzle events such as the Microsoft Puzzleday and the Microsoft Intern Game to the learning and social events where you can meet your fellow interns and researchers from all over the company!

The post Interning at Microsoft Quantum – 2023 appeared first on Q# Blog.

]]>The post Azure Quantum challenge at QCHack 2022: Recap appeared first on Q# Blog.

]]>Same as last year, our Bootcamp tutorials focused on preparing the participants for the challenge. Check out the recordings: Introduction to quantum computing with Q# and Azure Quantum and Introduction to Microsoft Quantum Development Kit and Azure Quantum.

The challenge we offered to the participants consisted of two parts. In part 1 the participants were presented with three independent tasks that tested their ability to implement a simple quantum oracle in Q#, as well as run Q# and Qiskit code via Azure Quantum. These tasks were designed to prepare the participants for part 2 of the challenge, in which they were to choose an arbitrary problem and explore it using IonQ simulator and QPU, and Quantinuum H1-2 system emulator.

After the usual 24 hours of hacking, we received 13 project submissions. Same as last year, it turned out that a team had to complete both parts of the challenge to qualify for one of the winning slots.

Let’s meet the winning teams and learn about their projects!

The winning team explored quantum image processing using Flexible Representation of Quantum Images. They experimented with different approaches to image encoding to find one that is feasible to run on an 11-qubit QPU, and then implemented several simple image processing tools such as rotation and shift. Finally, they ran their implementations on all three targets, getting perfect results on IonQ simulator and Quantinuum emulator, and a “somewhat recognizable” image on IonQ QPU that fell prey to the expected noise.

Fun fact: Mihai Zsisku was also a member of the winning team in our challenge in QCHack 2021!

In his project, Matthieu implemented a simple error correction scheme using small encoding circuits and explored its behavior on both IonQ and Quantinuum targets.

*“24h sure is short to achieve quantum error correction, but it’s exciting to try!”*

This project implemented entanglement teleportation protocol with a twist: it explored quantum repeater – a sequence of repeated entanglement teleportations that could enable entanglement teleportation over longer distances. It turned out one can run the protocol on Quantinuum emulator with four intermediaries between Alice and Bob, getting 87% fidelity in the process.

Fun fact: this is Wittmann’s third appearance on the list of our Hackathon winners – he took home wins from both last year’s QCHack and the MIT iQuHack earlier this year!

*“I really enjoyed the free-form format this year as it allowed me to implement some quantum algorithms which I was very interested in exploring, and this also allowed me the opportunity to learn how these algorithms perform on real noisy-devices. Part I of the challenge also was really helpful in getting me familiar with the API to connect with the quantum devices through Azure Quantum. Overall it was a very exciting weekend, and I look forward to participating again in the future!”*

Sumeet solved the subset sum problem – finding a subset of the given list of positive numbers that add up to a given target sum.

*“It was exciting to use an actual physical quantum computer for the first time! I’m at a point where I’m considering a career in quantum computing, and this was a great push towards that direction.”*

Congratulations to the winning teams! As always, it was a pleasure to host the challenge, and we’re looking forward to future to engage with the quantum community!

The post Azure Quantum challenge at QCHack 2022: Recap appeared first on Q# Blog.

]]>The post Microsoft/IonQ challenge at iQuHACK 2022: Recap appeared first on Q# Blog.

]]>The challenge proposed to the participants was very straightforward: use a quantum computer to build a game, or a component of a game. IonQ offered free access to their ion trap quantum device during the hackathon.

After the 26-hour hacking period we got 36 projects to judge. The projects were evaluated based on the lightning presentations by the teams and the code, and graded on five scales: utility of concept, technical merit, creativity, relevance, and communication. To fit the presentations in just a couple of hours between the end of the hacking and the results announcement, the teams were split into multiple rooms, so each judge only met a small subset of all teams.

The projects demonstrated a variety of takes on the theme: from quantum-inspired variants of card games and Tetris to educational games on topics such as universal gate sets or state tomography. Let’s take a look at the five winning teams and their projects.

The winning projects implemented a game that would teach the player about solving optimization problems using the Quantum Approximate Optimization Algorithm (QAOA). The game has two regimes: the player can either compete with the quantum computer to try and get a better result or cooperate with it to solve the problem together.

*“We were strangers before the hackathon (except for Tom and Nikita) and we built up the team in the slack of the competition. Then, we realized that 3 of us (Nikita, Vasiliy and Reinis) were in Munich that day, and they met for lunch just before the competition started.”*

Check out the interview with the winning team, or go straight to the project.

As the name hints, this project implemented a quantum variant of the classic Tic Tac Toe game, in which each square of the grid is a qubit, and players’ moves can apply individual gates, simple circuits, or measurements to modify the quantum state of the game.

*“iQuHACK was a super fun quantum hackathon. It was a great opportunity as I got to meet a lot of people with a deep love for quantum computing. We were very excited with the project prompt, and it was really amazing that we could run our program on an actual quantum computer… I think it’s fun and enriching to think of quantum in a game setting and apply complex knowledge in an approachable and educational context.”*

Check out the project here.

In this blackjack-inspired game the player can affect the probability distribution of the cards they are dealt by applying gates to the quantum state used to generate the next card randomly.

*“We were pleasantly surprised with the freedom the organizers gave us in designing our own project by having minimal requirements. That really got our creative juices flowing! Now we can say out loud that gambling is boring while cheating with quantum mechanics is fun!”*

Check out the project here.

SOULINQ is a 2-player 2D platformer in which the players share an entangled pair of souls. They have to navigate the world, consuming inner fire to evolve their soul states, fighting each other, and surviving cosmic rays that collapse their states to “dead” or “alive”.

*“With a passion for both independently, I really enjoyed the experience of building at the interface of game design and quantum computing. I thought the idea of representing human souls with qubits and human relationships with entanglement in a real-time multiplayer game was interesting, but the idea of the game as an interactive quantum prisoner’s dilemma simulation particularly intrigues me. A big thank-you to MIT and Microsoft for organizing the event, bringing our team together, and helping make this project possible— it was an absolute blast!”*

Check out the project here.

This project featured a game inspired by auto-chess, in which the players construct 2-qubit circuits that aim to flip their input states from 0 to 1 and then pit them against each other by combining them in longer circuits.

*“Overall we thought that it was a very enjoyable experience, and it helped us learn new ways to think about quantum circuits. We just wished the hackathon duration was longer so we could flesh out our game design (especially the GUI) more!”*

Check out the project here.

Congratulations to the winning teams! We really enjoyed hosting the challenge, and we are looking forward to future hackathons!

The post Microsoft/IonQ challenge at iQuHACK 2022: Recap appeared first on Q# Blog.

]]>The post Announcing Azure Quantum challenge at QCHack 2022 appeared first on Q# Blog.

]]>The first edition of QCHack ran in April 2021 and attracted over two thousand participants from 80 countries! Check out the last year’s event summary to learn more about the history of this Hackathon.

QCHack will consist of two parts: the Hackathon, running for 24 hours during the weekend of April 9-10, and the pre-Hackathon Bootcamp during the week of April 4-8. Same as last year, all bootcamp events and the Hackathon itself will take place online.

The bootcamp will help participants get started with their Hackathon preparation and immerse them into the world of quantum computing. It will include tutorials on general quantum computing, as well as workshops on quantum programming toolkits offered by the sponsor companies that will be used in their respective challenges. The participants will have ample opportunities to meet quantum computing professionals from the sponsor companies, to learn more about the cutting-edge research done by them and their journeys in quantum computing, and to get career advice.

You can find the recordings of the workshops offered at last year’s bootcamp in this playlist.

The main event will take place over the weekend of April 9-10. Each company will offer a unique challenge focused on using their quantum programming tools and platform to solve a certain problem, revealed at the kick-off ceremony on April 9^{th}. Look out for possible hints in the companies’ workshops at the bootcamp!

This year we will team up with our hardware partners IonQ and Quantinuum to offer a challenge focusing on Azure Quantum. It will consist of two parts:

- Warmup problems. To start with, you’ll be offered several simple problems to get familiar with the tools you’ll need in the main part of the challenge. Some of these tasks will come with testing harnesses, similar to the ones used in the Quantum Katas, so that you’ll be able to check whether your solutions are correct.
- Free-form challenge. In this part, you’ll create a project that solves a quantum computing problem within certain constraints. There will be no “right” or “wrong” way to solve this challenge; you have the freedom to decide what you want to do and what tools to use! The submissions will be judged on several criteria, such as creativity, technical depth, and the educational value of the project, published as part of the challenge description.

The points from both parts of the challenge will be added together, and the highest-scoring teams will be declared winners! The challenge will have prizes, as well as an opportunity for the winning teams to present their projects to the Azure Quantum team after the event.

Check out the recap of our challenge at QCHack 2021 to see what kind of tasks were offered. Of course, this year’s challenge will be different!

Are you excited about this Hackathon? Register for it and start learning!

Here are several great resources to practice for Microsoft’s challenge:

- Quantum computing foundations Microsoft Learn learning path introduces you to the QDK and Azure Quantum.
- The Quantum Katas offer a collection of tutorials and programming exercises covering the basic concepts and algorithms of quantum computing. They are a great way both to get started with quantum computing and Q# programming and to get familiar with the types of tasks that can be offered as warmup problems.
- You can use the $500 Azure Quantum credit to explore running jobs on quantum hardware and simulators via Azure Quantum.

I’m looking forward to the QCHack, and I hope to see you there!

The post Announcing Azure Quantum challenge at QCHack 2022 appeared first on Q# Blog.

]]>The post A quantum circuit logical puzzle appeared first on Q# Blog.

]]>- The single-qubit gates denoted by the question marks are I, H, X, and Z, each gate is present in the circuit exactly once.
- The state generated by this circuit from the |00⟩ state is entangled.
- Swapping the two gates that act on the bottom qubit changes the state.
- Swapping the two gates applied after the CNOT gate (on the right side of the circuit) does not change the state but changes its global phase.

What state does this circuit prepare? Is it possible to identify the circuit uniquely from this information?

You had a week to solve the puzzle, and now it is time for the solution! Let’s see how you could solve this puzzle in two different ways.

Clue #2 allows us to identify the position of the H gate right away: for the CNOT gate to entangle the two gates, its control qubit must be in superposition, and of the gates we’re given only the H gate does that.

Now we have 6 possible states to consider: all permutations of the gates I, X, and Z. Clue #3 allows us to narrow down the search space a bit more: both I and X gate commute with the CNOT gate when applied on the target qubit, so if both were acting on the bottom qubit, clue #3 wouldn’t hold. This rules out two more possibilities, leaving us with 4: H – I – X – Z, H – I – Z – X, H – X – I – Z, and H – X – Z – I. (Here I list the gates in the reading order: the top left one, the top right one, the bottom left one, and the top right one.)

After that it’s trial and error: you need to try these four combinations and for each of them check whether clues #3 and #4 fit them. In the end you should have two possible answers: H – I – X – Z and H – X – I – Z. Both these circuits prepare the same state: the Bell state 1/√2 (|10⟩ – |01⟩).

Now let’s see if we can verify our pen-and-paper computations with some Q# code. We’ll start with the same deduction as in the previous solution, identifying the location of the H gate, and focus on the other three gates. To check whether a certain circuit satisfies clues #3 and #4, we need several steps:

We’ll use a `String[]`

type, with each array element encoding the name of the gate. If we were going to use this type only in Q# code, we could’ve used `(Qubit => Unit is Adj+Ctl)[]`

type, with array elements being the gates themselves, but, as you’ll see later, we’ll need to pass that type from the classical host program, and we can’t do that with callable types.

We’ll do that using two operations: one operation to apply an individual gate based on its string name

operation ApplyGate (q : Qubit, gateStr : String) : Unit is Adj + Ctl { let gate = gateStr == "H" ? H | gateStr == "X" ? X | gateStr == "Z" ? Z | I; gate(q); }

and another to apply the whole circuit:

operation ApplyCircuit (qs : Qubit[], gatesStr : String[]) : Unit is Adj + Ctl { ApplyGate(qs[0], gatesStr[0]); ApplyGate(qs[1], gatesStr[2]); CNOT(qs[0], qs[1]); ApplyGate(qs[0], gatesStr[1]); ApplyGate(qs[1], gatesStr[3]); }

Here we’ll use the same trick for checking states equality that I use in the Quantum Katas: apply the operation that prepares one of the states, apply adjoint of the operation that prepares the other state, and check whether the resulting state is |00⟩ using the library operation AssertAllZero. We’ll use a convenient library function Swapped to swap the elements of the array to represent swapping the gates in the circuit:

operation TestThirdConstraint (gates : String[]) : Unit { use qs = Qubit[2]; ApplyCircuit(qs, gates); Adjoint ApplyCircuit(qs, Swapped(2, 3, gates)); // If the result is not 00, the constraint is satisfied. AssertAllZero(qs); }

However, we’ll need to modify this trick a bit. If we’re going to try all possible gate combinations and check whether each of them fits the clues, we need to be able to figure out whether the states are equal or not programmatically, and Q# doesn’t offer exception handling. Instead, we’ll call this code from a classical host code (in this case C#) and do exception handling there:

var thirdSatisfied = false; try { TestThirdConstraint.Run(sim, new QArray<string>(gates)).Wait(); } catch (Exception) { thirdSatisfied = true; }

We’ll take a similar approach to testing clue #4, though we’ll need to check two parts of the clue here: first, that swapping two gates doesn’t change the state itself, and second, that swapping two gates changes the global phase of the state.

The first part of the check can be done similarly to the `TestThirdConstraint`

operation above. For the second part of the test, we’ll allocate an extra qubit in the |+⟩ state and compare *controlled* versions of the state preparation operations to coax out the global phase that should be introduced by the gate swap. Furthermore, we can observe that that global phase can only be -1 (the Z gate is the only one that can introduce it), so we can make our test even more accurate: we can check that after applying the controlled versions of both operations the control qubit should end up in the |+⟩ state.

With these observations in place, the test for clue #4 will work as the opposite of the test for clue #3: the clue is satisfied only if the test operation does not throw an exception.

With all these pieces assembled and the classical host program iterating over all gate combinations, this solution yields the same result as the pen-and-paper one. You can find the complete code for this puzzle here.

For this puzzle, the advantage of the programmatic solution is not immediately clear – with so few possible circuits, writing the code might take longer than trying all possibilities by hand! However, the code is less error-prone compared to manual computations, and it scales up a lot better than the pen-and-paper approach!

The post A quantum circuit logical puzzle appeared first on Q# Blog.

]]>The post Analyzing a Sudoku solver using resources estimation appeared first on Q# Blog.

]]>A couple of months ago one of our users asked a very interesting question about one of the projects in our samples repository. The gist of the question was: Grover’s search-based Sudoku solver worked fine for one input puzzle but threw an exception when switched to a different puzzle. What’s going on, and might it be a memory issue?

Right now, quantum software development is at a stage where this type of questions – trying to troubleshoot unfamiliar quantum code developed by someone else – are very rare for most people outside of teams working on quantum software daily. But, similarly to classical software, eventually the field will grow so that such questions will be routine. I figured out that it would be interesting to use this question to show some tricks that can be used to answer it without getting familiar with every line of code.

In the past Q# Advent Calendars I wrote about solving constraint satisfaction problems using Grover’s search, some challenges arising in the process and some tricks to overcome them. In the latest post of the series I dealt with a related issue: the program ran successfully but took longer than I liked to complete.

Both the out-of-memory issue and the too-long-runtime issue can stem from the same cause: using too many qubits in a program that runs on a full state quantum simulator – a classical program which models the behavior of a quantum system without accessing actual quantum hardware. A full state simulator uses 2ᴺ complex numbers to describe the state of an N-qubit system, so the more qubits the program uses at once, the more memory its state representation takes, and the more time it takes to update the state of the system after each gate application.

The rule of thumb I use is that programs which use under 25 qubits run within a reasonable time and memory footprint, programs which use over 35 qubits do not, and programs between these two extremes can vary. Let’s see where this Sudoku solver program falls on this spectrum!

To start with, let’s minimize the classical portion of the code. I’m going to work with just 4×4 Sudoku puzzles, dropping digits from the grid as needed, so I’ll remove all code related to parsing command line parameters, working with other puzzle sizes, and the classical solution. I’ll start with the puzzle included in the sample (on the left) and see if I can work our way up to the puzzle suggested in the issue (on the right):

Next, let’s create `QuantumSimulator`

inside the `SudokuQuantum.QuantumSolve`

method instead of passing it as a parameter. I’m going to use the same two simulators each time I try to solve the puzzle, so it makes sense to create both inside the method.

The next step is to split the code inside `SudokuQuantum.QuantumSolve`

method into three parts: parsing the input puzzle into a set of constraints that need to be satisfied, estimating the resources required for the quantum solution, and running the quantum solution. The basic code for resources estimation is very simple: you just need to create a separate simulator called ResourcesEstimator and pass it as the simulator parameter to the `SolvePuzzle.Run`

method, extracting the necessary statistics afterwards:

var estimator = new ResourcesEstimator(); SolvePuzzle.Run(estimator, emptySquares.Count, size, emptySquareEdgesQArray, startingNumberConstraintsQArray).Wait(); Console.WriteLine(estimator.Data.Rows.Find("QubitCount")["Sum"]);

However, at this point we hit a runtime exception `ExecutionFailException`

that we didn’t see when running the Q# code on a full state simulator. Where does it come from?

Q# operation `SolvePuzzle`

tries to solve the puzzle using different numbers of Grover iterations from 1 to the optimal number calculated with the assumption that there is exactly one solution to the provided puzzle. On each attempt the code checks whether the obtained result is correct, and if it is not, tries the next number of iterations, eventually giving up and throwing this exception to indicate that the solution was not found.

Resources estimator, however, does not actually simulate the gates applied by the code – it only goes through them, tracking events such as gates applications and qubit allocations. This allows this simulator to process programs that require hundreds and thousands of qubits, but on the flip side, whenever it encounters a measurement, it always assumes that the measurement result is 0, thus never realizing that the puzzle has a solution!

A more advanced resources estimator called QCTraceSimulator allows to provide probabilities of measurement outcomes to use in resources estimation, but this is out of scope of this blog post.

Once we rewrite `SolvePuzzle`

to run the search just once and to remove the correctness check (it is repeated by the classical code afterwards anyways), we can see that this program is going to use 27 qubits, so it can be simulated. However, if we remove 5 more digits from the puzzle to get the input suggested in the original issue, the qubit count will jump to 81 – which is a lot more than can be simulated!

Why does such a small program use so many qubits? Let’s fall back to the original puzzle with 3 missing digits and see what we can figure out from reading the code.

On the surface, we need to find values for three variables (the numbers in the missing cells), each of which can range from 0 to 3, thus requiring 2 bits per variable – but this accounts only for **6 qubits**. Where do 21 more come from?

- Checking answer correctness in Grover’s search (before refactoring to remove the check):
**1 qubit**. Operation`FindColorsWithGrover`

allocates the qubit “output” used to verify the correctness of the answer alongside the register used for storing the variables, though it doesn’t use it until after the main iterations are done. - Phase kickback trick:
**1 qubit**. Every time a Grover iteration applies the marking oracle that checks whether the variable assignment is a solution, it needs to convert it into a phase oracle using phase kickback trick, which uses an extra qubit. - Constraints on the variables that cannot be equal:
**2 qubits**. Every time two missing digits are in the same row, column, or 2×2 square of the Sudoku grid, they add an inequality constraint on the matching variables, which needs a qubit to track it. In our cases two of the missing digits are in the top left square of the Sudoku grid, and two are in the second column, so there are two constraints. - Constraints on the values the variables cannot take:
**9 qubits**. Similarly, for every missing digit every digit that is in the same row, column, or 2×2 square adds an inequality constraint, since the missing digit cannot take the same value as any of them. The classical part of the code does the pre-processing to remove duplicate constraints, but each constraint is checked using a separate qubit, so with each of the 3 variables having 3 values they cannot take, we need 9 qubits to track these constraints. - If you look through the rest of the Q# code, you won’t find any more explicit qubit allocations, so where are the remaining
**9 qubits**coming from? Those are a sort of “virtual” qubits – qubits that you didn’t allocate explicitly, but that would have to be allocated by the compiler when running the code on hardware to implement the multi-controlled gates used in the`ApplyVertexColoringOracle`

. Resources estimations target hardware execution, so they count those qubits even though they won’t be used when running on a simulator. The simulator only ever allocates 18 qubits, making the simulation comfortably within its simulation capabilities.

Can we optimize the code to be able to solve more complicated instances of the Sudoku puzzle?

The first and obvious optimization is changing the way to evaluate the constraints on the values that the variables cannot take. We can use one qubit per missing digit and evaluate all constraints that involve this digit using it. This allows us to save several qubits (6 for the small puzzle we follow in this blog post), but not enough to allow us to solve larger puzzles.

A better way is to rewrite Grover’s search implementation to build these checks in the search space rather than evaluate them as constraints on the variables. As a reminder, Grover’s search uses an equal superposition of all basis states in the search space both as its starting state and as a part of “reflection about the mean” step. We can use a superposition of only the states that satisfy the constraints imposed by existing digits in the grid. Not only does this reduce the number of constraints to check (and thus the number of qubits allocated), but it also reduces the number of iterations the search needs to do!

The details of this refactoring are out of scope for this blog post, but you can see the complete code here. You see that it can solve many puzzles without any search iterations – with enough digits the search space size is 1, and the correct answer is obtained by just preparing the “superposition” of one basis state and measuring it (this means that the solution is effectively classical, with all the work done by the preprocessing routines). And finally, it solves the puzzle mentioned in the issue with 8 missing digits correctly in just 2 search iterations, taking about 5 minutes!

The post Analyzing a Sudoku solver using resources estimation appeared first on Q# Blog.

]]>