Skip to content

DiffMethod ​

DiffMethod is an enumeration that selects the differentiation strategy used by VQCircuit.get_gradients and VQCircuit.get_gradients_and_expectation to compute parameter gradients.

Overview ​

The choice of differentiation method determines how the gradient of the expectation value with respect to each variational parameter is computed. Different methods trade off circuit evaluation count, memory usage, and numerical accuracy.

Enum Values ​

ValueDescription
ADJOINT_DIFFAdjoint differentiation method. Computes gradients by running the circuit forward and then backward (adjoint), requiring only two circuit evaluations regardless of the number of parameters. Based on the method described in Jones and Gacon, "Efficient calculation of gradients in classical simulations of variational quantum algorithms" (arXiv:2009.02823).

Usage ​

Pass a DiffMethod value to the gradient computation methods of VQCircuit:

python
import numpy as np
from pyqpanda3.core import RY, CNOT
from pyqpanda3.vqcircuit import VQCircuit, DiffMethod
from pyqpanda3.hamiltonian import Hamiltonian

# Build a simple variational circuit with 4 parameters
vqc = VQCircuit()
vqc.set_Param([4])
p0 = vqc.Param([0])
p1 = vqc.Param([1])
p2 = vqc.Param([2])
p3 = vqc.Param([3])
vqc << RY(0, p0) << RY(1, p1)
vqc << CNOT(0, 1)
vqc << RY(0, p2) << RY(1, p3)

params = np.array([0.1, 0.2, 0.3, 0.4])
hamiltonian = Hamiltonian({"Z0 Z1": 1.0, "Z0": 0.5, "Z1": 0.3})

# Use adjoint differentiation
grads = vqc.get_gradients(params, hamiltonian, DiffMethod.ADJOINT_DIFF)
print("Gradients:", grads.gradients())

# Also available with expectation value
result = vqc.get_gradients_and_expectation(params, hamiltonian, DiffMethod.ADJOINT_DIFF)
print("Expectation:", result.expectation_val())
print("Gradients:", result.gradients())

运行结果:

Gradients: [0.0179528385604528, -0.721177868772871, -0.3633729025298299, -0.6801970817746747]
Expectation: 1.5189304033281137
Gradients: [0.0179528385604528, -0.721177868772871, -0.3633729025298299, -0.6801970817746747]

References ​

  • T. Jones and S. Gacon, "Efficient calculation of gradients in classical simulations of variational quantum algorithms," arXiv:2009.02823, 2020. Available at https://arxiv.org/abs/2009.02823.

See Also ​

Released under the MIT License.