Git Product home page Git Product logo

quantum's Introduction

TensorFlow Quantum


TensorFlow Quantum (TFQ) is a Python framework for hybrid quantum-classical machine learning that is primarily focused on modeling quantum data. TFQ is an application framework developed to allow quantum algorithms researchers and machine learning applications researchers to explore computing workflows that leverage Google’s quantum computing offerings, all from within TensorFlow.

Motivation

Quantum computing at Google has hit an exciting milestone with the achievement of Quantum Supremacy. In the wake of this demonstration, Google is now turning its attention to developing and implementing new algorithms to run on its Quantum Computer that have real world applications.

To provide users with the tools they need to program and simulate a quantum computer, Google is working on Cirq. Cirq is designed for quantum computing researchers who are interested in running and designing algorithms that leverage existing (imperfect) quantum computers.

TensorFlow Quantum provides users with the tools they need to interleave quantum algorithms and logic designed in Cirq with the powerful and performant ML tools from TensorFlow. With this connection we hope to unlock new and exciting paths for Quantum Computing research that would not have otherwise been possible.

Installation

See the installation instructions.

Examples

All of our examples can be found here in the form of Python notebook tutorials

Report issues

Report bugs or feature requests using the TensorFlow Quantum issue tracker.

We also have a Stack Overflow tag for more general TFQ related discussions.

In the meantime check out the install instructions to get the experimental code running!

Contributing

We are eager to collaborate with you! TensorFlow Quantum is still a very young code base, if you have ideas for features that you would like added feel free to check out our Contributor Guidelines to get started.

References

If you use TensorFlow Quantum in your research, please cite:

TensorFlow Quantum: A Software Framework for Quantum Machine Learning arXiv:2003.02989, 2020.

quantum's People

Contributors

abhinavsp0730 avatar balopat avatar bankde avatar brettkoonce avatar cynocracy avatar dependabot[bot] avatar jaeyoo avatar kristenrq avatar lamberta avatar lockwo avatar markdaoust avatar michaelbroughton avatar peterse avatar prantik-pdeb avatar prashanth-up avatar qu-tan-um avatar quantumjaeyoo avatar ryanhill1 avatar shuxiangcao avatar sinestro38 avatar sjerbi avatar therooler avatar tiancheng2000 avatar tonybruguier avatar vinitx avatar we-taper avatar yashk2810 avatar yifeif avatar yuanoook avatar zaqqwerty avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

quantum's Issues

NotFoundError: _tfq_simulate_ops.so

Upon fresh installation of tensorflow quantum in a conda environment, importing tensorfloq_quantum gives:

NotFoundError: XXXXXX/miniconda3/envs/tensorflow_quantum/lib/python3.6/site-packages/tensorflow_quantum/core/ops/_tfq_simulate_ops.so: undefined symbol: _ZN10tensorflow12OpDefBuilder5InputESs

In more detail:

---------------------------------------------------------------------------
NotFoundError                             Traceback (most recent call last)
~/miniconda3/envs/tensorflow_quantum/lib/python3.6/site-packages/tensorflow_quantum/core/ops/load_module.py in load_module(name)
     41         path = resource_loader.get_path_to_datafile(name)
---> 42         return load_library.load_op_library(path)
     43     except:

