diff --git a/benchmarks/scripts/benchmark_clifford_circuit.py b/benchmarks/scripts/benchmark_clifford_circuit.py index 643eff790..c71751dbc 100644 --- a/benchmarks/scripts/benchmark_clifford_circuit.py +++ b/benchmarks/scripts/benchmark_clifford_circuit.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """Benchmark simulators against classically simulatable circuits.""" import os import time diff --git a/benchmarks/scripts/benchmark_op_gradients.py b/benchmarks/scripts/benchmark_op_gradients.py index 89b04cfd1..687e1b1f6 100644 --- a/benchmarks/scripts/benchmark_op_gradients.py +++ b/benchmarks/scripts/benchmark_op_gradients.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """Benchmark differentiator methods.""" import os import time diff --git a/benchmarks/scripts/benchmark_random_circuit.py b/benchmarks/scripts/benchmark_random_circuit.py index 51d4ccfbf..b265237d7 100644 --- a/benchmarks/scripts/benchmark_random_circuit.py +++ b/benchmarks/scripts/benchmark_random_circuit.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """Benchmark simulators against classically intractable 'supremacy' circuits.""" import os import time diff --git a/benchmarks/scripts/benchmark_util.py b/benchmarks/scripts/benchmark_util.py index 5b4bea2e5..87e903ecb 100644 --- a/benchmarks/scripts/benchmark_util.py +++ b/benchmarks/scripts/benchmark_util.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """Utility functions for benchmark tools.""" import tensorflow as tf import test_log_pb2 diff --git a/benchmarks/scripts/benchmark_util_test.py b/benchmarks/scripts/benchmark_util_test.py index bece69897..951478a19 100644 --- a/benchmarks/scripts/benchmark_util_test.py +++ b/benchmarks/scripts/benchmark_util_test.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """Tests for utilities related to reading/running benchmarks.""" import os import tempfile diff --git a/benchmarks/scripts/flags.py b/benchmarks/scripts/flags.py index eaf7e78e2..ee173ef28 100644 --- a/benchmarks/scripts/flags.py +++ b/benchmarks/scripts/flags.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """Command line flags shared between benchmarks.""" from collections import namedtuple from absl import flags as absl_flags diff --git a/benchmarks/scripts/flags_test.py b/benchmarks/scripts/flags_test.py index 6383809c6..c51a2f814 100644 --- a/benchmarks/scripts/flags_test.py +++ b/benchmarks/scripts/flags_test.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """Tests for benchmark command line flags.""" import tensorflow as tf diff --git a/benchmarks/scripts/models/__init__.py b/benchmarks/scripts/models/__init__.py index bf5b48863..9d181170d 100644 --- a/benchmarks/scripts/models/__init__.py +++ b/benchmarks/scripts/models/__init__.py @@ -11,4 +11,4 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== \ No newline at end of file +# ============================================================================= \ No newline at end of file diff --git a/benchmarks/scripts/models/random_clifford_circuit.py b/benchmarks/scripts/models/random_clifford_circuit.py index a08a667b5..09012c14e 100644 --- a/benchmarks/scripts/models/random_clifford_circuit.py +++ b/benchmarks/scripts/models/random_clifford_circuit.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= from typing import Iterable diff --git a/benchmarks/scripts/models/random_clifford_circuit_test.py b/benchmarks/scripts/models/random_clifford_circuit_test.py index c6d968ea0..bee8f5464 100644 --- a/benchmarks/scripts/models/random_clifford_circuit_test.py +++ b/benchmarks/scripts/models/random_clifford_circuit_test.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= from absl.testing import parameterized import cirq diff --git a/configure.sh b/configure.sh index decaaa2c6..53db1975a 100755 --- a/configure.sh +++ b/configure.sh @@ -12,7 +12,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= PLATFORM="$(uname -s | tr 'A-Z' 'a-z')" function write_to_bazelrc() { diff --git a/release/build_pip_package.sh b/release/build_pip_package.sh index 8bed5b909..1c423c656 100755 --- a/release/build_pip_package.sh +++ b/release/build_pip_package.sh @@ -12,7 +12,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= set -e set -x diff --git a/release/setup.py b/release/setup.py index c2e9fb718..109c909e9 100644 --- a/release/setup.py +++ b/release/setup.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """TensorFlow Quantum adds qauntum computing primitives to TensorFlow. TensorFlow Quantum is an open source library for high performance batch diff --git a/scripts/benchmark_all.sh b/scripts/benchmark_all.sh index cd50209c2..648d9ebad 100644 --- a/scripts/benchmark_all.sh +++ b/scripts/benchmark_all.sh @@ -12,7 +12,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= echo "Testing benchmarks."; test_outputs=$(bazel test -c opt --cxxopt="-D_GLIBCXX_USE_CXX11_ABI=1" --cxxopt="-msse2" --cxxopt="-msse3" --cxxopt="-msse4" --test_output=errors $(bazel query //benchmarks/...)) exit_code=$? diff --git a/scripts/build_docs.py b/scripts/build_docs.py index dc47df224..3ad066491 100644 --- a/scripts/build_docs.py +++ b/scripts/build_docs.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """Tool to generate external api_docs for tfq.""" from __future__ import absolute_import diff --git a/scripts/build_pip_package_test.sh b/scripts/build_pip_package_test.sh index 644338b6a..144a42cfb 100755 --- a/scripts/build_pip_package_test.sh +++ b/scripts/build_pip_package_test.sh @@ -12,7 +12,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= pip install -r requirements.txt diff --git a/scripts/ci_install.sh b/scripts/ci_install.sh index 04e6b3159..860c02ecc 100755 --- a/scripts/ci_install.sh +++ b/scripts/ci_install.sh @@ -12,7 +12,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= wget https://github.com/bazelbuild/bazel/releases/download/5.3.0/bazel_5.3.0-linux-x86_64.deb sudo dpkg -i bazel_5.3.0-linux-x86_64.deb pip install --upgrade pip setuptools wheel diff --git a/scripts/ci_validate_tutorials.sh b/scripts/ci_validate_tutorials.sh index e58355faf..d64361464 100755 --- a/scripts/ci_validate_tutorials.sh +++ b/scripts/ci_validate_tutorials.sh @@ -12,7 +12,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= # Run the tutorials using the installed pip package pip install jupyter nbclient==0.6.5 jupyter-client==6.1.12 ipython==7.22.0 diff --git a/scripts/format_all.sh b/scripts/format_all.sh index 0e374a3cc..a30017981 100755 --- a/scripts/format_all.sh +++ b/scripts/format_all.sh @@ -12,7 +12,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= echo "Doing python language formatting..." python3 -m yapf --style=google --in-place --recursive ./benchmarks python3 -m yapf --style=google --in-place --recursive ./tensorflow_quantum diff --git a/scripts/format_check.sh b/scripts/format_check.sh index 1d91427e0..d128d36b4 100755 --- a/scripts/format_check.sh +++ b/scripts/format_check.sh @@ -12,7 +12,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= echo "Checking python formatting..."; ################################################################################ diff --git a/scripts/format_ipynb.py b/scripts/format_ipynb.py index fac7a8bf1..10d2e447f 100644 --- a/scripts/format_ipynb.py +++ b/scripts/format_ipynb.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """Format notebook code cells using yapf google style.""" import glob import nbformat diff --git a/scripts/import_test.py b/scripts/import_test.py index 83ec24d2e..ce2c87307 100644 --- a/scripts/import_test.py +++ b/scripts/import_test.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """Tests to check if importing `tfq` APIs is successful or not.""" import tensorflow_quantum as tfq diff --git a/scripts/lint_all.sh b/scripts/lint_all.sh index fb7e1c9a5..755906981 100755 --- a/scripts/lint_all.sh +++ b/scripts/lint_all.sh @@ -12,7 +12,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= echo "Checking for lint in python code..."; linting_outputs=$(pylint --rcfile .pylintrc ./tensorflow_quantum ./examples); exit_code=$? diff --git a/scripts/msan_test.sh b/scripts/msan_test.sh index d47e8ccfe..398332315 100755 --- a/scripts/msan_test.sh +++ b/scripts/msan_test.sh @@ -12,7 +12,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= echo "Testing All Bazel cc_tests with msan."; test_outputs=$(bazel test -c opt --cxxopt="-D_GLIBCXX_USE_CXX11_ABI=1" \ --cxxopt="-msse2" --cxxopt="-msse3" --cxxopt="-msse4" \ diff --git a/scripts/run_example.sh b/scripts/run_example.sh index bb86edc22..1fbdd62d7 100755 --- a/scripts/run_example.sh +++ b/scripts/run_example.sh @@ -12,7 +12,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= cd .. cp quantum/scripts/import_test.py import_test.py python import_test.py \ No newline at end of file diff --git a/scripts/test_all.sh b/scripts/test_all.sh index de82f406d..ffb43d42d 100755 --- a/scripts/test_all.sh +++ b/scripts/test_all.sh @@ -12,7 +12,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= echo "Testing All Bazel py_test and cc_tests."; ENABLE_CUDA=${1} diff --git a/scripts/test_benchmarks.sh b/scripts/test_benchmarks.sh index 07e3adec1..281791ec7 100644 --- a/scripts/test_benchmarks.sh +++ b/scripts/test_benchmarks.sh @@ -12,7 +12,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= echo "Testing all Benchmarks."; bazel test -c opt --cxxopt="-D_GLIBCXX_USE_CXX11_ABI=1" --cxxopt="-msse2" --cxxopt="-msse3" --cxxopt="-msse4" --test_output=errors $(bazel query //benchmarks/scripts:all) # test_outputs=$(bazel test -c opt --cxxopt="-D_GLIBCXX_USE_CXX11_ABI=1" --cxxopt="-msse2" --cxxopt="-msse3" --cxxopt="-msse4" --test_output=errors $(bazel query //benchmarks/scripts:all)) diff --git a/scripts/test_tutorials.py b/scripts/test_tutorials.py index 1650caf15..b4463b90d 100644 --- a/scripts/test_tutorials.py +++ b/scripts/test_tutorials.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """Module to ensure all notebooks execute without error by pytesting them.""" import glob import re diff --git a/tensorflow_quantum/__init__.py b/tensorflow_quantum/__init__.py index 5df8ae1f8..4403510f7 100644 --- a/tensorflow_quantum/__init__.py +++ b/tensorflow_quantum/__init__.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """Module functions for tensorflow_quantum.*""" # Import basic ops and op getters. diff --git a/tensorflow_quantum/core/__init__.py b/tensorflow_quantum/core/__init__.py index fb24ad4a8..7e43c4be5 100644 --- a/tensorflow_quantum/core/__init__.py +++ b/tensorflow_quantum/core/__init__.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """Imports to tensorflow_quantum.core.* level.""" # Import getters for constructing ops. from tensorflow_quantum.core.ops import (get_expectation_op, diff --git a/tensorflow_quantum/core/ops/__init__.py b/tensorflow_quantum/core/ops/__init__.py index 062ea7499..fc687424a 100644 --- a/tensorflow_quantum/core/ops/__init__.py +++ b/tensorflow_quantum/core/ops/__init__.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """Module for tfq.core.ops.*""" # Import getters for constructing ops. diff --git a/tensorflow_quantum/core/ops/batch_util.py b/tensorflow_quantum/core/ops/batch_util.py index 75f148424..7575ffae1 100644 --- a/tensorflow_quantum/core/ops/batch_util.py +++ b/tensorflow_quantum/core/ops/batch_util.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """A module to for running Cirq objects.""" import collections diff --git a/tensorflow_quantum/core/ops/batch_util_test.py b/tensorflow_quantum/core/ops/batch_util_test.py index 6b11becd7..48eb02ed3 100644 --- a/tensorflow_quantum/core/ops/batch_util_test.py +++ b/tensorflow_quantum/core/ops/batch_util_test.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """Test parallel Cirq simulations.""" # Remove PYTHONPATH collisions for protobuf. # pylint: disable=wrong-import-position diff --git a/tensorflow_quantum/core/ops/circuit_execution_ops.py b/tensorflow_quantum/core/ops/circuit_execution_ops.py index d39edad48..2c87baa09 100644 --- a/tensorflow_quantum/core/ops/circuit_execution_ops.py +++ b/tensorflow_quantum/core/ops/circuit_execution_ops.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """A module for user-facing generators of tfq ops.""" import enum @@ -23,15 +23,16 @@ try: from tensorflow_quantum.core.ops import tfq_simulate_ops_cuquantum - _enable_use_cuquantum = True + _ENABLE_USE_CUQUANTUM = True except: - # `_enable_use_cuquantum = False` makes `use_cuquantum` silent. - _enable_use_cuquantum = False + # `_ENABLE_USE_CUQUANTUM = False` makes `use_cuquantum` silent. + _ENABLE_USE_CUQUANTUM = False tfq_simulate_ops_cuquantum = tfq_simulate_ops -def is_cuda_configured() -> bool: - return _enable_use_cuquantum +def is_gpu_configured() -> bool: + """Returns True if gpu ops are available or not.""" + return _ENABLE_USE_CUQUANTUM class TFQStateVectorSimulator(enum.Enum): @@ -45,12 +46,9 @@ class TFQStateVectorSimulator(enum.Enum): state = tfq_simulate_ops.tfq_simulate_state state_cuquantum = tfq_simulate_ops_cuquantum.tfq_simulate_state - sampled_expectation = ( - tfq_simulate_ops.tfq_simulate_sampled_expectation - ) + sampled_expectation = tfq_simulate_ops.tfq_simulate_sampled_expectation sampled_expectation_cuquantum = ( - tfq_simulate_ops_cuquantum.tfq_simulate_sampled_expectation - ) + tfq_simulate_ops_cuquantum.tfq_simulate_sampled_expectation) def _check_quantum_concurrent(quantum_concurrent, use_cuquantum): @@ -150,7 +148,7 @@ def get_expectation_op( """ # TODO (mbbrough): investigate how the above docstring renders. _check_quantum_concurrent(quantum_concurrent, use_cuquantum) - use_cuquantum = _enable_use_cuquantum and use_cuquantum + use_cuquantum = _ENABLE_USE_CUQUANTUM and use_cuquantum op = None if backend is None: @@ -256,7 +254,7 @@ def get_sampling_op( # TODO (mbbrough): investigate how the above docstring renders. _check_quantum_concurrent(quantum_concurrent, use_cuquantum) - use_cuquantum = _enable_use_cuquantum and use_cuquantum + use_cuquantum = _ENABLE_USE_CUQUANTUM and use_cuquantum op = None if backend is None: @@ -352,7 +350,7 @@ def get_state_op( # TODO (mbbrough): investigate how the above docstring renders. _check_quantum_concurrent(quantum_concurrent, use_cuquantum) - use_cuquantum = _enable_use_cuquantum and use_cuquantum + use_cuquantum = _ENABLE_USE_CUQUANTUM and use_cuquantum op = None if backend is None: @@ -470,7 +468,7 @@ def get_sampled_expectation_op( """ # TODO (mbbrough): investigate how the above docstring renders. _check_quantum_concurrent(quantum_concurrent, use_cuquantum) - use_cuquantum = _enable_use_cuquantum and use_cuquantum + use_cuquantum = _ENABLE_USE_CUQUANTUM and use_cuquantum op = None if backend is None: @@ -503,4 +501,4 @@ def get_sampled_expectation_op( raise TypeError( "Backend {} is invalid. Expected a Cirq.Sampler or None.".format( - backend)) \ No newline at end of file + backend)) diff --git a/tensorflow_quantum/core/ops/circuit_execution_ops_test.py b/tensorflow_quantum/core/ops/circuit_execution_ops_test.py index 549901258..6a36afb4f 100644 --- a/tensorflow_quantum/core/ops/circuit_execution_ops_test.py +++ b/tensorflow_quantum/core/ops/circuit_execution_ops_test.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """Module to test consistency between Cirq and TFQ circuit execution ops.""" # Remove PYTHONPATH collisions for protobuf. # pylint: disable=wrong-import-position diff --git a/tensorflow_quantum/core/ops/cirq_ops.py b/tensorflow_quantum/core/ops/cirq_ops.py index 884fe98d2..808296433 100644 --- a/tensorflow_quantum/core/ops/cirq_ops.py +++ b/tensorflow_quantum/core/ops/cirq_ops.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """Generators for ops that call out to cirq simulators from the tf graph.""" import functools import numbers diff --git a/tensorflow_quantum/core/ops/cirq_ops_test.py b/tensorflow_quantum/core/ops/cirq_ops_test.py index d634e671c..79a108b66 100644 --- a/tensorflow_quantum/core/ops/cirq_ops_test.py +++ b/tensorflow_quantum/core/ops/cirq_ops_test.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """Tests for the cirq simulation ops.""" # Remove PYTHONPATH collisions for protobuf. # pylint: disable=wrong-import-position diff --git a/tensorflow_quantum/core/ops/load_module.py b/tensorflow_quantum/core/ops/load_module.py index b5002ad84..ee4f9b0b6 100644 --- a/tensorflow_quantum/core/ops/load_module.py +++ b/tensorflow_quantum/core/ops/load_module.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """Module to load python op libraries.""" import os diff --git a/tensorflow_quantum/core/ops/math_ops/__init__.py b/tensorflow_quantum/core/ops/math_ops/__init__.py index 982e26911..9d3b92f64 100644 --- a/tensorflow_quantum/core/ops/math_ops/__init__.py +++ b/tensorflow_quantum/core/ops/math_ops/__init__.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """Module for tfq.core.ops.math_ops.*""" from tensorflow_quantum.core.ops.math_ops.fidelity_op import fidelity diff --git a/tensorflow_quantum/core/ops/math_ops/fidelity_op.py b/tensorflow_quantum/core/ops/math_ops/fidelity_op.py index 8f2e87e44..ae2908baa 100644 --- a/tensorflow_quantum/core/ops/math_ops/fidelity_op.py +++ b/tensorflow_quantum/core/ops/math_ops/fidelity_op.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """Module for tfq.math.fidelity op.""" import tensorflow as tf from tensorflow_quantum.core.ops.math_ops import inner_product_op diff --git a/tensorflow_quantum/core/ops/math_ops/fidelity_op_test.py b/tensorflow_quantum/core/ops/math_ops/fidelity_op_test.py index 1ab8031ea..9fe171785 100644 --- a/tensorflow_quantum/core/ops/math_ops/fidelity_op_test.py +++ b/tensorflow_quantum/core/ops/math_ops/fidelity_op_test.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """Tests that specifically target tfq_inner_product.""" # Remove PYTHONPATH collisions for protobuf. # pylint: disable=wrong-import-position diff --git a/tensorflow_quantum/core/ops/math_ops/inner_product_grad_test.py b/tensorflow_quantum/core/ops/math_ops/inner_product_grad_test.py index 7fa74ee40..8d13974b8 100644 --- a/tensorflow_quantum/core/ops/math_ops/inner_product_grad_test.py +++ b/tensorflow_quantum/core/ops/math_ops/inner_product_grad_test.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """Tests that specifically target tfq_inner_product_grad.""" # Remove PYTHONPATH collisions for protobuf. # pylint: disable=wrong-import-position diff --git a/tensorflow_quantum/core/ops/math_ops/inner_product_op.py b/tensorflow_quantum/core/ops/math_ops/inner_product_op.py index 5d92b7b92..54e49643e 100644 --- a/tensorflow_quantum/core/ops/math_ops/inner_product_op.py +++ b/tensorflow_quantum/core/ops/math_ops/inner_product_op.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """Module to register python op gradient.""" import os import tensorflow as tf diff --git a/tensorflow_quantum/core/ops/math_ops/inner_product_op_test.py b/tensorflow_quantum/core/ops/math_ops/inner_product_op_test.py index ae83857b6..458b88560 100644 --- a/tensorflow_quantum/core/ops/math_ops/inner_product_op_test.py +++ b/tensorflow_quantum/core/ops/math_ops/inner_product_op_test.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """Tests that specifically target tfq_inner_product.""" # Remove PYTHONPATH collisions for protobuf. # pylint: disable=wrong-import-position diff --git a/tensorflow_quantum/core/ops/math_ops/simulate_mps.py b/tensorflow_quantum/core/ops/math_ops/simulate_mps.py index 812081c05..41e1fd7c2 100644 --- a/tensorflow_quantum/core/ops/math_ops/simulate_mps.py +++ b/tensorflow_quantum/core/ops/math_ops/simulate_mps.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """Module to register MPS simulation ops.""" import os import tensorflow as tf diff --git a/tensorflow_quantum/core/ops/math_ops/simulate_mps_test.py b/tensorflow_quantum/core/ops/math_ops/simulate_mps_test.py index ee7317b6a..eee2190f7 100644 --- a/tensorflow_quantum/core/ops/math_ops/simulate_mps_test.py +++ b/tensorflow_quantum/core/ops/math_ops/simulate_mps_test.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """Tests that specifically target simulate_mps.""" # Remove PYTHONPATH collisions for protobuf. # pylint: disable=wrong-import-position diff --git a/tensorflow_quantum/core/ops/noise/__init__.py b/tensorflow_quantum/core/ops/noise/__init__.py index 71291d4d2..d7969cec5 100644 --- a/tensorflow_quantum/core/ops/noise/__init__.py +++ b/tensorflow_quantum/core/ops/noise/__init__.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """Module for tfq.core.ops.noise.*""" from tensorflow_quantum.core.ops.noise.noisy_expectation_op import expectation diff --git a/tensorflow_quantum/core/ops/noise/noisy_expectation_op.py b/tensorflow_quantum/core/ops/noise/noisy_expectation_op.py index e621988a0..7f801e686 100644 --- a/tensorflow_quantum/core/ops/noise/noisy_expectation_op.py +++ b/tensorflow_quantum/core/ops/noise/noisy_expectation_op.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """Module for high performance noisy circuit simulation ops.""" import os import tensorflow as tf diff --git a/tensorflow_quantum/core/ops/noise/noisy_expectation_op_test.py b/tensorflow_quantum/core/ops/noise/noisy_expectation_op_test.py index 1e73500b8..70659f888 100644 --- a/tensorflow_quantum/core/ops/noise/noisy_expectation_op_test.py +++ b/tensorflow_quantum/core/ops/noise/noisy_expectation_op_test.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """Tests that specifically target noisy expectation calculation.""" # Remove PYTHONPATH collisions for protobuf. # pylint: disable=wrong-import-position diff --git a/tensorflow_quantum/core/ops/noise/noisy_sampled_expectation_op.py b/tensorflow_quantum/core/ops/noise/noisy_sampled_expectation_op.py index 1874c8a5e..2cc84fd47 100644 --- a/tensorflow_quantum/core/ops/noise/noisy_sampled_expectation_op.py +++ b/tensorflow_quantum/core/ops/noise/noisy_sampled_expectation_op.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """Module for high performance noisy circuit sampled epxectation ops.""" import os import tensorflow as tf diff --git a/tensorflow_quantum/core/ops/noise/noisy_sampled_expectation_op_test.py b/tensorflow_quantum/core/ops/noise/noisy_sampled_expectation_op_test.py index 35d1cc113..17f3d31a1 100644 --- a/tensorflow_quantum/core/ops/noise/noisy_sampled_expectation_op_test.py +++ b/tensorflow_quantum/core/ops/noise/noisy_sampled_expectation_op_test.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """Tests that specifically target noisy expectation calculation.""" # Remove PYTHONPATH collisions for protobuf. # pylint: disable=wrong-import-position diff --git a/tensorflow_quantum/core/ops/noise/noisy_samples_op.py b/tensorflow_quantum/core/ops/noise/noisy_samples_op.py index 4441d0c04..1e19b19ae 100644 --- a/tensorflow_quantum/core/ops/noise/noisy_samples_op.py +++ b/tensorflow_quantum/core/ops/noise/noisy_samples_op.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """Module for high performance noisy circuit sampling ops""" import os import tensorflow as tf diff --git a/tensorflow_quantum/core/ops/noise/noisy_samples_op_test.py b/tensorflow_quantum/core/ops/noise/noisy_samples_op_test.py index b952e8d40..03687bdb7 100644 --- a/tensorflow_quantum/core/ops/noise/noisy_samples_op_test.py +++ b/tensorflow_quantum/core/ops/noise/noisy_samples_op_test.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """Tests that specifically target noisy sampling.""" # Remove PYTHONPATH collisions for protobuf. # pylint: disable=wrong-import-position diff --git a/tensorflow_quantum/core/ops/tfq_adj_grad_op.cc b/tensorflow_quantum/core/ops/tfq_adj_grad_op.cc index fa71bdad7..fe88a5817 100644 --- a/tensorflow_quantum/core/ops/tfq_adj_grad_op.cc +++ b/tensorflow_quantum/core/ops/tfq_adj_grad_op.cc @@ -209,8 +209,8 @@ class TfqAdjointGradientOp : public tensorflow::OpKernel { // sv now contains psi // scratch contains (sum_j paulis_sums[i][j] * downstream_grads[j])|psi> // scratch2 now contains psi as well. - [[maybe_unused]] Status unused = AccumulateOperators(pauli_sums[i], downstream_grads[i], - sim, ss, sv, scratch2, scratch); + [[maybe_unused]] Status unused = AccumulateOperators( + pauli_sums[i], downstream_grads[i], sim, ss, sv, scratch2, scratch); for (int j = partial_fused_circuits[i].size() - 1; j >= 0; j--) { for (int k = partial_fused_circuits[i][j].size() - 1; k >= 0; k--) { @@ -322,8 +322,8 @@ class TfqAdjointGradientOp : public tensorflow::OpKernel { // sv now contains psi // scratch contains (sum_j paulis_sums[i][j] * downstream_grads[j])|psi> // scratch2 now contains psi as well. - [[maybe_unused]] Status unused = AccumulateOperators(pauli_sums[i], downstream_grads[i], - sim, ss, sv, scratch2, scratch); + [[maybe_unused]] Status unused = AccumulateOperators( + pauli_sums[i], downstream_grads[i], sim, ss, sv, scratch2, scratch); for (int j = partial_fused_circuits[i].size() - 1; j >= 0; j--) { for (int k = partial_fused_circuits[i][j].size() - 1; k >= 0; k--) { diff --git a/tensorflow_quantum/core/ops/tfq_adj_grad_op.py b/tensorflow_quantum/core/ops/tfq_adj_grad_op.py index 04b8ff0fb..ead1e34d6 100644 --- a/tensorflow_quantum/core/ops/tfq_adj_grad_op.py +++ b/tensorflow_quantum/core/ops/tfq_adj_grad_op.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """Module to register python op gradient.""" import tensorflow as tf from tensorflow_quantum.core.ops.load_module import load_module diff --git a/tensorflow_quantum/core/ops/tfq_adj_grad_op_cuquantum.cu.cc b/tensorflow_quantum/core/ops/tfq_adj_grad_op_cuquantum.cu.cc index 93294c0fc..55213c78b 100644 --- a/tensorflow_quantum/core/ops/tfq_adj_grad_op_cuquantum.cu.cc +++ b/tensorflow_quantum/core/ops/tfq_adj_grad_op_cuquantum.cu.cc @@ -41,17 +41,16 @@ namespace tfq { namespace { // TODO(jaeyoo): Temorary hack for BulkSetAmpl with cuda ops. // Updates qsim custatevec side BulkSetAmple ops, and remove these utilities. -template +template __global__ void BulkSetAmplKernel(uint64_t mask, uint64_t bits, FP re, FP im, bool exclude, FP* state) { uint64_t k1 = uint64_t{blockIdx.x} * blockDim.x + threadIdx.x; - uint64_t k2 = 2 * k1 - threadIdx.x % warp_size; bool set = ((k1 & mask) == bits) ^ exclude; if (set) { - state[k2] = re; - state[k2 + warp_size] = im; + state[2 * k1] = re; + state[2 * k1 + 1] = im; } } @@ -246,8 +245,8 @@ class TfqAdjointGradientCuquantumOp : public tensorflow::OpKernel { // sv now contains psi // scratch contains (sum_j paulis_sums[i][j] * downstream_grads[j])|psi> // scratch2 now contains psi as well. - [[maybe_unused]] Status unused = AccumulateOperators(pauli_sums[i], downstream_grads[i], - sim, ss, sv, scratch2, scratch); + [[maybe_unused]] Status unused = AccumulateOperators( + pauli_sums[i], downstream_grads[i], sim, ss, sv, scratch2, scratch); for (int j = partial_fused_circuits[i].size() - 1; j >= 0; j--) { for (int k = partial_fused_circuits[i][j].size() - 1; k >= 0; k--) { diff --git a/tensorflow_quantum/core/ops/tfq_adj_grad_op_cuquantum.py b/tensorflow_quantum/core/ops/tfq_adj_grad_op_cuquantum.py index a96e13d23..e73775a45 100644 --- a/tensorflow_quantum/core/ops/tfq_adj_grad_op_cuquantum.py +++ b/tensorflow_quantum/core/ops/tfq_adj_grad_op_cuquantum.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """Module to register python op gradient.""" import tensorflow as tf from tensorflow_quantum.core.ops.load_module import load_module diff --git a/tensorflow_quantum/core/ops/tfq_adj_grad_op_cuquantum_test.py b/tensorflow_quantum/core/ops/tfq_adj_grad_op_cuquantum_test.py index 3933efde0..262f81728 100644 --- a/tensorflow_quantum/core/ops/tfq_adj_grad_op_cuquantum_test.py +++ b/tensorflow_quantum/core/ops/tfq_adj_grad_op_cuquantum_test.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """Tests that specifically target tfq_unitary_op.""" # Remove PYTHONPATH collisions for protobuf. # pylint: disable=wrong-import-position @@ -116,7 +116,7 @@ def test_calculate_adj_grad_cpu_vs_cuquantum(self): # The result should be the similar within a tolerance. np.testing.assert_allclose(res_cpu, res_cuquantum, - atol=1e-3, + atol=1e-4, err_msg=""" # If failed, the GPU architecture in this system may be unsupported. # Please refer to the supported architectures here. diff --git a/tensorflow_quantum/core/ops/tfq_adj_grad_op_test.py b/tensorflow_quantum/core/ops/tfq_adj_grad_op_test.py index 388bb163f..a46f2f1f7 100644 --- a/tensorflow_quantum/core/ops/tfq_adj_grad_op_test.py +++ b/tensorflow_quantum/core/ops/tfq_adj_grad_op_test.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """Tests that specifically target tfq_unitary_op.""" # Remove PYTHONPATH collisions for protobuf. # pylint: disable=wrong-import-position diff --git a/tensorflow_quantum/core/ops/tfq_circuit_append_op.cc b/tensorflow_quantum/core/ops/tfq_circuit_append_op.cc index 188df8ab5..582bd1681 100644 --- a/tensorflow_quantum/core/ops/tfq_circuit_append_op.cc +++ b/tensorflow_quantum/core/ops/tfq_circuit_append_op.cc @@ -54,8 +54,8 @@ class TfqCircuitAppendOp : public tensorflow::OpKernel { auto DoWork = [&](int start, int end) { std::string temp; for (int i = start; i < end; i++) { - for (int j = 0; - j < programs_to_append.at(i).circuit().moments().size(); j++) { + for (int j = 0; j < programs_to_append.at(i).circuit().moments().size(); + j++) { Moment *new_moment = programs.at(i).mutable_circuit()->add_moments(); *new_moment = programs_to_append.at(i).circuit().moments(j); } diff --git a/tensorflow_quantum/core/ops/tfq_ps_util_ops.py b/tensorflow_quantum/core/ops/tfq_ps_util_ops.py index ad746d045..5a90eb0b3 100644 --- a/tensorflow_quantum/core/ops/tfq_ps_util_ops.py +++ b/tensorflow_quantum/core/ops/tfq_ps_util_ops.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """Expose bindings for ParameterShift C++ ops.""" from tensorflow_quantum.core.ops.load_module import load_module diff --git a/tensorflow_quantum/core/ops/tfq_ps_util_ops_test.py b/tensorflow_quantum/core/ops/tfq_ps_util_ops_test.py index 14bccd9bf..187aab5c9 100644 --- a/tensorflow_quantum/core/ops/tfq_ps_util_ops_test.py +++ b/tensorflow_quantum/core/ops/tfq_ps_util_ops_test.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """Test for ParameterShift specific C++ ops.""" # Remove PYTHONPATH collisions for protobuf. # pylint: disable=wrong-import-position diff --git a/tensorflow_quantum/core/ops/tfq_simulate_ops.py b/tensorflow_quantum/core/ops/tfq_simulate_ops.py index 17f1fd6bd..a68116c3e 100644 --- a/tensorflow_quantum/core/ops/tfq_simulate_ops.py +++ b/tensorflow_quantum/core/ops/tfq_simulate_ops.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """Module to register python op gradient.""" import tensorflow as tf from tensorflow_quantum.core.ops.load_module import load_module diff --git a/tensorflow_quantum/core/ops/tfq_simulate_ops_cuquantum.py b/tensorflow_quantum/core/ops/tfq_simulate_ops_cuquantum.py index ba448d27e..27165e4d6 100644 --- a/tensorflow_quantum/core/ops/tfq_simulate_ops_cuquantum.py +++ b/tensorflow_quantum/core/ops/tfq_simulate_ops_cuquantum.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """Module to register cuQuantum simulation python op.""" import tensorflow as tf from tensorflow_quantum.core.ops.load_module import load_module diff --git a/tensorflow_quantum/core/ops/tfq_simulate_ops_cuquantum_test.py b/tensorflow_quantum/core/ops/tfq_simulate_ops_cuquantum_test.py index 7922504b3..3cc8ef0b7 100644 --- a/tensorflow_quantum/core/ops/tfq_simulate_ops_cuquantum_test.py +++ b/tensorflow_quantum/core/ops/tfq_simulate_ops_cuquantum_test.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """Tests that specifically target tfq_simulate_ops_cu*.""" import time import numpy as np diff --git a/tensorflow_quantum/core/ops/tfq_simulate_ops_test.py b/tensorflow_quantum/core/ops/tfq_simulate_ops_test.py index 4cdbe42e5..7b29773c8 100644 --- a/tensorflow_quantum/core/ops/tfq_simulate_ops_test.py +++ b/tensorflow_quantum/core/ops/tfq_simulate_ops_test.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """Tests that specifically target tfq_simulate_ops.""" # Remove PYTHONPATH collisions for protobuf. # pylint: disable=wrong-import-position diff --git a/tensorflow_quantum/core/ops/tfq_unitary_op.py b/tensorflow_quantum/core/ops/tfq_unitary_op.py index 5db7005db..775516896 100644 --- a/tensorflow_quantum/core/ops/tfq_unitary_op.py +++ b/tensorflow_quantum/core/ops/tfq_unitary_op.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """Module to register python op gradient.""" import tensorflow as tf from tensorflow_quantum.core.ops import tfq_utility_ops diff --git a/tensorflow_quantum/core/ops/tfq_unitary_op_test.py b/tensorflow_quantum/core/ops/tfq_unitary_op_test.py index 212094056..2396bc690 100644 --- a/tensorflow_quantum/core/ops/tfq_unitary_op_test.py +++ b/tensorflow_quantum/core/ops/tfq_unitary_op_test.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """Tests that specifically target tfq_unitary_op.""" # Remove PYTHONPATH collisions for protobuf. # pylint: disable=wrong-import-position diff --git a/tensorflow_quantum/core/ops/tfq_utility_ops.py b/tensorflow_quantum/core/ops/tfq_utility_ops.py index e560f579c..2d0d45def 100644 --- a/tensorflow_quantum/core/ops/tfq_utility_ops.py +++ b/tensorflow_quantum/core/ops/tfq_utility_ops.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """Expose bindings for tfq utility ops.""" import tensorflow as tf from tensorflow_quantum.core.ops.load_module import load_module diff --git a/tensorflow_quantum/core/ops/tfq_utility_ops_test.py b/tensorflow_quantum/core/ops/tfq_utility_ops_test.py index 00c5ff791..050a4478c 100644 --- a/tensorflow_quantum/core/ops/tfq_utility_ops_test.py +++ b/tensorflow_quantum/core/ops/tfq_utility_ops_test.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """Tests for tfq utility ops.""" # Remove PYTHONPATH collisions for protobuf. # pylint: disable=wrong-import-position diff --git a/tensorflow_quantum/core/proto/__init__.py b/tensorflow_quantum/core/proto/__init__.py index bdbbd7a51..be0da7259 100644 --- a/tensorflow_quantum/core/proto/__init__.py +++ b/tensorflow_quantum/core/proto/__init__.py @@ -11,4 +11,4 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= diff --git a/tensorflow_quantum/core/serialize/__init__.py b/tensorflow_quantum/core/serialize/__init__.py index 6ee678723..eebbe0156 100644 --- a/tensorflow_quantum/core/serialize/__init__.py +++ b/tensorflow_quantum/core/serialize/__init__.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """Module for tfq.core.serialize.*""" from tensorflow_quantum.core.serialize.serializer import (serialize_circuit, deserialize_circuit, diff --git a/tensorflow_quantum/core/serialize/serializer.py b/tensorflow_quantum/core/serialize/serializer.py index 73b38ee16..80ddb6672 100644 --- a/tensorflow_quantum/core/serialize/serializer.py +++ b/tensorflow_quantum/core/serialize/serializer.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """A basic serializer used to serialize/deserialize Cirq circuits for tfq.""" # TODO(pmassey / anyone): determine if this should be kept as globals. import copy diff --git a/tensorflow_quantum/core/serialize/serializer_test.py b/tensorflow_quantum/core/serialize/serializer_test.py index a43da0cf0..effc4f314 100644 --- a/tensorflow_quantum/core/serialize/serializer_test.py +++ b/tensorflow_quantum/core/serialize/serializer_test.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """Module to test serialization core.""" # Remove PYTHONPATH collisions for protobuf. # pylint: disable=wrong-import-position diff --git a/tensorflow_quantum/datasets/__init__.py b/tensorflow_quantum/datasets/__init__.py index de1192fd4..8ec6a1e5a 100644 --- a/tensorflow_quantum/datasets/__init__.py +++ b/tensorflow_quantum/datasets/__init__.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """Experimental location for interesting quantum datasets.""" # Import to the tensorflow_quantum.datasets.* level.""" from tensorflow_quantum.datasets.cluster_state import excited_cluster_states diff --git a/tensorflow_quantum/datasets/cluster_state.py b/tensorflow_quantum/datasets/cluster_state.py index 2c7f5a909..59c35997f 100644 --- a/tensorflow_quantum/datasets/cluster_state.py +++ b/tensorflow_quantum/datasets/cluster_state.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """Toy dataset showing boilerplate code for a cluster state example.""" import numpy as np import cirq diff --git a/tensorflow_quantum/datasets/cluster_state_test.py b/tensorflow_quantum/datasets/cluster_state_test.py index 49e75309d..040cc0a0a 100644 --- a/tensorflow_quantum/datasets/cluster_state_test.py +++ b/tensorflow_quantum/datasets/cluster_state_test.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """Test the cluster state dataset.""" # Remove PYTHONPATH collisions for protobuf. # pylint: disable=wrong-import-position diff --git a/tensorflow_quantum/datasets/spin_system.py b/tensorflow_quantum/datasets/spin_system.py index 4a180a68f..3d53d5eae 100644 --- a/tensorflow_quantum/datasets/spin_system.py +++ b/tensorflow_quantum/datasets/spin_system.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """Quantum datasets for quantum many-body spin systems.""" from collections import namedtuple diff --git a/tensorflow_quantum/datasets/spin_system_test.py b/tensorflow_quantum/datasets/spin_system_test.py index 654b60e2a..e8c85c575 100644 --- a/tensorflow_quantum/datasets/spin_system_test.py +++ b/tensorflow_quantum/datasets/spin_system_test.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """Test the spin system dataset""" # Remove PYTHONPATH collisions for protobuf. # pylint: disable=wrong-import-position diff --git a/tensorflow_quantum/python/__init__.py b/tensorflow_quantum/python/__init__.py index afc3cd168..a66da1f02 100644 --- a/tensorflow_quantum/python/__init__.py +++ b/tensorflow_quantum/python/__init__.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """Module definitions for tensorflow_quantum.python.util.*""" from tensorflow_quantum.python.util import ( # Utility functions. diff --git a/tensorflow_quantum/python/differentiators/BUILD b/tensorflow_quantum/python/differentiators/BUILD index 329e0b2d8..33103e4e7 100644 --- a/tensorflow_quantum/python/differentiators/BUILD +++ b/tensorflow_quantum/python/differentiators/BUILD @@ -39,6 +39,7 @@ py_test( deps = [ ":adjoint", "//tensorflow_quantum/core/ops:circuit_execution_ops", + "//tensorflow_quantum/python:util", ], ) @@ -122,6 +123,7 @@ py_test( py_test( name = "gradient_test", timeout = "eternal", + shard_count = 5, srcs = ["gradient_test.py"], python_version = "PY3", deps = [ diff --git a/tensorflow_quantum/python/differentiators/__init__.py b/tensorflow_quantum/python/differentiators/__init__.py index ab386b22c..8ce0a4889 100644 --- a/tensorflow_quantum/python/differentiators/__init__.py +++ b/tensorflow_quantum/python/differentiators/__init__.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """Module functions for tfq.differentiators.*""" from tensorflow_quantum.python.differentiators.adjoint import ( diff --git a/tensorflow_quantum/python/differentiators/adjoint.py b/tensorflow_quantum/python/differentiators/adjoint.py index 122d9fa0c..57ccd304b 100644 --- a/tensorflow_quantum/python/differentiators/adjoint.py +++ b/tensorflow_quantum/python/differentiators/adjoint.py @@ -11,19 +11,18 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """Compute gradients by combining function values linearly.""" import tensorflow as tf from tensorflow_quantum.core.ops import tfq_adj_grad_op try: from tensorflow_quantum.core.ops import tfq_adj_grad_op_cuquantum - _enable_use_cuquantum = True + _ENABLE_USE_CUQUANTUM = True except: - _enable_use_cuquantum = False + _ENABLE_USE_CUQUANTUM = False tfq_adj_grad_op_cuquantum = tfq_adj_grad_op - from tensorflow_quantum.python.differentiators import differentiator @@ -100,6 +99,7 @@ def generate_differentiable_op(self, raise ValueError("sample base backends are not supported by the " "Adjoint method, please use analytic expectation" " or choose another differentiator.") + use_cuquantum = _ENABLE_USE_CUQUANTUM and use_cuquantum return super().generate_differentiable_op(analytic_op=analytic_op, use_cuquantum=use_cuquantum) @@ -142,6 +142,21 @@ def differentiate_analytic( return tfq_adj_grad_op.tfq_adj_grad(programs, symbol_names, symbol_values, pauli_sums, grad) + def differentiate_sampled_cuquantum( + self, + programs, + symbol_names, + symbol_values, + pauli_sums, + num_samples, + forward_pass_vals, + grad, + ): + raise NotImplementedError( + "Adjoint state methods are not supported in sample based settings." + " Please use analytic expectation calculation or a different " + "tfq.differentiator.") + def differentiate_sampled( self, programs, diff --git a/tensorflow_quantum/python/differentiators/adjoint_test.py b/tensorflow_quantum/python/differentiators/adjoint_test.py index ffbf9173e..df5ecc0ef 100644 --- a/tensorflow_quantum/python/differentiators/adjoint_test.py +++ b/tensorflow_quantum/python/differentiators/adjoint_test.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """Tests for the differentiator abstract class.""" # Remove PYTHONPATH collisions for protobuf. # pylint: disable=wrong-import-position @@ -19,20 +19,65 @@ NEW_PATH = [x for x in sys.path if 'com_google_protobuf' not in x] sys.path = NEW_PATH # pylint: enable=wrong-import-position +from unittest import mock +from absl.testing import parameterized +import cirq +import numpy as np +import sympy import tensorflow as tf -from tensorflow_quantum.python.differentiators import adjoint from tensorflow_quantum.core.ops import circuit_execution_ops +from tensorflow_quantum.python import util +from tensorflow_quantum.python.differentiators import adjoint -class AdjointTest(tf.test.TestCase): +class AdjointTest(tf.test.TestCase, parameterized.TestCase): """Test that we can properly subclass differentiator.""" def test_instantiation(self): """Test that adjoint can be created.""" adjoint.Adjoint() + @parameterized.parameters( + list(util.kwargs_cartesian_product(**{ + 'use_cuquantum': [False, True], + }))) + def test_use_cuquantum(self, use_cuquantum): + """Ensure that use_cuquantum switches to cuquantum ops well.""" + if not circuit_execution_ops.is_gpu_configured(): + # Ignores this test if gpu is not configured. + self.skipTest("GPU is not set. Ignoring gpu tests...") + # Prepares a simple circuit. + qubit = cirq.GridQubit(0, 0) + circuit = util.convert_to_tensor( + [cirq.Circuit(cirq.X(qubit)**sympy.Symbol('alpha'))]) + psums = util.convert_to_tensor([[cirq.Z(qubit)]]) + symbol_values_array = np.array([[0.123]], dtype=np.float32) + symbol_values_tensor = tf.convert_to_tensor(symbol_values_array) + + # Mocks `Adjoint.differentiate_analytic*()` to check if + # it's called once correctly. + method_name = ("differentiate_analytic_cuquantum" + if use_cuquantum else "differentiate_analytic") + with mock.patch.object(adjoint.Adjoint, + method_name, + return_value=None, + autospec=True) as mock_adj: + dif = adjoint.Adjoint() + op = circuit_execution_ops.get_expectation_op( + use_cuquantum=use_cuquantum, quantum_concurrent=False) + diff_op = dif.generate_differentiable_op( + analytic_op=op, use_cuquantum=use_cuquantum) + + # Calculate tfq gradient. + with tf.GradientTape() as g: + g.watch(symbol_values_tensor) + expectations = diff_op(circuit, tf.convert_to_tensor(['alpha']), + symbol_values_tensor, psums) + _ = g.gradient(expectations, symbol_values_tensor) + mock_adj.assert_called_once() + def test_sample_errors(self): """Ensure that the adjoint method won't attach to sample ops.""" @@ -40,6 +85,8 @@ def test_sample_errors(self): op = circuit_execution_ops.get_sampled_expectation_op() with self.assertRaisesRegex(ValueError, expected_regex='not supported'): dif.generate_differentiable_op(sampled_op=op) + with self.assertRaisesRegex(ValueError, expected_regex='not supported'): + dif.generate_differentiable_op(sampled_op=op, use_cuquantum=True) def test_no_gradient_circuits(self): """Confirm the adjoint differentiator has no gradient circuits.""" diff --git a/tensorflow_quantum/python/differentiators/differentiator.py b/tensorflow_quantum/python/differentiators/differentiator.py index 40fc15ee9..72ee25e28 100644 --- a/tensorflow_quantum/python/differentiators/differentiator.py +++ b/tensorflow_quantum/python/differentiators/differentiator.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """Testing consistency in values across differentiation methods.""" import abc import inspect @@ -118,6 +118,9 @@ def generate_differentiable_op(self, raise TypeError('Provided arguments must be callable tensorflow ' 'ops.') + if not isinstance(use_cuquantum, bool): + raise TypeError('use_cuquantum should be boolean.') + # TODO (mbbrough): find a better workaround than this to ensure # that the correct sample based expectation wasn't accidentally # put inside of the analytical_op argument or vice versa. @@ -155,8 +158,12 @@ def generate_differentiable_op(self, 'Given arg: {}.'.format(str(key)) + '' 'The signature should contain: {}.'.format( list(expected_signature))) - _differentiate_ana = (self._differentiate_ana_cq - if use_cuquantum else self._differentiate_ana) + if use_cuquantum: + _differentiate_ana, _differentiate_sam = ( + self._differentiate_ana_cq, self._differentiate_sam_cq) + else: + _differentiate_ana, _differentiate_sam = (self._differentiate_ana, + self._differentiate_sam) @tf.custom_gradient def op_wrapper_analytic(programs, symbol_names, symbol_values, @@ -178,10 +185,9 @@ def op_wrapper_sampled(programs, symbol_names, symbol_values, num_samples) def gradient(grad): - return self._differentiate_sam(programs, symbol_names, - symbol_values, pauli_sums, - num_samples, forward_pass_vals, - grad) + return _differentiate_sam(programs, symbol_names, symbol_values, + pauli_sums, num_samples, + forward_pass_vals, grad) return forward_pass_vals, gradient @@ -207,6 +213,13 @@ def _differentiate_ana(self, programs, symbol_names, symbol_values, pauli_sums, forward_pass_vals, grad), \ None + def _differentiate_sam_cq(self, programs, symbol_names, symbol_values, + pauli_sums, num_samples, forward_pass_vals, grad): + return None, None, self.differentiate_sampled_cuquantum( + programs, symbol_names, symbol_values, + pauli_sums, num_samples, forward_pass_vals, grad), \ + None, None + def _differentiate_sam(self, programs, symbol_names, symbol_values, pauli_sums, num_samples, forward_pass_vals, grad): return None, None, self.differentiate_sampled( @@ -340,11 +353,27 @@ def get_gradient_circuits(self, programs, symbol_names, symbol_values): @catch_empty_inputs @tf.function - def differentiate_analytic_cuquantum(self, programs, symbol_names, symbol_values, - pauli_sums, forward_pass_vals, grad): - # `self.expectation_op` is already set to cuquantum op. - return self.differentiate_analytic(programs, symbol_names, symbol_values, - pauli_sums, forward_pass_vals, grad) + def differentiate_analytic_cuquantum(self, programs, symbol_names, + symbol_values, pauli_sums, + forward_pass_vals, grad): + """Differentiate a circuit with analytical expectation with GPU ops.""" + # `self.expectation_op` is already set to cuquantum op at + # generate_differentiable_op._differentiate_ana. + return self.differentiate_analytic(programs, symbol_names, + symbol_values, pauli_sums, + forward_pass_vals, grad) + + @catch_empty_inputs + @tf.function + def differentiate_sampled_cuquantum(self, programs, symbol_names, + symbol_values, pauli_sums, num_samples, + forward_pass_vals, grad): + """Differentiate a circuit with sampled expectation with GPU ops.""" + # `self.expectation_op` is already set to cuquantum op at + # generate_differentiable_op._differentiate_sam. + return self.differentiate_sampled(programs, symbol_names, symbol_values, + pauli_sums, num_samples, + forward_pass_vals, grad) @catch_empty_inputs @tf.function diff --git a/tensorflow_quantum/python/differentiators/differentiator_test.py b/tensorflow_quantum/python/differentiators/differentiator_test.py index 6f21f2e18..43c5f3286 100644 --- a/tensorflow_quantum/python/differentiators/differentiator_test.py +++ b/tensorflow_quantum/python/differentiators/differentiator_test.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """Tests for the differentiator abstract class.""" # Remove PYTHONPATH collisions for protobuf. # pylint: disable=wrong-import-position @@ -72,6 +72,26 @@ def test_generate_differentiable_op(self): WorkingDifferentiator().generate_differentiable_op( sampled_op=lambda programs, symbol_names, pauli_sums: 1) + def test_generate_differentiable_op_cuquantum(self): + """test the type checking on this method with `use_cuquantum`.""" + WorkingDifferentiator().generate_differentiable_op( + analytic_op=lambda programs, symbol_names, symbol_values, + pauli_sums: 1, + use_cuquantum=True) + WorkingDifferentiator().generate_differentiable_op( + sampled_op=lambda programs, symbol_names, symbol_values, pauli_sums, + num_samples: 1, + use_cuquantum=True) + with self.assertRaisesRegex(TypeError, expected_regex='boolean'): + WorkingDifferentiator().generate_differentiable_op( + analytic_op=lambda programs, symbol_names, symbol_values, + pauli_sums: 1, + use_cuquantum='junk') + with self.assertRaisesRegex(TypeError, expected_regex='boolean'): + WorkingDifferentiator().generate_differentiable_op( + sampled_op=lambda programs, symbol_names, pauli_sums: 1, + use_cuquantum='junk') + def test_single_op_link(self): """Tests if the `one-differentiator-per-op` policy is working well.""" wd = WorkingDifferentiator() diff --git a/tensorflow_quantum/python/differentiators/gradient_test.py b/tensorflow_quantum/python/differentiators/gradient_test.py index f666ad801..8db507579 100644 --- a/tensorflow_quantum/python/differentiators/gradient_test.py +++ b/tensorflow_quantum/python/differentiators/gradient_test.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """Testing for gradient calculation consistency in TFQ.""" # Remove PYTHONPATH collisions for protobuf. # pylint: disable=wrong-import-position @@ -36,6 +36,8 @@ from tensorflow_quantum.core.ops.noise import noisy_expectation_op from tensorflow_quantum.core.ops.noise import noisy_sampled_expectation_op +RANDOM_SEED = 1234 + ANALYTIC_DIFFS = [ linear_combination.ForwardDifference(grid_spacing=0.0001), linear_combination.ForwardDifference(error_order=2, grid_spacing=0.0001), @@ -57,12 +59,22 @@ circuit_execution_ops.get_expectation_op() # C++ ] +ANALYTIC_GPU_OPS = [ + circuit_execution_ops.get_expectation_op(use_cuquantum=True, + quantum_concurrent=False) +] + SAMPLED_OPS = [ circuit_execution_ops.get_sampled_expectation_op( cirq.sim.Simulator()), # WF circuit_execution_ops.get_sampled_expectation_op() # C++ ] +SAMPLED_GPU_OPS = [ + circuit_execution_ops.get_sampled_expectation_op(use_cuquantum=True, + quantum_concurrent=False) +] + NOISY_OPS = [ noisy_sampled_expectation_op.sampled_expectation, noisy_expectation_op.expectation @@ -117,19 +129,35 @@ class AnalyticGradientCorrectnessTest(tf.test.TestCase, parameterized.TestCase): @parameterized.parameters( list( - util.kwargs_cartesian_product(**{ - 'differentiator': ANALYTIC_DIFFS, - 'op': ANALYTIC_OPS - })) + [{ - 'differentiator': adjoint.Adjoint(), - 'op': circuit_execution_ops.get_expectation_op() - }]) - def test_backprop(self, differentiator, op): + util.kwargs_cartesian_product( + **{ + 'differentiator': ANALYTIC_DIFFS, + 'op': ANALYTIC_OPS, + 'use_cuquantum': [False], + })) + [{ + 'differentiator': adjoint.Adjoint(), + 'op': circuit_execution_ops.get_expectation_op(), + 'use_cuquantum': False, + }] + + list( + util.kwargs_cartesian_product( + **{ + 'differentiator': ANALYTIC_DIFFS + [adjoint.Adjoint()], + 'op': ANALYTIC_GPU_OPS, + 'use_cuquantum': [True], + }))) + def test_backprop(self, differentiator, op, use_cuquantum): """Test that gradients are correctly backpropagated through a quantum circuit via comparison to analytical results. """ + if use_cuquantum and not circuit_execution_ops.is_gpu_configured(): + # GPU is not set. Ignores this sub-test. + self.skipTest("GPU is not set. Ignoring gpu tests...") differentiator.refresh() - op = differentiator.generate_differentiable_op(analytic_op=op) + op = differentiator.generate_differentiable_op( + analytic_op=op, + use_cuquantum=use_cuquantum, + ) def exact_grad(theta): new_theta = 2 * np.pi * theta @@ -164,23 +192,42 @@ def exact_grad(theta): 'n_qubits': [5], 'n_programs': [3], 'n_ops': [3], - 'symbol_names': [['a', 'b']] + 'symbol_names': [['a', 'b']], + 'use_cuquantum': [False], })) + [{ 'differentiator': adjoint.Adjoint(), 'op': circuit_execution_ops.get_expectation_op(), 'n_qubits': 10, 'n_programs': 5, 'n_ops': 3, - 'symbol_names': ['a', 'b'] - }]) + 'symbol_names': ['a', 'b'], + 'use_cuquantum': False, + }] + + list( + util.kwargs_cartesian_product( + **{ + 'differentiator': ANALYTIC_DIFFS + [adjoint.Adjoint()], + 'op': ANALYTIC_GPU_OPS, + 'n_qubits': [5], + 'n_programs': [3], + 'n_ops': [3], + 'symbol_names': [['a', 'b']], + 'use_cuquantum': [True], + }))) def test_gradients_vs_cirq_finite_difference(self, differentiator, op, n_qubits, n_programs, n_ops, - symbol_names): + symbol_names, use_cuquantum): """Compare TFQ differentiators to fine-grained noiseless cirq finite differencing. """ + if use_cuquantum and not circuit_execution_ops.is_gpu_configured(): + # GPU is not set. Ignores this sub-test. + self.skipTest("GPU is not set. Ignoring gpu tests...") differentiator.refresh() - op = differentiator.generate_differentiable_op(analytic_op=op) + op = differentiator.generate_differentiable_op( + analytic_op=op, + use_cuquantum=use_cuquantum, + ) qubits = cirq.GridQubit.rect(1, n_qubits) circuit_batch, resolver_batch = \ @@ -219,18 +266,39 @@ def test_gradients_vs_cirq_finite_difference(self, differentiator, op, @parameterized.parameters( list( - util.kwargs_cartesian_product(**{ - 'differentiator': ANALYTIC_DIFFS, - 'op': ANALYTIC_OPS, - })) + [{ - 'differentiator': adjoint.Adjoint(), - 'op': circuit_execution_ops.get_expectation_op(), - }]) - def test_analytic_value_with_simple_circuit(self, differentiator, op): + util.kwargs_cartesian_product( + **{ + 'differentiator': ANALYTIC_DIFFS, + 'op': ANALYTIC_OPS, + 'use_cuquantum': [False], + })) + [{ + 'differentiator': adjoint.Adjoint(), + 'op': circuit_execution_ops.get_expectation_op(), + 'use_cuquantum': False, + }] + + list( + util.kwargs_cartesian_product( + **{ + 'differentiator': ANALYTIC_DIFFS + [adjoint.Adjoint()], + 'op': ANALYTIC_GPU_OPS, + 'use_cuquantum': [True], + }))) + def test_analytic_value_with_simple_circuit( + self, + differentiator, + op, + use_cuquantum, + ): """Test the value of differentiator with simple circuit.""" + if use_cuquantum and not circuit_execution_ops.is_gpu_configured(): + # GPU is not set. Ignores this sub-test. + self.skipTest("GPU is not set. Ignoring gpu tests...") # Get an expectation op, with this differentiator attached. differentiator.refresh() - op = differentiator.generate_differentiable_op(analytic_op=op) + op = differentiator.generate_differentiable_op( + analytic_op=op, + use_cuquantum=use_cuquantum, + ) qubit = cirq.GridQubit(0, 0) circuit = util.convert_to_tensor( [cirq.Circuit(cirq.X(qubit)**sympy.Symbol('alpha'))]) @@ -248,15 +316,28 @@ def test_analytic_value_with_simple_circuit(self, differentiator, op): @parameterized.parameters( list( - util.kwargs_cartesian_product(**{ - 'differentiator': ANALYTIC_DIFFS, - 'op': ANALYTIC_OPS, - })) + [{ - 'differentiator': adjoint.Adjoint(), - 'op': circuit_execution_ops.get_expectation_op(), - }]) - def test_empty_circuit_grad(self, differentiator, op): + util.kwargs_cartesian_product( + **{ + 'differentiator': ANALYTIC_DIFFS, + 'op': ANALYTIC_OPS, + 'use_cuquantum': [False], + })) + [{ + 'differentiator': adjoint.Adjoint(), + 'op': circuit_execution_ops.get_expectation_op(), + 'use_cuquantum': False, + }] + + list( + util.kwargs_cartesian_product( + **{ + 'differentiator': ANALYTIC_DIFFS + [adjoint.Adjoint()], + 'op': ANALYTIC_GPU_OPS, + 'use_cuquantum': [True], + }))) + def test_empty_circuit_grad(self, differentiator, op, use_cuquantum): """Test that providing no circuits will fail gracefully.""" + if use_cuquantum and not circuit_execution_ops.is_gpu_configured(): + # GPU is not set. Ignores this sub-test. + self.skipTest("GPU is not set. Ignoring gpu tests...") differentiator.refresh() op = differentiator.generate_differentiable_op(analytic_op=op) circuit = tf.convert_to_tensor([], dtype=tf.string) @@ -283,11 +364,23 @@ class SampledGradientCorrectnessTest(tf.test.TestCase, parameterized.TestCase): **{ 'differentiator': SAMPLED_DIFFS, 'op': SAMPLED_OPS, - 'num_samples': [20000] - }))) + 'num_samples': [20000], + 'use_cuquantum': [False], + })) + list( + util.kwargs_cartesian_product( + **{ + 'differentiator': SAMPLED_DIFFS, + 'op': SAMPLED_GPU_OPS, + 'num_samples': [20000], + 'use_cuquantum': [True], + }))) def test_sampled_value_with_simple_circuit(self, differentiator, op, - num_samples): + num_samples, use_cuquantum): """Test the value of sampled differentiator with simple circuit.""" + if use_cuquantum and not circuit_execution_ops.is_gpu_configured(): + # GPU is not set. Ignores this sub-test. + self.skipTest("GPU is not set. Ignoring gpu tests...") + tf.random.set_seed(RANDOM_SEED) # Get an expectation op, with this differentiator attached. differentiator.refresh() op = differentiator.generate_differentiable_op(sampled_op=op) @@ -317,15 +410,33 @@ def test_sampled_value_with_simple_circuit(self, differentiator, op, 'n_programs': [5], 'n_ops': [2], 'symbol_names': [['a', 'b']], - 'num_samples': [30000] + 'num_samples': [30000], + 'use_cuquantum': [False], + })) + + list( + util.kwargs_cartesian_product( + **{ + 'diff_and_tol': zip(SAMPLED_DIFFS, SAMPLED_DIFFS_TOLS), + 'op': SAMPLED_GPU_OPS, + 'n_qubits': [3], + 'n_programs': [5], + 'n_ops': [2], + 'symbol_names': [['a', 'b']], + 'num_samples': [30000], + 'use_cuquantum': [True], }))) def test_approx_equality_shallow(self, diff_and_tol, op, n_qubits, symbol_names, n_ops, n_programs, - num_samples): + num_samples, use_cuquantum): """Test small circuits with limited depth.""" + if use_cuquantum and not circuit_execution_ops.is_gpu_configured(): + # GPU is not set. Ignores this sub-test. + self.skipTest("GPU is not set. Ignoring gpu tests...") + tf.random.set_seed(RANDOM_SEED) differentiator, tol = diff_and_tol differentiator.refresh() - op = differentiator.generate_differentiable_op(sampled_op=op) + op = differentiator.generate_differentiable_op( + sampled_op=op, use_cuquantum=use_cuquantum) qubits = cirq.GridQubit.rect(1, n_qubits) circuit_batch, resolver_batch = \ @@ -368,12 +479,25 @@ def test_approx_equality_shallow(self, diff_and_tol, op, n_qubits, @parameterized.parameters( list( - util.kwargs_cartesian_product(**{ - 'differentiator': SAMPLED_DIFFS, - 'op': SAMPLED_OPS, - }))) - def test_empty_circuit_sampled_grad(self, differentiator, op): + util.kwargs_cartesian_product( + **{ + 'differentiator': SAMPLED_DIFFS, + 'op': SAMPLED_OPS, + 'use_cuquantum': [False], + })) + list( + util.kwargs_cartesian_product( + **{ + 'differentiator': SAMPLED_DIFFS, + 'op': SAMPLED_GPU_OPS, + 'use_cuquantum': [True], + }))) + def test_empty_circuit_sampled_grad(self, differentiator, op, + use_cuquantum): """Test that providing no circuits will fail gracefully.""" + if use_cuquantum and not circuit_execution_ops.is_gpu_configured(): + # GPU is not set. Ignores this sub-test. + self.skipTest("GPU is not set. Ignoring gpu tests...") + tf.random.set_seed(RANDOM_SEED) differentiator.refresh() op = differentiator.generate_differentiable_op(sampled_op=op) circuit = tf.convert_to_tensor([], dtype=tf.string) diff --git a/tensorflow_quantum/python/differentiators/linear_combination.py b/tensorflow_quantum/python/differentiators/linear_combination.py index dabbd9e34..cee6959bd 100644 --- a/tensorflow_quantum/python/differentiators/linear_combination.py +++ b/tensorflow_quantum/python/differentiators/linear_combination.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """Compute gradients by combining function values linearly.""" import numbers diff --git a/tensorflow_quantum/python/differentiators/linear_combination_test.py b/tensorflow_quantum/python/differentiators/linear_combination_test.py index f46b086e4..944b83937 100644 --- a/tensorflow_quantum/python/differentiators/linear_combination_test.py +++ b/tensorflow_quantum/python/differentiators/linear_combination_test.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """Basic tests for the LinearCombinationDifferentiator""" # Remove PYTHONPATH collisions for protobuf. # pylint: disable=wrong-import-position diff --git a/tensorflow_quantum/python/differentiators/parameter_shift.py b/tensorflow_quantum/python/differentiators/parameter_shift.py index bf1631bba..8a4ef9c3a 100644 --- a/tensorflow_quantum/python/differentiators/parameter_shift.py +++ b/tensorflow_quantum/python/differentiators/parameter_shift.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """Compute analytic gradients by using general parameter-shift rule. """ import tensorflow as tf diff --git a/tensorflow_quantum/python/differentiators/parameter_shift_test.py b/tensorflow_quantum/python/differentiators/parameter_shift_test.py index 5a0846f25..99aea8288 100644 --- a/tensorflow_quantum/python/differentiators/parameter_shift_test.py +++ b/tensorflow_quantum/python/differentiators/parameter_shift_test.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """Basic tests for the ParameterShift differentiator""" # Remove PYTHONPATH collisions for protobuf. # pylint: disable=wrong-import-position diff --git a/tensorflow_quantum/python/differentiators/parameter_shift_util.py b/tensorflow_quantum/python/differentiators/parameter_shift_util.py index 266b3b68e..34889c69a 100644 --- a/tensorflow_quantum/python/differentiators/parameter_shift_util.py +++ b/tensorflow_quantum/python/differentiators/parameter_shift_util.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """Util functions for general parameter-shift rule. """ import numpy as np import tensorflow as tf diff --git a/tensorflow_quantum/python/differentiators/parameter_shift_util_test.py b/tensorflow_quantum/python/differentiators/parameter_shift_util_test.py index 8c1083a10..c2d728a30 100644 --- a/tensorflow_quantum/python/differentiators/parameter_shift_util_test.py +++ b/tensorflow_quantum/python/differentiators/parameter_shift_util_test.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """Basic tests for utility functions for ParameterShift""" # Remove PYTHONPATH collisions for protobuf. # pylint: disable=wrong-import-position diff --git a/tensorflow_quantum/python/layers/__init__.py b/tensorflow_quantum/python/layers/__init__.py index 88f2e5dad..3de402f8d 100644 --- a/tensorflow_quantum/python/layers/__init__.py +++ b/tensorflow_quantum/python/layers/__init__.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """Module definitions for tensorflow_quantum.python.layers.*""" # Utility layers. from tensorflow_quantum.python.layers.circuit_construction import ( diff --git a/tensorflow_quantum/python/layers/circuit_construction/__init__.py b/tensorflow_quantum/python/layers/circuit_construction/__init__.py index 0c5ded5c5..765f26e83 100644 --- a/tensorflow_quantum/python/layers/circuit_construction/__init__.py +++ b/tensorflow_quantum/python/layers/circuit_construction/__init__.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """Module for tfq.python.layers.circuit_construction.*""" # pylint: disable=line-too-long diff --git a/tensorflow_quantum/python/layers/circuit_construction/elementary.py b/tensorflow_quantum/python/layers/circuit_construction/elementary.py index 66714f800..13574c435 100644 --- a/tensorflow_quantum/python/layers/circuit_construction/elementary.py +++ b/tensorflow_quantum/python/layers/circuit_construction/elementary.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """Elementary layers, such as the AddCircuit layer.""" import numpy as np import tensorflow as tf diff --git a/tensorflow_quantum/python/layers/circuit_construction/elementary_test.py b/tensorflow_quantum/python/layers/circuit_construction/elementary_test.py index 38577dbe9..e4aa63f1c 100644 --- a/tensorflow_quantum/python/layers/circuit_construction/elementary_test.py +++ b/tensorflow_quantum/python/layers/circuit_construction/elementary_test.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """Tests for the elementary layers.""" # Remove PYTHONPATH collisions for protobuf. # pylint: disable=wrong-import-position diff --git a/tensorflow_quantum/python/layers/circuit_executors/__init__.py b/tensorflow_quantum/python/layers/circuit_executors/__init__.py index 74d26d3e0..0ce744835 100644 --- a/tensorflow_quantum/python/layers/circuit_executors/__init__.py +++ b/tensorflow_quantum/python/layers/circuit_executors/__init__.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """Module for tfq.python.layers.circuit_executors.*""" # pylint: disable=line-too-long diff --git a/tensorflow_quantum/python/layers/circuit_executors/expectation.py b/tensorflow_quantum/python/layers/circuit_executors/expectation.py index 22e91204d..cba81e7b5 100644 --- a/tensorflow_quantum/python/layers/circuit_executors/expectation.py +++ b/tensorflow_quantum/python/layers/circuit_executors/expectation.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """A tf.keras.layer that ingests programs and outputs expectation values.""" import numbers @@ -285,15 +285,20 @@ def call(self, symbol_values=None, operators=None, repetitions=None, - initializer=tf.keras.initializers.RandomUniform(0, 2 * np.pi)): + initializer=None): """Keras call function. - Input options: - `inputs`, `symbol_names`, `symbol_values`: - see `input_checks.expand_circuits` - `operators`: see `input_checks.expand_operators` - - Output shape: + Args: + inputs: See `input_checks.expand_circuits. + symbol_names: See `input_checks.expand_circuits. + symbol_values: See `input_checks.expand_circuits. + operators: See `input_checks.expand_operators` + repetitions: A Python `int` or a pre-converted `tf.Tensor` + containing a single `int` entry. + initializer: The keras initializer object for weights. + Defaults to uniform distribution [0..2*pi] + + Returns: `tf.Tensor` with shape [batch_size, n_ops] that holds the expectation value for each circuit with each op applied to it (after resolving the corresponding parameters in). @@ -302,6 +307,9 @@ def call(self, if symbol_values is None: values_empty = True + if initializer is None: + initializer = tf.keras.initializers.RandomUniform(0, 2 * np.pi) + inputs, symbol_names, symbol_values = input_checks.expand_circuits( inputs, symbol_names, symbol_values) diff --git a/tensorflow_quantum/python/layers/circuit_executors/expectation_test.py b/tensorflow_quantum/python/layers/circuit_executors/expectation_test.py index 1b6a6a98d..1dce8cb98 100644 --- a/tensorflow_quantum/python/layers/circuit_executors/expectation_test.py +++ b/tensorflow_quantum/python/layers/circuit_executors/expectation_test.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """Tests for tensorflow_quantum.layers.circuit_executors.expectation.""" # Remove PYTHONPATH collisions for protobuf. # pylint: disable=wrong-import-position @@ -26,10 +26,13 @@ import tensorflow as tf import cirq +from tensorflow_quantum.core.ops import circuit_execution_ops from tensorflow_quantum.python.layers.circuit_executors import expectation from tensorflow_quantum.python.differentiators import linear_combination from tensorflow_quantum.python import util +RANDOM_SEED = 1234 + def _gen_single_bit_rotation_problem(bit, symbols, noisy): """Generate a toy problem on 1 qubit.""" @@ -47,7 +50,7 @@ def _gen_single_bit_rotation_problem(bit, symbols, noisy): return circuit -class ExpectationTest(tf.test.TestCase): +class ExpectationTest(parameterized.TestCase, tf.test.TestCase): """Basic tests for the expectation layer.""" def test_expectation_instantiate(self): @@ -282,10 +285,17 @@ def test_static_cases_noisy(self): ], [cirq.Z(bit), cirq.Z(bit), cirq.Z(bit)]], repetitions=[[1, 2, 3], [4, 5, 6]]) - def test_expectation_simple_tf_train(self): + @parameterized.parameters([{ + 'use_cuquantum': False, + }, { + 'use_cuquantum': True, + }]) + def test_expectation_simple_tf_train(self, use_cuquantum): """Train a layer using standard tf (not keras). This is a subtle test that will work since we don't use keras compile. """ + tf.random.set_seed(RANDOM_SEED) + initializer = tf.keras.initializers.RandomUniform(0, 2 * np.pi) bit = cirq.GridQubit(0, 0) circuit = \ cirq.Circuit(cirq.rx(sympy.Symbol('theta'))(bit)) @@ -296,7 +306,8 @@ def test_expectation_simple_tf_train(self): with tf.GradientTape() as tape: circuit_out = layer(circuit, symbol_names=['theta'], - operators=op) + operators=op, + initializer=initializer) mse = tf.square(tf.reduce_sum(tf.subtract(circuit_out, -1))) grads = tape.gradient(mse, layer.trainable_weights) optimizer.apply_gradients(zip(grads, layer.trainable_weights)) @@ -327,6 +338,11 @@ def test_simple_param_value_input(self, backend, use_cuquantum): state given the input zero or one. This tests the input signature: Expectation([input_value_batch]). """ + if use_cuquantum and not circuit_execution_ops.is_gpu_configured(): + # GPU is not set. Ignores this sub-test. + self.skipTest("GPU is not set. Ignoring gpu tests...") + tf.random.set_seed(RANDOM_SEED) + initializer = tf.keras.initializers.RandomUniform(0, 2 * np.pi) noisy = backend == 'noisy' bit = cirq.GridQubit(0, 0) symbols = sympy.symbols('x y z') @@ -344,7 +360,8 @@ def test_simple_param_value_input(self, backend, use_cuquantum): symbol_names=symbols, operators=cirq.Z(bit), symbol_values=l2, - repetitions=reps) + repetitions=reps, + initializer=initializer) model = tf.keras.Model(inputs=[datum, inputs], outputs=outputs) data_in = np.array([[1], [0]], dtype=np.float32) @@ -379,6 +396,11 @@ def test_simple_op_input(self, backend, use_cuquantum): Learn qubit in the z+ state using two different measurement operators. This tests input signature Expectation([operator_batch]) """ + if use_cuquantum and not circuit_execution_ops.is_gpu_configured(): + # GPU is not set. Ignores this sub-test. + self.skipTest("GPU is not set. Ignoring gpu tests...") + tf.random.set_seed(RANDOM_SEED) + normal_initializer = tf.keras.initializers.RandomNormal() noisy = backend == 'noisy' bit = cirq.GridQubit(0, 0) symbols = sympy.symbols('x, y, z') @@ -399,7 +421,7 @@ def test_simple_op_input(self, backend, use_cuquantum): )(circuit_input, symbol_names=symbols, operators=op_input, - initializer=tf.keras.initializers.RandomNormal(), + initializer=normal_initializer, repetitions=reps) model = tf.keras.Model( @@ -443,6 +465,11 @@ def test_simple_op_and_param_input(self, backend, use_cuquantum): binary input. This tests the input signature: Expectation([value_batch, operator_batch]). """ + if use_cuquantum and not circuit_execution_ops.is_gpu_configured(): + # GPU is not set. Ignores this sub-test. + self.skipTest("GPU is not set. Ignoring gpu tests...") + tf.random.set_seed(RANDOM_SEED) + initializer = tf.keras.initializers.RandomUniform(0, 2 * np.pi) noisy = backend == 'noisy' bit = cirq.GridQubit(0, 0) symbols = sympy.symbols('x, y, z') @@ -465,7 +492,8 @@ def test_simple_op_and_param_input(self, backend, use_cuquantum): symbol_names=symbols, symbol_values=dense_2, operators=op_inp, - repetitions=reps) + repetitions=reps, + initializer=initializer) functional_model = tf.keras.Model( inputs=[data_inp, op_inp, circuit_inp], outputs=[circuit_output]) @@ -500,6 +528,12 @@ def test_dnn_qnn_dnn(self, backend, use_cuquantum): Train the network to output +-5 given an input of 1 or 0. This tests that everything works when Expectation layer is a middle layers. """ + if use_cuquantum and not circuit_execution_ops.is_gpu_configured(): + # GPU is not set. Ignores this sub-test. + self.skipTest("GPU is not set. Ignoring gpu tests...") + tf.random.set_seed(RANDOM_SEED) + initializer = tf.keras.initializers.RandomUniform(0, 2 * np.pi) + noisy = backend == 'noisy' bit = cirq.GridQubit(0, 0) symbols = sympy.symbols('x, y, z') @@ -520,7 +554,8 @@ def test_dnn_qnn_dnn(self, backend, use_cuquantum): symbol_names=symbols, symbol_values=d2, operators=cirq.Z(bit), - repetitions=reps) + repetitions=reps, + initializer=initializer) d3 = tf.keras.layers.Dense(1)(quantum) model = tf.keras.Model(inputs=[circuit_input, classical_input], diff --git a/tensorflow_quantum/python/layers/circuit_executors/input_checks.py b/tensorflow_quantum/python/layers/circuit_executors/input_checks.py index b73fbde26..9855b5b74 100644 --- a/tensorflow_quantum/python/layers/circuit_executors/input_checks.py +++ b/tensorflow_quantum/python/layers/circuit_executors/input_checks.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """Input checks common to circuit execution layers.""" import numpy as np import sympy diff --git a/tensorflow_quantum/python/layers/circuit_executors/input_checks_test.py b/tensorflow_quantum/python/layers/circuit_executors/input_checks_test.py index affbd55d7..29d9f86b1 100644 --- a/tensorflow_quantum/python/layers/circuit_executors/input_checks_test.py +++ b/tensorflow_quantum/python/layers/circuit_executors/input_checks_test.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """Tests for tensorflow_quantum.layers.circuit_executors.input_checks.""" # Remove PYTHONPATH collisions for protobuf. # pylint: disable=wrong-import-position diff --git a/tensorflow_quantum/python/layers/circuit_executors/sample.py b/tensorflow_quantum/python/layers/circuit_executors/sample.py index 80f27bafe..3ba53c6bf 100644 --- a/tensorflow_quantum/python/layers/circuit_executors/sample.py +++ b/tensorflow_quantum/python/layers/circuit_executors/sample.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """A tf.keras.layer that ingests programs and outputs bitstring samples.""" import numbers @@ -179,17 +179,18 @@ def call(self, repetitions=None): """Keras call function. - Input options: - `inputs`, `symbol_names`, `symbol_values`: - see `input_checks.expand_circuits` - `repetitions`: a Python `int` or a pre-converted - `tf.Tensor` containing a single `int` entry. + Args: + inputs: See `input_checks.expand_circuits`. + symbol_names: See `input_checks.expand_circuits`. + symbol_values: See `input_checks.expand_circuits`. + repetitions: A Python `int` or a pre-converted `tf.Tensor` + containing a single `int` entry. - Output shape: + Returns: `tf.RaggedTensor` with shape: - [batch size of symbol_values, repetitions, ] - or - [number of circuits, repetitions, ] + [batch size of symbol_values, repetitions, ] + or + [number of circuits, repetitions, ] """ if repetitions is None: raise ValueError("Number of repetitions not specified.") diff --git a/tensorflow_quantum/python/layers/circuit_executors/sample_test.py b/tensorflow_quantum/python/layers/circuit_executors/sample_test.py index cb05d5242..a5b78cb60 100644 --- a/tensorflow_quantum/python/layers/circuit_executors/sample_test.py +++ b/tensorflow_quantum/python/layers/circuit_executors/sample_test.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """Tests for the sample layer.""" # Remove PYTHONPATH collisions for protobuf. # pylint: disable=wrong-import-position @@ -26,9 +26,12 @@ import tensorflow as tf import cirq +from tensorflow_quantum.core.ops import circuit_execution_ops from tensorflow_quantum.python.layers.circuit_executors import sample from tensorflow_quantum.python import util +RANDOM_SEED = 1234 + class SampleTest(tf.test.TestCase, parameterized.TestCase): """Tests for the Sample layer.""" @@ -107,6 +110,9 @@ def test_sample_invalid_shape_inputs(self): ]) def test_sample_invalid_combinations(self, backend, use_cuquantum): """Test with valid type inputs and valid value, but incorrect combo.""" + if use_cuquantum and not circuit_execution_ops.is_gpu_configured(): + # GPU is not set. Ignores this sub-test. + self.skipTest("GPU is not set. Ignoring gpu tests...") sampler = sample.Sample(backend, use_cuquantum=use_cuquantum) symbol = sympy.Symbol('alpha') circuit = cirq.Circuit(cirq.H(cirq.GridQubit(0, 0))**symbol) @@ -149,9 +155,17 @@ def test_sample_invalid_combinations(self, backend, use_cuquantum): symbol_values=np.zeros((3, 1)), repetitions=5) - def test_sample_basic_inputs(self): + @parameterized.parameters([{ + 'use_cuquantum': False, + }, { + 'use_cuquantum': True, + }]) + def test_sample_basic_inputs(self, use_cuquantum): """Test that sample ingests inputs correctly in simple settings.""" - sampler = sample.Sample() + if use_cuquantum and not circuit_execution_ops.is_gpu_configured(): + # GPU is not set. Ignores this sub-test. + self.skipTest("GPU is not set. Ignoring gpu tests...") + sampler = sample.Sample(use_cuquantum=use_cuquantum) sampler(cirq.Circuit(), repetitions=10) sampler([cirq.Circuit()], repetitions=10) sampler(cirq.Circuit(), @@ -163,9 +177,17 @@ def test_sample_basic_inputs(self): symbol_values=[[0.5]], repetitions=10) - def test_sample_outputs_simple(self): + @parameterized.parameters([{ + 'use_cuquantum': False, + }, { + 'use_cuquantum': True, + }]) + def test_sample_outputs_simple(self, use_cuquantum): """Test the simplest call where nothing but circuits are provided.""" - sampler = sample.Sample() + if use_cuquantum and not circuit_execution_ops.is_gpu_configured(): + # GPU is not set. Ignores this sub-test. + self.skipTest("GPU is not set. Ignoring gpu tests...") + sampler = sample.Sample(use_cuquantum=use_cuquantum) circuit = cirq.Circuit(cirq.H(cirq.GridQubit(0, 0))) output = sampler([circuit, circuit], repetitions=5) self.assertShapeEqual(np.empty((2, 5, 1)), output.to_tensor()) @@ -188,6 +210,10 @@ def test_sample_output(self, backend, use_cuquantum, all_n_qubits, cause what is output from the layer to structurally deviate from what is expected. """ + if use_cuquantum and not circuit_execution_ops.is_gpu_configured(): + # GPU is not set. Ignores this sub-test. + self.skipTest("GPU is not set. Ignoring gpu tests...") + tf.random.set_seed(RANDOM_SEED) if use_cuquantum: # If use_cuquantum is True, if backend is not None and backend != 'noiseless': diff --git a/tensorflow_quantum/python/layers/circuit_executors/sampled_expectation.py b/tensorflow_quantum/python/layers/circuit_executors/sampled_expectation.py index 454fb61f1..0fdcc421f 100644 --- a/tensorflow_quantum/python/layers/circuit_executors/sampled_expectation.py +++ b/tensorflow_quantum/python/layers/circuit_executors/sampled_expectation.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """A tf.keras.layer that ingests programs and outputs sampled expectation values .""" import numbers @@ -280,25 +280,31 @@ def call(self, symbol_values=None, operators=None, repetitions=None, - initializer=tf.keras.initializers.RandomUniform(0, 2 * np.pi)): + initializer=None): """Keras call function. - Input options: - `inputs`, `symbol_names`, `symbol_values`: - see `input_checks.expand_circuits` - `operators`: see `input_checks.expand_operators` - `repetitions`: a Python `int` or a pre-converted - `tf.Tensor` containing a single `int` entry. - - Output shape: + Args: + inputs: See `input_checks.expand_circuits. + symbol_names: See `input_checks.expand_circuits. + symbol_values: See `input_checks.expand_circuits. + operators: See `input_checks.expand_operators` + repetitions: A Python `int` or a pre-converted `tf.Tensor` + containing a single `int` entry. + initializer: The keras initializer object for weights. + Defaults to uniform distribution [0..2*pi] + + Returns: `tf.Tensor` with shape [batch_size, n_ops] that holds the - expectation value for each circuit with each op applied to it - (after resolving the corresponding parameters in). + expectation value for each circuit with each op applied to it + (after resolving the corresponding parameters in). """ values_empty = False if symbol_values is None: values_empty = True + if initializer is None: + initializer = tf.keras.initializers.RandomUniform(0, 2 * np.pi) + inputs, symbol_names, symbol_values = input_checks.expand_circuits( inputs, symbol_names, symbol_values) diff --git a/tensorflow_quantum/python/layers/circuit_executors/sampled_expectation_test.py b/tensorflow_quantum/python/layers/circuit_executors/sampled_expectation_test.py index e693068fc..1699c47b4 100644 --- a/tensorflow_quantum/python/layers/circuit_executors/sampled_expectation_test.py +++ b/tensorflow_quantum/python/layers/circuit_executors/sampled_expectation_test.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """Tests for tensorflow_quantum.layers.circuit_executors.sampled_expectation.""" # Remove PYTHONPATH collisions for protobuf. # pylint: disable=wrong-import-position @@ -26,11 +26,14 @@ import tensorflow as tf import cirq +from tensorflow_quantum.core.ops import circuit_execution_ops from tensorflow_quantum.python.layers.circuit_executors import \ sampled_expectation from tensorflow_quantum.python.differentiators import linear_combination from tensorflow_quantum.python import util +RANDOM_SEED = 1234 + class CustomSampler(cirq.Sampler): """Wrapper for cirq.Simulator to confirm that custom samplers work.""" @@ -128,6 +131,9 @@ def simulate_sweep(self): def test_sampled_expectation_type_inputs_error(self, backend, use_cuquantum): """Test that SampledExpectation errors within Keras call.""" + if use_cuquantum and not circuit_execution_ops.is_gpu_configured(): + # GPU is not set. Ignores this sub-test. + self.skipTest("GPU is not set. Ignoring gpu tests...") bit = cirq.GridQubit(0, 0) symbol = sympy.Symbol('alpha') @@ -195,6 +201,10 @@ def test_sampled_expectation_type_inputs_error(self, backend, ]) def test_sampled_expectation_op_error(self, backend, use_cuquantum): """Test that expectation errors within underlying ops correctly.""" + if use_cuquantum and not circuit_execution_ops.is_gpu_configured(): + # GPU is not set. Ignores this sub-test. + self.skipTest("GPU is not set. Ignoring gpu tests...") + # Note the expected_regex is left blank here since there is a # discrepancy between the error strings provided between backends. bit = cirq.GridQubit(0, 0) @@ -298,6 +308,9 @@ def test_sampled_expectation_op_error(self, backend, use_cuquantum): ]) def test_static_cases(self, backend, use_cuquantum): """Run inputs through in complex cases.""" + if use_cuquantum and not circuit_execution_ops.is_gpu_configured(): + # GPU is not set. Ignores this sub-test. + self.skipTest("GPU is not set. Ignoring gpu tests...") bit = cirq.GridQubit(0, 0) symbol = sympy.Symbol('alpha') @@ -379,18 +392,30 @@ def test_static_cases(self, backend, use_cuquantum): cirq.X(bit) + 2.0 * cirq.Z(bit)], repetitions=[5, 1]) - def test_sampled_expectation_simple_tf_train(self): + @parameterized.parameters([{ + 'use_cuquantum': False, + }, { + 'use_cuquantum': True, + }]) + def test_sampled_expectation_simple_tf_train(self, use_cuquantum): """Train a layer using standard tf (not keras).""" + if use_cuquantum and not circuit_execution_ops.is_gpu_configured(): + # GPU is not set. Ignores this sub-test. + self.skipTest("GPU is not set. Ignoring gpu tests...") + tf.random.set_seed(RANDOM_SEED) + initializer = tf.keras.initializers.RandomUniform(0, 2*np.pi) bit = cirq.GridQubit(0, 0) circuit = cirq.Circuit(cirq.rx(sympy.Symbol('theta'))(bit)) - layer = sampled_expectation.SampledExpectation() + layer = sampled_expectation.SampledExpectation( + use_cuquantum=use_cuquantum) optimizer = tf.optimizers.Adam(learning_rate=0.05) - for _ in range(10): + for _ in range(20): with tf.GradientTape() as tape: circuit_out = layer(circuit, symbol_names=['theta'], operators=cirq.Z(bit), - repetitions=100) + repetitions=100, + initializer=initializer) mse = tf.square(tf.reduce_sum(tf.subtract(circuit_out, -1))) grads = tape.gradient(mse, layer.trainable_weights) optimizer.apply_gradients(zip(grads, layer.trainable_weights)) @@ -417,6 +442,11 @@ def test_simple_param_value_input(self, backend, use_cuquantum): This model will put a qubit in the zero or one state from a random state given the input zero or one. """ + if use_cuquantum and not circuit_execution_ops.is_gpu_configured(): + # GPU is not set. Ignores this sub-test. + self.skipTest("GPU is not set. Ignoring gpu tests...") + tf.random.set_seed(RANDOM_SEED) + initializer = tf.keras.initializers.RandomUniform(0, 2*np.pi) bit = cirq.GridQubit(0, 0) symbols = sympy.symbols('x y z') circuit = _gen_single_bit_rotation_problem( @@ -433,7 +463,8 @@ def test_simple_param_value_input(self, backend, use_cuquantum): symbol_names=symbols, operators=cirq.Z(bit), symbol_values=l2, - repetitions=5000) + repetitions=5000, + initializer=initializer) model = tf.keras.Model(inputs=[datum, inputs], outputs=outputs) data_in = np.array([[1], [0]], dtype=np.float32) @@ -462,6 +493,11 @@ def test_simple_op_input(self, backend, use_cuquantum): Learn qubit in the z+ state using two different measurement operators. """ + if use_cuquantum and not circuit_execution_ops.is_gpu_configured(): + # GPU is not set. Ignores this sub-test. + self.skipTest("GPU is not set. Ignoring gpu tests...") + tf.random.set_seed(RANDOM_SEED) + initializer = tf.keras.initializers.RandomUniform(0, 2*np.pi) bit = cirq.GridQubit(0, 0) symbols = sympy.symbols('x y z') ops = util.convert_to_tensor([[cirq.Z(bit)], [cirq.Z(bit)]]) @@ -482,7 +518,8 @@ def test_simple_op_input(self, backend, use_cuquantum): )(circuit_inp, symbol_names=symbols, operators=op_inp, - repetitions=n_inp) + repetitions=n_inp, + initializer=initializer) model = tf.keras.Model(inputs=[circuit_inp, op_inp, n_inp], outputs=[circuit_output]) @@ -513,6 +550,11 @@ def test_simple_op_and_param_input(self, backend, use_cuquantum): Train a NN to put a qubit in the z+ or x+ states based on a classical binary input. """ + if use_cuquantum and not circuit_execution_ops.is_gpu_configured(): + # GPU is not set. Ignores this sub-test. + self.skipTest("GPU is not set. Ignoring gpu tests...") + tf.random.set_seed(RANDOM_SEED) + initializer = tf.keras.initializers.RandomUniform(0, 2*np.pi) bit = cirq.GridQubit(0, 0) symbols = sympy.symbols('x y z') ops = util.convert_to_tensor([[cirq.Z(bit)], [cirq.Z(bit)]]) @@ -537,7 +579,8 @@ def test_simple_op_and_param_input(self, backend, use_cuquantum): symbol_names=symbols, symbol_values=dense_2, operators=op_inp, - repetitions=n_inp) + repetitions=n_inp, + initializer=initializer) functional_model = tf.keras.Model( inputs=[circuit_inp, data_inp, op_inp, n_inp], @@ -568,6 +611,11 @@ def test_dnn_qnn_dnn(self, backend, use_cuquantum): Train the network to output +-5 given an input of 1 or 0. This tests that everything works when SampledExpectation layer is a middle layers. """ + if use_cuquantum and not circuit_execution_ops.is_gpu_configured(): + # GPU is not set. Ignores this sub-test. + self.skipTest("GPU is not set. Ignoring gpu tests...") + tf.random.set_seed(RANDOM_SEED) + initializer = tf.keras.initializers.RandomUniform(0, 2*np.pi) bit = cirq.GridQubit(0, 0) symbols = sympy.symbols('x, y, z') circuits = util.convert_to_tensor([ @@ -588,7 +636,8 @@ def test_dnn_qnn_dnn(self, backend, use_cuquantum): symbol_names=symbols, symbol_values=d2, operators=cirq.Z(bit), - repetitions=5000) + repetitions=5000, + initializer=initializer) d3 = tf.keras.layers.Dense(1)(quantum) model = tf.keras.Model(inputs=[circuit_input, classical_input], diff --git a/tensorflow_quantum/python/layers/circuit_executors/state.py b/tensorflow_quantum/python/layers/circuit_executors/state.py index d9219fbab..456a83463 100644 --- a/tensorflow_quantum/python/layers/circuit_executors/state.py +++ b/tensorflow_quantum/python/layers/circuit_executors/state.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """A tf.keras.layer that ingests programs and parameters and outputs a state.""" import tensorflow as tf @@ -150,11 +150,12 @@ def __init__(self, backend=None, use_cuquantum=False, **kwargs): def call(self, inputs, *, symbol_names=None, symbol_values=None): """Keras call function. - Input options: - `inputs`, `symbol_names`, `symbol_values`: - see `input_checks.expand_circuits` + Args: + inputs: See `input_checks.expand_circuits. + symbol_names: See `input_checks.expand_circuits. + symbol_values: See `input_checks.expand_circuits. - Output shape: + Returns: `tf.RaggedTensor` with shape: [batch size of symbol_values, ] or diff --git a/tensorflow_quantum/python/layers/circuit_executors/state_test.py b/tensorflow_quantum/python/layers/circuit_executors/state_test.py index 08980c937..34a5ab06c 100644 --- a/tensorflow_quantum/python/layers/circuit_executors/state_test.py +++ b/tensorflow_quantum/python/layers/circuit_executors/state_test.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """Tests for tensorflow_quantum.layers.circuit_executors.state.""" # Remove PYTHONPATH collisions for protobuf. # pylint: disable=wrong-import-position @@ -26,6 +26,7 @@ import tensorflow as tf import cirq +from tensorflow_quantum.core.ops import circuit_execution_ops from tensorflow_quantum.python.layers.circuit_executors import state from tensorflow_quantum.python import util @@ -59,7 +60,10 @@ def test_state_create(self): }]) def test_state_invalid_combinations(self, backend, use_cuquantum): """Test with valid type inputs and valid value, but incorrect combo.""" - state_calc = state.State(backend, use_cuquantum) + if use_cuquantum and not circuit_execution_ops.is_gpu_configured(): + # GPU is not set. Ignores this sub-test. + self.skipTest("GPU is not set. Ignoring gpu tests...") + state_calc = state.State(backend, use_cuquantum=use_cuquantum) symbol = sympy.Symbol('alpha') circuit = cirq.Circuit(cirq.H(cirq.GridQubit(0, 0))**symbol) with self.assertRaisesRegex(Exception, expected_regex=""): @@ -142,6 +146,9 @@ def test_state_output(self, backend_output, use_cuquantum): post processing done inside the layers should not cause output from the layer to structurally deviate from what is expected. """ + if use_cuquantum and not circuit_execution_ops.is_gpu_configured(): + # GPU is not set. Ignores this sub-test. + self.skipTest("GPU is not set. Ignoring gpu tests...") backend = backend_output[0] output = backend_output[1] state_executor = state.State( diff --git a/tensorflow_quantum/python/layers/circuit_executors/unitary.py b/tensorflow_quantum/python/layers/circuit_executors/unitary.py index 34e9385f7..73bd40c83 100644 --- a/tensorflow_quantum/python/layers/circuit_executors/unitary.py +++ b/tensorflow_quantum/python/layers/circuit_executors/unitary.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """A tf.keras.layer that ingests programs and outputs a unitary.""" import tensorflow as tf diff --git a/tensorflow_quantum/python/layers/circuit_executors/unitary_test.py b/tensorflow_quantum/python/layers/circuit_executors/unitary_test.py index 7330c807f..aaaf968f9 100644 --- a/tensorflow_quantum/python/layers/circuit_executors/unitary_test.py +++ b/tensorflow_quantum/python/layers/circuit_executors/unitary_test.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """Tests for tensorflow_quantum.layers.circuit_executors.unitary.""" # Remove PYTHONPATH collisions for protobuf. # pylint: disable=wrong-import-position diff --git a/tensorflow_quantum/python/layers/high_level/__init__.py b/tensorflow_quantum/python/layers/high_level/__init__.py index 2f7bd6580..19e1a000b 100644 --- a/tensorflow_quantum/python/layers/high_level/__init__.py +++ b/tensorflow_quantum/python/layers/high_level/__init__.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """Module for tfq.python.layers.high_level.*""" # pylint: disable=line-too-long diff --git a/tensorflow_quantum/python/layers/high_level/controlled_pqc.py b/tensorflow_quantum/python/layers/high_level/controlled_pqc.py index b35e4f69b..7a781f852 100644 --- a/tensorflow_quantum/python/layers/high_level/controlled_pqc.py +++ b/tensorflow_quantum/python/layers/high_level/controlled_pqc.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """Module for tfq.python.layers.high_level.controlled_pqc layer.""" import numbers import numpy as np diff --git a/tensorflow_quantum/python/layers/high_level/controlled_pqc_test.py b/tensorflow_quantum/python/layers/high_level/controlled_pqc_test.py index 0d9e76e7e..ed6447d5e 100644 --- a/tensorflow_quantum/python/layers/high_level/controlled_pqc_test.py +++ b/tensorflow_quantum/python/layers/high_level/controlled_pqc_test.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """Test module for tfq.python.layers.high_level.controlled_pqc layer.""" # Remove PYTHONPATH collisions for protobuf. # pylint: disable=wrong-import-position diff --git a/tensorflow_quantum/python/layers/high_level/noisy_controlled_pqc.py b/tensorflow_quantum/python/layers/high_level/noisy_controlled_pqc.py index 203a9cc10..2d6565dfc 100644 --- a/tensorflow_quantum/python/layers/high_level/noisy_controlled_pqc.py +++ b/tensorflow_quantum/python/layers/high_level/noisy_controlled_pqc.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """Module for tfq.python.layers.high_level.noisy_controlled_pqc layer.""" import numbers import numpy as np diff --git a/tensorflow_quantum/python/layers/high_level/noisy_controlled_pqc_test.py b/tensorflow_quantum/python/layers/high_level/noisy_controlled_pqc_test.py index 57ecf6cff..ee45937aa 100644 --- a/tensorflow_quantum/python/layers/high_level/noisy_controlled_pqc_test.py +++ b/tensorflow_quantum/python/layers/high_level/noisy_controlled_pqc_test.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """Test module for tfq.python.layers.high_level.controlled_pqc layer.""" # Remove PYTHONPATH collisions for protobuf. # pylint: disable=wrong-import-position diff --git a/tensorflow_quantum/python/layers/high_level/noisy_pqc.py b/tensorflow_quantum/python/layers/high_level/noisy_pqc.py index 3cfdb6082..0c72668ce 100644 --- a/tensorflow_quantum/python/layers/high_level/noisy_pqc.py +++ b/tensorflow_quantum/python/layers/high_level/noisy_pqc.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """Module for tfq.python.layers.high_level.noisy_pqc layer.""" import numbers import numpy as np diff --git a/tensorflow_quantum/python/layers/high_level/noisy_pqc_test.py b/tensorflow_quantum/python/layers/high_level/noisy_pqc_test.py index 112838912..c1997daab 100644 --- a/tensorflow_quantum/python/layers/high_level/noisy_pqc_test.py +++ b/tensorflow_quantum/python/layers/high_level/noisy_pqc_test.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """Test module for tfq.python.layers.high_level.noisy_pqc layer.""" # Remove PYTHONPATH collisions for protobuf. # pylint: disable=wrong-import-position diff --git a/tensorflow_quantum/python/layers/high_level/pqc.py b/tensorflow_quantum/python/layers/high_level/pqc.py index 7d05cc922..a4c5c3f05 100644 --- a/tensorflow_quantum/python/layers/high_level/pqc.py +++ b/tensorflow_quantum/python/layers/high_level/pqc.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """Module for tfq.python.layers.high_level.pqc layer.""" import numbers import numpy as np diff --git a/tensorflow_quantum/python/layers/high_level/pqc_test.py b/tensorflow_quantum/python/layers/high_level/pqc_test.py index e6d831c66..bae9e6d76 100644 --- a/tensorflow_quantum/python/layers/high_level/pqc_test.py +++ b/tensorflow_quantum/python/layers/high_level/pqc_test.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """Test module for tfq.python.layers.high_level.pqc layer.""" # Remove PYTHONPATH collisions for protobuf. # pylint: disable=wrong-import-position diff --git a/tensorflow_quantum/python/optimizers/__init__.py b/tensorflow_quantum/python/optimizers/__init__.py index d93023205..1a1d97d41 100755 --- a/tensorflow_quantum/python/optimizers/__init__.py +++ b/tensorflow_quantum/python/optimizers/__init__.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """Module definitions for tensorflow_quantum.python.optimizers.*""" # Quantum circuit specific optimizers. diff --git a/tensorflow_quantum/python/optimizers/rotosolve_minimizer.py b/tensorflow_quantum/python/optimizers/rotosolve_minimizer.py index 5bf23f6a0..3376cd20e 100755 --- a/tensorflow_quantum/python/optimizers/rotosolve_minimizer.py +++ b/tensorflow_quantum/python/optimizers/rotosolve_minimizer.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """The rotosolve minimization algorithm.""" import numpy as np import tensorflow as tf diff --git a/tensorflow_quantum/python/optimizers/rotosolve_minimizer_test.py b/tensorflow_quantum/python/optimizers/rotosolve_minimizer_test.py index b7d8a454e..ee49ba7b1 100755 --- a/tensorflow_quantum/python/optimizers/rotosolve_minimizer_test.py +++ b/tensorflow_quantum/python/optimizers/rotosolve_minimizer_test.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """Test module for tfq.python.optimizers.rotosolve_minimizer optimizer.""" # Remove PYTHONPATH collisions for protobuf. # pylint: disable=wrong-import-position diff --git a/tensorflow_quantum/python/optimizers/spsa_minimizer.py b/tensorflow_quantum/python/optimizers/spsa_minimizer.py index 471b46d9e..10a915ee0 100644 --- a/tensorflow_quantum/python/optimizers/spsa_minimizer.py +++ b/tensorflow_quantum/python/optimizers/spsa_minimizer.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """The SPSA minimization algorithm.""" import tensorflow as tf import numpy as np diff --git a/tensorflow_quantum/python/optimizers/spsa_minimizer_test.py b/tensorflow_quantum/python/optimizers/spsa_minimizer_test.py index a71f25101..f6769e0e4 100644 --- a/tensorflow_quantum/python/optimizers/spsa_minimizer_test.py +++ b/tensorflow_quantum/python/optimizers/spsa_minimizer_test.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """Test module for tfq.python.optimizers.spsa_minimizer optimizer.""" # Remove PYTHONPATH collisions for protobuf. # pylint: disable=wrong-import-position diff --git a/tensorflow_quantum/python/quantum_context.py b/tensorflow_quantum/python/quantum_context.py index 44c01cdeb..1a869bdea 100644 --- a/tensorflow_quantum/python/quantum_context.py +++ b/tensorflow_quantum/python/quantum_context.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """A global singleton object for defining op execution parameters.""" import multiprocessing diff --git a/tensorflow_quantum/python/quantum_context_test.py b/tensorflow_quantum/python/quantum_context_test.py index 5b219b1dc..b0612823d 100644 --- a/tensorflow_quantum/python/quantum_context_test.py +++ b/tensorflow_quantum/python/quantum_context_test.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """Tests for quantum_context functions.""" # Remove PYTHONPATH collisions for protobuf. # pylint: disable=wrong-import-position diff --git a/tensorflow_quantum/python/util.py b/tensorflow_quantum/python/util.py index 92ebeabee..c736a403f 100644 --- a/tensorflow_quantum/python/util.py +++ b/tensorflow_quantum/python/util.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """A collection of helper functions which are useful in places in TFQ.""" import itertools diff --git a/tensorflow_quantum/python/util_test.py b/tensorflow_quantum/python/util_test.py index 3d4e2dd76..9d12ea644 100644 --- a/tensorflow_quantum/python/util_test.py +++ b/tensorflow_quantum/python/util_test.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# ============================================================================== +# ============================================================================= """Tests for TFQ utilities.""" # Remove PYTHONPATH collisions for protobuf. # pylint: disable=wrong-import-position