PennyLane
PreviousNext

To attempt this challenge, please switch to a larger screen size.

Beginner
Optimization

The Parameter-Shift Rule

Challenge Statement

In this challenge, you will compute the gradient of a QNode using the parameter-shift rule:

\frac{\partial f}{\partial \theta_i} = \frac{ f(\mathbf{\theta} + s \mathbf{\hat{e}}_i) - f(\mathbf{\theta} - s \mathbf{\hat{e}}_i) }{ 2\sin(s) },

where f(\bf{\theta})=\langle \psi |U^\dagger(\bf{\theta})\hat{O}U^\dagger(\bf{\theta})|\psi \rangle is the output of the variational circuit (the measured expectation value), and \bf{\hat{e}}_i is the i-th coordinate unit vector.

You are also asked to build the circuit in question, which is shown in the diagram below.

drawing

If you're stuck, you might find the following hints helpful:

  • PennyLane documentation
  • Quantum Gradients demo

Challenge code

In this challenge you must complete the following two functions.

  1. circuit: This QNode builds the circuit shown below and returns the expectation value of the Y_0\otimes Z_2 observable. The circuit depends on a set weights (np.ndarray) of six parameters given to you as a 2\times 3 matrix
\begin{pmatrix} w_{00} & w_{01} & w_{02}\\ w_{10} & w_ {11} & w_{12} \end{pmatrix}.
  1. parameter_shift: This function returns the gradient of the QNode computed via the parameter shift rule evaluated at weights (np.ndarray), given as a 2\times 3 matrix as above. The gradient must respect the shape of the input array, meaning that the output should be an np.ndarray of shape (2,3) corresponding to
\begin{pmatrix} \frac{\partial f}{\partial w_{00}} & \frac{\partial f}{\partial w_{01}} & \frac{\partial f}{\partial w_{02}}\\ \frac{\partial f}{\partial w_{10}} & \frac{\partial f}{\partial w_{11}} & \frac{\partial f}{\partial w_{12}} \end{pmatrix}.

Input

As input to this problem, you are given an np.ndarray of shape (2,3) corresponding to the weights as explained above.

Output

The output of your code should be an np.ndarray of shape (2,3) corresponding to the gradient.

Test cases

The following public test cases are available to you. Note that there are additional hidden test cases that we use to verify that your code is valid in full generality.

test_input: [[1,0.5,-0.765],[0.1,0,-0.654]] expected_output: [[0.0, 0.0, 0.0], [0.0, -0.455, 0.0]] test_input: [[0.94,-0.2,6.03],[-2.6,-0.058,1.2]] expected_output: [[0.03, -0.039, 0.0], [-0.034, 0.166, 0.0]]

If your solution matches the correct one within the given tolerance specified in check (in this case it's a 1e-2 absolute error tolerance), the output will be "Success!" Otherwise, you will receive an "Incorrect" prompt.

Good luck!

Loading...