~/miniconda3/envs/tensorflow_quantum/lib/python3.6/site-packages/tensorflow_core/python/framework/load_library.py in load_op_library(library_filename)
     56   """
---> 57   lib_handle = py_tf.TF_LoadLibrary(library_filename)
     58   try:

NotFoundError: /home/hx/miniconda3/envs/tensorflow_quantum/lib/python3.6/site-packages/tensorflow_quantum/core/ops/_tfq_simulate_ops.so: undefined symbol: _ZN10tensorflow12OpDefBuilder5InputESs

During handling of the above exception, another exception occurred:

NotFoundError                             Traceback (most recent call last)
<ipython-input-3-def8eb400eeb> in <module>
      1 import tensorflow as tf
----> 2 import tensorflow_quantum as tfq
      3 
      4 import cirq
      5 import sympy

~/miniconda3/envs/tensorflow_quantum/lib/python3.6/site-packages/tensorflow_quantum/__init__.py in <module>
     16 
     17 # Import basic ops and op getters.
---> 18 from tensorflow_quantum.core import (append_circuit, get_expectation_op,
     19                                      get_sampled_expectation_op,
     20                                      get_sampling_op, get_state_op,

~/miniconda3/envs/tensorflow_quantum/lib/python3.6/site-packages/tensorflow_quantum/core/__init__.py in <module>
     15 """Imports to tensorflow_quantum.core.* level."""
     16 # Import getters for constructing ops.
---> 17 from tensorflow_quantum.core.ops import (get_expectation_op,
     18                                          get_sampled_expectation_op,
     19                                          get_sampling_op, get_state_op)

~/miniconda3/envs/tensorflow_quantum/lib/python3.6/site-packages/tensorflow_quantum/core/ops/__init__.py in <module>
     16 
     17 # Import getters for constructing ops.
---> 18 from tensorflow_quantum.core.ops.circuit_execution_ops import (
     19     get_expectation_op, get_sampled_expectation_op, get_sampling_op,
     20     get_state_op)

~/miniconda3/envs/tensorflow_quantum/lib/python3.6/site-packages/tensorflow_quantum/core/ops/circuit_execution_ops.py in <module>
     17 
     18 import cirq
---> 19 from tensorflow_quantum.core.ops import (cirq_ops, tfq_simulate_ops,
     20                                          tfq_utility_ops)
     21 

~/miniconda3/envs/tensorflow_quantum/lib/python3.6/site-packages/tensorflow_quantum/core/ops/tfq_simulate_ops.py in <module>
     17 from tensorflow_quantum.core.ops.load_module import load_module
     18 
---> 19 SIM_OP_MODULE = load_module("_tfq_simulate_ops.so")
     20 
     21 

~/miniconda3/envs/tensorflow_quantum/lib/python3.6/site-packages/tensorflow_quantum/core/ops/load_module.py in load_module(name)
     44         path = os.path.join(get_python_lib(), "tensorflow_quantum/core/ops",
     45                             name)
---> 46         return load_library.load_op_library(path)

~/miniconda3/envs/tensorflow_quantum/lib/python3.6/site-packages/tensorflow_core/python/framework/load_library.py in load_op_library(library_filename)
     55     RuntimeError: when unable to load the library or get the python wrappers.
     56   """
---> 57   lib_handle = py_tf.TF_LoadLibrary(library_filename)
     58   try:
     59     wrappers = py_tf.GetPythonWrappers(py_tf.TF_GetOpList(lib_handle))

NotFoundError: XXXXXX/miniconda3/envs/tensorflow_quantum/lib/python3.6/site-packages/tensorflow_quantum/core/ops/_tfq_simulate_ops.so: undefined symbol: _ZN10tensorflow12OpDefBuilder5InputESs

Other information:

$ python -c "import tensorflow as tf; print(tf.version.GIT_VERSION, tf.version.VERSION)"
unknown 2.1.0

OS: Ubuntu 19.10
Package Versions:

cirq==0.7.0
pathos==0.2.5
tensorflow-quantum==0.2.0
tensorflow==2.1.0

QCNN tutorial error

When I open and run the QCNN tutorial in colab, the runtime currently fails and restarts consistently at the first code cell after the imports. Error log:

Mar 26, 2020, 12:27:00 PM WARNING WARNING:root:kernel 496f68e2-6561-4722-8ef1-fdc4536ba38d restarted
Mar 26, 2020, 12:27:00 PM INFO KernelRestarter: restarting kernel (1/5), keep random ports
Mar 26, 2020, 12:26:58 PM WARNING 2020-03-26 16:26:58.481515: I tensorflow/compiler/xla/service/service.cc:176] StreamExecutor device (0): Host, Default Version
Mar 26, 2020, 12:26:58 PM WARNING 2020-03-26 16:26:58.481456: I tensorflow/compiler/xla/service/service.cc:168] XLA service 0x2717d40 initialized for platform Host (this does not guarantee that XLA will be used). Devices:
Mar 26, 2020, 12:26:58 PM WARNING 2020-03-26 16:26:58.481061: I tensorflow/core/platform/profile_utils/cpu_utils.cc:102] CPU Frequency: 2300000000 Hz
Mar 26, 2020, 12:26:58 PM WARNING 2020-03-26 16:26:58.455068: I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:156] kernel driver does not appear to be running on this host (67c4afeed90b): /proc/driver/nvidia/version does not exist
Mar 26, 2020, 12:26:58 PM WARNING 2020-03-26 16:26:58.453867: E tensorflow/stream_executor/cuda/cuda_driver.cc:313] failed call to cuInit: CUDA_ERROR_NO_DEVICE: no CUDA-capable device is detected
Mar 26, 2020, 12:26:58 PM WARNING 2020-03-26 16:26:58.403912: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcuda.so.1
Mar 26, 2020, 12:26:49 PM WARNING 2020-03-26 16:26:49.467374: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudart.so.10.1
Mar 26, 2020, 12:26:20 PM INFO Adapting to protocol v5.1 for kernel 496f68e2-6561-4722-8ef1-fdc4536ba38d
Mar 26, 2020, 12:26:18 PM INFO Kernel started: 496f68e2-6561-4722-8ef1-fdc4536ba38d
-- -- --
Mar 26, 2020, 12:10:39 PM INFO Use Control-C to stop this server and shut down all kernels (twice to skip confirmation).
Mar 26, 2020, 12:10:39 PM INFO REDACT IP
Mar 26, 2020, 12:10:39 PM INFO The Jupyter Notebook is running at:
Mar 26, 2020, 12:10:39 PM INFO 0 active kernels
Mar 26, 2020, 12:10:39 PM INFO Serving notebooks from local directory: /
Mar 26, 2020, 12:10:39 PM INFO google.colab serverextension initialized.
Mar 26, 2020, 12:10:39 PM INFO Writing notebook server cookie secret to /root/.local/share/jupyter/runtime/notebook_cookie_secret
Mar 26, 2020, 12:10:37 PM WARNING warn("IPython.utils.traitlets has moved to a top-level traitlets package.")
Mar 26, 2020, 12:10:37 PM WARNING /usr/local/lib/python2.7/dist-packages/IPython/utils/traitlets.py:5: UserWarning: IPython.utils.traitlets has moved to a top-level traitlets package.

