Are you sure you want to delete this task? Once this task is deleted, it cannot be recovered.
tyx_neu 5321d871ca | 1 year ago | |
---|---|---|
.github | 1 year ago | |
docs | 1 year ago | |
examples | 1 year ago | |
figs | 1 year ago | |
test | 1 year ago | |
torchquantum | 1 year ago | |
.flake8 | 1 year ago | |
.gitignore | 1 year ago | |
.gitmodules | 1 year ago | |
.pre-commit-config.yaml | 1 year ago | |
LICENSE | 1 year ago | |
README.md | 1 year ago | |
requirements.txt | 1 year ago | |
setup.py | 1 year ago | |
torchquantum_logo.jpg | 1 year ago |
A PyTorch Library for Quantum Simulation and Quantum Machine Learning
Faster, Scalable, Easy Debugging, Easy Deployment on Real Machine
Quantum simulation framework based on PyTorch. It supports statevector simulation and pulse simulation (coming soon) on GPUs. It can scale up to the simulation of 30+ qubits with multiple GPUs.
Researchers on quantum algorithm design, parameterized quantum circuit training, quantum optimal control, quantum machine learning, quantum neural networks.
Dynamic computation graph, automatic gradient computation, fast GPU support, batch model tersorized processing.
git clone https://github.com/mit-han-lab/torchquantum.git
cd torchquantum
pip install --editable .
import torchquantum as tq
import torchquantum.functional as tqf
qdev = tq.QuantumDevice(n_wires=2, bsz=5, device="cpu", record_op=True) # use device='cuda' for GPU
# use qdev.op
qdev.h(wires=0)
qdev.cnot(wires=[0, 1])
# use tqf
tqf.h(qdev, wires=1)
tqf.x(qdev, wires=1)
# use tq.Operator
op = tq.RX(has_params=True, trainable=True, init_params=0.5)
op(qdev, wires=0)
# print the current state (dynamic computation graph supported)
print(qdev)
# obtain the qasm string
from torchquantum.plugins import op_history2qasm
print(op_history2qasm(qdev.n_wires, qdev.op_history))
# measure the state on z basis
print(tq.measure(qdev, n_shots=1024))
# obtain the expval on a observable by stochastic sampling (doable on simulator and real quantum hardware)
from torchquantum.measurement import expval_joint_sampling
expval_sampling = expval_joint_sampling(qdev, 'ZX', n_shots=1024)
print(expval_sampling)
# obtain the expval on a observable by analytical computation (only doable on classical simulator)
from torchquantum.measurement import expval_joint_analytical
expval = expval_joint_analytical(qdev, 'ZX')
print(expval)
# obtain gradients of expval w.r.t. trainable parameters
expval[0].backward()
print(op.params.grad)
# Apply gates to qdev with tq.QuantumModule
ops = [
{'name': 'hadamard', 'wires': 0},
{'name': 'cnot', 'wires': [0, 1]},
{'name': 'rx', 'wires': 0, 'params': 0.5, 'trainable': True},
{'name': 'u3', 'wires': 0, 'params': [0.1, 0.2, 0.3], 'trainable': True},
{'name': 'h', 'wires': 1, 'inverse': True}
]
qmodule = tq.QuantumModule.from_op_history(ops)
qmodule(qdev)
We also prepare many example and tutorials using TorchQuantum.
For beginning level, you may check QNN for MNIST, Quantum Convolution (Quanvolution) and Quantum Kernel Method, and Quantum Regression.
For intermediate level, you may check Amplitude Encoding for MNIST, Clifford gate QNN, Save and Load QNN models, PauliSum Operation, How to convert tq to Qiskit.
For expert, you may check Parameter Shift on-chip Training, VQA Gradient Pruning, VQE, VQA for State Prepration, QAOA (Quantum Approximate Optimization Algorithm).
Construct parameterized quantum circuit models as simple as constructing a normal pytorch model.
import torch.nn as nn
import torch.nn.functional as F
import torchquantum as tq
import torchquantum.functional as tqf
class QFCModel(nn.Module):
def __init__(self):
super().__init__()
self.n_wires = 4
self.measure = tq.MeasureAll(tq.PauliZ)
self.encoder_gates = [tqf.rx] * 4 + [tqf.ry] * 4 + \
[tqf.rz] * 4 + [tqf.rx] * 4
self.rx0 = tq.RX(has_params=True, trainable=True)
self.ry0 = tq.RY(has_params=True, trainable=True)
self.rz0 = tq.RZ(has_params=True, trainable=True)
self.crx0 = tq.CRX(has_params=True, trainable=True)
def forward(self, x):
bsz = x.shape[0]
# down-sample the image
x = F.avg_pool2d(x, 6).view(bsz, 16)
# create a quantum device to run the gates
qdev = tq.QuantumDevice(n_wires=self.n_wires, bsz=bsz, device=x.device)
# encode the classical image to quantum domain
for k, gate in enumerate(self.encoder_gates):
gate(qdev, wires=k % self.n_wires, params=x[:, k])
# add some trainable gates (need to instantiate ahead of time)
self.rx0(qdev, wires=0)
self.ry0(qdev, wires=1)
self.rz0(qdev, wires=3)
self.crx0(qdev, wires=[0, 2])
# add some more non-parameterized gates (add on-the-fly)
qdev.h(wires=3)
qdev.sx(wires=2)
qdev.cnot(wires=[3, 0])
qdev.qubitunitary(wires=[1, 2], params=[[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 0, 1j],
[0, 0, -1j, 0]])
# perform measurement to get expectations (back to classical domain)
x = self.measure(qdev).reshape(bsz, 2, 2)
# classification
x = x.sum(-1).squeeze()
x = F.log_softmax(x, dim=1)
return x
Train a quantum circuit to perform VQE task.
Quito quantum computer as in simple_vqe.py
script:
cd examples/simple_vqe
python simple_vqe.py
Train a quantum circuit to perform MNIST classification task and deploy on the real IBM
Quito quantum computer as in mnist_example.py
script:
cd examples/simple_mnist
python mnist_example.py
File | Description |
---|---|
devices.py | QuantumDevice class which stores the statevector |
encoding.py | Encoding layers to encode classical values to quantum domain |
functional.py | Quantum gate functions |
operators.py | Quantum gate classes |
layers.py | Layer templates such as RandomLayer |
measure.py | Measurement of quantum states to get classical values |
graph.py | Quantum gate graph used in static mode |
super_layer.py | Layer templates for SuperCircuits |
plugins/qiskit* | Convertors and processors for easy deployment on IBMQ |
examples/ | More examples for training QML and VQE models |
torchquantum uses pre-commit hooks to ensure Python style consistency and prevent common mistakes in its codebase.
To enable it pre-commit hooks please reproduce:
pip install pre-commit
pre-commit install
concurrent
package issue for Qiskit)TorchQuantum Forum
Hanrui Wang hanrui@mit.edu
Jiannan Cao, Jessica Ding, Jiai Gu, Song Han, Zhirui Hu, Zirui Li, Zhiding Liang, Pengyu Liu, Yilian Liu, Mohammadreza Tavasoli, Hanrui Wang, Zhepeng Wang, Zhuoyang Ye
@inproceedings{hanruiwang2022quantumnas,
title = {Quantumnas: Noise-adaptive search for robust quantum circuits},
author = {Wang, Hanrui and Ding, Yongshan and Gu, Jiaqi and Li, Zirui and Lin, Yujun and Pan, David Z and Chong, Frederic T and Han, Song},
booktitle = {The 28th IEEE International Symposium on High-Performance Computer Architecture (HPCA-28)},
year = {2022}
}
Dear OpenI User
Thank you for your continuous support to the Openl Qizhi Community AI Collaboration Platform. In order to protect your usage rights and ensure network security, we updated the Openl Qizhi Community AI Collaboration Platform Usage Agreement in January 2024. The updated agreement specifies that users are prohibited from using intranet penetration tools. After you click "Agree and continue", you can continue to use our services. Thank you for your cooperation and understanding.
For more agreement content, please refer to the《Openl Qizhi Community AI Collaboration Platform Usage Agreement》