-
Notifications
You must be signed in to change notification settings - Fork 22
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #95 from Zhaoyilunnn/master
Add paramshift prototype
- Loading branch information
Showing
6 changed files
with
109 additions
and
11 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,54 @@ | ||
# (C) Copyright 2023 Beijing Academy of Quantum Information Sciences | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
|
||
import numpy as np | ||
from typing import List | ||
from quafu.algorithms import Estimator | ||
from quafu.algorithms.hamiltonian import Hamiltonian | ||
|
||
|
||
class ParamShift: | ||
"""Parameter shift rule to calculate gradients""" | ||
|
||
def __init__(self, estimator: Estimator) -> None: | ||
self._est = estimator | ||
|
||
def __call__(self, obs: Hamiltonian, params: List[float]): | ||
"""Calculate gradients using paramshift. | ||
Args: | ||
estimator (Estimator): estimator to calculate expectation values | ||
params (List[float]): params to optimize | ||
""" | ||
return self._grad(obs, params) | ||
|
||
def _gen_param_shift_vals(self, params): | ||
"""Given a param list with n values, replicate to 2*n param list""" | ||
num_vals = len(params) | ||
params = np.array(params) | ||
offsets = np.identity(num_vals) | ||
plus_params = params + offsets * np.pi / 2 | ||
minus_params = params - offsets * np.pi / 2 | ||
return plus_params.tolist() + minus_params.tolist() | ||
|
||
def _grad(self, obs: Hamiltonian, params: List[float]): | ||
shifted_params_lists = self._gen_param_shift_vals(params) | ||
|
||
res = np.zeros(len(shifted_params_lists)) | ||
for i, shifted_params in enumerate(shifted_params_lists): | ||
res[i] = self._est.run(obs, shifted_params) | ||
|
||
n = len(res) | ||
grads = (res[: n // 2] - res[n // 2 :]) / 2 | ||
return grads |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,41 @@ | ||
# (C) Copyright 2023 Beijing Academy of Quantum Information Sciences | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
|
||
import pytest | ||
import sys | ||
from quafu.algorithms.estimator import Estimator | ||
from quafu.algorithms.hamiltonian import Hamiltonian | ||
from quafu.algorithms.optimizer import ParamShift | ||
from quafu.circuits.quantum_circuit import QuantumCircuit | ||
|
||
|
||
class TestParamShift: | ||
@pytest.mark.skipif( | ||
sys.platform == "darwin", reason="Avoid error on MacOS arm arch." | ||
) | ||
def test_call(self): | ||
ham = Hamiltonian.from_pauli_list([("ZZ", 1), ("XI", 1)]) | ||
circ = QuantumCircuit(2) | ||
# circ.h(0) | ||
# circ.h(1) | ||
circ.rx(0, 0.5) | ||
circ.cnot(0, 1) | ||
circ.ry(1, 0.5) | ||
|
||
params = [0.2, 0.6] | ||
estimator = Estimator(circ) | ||
grad = ParamShift(estimator) | ||
|
||
grads = grad(ham, params) | ||
print(grads) |