Demo re-ordering

In our demos we currently setup the learning problems with:

  1. Model
  2. Data
  3. Train

It should probably go:

  1. Data
  2. Model
  3. Train

Fixing this up would mean moving the data definition part up a little bit higher in the Hello World, QCNN and the Sensing Example.

MNIST and already does this and it doesn't really apply for the other demos.

Add custom `get_config` for PQC layers

"This would allow users to call methods like save which can load full models without the original python code that created them. For now we have only save_weights which requires the user to also have the original python code that created the model (not a huge constraint)." @MichaelBroughton

Fix code formatting in docstrings

Comment from @MichaelBroughton
"Right now internal docstring renders screw up some of the code we have. Will need to fiddle with layers and differentiators to get this fixed. This also includes cleaning up the descriptions in the __init__.py modules so taht they describe in more detail what they are as they do get rendered."

Comment from @jaeyoo
"tfdevsite/quantum/api_docs/python/tfq/layers/Expectation

As you can see, some codes have no line space, but others have 1 empty line space between lines. Is it intended? If not, we need to unify them into the one way."

Finish C++ Backend for SampledExpectation

This is a deceptive amount of work. Roughly we will need to do the following things:

  1. Add ability to calculate sampled expectation in qsim and src.
  2. Add a new C++ op that will have the same signature as the python.
  3. Link that C++ op into get_sampled_expectation_op.

No need to modify any other tests or layers since this should just propagate up through the API.

Debugging macros are duplicated: glog vs tf

Here are some of warning message about it

bazel-out/k8-opt/bin/external/local_config_tf/include/tensorflow/core/platform/default/logging.h:444:0: note: this is the location of the previous definition
 #define DCHECK_GT(x, y) _TF_DCHECK_NOP(x, y)
 ^
In file included from ./tensorflow_quantum/core/qsim/simulator.h:21:0,
                 from ./tensorflow_quantum/core/qsim/q_state.h:24,
                 from tensorflow_quantum/core/qsim/q_state.cc:16:
bazel-out/k8-opt/bin/external/com_google_glog/_virtual_includes/glog/glog/logging.h:1089:0: warning: "VLOG" redefined
 #define VLOG(verboselevel) LOG_IF(INFO, VLOG_IS_ON(verboselevel))
 ^
In file included from bazel-out/k8-opt/bin/external/local_config_tf/include/tensorflow/core/platform/logging.h:27:0,
                 from bazel-out/k8-opt/bin/external/local_config_tf/include/tensorflow/core/lib/core/status.h:24,
                 from ./tensorflow_quantum/core/qsim/q_state.h:22,
                 from tensorflow_quantum/core/qsim/q_state.cc:16:
bazel-out/k8-opt/bin/external/local_config_tf/include/tensorflow/core/platform/default/logging.h:131:0: note: this is the location of the previous definition
 #define VLOG(level)     

Let's remove the dependency of glog and use TF's logging.

Convert int to size_t in for-loops

Here are many warning messages such as:

