diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 387b7d6a4..43f043e98 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -2,6 +2,7 @@ name: Continuous Integration on: [pull_request] + jobs: lint: name: Lint check @@ -10,7 +11,7 @@ jobs: - uses: actions/checkout@v1 - uses: actions/setup-python@v1 with: - python-version: '3.8' + python-version: '3.9' architecture: 'x64' - name: Install Lint tools run: pip install --upgrade pip setuptools; pip install -r requirements.txt; @@ -25,7 +26,7 @@ jobs: - uses: actions/checkout@v1 - uses: actions/setup-python@v1 with: - python-version: '3.8' + python-version: '3.9' architecture: 'x64' - name: Install Format tools run: pip install --upgrade pip setuptools; pip install -r requirements.txt; sudo apt-get install -y clang-format-6.0 @@ -40,7 +41,7 @@ jobs: - uses: actions/checkout@v1 - uses: actions/setup-python@v1 with: - python-version: '3.8' + python-version: '3.9' architecture: 'x64' - name: Install Bazel on CI run: ./scripts/ci_install.sh @@ -60,7 +61,7 @@ jobs: - uses: actions/checkout@v1 - uses: actions/setup-python@v1 with: - python-version: '3.8' + python-version: '3.9' architecture: 'x64' - name: Install Bazel on CI run: ./scripts/ci_install.sh @@ -78,7 +79,7 @@ jobs: - uses: actions/checkout@v1 - uses: actions/setup-python@v1 with: - python-version: '3.8' + python-version: '3.9' architecture: 'x64' - name: Install Bazel on CI run: ./scripts/ci_install.sh @@ -96,7 +97,7 @@ jobs: - uses: actions/checkout@v1 - uses: actions/setup-python@v1 with: - python-version: '3.8' + python-version: '3.9' architecture: 'x64' - name: Install notebook dependencies run: pip install --upgrade pip seaborn==0.10.0 diff --git a/.github/workflows/cirq_compatibility.yaml b/.github/workflows/cirq_compatibility.yaml index ee8e26f94..f5e5b9629 100644 --- a/.github/workflows/cirq_compatibility.yaml +++ b/.github/workflows/cirq_compatibility.yaml @@ -1,4 +1,3 @@ - name: Cirq Compatibility on: @@ -8,7 +7,7 @@ on: jobs: consistency: name: Nightly Compatibility - runs-on: ubuntu-20.04 + runs-on: ubuntu-16.04 steps: - uses: actions/checkout@v1 - uses: actions/setup-python@v1 diff --git a/WORKSPACE b/WORKSPACE index 6a29d598b..b47e25d2f 100644 --- a/WORKSPACE +++ b/WORKSPACE @@ -24,19 +24,11 @@ cc_library( ], ) -# http_archive( -# name = "qsim", -# sha256 = "b9c1eba09a885a938b5e73dfc2e02f5231cf3b01d899415caa24769346a731d5", -# strip_prefix = "qsim-0.13.3", -# urls = ["https://github.com/quantumlib/qsim/archive/refs/tags/v0.13.3.zip"], -# ) - -# TODO: After merging this patch later into qsim mainstream, remove this and uncomment the above. http_archive( name = "qsim", - sha256 = "", - strip_prefix = "qsim-0.15.0-dev20230327_v3", - urls = ["https://github.com/jaeyoo/qsim/archive/refs/tags/v0.15.0+dev20230327_v3.tar.gz"], + sha256 = "b9c1eba09a885a938b5e73dfc2e02f5231cf3b01d899415caa24769346a731d5", + strip_prefix = "qsim-0.13.3", + urls = ["https://github.com/quantumlib/qsim/archive/refs/tags/v0.13.3.zip"], ) http_archive( @@ -81,21 +73,3 @@ bind( actual = "@six_archive//:six", ) -new_local_repository( - name = "cuquantum_libs", - path = "/usr/local/google/home/jaeyoo/workspace/cuquantum-linux-x86_64-22.11.0.13-archive", - build_file_content = """ -cc_library( - name = "custatevec_headers", - srcs = ["include/custatevec.h"], - visibility = ["//visibility:public"], -) - -cc_library( - name = "custatevec", - srcs = ["lib/libcustatevec.so"], - visibility = ["//visibility:public"], -) -""", -) - diff --git a/benchmarks/scripts/benchmark_clifford_circuit.py b/benchmarks/scripts/benchmark_clifford_circuit.py index c71751dbc..643eff790 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 687e1b1f6..89b04cfd1 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 b265237d7..51d4ccfbf 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 87e903ecb..5b4bea2e5 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 951478a19..bece69897 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 ee173ef28..eaf7e78e2 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 c51a2f814..6383809c6 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 9d181170d..bf5b48863 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 09012c14e..a08a667b5 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 bee8f5464..c6d968ea0 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 0ca4a0ae4..ff42047fe 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() { @@ -62,11 +62,11 @@ while [[ "$TF_NEED_CUDA" == "" ]]; do done while [[ "$TF_CUDA_VERSION" == "" ]]; do - read -p "Are you building against TensorFlow 2.11(including RCs) or newer?[Y/n] " INPUT + read -p "Are you building against TensorFlow 2.1(including RCs) or newer?[Y/n] " INPUT case $INPUT in - [Yy]* ) echo "Build against TensorFlow 2.11 or newer."; TF_CUDA_VERSION=11;; - [Nn]* ) echo "Build against TensorFlow <2.11."; TF_CUDA_VERSION=10.0;; - "" ) echo "Build against TensorFlow 2.11 or newer."; TF_CUDA_VERSION=11;; + [Yy]* ) echo "Build against TensorFlow 2.1 or newer."; TF_CUDA_VERSION=11;; + [Nn]* ) echo "Build against TensorFlow <2.1."; TF_CUDA_VERSION=10.0;; + "" ) echo "Build against TensorFlow 2.1 or newer."; TF_CUDA_VERSION=11;; * ) echo "Invalid selection: " $INPUT;; esac done diff --git a/docs/_book.yaml b/docs/_book.yaml index 967d8ee7f..47daeba1b 100644 --- a/docs/_book.yaml +++ b/docs/_book.yaml @@ -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. -# ============================================================================= +# ============================================================================== upper_tabs: # Tabs left of dropdown menu - include: /_upper_tabs_left.yaml diff --git a/docs/_index.yaml b/docs/_index.yaml index fb1fc5876..e8de0371a 100644 --- a/docs/_index.yaml +++ b/docs/_index.yaml @@ -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. -# ============================================================================= +# ============================================================================== book_path: /quantum/_book.yaml project_path: /quantum/_project.yaml description: > diff --git a/release/BUILD b/release/BUILD index b588a6c5a..7212cb1d3 100644 --- a/release/BUILD +++ b/release/BUILD @@ -1,5 +1,3 @@ -load("@local_config_cuda//cuda:build_defs.bzl", "if_cuda_is_configured") - licenses(["notice"]) sh_binary( @@ -68,8 +66,5 @@ sh_binary( "//tensorflow_quantum/python:util", "//tensorflow_quantum/python/optimizers:rotosolve_minimizer", "//tensorflow_quantum/python/optimizers:spsa_minimizer", - ] + if_cuda_is_configured([ - "//tensorflow_quantum/core/ops:tfq_simulate_ops_cuda_py", - "//tensorflow_quantum/core/ops:tfq_simulate_ops_cuquantum_py", - ]), + ], ) diff --git a/release/build_pip_package.sh b/release/build_pip_package.sh index 1c423c656..8bed5b909 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 7b6037023..24424b613 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 @@ -53,7 +53,7 @@ def finalize_options(self): REQUIRED_PACKAGES = [ 'cirq-core==0.13.1', 'cirq-google>=0.13.1', 'sympy == 1.8', 'googleapis-common-protos==1.52.0', 'google-api-core==1.21.0', - 'google-auth==1.18.0', 'protobuf==3.19.5' + 'google-auth==1.18.0', 'protobuf==3.19.4' ] # placed as extra to not have required overwrite existing nightly installs if diff --git a/requirements.txt b/requirements.txt index 578179982..ae8700878 100644 --- a/requirements.txt +++ b/requirements.txt @@ -12,4 +12,4 @@ google-api-core==1.21.0 google-auth==1.18.0 google-api-python-client==1.8.0 grpcio==1.34.1 -protobuf==3.19.5 +protobuf==3.19.4 diff --git a/scripts/benchmark_all.sh b/scripts/benchmark_all.sh index 648d9ebad..cd50209c2 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 3ad066491..dc47df224 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 144a42cfb..644338b6a 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 860c02ecc..04e6b3159 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 d64361464..e58355faf 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 2a57c0747..0e374a3cc 100755 --- a/scripts/format_all.sh +++ b/scripts/format_all.sh @@ -12,13 +12,13 @@ # 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 echo -e "Done! \nDoing notebook formatting..." python3 ./scripts/format_ipynb.py echo -e "Done! \nDoing C++ formatting..." -find tensorflow_quantum/ -iname *.h -o -iname *.cc | xargs clang-format-6.0 -i -style=google +find tensorflow_quantum/ -iname *.h -o -iname *.cc | xargs clang-format -i -style=google echo "Done!" exit 0; diff --git a/scripts/format_check.sh b/scripts/format_check.sh index fb5b21ca1..1d91427e0 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..."; ################################################################################ @@ -92,7 +92,7 @@ else fi echo "Checking C++ formatting..."; -formatting_outputs=$(find tensorflow_quantum/ -iname *.h -o -iname *.cc | xargs clang-format-6.0 -style=google -output-replacements-xml); +formatting_outputs=$(find tensorflow_quantum/ -iname *.h -o -iname *.cc | xargs clang-format -style=google -output-replacements-xml); CFORMATCHECK=0 while read -r formatting_outputs; do if [ "$formatting_outputs" != "" ] && [ "$formatting_outputs" != "" ] && [ "$formatting_outputs" != "" ] && [ "$formatting_outputs" != " " ]; then diff --git a/scripts/format_ipynb.py b/scripts/format_ipynb.py index 10d2e447f..fac7a8bf1 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 ce2c87307..83ec24d2e 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 755906981..fb7e1c9a5 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 398332315..d47e8ccfe 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 1fbdd62d7..bb86edc22 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 2795e0429..7a9fc7824 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."; test_outputs=$(bazel test -c opt --experimental_repo_remote_exec --cxxopt="-D_GLIBCXX_USE_CXX11_ABI=1" --cxxopt="-std=c++17" --cxxopt="-msse2" --cxxopt="-msse3" --cxxopt="-msse4" --notest_keep_going --test_output=errors //tensorflow_quantum/...) exit_code=$? diff --git a/scripts/test_benchmarks.sh b/scripts/test_benchmarks.sh index 281791ec7..07e3adec1 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 b4463b90d..08a9d85d9 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 @@ -48,6 +48,5 @@ def test_notebook(self, path): _ = nbclient.execute(nb, timeout=900, kernel_name="python3") - if __name__ == "__main__": tf.test.main() diff --git a/tensorflow_quantum/__init__.py b/tensorflow_quantum/__init__.py index 44f4ba3ea..7c781f882 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 7e43c4be5..fb24ad4a8 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/BUILD b/tensorflow_quantum/core/ops/BUILD index 84361cef1..8087a8d3b 100644 --- a/tensorflow_quantum/core/ops/BUILD +++ b/tensorflow_quantum/core/ops/BUILD @@ -1,6 +1,4 @@ # load op_wrapper -load("@org_tensorflow//tensorflow:tensorflow.bzl", "tf_gpu_kernel_library", "tf_gen_op_wrapper_py") -load("@local_config_cuda//cuda:build_defs.bzl", "if_cuda_is_configured", "if_cuda") package(default_visibility = ["//visibility:public"]) @@ -14,23 +12,6 @@ config_setting( constraint_values = ["@bazel_tools//platforms:windows"], ) -cc_library( - name = "cuda", - data = [ - "@local_config_cuda//cuda:cudart", - ], - linkopts = select({ - ":windows": [], - "//conditions:default": [ - "-Wl,-rpath,../local_config_cuda/cuda/lib64", - "-Wl,-rpath,../local_config_cuda/cuda/extras/CUPTI/lib64", - ], - }), - deps = [ - "@local_config_cuda//cuda:cudart", - ], -) - py_library( name = "ops", srcs = ["__init__.py"], @@ -49,10 +30,7 @@ py_library( "//tensorflow_quantum/core/ops/math_ops:inner_product_op_py", "//tensorflow_quantum/core/ops/math_ops:fidelity_op_py", "//tensorflow_quantum/core/ops/noise:noisy_expectation_op_py", - ] + if_cuda_is_configured([ - ":tfq_simulate_ops_cuda_py", - ":tfq_simulate_ops_cuquantum_py", - ]), + ], ) cc_binary( @@ -641,198 +619,6 @@ py_test( ], ) -py_library( - name = "tfq_simulate_ops_cuda_py", - srcs = ["tfq_simulate_ops_cuda.py"], - data = [ - ":_tfq_simulate_ops_cuda.so", - ], - srcs_version = "PY3", - deps = [ - # tensorflow framework for wrappers - ":load_module", - ], -) - -py_library( - name = "tfq_simulate_ops_cuquantum_py", - srcs = ["tfq_simulate_ops_cuquantum.py"], - data = [ - ":_tfq_simulate_ops_cuquantum.so", - ], - srcs_version = "PY3", - deps = [ - # tensorflow framework for wrappers - ":load_module", - ], -) - -py_test( - name = "tfq_simulate_ops_gpu_test", - srcs = ["tfq_simulate_ops_gpu_test.py"], - deps = [ - ":tfq_simulate_ops_cuda_py", - ":tfq_simulate_ops_cuquantum_py", - ":tfq_simulate_ops_py", - "//tensorflow_quantum/python:util", - ], - srcs_version = "PY3", -) - -cc_binary( - name = "_tfq_simulate_ops_cuda.so", - srcs = [ - "tfq_simulate_expectation_op_cuda.cu.cc", - ], - linkshared = 1, - features = select({ - ":windows": ["windows_export_all_symbols"], - "//conditions:default": [], - }), - copts = select({ - ":windows": [ - "/D__CLANG_SUPPORT_DYN_ANNOTATION__", - "/D_USE_MATH_DEFINES", - "/DEIGEN_MPL2_ONLY", - "/DEIGEN_MAX_ALIGN_BYTES=64", - "/DEIGEN_HAS_TYPE_TRAITS=0", - "/DTF_USE_SNAPPY", - "/showIncludes", - "/MD", - "/O2", - "/DNDEBUG", - "/w", - "-DWIN32_LEAN_AND_MEAN", - "-DNOGDI", - "/d2ReducedOptimizeHugeFunctions", - "/arch:AVX", - "/std:c++17", - "-DTENSORFLOW_MONOLITHIC_BUILD", - "/DPLATFORM_WINDOWS", - "/DEIGEN_HAS_C99_MATH", - "/DTENSORFLOW_USE_EIGEN_THREADPOOL", - "/DEIGEN_AVOID_STL_ARRAY", - "/Iexternal/gemmlowp", - "/wd4018", - "/wd4577", - "/DNOGDI", - "/UTF_COMPILE_LIBRARY", - ], - "//conditions:default": [ - "-Iexternal/local_cuda/cuda/include", - # "--cuda-gpu-arch=sm_86", - # "-L/usr/local/cuda/lib64", - # "-lcudart_static", - # "-ldl", - # "-lrt", - "-pthread", - "-std=c++17", - "-D_GLIBCXX_USE_CXX11_ABI=1", - "-O3", - "-Iexternal/cuda_headers", - "-DNV_CUDNN_DISABLE_EXCEPTION", - # "-fpermissive", - ], - }) + if_cuda_is_configured(["-DTENSORFLOW_USE_NVCC=1", "-DGOOGLE_CUDA=1", "-x cuda", "-nvcc_options=relaxed-constexpr", "-nvcc_options=ftz=true"]), - deps = [ - # cirq cc proto - "//tensorflow_quantum/core/ops:parse_context", - "//tensorflow_quantum/core/ops:tfq_simulate_utils", - "//tensorflow_quantum/core/proto:pauli_sum_cc_proto", - "//tensorflow_quantum/core/proto:program_cc_proto", - "//tensorflow_quantum/core/src:circuit_parser_qsim", - "//tensorflow_quantum/core/src:util_qsim", - "@eigen//:eigen3", - # "@local_cuda//:cuda_headers" - # tensorflow core framework - # tensorflow core lib - # tensorflow core protos - ] + if_cuda_is_configured([ - ":cuda", - "@local_config_cuda//cuda:cuda_headers", - "@qsim//lib:qsim_cuda_lib", - ]), - # alwayslink=1, -) - -cc_binary( - name = "_tfq_simulate_ops_cuquantum.so", - srcs = [ - "tfq_simulate_expectation_op_cuquantum.cu.cc", - ], - linkshared = 1, - features = select({ - ":windows": ["windows_export_all_symbols"], - "//conditions:default": [], - }), - copts = select({ - ":windows": [ - "/D__CLANG_SUPPORT_DYN_ANNOTATION__", - "/D_USE_MATH_DEFINES", - "/DEIGEN_MPL2_ONLY", - "/DEIGEN_MAX_ALIGN_BYTES=64", - "/DEIGEN_HAS_TYPE_TRAITS=0", - "/DTF_USE_SNAPPY", - "/showIncludes", - "/MD", - "/O2", - "/DNDEBUG", - "/w", - "-DWIN32_LEAN_AND_MEAN", - "-DNOGDI", - "/d2ReducedOptimizeHugeFunctions", - "/arch:AVX", - "/std:c++17", - "-DTENSORFLOW_MONOLITHIC_BUILD", - "/DPLATFORM_WINDOWS", - "/DEIGEN_HAS_C99_MATH", - "/DTENSORFLOW_USE_EIGEN_THREADPOOL", - "/DEIGEN_AVOID_STL_ARRAY", - "/Iexternal/gemmlowp", - "/wd4018", - "/wd4577", - "/DNOGDI", - "/UTF_COMPILE_LIBRARY", - ], - "//conditions:default": [ - "-Iexternal/local_cuda/cuda/include", - # "--cuda-gpu-arch=sm_86", - # "-L/usr/local/cuda/lib64", - # "-lcudart_static", - # "-ldl", - # "-lrt", - "-pthread", - "-std=c++17", - "-D_GLIBCXX_USE_CXX11_ABI=1", - "-O3", - "-Iexternal/cuda_headers", - "-DNV_CUDNN_DISABLE_EXCEPTION", - # "-fpermissive", - ], - }) + if_cuda_is_configured(["-DTENSORFLOW_USE_NVCC=1", "-DGOOGLE_CUDA=1", "-x cuda", "-nvcc_options=relaxed-constexpr", "-nvcc_options=ftz=true"]), - deps = [ - # cirq cc proto - "//tensorflow_quantum/core/ops:parse_context", - "//tensorflow_quantum/core/ops:tfq_simulate_utils", - "//tensorflow_quantum/core/proto:pauli_sum_cc_proto", - "//tensorflow_quantum/core/proto:program_cc_proto", - "//tensorflow_quantum/core/src:circuit_parser_qsim", - "//tensorflow_quantum/core/src:util_qsim", - "@eigen//:eigen3", - # "@local_cuda//:cuda_headers" - # tensorflow core framework - # tensorflow core lib - # tensorflow core protos - ] + if_cuda_is_configured([ - ":cuda", - "@cuquantum_libs//:custatevec", - "@cuquantum_libs//:custatevec_headers", - "@local_config_cuda//cuda:cuda_headers", - "@qsim//lib:qsim_cuquantum_lib", - ]), - # alwayslink=1, -) - py_library( name = "load_module", srcs = ["load_module.py"], diff --git a/tensorflow_quantum/core/ops/__init__.py b/tensorflow_quantum/core/ops/__init__.py index fc687424a..062ea7499 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 7575ffae1..75f148424 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 16debfc0c..6b11becd7 100644 --- a/tensorflow_quantum/core/ops/batch_util_test.py +++ b/tensorflow_quantum/core/ops/batch_util_test.py @@ -11,12 +11,11 @@ # 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 import sys - NEW_PATH = [x for x in sys.path if 'com_google_protobuf' not in x] sys.path = NEW_PATH # pylint: enable=wrong-import-position diff --git a/tensorflow_quantum/core/ops/circuit_execution_ops.py b/tensorflow_quantum/core/ops/circuit_execution_ops.py index b2cc1ce70..1158e98e4 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 diff --git a/tensorflow_quantum/core/ops/circuit_execution_ops_test.py b/tensorflow_quantum/core/ops/circuit_execution_ops_test.py index 08e4f5b6f..f94297cdc 100644 --- a/tensorflow_quantum/core/ops/circuit_execution_ops_test.py +++ b/tensorflow_quantum/core/ops/circuit_execution_ops_test.py @@ -11,12 +11,11 @@ # 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 import sys - NEW_PATH = [x for x in sys.path if 'com_google_protobuf' not in x] sys.path = NEW_PATH # pylint: enable=wrong-import-position diff --git a/tensorflow_quantum/core/ops/cirq_ops.py b/tensorflow_quantum/core/ops/cirq_ops.py index 2c1039ac8..2650e812b 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 8dc0de4a9..1b54771a9 100644 --- a/tensorflow_quantum/core/ops/cirq_ops_test.py +++ b/tensorflow_quantum/core/ops/cirq_ops_test.py @@ -11,12 +11,11 @@ # 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 import sys - NEW_PATH = [x for x in sys.path if 'com_google_protobuf' not in x] sys.path = NEW_PATH # pylint: enable=wrong-import-position diff --git a/tensorflow_quantum/core/ops/load_module.py b/tensorflow_quantum/core/ops/load_module.py index ee4f9b0b6..b5002ad84 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 9d3b92f64..982e26911 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 ae2908baa..8f2e87e44 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 a17011bd3..1ab8031ea 100644 --- a/tensorflow_quantum/core/ops/math_ops/fidelity_op_test.py +++ b/tensorflow_quantum/core/ops/math_ops/fidelity_op_test.py @@ -11,12 +11,11 @@ # 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 import sys - NEW_PATH = [x for x in sys.path if 'com_google_protobuf' not in x] sys.path = NEW_PATH # pylint: enable=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 513f1eeb0..7fa74ee40 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,12 +11,11 @@ # 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 import sys - NEW_PATH = [x for x in sys.path if 'com_google_protobuf' not in x] sys.path = NEW_PATH # pylint: enable=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 54e49643e..5d92b7b92 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 fb4bbf5c9..ae83857b6 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,12 +11,11 @@ # 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 import sys - NEW_PATH = [x for x in sys.path if 'com_google_protobuf' not in x] sys.path = NEW_PATH # pylint: enable=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 41e1fd7c2..812081c05 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 3ed527ed8..114706d64 100644 --- a/tensorflow_quantum/core/ops/math_ops/simulate_mps_test.py +++ b/tensorflow_quantum/core/ops/math_ops/simulate_mps_test.py @@ -11,12 +11,11 @@ # 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 import sys - NEW_PATH = [x for x in sys.path if 'com_google_protobuf' not in x] sys.path = NEW_PATH # pylint: enable=wrong-import-position @@ -360,7 +359,7 @@ def test_complex_equality(self): symbol_values_array, util.convert_to_tensor(pauli_sums), bond_dim=32) - self.assertAllClose(mps_result, cirq_result, atol=1e-5) + self.assertAllClose(mps_result, cirq_result, atol=1e-4) def test_correctness_empty(self): """Tests the mps op with empty circuits.""" diff --git a/tensorflow_quantum/core/ops/math_ops/tfq_inner_product.cc b/tensorflow_quantum/core/ops/math_ops/tfq_inner_product.cc index 374aa5b55..74751f9cc 100644 --- a/tensorflow_quantum/core/ops/math_ops/tfq_inner_product.cc +++ b/tensorflow_quantum/core/ops/math_ops/tfq_inner_product.cc @@ -174,7 +174,7 @@ class TfqInnerProductOp : public tensorflow::OpKernel { // Simulate programs one by one. Parallelizing over state vectors // we no longer parallelize over circuits. Each time we encounter a // a larger circuit we will grow the Statevector as necessary. - for (size_t i = 0; i < fused_circuits.size(); i++) { + for (int i = 0; i < fused_circuits.size(); i++) { int nq = num_qubits[i]; if (nq > largest_nq) { // need to switch to larger statespace. @@ -186,10 +186,10 @@ class TfqInnerProductOp : public tensorflow::OpKernel { // the state if there is a possibility that circuit[i] and // circuit[i + 1] produce the same state. ss.SetStateZero(sv); - for (size_t j = 0; j < fused_circuits[i].size(); j++) { + for (int j = 0; j < fused_circuits[i].size(); j++) { qsim::ApplyFusedGate(sim, fused_circuits[i][j], sv); } - for (size_t j = 0; j < other_fused_circuits[i].size(); j++) { + for (int j = 0; j < other_fused_circuits[i].size(); j++) { // (#679) Just ignore empty program if (fused_circuits[i].size() == 0) { (*output_tensor)(i, j) = std::complex(1, 0); @@ -197,7 +197,7 @@ class TfqInnerProductOp : public tensorflow::OpKernel { } ss.SetStateZero(scratch); - for (size_t k = 0; k < other_fused_circuits[i][j].size(); k++) { + for (int k = 0; k < other_fused_circuits[i][j].size(); k++) { qsim::ApplyFusedGate(sim, other_fused_circuits[i][j][k], scratch); } @@ -255,13 +255,13 @@ class TfqInnerProductOp : public tensorflow::OpKernel { // no need to update scratch_state since ComputeExpectation // will take care of things for us. ss.SetStateZero(sv); - for (size_t j = 0; j < fused_circuits[cur_batch_index].size(); j++) { + for (int j = 0; j < fused_circuits[cur_batch_index].size(); j++) { qsim::ApplyFusedGate(sim, fused_circuits[cur_batch_index][j], sv); } } ss.SetStateZero(scratch); - for (size_t k = 0; + for (int k = 0; k < other_fused_circuits[cur_batch_index][cur_internal_index].size(); k++) { diff --git a/tensorflow_quantum/core/ops/math_ops/tfq_inner_product_grad.cc b/tensorflow_quantum/core/ops/math_ops/tfq_inner_product_grad.cc index 534d7fef9..3db493b11 100644 --- a/tensorflow_quantum/core/ops/math_ops/tfq_inner_product_grad.cc +++ b/tensorflow_quantum/core/ops/math_ops/tfq_inner_product_grad.cc @@ -398,13 +398,13 @@ class TfqInnerProductGradOp : public tensorflow::OpKernel { // if applicable compute control qubit mask and control value bits. uint64_t mask = 0; uint64_t cbits = 0; - for (size_t k = 0; k < cur_gate.controlled_by.size(); k++) { + for (int k = 0; k < cur_gate.controlled_by.size(); k++) { uint64_t control_loc = cur_gate.controlled_by[k]; mask |= uint64_t{1} << control_loc; cbits |= ((cur_gate.cmask >> k) & 1) << control_loc; } - for (size_t k = 0; + for (int k = 0; k < gradient_gates[cur_batch_index][l - 1].grad_gates.size(); k++) { // Copy sv_adj onto scratch2 in anticipation of non-unitary diff --git a/tensorflow_quantum/core/ops/noise/__init__.py b/tensorflow_quantum/core/ops/noise/__init__.py index d7969cec5..71291d4d2 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 7f801e686..e621988a0 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 5c87bdbfc..1e73500b8 100644 --- a/tensorflow_quantum/core/ops/noise/noisy_expectation_op_test.py +++ b/tensorflow_quantum/core/ops/noise/noisy_expectation_op_test.py @@ -11,12 +11,11 @@ # 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 import sys - NEW_PATH = [x for x in sys.path if 'com_google_protobuf' not in x] sys.path = NEW_PATH # pylint: enable=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 2cc84fd47..1874c8a5e 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 ea967c93b..35d1cc113 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,12 +11,11 @@ # 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 import sys - NEW_PATH = [x for x in sys.path if 'com_google_protobuf' not in x] sys.path = NEW_PATH # pylint: enable=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 1e19b19ae..4441d0c04 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 88b221941..b952e8d40 100644 --- a/tensorflow_quantum/core/ops/noise/noisy_samples_op_test.py +++ b/tensorflow_quantum/core/ops/noise/noisy_samples_op_test.py @@ -11,12 +11,11 @@ # 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 import sys - NEW_PATH = [x for x in sys.path if 'com_google_protobuf' not in x] sys.path = NEW_PATH # pylint: enable=wrong-import-position diff --git a/tensorflow_quantum/core/ops/noise/tfq_noisy_expectation.cc b/tensorflow_quantum/core/ops/noise/tfq_noisy_expectation.cc index 6f09da68f..c67fa01f7 100644 --- a/tensorflow_quantum/core/ops/noise/tfq_noisy_expectation.cc +++ b/tensorflow_quantum/core/ops/noise/tfq_noisy_expectation.cc @@ -175,8 +175,8 @@ class TfqNoisyExpectationOp : public tensorflow::OpKernel { tensorflow::GuardedPhiloxRandom random_gen; int max_n_shots = 1; - for (size_t i = 0; i < num_samples.size(); i++) { - for (size_t j = 0; j < num_samples[i].size(); j++) { + for (int i = 0; i < num_samples.size(); i++) { + for (int j = 0; j < num_samples[i].size(); j++) { max_n_shots = std::max(max_n_shots, num_samples[i][j]); } } @@ -188,12 +188,12 @@ class TfqNoisyExpectationOp : public tensorflow::OpKernel { // Simulate programs one by one. Parallelizing over state vectors // we no longer parallelize over circuits. Each time we encounter a // a larger circuit we will grow the Statevector as necessary. - for (size_t i = 0; i < ncircuits.size(); i++) { + for (int i = 0; i < ncircuits.size(); i++) { int nq = num_qubits[i]; // (#679) Just ignore empty program if (ncircuits[i].channels.size() == 0) { - for (size_t j = 0; j < pauli_sums[i].size(); j++) { + for (int j = 0; j < pauli_sums[i].size(); j++) { (*output_tensor)(i, j) = -2.0; } continue; @@ -220,7 +220,7 @@ class TfqNoisyExpectationOp : public tensorflow::OpKernel { sv, unused_stats); // Use this trajectory as a source for all expectation calculations. - for (size_t j = 0; j < pauli_sums[i].size(); j++) { + for (int j = 0; j < pauli_sums[i].size(); j++) { if (run_samples[j] >= num_samples[i][j]) { continue; } @@ -232,14 +232,14 @@ class TfqNoisyExpectationOp : public tensorflow::OpKernel { run_samples[j]++; } bool break_loop = true; - for (size_t j = 0; j < num_samples[i].size(); j++) { + for (int j = 0; j < num_samples[i].size(); j++) { if (run_samples[j] < num_samples[i][j]) { break_loop = false; break; } } if (break_loop) { - for (size_t j = 0; j < num_samples[i].size(); j++) { + for (int j = 0; j < num_samples[i].size(); j++) { rolling_sums[j] /= num_samples[i][j]; (*output_tensor)(i, j) = static_cast(rolling_sums[j]); } @@ -280,8 +280,8 @@ class TfqNoisyExpectationOp : public tensorflow::OpKernel { tensorflow::GuardedPhiloxRandom random_gen; int max_n_shots = 1; - for (size_t i = 0; i < num_samples.size(); i++) { - for (size_t j = 0; j < num_samples[i].size(); j++) { + for (int i = 0; i < num_samples.size(); i++) { + for (int j = 0; j < num_samples[i].size(); j++) { max_n_shots = std::max(max_n_shots, num_samples[i][j]); } } @@ -304,13 +304,13 @@ class TfqNoisyExpectationOp : public tensorflow::OpKernel { random_gen.ReserveSamples128(ncircuits.size() * max_n_shots + 1); tensorflow::random::SimplePhilox rand_source(&local_gen); - for (size_t i = 0; i < ncircuits.size(); i++) { + for (int i = 0; i < ncircuits.size(); i++) { int nq = num_qubits[i]; int rep_offset = rep_offsets[start][i]; // (#679) Just ignore empty program if (ncircuits[i].channels.size() == 0) { - for (size_t j = 0; j < pauli_sums[i].size(); j++) { + for (int j = 0; j < pauli_sums[i].size(); j++) { (*output_tensor)(i, j) = -2.0; } continue; @@ -337,7 +337,7 @@ class TfqNoisyExpectationOp : public tensorflow::OpKernel { sim, sv, unused_stats); // Compute expectations across all ops using this trajectory. - for (size_t j = 0; j < pauli_sums[i].size(); j++) { + for (int j = 0; j < pauli_sums[i].size(); j++) { int p_reps = (num_samples[i][j] + num_threads - 1) / num_threads; if (run_samples[j] >= p_reps + rep_offset) { continue; @@ -354,7 +354,7 @@ class TfqNoisyExpectationOp : public tensorflow::OpKernel { // Check if we have run enough trajectories for all ops. bool break_loop = true; - for (size_t j = 0; j < num_samples[i].size(); j++) { + for (int j = 0; j < num_samples[i].size(); j++) { int p_reps = (num_samples[i][j] + num_threads - 1) / num_threads; if (run_samples[j] < p_reps + rep_offset) { break_loop = false; @@ -364,7 +364,7 @@ class TfqNoisyExpectationOp : public tensorflow::OpKernel { if (break_loop) { // Lock writing to this batch index in output_tensor. batch_locks[i].lock(); - for (size_t j = 0; j < num_samples[i].size(); j++) { + for (int j = 0; j < num_samples[i].size(); j++) { rolling_sums[j] /= num_samples[i][j]; (*output_tensor)(i, j) += static_cast(rolling_sums[j]); } diff --git a/tensorflow_quantum/core/ops/noise/tfq_noisy_sampled_expectation.cc b/tensorflow_quantum/core/ops/noise/tfq_noisy_sampled_expectation.cc index 7e1993a7e..aa0c85691 100644 --- a/tensorflow_quantum/core/ops/noise/tfq_noisy_sampled_expectation.cc +++ b/tensorflow_quantum/core/ops/noise/tfq_noisy_sampled_expectation.cc @@ -177,8 +177,8 @@ class TfqNoisySampledExpectationOp : public tensorflow::OpKernel { tensorflow::GuardedPhiloxRandom random_gen; int max_psum_length = 1; int max_n_shots = 1; - for (size_t i = 0; i < pauli_sums.size(); i++) { - for (size_t j = 0; j < pauli_sums[i].size(); j++) { + for (int i = 0; i < pauli_sums.size(); i++) { + for (int j = 0; j < pauli_sums[i].size(); j++) { max_psum_length = std::max(max_psum_length, pauli_sums[i][j].terms().size()); max_n_shots = std::max(max_n_shots, num_samples[i][j]); @@ -192,12 +192,12 @@ class TfqNoisySampledExpectationOp : public tensorflow::OpKernel { // Simulate programs one by one. Parallelizing over state vectors // we no longer parallelize over circuits. Each time we encounter a // a larger circuit we will grow the Statevector as necessary. - for (size_t i = 0; i < ncircuits.size(); i++) { + for (int i = 0; i < ncircuits.size(); i++) { int nq = num_qubits[i]; // (#679) Just ignore empty program if (ncircuits[i].channels.empty()) { - for (size_t j = 0; j < pauli_sums[i].size(); j++) { + for (int j = 0; j < pauli_sums[i].size(); j++) { (*output_tensor)(i, j) = -2.0; } continue; @@ -224,7 +224,7 @@ class TfqNoisySampledExpectationOp : public tensorflow::OpKernel { sv, unused_stats); // Use this trajectory as a source for all expectation calculations. - for (size_t j = 0; j < pauli_sums[i].size(); j++) { + for (int j = 0; j < pauli_sums[i].size(); j++) { if (run_samples[j] >= num_samples[i][j]) { continue; } @@ -236,14 +236,14 @@ class TfqNoisySampledExpectationOp : public tensorflow::OpKernel { run_samples[j]++; } bool break_loop = true; - for (size_t j = 0; j < num_samples[i].size(); j++) { + for (int j = 0; j < num_samples[i].size(); j++) { if (run_samples[j] < num_samples[i][j]) { break_loop = false; break; } } if (break_loop) { - for (size_t j = 0; j < num_samples[i].size(); j++) { + for (int j = 0; j < num_samples[i].size(); j++) { rolling_sums[j] /= num_samples[i][j]; (*output_tensor)(i, j) = static_cast(rolling_sums[j]); } @@ -285,8 +285,8 @@ class TfqNoisySampledExpectationOp : public tensorflow::OpKernel { tensorflow::GuardedPhiloxRandom random_gen; int max_psum_length = 1; int max_n_shots = 1; - for (size_t i = 0; i < pauli_sums.size(); i++) { - for (size_t j = 0; j < pauli_sums[i].size(); j++) { + for (int i = 0; i < pauli_sums.size(); i++) { + for (int j = 0; j < pauli_sums[i].size(); j++) { max_psum_length = std::max(max_psum_length, pauli_sums[i][j].terms().size()); max_n_shots = std::max(max_n_shots, num_samples[i][j]); @@ -310,13 +310,13 @@ class TfqNoisySampledExpectationOp : public tensorflow::OpKernel { auto local_gen = random_gen.ReserveSamples128(num_rand); tensorflow::random::SimplePhilox rand_source(&local_gen); - for (size_t i = 0; i < ncircuits.size(); i++) { + for (int i = 0; i < ncircuits.size(); i++) { int nq = num_qubits[i]; int rep_offset = rep_offsets[start][i]; // (#679) Just ignore empty program if (ncircuits[i].channels.empty()) { - for (size_t j = 0; j < pauli_sums[i].size(); j++) { + for (int j = 0; j < pauli_sums[i].size(); j++) { (*output_tensor)(i, j) = -2.0; } continue; @@ -343,7 +343,7 @@ class TfqNoisySampledExpectationOp : public tensorflow::OpKernel { sim, sv, unused_stats); // Compute expectations across all ops using this trajectory. - for (size_t j = 0; j < pauli_sums[i].size(); j++) { + for (int j = 0; j < pauli_sums[i].size(); j++) { int p_reps = (num_samples[i][j] + num_threads - 1) / num_threads; if (run_samples[j] >= p_reps + rep_offset) { continue; @@ -360,7 +360,7 @@ class TfqNoisySampledExpectationOp : public tensorflow::OpKernel { // Check if we have run enough trajectories for all ops. bool break_loop = true; - for (size_t j = 0; j < num_samples[i].size(); j++) { + for (int j = 0; j < num_samples[i].size(); j++) { int p_reps = (num_samples[i][j] + num_threads - 1) / num_threads; if (run_samples[j] < p_reps + rep_offset) { break_loop = false; @@ -370,7 +370,7 @@ class TfqNoisySampledExpectationOp : public tensorflow::OpKernel { if (break_loop) { // Lock writing to this batch index in output_tensor. batch_locks[i].lock(); - for (size_t j = 0; j < num_samples[i].size(); j++) { + for (int j = 0; j < num_samples[i].size(); j++) { rolling_sums[j] /= num_samples[i][j]; (*output_tensor)(i, j) += static_cast(rolling_sums[j]); } diff --git a/tensorflow_quantum/core/ops/noise/tfq_noisy_samples.cc b/tensorflow_quantum/core/ops/noise/tfq_noisy_samples.cc index 1af738323..341c87910 100644 --- a/tensorflow_quantum/core/ops/noise/tfq_noisy_samples.cc +++ b/tensorflow_quantum/core/ops/noise/tfq_noisy_samples.cc @@ -159,7 +159,7 @@ class TfqNoisySamplesOp : public tensorflow::OpKernel { // Simulate programs one by one. Parallelizing over state vectors // we no longer parallelize over circuits. Each time we encounter a // a larger circuit we will grow the Statevector as nescessary. - for (size_t i = 0; i < ncircuits.size(); i++) { + for (int i = 0; i < ncircuits.size(); i++) { int nq = num_qubits[i]; if (nq > largest_nq) { @@ -252,7 +252,7 @@ class TfqNoisySamplesOp : public tensorflow::OpKernel { auto local_gen = random_gen.ReserveSamples32(needed_random); tensorflow::random::SimplePhilox rand_source(&local_gen); - for (size_t i = 0; i < ncircuits.size(); i++) { + for (int i = 0; i < ncircuits.size(); i++) { int nq = num_qubits[i]; int j = start > 0 ? offset_prefix_sum[start - 1][i] : 0; int needed_samples = offset_prefix_sum[start][i] - j; diff --git a/tensorflow_quantum/core/ops/parse_context.cc b/tensorflow_quantum/core/ops/parse_context.cc index 026c57321..f926d15bb 100644 --- a/tensorflow_quantum/core/ops/parse_context.cc +++ b/tensorflow_quantum/core/ops/parse_context.cc @@ -20,7 +20,6 @@ limitations under the License. #include #include -#include "absl/status/status.h" #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/lib/core/error_codes.pb.h" #include "tensorflow/core/lib/core/status.h" @@ -52,7 +51,7 @@ Status ParseProto(const std::string& text, T* proto) { } return Status( - static_cast(absl::StatusCode::kInvalidArgument), + static_cast(absl::StatusCode::kInvalidArgument), "Unparseable proto: " + text); } @@ -69,7 +68,7 @@ Status ParsePrograms(OpKernelContext* context, const std::string& input_name, if (input->dims() != 1) { // Never parse anything other than a 1d list of circuits. return Status( - static_cast( + static_cast( absl::StatusCode::kInvalidArgument), absl::StrCat("programs must be rank 1. Got rank ", input->dims(), ".")); } @@ -78,13 +77,9 @@ Status ParsePrograms(OpKernelContext* context, const std::string& input_name, const int num_programs = program_strings.dimension(0); programs->assign(num_programs, Program()); - Status parse_status = ::tensorflow::Status(); - auto p_lock = tensorflow::mutex(); - auto DoWork = [&](int start, int end) { for (int i = start; i < end; i++) { - Status local = ParseProto(program_strings(i), &programs->at(i)); - NESTED_FN_STATUS_SYNC(parse_status, local, p_lock); + OP_REQUIRES_OK(context, ParseProto(program_strings(i), &programs->at(i))); } }; @@ -93,7 +88,7 @@ Status ParsePrograms(OpKernelContext* context, const std::string& input_name, context->device()->tensorflow_cpu_worker_threads()->workers->ParallelFor( num_programs, cycle_estimate, DoWork); - return parse_status; + return ::tensorflow::Status(); } Status ParsePrograms2D(OpKernelContext* context, const std::string& input_name, @@ -106,7 +101,7 @@ Status ParsePrograms2D(OpKernelContext* context, const std::string& input_name, if (input->dims() != 2) { // Never parse anything other than a 1d list of circuits. - return Status(static_cast( + return Status(static_cast( absl::StatusCode::kInvalidArgument), absl::StrCat("other_programs must be rank 2. Got rank ", input->dims(), ".")); @@ -117,14 +112,12 @@ Status ParsePrograms2D(OpKernelContext* context, const std::string& input_name, const int num_entries = program_strings.dimension(1); programs->assign(num_programs, std::vector(num_entries, Program())); - Status parse_status = ::tensorflow::Status(); - auto p_lock = tensorflow::mutex(); auto DoWork = [&](int start, int end) { for (int i = start; i < end; i++) { - Status local = + OP_REQUIRES_OK( + context, ParseProto(program_strings(i / num_entries, i % num_entries), - &programs->at(i / num_entries).at(i % num_entries)); - NESTED_FN_STATUS_SYNC(parse_status, local, p_lock); + &programs->at(i / num_entries).at(i % num_entries))); } }; @@ -133,7 +126,7 @@ Status ParsePrograms2D(OpKernelContext* context, const std::string& input_name, context->device()->tensorflow_cpu_worker_threads()->workers->ParallelFor( num_programs * num_entries, cycle_estimate, DoWork); - return parse_status; + return ::tensorflow::Status(); } Status GetProgramsAndProgramsToAppend( @@ -150,7 +143,7 @@ Status GetProgramsAndProgramsToAppend( } if (programs->size() != programs_to_append->size()) { - return Status(static_cast( + return Status(static_cast( absl::StatusCode::kInvalidArgument), "programs and programs_to_append must have matching sizes."); } @@ -178,7 +171,7 @@ Status GetProgramsAndNumQubits( } if (programs->size() != p_sums->size()) { return Status( - static_cast( + static_cast( absl::StatusCode::kInvalidArgument), absl::StrCat("Number of circuits and PauliSums do not match. Got ", programs->size(), " circuits and ", p_sums->size(), @@ -187,22 +180,19 @@ Status GetProgramsAndNumQubits( } // Resolve qubit ID's in parallel. - Status parse_status = ::tensorflow::Status(); - auto p_lock = tensorflow::mutex(); num_qubits->assign(programs->size(), -1); auto DoWork = [&](int start, int end) { for (int i = start; i < end; i++) { Program& program = (*programs)[i]; unsigned int this_num_qubits; - Status local; if (p_sums) { - local = ResolveQubitIds(&program, &this_num_qubits, &(p_sums->at(i)), - swap_endianness); + OP_REQUIRES_OK(context, + ResolveQubitIds(&program, &this_num_qubits, + &(p_sums->at(i)), swap_endianness)); } else { - local = ResolveQubitIds(&program, &this_num_qubits, nullptr, - swap_endianness); + OP_REQUIRES_OK(context, ResolveQubitIds(&program, &this_num_qubits, + nullptr, swap_endianness)); } - NESTED_FN_STATUS_SYNC(parse_status, local, p_lock); (*num_qubits)[i] = this_num_qubits; } }; @@ -212,7 +202,7 @@ Status GetProgramsAndNumQubits( context->device()->tensorflow_cpu_worker_threads()->workers->ParallelFor( num_qubits->size(), cycle_estimate, DoWork); - return parse_status; + return ::tensorflow::Status(); } tensorflow::Status GetProgramsAndNumQubits( @@ -233,7 +223,7 @@ tensorflow::Status GetProgramsAndNumQubits( } if (programs->size() != other_programs->size()) { - return Status(static_cast( + return Status(static_cast( absl::StatusCode::kInvalidArgument), absl::StrCat("programs and other_programs batch dimension", " do not match. Foud: ", programs->size(), @@ -241,16 +231,13 @@ tensorflow::Status GetProgramsAndNumQubits( } // Resolve qubit ID's in parallel. - Status parse_status = ::tensorflow::Status(); - auto p_lock = tensorflow::mutex(); num_qubits->assign(programs->size(), -1); auto DoWork = [&](int start, int end) { for (int i = start; i < end; i++) { Program& program = (*programs)[i]; unsigned int this_num_qubits; - Status local = - ResolveQubitIds(&program, &this_num_qubits, &(*other_programs)[i]); - NESTED_FN_STATUS_SYNC(parse_status, local, p_lock); + OP_REQUIRES_OK(context, ResolveQubitIds(&program, &this_num_qubits, + &(*other_programs)[i])); (*num_qubits)[i] = this_num_qubits; } }; @@ -260,7 +247,7 @@ tensorflow::Status GetProgramsAndNumQubits( context->device()->tensorflow_cpu_worker_threads()->workers->ParallelFor( num_qubits->size(), cycle_estimate, DoWork); - return parse_status; + return ::tensorflow::Status(); } Status GetPauliSums(OpKernelContext* context, @@ -273,7 +260,7 @@ Status GetPauliSums(OpKernelContext* context, } if (input->dims() != 2) { - return Status(static_cast( + return Status(static_cast( absl::StatusCode::kInvalidArgument), absl::StrCat("pauli_sums must be rank 2. Got rank ", input->dims(), ".")); @@ -283,18 +270,12 @@ Status GetPauliSums(OpKernelContext* context, p_sums->assign(sum_specs.dimension(0), std::vector(sum_specs.dimension(1), PauliSum())); const int op_dim = sum_specs.dimension(1); - Status parse_status = ::tensorflow::Status(); - auto p_lock = tensorflow::mutex(); auto DoWork = [&](int start, int end) { for (int ii = start; ii < end; ii++) { const int i = ii / op_dim; const int j = ii % op_dim; PauliSum p; - // We should not stop the whole program, because TFQ cuQuantum ops - // requires running destructors to return cuQuantum handlers, - // and not to fall into segfault. - Status local = ParseProto(sum_specs(i, j), &p); - NESTED_FN_STATUS_SYNC(parse_status, local, p_lock); + OP_REQUIRES_OK(context, ParseProto(sum_specs(i, j), &p)); (*p_sums)[i][j] = p; } }; @@ -304,7 +285,7 @@ Status GetPauliSums(OpKernelContext* context, context->device()->tensorflow_cpu_worker_threads()->workers->ParallelFor( sum_specs.dimension(0) * sum_specs.dimension(1), cycle_estimate, DoWork); - return parse_status; + return ::tensorflow::Status(); } Status GetSymbolMaps(OpKernelContext* context, std::vector* maps) { @@ -316,7 +297,7 @@ Status GetSymbolMaps(OpKernelContext* context, std::vector* maps) { } if (input_names->dims() != 1) { - return Status(static_cast( + return Status(static_cast( absl::StatusCode::kInvalidArgument), absl::StrCat("symbol_names must be rank 1. Got rank ", input_names->dims(), ".")); @@ -329,7 +310,7 @@ Status GetSymbolMaps(OpKernelContext* context, std::vector* maps) { } if (input_values->dims() != 2) { - return Status(static_cast( + return Status(static_cast( absl::StatusCode::kInvalidArgument), absl::StrCat("symbol_values must be rank 2. Got rank ", input_values->dims(), ".")); @@ -339,7 +320,7 @@ Status GetSymbolMaps(OpKernelContext* context, std::vector* maps) { const auto symbol_values = input_values->matrix(); if (symbol_names.dimension(0) != symbol_values.dimension(1)) { - return Status(static_cast( + return Status(static_cast( absl::StatusCode::kInvalidArgument), "Input symbol names and value sizes do not match."); } @@ -375,7 +356,7 @@ tensorflow::Status GetNumSamples( } if (input_num_samples->dims() != 2) { - return Status(static_cast( + return Status(static_cast( absl::StatusCode::kInvalidArgument), absl::StrCat("num_samples must be rank 2. Got rank ", input_num_samples->dims(), ".")); @@ -389,7 +370,7 @@ tensorflow::Status GetNumSamples( for (unsigned int j = 0; j < matrix_num_samples.dimension(1); j++) { const int num_samples = matrix_num_samples(i, j); if (num_samples < 1) { - return Status(static_cast( + return Status(static_cast( absl::StatusCode::kInvalidArgument), "Each element of num_samples must be greater than 0."); } @@ -411,7 +392,7 @@ Status GetIndividualSample(tensorflow::OpKernelContext* context, } if (input_num_samples->dims() != 1) { - return Status(static_cast( + return Status(static_cast( absl::StatusCode::kInvalidArgument), absl::StrCat("num_samples must be rank 1. Got rank ", input_num_samples->dims(), ".")); @@ -420,7 +401,7 @@ Status GetIndividualSample(tensorflow::OpKernelContext* context, const auto vector_num_samples = input_num_samples->vec(); if (vector_num_samples.dimension(0) != 1) { - return Status(static_cast( + return Status(static_cast( absl::StatusCode::kInvalidArgument), absl::StrCat("num_samples must contain 1 element. Got ", vector_num_samples.dimension(0), ".")); @@ -441,7 +422,7 @@ tensorflow::Status GetPrevGrads( } if (input_grads->dims() != 2) { - return Status(static_cast( + return Status(static_cast( absl::StatusCode::kInvalidArgument), absl::StrCat("downstream_grads must be rank 2. Got rank ", input_grads->dims(), ".")); diff --git a/tensorflow_quantum/core/ops/tfq_adj_grad_op.cc b/tensorflow_quantum/core/ops/tfq_adj_grad_op.cc index fe88a5817..e7252baee 100644 --- a/tensorflow_quantum/core/ops/tfq_adj_grad_op.cc +++ b/tensorflow_quantum/core/ops/tfq_adj_grad_op.cc @@ -202,15 +202,15 @@ class TfqAdjointGradientOp : public tensorflow::OpKernel { } ss.SetStateZero(sv); - for (size_t j = 0; j < full_fuse[i].size(); j++) { + for (int j = 0; j < full_fuse[i].size(); j++) { qsim::ApplyFusedGate(sim, full_fuse[i][j], sv); } // 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); + 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--) { @@ -231,14 +231,13 @@ class TfqAdjointGradientOp : public tensorflow::OpKernel { // if applicable compute control qubit mask and control value bits. uint64_t mask = 0; uint64_t cbits = 0; - for (size_t k = 0; k < cur_gate.controlled_by.size(); k++) { + for (int k = 0; k < cur_gate.controlled_by.size(); k++) { uint64_t control_loc = cur_gate.controlled_by[k]; mask |= uint64_t{1} << control_loc; cbits |= ((cur_gate.cmask >> k) & 1) << control_loc; } - for (size_t k = 0; k < gradient_gates[i][j - 1].grad_gates.size(); - k++) { + for (int k = 0; k < gradient_gates[i][j - 1].grad_gates.size(); k++) { // Copy sv onto scratch2 in anticipation of non-unitary "gradient // gate". ss.Copy(sv, scratch2); @@ -298,7 +297,7 @@ class TfqAdjointGradientOp : public tensorflow::OpKernel { auto scratch = ss.Create(largest_nq); auto scratch2 = ss.Create(largest_nq); - for (size_t i = 0; i < partial_fused_circuits.size(); i++) { + for (int i = 0; i < partial_fused_circuits.size(); i++) { int nq = num_qubits[i]; if (nq > largest_nq) { @@ -315,15 +314,15 @@ class TfqAdjointGradientOp : public tensorflow::OpKernel { } ss.SetStateZero(sv); - for (size_t j = 0; j < full_fuse[i].size(); j++) { + for (int j = 0; j < full_fuse[i].size(); j++) { qsim::ApplyFusedGate(sim, full_fuse[i][j], sv); } // 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); + 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--) { @@ -343,14 +342,13 @@ class TfqAdjointGradientOp : public tensorflow::OpKernel { // if applicable compute control qubit mask and control value bits. uint64_t mask = 0; uint64_t cbits = 0; - for (size_t k = 0; k < cur_gate.controlled_by.size(); k++) { + for (int k = 0; k < cur_gate.controlled_by.size(); k++) { uint64_t control_loc = cur_gate.controlled_by[k]; mask |= uint64_t{1} << control_loc; cbits |= ((cur_gate.cmask >> k) & 1) << control_loc; } - for (size_t k = 0; k < gradient_gates[i][j - 1].grad_gates.size(); - k++) { + for (int k = 0; k < gradient_gates[i][j - 1].grad_gates.size(); k++) { // Copy sv onto scratch2 in anticipation of non-unitary "gradient // gate". ss.Copy(sv, scratch2); diff --git a/tensorflow_quantum/core/ops/tfq_adj_grad_op.py b/tensorflow_quantum/core/ops/tfq_adj_grad_op.py index ead1e34d6..04b8ff0fb 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_test.py b/tensorflow_quantum/core/ops/tfq_adj_grad_op_test.py index 3acb662c4..388bb163f 100644 --- a/tensorflow_quantum/core/ops/tfq_adj_grad_op_test.py +++ b/tensorflow_quantum/core/ops/tfq_adj_grad_op_test.py @@ -11,12 +11,11 @@ # 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 import sys - NEW_PATH = [x for x in sys.path if 'com_google_protobuf' not in x] sys.path = NEW_PATH # pylint: enable=wrong-import-position diff --git a/tensorflow_quantum/core/ops/tfq_calculate_unitary_op.cc b/tensorflow_quantum/core/ops/tfq_calculate_unitary_op.cc index 4f1f662ca..ace5327e1 100644 --- a/tensorflow_quantum/core/ops/tfq_calculate_unitary_op.cc +++ b/tensorflow_quantum/core/ops/tfq_calculate_unitary_op.cc @@ -116,7 +116,7 @@ class TfqCalculateUnitaryOp : public tensorflow::OpKernel { // Simulate programs one by one. Parallelizing over state vectors // we no longer parallelize over circuits. Each time we encounter a // a larger circuit we will grow the unitary as nescessary. - for (size_t i = 0; i < fused_circuits.size(); i++) { + for (int i = 0; i < fused_circuits.size(); i++) { int nq = num_qubits[i]; UCalculator sim = UCalculator(tfq_for); UnitarySpace us = UnitarySpace(tfq_for); @@ -126,7 +126,7 @@ class TfqCalculateUnitaryOp : public tensorflow::OpKernel { u = us.CreateUnitary(nq); } us.SetIdentity(u); - for (size_t j = 0; j < fused_circuits[i].size(); j++) { + for (int j = 0; j < fused_circuits[i].size(); j++) { qsim::ApplyFusedGate(sim, fused_circuits[i][j], u); } diff --git a/tensorflow_quantum/core/ops/tfq_ps_decompose_op.cc b/tensorflow_quantum/core/ops/tfq_ps_decompose_op.cc index 5c20e546e..669ea6368 100644 --- a/tensorflow_quantum/core/ops/tfq_ps_decompose_op.cc +++ b/tensorflow_quantum/core/ops/tfq_ps_decompose_op.cc @@ -65,11 +65,11 @@ class TfqPsDecomposeOp : public tensorflow::OpKernel { new_program.mutable_language()->set_gate_set("tfq_gate_set"); new_program.mutable_circuit()->set_scheduling_strategy( Circuit::MOMENT_BY_MOMENT); - for (size_t j = 0; j < cur_program.circuit().moments().size(); j++) { + for (int j = 0; j < cur_program.circuit().moments().size(); j++) { Moment cur_moment(cur_program.circuit().moments().at(j)); std::vector temp_moment_list(max_buffer_moments, Moment()); int num_extra_moments = 0; - for (size_t k = 0; k < cur_moment.operations().size(); k++) { + for (int k = 0; k < cur_moment.operations().size(); k++) { Operation cur_op = cur_moment.operations().at(k); auto &cur_op_map = *cur_op.mutable_args(); if (cur_op.gate().id() == "PISP") { diff --git a/tensorflow_quantum/core/ops/tfq_ps_symbol_replace_op.cc b/tensorflow_quantum/core/ops/tfq_ps_symbol_replace_op.cc index 6a38be061..559fbecc9 100644 --- a/tensorflow_quantum/core/ops/tfq_ps_symbol_replace_op.cc +++ b/tensorflow_quantum/core/ops/tfq_ps_symbol_replace_op.cc @@ -89,9 +89,9 @@ class TfqPsSymbolReplaceOp : public tensorflow::OpKernel { std::string symbol_to_replace = symbols(sidx); std::string temp_symbol_holder; Program cur_program = programs.at(pidx); - for (size_t j = 0; j < cur_program.circuit().moments().size(); j++) { + for (int j = 0; j < cur_program.circuit().moments().size(); j++) { Moment cur_moment = cur_program.circuit().moments().at(j); - for (size_t k = 0; k < cur_moment.operations().size(); k++) { + for (int k = 0; k < cur_moment.operations().size(); k++) { Operation cur_op = cur_moment.operations().at(k); for (auto l = cur_op.args().begin(); l != cur_op.args().end(); l++) { @@ -163,12 +163,12 @@ class TfqPsSymbolReplaceOp : public tensorflow::OpKernel { for (int i = start; i < end; i++) { int sidx = i % n_symbols; int pidx = i / n_symbols; - for (size_t j = 0; j < output_programs.at(pidx).at(sidx).size(); j++) { + for (int j = 0; j < output_programs.at(pidx).at(sidx).size(); j++) { output_tensor(pidx, sidx, j) = output_programs.at(pidx).at(sidx).at(j); } - for (size_t j = output_programs.at(pidx).at(sidx).size(); - j < biggest_pad; j++) { + for (int j = output_programs.at(pidx).at(sidx).size(); j < biggest_pad; + j++) { output_tensor(pidx, sidx, j) = empty_program; } } diff --git a/tensorflow_quantum/core/ops/tfq_ps_util_ops.py b/tensorflow_quantum/core/ops/tfq_ps_util_ops.py index 5a90eb0b3..ad746d045 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 3ee1b3f61..14bccd9bf 100644 --- a/tensorflow_quantum/core/ops/tfq_ps_util_ops_test.py +++ b/tensorflow_quantum/core/ops/tfq_ps_util_ops_test.py @@ -11,12 +11,11 @@ # 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 import sys - NEW_PATH = [x for x in sys.path if 'com_google_protobuf' not in x] sys.path = NEW_PATH # pylint: enable=wrong-import-position diff --git a/tensorflow_quantum/core/ops/tfq_ps_weights_from_symbols_op.cc b/tensorflow_quantum/core/ops/tfq_ps_weights_from_symbols_op.cc index 65c03a77c..4a027223e 100644 --- a/tensorflow_quantum/core/ops/tfq_ps_weights_from_symbols_op.cc +++ b/tensorflow_quantum/core/ops/tfq_ps_weights_from_symbols_op.cc @@ -82,9 +82,9 @@ class TfqPsWeightsFromSymbolOp : public tensorflow::OpKernel { auto DoWork = [&](int start, int end) { for (int i = start; i < end; i++) { Program cur_program = programs.at(i); - for (size_t j = 0; j < cur_program.circuit().moments().size(); j++) { + for (int j = 0; j < cur_program.circuit().moments().size(); j++) { Moment cur_moment = cur_program.circuit().moments().at(j); - for (size_t k = 0; k < cur_moment.operations().size(); k++) { + for (int k = 0; k < cur_moment.operations().size(); k++) { Operation cur_op = cur_moment.operations().at(k); if (ignored_symbol_set.contains(cur_op.gate().id())) continue; @@ -146,10 +146,10 @@ class TfqPsWeightsFromSymbolOp : public tensorflow::OpKernel { auto DoWork2 = [&](int start, int end) { for (int i = start; i < end; i++) { for (int j = 0; j < n_symbols; j++) { - for (size_t k = 0; k < output_results.at(i).at(j).size(); k++) { + for (int k = 0; k < output_results.at(i).at(j).size(); k++) { output_tensor(i, j, k) = output_results.at(i).at(j).at(k); } - for (size_t k = output_results.at(i).at(j).size(); + for (int k = output_results.at(i).at(j).size(); k < largest_single_symbol; k++) { output_tensor(i, j, k) = 0.0f; } diff --git a/tensorflow_quantum/core/ops/tfq_simulate_expectation_op.cc b/tensorflow_quantum/core/ops/tfq_simulate_expectation_op.cc index 210e9e93f..bca6d2f63 100644 --- a/tensorflow_quantum/core/ops/tfq_simulate_expectation_op.cc +++ b/tensorflow_quantum/core/ops/tfq_simulate_expectation_op.cc @@ -143,7 +143,7 @@ class TfqSimulateExpectationOp : public tensorflow::OpKernel { // Simulate programs one by one. Parallelizing over state vectors // we no longer parallelize over circuits. Each time we encounter a // a larger circuit we will grow the Statevector as necessary. - for (size_t i = 0; i < fused_circuits.size(); i++) { + for (int i = 0; i < fused_circuits.size(); i++) { int nq = num_qubits[i]; if (nq > largest_nq) { @@ -156,10 +156,10 @@ class TfqSimulateExpectationOp : public tensorflow::OpKernel { // the state if there is a possibility that circuit[i] and // circuit[i + 1] produce the same state. ss.SetStateZero(sv); - for (size_t j = 0; j < fused_circuits[i].size(); j++) { + for (int j = 0; j < fused_circuits[i].size(); j++) { qsim::ApplyFusedGate(sim, fused_circuits[i][j], sv); } - for (size_t j = 0; j < pauli_sums[i].size(); j++) { + for (int j = 0; j < pauli_sums[i].size(); j++) { // (#679) Just ignore empty program if (fused_circuits[i].size() == 0) { (*output_tensor)(i, j) = -2.0; @@ -221,7 +221,7 @@ class TfqSimulateExpectationOp : public tensorflow::OpKernel { // no need to update scratch_state since ComputeExpectation // will take care of things for us. ss.SetStateZero(sv); - for (size_t j = 0; j < fused_circuits[cur_batch_index].size(); j++) { + for (int j = 0; j < fused_circuits[cur_batch_index].size(); j++) { qsim::ApplyFusedGate(sim, fused_circuits[cur_batch_index][j], sv); } } diff --git a/tensorflow_quantum/core/ops/tfq_simulate_expectation_op_cuda.cu.cc b/tensorflow_quantum/core/ops/tfq_simulate_expectation_op_cuda.cu.cc deleted file mode 100644 index 20e5bfe8c..000000000 --- a/tensorflow_quantum/core/ops/tfq_simulate_expectation_op_cuda.cu.cc +++ /dev/null @@ -1,206 +0,0 @@ -/* Copyright 2020 The TensorFlow Quantum Authors. All Rights Reserved. -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - http://www.apache.org/licenses/LICENSE-2.0 -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -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. -==============================================================================*/ - -#include -#include - -#include - -#include "../qsim/lib/circuit.h" -#include "../qsim/lib/gate_appl.h" -#include "../qsim/lib/gates_cirq.h" -#include "../qsim/lib/gates_qsim.h" -#include "../qsim/lib/seqfor.h" -#include "../qsim/lib/simulator_cuda.h" -#include "../qsim/lib/statespace_cuda.h" -#include "tensorflow/core/framework/op_kernel.h" -#include "tensorflow/core/framework/shape_inference.h" -#include "tensorflow/core/framework/tensor_shape.h" -#include "tensorflow/core/lib/core/error_codes.pb.h" -#include "tensorflow/core/lib/core/status.h" -#include "tensorflow/core/lib/core/threadpool.h" -#include "tensorflow/core/platform/mutex.h" -#include "tensorflow_quantum/core/ops/parse_context.h" -#include "tensorflow_quantum/core/proto/pauli_sum.pb.h" -#include "tensorflow_quantum/core/proto/program.pb.h" -#include "tensorflow_quantum/core/src/util_qsim.h" - -namespace tfq { - -using ::tensorflow::Status; -using ::tfq::proto::PauliSum; -using ::tfq::proto::Program; - -typedef qsim::Cirq::GateCirq QsimGate; -typedef qsim::Circuit QsimCircuit; - -class TfqSimulateExpectationOpCuda : public tensorflow::OpKernel { - public: - explicit TfqSimulateExpectationOpCuda( - tensorflow::OpKernelConstruction* context) - : OpKernel(context) {} - - void Compute(tensorflow::OpKernelContext* context) override { - // TODO (mbbrough): add more dimension checks for other inputs here. - const int num_inputs = context->num_inputs(); - OP_REQUIRES(context, num_inputs == 4, - tensorflow::errors::InvalidArgument(absl::StrCat( - "Expected 4 inputs, got ", num_inputs, " inputs."))); - - // Create the output Tensor. - const int output_dim_batch_size = context->input(0).dim_size(0); - const int output_dim_op_size = context->input(3).dim_size(1); - tensorflow::TensorShape output_shape; - output_shape.AddDim(output_dim_batch_size); - output_shape.AddDim(output_dim_op_size); - - tensorflow::Tensor* output = nullptr; - tensorflow::AllocatorAttributes alloc_attr; - alloc_attr.set_on_host(true); - alloc_attr.set_gpu_compatible(true); - OP_REQUIRES_OK(context, context->allocate_output(0, output_shape, &output, - alloc_attr)); - auto output_tensor = output->matrix(); - // Parse program protos. - std::vector programs; - std::vector num_qubits; - std::vector> pauli_sums; - OP_REQUIRES_OK(context, GetProgramsAndNumQubits(context, &programs, - &num_qubits, &pauli_sums)); - - std::vector maps; - OP_REQUIRES_OK(context, GetSymbolMaps(context, &maps)); - - OP_REQUIRES(context, programs.size() == maps.size(), - tensorflow::errors::InvalidArgument(absl::StrCat( - "Number of circuits and symbol_values do not match. Got ", - programs.size(), " circuits and ", maps.size(), - " symbol values."))); - - // Construct qsim circuits. - std::vector qsim_circuits(programs.size(), QsimCircuit()); - std::vector>> fused_circuits( - programs.size(), std::vector>({})); - - Status parse_status = Status(); - auto p_lock = tensorflow::mutex(); - auto construct_f = [&](int start, int end) { - for (int i = start; i < end; i++) { - Status local = - QsimCircuitFromProgram(programs[i], maps[i], num_qubits[i], - &qsim_circuits[i], &fused_circuits[i]); - NESTED_FN_STATUS_SYNC(parse_status, local, p_lock); - } - }; - - const int num_cycles = 1000; - context->device()->tensorflow_cpu_worker_threads()->workers->ParallelFor( - programs.size(), num_cycles, construct_f); - OP_REQUIRES_OK(context, parse_status); - - int max_num_qubits = 0; - for (const int num : num_qubits) { - max_num_qubits = std::max(max_num_qubits, num); - } - ComputeLarge(num_qubits, fused_circuits, pauli_sums, context, - &output_tensor); - } - - private: - int num_threads_in_sim_; - int block_count_; - - // Define the GPU implementation that launches the CUDA kernel. - void ComputeLarge( - const std::vector& num_qubits, - const std::vector>>& fused_circuits, - const std::vector>& pauli_sums, - tensorflow::OpKernelContext* context, - tensorflow::TTypes::Matrix* output_tensor) { - // Instantiate qsim objects. - using Simulator = qsim::SimulatorCUDA; - using StateSpace = Simulator::StateSpace; - // Begin simulation with default parameters. - int largest_nq = 1; - Simulator sim = Simulator(); - StateSpace ss = StateSpace(StateSpace::Parameter()); - auto sv = ss.Create(largest_nq); - auto scratch = ss.Create(largest_nq); - - // Simulate programs one by one. Parallelizing over state vectors - // we no longer parallelize over circuits. Each time we encounter a - // a larger circuit we will grow the Statevector as necessary. - for (int i = 0; i < fused_circuits.size(); i++) { - int nq = num_qubits[i]; - - if (nq > largest_nq) { - // need to switch to larger statespace. - largest_nq = nq; - sv = ss.Create(largest_nq); - scratch = ss.Create(largest_nq); - } - // TODO: add heuristic here so that we do not always recompute - // the state if there is a possibility that circuit[i] and - // circuit[i + 1] produce the same state. - ss.SetStateZero(sv); - for (int j = 0; j < fused_circuits[i].size(); j++) { - qsim::ApplyFusedGate(sim, fused_circuits[i][j], sv); - } - for (int j = 0; j < pauli_sums[i].size(); j++) { - // (#679) Just ignore empty program - if (fused_circuits[i].size() == 0) { - (*output_tensor)(i, j) = -2.0; - continue; - } - float exp_v = 0.0; - OP_REQUIRES_OK(context, - ComputeExpectationQsim(pauli_sums[i][j], sim, ss, sv, - scratch, &exp_v)); - (*output_tensor)(i, j) = exp_v; - } - } - } -}; - -REGISTER_KERNEL_BUILDER( - Name("TfqSimulateExpectationCuda").Device(tensorflow::DEVICE_CPU), - TfqSimulateExpectationOpCuda); - -REGISTER_OP("TfqSimulateExpectationCuda") - .Input("programs: string") - .Input("symbol_names: string") - .Input("symbol_values: float") - .Input("pauli_sums: string") - .Output("expectations: float") - .SetShapeFn([](tensorflow::shape_inference::InferenceContext* c) { - tensorflow::shape_inference::ShapeHandle programs_shape; - TF_RETURN_IF_ERROR(c->WithRank(c->input(0), 1, &programs_shape)); - - tensorflow::shape_inference::ShapeHandle symbol_names_shape; - TF_RETURN_IF_ERROR(c->WithRank(c->input(1), 1, &symbol_names_shape)); - - tensorflow::shape_inference::ShapeHandle symbol_values_shape; - TF_RETURN_IF_ERROR(c->WithRank(c->input(2), 2, &symbol_values_shape)); - - tensorflow::shape_inference::ShapeHandle pauli_sums_shape; - TF_RETURN_IF_ERROR(c->WithRank(c->input(3), 2, &pauli_sums_shape)); - - tensorflow::shape_inference::DimensionHandle output_rows = - c->Dim(programs_shape, 0); - tensorflow::shape_inference::DimensionHandle output_cols = - c->Dim(pauli_sums_shape, 1); - c->set_output(0, c->Matrix(output_rows, output_cols)); - - return ::tensorflow::Status(); - }); - -} // namespace tfq diff --git a/tensorflow_quantum/core/ops/tfq_simulate_expectation_op_cuquantum.cu.cc b/tensorflow_quantum/core/ops/tfq_simulate_expectation_op_cuquantum.cu.cc deleted file mode 100644 index 6c9f03eb7..000000000 --- a/tensorflow_quantum/core/ops/tfq_simulate_expectation_op_cuquantum.cu.cc +++ /dev/null @@ -1,220 +0,0 @@ -/* Copyright 2020 The TensorFlow Quantum Authors. All Rights Reserved. -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - http://www.apache.org/licenses/LICENSE-2.0 -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -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. -==============================================================================*/ - -#include -#include - -#include - -#include "../cuquantum_libs/include/custatevec.h" -#include "../qsim/lib/circuit.h" -#include "../qsim/lib/gate_appl.h" -#include "../qsim/lib/gates_cirq.h" -#include "../qsim/lib/gates_qsim.h" -#include "../qsim/lib/seqfor.h" -#include "../qsim/lib/simulator_custatevec.h" -#include "../qsim/lib/statespace_custatevec.h" -#include "tensorflow/core/framework/op_kernel.h" -#include "tensorflow/core/framework/shape_inference.h" -#include "tensorflow/core/framework/tensor_shape.h" -#include "tensorflow/core/lib/core/error_codes.pb.h" -#include "tensorflow/core/lib/core/status.h" -#include "tensorflow/core/lib/core/threadpool.h" -#include "tensorflow/core/platform/mutex.h" -#include "tensorflow_quantum/core/ops/parse_context.h" -#include "tensorflow_quantum/core/proto/pauli_sum.pb.h" -#include "tensorflow_quantum/core/proto/program.pb.h" -#include "tensorflow_quantum/core/src/util_qsim.h" - -namespace tfq { - -using ::tensorflow::Status; -using ::tfq::proto::PauliSum; -using ::tfq::proto::Program; - -typedef qsim::Cirq::GateCirq QsimGate; -typedef qsim::Circuit QsimCircuit; - -class TfqSimulateExpectationOpCuQuantum : public tensorflow::OpKernel { - public: - explicit TfqSimulateExpectationOpCuQuantum( - tensorflow::OpKernelConstruction* context) - : OpKernel(context) {} - - void Compute(tensorflow::OpKernelContext* context) override { - // TODO (mbbrough): add more dimension checks for other inputs here. - const int num_inputs = context->num_inputs(); - OP_REQUIRES(context, num_inputs == 4, - tensorflow::errors::InvalidArgument(absl::StrCat( - "Expected 4 inputs, got ", num_inputs, " inputs."))); - - // Create the output Tensor. - const int output_dim_batch_size = context->input(0).dim_size(0); - const int output_dim_op_size = context->input(3).dim_size(1); - tensorflow::TensorShape output_shape; - output_shape.AddDim(output_dim_batch_size); - output_shape.AddDim(output_dim_op_size); - - tensorflow::Tensor* output = nullptr; - tensorflow::AllocatorAttributes alloc_attr; - alloc_attr.set_on_host(true); // why?? - alloc_attr.set_gpu_compatible(true); - OP_REQUIRES_OK(context, context->allocate_output(0, output_shape, &output, - alloc_attr)); - auto output_tensor = output->matrix(); - // Parse program protos. - std::vector programs; - std::vector num_qubits; - std::vector> - pauli_sums; // why is this a vector of vectors?? - OP_REQUIRES_OK(context, GetProgramsAndNumQubits(context, &programs, - &num_qubits, &pauli_sums)); - - std::vector maps; - OP_REQUIRES_OK(context, GetSymbolMaps(context, &maps)); - - OP_REQUIRES(context, programs.size() == maps.size(), - tensorflow::errors::InvalidArgument(absl::StrCat( - "Number of circuits and symbol_values do not match. Got ", - programs.size(), " circuits and ", maps.size(), - " symbol values."))); - - // Construct qsim circuits. - std::vector qsim_circuits(programs.size(), QsimCircuit()); - std::vector>> fused_circuits( - programs.size(), std::vector>({})); - - Status parse_status = Status::OK(); - auto p_lock = tensorflow::mutex(); - auto construct_f = [&](int start, int end) { - for (int i = start; i < end; i++) { - Status local = - QsimCircuitFromProgram(programs[i], maps[i], num_qubits[i], - &qsim_circuits[i], &fused_circuits[i]); - NESTED_FN_STATUS_SYNC(parse_status, local, p_lock); - } - }; - - const int num_cycles = 1000; - context->device()->tensorflow_cpu_worker_threads()->workers->ParallelFor( - programs.size(), num_cycles, construct_f); - OP_REQUIRES_OK(context, parse_status); - - int max_num_qubits = 0; - for (const int num : num_qubits) { - max_num_qubits = std::max(max_num_qubits, num); - } - - // create handles for simulator - cublasCreate(&cublas_handle_); - custatevecCreate(&custatevec_handle_); - - ComputeLarge(num_qubits, fused_circuits, pauli_sums, context, - &output_tensor); - - // destroy handles in sync with simulator lifetime - cublasDestroy(cublas_handle_); - custatevecDestroy(custatevec_handle_); - } - - private: - cublasHandle_t cublas_handle_; - custatevecHandle_t custatevec_handle_; - - // Define the GPU implementation that launches the CUDA kernel. - void ComputeLarge( - const std::vector& num_qubits, - const std::vector>>& fused_circuits, - const std::vector>& pauli_sums, - tensorflow::OpKernelContext* context, - tensorflow::TTypes::Matrix* output_tensor) { - // Instantiate qsim objects. - using Simulator = qsim::SimulatorCuStateVec; - using StateSpace = Simulator::StateSpace; - - // Launch the cuda kernel. - // Begin simulation. - int largest_nq = 1; - Simulator sim = Simulator(cublas_handle_, custatevec_handle_); - StateSpace ss = StateSpace(cublas_handle_, custatevec_handle_); - auto sv = ss.Create(largest_nq); - ss.SetStateZero(sv); - auto scratch = ss.Create(largest_nq); - - // Simulate programs one by one. Parallelizing over state vectors - // we no longer parallelize over circuits. Each time we encounter a - // a larger circuit we will grow the Statevector as necessary. - for (int i = 0; i < fused_circuits.size(); i++) { - int nq = num_qubits[i]; - - if (nq > largest_nq) { - // need to switch to larger statespace. - largest_nq = nq; - sv = ss.Create(largest_nq); - scratch = ss.Create(largest_nq); - } - // TODO: add heuristic here so that we do not always recompute - // the state if there is a possibility that circuit[i] and - // circuit[i + 1] produce the same state. - ss.SetStateZero(sv); - for (int j = 0; j < fused_circuits[i].size(); j++) { - qsim::ApplyFusedGate(sim, fused_circuits[i][j], sv); - } - for (int j = 0; j < pauli_sums[i].size(); j++) { - // (#679) Just ignore empty program - if (fused_circuits[i].size() == 0) { - (*output_tensor)(i, j) = -2.0; - continue; - } - float exp_v = 0.0; - OP_REQUIRES_OK(context, - ComputeExpectationQsim(pauli_sums[i][j], sim, ss, sv, - scratch, &exp_v)); - (*output_tensor)(i, j) = exp_v; - } - } - } -}; - -REGISTER_KERNEL_BUILDER( - Name("TfqSimulateExpectationCuquantum").Device(tensorflow::DEVICE_CPU), - TfqSimulateExpectationOpCuQuantum); - -REGISTER_OP("TfqSimulateExpectationCuquantum") - .Input("programs: string") - .Input("symbol_names: string") - .Input("symbol_values: float") - .Input("pauli_sums: string") - .Output("expectations: float") - .SetShapeFn([](tensorflow::shape_inference::InferenceContext* c) { - tensorflow::shape_inference::ShapeHandle programs_shape; - TF_RETURN_IF_ERROR(c->WithRank(c->input(0), 1, &programs_shape)); - - tensorflow::shape_inference::ShapeHandle symbol_names_shape; - TF_RETURN_IF_ERROR(c->WithRank(c->input(1), 1, &symbol_names_shape)); - - tensorflow::shape_inference::ShapeHandle symbol_values_shape; - TF_RETURN_IF_ERROR(c->WithRank(c->input(2), 2, &symbol_values_shape)); - - tensorflow::shape_inference::ShapeHandle pauli_sums_shape; - TF_RETURN_IF_ERROR(c->WithRank(c->input(3), 2, &pauli_sums_shape)); - - tensorflow::shape_inference::DimensionHandle output_rows = - c->Dim(programs_shape, 0); - tensorflow::shape_inference::DimensionHandle output_cols = - c->Dim(pauli_sums_shape, 1); - c->set_output(0, c->Matrix(output_rows, output_cols)); - - return tensorflow::Status::OK(); - }); - -} // namespace tfq diff --git a/tensorflow_quantum/core/ops/tfq_simulate_ops.py b/tensorflow_quantum/core/ops/tfq_simulate_ops.py index a68116c3e..17f1fd6bd 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_cuda.py b/tensorflow_quantum/core/ops/tfq_simulate_ops_cuda.py deleted file mode 100644 index d1a2ca4d2..000000000 --- a/tensorflow_quantum/core/ops/tfq_simulate_ops_cuda.py +++ /dev/null @@ -1,44 +0,0 @@ -# Copyright 2020 The TensorFlow Quantum Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# 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 cuda simulation python op.""" -import tensorflow as tf -from tensorflow_quantum.core.ops.load_module import load_module - -SIM_OP_MODULE = load_module("_tfq_simulate_ops_cuda.so") - - -def tfq_simulate_expectation(programs, symbol_names, symbol_values, pauli_sums): - """Calculates the expectation value of circuits wrt some operator(s). - Args: - programs: `tf.Tensor` of strings with shape [batch_size] containing - the string representations of the circuits to be executed. - symbol_names: `tf.Tensor` of strings with shape [n_params], which - is used to specify the order in which the values in - `symbol_values` should be placed inside of the circuits in - `programs`. - symbol_values: `tf.Tensor` of real numbers with shape - [batch_size, n_params] specifying parameter values to resolve - into the circuits specificed by programs, following the ordering - dictated by `symbol_names`. - pauli_sums: `tf.Tensor` of strings with shape [batch_size, n_ops] - containing the string representation of the operators that will - be used on all of the circuits in the expectation calculations. - 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). - """ - return SIM_OP_MODULE.tfq_simulate_expectation_cuda( - programs, symbol_names, tf.cast(symbol_values, tf.float32), pauli_sums) \ No newline at end of file diff --git a/tensorflow_quantum/core/ops/tfq_simulate_ops_cuquantum.py b/tensorflow_quantum/core/ops/tfq_simulate_ops_cuquantum.py deleted file mode 100644 index 785cce16c..000000000 --- a/tensorflow_quantum/core/ops/tfq_simulate_ops_cuquantum.py +++ /dev/null @@ -1,44 +0,0 @@ -# Copyright 2023 The TensorFlow Quantum Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# 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 - -SIM_OP_MODULE = load_module("_tfq_simulate_ops_cuquantum.so") - - -def tfq_simulate_expectation(programs, symbol_names, symbol_values, pauli_sums): - """Calculates the expectation value of circuits wrt some operator(s). - Args: - programs: `tf.Tensor` of strings with shape [batch_size] containing - the string representations of the circuits to be executed. - symbol_names: `tf.Tensor` of strings with shape [n_params], which - is used to specify the order in which the values in - `symbol_values` should be placed inside of the circuits in - `programs`. - symbol_values: `tf.Tensor` of real numbers with shape - [batch_size, n_params] specifying parameter values to resolve - into the circuits specificed by programs, following the ordering - dictated by `symbol_names`. - pauli_sums: `tf.Tensor` of strings with shape [batch_size, n_ops] - containing the string representation of the operators that will - be used on all of the circuits in the expectation calculations. - 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). - """ - return SIM_OP_MODULE.tfq_simulate_expectation_cuquantum( - programs, symbol_names, tf.cast(symbol_values, tf.float32), pauli_sums) \ No newline at end of file diff --git a/tensorflow_quantum/core/ops/tfq_simulate_ops_gpu_test.py b/tensorflow_quantum/core/ops/tfq_simulate_ops_gpu_test.py deleted file mode 100644 index eb1bc02f6..000000000 --- a/tensorflow_quantum/core/ops/tfq_simulate_ops_gpu_test.py +++ /dev/null @@ -1,139 +0,0 @@ -# Copyright 2020 The TensorFlow Quantum Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# 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 -import tensorflow as tf -import cirq - -from tensorflow_quantum.core.ops import tfq_simulate_ops -from tensorflow_quantum.core.ops import tfq_simulate_ops_cuda -from tensorflow_quantum.core.ops import tfq_simulate_ops_cuquantum -from tensorflow_quantum.python import util - - -def measure_average_runtime(fn, tag, num_samples=10): - """ - Measure the average runtime of a function. - - Args: - fn: A function to measure. - tag: A string to print. - num_samples: Number of samples to measure. - - Returns: - A tuple of (average runtime, function result). - """ - avg_time = [] - for _ in range(num_samples): - begin_time = time.time() - result = fn() - duration = time.time() - begin_time - avg_time.append(duration) - avg_time = sum(avg_time) / float(num_samples) - print(f"\n\t{tag} time: {avg_time}\n") - return avg_time, result - - -class SimulateExpectationGpuTest(tf.test.TestCase): - """Tests tfq_simulate_expectation.""" - - def test_simulate_expectation_cpu_vs_cuda(self): - """Make sure that cpu & gpu(cuda) ops have the same results.""" - n_qubits = 20 - batch_size = 5 - symbol_names = ['alpha'] - qubits = cirq.GridQubit.rect(1, n_qubits) - circuit_batch, resolver_batch = \ - util.random_symbol_circuit_resolver_batch( - qubits, symbol_names, batch_size) - - circuit_batch_tensor = util.convert_to_tensor(circuit_batch) - - symbol_values_array = np.array( - [[resolver[symbol] - for symbol in symbol_names] - for resolver in resolver_batch]) - - pauli_sums = util.random_pauli_sums(qubits, 3, batch_size) - pauli_sums_tensor = util.convert_to_tensor([[x] for x in pauli_sums]) - - cpu_avg_time, res_cpu = measure_average_runtime( - lambda: tfq_simulate_ops.tfq_simulate_expectation( - circuit_batch_tensor, symbol_names, - symbol_values_array.astype(np.float64), pauli_sums_tensor), - "CPU", - num_samples=100, - ) - - cuda_avg_time, res_cuda = measure_average_runtime( - lambda: tfq_simulate_ops_cuda.tfq_simulate_expectation( - circuit_batch_tensor, symbol_names, - symbol_values_array.astype(np.float64), pauli_sums_tensor), - "CUDA", - num_samples=100, - ) - - # The result should be the similar within a tolerance. - np.testing.assert_allclose(res_cpu, res_cuda, atol=1e-4) - - # CUDA op should be faster than CPU op. - self.assertGreater(cpu_avg_time, cuda_avg_time) - - def test_simulate_expectation_cpu_vs_cuquantum(self): - """Make sure that cpu & gpu(cuquantum) ops have the same results.""" - n_qubits = 20 - batch_size = 5 - symbol_names = ['alpha'] - qubits = cirq.GridQubit.rect(1, n_qubits) - circuit_batch, resolver_batch = \ - util.random_symbol_circuit_resolver_batch( - qubits, symbol_names, batch_size) - - circuit_batch_tensor = util.convert_to_tensor(circuit_batch) - - symbol_values_array = np.array( - [[resolver[symbol] - for symbol in symbol_names] - for resolver in resolver_batch]) - - pauli_sums = util.random_pauli_sums(qubits, 3, batch_size) - pauli_sums_tensor = util.convert_to_tensor([[x] for x in pauli_sums]) - - cpu_avg_time, res_cpu = measure_average_runtime( - lambda: tfq_simulate_ops.tfq_simulate_expectation( - circuit_batch_tensor, symbol_names, - symbol_values_array.astype(np.float64), pauli_sums_tensor), - "CPU", - num_samples=100, - ) - - cuda_avg_time, res_cuda = measure_average_runtime( - lambda: tfq_simulate_ops_cuquantum.tfq_simulate_expectation( - circuit_batch_tensor, symbol_names, - symbol_values_array.astype(np.float64), pauli_sums_tensor), - "cuQuantum", - num_samples=100, - ) - - # The result should be the similar within a tolerance. - np.testing.assert_allclose(res_cpu, res_cuda, atol=1e-4) - - # cuQuantum op should be faster than CPU op. - self.assertGreater(cpu_avg_time, cuda_avg_time) - - -if __name__ == "__main__": - tf.test.main() diff --git a/tensorflow_quantum/core/ops/tfq_simulate_ops_test.py b/tensorflow_quantum/core/ops/tfq_simulate_ops_test.py index cb1d05f10..4cdbe42e5 100644 --- a/tensorflow_quantum/core/ops/tfq_simulate_ops_test.py +++ b/tensorflow_quantum/core/ops/tfq_simulate_ops_test.py @@ -11,12 +11,11 @@ # 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 import sys - NEW_PATH = [x for x in sys.path if 'com_google_protobuf' not in x] sys.path = NEW_PATH # pylint: enable=wrong-import-position diff --git a/tensorflow_quantum/core/ops/tfq_simulate_state_op.cc b/tensorflow_quantum/core/ops/tfq_simulate_state_op.cc index 833deb965..e659800ce 100644 --- a/tensorflow_quantum/core/ops/tfq_simulate_state_op.cc +++ b/tensorflow_quantum/core/ops/tfq_simulate_state_op.cc @@ -135,8 +135,8 @@ class TfqSimulateStateOp : public tensorflow::OpKernel { // Simulate programs one by one. Parallelizing over state vectors // we no longer parallelize over circuits. Each time we encounter a - // a larger circuit we will grow the Statevector as necessary. - for (size_t i = 0; i < fused_circuits.size(); i++) { + // a larger circuit we will grow the Statevector as nescessary. + for (int i = 0; i < fused_circuits.size(); i++) { int nq = num_qubits[i]; if (nq > largest_nq) { @@ -145,7 +145,7 @@ class TfqSimulateStateOp : public tensorflow::OpKernel { sv = ss.Create(largest_nq); } ss.SetStateZero(sv); - for (size_t j = 0; j < fused_circuits[i].size(); j++) { + for (int j = 0; j < fused_circuits[i].size(); j++) { qsim::ApplyFusedGate(sim, fused_circuits[i][j], sv); } @@ -194,7 +194,7 @@ class TfqSimulateStateOp : public tensorflow::OpKernel { sv = ss.Create(largest_nq); } ss.SetStateZero(sv); - for (size_t j = 0; j < fused_circuits[i].size(); j++) { + for (int j = 0; j < fused_circuits[i].size(); j++) { qsim::ApplyFusedGate(sim, fused_circuits[i][j], sv); } diff --git a/tensorflow_quantum/core/ops/tfq_unitary_op.py b/tensorflow_quantum/core/ops/tfq_unitary_op.py index 775516896..5db7005db 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 04f8c576a..212094056 100644 --- a/tensorflow_quantum/core/ops/tfq_unitary_op_test.py +++ b/tensorflow_quantum/core/ops/tfq_unitary_op_test.py @@ -11,12 +11,11 @@ # 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 import sys - NEW_PATH = [x for x in sys.path if 'com_google_protobuf' not in x] sys.path = NEW_PATH # pylint: enable=wrong-import-position diff --git a/tensorflow_quantum/core/ops/tfq_utility_ops.py b/tensorflow_quantum/core/ops/tfq_utility_ops.py index 2d0d45def..e560f579c 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 806437176..00c5ff791 100644 --- a/tensorflow_quantum/core/ops/tfq_utility_ops_test.py +++ b/tensorflow_quantum/core/ops/tfq_utility_ops_test.py @@ -11,12 +11,11 @@ # 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 import sys - NEW_PATH = [x for x in sys.path if 'com_google_protobuf' not in x] sys.path = NEW_PATH # pylint: enable=wrong-import-position diff --git a/tensorflow_quantum/core/proto/__init__.py b/tensorflow_quantum/core/proto/__init__.py index be0da7259..bdbbd7a51 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 eebbe0156..6ee678723 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/op_deserializer_test.py b/tensorflow_quantum/core/serialize/op_deserializer_test.py index 634561d2b..ce1748b65 100644 --- a/tensorflow_quantum/core/serialize/op_deserializer_test.py +++ b/tensorflow_quantum/core/serialize/op_deserializer_test.py @@ -15,7 +15,6 @@ # Remove PYTHONPATH collisions for protobuf. # pylint: disable=wrong-import-position import sys - NEW_PATH = [x for x in sys.path if 'com_google_protobuf' not in x] sys.path = NEW_PATH # pylint: enable=wrong-import-position diff --git a/tensorflow_quantum/core/serialize/op_serializer_test.py b/tensorflow_quantum/core/serialize/op_serializer_test.py index 432dd117f..a485091e7 100644 --- a/tensorflow_quantum/core/serialize/op_serializer_test.py +++ b/tensorflow_quantum/core/serialize/op_serializer_test.py @@ -15,7 +15,6 @@ # Remove PYTHONPATH collisions for protobuf. # pylint: disable=wrong-import-position import sys - NEW_PATH = [x for x in sys.path if 'com_google_protobuf' not in x] sys.path = NEW_PATH # pylint: enable=wrong-import-position diff --git a/tensorflow_quantum/core/serialize/serializable_gate_set_test.py b/tensorflow_quantum/core/serialize/serializable_gate_set_test.py index e8f94b1db..1e6fd9861 100644 --- a/tensorflow_quantum/core/serialize/serializable_gate_set_test.py +++ b/tensorflow_quantum/core/serialize/serializable_gate_set_test.py @@ -15,7 +15,6 @@ # Remove PYTHONPATH collisions for protobuf. # pylint: disable=wrong-import-position import sys - NEW_PATH = [x for x in sys.path if 'com_google_protobuf' not in x] sys.path = NEW_PATH # pylint: enable=wrong-import-position diff --git a/tensorflow_quantum/core/serialize/serializer.py b/tensorflow_quantum/core/serialize/serializer.py index 80ddb6672..73b38ee16 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 d4e1667e6..a43da0cf0 100644 --- a/tensorflow_quantum/core/serialize/serializer_test.py +++ b/tensorflow_quantum/core/serialize/serializer_test.py @@ -11,12 +11,11 @@ # 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 import sys - NEW_PATH = [x for x in sys.path if 'com_google_protobuf' not in x] sys.path = NEW_PATH # pylint: enable=wrong-import-position @@ -100,7 +99,7 @@ def _build_op_proto(gate_id, arg_names, arg_vals, qubit_ids): if isinstance(arg_vals[i], str) else \ program_pb2.Arg( arg_value=program_pb2.ArgValue( - float_value=np.round(float(arg_vals[i]), 6)))) + float_value=np.round(float(arg_vals[i]), 6)))) \ for i in range(len(arg_vals))}, qubits=[program_pb2.Qubit( id=q_id) for q_id in qubit_ids])]) diff --git a/tensorflow_quantum/core/src/adj_util.cc b/tensorflow_quantum/core/src/adj_util.cc index e15ff8a8c..ceb76b2c1 100644 --- a/tensorflow_quantum/core/src/adj_util.cc +++ b/tensorflow_quantum/core/src/adj_util.cc @@ -38,7 +38,7 @@ void CreateGradientCircuit( const QsimCircuit& circuit, const std::vector& metadata, std::vector>>* partial_fuses, std::vector* grad_gates) { - for (size_t i = 0; i < metadata.size(); i++) { + for (int i = 0; i < metadata.size(); i++) { if (metadata[i].symbol_values.empty()) { continue; } @@ -78,7 +78,7 @@ void CreateGradientCircuit( // PhasedX else if (circuit.gates[i].kind == qsim::Cirq::GateKind::kPhasedXPowGate) { // Process potentially several symbols. - for (size_t j = 0; j < metadata[i].symbol_values.size(); j++) { + for (int j = 0; j < metadata[i].symbol_values.size(); j++) { if (metadata[i].placeholder_names[j] == GateParamNames::kPhaseExponent) { PopulateGradientPhasedXPhasedExponent( @@ -103,7 +103,7 @@ void CreateGradientCircuit( // Process potentially several symbols. bool swapq = circuit.gates[i].swapped; - for (size_t j = 0; j < metadata[i].symbol_values.size(); j++) { + for (int j = 0; j < metadata[i].symbol_values.size(); j++) { if (metadata[i].placeholder_names[j] == GateParamNames::kTheta) { PopulateGradientFsimTheta( metadata[i].symbol_values[j], i, @@ -128,7 +128,7 @@ void CreateGradientCircuit( qsim::Cirq::GateKind::kPhasedISwapPowGate) { // Process potentially several symbols. bool swapq = circuit.gates[i].swapped; - for (size_t j = 0; j < metadata[i].symbol_values.size(); j++) { + for (int j = 0; j < metadata[i].symbol_values.size(); j++) { if (metadata[i].placeholder_names[j] == GateParamNames::kPhaseExponent) { PopulateGradientPhasedISwapPhasedExponent( @@ -159,7 +159,7 @@ void CreateGradientCircuit( partial_fuses->assign(grad_gates->size() + 1, std::vector>({})); - for (size_t i = 0; i < grad_gates->size(); i++) { + for (int i = 0; i < grad_gates->size(); i++) { right = circuit.gates.begin() + (*grad_gates)[i].index; (*partial_fuses)[i] = fuser.FuseGates(qsim::BasicGateFuser::Parameter(), diff --git a/tensorflow_quantum/core/src/circuit_parser_qsim.cc b/tensorflow_quantum/core/src/circuit_parser_qsim.cc index 8b70ab041..1024d28c7 100644 --- a/tensorflow_quantum/core/src/circuit_parser_qsim.cc +++ b/tensorflow_quantum/core/src/circuit_parser_qsim.cc @@ -27,7 +27,6 @@ limitations under the License. #include "../qsim/lib/gates_cirq.h" #include "../qsim/lib/io.h" #include "absl/container/flat_hash_map.h" -#include "absl/status/status.h" #include "absl/strings/numbers.h" #include "absl/strings/str_split.h" #include "absl/strings/string_view.h" @@ -59,7 +58,7 @@ inline Status ParseProtoArg( // iterator> const auto arg_v = op.args().find(arg_name); if (arg_v == op.args().end()) { - return Status(static_cast( + return Status(static_cast( absl::StatusCode::kInvalidArgument), "Could not find arg: " + arg_name + " in op."); } @@ -72,7 +71,7 @@ inline Status ParseProtoArg( const auto iter = param_map.find(proto_arg.symbol()); if (iter == param_map.end()) { return Status( - static_cast( + static_cast( absl::StatusCode::kInvalidArgument), "Could not find symbol in parameter map: " + proto_arg.symbol()); } @@ -104,7 +103,7 @@ inline Status ParseProtoControls(const Operation& op, absl::StrSplit(control_v_str, ','); if (control_toks.size() != control_v_toks.size()) { - return Status(static_cast( + return Status(static_cast( absl::StatusCode::kInvalidArgument), "Mistmatched number of control qubits and control values."); } @@ -124,7 +123,7 @@ inline Status ParseProtoControls(const Operation& op, for (auto tok : control_v_toks) { valid = absl::SimpleAtoi(tok, &tmp); if (!valid) { - return Status(static_cast( + return Status(static_cast( absl::StatusCode::kInvalidArgument), "Unparseable control value: " + std::string(tok)); } @@ -187,8 +186,7 @@ inline Status TwoConstantGate( const unsigned int num_qubits, const unsigned int time, QsimCircuit* circuit, std::vector* metadata) { unsigned int q0, q1; - [[maybe_unused]] bool unused; - unused = absl::SimpleAtoi(op.qubits(0).id(), &q0); + bool unused = absl::SimpleAtoi(op.qubits(0).id(), &q0); unused = absl::SimpleAtoi(op.qubits(1).id(), &q1); auto gate = create_f(time, num_qubits - q0 - 1, num_qubits - q1 - 1); Status s = OptionalInsertControls(op, num_qubits, &gate); @@ -214,10 +212,9 @@ inline Status SingleEigenGate( const unsigned int num_qubits, const unsigned int time, QsimCircuit* circuit, std::vector* metadata) { unsigned int q0; - + bool unused; float exp, exp_s, gs; Status u; - [[maybe_unused]] bool unused; unused = absl::SimpleAtoi(op.qubits(0).id(), &q0); absl::optional exponent_symbol; @@ -265,9 +262,8 @@ inline Status TwoEigenGate( QsimCircuit* circuit, std::vector* metadata) { unsigned int q0, q1; float exp, exp_s, gs; - + bool unused; Status u; - [[maybe_unused]] bool unused; unused = absl::SimpleAtoi(op.qubits(0).id(), &q0); unused = absl::SimpleAtoi(op.qubits(1).id(), &q1); @@ -405,10 +401,9 @@ inline Status PhasedXGate(const Operation& op, const SymbolMap& param_map, const unsigned int time, QsimCircuit* circuit, std::vector* metadata) { int q0; - + bool unused; float pexp, pexp_s, exp, exp_s, gs; Status u; - [[maybe_unused]] bool unused; unused = absl::SimpleAtoi(op.qubits(0).id(), &q0); absl::optional exponent_symbol; @@ -466,10 +461,9 @@ inline Status FsimGate(const Operation& op, const SymbolMap& param_map, QsimCircuit* circuit, std::vector* metadata) { int q0, q1; - + bool unused; float theta, theta_s, phi, phi_s; Status u; - [[maybe_unused]] bool unused; unused = absl::SimpleAtoi(op.qubits(0).id(), &q0); unused = absl::SimpleAtoi(op.qubits(1).id(), &q1); @@ -524,10 +518,9 @@ inline Status PhasedISwapGate(const Operation& op, const SymbolMap& param_map, const unsigned int time, QsimCircuit* circuit, std::vector* metadata) { int q0, q1; - + bool unused; float pexp, pexp_s, exp, exp_s; Status u; - [[maybe_unused]] bool unused; unused = absl::SimpleAtoi(op.qubits(0).id(), &q0); unused = absl::SimpleAtoi(op.qubits(1).id(), &q1); @@ -602,7 +595,7 @@ tensorflow::Status ParseAppendGate(const Operation& op, auto build_f = func_map.find(op.gate().id()); if (build_f == func_map.end()) { *lookup_succeeded = false; - return Status(static_cast( + return Status(static_cast( absl::StatusCode::kInvalidArgument), absl::StrCat("Could not parse gate id: ", op.gate().id(), ". This is likely because a cirq.Channel was " @@ -617,10 +610,9 @@ inline Status AsymmetricDepolarizingChannel(const Operation& op, const unsigned int time, NoisyQsimCircuit* ncircuit) { int q; - + bool unused; float p_x, p_y, p_z; Status u; - [[maybe_unused]] bool unused; unused = absl::SimpleAtoi(op.qubits(0).id(), &q); u = ParseProtoArg(op, "p_x", {}, &p_x); @@ -640,10 +632,9 @@ inline Status DepolarizingChannel(const Operation& op, const unsigned int time, NoisyQsimCircuit* ncircuit) { int q; - + bool unused; float p; Status u; - [[maybe_unused]] bool unused; unused = absl::SimpleAtoi(op.qubits(0).id(), &q); u = ParseProtoArg(op, "p", {}, &p); @@ -659,10 +650,9 @@ inline Status DepolarizingChannel(const Operation& op, inline Status GADChannel(const Operation& op, const unsigned int num_qubits, const unsigned int time, NoisyQsimCircuit* ncircuit) { int q; - + bool unused; float p, gamma; Status u; - [[maybe_unused]] bool unused; unused = absl::SimpleAtoi(op.qubits(0).id(), &q); u = ParseProtoArg(op, "p", {}, &p); @@ -684,8 +674,7 @@ inline Status ResetChannel(const Operation& op, const unsigned int num_qubits, const unsigned int time, NoisyQsimCircuit* ncircuit) { int q; - - [[maybe_unused]] bool unused; + bool unused; unused = absl::SimpleAtoi(op.qubits(0).id(), &q); auto chan = qsim::Cirq::ResetChannel::Create(time, num_qubits - q - 1); @@ -698,10 +687,9 @@ inline Status AmplitudeDampingChannel(const Operation& op, const unsigned int time, NoisyQsimCircuit* ncircuit) { int q; - + bool unused; float gamma; Status u; - [[maybe_unused]] bool unused; unused = absl::SimpleAtoi(op.qubits(0).id(), &q); u = ParseProtoArg(op, "gamma", {}, &gamma); @@ -719,10 +707,9 @@ inline Status PhaseDampingChannel(const Operation& op, const unsigned int time, NoisyQsimCircuit* ncircuit) { int q; - + bool unused; float gamma; Status u; - [[maybe_unused]] bool unused; unused = absl::SimpleAtoi(op.qubits(0).id(), &q); u = ParseProtoArg(op, "gamma", {}, &gamma); @@ -741,10 +728,9 @@ inline Status PhaseFlipChannel(const Operation& op, const unsigned int time, NoisyQsimCircuit* ncircuit) { int q; - + bool unused; float p; Status u; - [[maybe_unused]] bool unused; unused = absl::SimpleAtoi(op.qubits(0).id(), &q); u = ParseProtoArg(op, "p", {}, &p); @@ -762,10 +748,9 @@ inline Status BitFlipChannel(const Operation& op, const unsigned int num_qubits, const unsigned int time, NoisyQsimCircuit* ncircuit) { int q; - + bool unused; float p; Status u; - [[maybe_unused]] bool unused; unused = absl::SimpleAtoi(op.qubits(0).id(), &q); u = ParseProtoArg(op, "p", {}, &p); @@ -795,7 +780,7 @@ tensorflow::Status ParseAppendChannel(const Operation& op, auto build_f = chan_func_map.find(op.gate().id()); if (build_f == chan_func_map.end()) { - return Status(static_cast( + return Status(static_cast( absl::StatusCode::kInvalidArgument), absl::StrCat("Could not parse channel id: ", op.gate().id())); } @@ -866,8 +851,7 @@ tensorflow::Status QsimCircuitFromProgram( // Convert proto to qsim internal representation. circuit->num_qubits = num_qubits; int time = 0; - [[maybe_unused]] bool unused; - + bool unused; // Special case empty. if (num_qubits <= 0) { return ::tensorflow::Status(); diff --git a/tensorflow_quantum/core/src/circuit_parser_qsim_test.cc b/tensorflow_quantum/core/src/circuit_parser_qsim_test.cc index 811ecd430..e6ea68e80 100644 --- a/tensorflow_quantum/core/src/circuit_parser_qsim_test.cc +++ b/tensorflow_quantum/core/src/circuit_parser_qsim_test.cc @@ -23,7 +23,6 @@ limitations under the License. #include "../qsim/lib/circuit_noisy.h" #include "../qsim/lib/gates_cirq.h" #include "absl/container/flat_hash_map.h" -#include "absl/status/status.h" #include "absl/strings/numbers.h" #include "gtest/gtest.h" #include "tensorflow/core/lib/core/status.h" @@ -65,7 +64,7 @@ Arg MakeControlArg(const std::string& val) { } inline void AssertControlEqual(const QsimGate& a, const QsimGate& b) { - for (size_t i = 0; i < a.controlled_by.size(); i++) { + for (int i = 0; i < a.controlled_by.size(); i++) { ASSERT_EQ(a.controlled_by[i], b.controlled_by[i]); } ASSERT_EQ(a.cmask, b.cmask); @@ -90,14 +89,14 @@ inline void AssertOneQubitEqual(const QsimGate& a, const QsimGate& b) { inline void AssertChannelEqual(const QsimChannel& a, const QsimChannel& b) { ASSERT_EQ(a.size(), b.size()); - for (size_t i = 0; i < a.size(); i++) { + for (int i = 0; i < a.size(); i++) { ASSERT_EQ(a[i].kind, b[i].kind); ASSERT_EQ(a[i].unitary, b[i].unitary); ASSERT_NEAR(a[i].prob, b[i].prob, 1e-5); auto a_k_ops = a[i].ops; auto b_k_ops = b[i].ops; EXPECT_EQ(a_k_ops.size(), b_k_ops.size()); - for (size_t j = 0; j < a_k_ops.size(); j++) { + for (int j = 0; j < a_k_ops.size(); j++) { AssertOneQubitEqual(a_k_ops[j], b_k_ops[j]); } } diff --git a/tensorflow_quantum/core/src/program_resolution.cc b/tensorflow_quantum/core/src/program_resolution.cc index 86e3ab897..0fbda9368 100644 --- a/tensorflow_quantum/core/src/program_resolution.cc +++ b/tensorflow_quantum/core/src/program_resolution.cc @@ -20,7 +20,6 @@ limitations under the License. #include "absl/container/flat_hash_map.h" #include "absl/container/flat_hash_set.h" -#include "absl/status/status.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_join.h" #include "absl/strings/str_split.h" @@ -67,17 +66,17 @@ Status RegisterQubits( } if (splits.size() != 2) { - return Status(static_cast( + return Status(static_cast( absl::StatusCode::kInvalidArgument), absl::StrCat("Unable to parse qubit: ", qb)); } if (!absl::SimpleAtoi(splits[0], &r)) { - return Status(static_cast( + return Status(static_cast( absl::StatusCode::kInvalidArgument), absl::StrCat("Unable to parse qubit: ", qb)); } if (!absl::SimpleAtoi(splits[1], &c)) { - return Status(static_cast( + return Status(static_cast( absl::StatusCode::kInvalidArgument), absl::StrCat("Unable to parse qubit: ", qb)); } @@ -173,7 +172,7 @@ Status ResolveQubitIds(Program* program, unsigned int* num_qubits, const auto result = id_to_index.find(pair.qubit_id()); if (result == id_to_index.end()) { return Status( - static_cast( + static_cast( absl::StatusCode::kInvalidArgument), "Found a Pauli sum operating on qubits not found in circuit."); } @@ -265,7 +264,7 @@ Status ResolveQubitIds(Program* program, unsigned int* num_qubits, visited_qubits.erase(qubit.id()); const auto result = id_to_index.find(qubit.id()); if (result == id_to_index.end()) { - return Status(static_cast( + return Status(static_cast( absl::StatusCode::kInvalidArgument), "A paired circuit contains qubits not found in " "reference circuit."); @@ -288,7 +287,7 @@ Status ResolveQubitIds(Program* program, unsigned int* num_qubits, visited_qubits.erase(id); const auto result = id_to_index.find(id); if (result == id_to_index.end()) { - return Status(static_cast( + return Status(static_cast( absl::StatusCode::kInvalidArgument), "A paired circuit contains qubits not found in " "reference circuit."); @@ -303,7 +302,7 @@ Status ResolveQubitIds(Program* program, unsigned int* num_qubits, } if (!visited_qubits.empty()) { return Status( - static_cast( + static_cast( absl::StatusCode::kInvalidArgument), "A reference circuit contains qubits not found in paired circuit."); } @@ -324,7 +323,7 @@ Status ResolveSymbols( if (iter == param_map.end()) { if (resolve_all) { return Status( - static_cast( + static_cast( absl::StatusCode::kInvalidArgument), "Could not find symbol in parameter map: " + arg.symbol()); } @@ -365,7 +364,7 @@ Status CheckMPSSupported(const Program& program) { const int total_num_qubits = qubits.size() + control_ids.size(); if (total_num_qubits > 2) { return Status( - static_cast( + static_cast( absl::StatusCode::kInvalidArgument), absl::StrCat("1D operations only support 1 and 2 qubit gates. " "Found: ", @@ -373,7 +372,7 @@ Status CheckMPSSupported(const Program& program) { } if (total_num_qubits == 2) { - size_t j = 0; + int j = 0; std::vector qids(2, -1234); for (; j < qubits.size(); j++) { (void)absl::SimpleAtoi(qubits[j].id(), &qids[j]); @@ -384,7 +383,7 @@ Status CheckMPSSupported(const Program& program) { // Are the two qubits not neighbors? if (std::abs((int)qids[0] - (int)qids[1]) > 1) { - return Status(static_cast( + return Status(static_cast( absl::StatusCode::kInvalidArgument), "A program is not in 1D topology. It contains an" " operation with qubits not neighbors each other."); diff --git a/tensorflow_quantum/core/src/program_resolution_test.cc b/tensorflow_quantum/core/src/program_resolution_test.cc index 450d5d1cf..2a4e61151 100644 --- a/tensorflow_quantum/core/src/program_resolution_test.cc +++ b/tensorflow_quantum/core/src/program_resolution_test.cc @@ -20,7 +20,6 @@ limitations under the License. #include #include "absl/container/flat_hash_map.h" -#include "absl/status/status.h" #include "gtest/gtest.h" #include "tensorflow/core/lib/core/status.h" #include "tensorflow_quantum/core/proto/program.pb.h" @@ -236,7 +235,7 @@ TEST(ProgramResolutionTest, ResolveQubitIdsInvalidControlQubit) { .mutable_arg_value() ->set_string_value("junk"); EXPECT_EQ(ResolveQubitIds(&program, &qubit_count), - tensorflow::Status(static_cast( + tensorflow::Status(static_cast( absl::StatusCode::kInvalidArgument), "Unable to parse qubit: junk")); } @@ -253,7 +252,7 @@ TEST(ProgramResolutionTest, ResolveQubitIdsInvalidQubit) { ->mutable_qubits(0) ->set_id("junk"); EXPECT_EQ(ResolveQubitIds(&program, &qubit_count), - tensorflow::Status(static_cast( + tensorflow::Status(static_cast( absl::StatusCode::kInvalidArgument), "Unable to parse qubit: junk")); } @@ -303,7 +302,7 @@ TEST(ProgramResolutionTest, ResolveQubitIdsWithInvalidPauliSum) { EXPECT_EQ(ResolveQubitIds(&program, &qubit_count, &p_sums), tensorflow::Status( - static_cast( + static_cast( absl::StatusCode::kInvalidArgument), "Found a Pauli sum operating on qubits not found in circuit.")); } @@ -377,7 +376,7 @@ TEST(ProgramResolutionTest, ResolveQubitIdsMultiProgramInvalid) { ->set_id("junk"); std::vector others = {other, other}; EXPECT_EQ(ResolveQubitIds(&program, &qubit_count, &others), - tensorflow::Status(static_cast( + tensorflow::Status(static_cast( absl::StatusCode::kInvalidArgument), "Unable to parse qubit: junk")); } @@ -398,7 +397,7 @@ TEST(ProgramResolutionTest, ResolveQubitIdsMultiProgramInvalidControl) { ->set_string_value("junk"); std::vector others = {other, other}; EXPECT_EQ(ResolveQubitIds(&program, &qubit_count, &others), - tensorflow::Status(static_cast( + tensorflow::Status(static_cast( absl::StatusCode::kInvalidArgument), "Unable to parse qubit: junk")); } @@ -419,7 +418,7 @@ TEST(ProgramResolutionTest, ResolveQubitIdsMultiProgramMismatch) { EXPECT_EQ( ResolveQubitIds(&program, &qubit_count, &others), tensorflow::Status( - static_cast( + static_cast( absl::StatusCode::kInvalidArgument), "A paired circuit contains qubits not found in reference circuit.")); } @@ -442,7 +441,7 @@ TEST(ProgramResolutionTest, ResolveQubitIdsMultiProgramMismatchControl) { EXPECT_EQ( ResolveQubitIds(&program, &qubit_count, &others), tensorflow::Status( - static_cast( + static_cast( absl::StatusCode::kInvalidArgument), "A paired circuit contains qubits not found in reference circuit.")); } @@ -463,7 +462,7 @@ TEST(ProgramResolutionTest, ResolveQubitIdsMultiProgramSmaller) { EXPECT_EQ( ResolveQubitIds(&program, &qubit_count, &others), tensorflow::Status( - static_cast( + static_cast( absl::StatusCode::kInvalidArgument), "A reference circuit contains qubits not found in paired circuit.")); } @@ -486,7 +485,7 @@ TEST(ProgramResolutionTest, ResolveQubitIdsMultiProgramSmallerControl) { EXPECT_EQ( ResolveQubitIds(&program, &qubit_count, &others), tensorflow::Status( - static_cast( + static_cast( absl::StatusCode::kInvalidArgument), "A reference circuit contains qubits not found in paired circuit.")); } @@ -547,7 +546,7 @@ TEST(ProgramResolutionTest, ResolveSymbolsStrictPartial) { const absl::flat_hash_map> param_map = { {"v1", {0, 1.0}}}; EXPECT_EQ(ResolveSymbols(param_map, &symbol_program, true), - Status(static_cast( + Status(static_cast( absl::StatusCode::kInvalidArgument), "Could not find symbol in parameter map: v2")); } @@ -587,7 +586,7 @@ TEST(ProgramResolutionTest, CheckQubitsIn1DFailedByOpWithMoreThan2Qubits) { ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString( three_qubit_op_program, &program_with_3qubit_op)); EXPECT_EQ(CheckMPSSupported(program_with_3qubit_op), - Status(static_cast( + Status(static_cast( absl::StatusCode::kInvalidArgument), "1D operations only support 1 and 2 qubit gates. " "Found: 3 qubit gate.")); @@ -599,7 +598,7 @@ TEST(ProgramResolutionTest, ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString( valid_program, &program_with_3qubit_op)); EXPECT_EQ(CheckMPSSupported(program_with_3qubit_op), - Status(static_cast( + Status(static_cast( absl::StatusCode::kInvalidArgument), "1D operations only support 1 and 2 qubit gates. " "Found: 3 qubit gate.")); @@ -610,7 +609,7 @@ TEST(ProgramResolutionTest, CheckQubitsIn1DFailedByNot1DTopology) { ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString( resolved_qubit_program_not_1d, &program_not_1d)); EXPECT_EQ(CheckMPSSupported(program_not_1d), - Status(static_cast( + Status(static_cast( absl::StatusCode::kInvalidArgument), "A program is not in 1D topology. It contains an" " operation with qubits not neighbors each other.")); diff --git a/tensorflow_quantum/core/src/util_qsim.h b/tensorflow_quantum/core/src/util_qsim.h index adf38705e..f08715343 100644 --- a/tensorflow_quantum/core/src/util_qsim.h +++ b/tensorflow_quantum/core/src/util_qsim.h @@ -453,13 +453,13 @@ static void BalanceTrajectory(const std::vector>& num_samples, std::vector rep_limits(num_samples.size(), -1); std::vector height(num_threads, 0); - for (size_t i = 0; i < num_samples.size(); i++) { - for (size_t j = 0; j < num_samples[i].size(); j++) { + for (int i = 0; i < num_samples.size(); i++) { + for (int j = 0; j < num_samples[i].size(); j++) { rep_limits[i] = std::max(rep_limits[i], num_samples[i][j]); } } int prev_max_height = -1; - for (size_t j = 0; j < num_samples.size(); j++) { + for (int j = 0; j < num_samples.size(); j++) { int run_ceiling = ((rep_limits[j] + num_threads - 1) / num_threads); int num_lo = num_threads * run_ceiling - rep_limits[j]; int num_hi = num_threads - num_lo; @@ -498,7 +498,7 @@ static void BalanceTrajectory(const int& num_samples, const int& num_threads, std::vector height(num_threads, 0); int prev_max_height = -1; - for (size_t j = 0; j < (*thread_offsets)[0].size(); j++) { + for (int j = 0; j < (*thread_offsets)[0].size(); j++) { int run_ceiling = ((num_samples + num_threads - 1) / num_threads); int num_lo = num_threads * run_ceiling - num_samples; int num_hi = num_threads - num_lo; diff --git a/tensorflow_quantum/core/src/util_qsim_test.cc b/tensorflow_quantum/core/src/util_qsim_test.cc index 400c16d76..b4f630f3c 100644 --- a/tensorflow_quantum/core/src/util_qsim_test.cc +++ b/tensorflow_quantum/core/src/util_qsim_test.cc @@ -646,13 +646,13 @@ static void AssertWellBalanced(const std::vector>& n_reps, const int& num_threads, const std::vector>& offsets) { auto max_work = std::vector(n_reps.size(), -1); - for (size_t i = 0; i < n_reps.size(); i++) { - for (size_t j = 0; j < n_reps[0].size(); j++) { + for (int i = 0; i < n_reps.size(); i++) { + for (int j = 0; j < n_reps[0].size(); j++) { max_work[i] = std::max(max_work[i], n_reps[i][j]); } } - for (size_t i = 0; i < n_reps.size(); i++) { + for (int i = 0; i < n_reps.size(); i++) { int sum = 0; int prev_local_work = 0; for (int k = 0; k < num_threads; k++) { diff --git a/tensorflow_quantum/datasets/__init__.py b/tensorflow_quantum/datasets/__init__.py index 8ec6a1e5a..de1192fd4 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 59c35997f..2c7f5a909 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 0b675d145..49e75309d 100644 --- a/tensorflow_quantum/datasets/cluster_state_test.py +++ b/tensorflow_quantum/datasets/cluster_state_test.py @@ -11,12 +11,11 @@ # 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 import sys - NEW_PATH = [x for x in sys.path if 'com_google_protobuf' not in x] sys.path = NEW_PATH # pylint: enable=wrong-import-position diff --git a/tensorflow_quantum/datasets/spin_system.py b/tensorflow_quantum/datasets/spin_system.py index 3d53d5eae..4a180a68f 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 200120a65..3dac53a80 100644 --- a/tensorflow_quantum/datasets/spin_system_test.py +++ b/tensorflow_quantum/datasets/spin_system_test.py @@ -11,12 +11,11 @@ # 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 import sys - NEW_PATH = [x for x in sys.path if 'com_google_protobuf' not in x] sys.path = NEW_PATH # pylint: enable=wrong-import-position @@ -28,8 +27,7 @@ from tensorflow_quantum.datasets.spin_system import SpinSystemInfo -# TODO(#748): Inherit this class from tf.test.TestCase after fixing the issue. -class TFIChainTest: +class TFIChainTest(tf.test.TestCase): """Testing tfi_chain.""" # pylint: disable=C0103 diff --git a/tensorflow_quantum/python/__init__.py b/tensorflow_quantum/python/__init__.py index a66da1f02..afc3cd168 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/__init__.py b/tensorflow_quantum/python/differentiators/__init__.py index 8ce0a4889..ab386b22c 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 44b8e9da6..95ff5554e 100644 --- a/tensorflow_quantum/python/differentiators/adjoint.py +++ b/tensorflow_quantum/python/differentiators/adjoint.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 tensorflow as tf diff --git a/tensorflow_quantum/python/differentiators/adjoint_test.py b/tensorflow_quantum/python/differentiators/adjoint_test.py index 640a87d30..ffbf9173e 100644 --- a/tensorflow_quantum/python/differentiators/adjoint_test.py +++ b/tensorflow_quantum/python/differentiators/adjoint_test.py @@ -11,12 +11,11 @@ # 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 import sys - NEW_PATH = [x for x in sys.path if 'com_google_protobuf' not in x] sys.path = NEW_PATH # pylint: enable=wrong-import-position diff --git a/tensorflow_quantum/python/differentiators/differentiator.py b/tensorflow_quantum/python/differentiators/differentiator.py index bb3668a92..4b1d597ed 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 diff --git a/tensorflow_quantum/python/differentiators/differentiator_test.py b/tensorflow_quantum/python/differentiators/differentiator_test.py index b61b2a323..6f21f2e18 100644 --- a/tensorflow_quantum/python/differentiators/differentiator_test.py +++ b/tensorflow_quantum/python/differentiators/differentiator_test.py @@ -11,12 +11,11 @@ # 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 import sys - NEW_PATH = [x for x in sys.path if 'com_google_protobuf' not in x] sys.path = NEW_PATH # pylint: enable=wrong-import-position diff --git a/tensorflow_quantum/python/differentiators/gradient_test.py b/tensorflow_quantum/python/differentiators/gradient_test.py index b85506b0d..f666ad801 100644 --- a/tensorflow_quantum/python/differentiators/gradient_test.py +++ b/tensorflow_quantum/python/differentiators/gradient_test.py @@ -11,12 +11,11 @@ # 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 import sys - NEW_PATH = [x for x in sys.path if 'com_google_protobuf' not in x] sys.path = NEW_PATH # pylint: enable=wrong-import-position diff --git a/tensorflow_quantum/python/differentiators/linear_combination.py b/tensorflow_quantum/python/differentiators/linear_combination.py index cee6959bd..aae72d8ae 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 @@ -305,8 +305,9 @@ def __init__(self, error_order=2, grid_spacing=0.001): np.arange(1, error_order / 2 + 1) ]) weights = [] - n = error_order / 2 + n = int(error_order / 2) for k in grid_points_to_eval: + k = int(k) numerator = (-1)**(k + 1) * np.math.factorial(n)**2 denom = k * np.math.factorial(n - k) * np.math.factorial(n + k) weights.append(numerator / (denom * grid_spacing)) diff --git a/tensorflow_quantum/python/differentiators/linear_combination_test.py b/tensorflow_quantum/python/differentiators/linear_combination_test.py index ecb223816..f46b086e4 100644 --- a/tensorflow_quantum/python/differentiators/linear_combination_test.py +++ b/tensorflow_quantum/python/differentiators/linear_combination_test.py @@ -11,12 +11,11 @@ # 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 import sys - NEW_PATH = [x for x in sys.path if 'com_google_protobuf' not in x] sys.path = NEW_PATH # pylint: enable=wrong-import-position diff --git a/tensorflow_quantum/python/differentiators/parameter_shift.py b/tensorflow_quantum/python/differentiators/parameter_shift.py index 8a4ef9c3a..bf1631bba 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 d40b2257e..5a0846f25 100644 --- a/tensorflow_quantum/python/differentiators/parameter_shift_test.py +++ b/tensorflow_quantum/python/differentiators/parameter_shift_test.py @@ -11,12 +11,11 @@ # 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 import sys - NEW_PATH = [x for x in sys.path if 'com_google_protobuf' not in x] sys.path = NEW_PATH # pylint: enable=wrong-import-position diff --git a/tensorflow_quantum/python/differentiators/parameter_shift_util.py b/tensorflow_quantum/python/differentiators/parameter_shift_util.py index 34889c69a..266b3b68e 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 a8178be6e..8c1083a10 100644 --- a/tensorflow_quantum/python/differentiators/parameter_shift_util_test.py +++ b/tensorflow_quantum/python/differentiators/parameter_shift_util_test.py @@ -11,12 +11,11 @@ # 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 import sys - NEW_PATH = [x for x in sys.path if 'com_google_protobuf' not in x] sys.path = NEW_PATH # pylint: enable=wrong-import-position diff --git a/tensorflow_quantum/python/layers/__init__.py b/tensorflow_quantum/python/layers/__init__.py index 3de402f8d..88f2e5dad 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 765f26e83..0c5ded5c5 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 13574c435..66714f800 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 6d07cd2e1..38577dbe9 100644 --- a/tensorflow_quantum/python/layers/circuit_construction/elementary_test.py +++ b/tensorflow_quantum/python/layers/circuit_construction/elementary_test.py @@ -11,12 +11,11 @@ # 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 import sys - NEW_PATH = [x for x in sys.path if 'com_google_protobuf' not in x] sys.path = NEW_PATH # pylint: enable=wrong-import-position diff --git a/tensorflow_quantum/python/layers/circuit_executors/__init__.py b/tensorflow_quantum/python/layers/circuit_executors/__init__.py index 0ce744835..74d26d3e0 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 35d0c1b50..c3b1d913e 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 diff --git a/tensorflow_quantum/python/layers/circuit_executors/expectation_test.py b/tensorflow_quantum/python/layers/circuit_executors/expectation_test.py index 1ef7b99fc..e4489e763 100644 --- a/tensorflow_quantum/python/layers/circuit_executors/expectation_test.py +++ b/tensorflow_quantum/python/layers/circuit_executors/expectation_test.py @@ -11,12 +11,11 @@ # 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 import sys - NEW_PATH = [x for x in sys.path if 'com_google_protobuf' not in x] sys.path = NEW_PATH # pylint: enable=wrong-import-position diff --git a/tensorflow_quantum/python/layers/circuit_executors/input_checks.py b/tensorflow_quantum/python/layers/circuit_executors/input_checks.py index 9855b5b74..b73fbde26 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 304b365e1..affbd55d7 100644 --- a/tensorflow_quantum/python/layers/circuit_executors/input_checks_test.py +++ b/tensorflow_quantum/python/layers/circuit_executors/input_checks_test.py @@ -11,12 +11,11 @@ # 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 import sys - NEW_PATH = [x for x in sys.path if 'com_google_protobuf' not in x] sys.path = NEW_PATH # pylint: enable=wrong-import-position diff --git a/tensorflow_quantum/python/layers/circuit_executors/sample.py b/tensorflow_quantum/python/layers/circuit_executors/sample.py index 750885c20..616d811bc 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 diff --git a/tensorflow_quantum/python/layers/circuit_executors/sample_test.py b/tensorflow_quantum/python/layers/circuit_executors/sample_test.py index 7103759b4..b83848132 100644 --- a/tensorflow_quantum/python/layers/circuit_executors/sample_test.py +++ b/tensorflow_quantum/python/layers/circuit_executors/sample_test.py @@ -11,12 +11,11 @@ # 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 import sys - NEW_PATH = [x for x in sys.path if 'com_google_protobuf' not in x] sys.path = NEW_PATH # pylint: enable=wrong-import-position diff --git a/tensorflow_quantum/python/layers/circuit_executors/sampled_expectation.py b/tensorflow_quantum/python/layers/circuit_executors/sampled_expectation.py index fa434e332..ebc750e59 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 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 b027cfbe5..4e96a5c49 100644 --- a/tensorflow_quantum/python/layers/circuit_executors/sampled_expectation_test.py +++ b/tensorflow_quantum/python/layers/circuit_executors/sampled_expectation_test.py @@ -11,12 +11,11 @@ # 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 import sys - NEW_PATH = [x for x in sys.path if 'com_google_protobuf' not in x] sys.path = NEW_PATH # pylint: enable=wrong-import-position diff --git a/tensorflow_quantum/python/layers/circuit_executors/state.py b/tensorflow_quantum/python/layers/circuit_executors/state.py index f2b213ee1..6f979139a 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 diff --git a/tensorflow_quantum/python/layers/circuit_executors/state_test.py b/tensorflow_quantum/python/layers/circuit_executors/state_test.py index 8904014b7..8addb0d8f 100644 --- a/tensorflow_quantum/python/layers/circuit_executors/state_test.py +++ b/tensorflow_quantum/python/layers/circuit_executors/state_test.py @@ -11,12 +11,11 @@ # 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 import sys - NEW_PATH = [x for x in sys.path if 'com_google_protobuf' not in x] sys.path = NEW_PATH # pylint: enable=wrong-import-position diff --git a/tensorflow_quantum/python/layers/circuit_executors/unitary.py b/tensorflow_quantum/python/layers/circuit_executors/unitary.py index 73bd40c83..34e9385f7 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 30a84eecd..7330c807f 100644 --- a/tensorflow_quantum/python/layers/circuit_executors/unitary_test.py +++ b/tensorflow_quantum/python/layers/circuit_executors/unitary_test.py @@ -11,12 +11,11 @@ # 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 import sys - NEW_PATH = [x for x in sys.path if 'com_google_protobuf' not in x] sys.path = NEW_PATH # pylint: enable=wrong-import-position diff --git a/tensorflow_quantum/python/layers/high_level/__init__.py b/tensorflow_quantum/python/layers/high_level/__init__.py index 19e1a000b..2f7bd6580 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 a61b4b50e..588a8aa59 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 11f7e1e59..0d9e76e7e 100644 --- a/tensorflow_quantum/python/layers/high_level/controlled_pqc_test.py +++ b/tensorflow_quantum/python/layers/high_level/controlled_pqc_test.py @@ -11,12 +11,11 @@ # 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 import sys - NEW_PATH = [x for x in sys.path if 'com_google_protobuf' not in x] sys.path = NEW_PATH # pylint: enable=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 9a3b86eec..f3239e443 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 111f2c506..57ecf6cff 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,12 +11,11 @@ # 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 import sys - NEW_PATH = [x for x in sys.path if 'com_google_protobuf' not in x] sys.path = NEW_PATH # pylint: enable=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 2c6796231..05cb535e8 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 ea56115c0..112838912 100644 --- a/tensorflow_quantum/python/layers/high_level/noisy_pqc_test.py +++ b/tensorflow_quantum/python/layers/high_level/noisy_pqc_test.py @@ -11,12 +11,11 @@ # 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 import sys - NEW_PATH = [x for x in sys.path if 'com_google_protobuf' not in x] sys.path = NEW_PATH # pylint: enable=wrong-import-position diff --git a/tensorflow_quantum/python/layers/high_level/pqc.py b/tensorflow_quantum/python/layers/high_level/pqc.py index 229ded921..e370be294 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 33b74fedb..e6d831c66 100644 --- a/tensorflow_quantum/python/layers/high_level/pqc_test.py +++ b/tensorflow_quantum/python/layers/high_level/pqc_test.py @@ -11,12 +11,11 @@ # 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 import sys - NEW_PATH = [x for x in sys.path if 'com_google_protobuf' not in x] sys.path = NEW_PATH # pylint: enable=wrong-import-position diff --git a/tensorflow_quantum/python/optimizers/__init__.py b/tensorflow_quantum/python/optimizers/__init__.py index 1a1d97d41..d93023205 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 3376cd20e..5bf23f6a0 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 0687f4ee3..1d3a2965f 100755 --- a/tensorflow_quantum/python/optimizers/rotosolve_minimizer_test.py +++ b/tensorflow_quantum/python/optimizers/rotosolve_minimizer_test.py @@ -11,12 +11,11 @@ # 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 import sys - NEW_PATH = [x for x in sys.path if 'com_google_protobuf' not in x] sys.path = NEW_PATH # pylint: enable=wrong-import-position diff --git a/tensorflow_quantum/python/optimizers/spsa_minimizer.py b/tensorflow_quantum/python/optimizers/spsa_minimizer.py index 10a915ee0..471b46d9e 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 33dcb180e..1de86d86c 100644 --- a/tensorflow_quantum/python/optimizers/spsa_minimizer_test.py +++ b/tensorflow_quantum/python/optimizers/spsa_minimizer_test.py @@ -11,12 +11,11 @@ # 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 import sys - NEW_PATH = [x for x in sys.path if 'com_google_protobuf' not in x] sys.path = NEW_PATH # pylint: enable=wrong-import-position diff --git a/tensorflow_quantum/python/quantum_context.py b/tensorflow_quantum/python/quantum_context.py index 1a869bdea..44c01cdeb 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 7f7a62d58..5b219b1dc 100644 --- a/tensorflow_quantum/python/quantum_context_test.py +++ b/tensorflow_quantum/python/quantum_context_test.py @@ -11,12 +11,11 @@ # 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 import sys - NEW_PATH = [x for x in sys.path if 'com_google_protobuf' not in x] sys.path = NEW_PATH # pylint: enable=wrong-import-position diff --git a/tensorflow_quantum/python/util.py b/tensorflow_quantum/python/util.py index c736a403f..92ebeabee 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 0e1159806..3d4e2dd76 100644 --- a/tensorflow_quantum/python/util_test.py +++ b/tensorflow_quantum/python/util_test.py @@ -11,12 +11,11 @@ # 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 import sys - NEW_PATH = [x for x in sys.path if 'com_google_protobuf' not in x] sys.path = NEW_PATH # pylint: enable=wrong-import-position