Skip to content

Commit

Permalink
Merge branch 'dev' into more_gh_actions_test
Browse files Browse the repository at this point in the history
  • Loading branch information
01110011011101010110010001101111 authored Nov 25, 2023
2 parents 52391de + 2988f27 commit 53ed825
Show file tree
Hide file tree
Showing 14 changed files with 806 additions and 391 deletions.
10 changes: 7 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,19 @@


<p align="center">
<a href="https://github.com/mit-han-lab/torchquantum/blob/master/LICENSE">
<img alt="MIT License" src="https://img.shields.io/github/license/mit-han-lab/torchquantum">
</a>
<a href="https://torchquantum.readthedocs.io/">
<img alt="Documentation" src="https://img.shields.io/readthedocs/torchquantum/main">
</a>
<a href="https://github.com/mit-han-lab/torchquantum/blob/master/LICENSE">
<img alt="MIT License" src="https://img.shields.io/github/license/mit-han-lab/torchquantum">
</a>

<a href="https://join.slack.com/t/torchquantum/shared_invite/zt-1ghuf283a-OtP4mCPJREd~367VX~TaQQ">
<img alt="Chat @ Slack" src="https://img.shields.io/badge/slack-chat-2eb67d.svg?logo=slack">
</a>
<a href="https://discord.gg/VTHZAB5E">
<img alt="Chat @ Discord" src="https://img.shields.io/badge/contact-me-blue?logo=discord&logoColor=white">
</a>
<a href="https://qmlsys.hanruiwang.me">
<img alt="Forum" src="https://img.shields.io/discourse/status?server=https%3A%2F%2Fqmlsys.hanruiwang.me%2F">
</a>
Expand Down
29 changes: 29 additions & 0 deletions docs/source/api_layers.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
torchquantum.layers
======================

.. currentmodule:: torchquantum.layer

Layers
---------
.. autosummary::
:toctree: generated
:template: classtemplate_controlflow.rst


QuantumModuleFromOps
TrainableOpAll
ClassicalInOpAll
FixedOpAll
TwoQAll
RandomLayer
RandomLayerAllTypes
Op1QAllLayer
RandomOp1All
Op2QAllLayer
Op2QButterflyLayer
Op2QDenseLayer
CXLayer
CXCXCXLayer
SWAPSWAPLayer
RXYZCXLayer0
QFTLayer
2 changes: 1 addition & 1 deletion docs/source/api_operators.rst
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
torchquantum.operators
======================

.. currentmodule:: torchquantum.operators
.. currentmodule:: torchquantum.operator

Classes
---------
Expand Down
1 change: 1 addition & 0 deletions docs/source/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
api_torchquantum
api_functional
api_operators
api_layers