INFO: From Compiling tensorflow_quantum/core/src/program_resolution.cc:
tensorflow_quantum/core/src/program_resolution.cc: In function 'tensorflow::Status tfq::ResolveQubitIds(cirq::google::api::v2::Program*, std::vector<tfq::proto::PauliSum>*)':
tensorflow_quantum/core/src/program_resolution.cc:61:21: warning: comparison of integer expressions of different signedness: 'int' and 'std::vector<std::basic_string<char> >::size_type' {aka 'long unsigned int'} [-Wsign-compare]
   61 |   for (int i = 0; i < ids.size(); i++) {
      |                   ~~^~~~~~~~~~~~
tensorflow_quantum/core/src/program_resolution.cc:77:23: warning: comparison of integer expressions of different signedness: 'int' and 'std::vector<tfq::proto::PauliSum>::size_type' {aka 'long unsigned int'} [-Wsign-compare]
   77 |     for (int i = 0; i < p_sums->size(); i++) {
      |                     ~~^~~~~~~~~~~~~~~~
INFO: From Compiling tensorflow_quantum/core/ops/parse_context.cc:
tensorflow_quantum/core/ops/parse_context.cc: In function 'tensorflow::Status tfq::GetProgramsAndNumQubits(tensorflow::OpKernelContext*, std::vector<cirq::google::api::v2::Program>*, std::vector<int>*, std::vector<std::vector<tfq::proto::PauliSum> >*)':
tensorflow_quantum/core/ops/parse_context.cc:132:21: warning: comparison of integer expressions of different signedness: 'int' and 'std::vector<cirq::google::api::v2::Program>::size_type' {aka 'long unsigned int'} [-Wsign-compare]
  132 |   for (int i = 0; i < programs->size(); i++) {
      |                   ~~^~~~~~~~~~~~~~~~~~
INFO: From Compiling tensorflow_quantum/core/ops/tfq_ps_weights_from_symbols_op.cc:
tensorflow_quantum/core/ops/tfq_ps_weights_from_symbols_op.cc: In member function 'virtual void tfq::TfqPsWeightsFromSymbolOp::Compute(tensorflow::OpKernelContext*)':
tensorflow_quantum/core/ops/tfq_ps_weights_from_symbols_op.cc:127:23: warning: comparison of integer expressions of different signedness: 'int' and 'std::vector<int>::size_type' {aka 'long unsigned int'} [-Wsign-compare]
  127 |     for (int i = 0; i < n_single_symbol.size(); i++) {
      |                     ~~^~~~~~~~~~~~~~~~~~~~~~~~
tensorflow_quantum/core/ops/tfq_ps_weights_from_symbols_op.cc: In lambda function:
tensorflow_quantum/core/ops/tfq_ps_weights_from_symbols_op.cc:147:29: warning: comparison of integer expressions of different signedness: 'int' and 'std::vector<float>::size_type' {aka 'long unsigned int'} [-Wsign-compare]
  147 |           for (int k = 0; k < output_results.at(i).at(j).size(); k++) {
      |                           ~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
INFO: From Compiling tensorflow_quantum/core/ops/tfq_ps_symbol_replace_op.cc:
tensorflow_quantum/core/ops/tfq_ps_symbol_replace_op.cc: In member function 'virtual void tfq::TfqPsSymbolReplaceOp::Compute(tensorflow::OpKernelContext*)':
tensorflow_quantum/core/ops/tfq_ps_symbol_replace_op.cc:136:28: warning: comparison of integer expressions of different signedness: 'size_t' {aka 'long unsigned int'} and 'const int' [-Wsign-compare]
  136 |       for (size_t j = 0; j < n_symbols; j++) {
      |                          ~~^~~~~~~~~~~
tensorflow_quantum/core/ops/tfq_ps_symbol_replace_op.cc: In lambda function:
tensorflow_quantum/core/ops/tfq_ps_symbol_replace_op.cc:160:27: warning: comparison of integer expressions of different signedness: 'int' and 'std::vector<std::basic_string<char> >::size_type' {aka 'long unsigned int'} [-Wsign-compare]
  160 |         for (int j = 0; j < output_programs.at(pidx).at(sidx).size(); j++) {
      |                         ~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
tensorflow_quantum/core/ops/tfq_ps_symbol_replace_op.cc:164:66: warning: comparison of integer expressions of different signedness: 'int' and 'size_t' {aka 'long unsigned int'} [-Wsign-compare]
  164 |         for (int j = output_programs.at(pidx).at(sidx).size(); j < biggest_pad;
      |                                                                ~~^~~~~~~~~~~~~
INFO: From Compiling tensorflow_quantum/core/src/program_resolution.cc:
tensorflow_quantum/core/src/program_resolution.cc: In function 'tensorflow::Status tfq::ResolveQubitIds(cirq::google::api::v2::Program*, std::vector<tfq::proto::PauliSum>*)':
tensorflow_quantum/core/src/program_resolution.cc:61:21: warning: comparison of integer expressions of different signedness: 'int' and 'std::vector<std::basic_string<char> >::size_type' {aka 'long unsigned int'} [-Wsign-compare]
   61 |   for (int i = 0; i < ids.size(); i++) {
      |                   ~~^~~~~~~~~~~~
tensorflow_quantum/core/src/program_resolution.cc:77:23: warning: comparison of integer expressions of different signedness: 'int' and 'std::vector<tfq::proto::PauliSum>::size_type' {aka 'long unsigned int'} [-Wsign-compare]
   77 |     for (int i = 0; i < p_sums->size(); i++) {
      |                     ~~^~~~~~~~~~~~~~~~

Let's use size_t instead of int in C++.

Can't run tfq.layers.PQC with a value for repetitions on windows

Running the code in the docstring for tfq.layers.PQC with a value for repetitions produces an error on windows.
This could be due to the use of multiprocessing in tfq.core.ops.batch_util.batch_calculate_sampled_expectation - Pickle cannot handle module objects to send to different cores. I am unsure of a way that this can be circumvented - it still doesn't work when entering as __main__, see below:

I presume the fix would be to check for windows and do the calculation without multiprocessing.

System: Windows 10
tensorflow==2.1.0
tensorflow_quantum == 0.2.0
cirq == 0.70
python == 3.7.6

Input:

if __name__ == '__main__':
    import cirq
    import tensorflow_quantum as tfq
    import sympy

    q = cirq.GridQubit(0, 0)
    (a, b, c) = sympy.symbols("a b c")
    circuit = cirq.Circuit(
        cirq.rz(a)(q),
        cirq.rx(b)(q),
        cirq.rz(c)(q),
        cirq.rx(-b)(q),
        cirq.rz(-a)(q)
    )
    measurement = [cirq.X(q), cirq.Y(q), cirq.Z(q)]
    outputs = tfq.layers.PQC(circuit, measurement, repetitions=200)
    quantum_data = tfq.convert_to_tensor([
        cirq.Circuit(),
        cirq.Circuit(cirq.X(q))])
    res = outputs(quantum_data)
    print(res)

Output:

2020-03-12 22:56:14.112680: W tensorflow/core/framework/op_kernel.cc:1643] Invalid argument: TypeError: can't pickle module objects
Traceback (most recent call last):

  File "C:\Users\Andrew Patterson\Documents\PhD\envs\tf_quantum\lib\site-packages\tensorflow_core\python\ops\script_ops.py", line 234, in __call__
    return func(device, token, args)

  File "C:\Users\Andrew Patterson\Documents\PhD\envs\tf_quantum\lib\site-packages\tensorflow_core\python\ops\script_ops.py", line 123, in __call__
    ret = self._func(*args)

  File "C:\Users\Andrew Patterson\Documents\PhD\envs\tf_quantum\lib\site-packages\tensorflow_quantum\core\ops\cirq_ops.py", line 340, in cirq_sampled_expectation
    programs, resolvers, sum_inputs, num_samples, simulator)

  File "C:\Users\Andrew Patterson\Documents\PhD\envs\tf_quantum\lib\site-packages\tensorflow_quantum\core\ops\batch_util.py", line 566, in batch_calculate_sampled_expectation
    simulator, None)) as pool:

  File "C:\Users\Andrew Patterson\AppData\Local\Programs\Python\Python37\Lib\multiprocessing\context.py", line 119, in Pool
    context=self.get_context())

  File "C:\Users\Andrew Patterson\AppData\Local\Programs\Python\Python37\Lib\multiprocessing\pool.py", line 176, in __init__
    self._repopulate_pool()

  File "C:\Users\Andrew Patterson\AppData\Local\Programs\Python\Python37\Lib\multiprocessing\pool.py", line 241, in _repopulate_pool
    w.start()

  File "C:\Users\Andrew Patterson\AppData\Local\Programs\Python\Python37\Lib\multiprocessing\process.py", line 112, in start
    self._popen = self._Popen(self)

  File "C:\Users\Andrew Patterson\AppData\Local\Programs\Python\Python37\Lib\multiprocessing\context.py", line 322, in _Popen
    return Popen(process_obj)

  File "C:\Users\Andrew Patterson\AppData\Local\Programs\Python\Python37\Lib\multiprocessing\popen_spawn_win32.py", line 89, in __init__
    reduction.dump(process_obj, to_child)

  File "C:\Users\Andrew Patterson\AppData\Local\Programs\Python\Python37\Lib\multiprocessing\reduction.py", line 60, in dump
    ForkingPickler(file, protocol).dump(obj)

TypeError: can't pickle module objects


Traceback (most recent call last):
  File "C:/Users/Andrew Patterson/Google Drive/PhD/Second Year/Projects/tfq_qVAE/encode_state.py", line 65, in <module>
    res = outputs(quantum_data)
  File "C:\Users\Andrew Patterson\Documents\PhD\envs\tf_quantum\lib\site-packages\tensorflow_core\python\keras\engine\base_layer.py", line 822, in __call__
    outputs = self.call(cast_inputs, *args, **kwargs)
  File "C:\Users\Andrew Patterson\Documents\PhD\envs\tf_quantum\lib\site-packages\tensorflow_quantum\python\layers\high_level\pqc.py", line 286, in call
    repetitions=tiled_up_repetitions)
  File "C:\Users\Andrew Patterson\Documents\PhD\envs\tf_quantum\lib\site-packages\tensorflow_core\python\keras\engine\base_layer.py", line 822, in __call__
    outputs = self.call(cast_inputs, *args, **kwargs)
  File "C:\Users\Andrew Patterson\Documents\PhD\envs\tf_quantum\lib\site-packages\tensorflow_quantum\python\layers\circuit_executors\sampled_expectation.py", line 394, in call
    operators, num_samples)
  File "C:\Users\Andrew Patterson\Documents\PhD\envs\tf_quantum\lib\site-packages\tensorflow_core\python\ops\custom_gradient.py", line 256, in __call__
    return self._d(self._f, a, k)
  File "C:\Users\Andrew Patterson\Documents\PhD\envs\tf_quantum\lib\site-packages\tensorflow_core\python\ops\custom_gradient.py", line 210, in decorated
    return _eager_mode_decorator(wrapped, args, kwargs)
  File "C:\Users\Andrew Patterson\Documents\PhD\envs\tf_quantum\lib\site-packages\tensorflow_core\python\ops\custom_gradient.py", line 406, in _eager_mode_decorator
    result, grad_fn = f(*args, **kwargs)
  File "C:\Users\Andrew Patterson\Documents\PhD\envs\tf_quantum\lib\site-packages\tensorflow_quantum\python\differentiators\differentiator.py", line 142, in op_wrapper_sampled
    num_samples)
  File "C:\Users\Andrew Patterson\Documents\PhD\envs\tf_quantum\lib\site-packages\tensorflow_quantum\core\ops\cirq_ops.py", line 40, in wrapper
    return op_wrapper(*tensorized_args)
  File "C:\Users\Andrew Patterson\Documents\PhD\envs\tf_quantum\lib\site-packages\tensorflow_quantum\core\ops\cirq_ops.py", line 360, in sampled_expectation_generator
    Tout=tf.float32,
  File "C:\Users\Andrew Patterson\Documents\PhD\envs\tf_quantum\lib\site-packages\tensorflow_core\python\ops\script_ops.py", line 428, in eager_py_func
    return _internal_py_func(func=func, inp=inp, Tout=Tout, eager=True, name=name)
  File "C:\Users\Andrew Patterson\Documents\PhD\envs\tf_quantum\lib\site-packages\tensorflow_core\python\ops\script_ops.py", line 317, in _internal_py_func
    name=name)
  File "C:\Users\Andrew Patterson\Documents\PhD\envs\tf_quantum\lib\site-packages\tensorflow_core\python\ops\gen_script_ops.py", line 55, in eager_py_func
    _ops.raise_from_not_ok_status(e, name)
  File "C:\Users\Andrew Patterson\Documents\PhD\envs\tf_quantum\lib\site-packages\tensorflow_core\python\framework\ops.py", line 6606, in raise_from_not_ok_status
    six.raise_from(core._status_to_exception(e.code, message), None)
  File "<string>", line 3, in raise_from
tensorflow.python.framework.errors_impl.InvalidArgumentError: TypeError: can't pickle module objects
Traceback (most recent call last):

  File "C:\Users\Andrew Patterson\Documents\PhD\envs\tf_quantum\lib\site-packages\tensorflow_core\python\ops\script_ops.py", line 234, in __call__
    return func(device, token, args)

  File "C:\Users\Andrew Patterson\Documents\PhD\envs\tf_quantum\lib\site-packages\tensorflow_core\python\ops\script_ops.py", line 123, in __call__
    ret = self._func(*args)

  File "C:\Users\Andrew Patterson\Documents\PhD\envs\tf_quantum\lib\site-packages\tensorflow_quantum\core\ops\cirq_ops.py", line 340, in cirq_sampled_expectation
    programs, resolvers, sum_inputs, num_samples, simulator)

  File "C:\Users\Andrew Patterson\Documents\PhD\envs\tf_quantum\lib\site-packages\tensorflow_quantum\core\ops\batch_util.py", line 566, in batch_calculate_sampled_expectation
    simulator, None)) as pool:

  File "C:\Users\Andrew Patterson\AppData\Local\Programs\Python\Python37\Lib\multiprocessing\context.py", line 119, in Pool
    context=self.get_context())

  File "C:\Users\Andrew Patterson\AppData\Local\Programs\Python\Python37\Lib\multiprocessing\pool.py", line 176, in __init__
    self._repopulate_pool()

  File "C:\Users\Andrew Patterson\AppData\Local\Programs\Python\Python37\Lib\multiprocessing\pool.py", line 241, in _repopulate_pool
    w.start()

  File "C:\Users\Andrew Patterson\AppData\Local\Programs\Python\Python37\Lib\multiprocessing\process.py", line 112, in start
    self._popen = self._Popen(self)

  File "C:\Users\Andrew Patterson\AppData\Local\Programs\Python\Python37\Lib\multiprocessing\context.py", line 322, in _Popen
    return Popen(process_obj)

  File "C:\Users\Andrew Patterson\AppData\Local\Programs\Python\Python37\Lib\multiprocessing\popen_spawn_win32.py", line 89, in __init__
    reduction.dump(process_obj, to_child)

  File "C:\Users\Andrew Patterson\AppData\Local\Programs\Python\Python37\Lib\multiprocessing\reduction.py", line 60, in dump
    ForkingPickler(file, protocol).dump(obj)

