
Pytorch의 양자 컴퓨팅
더 빠르고 확장 가능하며 쉬운 디버깅, 실제 기계에서 쉽게 배포 할 수 있습니다
Pytorch를 사용하여 클래식 하드웨어에서 양자 계산을 시뮬레이션하십시오. GPU의 StateVector 시뮬레이션 및 펄스 시뮬레이션을 지원합니다. 다수의 GPU로 30 개 이상의 큐 비트 시뮬레이션으로 확장 할 수 있습니다.
양자 알고리즘 설계, 매개 변수화 된 양자 회로 훈련, 양자 최적 제어, 양자 기계 학습, 양자 신경망.
동적 계산 그래프, 자동 그라디언트 계산, 빠른 GPU 지원, 배치 모델 지식 처리.
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 . 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 )또한 Torchquantum을 사용하여 많은 예제 및 튜토리얼을 준비합니다.
시작 레벨 의 경우 QNN에서 MNIST, Quantum Convolution (Quanvolution) 및 양자 커널 방법 및 양자 회귀를 확인할 수 있습니다.
중간 레벨 의 경우 MNIST, Clifford Gate QNN의 진폭 인코딩, QNN 모델 저장 및로드, Paulisum 작동, TQ를 Qiskit로 변환하는 방법을 확인할 수 있습니다.
전문가 의 경우 매개 변수 시프트 온 칩 트레이닝, VQA 그라디언트 가지 치기, VQE, State Prepration 용 VQA, QAOA (Quantum 대략 최적화 알고리즘)를 확인할 수 있습니다.
정상적인 Pytorch 모델을 구성하는 것처럼 매개 변수화 된 양자 회로 모델을 단순하게 구성하십시오.
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 작업을 수행하기 위해 양자 회로를 훈련시킵니다. simple_vqe.py 스크립트에서와 같이 quito Quantum 컴퓨터 :
cd examples / vqe
python vqe . py MNIST 분류 작업을 수행하고 MNIST_Example.py 스크립트에서와 같이 실제 IBM Quito Quantum 컴퓨터에 배치하기 위해 양자 회로를 훈련시킵니다.
cd examples / mnist
python mnist . py | 파일 | 설명 |
|---|---|
| devices.py | StateVector를 저장하는 QuantumDevice 클래스 |
| 인코딩 .py | 층을 인코딩하여 고전적인 값을 양자 도메인에 인코딩합니다 |
| functional.py | 양자 게이트 기능 |
| 연산자 .py | 양자 게이트 클래스 |
| Layers.py | Randomlayer와 같은 레이어 템플릿 |
| 측정 .py | 고전적인 가치를 얻기 위해 양자 상태의 측정 |
| 그래프 .py | 정적 모드에서 사용되는 양자 게이트 그래프 |
| super_layer.py | 과잉 회로를위한 레이어 템플릿 |
| 플러그인/Qiskit* | IBMQ에서 쉽게 배포 할 수있는 컨버터 및 프로세서 |
| 예/ | QML 및 VQE 모델을 훈련하기위한 더 많은 예 |
Torchquantum은 사전 커밋 후크를 사용하여 파이썬 스타일의 일관성을 보장하고 코드베이스의 일반적인 실수를 방지합니다.
사전 커밋 후크를 활성화하려면 다음을 재현하십시오.
pip install pre-commit
pre-commit installconcurrent 패키지 문제가있을 수 있습니다)Torchquantum 포럼
Hanrui Wang [email protected]
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}
}