-
Notifications
You must be signed in to change notification settings - Fork 9
Use qibo as a backend for vegasflow #91
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
scarlehoff
wants to merge
3
commits into
master
Choose a base branch
from
quantum_rng
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,46 @@ | ||
| """ | ||
| Run integration with qibo as the backend | ||
| and compares it to other algorithms | ||
| """ | ||
|
|
||
| from vegasflow.quantum import quantum_wrapper, quantumflow_wrapper | ||
| from vegasflow import float_me, vegas_wrapper, plain_wrapper, run_eager | ||
| import time | ||
| import numpy as np | ||
| import tensorflow as tf | ||
|
|
||
| run_eager(True) | ||
| # MC integration setup | ||
| dim = 2 | ||
| ncalls = int(1e5) | ||
| n_iter = 5 | ||
|
|
||
|
|
||
| def symgauss(xarr): | ||
| """symgauss test function""" | ||
| n_dim = xarr.shape[-1] | ||
| a = float_me(0.1) | ||
| n100 = float_me(100 * n_dim) | ||
| pref = tf.pow(1.0 / a / np.sqrt(np.pi), n_dim) | ||
| coef = tf.reduce_sum(tf.range(n100 + 1)) | ||
| coef += tf.reduce_sum(tf.square((xarr - 1.0 / 2.0) / a), axis=1) | ||
| coef -= (n100 + 1) * n100 / 2.0 | ||
| return pref * tf.exp(-coef) | ||
|
|
||
|
|
||
| def test_me(wrapper, nev): | ||
| nev = int(nev) | ||
| algo = wrapper.__name__.split("_")[0] | ||
| print(f"> Running {algo} for {nev} events") | ||
| start = time.time() | ||
| result = wrapper(symgauss, dim, n_iter, nev) | ||
| end = time.time() | ||
| print(f"This run took {end-start}\n") | ||
| return result | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| test_me(plain_wrapper, ncalls) | ||
| test_me(vegas_wrapper, ncalls) | ||
| test_me(quantum_wrapper, ncalls) | ||
| test_me(quantumflow_wrapper, ncalls) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,77 @@ | ||
| """ | ||
| A Monte Carlo integrator built upon Qibo for quantum integration | ||
| """ | ||
|
|
||
| import tensorflow as tf | ||
|
|
||
| from .configflow import DTYPE, run_eager | ||
| from .monte_carlo import MonteCarloFlow, sampler, wrapper | ||
| from .plain import PlainFlow | ||
| from .vflow import VegasFlow | ||
|
|
||
|
|
||
| class QuantumBase(MonteCarloFlow): | ||
| """ | ||
| This class serves as a basis for the quantum monte carlo integrator. | ||
| At initialization it tries to import qibolab and connect to the quantum device, | ||
| if successful, saves the reference to _quantum_sampler. | ||
|
|
||
| This class is compatible with all ``MonteCarloFlow`` classes, it overrides | ||
| the uniform sampling and uses the quantum device instead. | ||
| """ | ||
|
|
||
| _CAN_RUN_VECTORIAL = False | ||
|
|
||
| def __init__(self, *args, **kwargs): | ||
| # This integrator can only run for now in eager mode and needs qibolab to be installed | ||
| run_eager(True) | ||
|
|
||
| try: | ||
| from qibolab.instruments.qrng import QRNG | ||
| from serial.serialutil import SerialException | ||
| except ModuleNotFoundError as e: | ||
| raise ModuleNotFoundError("You can do pip install vegasflow[quantum]") from e | ||
|
|
||
| qaddress = "/dev/ttyACM0" | ||
| try: | ||
| # Check whether the quantum device is available and we can connect | ||
| qrng = QRNG(address=qaddress) | ||
| qrng.connect() | ||
| qrng.disconnect() | ||
| except SerialException as e: | ||
| raise SerialException(f"No quantum device found at {qaddress}") from e | ||
|
|
||
| print(f"Sucessfuly connected to quantum device in {qaddress}") | ||
|
|
||
| self._quantum_sampler = qrng | ||
| super().__init__(*args, **kwargs) | ||
|
|
||
| def _internal_sampler(self, n_events): | ||
| """Sample ``n_events x n_dim`` numbers from the quantum device | ||
| and cast them to a TF DTYPE to pass down to the MC algorithm""" | ||
| self._quantum_sampler.connect() | ||
| quantum_rnds_raw = self._quantum_sampler.random((n_events, self.n_dim)) | ||
| self._quantum_sampler.disconnect() | ||
| return tf.cast(quantum_rnds_raw, dtype=DTYPE) | ||
|
|
||
|
|
||
| class QuantumIntegrator(PlainFlow, QuantumBase): | ||
| pass | ||
|
|
||
|
|
||
| class QuantumFlow(VegasFlow, QuantumBase): | ||
| pass | ||
|
|
||
|
|
||
| def quantum_wrapper(*args, **kwargs): | ||
| """Wrapper around QuantumIntegrator""" | ||
| return wrapper(QuantumIntegrator, *args, **kwargs) | ||
|
|
||
|
|
||
| def quantumflow_wrapper(*args, **kwargs): | ||
| return wrapper(QuantumFlow, *args, **kwargs) | ||
|
|
||
|
|
||
| def quantum_sampler(*args, **kwargs): | ||
| """Wrapper sampler around QuantumIntegrator""" | ||
| return sampler(QuantumIntegrator, *args, **kwargs) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Instead of connecting and disconnecting every time, why don't you keep the connection in the object? (and just disconnect on delete)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I'm not claiming that is going to be the main performance bottleneck - but it's certainly some overhead (if it can be avoided).
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Because while I was testing I got several times an error along the lines of "someone else is using the device" which I thought maybe it was @stravos11 testing so I thought it was better to close it asap to avoid making his stuff error out in the same way.
(indeed, in the first commit I do as you suggest)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It was not me, so it is either a different kind of error that we would need to address if it appears often, or someone else tried to use at the same time, but I don't think anyone other than us and @scarrazza would. Personally, I have another qrng that I connect directly to my computer for debugging so I avoid using the one in the qrccluster.
Also, I don't think
connect()anddisconnect()will have any effect on others. Based on a quick experiment I did, if someone else tries to access numbers while you are sampling, your connection will automatically drop (with an error) and their job will start. So basically the last one always wins. Also, I thinkconnect()anddisconnect()have no effect on the qrng device itself, they just create/destroy theSerialobject in your Python runtime.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
ok, then I'll redo what I was doing before and paste the error. By disconecting inmediately after use like now i didn't see the error
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yes, I actually thought that could be the case, but I was unsure about the setup. It may be that you're actually trying reconnecting multiple times somehow (e.g., instantiating the object multiple times).
In case you still experience the error, would you post it?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@stavros11 while on the device it may have no effect (not so expert in serial interfaces...), for sure it has an effect on the OS, since it has at least to open a file descriptor for the communication. Then, this will be handled by the given fs, and potentially boil down to a tiny and likely negligible operation.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I ran a long test yesterday evening and didn't experience the error again. I think I might have really clashed with you or someone else who tried to use it?
In any case, I can "force" the error by just login in twice to the node and running the same script in both, one of them will error out with:
(the crash happened in the one that ran second fwiw)