.. toctree::
:maxdepth: 1
Expand Down
4 changes: 2 additions & 2 deletions examples/gradient_pruning/q_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ def shift_and_run(
node.shift_this_step[idx] = True
elif self.pruning_method == "perlayer_pruning":
node.shift_this_step[:] = False
idxs = torch.range(0, self.n_params - 1, dtype=int).view(
idxs = torch.arange(0, self.n_params, dtype=int).view(
self.n_qubits, self.n_layers
)
sampled_colums = self.colums
Expand All @@ -164,7 +164,7 @@ def shift_and_run(
self.colums %= self.n_layers
elif self.pruning_method == "perqubit_pruning":
node.shift_this_step[:] = False
idxs = torch.range(0, self.n_params - 1, dtype=int).view(
idxs = torch.arange(0, self.n_params, dtype=int).view(
self.n_qubits, self.n_layers
)
sampled_rows = self.rows
Expand Down
4 changes: 3 additions & 1 deletion examples/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,6 @@ TorchQuantum Examples
param_shift_onchip_training/param_shift_onchip_training.ipynb
quantum_kernel_method/quantum_kernel_method.ipynb
quanvolution/quanvolution.ipynb
superdense_coding/superdense_coding_torchquantum.ipynb
superdense_coding/superdense_coding_torchquantum.ipynb
qubit_rotation/TQ_Qubit_Rotation_Tutorial.ipynb

Original file line number Diff line number Diff line change
Expand Up @@ -502,7 +502,7 @@
"id": "nFC9-bqHbG2I"
},
"source": [
"# References:\n",
"## References:\n",
"\n",
"[1] Bennett, C.H., Brassard, G., Crépeau, C., Jozsa, R., Peres, A. and Wootters, W.K., 1993. Teleporting an unknown quantum state via dual classical and Einstein-Podolsky-Rosen channels. Physical review letters, 70(13), p.1895.\n",
"\n",
Expand Down
55 changes: 55 additions & 0 deletions test/layers/test_rotgate.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import torchquantum as tq
import qiskit
from qiskit import Aer, execute

from torchquantum.util import (
switch_little_big_endian_matrix,
find_global_phase,
)

from qiskit.circuit.library import GR, GRX, GRY, GRZ
import numpy as np

all_pairs = [
{"qiskit": GR, "tq": tq.layer.GlobalR, "params": 2},
{"qiskit": GRX, "tq": tq.layer.GlobalRX, "params": 1},
{"qiskit": GRY, "tq": tq.layer.GlobalRY, "params": 1},
{"qiskit": GRZ, "tq": tq.layer.GlobalRZ, "params": 1},
]

ITERATIONS = 10

# test each pair
for pair in all_pairs:
# test 2-5 wires
for num_wires in range(2, 5):
# try multiple random parameters
for _ in range(ITERATIONS):
# generate random parameters
params = [
np.random.uniform(-2 * np.pi, 2 * np.pi) for _ in range(pair["params"])
]

# create the qiskit circuit
qiskit_circuit = pair["qiskit"](num_wires, *params)

# get the unitary from qiskit
backend = Aer.get_backend("unitary_simulator")
result = execute(qiskit_circuit, backend).result()
unitary_qiskit = result.get_unitary(qiskit_circuit)

# create tq circuit
qdev = tq.QuantumDevice(num_wires)
tq_circuit = pair["tq"](num_wires, *params)
tq_circuit(qdev)

# get the unitary from tq
unitary_tq = tq_circuit.get_unitary(qdev)
unitary_tq = switch_little_big_endian_matrix(unitary_tq.data.numpy())

# phase?
phase = find_global_phase(unitary_tq, unitary_qiskit, 1e-4)

assert np.allclose(
unitary_tq * phase, unitary_qiskit, atol=1e-6
), f"{pair} not equal with {params=}!"
1 change: 1 addition & 0 deletions torchquantum/layer/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,4 @@

from .layers import *
from .nlocal import *
from .general import *
104 changes: 104 additions & 0 deletions torchquantum/layer/general.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
"""
MIT License
Copyright (c) 2020-present TorchQuantum Authors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""


import torch
import torchquantum as tq
from torchquantum.layer.layers import (
LayerTemplate0,
Op1QAllLayer,
Op2QAllLayer,
RandomOp1All,
)

__all__ = [
"GlobalR",
"GlobalRX",
"GlobalRY",
"GlobalRZ",
]


class GlobalR(tq.QuantumModule):
"""Layer Template for a Global R General Gate"""

def __init__(
self,
n_wires: int = 0,
theta: float = 0,
phi: float = 0,
):
"""Create the layer"""
super().__init__()
self.n_wires = n_wires
self.params = torch.tensor([[theta, phi]])

@tq.static_support
def forward(self, q_device, x=None):
for k in range(self.n_wires):
tq.R()(q_device, wires=k, params=self.params)


class GlobalRX(GlobalR):
"""Layer Template for a Global RX General Gate"""

def __init__(
self,
n_wires: int = 0,
theta: float = 0,
):
"""Create the layer"""
super().__init__(n_wires, theta, phi=0)


class GlobalRY(GlobalR):
"""Layer Template for a Global RY General Gate"""

def __init__(
self,
n_wires: int = 0,
theta: float = 0,
):
"""Create the layer"""
super().__init__(n_wires, theta, phi=torch.pi / 2)

class GlobalRZ(tq.QuantumModule):
"""Layer Template for a Global RZ General Gate"""

def __init__(
self,
n_wires: int = 0,
phi: float = 0,
):
"""Create the layer"""
super().__init__()
self.n_wires = n_wires
self.params = torch.tensor([[phi]])

@tq.static_support
def forward(self, q_device, x=None):
for k in range(self.n_wires):
tq.RZ()(q_device, wires=k, params=self.params)


Loading

0 comments on commit 53ed825

Please sign in to comment.