TypeError: can't pickle module objects

 [Op:EagerPyFunc]

Process finished with exit code 1

Upgrade matrix uses to Eigen3

Right now we use only float* objects for our gates. It would probably be better if we used Eigen3 matrices and then when it came to state simulation just returned the matrices row-major .data() property. This would make our matrices far more extensible than anything we have now.

This will be an issue to tackle later on once we have qsim and src more organized and well tested.

MNIST Notebook is slow

We are running a LOT of quantum circuits in the MNIST tutorial. Maybe we should find a way to trim it down a little bit ? so CI can run faster. Right now it takes as much as 30+ mins on all the notebooks.

Add better Swap tests for gate matrices

Currently the swapped versions of gates are checked at only one set of angles, probably there should be an explicit swapping test for some random angles.

QPU access

Does QPU access like rigetti.com otherwise It's only simulation this library.

CI formatter uses old clang-format version

My local format check does not catch any problems, though the CI fails #72 . It seems the "Install Format tools" section of the lint-and-format job installs clang-format-3.8, which is not available through standard apt-get. Is there a way to keep required dev tool versions and CI versions in sync?

QAOA testing- q on extracting parameters, inconsistent output states

Hi, I'm trying out TFQ with the QAOA max-cut circuit that appears in arXiv:2003.02989v1. My set up is tensorflow_quantum 0.3.0, tensorflow 2.1.0 and cirq 0.8.0. I'm running on a CPU, on both a mac 10.13 and a linux box RHEL7.7. Both show the same results.

