Quantum Computing in PyTorch — community fork of torchquantum with Python 3.12+ support.
Project description
Quantum Computing in PyTorch
Faster, Scalable, Easy Debugging, Easy Deployment on Real Machine
Community fork notice
This repository is a community-maintained fork of
mit-han-lab/torchquantum, kept alive while the upstream is on pause. The PyPI distribution name istorchquantum-ng, but the Python import name is unchanged — code that already usesimport torchquantumkeeps working.# Recommended: remove the upstream first so the two don't overlay each # other in site-packages (they install into the same `torchquantum/` dir). pip uninstall -y torchquantum pip install torchquantum-ngimport torchquantum as tq # unchangedCompared to upstream
torchquantum==0.1.8this fork additionally:
- tests on Python 3.8 – 3.13 (and an experimental 3.14-dev job);
- drops the unused
dillpin and movestensorflow/pyscfto optional extras (pip install 'torchquantum-ng[quantumnas]',pip install 'torchquantum-ng[chem]') so plain installs work on new Python releases without dragging in heavy native wheels.
👋 Welcome
What it is doing
Simulate quantum computations on classical hardware using PyTorch. It supports statevector simulation and pulse simulation on GPUs. It can scale up to the simulation of 30+ qubits with multiple GPUs.
Who will benefit
Researchers on quantum algorithm design, parameterized quantum circuit training, quantum optimal control, quantum machine learning, quantum neural networks.
Differences from Qiskit/Pennylane
Dynamic computation graph, automatic gradient computation, fast GPU support, batch model tersorized processing.
News
- Torchquantum is used in the winning team for ACM Quantum Computing for Drug Discovery Challenge.
- Torchquantum is highlighted in unitaryHACK.
- TorchQuantum received a Unitary Foundation microgrant.
- TorchQuantum is integrated to IBM Qiskit Ecosystem.
- TorchQuantum is integrated to PyTorch Ecosystem.
- v0.1.8 Available!
- Check the dev branch for new latest features on quantum layers and quantum algorithms.
- Join our Slack for real time support!
- Welcome to contribute! Please contact us or post in the Github Issues if you want to have new examples implemented by TorchQuantum or any other questions.
- Qmlsys website goes online: qmlsys.mit.edu and torchquantum.org
Features
- Easy construction and simulation of quantum circuits in PyTorch
- Dynamic computation graph for easy debugging
- Gradient support via autograd
- Batch mode inference and training on CPU/GPU
- Easy deployment on real quantum devices such as IBMQ
- Easy hybrid classical-quantum model construction
- (coming soon) pulse-level simulation
Installation
git clone https://github.com/mit-han-lab/torchquantum.git
cd torchquantum
pip install --editable .
Basic Usage
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.plugin 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)
Guide to the examples
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).
Usage
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
VQE Example
Train a quantum circuit to perform VQE task. Quito quantum computer as in simple_vqe.py script:
cd examples/vqe
python vqe.py
MNIST Example
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/mnist
python mnist.py
Files
| 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 |
Coding Style
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
Papers using TorchQuantum
- [HPCA'22] Wang et al., "QuantumNAS: Noise-Adaptive Search for Robust Quantum Circuits"
- [DAC'22] Wang et al., "QuantumNAT: Quantum Noise-Aware Training with Noise Injection, Quantization and Normalization"
- [DAC'22] Wang et al., "QOC: Quantum On-Chip Training with Parameter Shift and Gradient Pruning"
- [QCE'22] Liang et al., "Variational Quantum Pulse Learning"
- [ICCAD'22] Hu et al., "Quantum Neural Network Compression"
- [ICCAD'22] Wang et al., "QuEst: Graph Transformer for Quantum Circuit Reliability Estimation"
- [ICML Workshop] Yun et al., "Slimmable Quantum Federated Learning"
- [IEEE ICDCS] Yun et al., "Quantum Multi-Agent Reinforcement Learning via Variational Quantum Circuit Design"
- [QCE'23] Zhan et al., "Quantum Sensor Network Algorithms for Transmitter Localization"
Manuscripts
Manuscripts
- Yun et al., "Projection Valued Measure-based Quantum Machine Learning for Multi-Class Classification"
- Baek et al., "3D Scalable Quantum Convolutional Neural Networks for Point Cloud Data Processing in Classification Applications"
- Baek et al., "Scalable Quantum Convolutional Neural Networks"
- Yun et al., "Quantum Multi-Agent Meta Reinforcement Learning"
Dependencies
- 3.9 >= Python >= 3.7 (Python 3.10 may have the
concurrentpackage issue for Qiskit) - PyTorch >= 1.8.0
- configargparse >= 0.14
- GPU model training requires NVIDIA GPUs
Contact
TorchQuantum Forum
Hanrui Wang hanrui@mit.edu
Contributors
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
Citation
@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}
}
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file torchquantum_ng-0.2.0.tar.gz.
File metadata
- Download URL: torchquantum_ng-0.2.0.tar.gz
- Upload date:
- Size: 437.8 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
b455b4e6071300aa0ab3a165d83b40ffe35944f6d5d6fbba9c50477e3c9d444e
|
|
| MD5 |
86671c34da622c8abbe89d72f758d396
|
|
| BLAKE2b-256 |
5bbd974bd1d1469cfcdf9be13432650dd131f924c3c24b4bf314596d63b132c6
|
Provenance
The following attestation bundles were made for torchquantum_ng-0.2.0.tar.gz:
Publisher:
publish-pypi.yaml on Agony5757/torchquantum
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
torchquantum_ng-0.2.0.tar.gz -
Subject digest:
b455b4e6071300aa0ab3a165d83b40ffe35944f6d5d6fbba9c50477e3c9d444e - Sigstore transparency entry: 1734514266
- Sigstore integration time:
-
Permalink:
Agony5757/torchquantum@487b73e61130a26af52640db3f8f5139acd5b8ba -
Branch / Tag:
refs/tags/v0.2.0 - Owner: https://github.com/Agony5757
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish-pypi.yaml@487b73e61130a26af52640db3f8f5139acd5b8ba -
Trigger Event:
push
-
Statement type:
File details
Details for the file torchquantum_ng-0.2.0-py3-none-any.whl.
File metadata
- Download URL: torchquantum_ng-0.2.0-py3-none-any.whl
- Upload date:
- Size: 242.2 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
34b96eefdad55067a7d47ae32aa145a317dacafa1f216409a9aa4951e579d04c
|
|
| MD5 |
8a4a2753438f8de01b571e140978b525
|
|
| BLAKE2b-256 |
43d34c846e1b30d7b0a71328bc4053e84c727de24cba0d41ffb89573ccc7589f
|
Provenance
The following attestation bundles were made for torchquantum_ng-0.2.0-py3-none-any.whl:
Publisher:
publish-pypi.yaml on Agony5757/torchquantum
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
torchquantum_ng-0.2.0-py3-none-any.whl -
Subject digest:
34b96eefdad55067a7d47ae32aa145a317dacafa1f216409a9aa4951e579d04c - Sigstore transparency entry: 1734514403
- Sigstore integration time:
-
Permalink:
Agony5757/torchquantum@487b73e61130a26af52640db3f8f5139acd5b8ba -
Branch / Tag:
refs/tags/v0.2.0 - Owner: https://github.com/Agony5757
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish-pypi.yaml@487b73e61130a26af52640db3f8f5139acd5b8ba -
Trigger Event:
push
-
Statement type: