<br />

|---|
| [![](https://www.tensorflow.org/images/GitHub-Mark-32px.png) View source on GitHub](https://github.com/tensorflow/quantum/blob/v0.7.6/tensorflow_quantum/python/differentiators/parameter_shift.py#L22-L108) |

Calculate the general version of parameter-shift rule based gradients.

Inherits From: [`Differentiator`](https://www.tensorflow.org/quantum/api_docs/python/tfq/differentiators/Differentiator)

### Used in the notebooks

| Used in the tutorials |
|---|
| - [Calculate gradients](https://www.tensorflow.org/quantum/tutorials/gradients) |

This ParameterShift is the gradient estimator of the following paper:

[arXiv:1905.13311](https://arxiv.org/abs/1905.13311), Gavin E. Crooks.

This ParameterShift is used for any programs with parameterized gates.
It internally decomposes any programs into array of gates with at most
two distinct eigenvalues.

    non_diff_op = tfq.get_expectation_op()
    linear_differentiator = tfq.differentiators.ParameterShift()
    # Get an expectation op, with this differentiator attached.
    op = linear_differentiator.generate_differentiable_op(
        analytic_op=non_diff_op
    )
    qubit = cirq.GridQubit(0, 0)
    circuit = tfq.convert_to_tensor([
        cirq.Circuit(cirq.X(qubit) ** sympy.Symbol('alpha'))
    ])
    psums = tfq.convert_to_tensor([[cirq.Z(qubit)]])
    symbol_values = np.array([[0.123]], dtype=np.float32)
    # Calculate tfq gradient.
    symbol_values_t = tf.convert_to_tensor(symbol_values)
    symbol_names = tf.convert_to_tensor(['alpha'])
    with tf.GradientTape() as g:
        g.watch(symbol_values_t)
        expectations = op(circuit, symbol_names, symbol_values_t, psums)
    # This value is now computed via the ParameterShift rule.
    # https://arxiv.org/abs/1905.13311
    grads = g.gradient(expectations, symbol_values_t)
    grads
    tf.Tensor([[-1.1839752]], shape=(1, 1), dtype=float32)

## Methods

### `differentiate_analytic`

[View source](https://github.com/tensorflow/quantum/blob/v0.7.6/tensorflow_quantum/python/differentiators/differentiator.py#L327-L389)

    @tf.function
    differentiate_analytic(
        programs, symbol_names, symbol_values, pauli_sums, forward_pass_vals, grad
    )

Differentiate a circuit with analytical expectation.

This is called at graph runtime by TensorFlow. `differentiate_analytic`
calls the inheriting differentiator's `get_gradient_circuits` and uses
those components to construct the gradient.

> [!NOTE]
> **Note:** the default implementation does not use `forward_pass_vals`; the inheriting differentiator is free to override the default implementation and use this argument if desired.

<br />

<br />

<br />

| Args ||
|---|---|
| `programs` | [`tf.Tensor`](https://www.tensorflow.org/api_docs/python/tf/Tensor) of strings with shape \[batch_size\] containing the string representations of the circuits to be executed. |
| `symbol_names` | [`tf.Tensor`](https://www.tensorflow.org/api_docs/python/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`](https://www.tensorflow.org/api_docs/python/tf/Tensor) of real numbers with shape \[batch_size, n_params\] specifying parameter values to resolve into the circuits specified by programs, following the ordering dictated by `symbol_names`. |
| `pauli_sums` | [`tf.Tensor`](https://www.tensorflow.org/api_docs/python/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. |
| `forward_pass_vals` | [`tf.Tensor`](https://www.tensorflow.org/api_docs/python/tf/Tensor) of real numbers with shape \[batch_size, n_ops\] containing the output of the forward pass through the op you are differentiating. |
| `grad` | [`tf.Tensor`](https://www.tensorflow.org/api_docs/python/tf/Tensor) of real numbers with shape \[batch_size, n_ops\] representing the gradient backpropagated to the output of the op you are differentiating through. |

<br />

<br />

<br />

<br />

| Returns ||
|---|---|
| A [`tf.Tensor`](https://www.tensorflow.org/api_docs/python/tf/Tensor) with the same shape as `symbol_values` representing the gradient backpropageted to the `symbol_values` input of the op you are differentiating through. ||

<br />

### `differentiate_sampled`

[View source](https://github.com/tensorflow/quantum/blob/v0.7.6/tensorflow_quantum/python/differentiators/differentiator.py#L391-L458)

    @tf.function
    differentiate_sampled(
        programs,
        symbol_names,
        symbol_values,
        pauli_sums,
        num_samples,
        forward_pass_vals,
        grad
    )

Differentiate a circuit with sampled expectation.

This is called at graph runtime by TensorFlow. `differentiate_sampled`
calls he inheriting differentiator's `get_gradient_circuits` and uses
those components to construct the gradient.

> [!NOTE]
> **Note:** the default implementation does not use `forward_pass_vals`; the inheriting differentiator is free to override the default implementation and use this argument if desired.

<br />

<br />

<br />

| Args ||
|---|---|
| `programs` | [`tf.Tensor`](https://www.tensorflow.org/api_docs/python/tf/Tensor) of strings with shape \[batch_size\] containing the string representations of the circuits to be executed. |
| `symbol_names` | [`tf.Tensor`](https://www.tensorflow.org/api_docs/python/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`](https://www.tensorflow.org/api_docs/python/tf/Tensor) of real numbers with shape \[batch_size, n_params\] specifying parameter values to resolve into the circuits specified by programs, following the ordering dictated by `symbol_names`. |
| `pauli_sums` | [`tf.Tensor`](https://www.tensorflow.org/api_docs/python/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. |
| `num_samples` | [`tf.Tensor`](https://www.tensorflow.org/api_docs/python/tf/Tensor) of positive integers representing the number of samples per term in each term of pauli_sums used during the forward pass. |
| `forward_pass_vals` | [`tf.Tensor`](https://www.tensorflow.org/api_docs/python/tf/Tensor) of real numbers with shape \[batch_size, n_ops\] containing the output of the forward pass through the op you are differentiating. |
| `grad` | [`tf.Tensor`](https://www.tensorflow.org/api_docs/python/tf/Tensor) of real numbers with shape \[batch_size, n_ops\] representing the gradient backpropagated to the output of the op you are differentiating through. |

<br />

<br />

<br />

<br />

| Returns ||
|---|---|
| A [`tf.Tensor`](https://www.tensorflow.org/api_docs/python/tf/Tensor) with the same shape as `symbol_values` representing the gradient backpropageted to the `symbol_values` input of the op you are differentiating through. ||

<br />

### `generate_differentiable_op`

[View source](https://github.com/tensorflow/quantum/blob/v0.7.6/tensorflow_quantum/python/differentiators/differentiator.py#L58-L187)

    generate_differentiable_op(
        *, sampled_op=None, analytic_op=None
    )

Generate a differentiable op by attaching self to an op.

This function returns a [`tf.function`](https://www.tensorflow.org/api_docs/python/tf/function) that passes values through to
`forward_op` during the forward pass and this differentiator (`self`) to
backpropagate through the op during the backward pass. If sampled_op
is provided the differentiators `differentiate_sampled` method will
be invoked (which requires sampled_op to be a sample based expectation
op with num_samples input tensor). If analytic_op is provided the
differentiators `differentiate_analytic` method will be invoked (which
requires analytic_op to be an analytic based expectation op that does
NOT have num_samples as an input). If both sampled_op and analytic_op
are provided an exception will be raised.

> [!CAUTION]
> **Caution:**

This `generate_differentiable_op()` can be called only ONCE because
of the `one differentiator per op` policy. You need to call `refresh()`
to reuse this differentiator with another op.

<br />

<br />

<br />

| Args ||
|---|---|
| `sampled_op` | A `callable` op that you want to make differentiable using this differentiator's `differentiate_sampled` method. |
| `analytic_op` | A `callable` op that you want to make differentiable using this differentiators `differentiate_analytic` method. |

<br />

<br />

<br />

<br />

| Returns ||
|---|---|
| A `callable` op that who's gradients are now registered to be a call to this differentiators `differentiate_*` function. ||

<br />

### `get_gradient_circuits`

[View source](https://github.com/tensorflow/quantum/blob/v0.7.6/tensorflow_quantum/python/differentiators/parameter_shift.py#L59-L108)

    @tf.function
    get_gradient_circuits(
        programs, symbol_names, symbol_values
    )

See base class description.

### `refresh`

[View source](https://github.com/tensorflow/quantum/blob/v0.7.6/tensorflow_quantum/python/differentiators/differentiator.py#L203-L209)

    refresh()

Refresh this differentiator in order to use it with other ops.