def test_stochastic_differentiator_call_analytic(self, coordinate,
                                                     generator, cost, uniform):
        """Test if SGDifferentiator.differentiate_analytical doesn't crash
            before running."""
        programs, names, values, ops, _, true_f, true_g = \
        _simple_op_inputs()
        diff = stochastic_differentiator.SGDifferentiator(
            coordinate, generator, cost, uniform)
        op = diff.generate_differentiable_op(
            analytic_op=circuit_execution_ops.get_expectation_op())

        with tf.GradientTape() as g:
            g.watch(values)
            expectations = op(programs, names, values, ops)
        grads = g.gradient(expectations, values)
        self.assertAllClose(expectations, true_f, atol=1e-2, rtol=1e-2)
        self.assertAllClose(grads, true_g, atol=1e-2, rtol=1e-2)
class GradientBenchmarksTest(tf.test.TestCase, parameterized.TestCase):
    """Test the Gradient benchmarking class."""
    @parameterized.parameters(
        list(
            util.kwargs_cartesian_product(
                **{
                    'diff': [
                        linear_combination.ForwardDifference(),
                        linear_combination.CentralDifference(),
                        parameter_shift.ParameterShift(),
                        stochastic_differentiator.SGDifferentiator(),
                    ],
                    'params': [TEST_PARAMS_1, TEST_PARAMS_2]
                })))
    def testBenchmarkGradient(self, diff, params):
        """Test that op constructs and runs correctly."""

        bench_name = "GradientBenchmarks.{}_{}_{}_{}_{}".format(
            diff.__class__.__name__, params.n_qubits, params.n_moments,
            params.batch_size, params.n_symbols)
        proto_file_path = os.path.join(SRC, "reports/",
                                       "{}".format(bench_name))
        self.addCleanup(os.remove, proto_file_path)

        bench = GradientBenchmarks(params=params)
        bench.setup()
        bench._benchmark_tfq_differentiator(diff, params)

        res = benchmark_util.read_benchmark_entry(proto_file_path)
        self.assertEqual(res.name, bench_name)
        self.assertEqual(
            res.extras.get("n_qubits").double_value, params.n_qubits)
        self.assertEqual(
            res.extras.get("n_moments").double_value, params.n_moments)
        self.assertEqual(
            res.extras.get("op_density").double_value, params.op_density)
        assert hasattr(res, 'iters')
        assert hasattr(res, 'wall_time')
Esempio n. 3
0
from tensorflow_quantum.python.differentiators import linear_combination
from tensorflow_quantum.python.differentiators import parameter_shift
from tensorflow_quantum.python.differentiators import stochastic_differentiator
from tensorflow_quantum.core.ops import circuit_execution_ops, batch_util

DIFFS = [
    linear_combination.ForwardDifference(grid_spacing=0.0001),
    linear_combination.ForwardDifference(error_order=2, grid_spacing=0.0001),
    linear_combination.CentralDifference(grid_spacing=0.0001),
    linear_combination.CentralDifference(error_order=4, grid_spacing=0.0001),
    parameter_shift.ParameterShift(),
]

STOCHASTIC_DIFFS = [
    stochastic_differentiator.SGDifferentiator(stochastic_coordinate=False,
                                               stochastic_generator=False,
                                               stochastic_cost=False),
    stochastic_differentiator.SGDifferentiator(stochastic_coordinate=True,
                                               stochastic_generator=False,
                                               stochastic_cost=False),
    stochastic_differentiator.SGDifferentiator(stochastic_coordinate=False,
                                               stochastic_generator=True,
                                               stochastic_cost=False),
    stochastic_differentiator.SGDifferentiator(stochastic_coordinate=True,
                                               stochastic_generator=True,
                                               stochastic_cost=False),
]

OPS = [
    circuit_execution_ops.get_expectation_op(cirq.sim.Simulator()),  # WF
    circuit_execution_ops.get_expectation_op(
 def test_stochastic_differentiator_instantiate(self):
     """Test SGDifferentiator type checking."""
     stochastic_differentiator.SGDifferentiator()
     with self.assertRaisesRegex(
             TypeError, expected_regex="stochastic_coordinate must be"):
         stochastic_differentiator.SGDifferentiator(stochastic_coordinate=1)
         stochastic_differentiator.SGDifferentiator(
             stochastic_coordinate=0.1)
         stochastic_differentiator.SGDifferentiator(
             stochastic_coordinate=[1])
         stochastic_differentiator.SGDifferentiator(
             stochastic_coordinate="junk")
     with self.assertRaisesRegex(
             TypeError, expected_regex="stochastic_generator must be"):
         stochastic_differentiator.SGDifferentiator(stochastic_generator=1)
         stochastic_differentiator.SGDifferentiator(stochastic_generator=0.1)
         stochastic_differentiator.SGDifferentiator(stochastic_generator=[1])
         stochastic_differentiator.SGDifferentiator(
             stochastic_generator="junk")
     with self.assertRaisesRegex(TypeError,
                                 expected_regex="stochastic_cost must be"):
         stochastic_differentiator.SGDifferentiator(stochastic_cost=1)
         stochastic_differentiator.SGDifferentiator(stochastic_cost=0.1)
         stochastic_differentiator.SGDifferentiator(stochastic_cost=[1])
         stochastic_differentiator.SGDifferentiator(stochastic_cost="junk")
 def benchmark_stochastic_differentiator(self):
     """Benchmark the default stochastic differentiator."""
     diff = stochastic_differentiator.SGDifferentiator()
     self._benchmark_tfq_differentiator(diff, self.params)
Esempio n. 6
0
import numpy as np
import tensorflow as tf
from absl.testing import parameterized

import cirq
from tensorflow_quantum.python import util
from tensorflow_quantum.python.differentiators import stochastic_differentiator
from tensorflow_quantum.core.ops import tfq_simulate_ops, batch_util

# DISCLAIMER: Environment : Intel(R) Xeon(R) W-2135 CPU @ 3.70GHz, 12 cores.
# The overall tests take around 1 hours.
DIFFS_NUM_RUNS = [
    # The tests without sampling cost Hamiltonian take 1.5 hours.
    # Case 1 : ParameterShift ~ 0.04 sec/shot
    (stochastic_differentiator.SGDifferentiator(stochastic_coordinate=False,
                                                stochastic_generator=False,
                                                stochastic_cost=False), 1),
    # Case 2 : coordinate ~ 42 sec (0.04 sec/shot)
    (stochastic_differentiator.SGDifferentiator(stochastic_coordinate=True,
                                                stochastic_generator=False,
                                                stochastic_cost=False), 1100),
    # Case 3 : generator ~ 350 sec (0.023 sec/shot)
    (stochastic_differentiator.SGDifferentiator(stochastic_coordinate=False,
                                                stochastic_generator=True,
                                                stochastic_cost=False), 15000),
    # Case 4 : coordinate + generator ~ 400 sec ~ (0.020 sec/shot)
    (stochastic_differentiator.SGDifferentiator(stochastic_coordinate=True,
                                                stochastic_generator=True,
                                                stochastic_cost=False), 20000),
    # The tests with sampling cost Hamiltonian takes around 3 hours
    # Case 5 : cost ~ 35 sec (0.15 sec/shot)