Microsoft's Quantum team is excited to announce the Q# Coding Contest – Summer 2020, the third in the series of Q# contests! In this contest you can put your quantum programming skills to the test, solving quantum computing tasks in Q#. The winners (as well as some lucky participants) will receive a Microsoft Quantum T-shirt!
Quantum computing is a radically different computing paradigm compared to classical computing. Indeed, it is so different that some tasks that are believed to be classically intractable (such as factoring integers or simulating physical systems) can be performed efficiently on a quantum computer. In December 2017 Microsoft introduced the Quantum Development Kit which includes the Q# programming language.
In summer of 2018 we hosted the first quantum programming contest, which included problems on introductory topics in quantum computing: superposition, measurement, quantum oracles and simple algorithms. In winter of 2019 we hosted the second quantum programming contest, which offered harder problems on those topics plus some tasks on implementing unitary transformations. This contest will introduce new types of tasks, as well as some twists on the previous ones.
The contest will run from June 19 to June 22. As usual, we will hold a warmup round the weekend before the contest, from June 12 to June 15, to give you an opportunity to get familiar with the contest environment and submission system before the main contest. Participation in the warmup round is optional.
Good luck! We hope you enjoy the contest!
The rules of the contest are:
- The main contest and the warmup round will have several tasks of various complexity levels.
- To solve each task, you will write Q# code to implement the described task. Solutions are accepted in Q# only.
- The solution is correct if it passes all tests from a predefined test set. You will know whether the solution is correct soon after submitting it.
- Participants are ranked according to the number of correctly solved tasks.
- Ties are resolved based on lowest penalty time for all tasks, which is computed as the latest submission time (the time since the start of the contest) for any of the correctly solved tasks. There is no penalty for failed submissions.
- The contest and the warmup round will award T-shirts as follows:
- The top 50 ranked participants in the main contest will receive a Microsoft Quantum T-shirt.
- Random 25 participants of the main contest who solved at least one problem but didn't finish in the top 50 will receive a Microsoft Quantum T-shirt.
- Random 25 participants of the warmup round who solved at least one problem but didn't win a T-shirt in the main contest will receive a Microsoft Quantum T-shirt.
- All T-shirt winners will be selected after the end of the main contest. T-shirt designs will be announced later :-)
- NO PURCHASE NECESSARY. Must be 16 years of age or older. Game ends 06/22/20. For details, see the Official Rules.
For first time Codeforces users:
- Create user account here.
- Register for the warmup round here.
- Register for the contest here.
- Once the warmup round starts on June 12, access the problems here.
- Once the contest starts on June 19, access the problems here.
Quantum computing and Q# materials:
- The Quantum Katas — a collection of tutorials and programming exercises that help you learn quantum computing and Q# (includes most of the problems from previous contests).
- A collection of awesome quantum computing learning resources, including MOOCs and books.
- A collection of awesome Q# resources.
- Q# installation instructions and documentation.
- Microsoft Q# Coding Contest — Summer 2018 and Warmup Round.
- Microsoft Q# Coding Contest — Winter 2019 and Warmup Round.
Note that this contest will use Q# 0.11.2004.2825, while the previous contests used Q# 0.2 and Q# 0.4, respectively. We've updated the test harnesses from the previous contests to support the latest version of Q#, so you can use them for practice.
Update: The warmup round is over, here is the editorial for the problems. You should be able to see other people's solutions and practice now.
Is it rated?
No. Q# contests are quite different from regular Codeforces rounds, and not frequent enough to warrant a rating of their own :-)
lol your(ezdp )profile picture shows your reaction after posting "is it rated?" :P
I'll add to resources: my syntax highlighting for Sublime Text 3 (and maybe something else), which works better than C#/F# syntax highlighting. If you want to improve it, especially by adding samples/tests, feel free to fork or submit a pull request.
Q# C# F# oof
Do the participants get participation certificates?
No. You'll be immortalized in the contest standings, though :-)
Will there be no cf normal rounds like div2 or educational rounds ?
Normal CF rounds are pretty much orthogonal to the Q# round, so it doesn't affect them. (In fact, at least one of the previous Q# contests overlapped with a normal round.) Right now the calendar has two upcoming contests in May.
Super Excited
actually you're super saiyan gohan lol!
What will probably happen to me:
If you're going to introduce your cat to quantum computing, you might want to avoid the topic of Schrödinger's cat... I believe this is why historically cats don't do so well with quantum physics.
Can someone with experience from previous Q# contests suggest some more interesting resources?
is q# easy to learn? plz suggest resources!!
Use those to get the answer: Google.com — YouTube.com — Quora.com :D
I hate this kind of response. If he asked about covid-19, sure, but a site dedicated to competitive programming which hosts a competition in q# is a perfectly reasonable place to ask about a programming competition in q#.
I asked last year a similiar question and got a useful resource: http://lapastillaroja.net/wp-content/uploads/2016/09/Intro_to_QC_Vol_1_Loceff.pdf
TL;DR The programming environment of Q# is nicely simple, but quantum physics is not.
I only found the documentation ? also how to install it on local machines?
Have you checked the resources linked from the blog post? They definitely have a lot more information than just installation instructions.
I'm glad to be able to join these contests again!
Does anybody knows when the div 2,3,4 will be back ?
Looking at the contest schedule — May 26 :-)
looks at previous contest participation
Oh this seems an easy way to get a tshirt, not many participants! I'm sure I can learn the basics in a month I mean how hard can it be.
opens Quantum Katas, excited about something new.
drowns in linear algebra and hard-to-visualize concepts
Seriously though tshirts aside, the topic does seem really interesting and I'd love to get to know more but I didn't like the written tutorials.. maybe just because I prefer videos. Is there any online resource/course that explains all the quantum basics in a more visual way ? Appreciated!
?
Linear algebra is like the most visualizable thing ever.
Non-trivial quantum computing, the type where you use entanglement non-trivially, starts in 8 (real) dimensions though. A couple fewer if you only look at unit vectors and normalize the global phase in some way, but still strictly more than 3.
I don't think you need to literally imagine 8 (or whatever) dimensions in your head to "visualize" higher-dimensional linear algebra. Visual intuition about 2- and 3-dimensional stuff carries over well enough. Even when working with infinite-dimensional spaces, doodling 2D stuff on paper can be helpful.
Awesome quantum computing offers a lot of resources in a variety of formats — a lot of them are written but there are videos and MOOCs there as well.
Thank you! Exactly what I was looking for.
What is Q# coding? Why we want this? and why we will do QUANTAM COMPUTING? (I just want to know. Can you please motivate us by telling some awesome benefits?)
Here is a great video on "why quantum computing?" by Dave Wecker: https://cloudblogs.microsoft.com/quantum/2018/06/01/achieving-practical-quantum-computing/. And we want to learn Q# to be able to implement the algorithms that allow us to solve unsolvable problems of today.
I'll participate in the contest. Also you are beautiful!
if he is participating because she's beautiful. BIG SIMP else just a compliment.
I've always found quantum computing fascinating, and now I have a reason to learn its language and work with it :)
Are these warmup challenges only for practice purposes or rated on codeforces?
Both the warmup round and the main contest are not rated. You can win a T-shirt in the warmup round, though, so it's a little more significant than only for practice purposes this time.
Okay! Thanks :)
Can someone tell me how do I run a Q# program on terminal? Googled a bit and they all told me to download some IDE.
You can bypass Visual Studio and just use .Net Core SDK (packages
dotnet*
) in Linux. Look for commands that use it, like here.Thanks a lot!
Don't upvote.
Okay, Downvoted.
Can anyone suggest best apps for writing code like codeblocks ( other than codeblock) for a windows user
Does anyone have experience running Q# via Jupyter Notebooks? I tried some sample code from the warm-up rounds and it shows "The given key was not present in the dictionary".
Can you please provide the exact steps you're following for a repro? It could be, for example, this issue if you're opening namespace in a separate cell.
In general, Q# accumulated some syntax and libraries changes since the last warmup round (it's been over a year, after all :-)), so some of the code will generate warnings and errors on the latest Q#.
Does this help? I'm not sure what you mean by 'repro'. I used this link for installing Q# in Jupyter Notebooks.
I basically copied code from the warmup round 2018 and tried running it in one cell. Since I could get 'Hello World' and other simple programs to run, I thought I could run code the same way as other languages. But it seems I'm missing @EntryPoint() and other important syntax or I need a separate script for inputs? Either way, I guess I need to spend more time reading the docs.
"Repro" is the fragment of code or sequence of steps that allows to reproduce your problem. In this case, the screenshot tells me that you don't need to specify the namespace if you're running in notebooks, just the open directives and the operations you declare. (You don't need to specify EntryPoint either in the notebooks or when running on Codeforces, that is syntax for standalone Q# application which is a yet separate scenario.)
You raise a good point here. I'll see if I can find the docs about the differences between running Q# in notebooks vs in console app. For Codeforces, each problem specifies the signature your code should have, and that matches running Q# code as an app with a driver.
Thanks for explaining!
So you mean that for running Q# code using VS Code(for example) and .NET, you need a custom driver program in C# for each solution ?
I'm considering switching to another method(like VS Code) as my Q# kernel won't connect any longer for some reason.
There are multiple ways to run Q# code; you can do it with a driver program in C# or Python, or you can do it as standalone executable. Codeforces testing harness uses C#, since I need specific exception processing to provide different verdicts for some problems. You can find examples of different ways in this repository:
How are you running Q# notebooks? If you install it locally, a restart should fix things like unresponsive kernel.
How do we check in our local ide whether we have generated the correct state that has been desired in the question ?
Okay thanks, i'll try it out
When will the T-shirt designs be revealed? I'm debating whether I should participate or not, because it takes time to prepare and study for this, and I have other stuff that's taking up my time.
As soon as we have them :-)
I am trying to learn Q# with the help of Quantum katas but am stuck in a question. i dont know to whom to ask so i am asking it here. can anyone help? I m stuck at exercise 6 in single qubit gates.
github link for the exercise
Have you checked the solution in ReferenceImplementation.qs? For solving these exercises you go through the list of available gates and their effects (for example, in BasicGates tutorial) and check which ones have effects similar to what you need. In this case, it's just one gate.
I just didn't found the solution to this exercise previuosly. Thanks for sharing. I now totally understand it!
can anyone explain U3 of 2019 Warmup. I read the editorial but didn't understand it.
For an integer $$$k \in [0, 2^N - 1]$$$, I write $$$|k\rangle$$$ to mean the state vector corresponding to the little-endian encoding of $$$k$$$. The required unitary needs to do the following:
The first task can be accomplished by flipping the each qubit in
qs[0 .. N-2]
ifqs[N-1] == 0
. This is done via the lineThe second task can be accomplished by applying the $$$H$$$-gate to each qubit in
qs[0 .. N-2]
ifqs[N-1] == 1
. This is done via the lineI understood how the program implements the unitary. What i can't understand is how you found out what the required unitary did.
You can read off what a unitary does from it's matrix. For example, here's the matrix for U3 for $$$N=3$$$:
The leftmost column tells us what $$$|0\rangle$$$ gets mapped to. In this case it gets mapped to $$$c_0|3\rangle$$$, for some complex constant $$$|c_0| = 1$$$. This is because the only
X
in column zero is in row 3, and we know the unitary transform preserves norms. More generally $$$|0\rangle$$$ gets mapped to $$$c_0|2^{N-1}-1\rangle$$$.Column one tells us that $$$|1\rangle$$$ is mapped to $$$c_1|2^{N-1}-2\rangle$$$ for some $$$|c_1| = 1$$$.
Likewise the rightmost column tells us that $$$|2^N - 1\rangle$$$ gets mapped to some linear combination of $$$|2^{N-1}\rangle, |2^{N-1} + 1\rangle, \ldots, |2^N - 1\rangle$$$.
Thanks
Is it rated?
No … Already asked and answered in the 1st comment :v
I think it is yes because last year it was rated.
looking forward to participate.
Rated!!!
Finally a Rated contest!!!
I'm so excited!!!
is it possible to learn Q# like in 10 hr or so if it is then can you plz share some material
The resources I link in the post are really good — and you don't need to learn all the capabilities of Q#, just enough to start solving the problems. For example, you can safely skip generics :-)
so now I have to stay up the whole night :) thanx a lot!!!! I also find https://www.youtube.com/watch?v=F_Riqjdh2oM this video from Microsoft very good for beginners
The warmup round runs for 3 days, and the T-shirts in it are awarded randomly, so quite that level of sacrifice might not be necessary :-)
actually my exams are also going on :| i have to do lots and lots of assignments from day after tomorrow!! ༼ ಥ_ಥ ༽ sometimes i wonder why i m always so fucked up!!
Can anyone help me with testing the code locally?
For example I wrote a Q# program, how can I test it with some testcases.
I have no experience except learning from QuantumKatas which provides unit test. I have installed the environment suggested here.
This particular problem is task 1.11 from Superposition kata, so it's very easy to test :-)
More generally, testing quantum programs can be quite challenging, depending on the type of problem. You can study the testing harnesses in the Quantum Katas to see how they are implemented for a type of problem similar to yours. Superposition tasks, though, are tested by comparing them with the correct solution, so if you don't have a correct solution on hand, you can't take the same approach. In this case I would use DumpMachine to check the amplitudes of the basis states in the state you prepared.
You can follow this tutorial to create a runnable executable with Q# code and then modify Q# code to allocate qubits, call your solution on them and use DumpMachine to inspect the amplitudes.
Thank you!! I think DumpMachine would be useful for the contest.
Though it's not rated, it will provide tough competition.
Rated contests are only for motivation, the reality is to solve practice questions which boost up the confidence.
Thanks Nickolas.
Happy Coding! :)
In this contest, will Python3 be acceptable?
From the announcement blog:
Could anyone get the IntelliSense in Visual Studio working for Q#? Mine cannot find the namespaces and gives errors like 'No namespace with the name "Microsoft.Quantum.Canon" exists.'. The program compiles and runs correctly.
VS IntelliSense can be sensitive to a number of things in your environment, like .NET Core version and VS version; for example, this issue happens when you're running QDK 0.11.2004.2825 with .NET Core 3.1.300. I got my configuration working but I'm using .NET Core 3.1.201.
Is it possible to run code in the Custom Invocation tab? I tried adding an entry point, but I'm getting this error:
My code:
Googling the error code did not help at all.
Custom invocation was implemented for the last contest:
https://codeforces.net/blog/entry/65579
See if that still works.
It doesn't, unless I misunderstand something.
CSC : error CS5001: Program does not contain a static 'Main' method suitable for an entry point
Edit: this code now works, thank you.
You definitely shouldn't have to add
@EntryPoint
to run in Custom Invocation. However, it looks like it was broken when we updated Codeforces from the previous QDK version to 0.11. Let us look into fixing this...We've updated custom invocation, so it should work now if you define a wrapper operation
RunQsharp
:I have a question. Maybe this is really stupid.
How does Q# works? First i thought maybe they run on an actual quantum computer and we just get the output but what happens when we run it locally. Is the Microsoft quantum development kit a simulation which behaves like a quantum computer but inefficient because it's on a classical computer? I really have no idea
edit: corrected a mistake
Microsoft QDK is a collection of tools, from the Q# programming language and compiler to several simulators. When you run a Q# program locally, it will typically use a full state simulator which imitates the behavior of a perfect (error-free) quantum device up to ~30 qubits. You will also be able to use QDK to run the same Q# programs with a resource estimator or on real hardware, but this is out of scope of this contest :-)
What is the best way of casting LittleEndian to Qubit[]?
It seems like, without casting, it's impossible to access individual qubits. I looked through the Q# reference, including the LittleEndian and Convert documentation, and couldn't find anything that works.
LittleEndian
is a wrapper type around theQubit[]
type, so to treat it as aQubit[]
you need to unwrap it:Length(register!)
to get the number of qubits orregister![i]
to get i-th qubit.Thanks, that's exactly what I needed! I found the "newtype LittleEndian = Qubit[]" but didn't know how to remove the tag.
Is there a page in the reference talking about the "!" syntax?
Types in Q#, more specifically the section on unwrap operator.
I had the same question as Svlad_Cjelli. Thank you for the answer!
Is there an easily searchable repository of Q# examples yet? If I'd seen any piece of code actually using LittleEndian I think this would have been obvious, but I don't know where to look. I don't think the documentation helps.
https://github.com/Microsoft/QuantumKatas/ and https://github.com/Microsoft/Quantum. It would be tricky to search for
!
, butLittleEndian
is quite searchable.Excuse me, but... why?
From the docs:
Ok, but I don't want to have to remember the entire standard library just to write some simple imperative testing code. I'm already making a G̶o̶o̶g̶l̶e̶ Bing search every minute.
I much prefer the old syntax (
set arr[idx] = expr;
) even if it's semantically an ugly special case.Could someone help with setting up the machine learning environment? I tried doing everything as instructed but the compiler complains about having C# and Q# files in the same project, saying I should convert the executable Q# project into a Q# library and moving C# into a separate project. But when I do that, the C# project doesn't recognize and Q# classes, even though I added the Q# library project as a dependency.
I also tried using python for the host program but that didn't work either for some reason, currently investigating.
EDIT: I managed to get Python to work.
Have you tried taking the projects from https://github.com/microsoft/MLADS2020-QuantumClassification or from https://github.com/microsoft/Quantum/tree/master/samples/machine-learning/? That's what I did when I started learning our QML library — starting with a project that already does it and modifying it is a lot easier than starting from scratch.
Yes, I tried building the HalfMoon example but it gave me the same errors. I guess I have a newer version of the QDK which has some non-backward-compatible changes?
If you're building an existing project HalfMoon, it should use the version of QDK specified in its csproj file, and it should build regardless of the QDK version you have installed. When I try to build it, it gives me a warning "The project is an executable Q# project but no entry point has been found. The project should be a library, and any C# driver code should be defined in a separate project.", but as it's a warning, it can be safely ignored.
If you're getting an actual error, can you give the exact error message you get?
I'm getting a runtime error "Could not load file or assembly 'System.Runtime, Version=4.2.2.0'" I tried some suggested fixes from StackOverflow but nothing worked.
Now, I did make it build and run from Python, but it's not really working well. All the final parameters end up within 0.0001 of one of the initial parameter seeds, and the end result has 15% error rate. I tried increasing the LearningRate parameter, but it didn't help. Applies to both the original HalfMoons example and the D1 training set.
This looks like some issue with the .NET Core version or VS, I haven't seen this kind of error recently...
In the tutorial I had to both increase the LearningRate and decrease the Tolerance. Additionally, starting with multiple starting parameter sets for search helps.
Anyone else manage to pass D1/2 without actually getting machine learning to work? :|
Well, I know how to do it, so it's not unexpected that you'll be able to figure it out :-) However, for the sake of solving problems in the main round you'll probably want to get it to work.
Seems doubtful, overwhelmed by too many errors D:
Regarding Python / Jupyter Notebooks:
The intro works fine. However,
I saw this but it doesn't seem to help. %package gives
"ExploringQuantumClassificationLibrary": %package and %version don't seem to work at all.
"HalfMoons":
EDIT: Ok changing MachineLearning to 0.11.2006.403 seems to work for "InsideQuantumClassifiers" and "HalfMoons."
Half-moons with C# runs (although as mentioned earlier the error rate seems to be above 15%?).
I see that
<PackageReference Include="Microsoft.Quantum.MachineLearning" Version="0.11.2004.2825" />
is part ofHalfMoons.csproj
. After addingopen Microsoft.Quantum.MachineLearning;
toProgram.qs
how do I automatically add it to.csproj
?dotnet restore
anddotnet build
don't change anything, are they supposed to?I don't think the package reference can be added automatically, you have to add package reference first and then you can open namespaces (I think other .NET languages work the same, it's not a Q# restriction).
dotnet restore
anddotnet build
restore NuGet packages that are already specified in.csproj
, not add new ones.For your earlier comment that is unresolved,
%package
and%version
are IQ# commands, and ExploringQuantumClassificationLibrary is a Python notebook, so they won't work in that one.I also encounter many errors when running "InsideQuantumClassifiers". Changing MachineLearning to 0.11.2006.403 helps a lot! I think this should be fixed in "InsideQuantumClassifiers".
I've thought about it, but from what I gathered from the documentation, the preparation of the qubit state from a given input isn't deterministic. How did you figure it out?
Ok, I found the actual library implementation, it's much simpler than what they say in the arxiv paper as there's no normalization with added padding elements to preserve features. I'll have to think about how to extract the maximum probability component of a qubit, sounds similar to Grover's algorithm...
I got it, the library automatically does that, haha. It turned out way easier that I thought.
Did you find a place where that's mentioned in the documentation? How can I determine how many qubits will be used? (other than assuming myself)
The same principle is used in machine learning in general, I just forgot about it.
The network outputs a list of "confidence" probabilities, and the top one is chosen as the "answer".
I thought maybe quantum machine learning would give results randomly according to the probabilities, but that's not the case, they run it many times to calculate the probability and then just output the most likely one.
So in the D1 task, if you don't apply any rotations and just measure the qubit directly, you'll get the exact opposite from the desired result: the state preparation assigns the X coordinate to the Zero eigenvalue and the Y coordinate to the One eigenvalue, while the task is to output 1 if x>y and 0 otherwise.
The solution is just to apply an X flip, or equivalently a Y rotation of Pi.
The number of qubits is always the logarithm of first power of two greater than the number of features (dimensions), or equivalently the ceiling of the logarithm of the number of features.
In our 2D case, that is 1.
The states are assigned as probability amplitudes of a LittleEndian register.
So the first dimension (in this case, the X coordinate) is the probability amplitude of the 0 value, and the second is of the 1 value.
Of course, they are first normalized, as the total probability must be unity.
If you want to avoid that, you may want to preprocess your samples with an additional dimension that takes care of the normalization and is later ignored in the circuit.
With 4D data, each coordinate would correspond to the probability amplitude of one value of the register, 00, 10, 01, 11.
Et cetera for bigger data.
In the cases of tasks D1 and D2, normalization works in our favor since classification only depends on the polar angle of the point, and not on its distance from the origin.
Alright, this is what I wanted to know. But still, are these mentioned in the documentation somewhere?
The documentation is pretty bad, yes.
I think the best explanation is in this tutorial, though it could be better: https://github.com/microsoft/MLADS2020-QuantumClassification
I also had to check out the implementation of the library to understand some things: https://github.com/microsoft/QuantumLibraries/tree/master/MachineLearning/src
Of course, there's the official documentation, but it's pretty bad: https://docs.microsoft.com/en-us/quantum/libraries/machine-learning/
For more theoretical details you may want to check the paper describing the technique: https://arxiv.org/abs/1804.00633
I personally spent more than 8 hours to get everything working...
How can I test my program locally with testcases?(In jypyter notebook) I've done a lot of searching but cannot find a good answer. Hope someone can help, Thanks.
That really depends on the kind of program you need to test. (The main challenge is devising the code, not porting it to Jupyter notebook.)
You can study the testing harnesses in the Quantum Katas to see how they are implemented for a type of problem similar to yours. This will work, for example, for reversible-computing problems (the katas are SolveSATWithGrover, GraphColoring and RippleCarryAdder). For problems A1-A5 the testing harness is the closest to the one used in the Measurements kata.
Superposition tasks, though, are tested by comparing them with the correct solution, so if you don't have a correct solution on hand, you can't take the same approach. In this case I would use DumpMachine to check the amplitudes of the basis states in the state you prepared and compare them with the ones you need.
Microsoft.Quantum.IQSharp.Workspace[0] QS6104: No namespace with the name "Microsoft.Quantum.MachineLearning" exists.
running the host python program just gives this error
It's hard to debug without seeing the code (you can ask a question in contest interface so that only the contest managers will see it). Did you do things like the following to import the package?
Thanks
I trained the model and got a array of parameters and a bias.. so how do i submit it
Are the type of tasks in the practice contest indicative of the type of problems we will have in the main contest? QML is something completely new this time so I guess we can expect it in the main contest as well right?
Yes. The goal of the warmup round is to prepare you to solving the harder problems of the main contest: allow you to set up your environment and make sure it works and figure out how the new types of problems work.
The only thing not in the QML resources is that how are the Controlled Rotations chosen
That's where your creativity comes in, I guess.
Well, in these two particular cases, with a single qubit representing an angle, it's obvious only Y rotations make any sense.
For more general cases, I suggest starting by replicating the examples given in the documentation for general-purpose two- and three-qubit circuit configurations.
If that doesn't yield satisfactory results, you should look for some sort of nice structure in the given data, and design the circuit yourself specifically to exploit that.
how do i encode sample data into multiple qubits.. i understand that only the angle data is preserved in single qubit encoding... how do i also encode distance data
https://codeforces.net/blog/entry/77614?#comment-641653
Is there any way to find out what is causing the runtime error in my submit? Everything works fine locally for me.
Which task?
If it's task B1 or B2, pay attention to the note on the bottom of the task statement.
It is task B, but I am only using the allowed gates.
Make sure that any additional qubits used are left with certainty in the zero state.
I reset all additional qubits at the end of the using block. Can it be that I use more time or memory than allowed?
In this type of tasks, you have to uncompute the qubits rather than reset them. Resetting them involves measurement, which collapses superposition in which the inputs can be. Uncomputing, though, returns the qubits to zero state without measuring them, thus preserving superposition on the other qubits.
Trying to run the sample QML code gives the following error (using python): qsharp.clients.iqsharp.IQSharpError: The Q# kernel raised the following errors: /home/geekpradd/Desktop/Q%23/Summer%202020%20Practice/D1/qsharp.qs(2,10): error QS6104: No namespace with the name "Microsoft.Quantum.Convert" exists. /home/geekpradd/Desktop/Q%23/Summer%202020%20Practice/D1/qsharp.qs(3,10): error QS6104: No namespace with the name "Microsoft.Quantum.Intrinsic" exists.
I tried using qsharp.packages.add() to add these namespaces but that didn't work also (aren't these the standard Q# namespaces and so this error shouldn't occur.. It seems adding the Machine Learning Package is causing this) Help would be appreciated.
Most likely it is a version mismatch.. Try downgrading your iqsharp to 0.11.2004.2825 Or first, try changing the library version to whichever you are using in the add packages line.
Thanks a lot. I installed the version of iqsharp that the Jupyter Notebook in the link given was supposed to have and it worked.
I installed the latest version and now can't install the older version.
Tool 'microsoft.quantum.iqsharp' is already installed.
So I tried to
dotnet tool uninstall microsoft.quantum.iqsharp -g
but I'm getting permission errors, saying that access to the path~/.dotnet/tools/.store/microsoft.quantum.iqsharp/0.11.2006.403
is denied.Help, please?
Uninstall the existing version of IQ#: (you might need the
-g
switch here depending on how you do it; and you'll need to make sure you don't have any Q# notebooks running that would use the kernel)dotnet tool uninstall microsoft.quantum.iqsharp
Install the right version:
dotnet tool install microsoft.quantum.iqsharp -g --version 0.11.2004.2825
Reinstall the kernel:
dotnet iqsharp install
That should work.
Thanks! I don't remember if I had any notebooks opened, but after rebooting, with everything else closed, it worked for me. I now have the right version. However,
ExploringQuantumClassificationLibrary.ipynb
still doesn't work for me.InsideQuantumClassifiers.ipynb
does though.Oh, I just checked out the repo from scratch and it worked. Apparently some state about the previous installation gets persisted into the notebook.
Solving at least one problem means like we have to solve all of A, or it means solving atleast one part?
A1 and A2 are different problems, you can think of the letters as groups of problems that are solved in broadly the same way.
removed
I'm assuming discussing solutions for the warmup round is fine — I'm a bit stuck on B1. I decided to just use this function but this gives me RTE. Testing locally I can't really find an issue. Would it be possible to output the error when the verdict is RTE?
It's mentioned that arbitary rotation gates (and that function in particular) cannot be used which is why you are getting RTE. You can implement this operation by using Controlled CNOT gates as mentioned in the question
Or Controlled recursion ;)
We posted a couple of hints for problems A and C as contest announcements. I hope that helps some of you to get them right! And remember, in the warmup round it's ok to ask for hints and help, though I would draw a line at sharing the exact solution code :-)
for the QML problems i understand that only the angle data is preserved and is converted to a single qubit but how do i edit it to encode the data in multiple qubits and also preserve the distance data
In these problems you can't do that, but you also don't need this, since the classes are perfectly distinguishable with just the angle. That's why these problems don't offer you this option.
You'll need to manipulate input data before encoding it in the problems of the main round :-)
In general you need to preprocess your data and calculate new features for it before you pass it to the library. For example, in the HalfMoons example the data is preprocessed before encoding: WithProductKernel function adds an extra feature that is the product of all original features. After that the standard encoding realizes that there are 3 features in the data and those can't fit in a single-qubit state, and automatically uses an extra qubit to encode the features (the missing features are padded with 0s to the nearest power of 2).
Are there any other examples of adding extra features except Half Moons and also are there any other examples of features for a point except angle and distance
You can build examples of adding extra features yourself easily, if you start with HalfMoons and modify the classical logic of feature calculation to compute whatever feature you need. We will share the testing harness for the main contest, so that you can see the typical feature engineering approaches.
Angle and distance are not quite the chosen features of a point, but rather angle is the effective feature that results from encoding two features x1 and x2 into the amplitudes of the basis states |0⟩ and |1⟩: the amplitudes have to be normalized, so they become x1/sqrt(x1^2+x2^2) and x2/sqrt(x1^2+x2^2), which preserves only the angle of the original point. If you have more features, they'll be normalized by dividing them by a square root of the sum of their squares.
How good of a idea it is to set tolerance to 0.00 to try to keep misses as low as possible
I can't get the HalfMoons example to below 10% error rate, and the best model I could get is one that ignores the second qubit and simply says that the upper half is 0 and the bottom half is 1 (or maybe the opposite, I don't remember and can't check right now).
It would really help if there was an example of successfully using an extra feature to avoid losing information by normalization.
I am trying a way which encodes distance as third feature... it is still training I will let you know the results after training Edit: the best i could do was 15 misses which is around 90% accurate
Can you elaborate on this a bit? Does it mean a preprocessing function will be submitted as well (then you could do any kind of ML on it), or that a manipulation will be defined in the statement (then you could've just had that in the training data in the first place)?
Maybe this is a little too specific and revealing of the problems but I'm not seeing how a preprocess step makes sense in the competition.
The idea is to offer a pool of the ways you can manipulate your features (some of them parameterized) and to let you choose the function you want and the parameters for it.
This type of problems is still very experimental, but this seems like a reasonable compromise between allowing you to do anything you want (as you point out, it would be a lot easier to classify data classically and return [1,0] for class 0 and [0,1] for class 1) and giving you exactly the features you need to use.
Does this make sense?
Seems reasonable. Thanks for clarifying.
Is the "time limit per test" taken as the time to run in simulated environment or do you somehow calculate what it will take on a quantum computer? Similar question for memory also..
Both time and memory are measured for running the simulation. (So, for example, the more qubits you have allocated, the slower the gates become, though this doesn't have noticeable impact until 20+ qubits — I explored this a bit in this blog post)
Anyone know how to solve Half Moon with 95-100% accuracy... the best i could do was 85-90%
I got the error rate down to 6% with some preprocessing. First I centered everything, then I converted it to polar coordinates, and then added some ad-hoc fixes for the argument wrap-around. After preprocessing, the training data looks like this:
which is a lot easier to work with.
I got the error rate down to 3%...
[3.16204833984375,1.89954833984375,12.87579833984375,0.005798339843750039,-17.62857666015625,-3.89232666015625,11.0446875,9.2503125,-1.2625,0,-15.5603125,2.840625,16.335], 0.19120000000000006 with 5 misses
could you help to make a structure for 4 parameters which maybe will get 0% error
Your parameters mean nothing to me without your structure and your preprocessing...
Also, the validation data has only 15 points so you can't have 3% error rate with 5 misses, did you run the validation on the training data or did you make your own data?
Also remember that just adding more parameters won't necessarily help. Machine learning is in its essence linear algebra, if there's no linear algebraic relation that can classify the data you MUST apply some non-linear preprocessing, and it can't be just any random processing like the addition of the product that they did, it must transform the data into a form that is easy to classify using quantum gates.
I got 0% error with a single feature! (+1 pseudo-feature to avoid them all getting normalized to 1)
As you can see on my image above, the two clusters look like linear functions with the same slope, 2. The single feature I used is the y-intercept of the line with slope 2 passing through the point, and then I added sqrt(1-x^2) as another feature to avoid normalization.
For my classification circuit I used a single Y rotation, as it usually is done with a single qubit.
It was amazing, usually training takes a few minutes but here it got under the specified tolerance in only a few epochs and short-circuited as it got the perfect solution easily, beautiful.
Another method that produced 0% error is treating the y-intercept as an angle, scaling it so that the total range is pi, and supplying the sine and cosine as features.
The preprocessed data looks almost the same in both cases because x and sin(x) act similarly near zero.
Were you also able to do similar preprocessing for D1 to make the data linearly separable?
D1 and D2 don't need any preprocessing, in fact the format for submitting the solution doesn't allow preprocessing in the first place.
I tried using the same model as half-moons but the accuracy is pretty bad. Should I try experimenting with the structure?
Yes, you should change the structure.
The model from https://github.com/microsoft/MLADS2020-QuantumClassification works wonderfully, and indeed it is the only model that makes sense for data in a single qubit.
Will try. Thanks!
This worked surprisingly well. I'm curious why, Is there any intuition as to why a single PauliY gate works while multiple PauliX/Z gates don't? I'm unable to visualise how the transformation takes place by looking at the data plot.
Well the PauliY rotation gate is straightforwardly just a rotation between 0 and 1, while the others include some sort of phase shift that doesn't really interest us in the single qubit case but could be useful with multiple qubits.
Hey can You tell me how did you actually preprocessed the data? Particularly centered everything around origin?
Centering around the origin was the easiest part, I just eyeballed the center of the spirals to be around (0.25, 0.5) or something, don't remember exactly, and subtracted that from the points.
Then I converted the points to polar coordinates, but since angles wrap around at 2 pi they didn't look like the straight lines in the plot. To fix that I just ad-hoc'd it, saying "if it's in the bottom right corner add 2pi, if it's in the top left corner subtract 2pi" and that gave me those nice lines.
At this point the data set is linearly separable so you could probably feed it into a 2-qubit machine learning circuit and it could figure it out on its own, but I went even further:
I eyeballed the slope of the lines to be about 2, calculated the y-intercept of the line with slope 2 that each point belongs to, encoded that as the angle of the single input point, and from there getting a circuit that classifies them was trivial.
After working with the QML API in the warmup round and looking at the implementation a bit, I thought maybe I should make my own learner. Sampling probabilities and no backpropagation is just too damn slow. Hennkka had the same idea independently and we worked on it together last week. (Before the contest of course!) The project is on GitHub.
With that I was able to get perfect or near perfect classifications on halfmoons:
IIRC it was a bit better if the data was centered first, but there's no cheaty preprocessing here. Features in the above model are encoded into two qubits as
The major change is that we changed the cost function to a higher power instead of mean-squares. It helped lessen the misses, but of course in proper ML that doesn't make too much sense. (no separate training and testing datasets to verify it helps, generalization is far more important than absolute misses, etc). But it did work pretty well with the strictly defined areas that the contest tasks had.
With it the QML tasks of the contest were a breeze (except for the qubit endianness being wrong). Kinda defeats the purpose, but hey, I had never made a gradient descent learner before. I also found a couple flaws in Microsoft's implementation of things, I'll leave issues there at some point.
So I was doing the winter round problems and they involve using Most function on qubits before applying the ApplyForEach function in the Unitary Transformation Problems. But running on my system gives that Most is not defined. What's going wrong?
i think that you need to open Microsoft.Quantum.Arrays to use most
you need to import the proper package, some things were moved around since the last contest https://docs.microsoft.com/en-us/qsharp/api/
In B why we cannot use an extra qubit. Because if I use and use Reset to reset it there is compilation error.
You're not allowed to use measurements.
Reset is a measurement.
I recommend that you solve the previous two warmups first, you can read their editorials for help.
Struggling to understand quantum controlling.
MultiQubitGates tutorial:
Quantum reality:
results in 50% 0 or 1, while without the CNOT, results in 100% 0.
Quantum operations don't commute, two Hs can't annihilate across the CNOT.
Also, that tutorial is telling you lies, all gates affect all qubits.
the tutorial means to say that a control qubit should not be also used as a target qubit
I see, that would make sense, but it's a bad way to express it.
It's a somewhat tricky idea to express: if you're using controlled gates on the basis states, the state of controls doesn't change; this is what allows to uncompute the changes done to the control qubits. But if you use them on the states with control qubits in superposition, there is going to be all kinds of interesting behaviors, including the one you mentioned.
Thank you for pointing this out, I'll need to think how to express this better...
I'm also misunderstanding this concept and it's causing my solution to task 2.2 from the Measurements Katas (man, the difficulty really ramps up at this stage ... ) to not work.
Any explanation from Nickolas or someone else would be appreciated (I'm afraid I don't understand your comment).
Could you please clarify what explanation you'd like? Task 2.2 from the Measurements kata doesn't actually use controlled gates :-)
I think I understand this better now ... I got the following advice from Monogon on discord:
And in this case, in your example hellman_ we are first applying $$$H \otimes I$$$ to the system, then CNOT, then $$$H \otimes I$$$ again. We get that the system is in the state
$$$\frac12 \left( |00\rangle + |01\rangle + |10\rangle - |11\rangle \right)$$$
which explains why we get the 50% 0, 50% 1 behaviour.
I think a note word of warning in the katas would be super helpful for this, since in my opinion the Q# syntax is hiding the fact that
H(a)
is actually $$$H \otimes I$$$, not just $$$H$$$ applied to an isolated qubit (there are no isolated qubits, due to entanglement).I would just like to add that the classical descriptions of the gates are helpful, but you should try your best not to rely on them too heavily. Entanglement defies intuition.
One way to somewhat regain the intuition is (correct me if I'm wrong) that if you think of the CNOT as "measuring" the superposed bit (but not revealing it to us, so the superposed/entangled bit still has the same relative probabilities), the resulting probability amplitudes would end up the same. That's why placing an H gate after it will still generate a 50-50 chance, unlike what happens when two H gates are placed in a row.
This is the fundamental "measurement problem" of quantum mechanics. There doesn't seem to be a fundamental difference physically between "if this qubit is $$$|1\rangle$$$, flip the other qubit", and "if this qubit is $$$|1\rangle$$$, display "1" on the computer screen", except that the latter entangles the state of a nano-physical object with a macro-physical object. However, once we look at the computer screen, we don't observe the superposition or entanglements anymore, but it instead appears to "collapse" into a single coherent "classical" reality. Interpretations of this phenomenon is where hard physical science ends and philosophy begins, and takes many forms.
Indeed, it may be that measurement/collapse is an inherently subjectivist/relativist concept, since even though from our perspective we may consider the computer superposed/entangled until we look at it, for the purposes of quantum computing, collapse happens at the
M()
command, since once we entangle qubits with classical bits, we obviously can't manipulate the latter with quantum computing operations anymore. This is what is called quantum decoherence; once information from the quantum system "leaks" into the surrounding environment, from one interpretation/perspective, collapse has occurred, from another interpretation/perspective, the system is entangled with the state of the environment, but either way, the superpositions no longer work as before within the quantum system. Making sure this doesn't happen non-deliberately is one of the chief challenges of building a real quantum computing system.Okay so this made me feel like https://codeforces.net/blog/entry/77614?#comment-626409 ... except it was you Spheniscine who posted that to begin with!
Would anyone know how to get the Kronecker product of 2 gates? I can't seem to find details in the documentation.
Just apply them to different qubits one after another.
This post may contain some spoilers for B1 and/or B2.
I had some trouble solving B1/B2. I couldn't think of an easy linear approach, so eventually I settled on the "quadratic" approach, where I use O(N) controlled X gates with O(N) controls each. Because I used a variable-sized set of controls, the compiler wouldn't automatically generate an adjoint for me, and I had to write it myself. Of course, I had to do this anyway, because it's the other of the two problems, but it seems against the intent of the problem, since it specifically advises you that the adjoint will be automatically generated.
After using this solution (it gets AC) I googled for a better approach. The only things I found seemed very complex, and not the sort of thing I would come up with in a contest setting. (More difficult than any of the other Q# problems on this site I've tackled.)
Is my approach correct/intended? Is there an easier approach I missed? Is the correct solution just very difficult to come up with from scratch?
The simplest possible solution is using Controlled recursion, you can do it in 2 lines of code and the compiler can generate an Adjoint automatically without problem.
Interesting. I hadn't considered recursion in Q#. I'll take a look at your submission to the problem when the contest ends.
There is a rather simple approach using O(N) CCNOT,CNOT gates and N ancilla qubits. Just note that your controls are very structured.
Ah, right, I failed to mention this in my post but that's another approach I had considered. Since simulating N additional qubits incurs a factor 2^N (ish) overhead to fully simulate (or does it?) I was worried that it would likely cause my code to timeout.
In gemeral, for a full state simulation additional qubits indeed increase the memory used by the program and the time to simulate each gate, but the effects are not going to be particularly noticeable until ~20 qubits (I timed larger programs in this blog post).
In this contest in B problems we (actually msoeken :-)) used a variation of Toffoli simulator that takes linear memory to process extra qubits but do not support arbitrary rotations. So simulating extra N qubits shouldn't push your solution above the time limit, though I'll admit I haven't tried that.
Your approach is correct and intended, but it can be implemented a lot easier. The compiler couldn't generate an adjoint automatically only because you used a mutable variable to store your control qubits, which is not really necessary. If instead you express the controls in terms of index i and a subarray of reg (array slicing is very useful for this), the code becomes something like 3 lines — and no manual Adjoint definition.
Ah, thanks, this is good to know. I often run into more problems with the non-quantum part of Q# than the actual QC knowledge.
That is understandable, as I can only imagine that the Q# compiler is very weird and different from normal compilers. I remember that 2 years ago for the first contest, the language was even weirder and harder to understand, and the compiler had lots of bugs like not parsing doubles correctly. I had to write 2.5 as 25. / 10., those were fun times.
Apparently
ApplyToEach
can't be used withinAdj+Ctl
unitary functions, but regularfor
-loops can.ApplyToEachCA
dotnet run
for an empty program takes 16 seconds on my machine. Is that expected? Is there a way to make it go faster?Are there plans for continuing this competition in 2021?
We're not even done with the warmup round 2020 yet :-)
how will we preprocess data in the main round because we just submit the parameters and the structure
https://codeforces.net/blog/entry/77614?#comment-642147
could you give the list of functions for practice
Any QML questions for practice... I finished D1,D2 and the half moons with 100% acuracy
There are two datasets (Wine and Iris) in the MachineLearning package and there is a sample for training on Wine.
The Wine example takes several hours to train...
Can you please give me some insight on how you got Half Moon to reach so high? I am unable to get even a mildly satisfactory result. Also, does the default set of programs (official sample for HalfMooon) take forever to run for you?
vilim_l helped preprocess the data in to linearly seprable classes. see comment above if you need more help just drop a message to me
Preprocessing data in Q# seems like a lot of work. Would it not be better to preprocesss it in the host program? This way, you could ask us to submit one Python/C# program that contains a function with some signature to return the data that would go into the model as defined by the Q# code, like in the examples now.
This approach would convert this competition into "do the training classically and encode the labels in the output data", which would defeat the purpose of exploring quantum machine learning capabilities :-)
Oh right, didn't see that loophole there. xD
Isn't it like it now? I "trained" the circuit basically by hand..
For the case of a single qubit, the only possible way to do anything is "classically encode your feature as an angle and then let the QML algorithm find the boundary between the angles of each label with a single Y rotation", but with higher-dimensional datasets it should be possible to do something interesting. Hopefully.
I am facing this problem after installation. Any solution? I tried installing 2-3 times ~~~~~ Preparing Q# environment... fail: Microsoft.Quantum.IQSharp.Workspace[0] QS6104: No namespace with the name "Microsoft.Quantum.MachineLearning" exists. fail: Microsoft.Quantum.IQSharp.Workspace[0] QS6005: No type with the name "ControlledRotation" exists in any of the open namespaces. fail: Microsoft.Quantum.IQSharp.Workspace[0] QS6005: No type with the name "SamplingSchedule" exists in any of the open namespaces. ~~~~~
You need to check that the correct version of the ML library is imported. If you installed or updated your QDK in the past few days, it should be 0.11.2006.403, but the examples by default import 0.11.2004.2825.
I'm trying to test my code for A1 locally using Jupyter Notebooks but I can't seem to run the Solve() function. It gives me the error
Got an argument of type Qubit, expecting one of type (Qubit => Unit is Adj + Ctl) instead.
.What is type
(Qubit => Unit is Adj + Ctl)
? As far as I understood, it is a callable that supports both controlled and adjoint. Can I do something likeSolve(X(q))
orSolve(X)
?Qubit => Unit
means a function that takes aQubit
as argument and returnsUnit
(essentially avoid
function, if you're used to C/C++/Java). The signature suggests that it operates on qubits, and the "output" is given by the state in which it leaves the qubit. TheAdj + Ctl
means that the operation has an adjoint and a controlled version available, which is true of (for instance)X
. So indeedSolve(X);
is a correct line of code ifSolve
has the signature you describe.Thanks for explaining what it means.
But when I run the following code for example,
I get
C:/snippet_.qs(7,5): error QS5011: Expecting expression of type Unit. Only expressions of type Unit can be used as expression statements.
Solve
returns a value, and you need to somehow use it — assign to a variable or print in aMessage
.This post contains spoilers for D1.
I'm stuck on getting the machine learning problems to work. From the correct submissions (and the comments on this post, before that) I realize the correct solution to D1 is to have a single PauliY gate, controlled on nothing, with a parameter of pi (and possibly some bias).
If I try to run the example code from this website (in particular with the Python host file), and the only change I make is that I split the json file into training and validation data (because the code assumes that the json file contains both) then after running for a long time it just... reports the initial parameters it started with, with a gigantic miss rate (near 50%).
If I change the
ClassifierStructure
function into the following:and I hardcode the correct value for the rotation in the Python file:
it runs much quicker, but it does not change the parameter at all, yet it reports, again, a nearly 50% miss rate.
Additionally, sometimes when I run host.py I get a whole bunch of errors of the form
fail: Microsoft.Quantum.IQSharp.Workspace[0] QS5022: No identifier with the name "ControlledRotation" exists.
But whether or not I get these errors seems somewhat non-deterministic: it doesn't happen every time.
What is going on?
I haven't tried running this data with the website code; if you run it with the code from https://github.com/microsoft/MLADS2020-QuantumClassification, which is what I did, it will learn. To improve the learning speed and push the model away from the starting parameters, I had to increase LearningRate parameter and reduce Tolerance (https://github.com/microsoft/MLADS2020-QuantumClassification/blob/master/QuantumClassification/Backend.qs#L44).
Ah, thank you. That seems to have worked. That gives me some confidence in the contest next weekend.
It is similar to classical ML — you have to experiment with model structure and hyperparameters to figure out what works best for the exact problem you're solving.
Sure, but if I were programming in PyTorch and my parameters weren't updating I would know how to get the gradient I am using for the update and print some statistics (max, min, mean, variance) to see if the hyperparameters are the problem or there is just a bug in my code (or something wrong with my installation of the backend). Q# is still a little arcane to me.
How do I find out what hyperparameters are available to me, and what they mean (i.e. what their definition is)? It is not meaningfully specified here or here.
There is an issue with the docs generation pipeline which causes user-defined types lose most of their documentation :-( You can find the comments in the source here.
Thanks!
Is Q# compilation supposed to be very slow?
I run it as in this tutorial by creating a project in VS Code and running "dotnet run" in the console. It takes about 15 seconds to compile a basic program.
Question about allowed operations
Problem 'C' (of Warmup) states:
so I expected I am allowed to use X, Y, Z, H, CX=CNOT, CY, CZ, CH, but not anything else, most importantly, CCNOT, which I thought I need to implement myself. Meanwhile, the solution with CCNOT worked: https://codeforces.net/contest/1356/submission/83551196
Can you please clarify if this is a mistake of testing or if I misunderstand something?
CCNOT is a controlled version of X — just with several controls. So you can do CCCNOT etc. I'll clarify this for the main round, thank you for pointing this out!
Thanks for clarification! I thought implementing CCNOT from 1-2 qubit operations was part of the challenge. Now I see people use CCNOT or even 'Controlled' keywork.
I took a look at last year's solutions to see what exactly was banned for this year (preparing state directly with Ry, without any measurements or loops).
So last year's Winter problems have used ancilla qubits in implementing oracles. However as was mentioned previously we cannot use Reset/ResetAll in operations that need to be auto adjoint. So the solutions don't reset at all and it works. Why is this so? Does the Q# compiler auto reset them? (It seems that one needs to Reset using adjoint self. I still find it weird though. Also the solutions haven't used reset but the same code on my pc requires me to reset. Weird)
I am not sure I understand your question, but the testing code allocates the qubits for you, passes this qubits as parameters to your code and at the end resets the allocated qubits.
But if you allocate qubits yourself (for testing or for some problems) then your need to reset those specific qubits.
There are two ways to return the qubits to 0 state after you're done with them.
Reset
is a shorthand for "measure, and if measurement result is 1, apply an X gate" — this way collapses superposition, if the qubit was not in a basis state |0⟩ or |1⟩. This is good if the qubit is not entangled with the other qubits and you don't care what happens to it. For example, if you used an extra qubit in the |-⟩ state to implement phase kickback trick, it's not going to be entangled with the rest of your qubits, and you can just measure it — that measurement will not affect the rest of the system.But quite often your ancilla qubits will be entangled with the rest of the system, and then you cannot measure them, because this will collapse not just the state of the ancilla, but also the state of the rest of the system. Here is the simplest example: if you have the main qubit and the ancilla qubit in a state (|00⟩ + |11⟩), and you wanted to prepare the main qubit in the |0⟩+|1⟩ state, you cannot just measure the ancilla to get rid of it, since that will collapse the full system to |00⟩ or |11⟩, affecting the state of the main qubit as well. In this case you need to return the extra qubits to |0⟩ state coherently, using uncomputation — and that's what you'll want to do when implementing oracles.
I think I now get why the language forces you to manually reset qubits with runtime exceptions. Just to be sure: is my understanding correct that there will be no runtime checks on real quantum hardware? (since there is no way to check it without doing measurements and collapsing states) It will just give you weird results.
Yes, on real quantum hardware the runtime software won't be able to track the full state of the system, so you're on your own :-)
That's part of the reason why we want to enforce this on the simulator — if you're writing your code for hardware, you'll be better off troubleshooting this kind of issues on small instances of the problem in simulation before you run it on hardware and spend a lot of time figuring out why your results don't make sense :-)
How do you implement -Z operation from A5? (for testing)
I used:
It seems like there should be some build-in gate to do negation directly, but I couldn't find any.
You can do a gate which applies a global phase using R gate with PauliI argument. But for the global phase of -1 XZXZ might be the more intuitive way.
Thanks. Thought, there would be something simple like 'Negate', although not sure if it's used often.
How do you test your code?
I create operations for testing and comment out the line with @EntryPoint() just before submitting the solution. Sample solution. I see many participants don't have any testing code in their submissions.
How do they test then?
I write my code in a jupyter notebook, with testing code next to it. Once I want to submit I copy the code to a new text file and submit that. This workflow is terrible and I wouldn't recommend it to anyone. :^)
I like Jupyter Notebooks for Python ML work. I didn't know there is an extension for Q#.
How does it work? Code completion is probably very bad (it's bad even for Python).
Is it fast? Basic scripts take 15 seconds to compile with 'dotnet run' and I am not sure it is supposed to take that long.
In my current solutions file, these are the first three cells:
Running all three of these cells takes about 3 seconds.
To hand in the code, I copy the content of the first cell into a text file, add the correct namespace, and change the name from
SolveA1
toSolve
.I create an additional operation called
test
, and then call it using python. No need for commenting.To use this method you need to install the dependencies listed here: https://docs.microsoft.com/en-us/quantum/install-guide/pyinstall
Sample solution: 83561027
Sample python script:
I'll check Python host. Is it fast? Basic scripts take 15 seconds to compile with 'dotnet run' and I am not sure it is supposed to take that long.
You have a cool minimalistic solution for problem 'C' by the way:)
For me it takes 9 seconds if I need to build the file and 3 seconds otherwise. My computer has 8 2.3GHz i9 cores.
And I'm glad you liked my solution to C.
Could this be a reason for a runtime error?
Controlled X([Qi], Qj)
//some more statements
and then doing
Controlled X([Qj], Qi)
No
Yes, actually. If this is in a task, where the qubits have to be reset to the zero state, then this probably won't put them in a zero state. I would need to see the task and the rest of the code for more information. Maybe doing
Controlled X([Qi], Qj)
in the end instead would solve the error.The code is for task B1 increment https://codeforces.net/contest/1356/submission/83904158 I used N extra qubits to store whether a carry needs to be added or not, but I get a runtime error, I am unsure what caused it but I believe using a
CNOT
with controls and targets switched/overlapped after an earlierCNOT
caused it.I think you got the right intuition. I can see two reasons for why the ancillas are not uncomputed/reset properly: 1. The state of
register
is different in the end, so you apply different operations to the ancillas. 2. You need to do the uncomputations in REVERSE order. Sofor (i in (l - 2) .. -1 .. 0)
etc.But you can also solve the problem without ancillas, and I see you also have also submitted such a solution.
in general it would'nt matter as long as he didnt change state of either qubit
is anyone able to solve wine dataset?? the best i could do was 22 misses on the training data
Don't test on training data, you'll overfit and get a low miss rate but your model will be bad.
Out of the box, the default implementation gets to 4 misses on the validation data, and I got it down to 2 with the same kind of precomputation as with HalfMoons (the second half, skipping the cartesian-to-polar conversion) and a single Y rotation.
That seems to be the limit, since after I removed that one dimension from the data all that was left was random noise and both the data labeled 1 and the data labeled 0 had the exact same averages to 18 decimal digits.
I managed G1 and G2 from the winter 2019 warmup, but in trying G3 I keep getting compilation errors related to
Deprecated syntax. Use "is Adj" to denote the operation characteristics instead.
.This might have something to do with trying to create 8 qubits as follows:
using(qs = Qubit[8]) { // things... }
Any help?
instead of the body(...) {} adjoint = auto syntax, use "is Adj", as stated in the error message
But that doesn't follow the signature in the problem statement?
Also I ended up needing to manually reset the bits of
qs
sinceResetAll(qs)
didn't work. I tried usingopen Microsoft.Quantum.Intrinsic;
but that seemed to not work well withopen Microsoft.Quantum.Primitive
... any idea why?Look at which line the error appears.
Also, Intrinsic replaces Primitive, remove the latter.
Also, Intrinsic replaces Primitive, remove the latter.
So this alone would have made what took 30+ submissions take one submission only ... rip
More specifically, Intrinsic and Primitive are both functional as the moment, though Primitive is deprecated, so if you include both there will be two copies of a lot of gates defined, and this ambiguity is what's causing the error.
The signatures in the statements are still on the same syntax as was used at the time of the contest. (I went through all old problems to update the testing harnesses, but didn't realize the code signature in the statements is unchanged until much later.) But this should be a warning, not an error — does it fail compilation? Sorry about that!
I am struggling with the QML classifier parameters, more specifically with my Initial Parameters,
Even when I define the same amount of vectors with the same values I am getting pretty different accuracy rates.
So, what does the number of vectors changes in my computation and how may I define the x_i values in such a way that I will get better results? And what is inside this optimization black-box?
These vectors specify several starting points from which you start training. Each starting point is used independently in a separate training process, and only the best set of parameters across all trained models is returned. Variation in accuracy is caused by the randomized nature of training. Picking starting parameters near the optimal ones will help, but it can be tricky :-)
You can find the insides of optimization black box in the Q# libraries — I believe
Training.qs
is the good starting point. I haven't dug deep into it myself yet, so I can't provide a more educated answer.Hello,
Are 25 random shirt winners already selected for the warmup or not yet ? :)
Thank you.
Not yet, we'll select them after the main round is complete and the top 50 in it are defined.
You can find the list of T-shirt winners for the warmup round here.
Is server error is OK by this link? https://github.com/Microsoft/QuantumKatas
If GitHub is up, this repo should be up too :-)
B1/B2 don't have a constraint on N, but still have a time limit