Skip to content

Commit

Permalink
Update gradient logic for Qiskit Rust circuit data implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
woodsp-ibm committed Jul 12, 2024
1 parent e0c63ec commit b257361
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 3 deletions.
20 changes: 17 additions & 3 deletions qiskit_algorithms/gradients/reverse/derive_circuit.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,8 +132,18 @@ def derive_circuit(
if parameter not in circuit.parameters:
raise ValueError(f"The parameter {parameter} is not in this circuit.")

if len(circuit._parameter_table[parameter]) > 1:
raise NotImplementedError("No product rule support yet, circuit parameters must be unique.")
if hasattr(circuit, "_parameter_table"):
if len(circuit._parameter_table[parameter]) > 1:
raise NotImplementedError(
"Product rule is not supported, circuit parameters must be unique."
)
else:
# Qiskit is moving circuit functionality to Rust and with the updated logic the former attribute
# which was used no longer exists.
if circuit._data._get_entry_count(parameter) > 1:
raise NotImplementedError(
"Product rule is not supported, circuit parameters must be unique."
)

summands, op_context = [], []
for i, op in enumerate(circuit.data):
Expand All @@ -151,7 +161,11 @@ def derive_circuit(
c = complex(1)
for i, term in enumerate(product_rule_term):
c *= term[0]
summand_circuit.data.append([term[1], *op_context[i]])
if hasattr(summand_circuit.data, "_resolve_legacy_value"):
value = summand_circuit.data._resolve_legacy_value(term[1], *op_context[i])
summand_circuit.data.append(value)
else:
summand_circuit.data.append([term[1], *op_context[i]])
gradient += [(c, summand_circuit.copy())]

return gradient
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
other:
- |
Aspects of the gradients internal implementation, which manipulate circuits more
directly, have been updated now that circuit data is being handled by Rust so it's
compatible with the former Python way as well as the new Qiskit Rust implementation.
12 changes: 12 additions & 0 deletions test/gradients/test_estimator_gradient.py
Original file line number Diff line number Diff line change
Expand Up @@ -512,6 +512,18 @@ def operations_callback(op):
with self.subTest(msg="assert result is correct"):
self.assertAlmostEqual(result.gradients[0].item(), expect, places=5)

def test_product_rule_check(self):
"""Test product rule check."""
p = Parameter("p")
qc = QuantumCircuit(1)
qc.rx(p, 0)
qc.ry(p, 0)

from qiskit_algorithms.gradients.reverse.derive_circuit import derive_circuit

with self.assertRaises(NotImplementedError):
_ = derive_circuit(qc, p)


if __name__ == "__main__":
unittest.main()

0 comments on commit b257361

Please sign in to comment.