This ticket uses QAOA terminology, but the gist is tfq.layers.Sample is producing weird results for me, and model.weights appears to go in reverse order to match to sympy parameters.

TFQ works great on the QAOA execution proper- it minimizes the energy quickly. However, I run into trouble when I want to extract the final states- I want to check that the energy minimization corresponds with the maxcut solution. I'm doing this two different ways:

  1. use tfq.layers.Sample after model fitting on the QAOA circuit to extract the final state, supplying the trained model weights as parameters.

  2. build an identical circuit using cirq and again supply the trained model weights as parameters.

I did this for QAOA (p=1) on a trivial graph: two nodes, 1 edge. The solution state is (0,1) or (1,0), with optimal parameters gamma = -pi/2, beta = pi/8. What I found:

  • tfq.layers.Sample produces completely random states. The average energy it predicts doesn't match the loss (= average energy for optimal value=0?).

  • the cirq circuit works perfectly if I flip the weights. So if my parameter list is [gamma, beta], I have to assign weights as gamma = weight[1], beta = weight[0].

I tried flipping the weights for tf.Sample, but I still got random results.

I've been having trouble fully understanding the TFQ API, so this could be completely on me, but I don't understand the inconsistencies here, or why the model weights are flipped, if in fact they are. Thanks!
google_qaoa.py.zip

