Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Bug] Use torch.no_grad() in the QNG-SPSA algorithm #25

Merged
merged 1 commit into from
Oct 14, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 23 additions & 23 deletions qadence_libs/qinfo_tools/qng.py
Original file line number Diff line number Diff line change
Expand Up @@ -215,29 +215,29 @@ def qng_spsa(

See :class:`~qadence_libs.qinfo_tools.QuantumNaturalGradient` for details.
"""
with torch.no_grad():
# Get estimation of the QFI matrix
vparams_dict = dict(zip(vparams_keys, vparams_values))
qfi_estimator, qfi_mat_positive_sd = get_quantum_fisher_spsa(
circuit=circuit,
iteration=state["iter"],
vparams_dict=vparams_dict,
previous_qfi_estimator=state["qfi_estimator"],
epsilon=epsilon,
beta=beta,
)

# Get estimation of the QFI matrix
vparams_dict = dict(zip(vparams_keys, vparams_values))
qfi_estimator, qfi_mat_positive_sd = get_quantum_fisher_spsa(
circuit=circuit,
iteration=state["iter"],
vparams_dict=vparams_dict,
previous_qfi_estimator=state["qfi_estimator"],
epsilon=epsilon,
beta=beta,
)

# Get transformed gradient vector solving the least squares problem
transf_grad = torch.linalg.lstsq(
0.25 * qfi_mat_positive_sd,
grad_vec,
driver="gelsd",
).solution
# Get transformed gradient vector solving the least squares problem
transf_grad = torch.linalg.lstsq(
0.25 * qfi_mat_positive_sd,
grad_vec,
driver="gelsd",
).solution

for i, p in enumerate(vparams_values):
if p.grad is None:
continue
p.data.add_(transf_grad[i], alpha=-lr)
for i, p in enumerate(vparams_values):
if p.grad is None:
continue
p.data.add_(transf_grad[i], alpha=-lr)

state["iter"] += 1
state["qfi_estimator"] = qfi_estimator
state["iter"] += 1
state["qfi_estimator"] = qfi_estimator