-
Notifications
You must be signed in to change notification settings - Fork 23
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 #104 from Zhaoyilunnn/master
Autograd with param shift demo
- Loading branch information
Showing
14 changed files
with
328 additions
and
31 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
name: Unit test | ||
on: | ||
push: | ||
pull_request: | ||
branches: ['main'] | ||
jobs: | ||
unnittest: | ||
name: Unit test | ||
runs-on: ubuntu-latest | ||
steps: | ||
- uses: actions/checkout@v3 | ||
- uses: actions/setup-python@v4 | ||
name: Install Python | ||
with: | ||
python-version: '3.10' | ||
|
||
- name: Install dependency | ||
run: python -m pip install -r requirements.txt && python -m pip install pytest | ||
|
||
# TODO(zhaoyilun): Build seperate package for pyquafu-torch | ||
- name: Install torch | ||
run: python -m pip install torch torchvision torchaudio | ||
|
||
- name: Install pyquafu | ||
run: python -m pip install . | ||
|
||
- name: Run unit tests | ||
run: pytest tests/ |
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 |
---|---|---|
@@ -1,5 +1,5 @@ | ||
"""Algorithm module""" | ||
|
||
from .hamiltonian import * | ||
from .hamiltonian import Hamiltonian | ||
from .ansatz import * | ||
from .estimator import * |
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,15 @@ | ||
# (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. | ||
|
||
from .param_shift import ParamShift |
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 @@ | ||
from .qnode import compute_vjp, jacobian |
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,15 @@ | ||
# (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. | ||
|
||
"""Pre-built quafu circuit blocks""" |
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,86 @@ | ||
# (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. | ||
|
||
|
||
from typing import List, Optional | ||
import numpy as np | ||
from quafu import QuantumCircuit | ||
from quafu.algorithms import Hamiltonian | ||
from quafu.algorithms.estimator import Estimator | ||
from quafu.algorithms.gradients import ParamShift | ||
|
||
|
||
def _generate_expval_z(num_qubits: int): | ||
obs_list = [] | ||
base_pauli = "I" * num_qubits | ||
for i in range(num_qubits): | ||
pauli = base_pauli[:i] + "Z" + base_pauli[i + 1 :] | ||
obs_list.append(Hamiltonian.from_pauli_list([(pauli, 1)])) | ||
return obs_list | ||
|
||
|
||
# TODO(zhaoyilun): support more measurement types | ||
def run_circ(circ: QuantumCircuit, params: Optional[List[float]] = None): | ||
"""Execute a circuit | ||
Args: | ||
circ (QuantumCircuit): circ | ||
params (Optional[List[float]]): params | ||
""" | ||
obs_list = _generate_expval_z(circ.num) | ||
estimator = Estimator(circ) | ||
if params is None: | ||
params = [g.paras for g in circ.parameterized_gates] | ||
output = [estimator.run(obs, params) for obs in obs_list] | ||
return np.array(output) | ||
|
||
|
||
# TODO(zhaoyilun): support more gradient methods | ||
def jacobian(circ: QuantumCircuit, params_input: np.ndarray): | ||
"""Calculate Jacobian matrix | ||
Args: | ||
circ (QuantumCircuit): circ | ||
params_input (np.ndarray): params_input, with shape [batch_size, num_params] | ||
""" | ||
batch_size, num_params = params_input.shape | ||
obs_list = _generate_expval_z(circ.num) | ||
num_outputs = len(obs_list) | ||
estimator = Estimator(circ) | ||
calc_grad = ParamShift(estimator) | ||
output = np.zeros((batch_size, num_outputs, num_params)) | ||
for i in range(batch_size): | ||
grad_list = [ | ||
np.array(calc_grad(obs, params_input[i, :].tolist())) for obs in obs_list | ||
] | ||
output[i, :, :] = np.stack(grad_list) | ||
return output | ||
|
||
|
||
def compute_vjp(jac: np.ndarray, dy: np.ndarray): | ||
"""compute vector-jacobian product | ||
Args: | ||
jac (np.ndarray): jac with shape (batch_size, num_outputs, num_params) | ||
dy (np.ndarray): dy with shape (batch_size, num_outputs) | ||
""" | ||
batch_size, num_outputs, num_params = jac.shape | ||
assert dy.shape[0] == batch_size and dy.shape[1] == num_outputs | ||
|
||
vjp = np.zeros((batch_size, num_params)) | ||
|
||
for i in range(batch_size): | ||
vjp[i] = dy[i, :].T @ jac[i, :, :] | ||
|
||
return vjp |
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,61 @@ | ||
# (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. | ||
|
||
"""quafu PyTorch quantum layer""" | ||
|
||
import torch | ||
import numpy as np | ||
from quafu import QuantumCircuit | ||
from quafu.algorithms.layers.qnode import compute_vjp, jacobian | ||
|
||
|
||
class ExecuteCircuits(torch.autograd.Function): | ||
"""TODO(zhaoyilun): document""" | ||
|
||
@staticmethod | ||
def forward(ctx, parameters, kwargs): | ||
ctx.run_fn = kwargs["run_fn"] | ||
ctx.circ = kwargs["circ"] | ||
ctx.save_for_backward(parameters) | ||
parameters = parameters.numpy().tolist() | ||
outputs = [] | ||
for para in parameters: | ||
out = ctx.run_fn(ctx.circ, para) | ||
outputs.append(out) | ||
outputs = np.stack(outputs) | ||
outputs = torch.from_numpy(outputs) | ||
return outputs | ||
|
||
@staticmethod | ||
def backward(ctx, grad_out): | ||
(parameters,) = ctx.saved_tensors | ||
jac = jacobian(ctx.circ, parameters.numpy()) | ||
vjp = compute_vjp(jac, grad_out.numpy()) | ||
vjp = torch.from_numpy(vjp) | ||
return vjp, None | ||
|
||
|
||
# TODO(zhaoyilun): doc | ||
def execute(circ: QuantumCircuit, run_fn, grad_fn, parameters: torch.Tensor): | ||
"""execute. | ||
Args: | ||
circ: | ||
run_fn: | ||
grad_fn: | ||
""" | ||
|
||
kwargs = {"circ": circ, "run_fn": run_fn, "grad_fn": grad_fn} | ||
|
||
return ExecuteCircuits.apply(parameters, kwargs) |
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,15 @@ | ||
# (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. | ||
|
||
"""Simulate the execution of a quantum circuit using pytorch""" |
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
Oops, something went wrong.