Move island gate collection from circuit conversion to fuser

Currently, the fuser relies on circuits having the structure that all single qubit gates be followed somewhere in the circuit by a 2 qubit gate, but the Circuit class does not enforce this. Seems Circuit should not carry these gates and instead Fuser should add these as necessary to collect all gates

Remove tfq install lines at top of notebooks

When running these notebooks we should assume people have Cirq and TensorFlow all ready to go on their computers. This was nice to have for testing, but close to release we likely need to get rid of the cells entirely

Implement quantum execution context

For our slower (cirq_ops) ops where we have the potential of going through to engineSampler in Cirq we might have to drastically change certain execution parameters. For example things like:

  1. Reducing from parallel execution to serial execution.
  2. Increasing optimization for minimizing circuit depth.
  3. Make better use of sweeps.
  4. Grouping identical circuits in the batch into the same job.

Need to be defined at the global level. To implement this we should implement a context module in the python directory that allows you to set these parameters globally in a thread safe fashion. We can take pretty closely after this: https://github.com/tensorflow/tensorflow/blob/v2.1.0/tensorflow/python/eager/context.py

Implementing this should roughly involve:

  1. Implement quantum_context.py and tests
  2. Implement engine_util.py and tests (#186 )
  3. Connect engine_util.py to cirq_ops.py via quantum_context.py.
  4. Allow users to enable or disable engine compatability mode via tf.enable_engine_mode in util.py

Cleanup ParameterShift C++ code.

This is a low priority issue and not a huge rush.

Some of the C++ op code in particular the ones for the parametershift has some kind of ugly C++ code in it. It would be nice if we could clean that up at some point. Especially if Cirq keeps adding new gates, we may need to make sure it's easy to add them in here.

Add TFQ whitepaper to readme after release

Comment from @jaeyoo
"
It is conventional to write a paper on TensorFlow & TensorFlow addon libraries.

For example, TensorFlow Probability also has its own paper aligned with its release, and the following message is inside README.md of its GitHub repo. here

If you use TensorFlow Probability in a paper, please cite:

TensorFlow Distributions. Joshua V. Dillon, Ian Langmore, Dustin Tran, Eugene Brevdo, Srinivas Vasudevan, Dave Moore, Brian Patton, Alex Alemi, Matt Hoffman, Rif A. Saurous. arXiv preprint arXiv:1711.10604, 2017.

References:
TensorFlow arXiv
TensorNetwork arXiv
TensorFlow.js arXiv
TensorFlow Distributions arXiv
"

Notebook install change

The install lines that read like this:

%%capture
h = 2dfcfceb9726fa73c40381c037dc01facd3d061e
!cd ~/
!rm -r -f TFQuantum/
!git clone https://{h}:{h}@github.com/quantumlib/TFQuantum.git;cd TFQuantum/
!pip install --upgrade ./TFQuantum/wheels/tfquantum-0.2.0-cp36-cp36m-linux_x86_64.whl

In all of the tutorial notebooks will need to be changed to:

!pip install tensorflow_quantum

When we get a little closer to release and get things up on PyPi

Add clang-tidy to linter

Comment from @jaeyoo
"
This issue is related to these files.

scripts/README.md
scripts/lint_all.sh
Let me find a way to add clang-tidy.
"

Improve sensing demo

It would be nice if the sensing demo had a bit more background information and was cleaned up a little bit.

Parallelization of parsing ops

Comment from @philiptmassey
"We should be calling ParallelFor instead of TransformRangeConcurrently. We can use absl::nullopt or {} as the current estimate of work value, but this would also allow us to make predictions on how much work a circuit takes, which could provide speedups."

Comments from @MichaelBroughton
"When running REALLY deep circuits with lots of symbols through our ops it looks like we may be spending a LOT of time parsing the circuit (sometimes more than actually computing the answer). We should try and make the parse operations that most of ops call right at the very top of their compute functions parallel."
"Maybe we should also make _batch_deserialize_helper in cirq_ops.py parallel as well ?"

Incorporate a new script for coverage checks

Comment from @MichaelBroughton
"It would be nice to have a script like ./scripts/coverage_check.sh that would tell us our python and C++ code coverage. A quick look around bazel docs seems to show that comprehensive coverage support across python and C++ is still kind of in the works and since we're locked into an old version, 0.26.1 or lower, we might have to look elsewhere ?"

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.