Skip to content

Commit 8946f82

Browse files
committed
typo
1 parent dcc0817 commit 8946f82

File tree

12 files changed

+442
-235
lines changed

12 files changed

+442
-235
lines changed
7.48 MB
Binary file not shown.
1.57 MB
Binary file not shown.
9.77 KB
Binary file not shown.
4.44 KB
Binary file not shown.
44.9 MB
Binary file not shown.
9.45 MB
Binary file not shown.
58.6 KB
Binary file not shown.
28.2 KB
Binary file not shown.
Lines changed: 213 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,213 @@
1+
"""
2+
MIT License
3+
4+
Copyright (c) 2020-present TorchQuantum Authors
5+
6+
Permission is hereby granted, free of charge, to any person obtaining a copy
7+
of this software and associated documentation files (the "Software"), to deal
8+
in the Software without restriction, including without limitation the rights
9+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10+
copies of the Software, and to permit persons to whom the Software is
11+
furnished to do so, subject to the following conditions:
12+
13+
The above copyright notice and this permission notice shall be included in all
14+
copies or substantial portions of the Software.
15+
16+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22+
SOFTWARE.
23+
"""
24+
25+
"""
26+
use 2 qubit to perform 4 class classification,
27+
We can choose four different observables to measure the qubit state:
28+
1. XX
29+
2. YY
30+
3. ZZ
31+
4. XY
32+
"""
33+
34+
import torch
35+
import torch.nn.functional as F
36+
import torch.optim as optim
37+
import argparse
38+
39+
import torchquantum as tq
40+
import torchquantum.functional as tqf
41+
42+
from torchquantum.measurement import expval_joint_analytical
43+
44+
from torchquantum.dataset import MNIST
45+
from torch.optim.lr_scheduler import CosineAnnealingLR
46+
47+
import random
48+
import numpy as np
49+
50+
51+
class QFCModel(tq.QuantumModule):
52+
class QLayer(tq.QuantumModule):
53+
def __init__(self):
54+
super().__init__()
55+
self.n_wires = 2
56+
self.random_layer = tq.RandomLayer(
57+
n_ops=50, wires=list(range(self.n_wires))
58+
)
59+
60+
# gates with trainable parameters
61+
self.rx0 = tq.RX(has_params=True, trainable=True)
62+
self.ry0 = tq.RY(has_params=True, trainable=True)
63+
self.rz0 = tq.RZ(has_params=True, trainable=True)
64+
self.crx0 = tq.CRX(has_params=True, trainable=True)
65+
66+
def forward(self, qdev: tq.QuantumDevice):
67+
self.random_layer(qdev)
68+
69+
# some trainable gates (instantiated ahead of time)
70+
self.rx0(qdev, wires=0)
71+
self.ry0(qdev, wires=1)
72+
self.rz0(qdev, wires=0)
73+
self.crx0(qdev, wires=[0, 1])
74+
75+
def __init__(self):
76+
super().__init__()
77+
self.n_wires = 2
78+
# the encoder here is just for illustration purpose, may not be the best choice
79+
self.encoder = tq.GeneralEncoder(
80+
tq.encoder_op_list_name_dict["2x8_rxryrzrxryrzrxry"]
81+
)
82+
83+
self.q_layer = self.QLayer()
84+
85+
def forward(self, x, use_qiskit=False):
86+
qdev = tq.QuantumDevice(
87+
n_wires=self.n_wires, bsz=x.shape[0], device=x.device, record_op=True
88+
)
89+
90+
bsz = x.shape[0]
91+
x = F.avg_pool2d(x, 6).view(bsz, 16)
92+
93+
self.encoder(qdev, x)
94+
self.q_layer(qdev)
95+
obs_xx = expval_joint_analytical(qdev, "XX")
96+
obs_yy = expval_joint_analytical(qdev, "YY")
97+
obs_zz = expval_joint_analytical(qdev, "ZZ")
98+
obs_xy = expval_joint_analytical(qdev, "XY")
99+
100+
x = torch.stack([obs_xx, obs_yy, obs_zz, obs_xy], dim=1)
101+
x = F.log_softmax(x, dim=1)
102+
103+
return x
104+
105+
106+
def train(dataflow, model, device, optimizer):
107+
for feed_dict in dataflow["train"]:
108+
inputs = feed_dict["image"].to(device)
109+
targets = feed_dict["digit"].to(device)
110+
111+
outputs = model(inputs)
112+
loss = F.nll_loss(outputs, targets)
113+
optimizer.zero_grad()
114+
loss.backward()
115+
optimizer.step()
116+
print(f"loss: {loss.item()}", end="\r")
117+
118+
119+
def valid_test(dataflow, split, model, device, qiskit=False):
120+
target_all = []
121+
output_all = []
122+
with torch.no_grad():
123+
for feed_dict in dataflow[split]:
124+
inputs = feed_dict["image"].to(device)
125+
targets = feed_dict["digit"].to(device)
126+
127+
outputs = model(inputs, use_qiskit=qiskit)
128+
129+
target_all.append(targets)
130+
output_all.append(outputs)
131+
target_all = torch.cat(target_all, dim=0)
132+
output_all = torch.cat(output_all, dim=0)
133+
134+
_, indices = output_all.topk(1, dim=1)
135+
masks = indices.eq(target_all.view(-1, 1).expand_as(indices))
136+
size = target_all.shape[0]
137+
corrects = masks.sum().item()
138+
accuracy = corrects / size
139+
loss = F.nll_loss(output_all, target_all).item()
140+
141+
print(f"{split} set accuracy: {accuracy}")
142+
print(f"{split} set loss: {loss}")
143+
144+
145+
def main():
146+
parser = argparse.ArgumentParser()
147+
parser.add_argument(
148+
"--static", action="store_true", help="compute with " "static mode"
149+
)
150+
parser.add_argument("--pdb", action="store_true", help="debug with pdb")
151+
parser.add_argument(
152+
"--wires-per-block", type=int, default=2, help="wires per block int static mode"
153+
)
154+
parser.add_argument(
155+
"--epochs", type=int, default=5, help="number of training epochs"
156+
)
157+
158+
args = parser.parse_args()
159+
160+
if args.pdb:
161+
import pdb
162+
163+
pdb.set_trace()
164+
165+
seed = 0
166+
random.seed(seed)
167+
np.random.seed(seed)
168+
torch.manual_seed(seed)
169+
170+
dataset = MNIST(
171+
root="./mnist_data",
172+
train_valid_split_ratio=[0.9, 0.1],
173+
digits_of_interest=[0, 1, 2, 3],
174+
n_test_samples=100,
175+
)
176+
177+
dataflow = dict()
178+
179+
for split in dataset:
180+
sampler = torch.utils.data.RandomSampler(dataset[split])
181+
dataflow[split] = torch.utils.data.DataLoader(
182+
dataset[split],
183+
batch_size=256,
184+
sampler=sampler,
185+
num_workers=8,
186+
pin_memory=True,
187+
)
188+
189+
use_cuda = torch.cuda.is_available()
190+
device = torch.device("cuda" if use_cuda else "cpu")
191+
192+
model = QFCModel().to(device)
193+
194+
n_epochs = args.epochs
195+
optimizer = optim.Adam(model.parameters(), lr=5e-3, weight_decay=1e-4)
196+
scheduler = CosineAnnealingLR(optimizer, T_max=n_epochs)
197+
198+
for epoch in range(1, n_epochs + 1):
199+
# train
200+
print(f"Epoch {epoch}:")
201+
train(dataflow, model, device, optimizer)
202+
print(optimizer.param_groups[0]["lr"])
203+
204+
# valid
205+
valid_test(dataflow, "valid", model, device)
206+
scheduler.step()
207+
208+
# test
209+
valid_test(dataflow, "test", model, device, qiskit=False)
210+
211+
212+
if __name__ == "__main__":
213+
main()

doc/Programs/QuantumML/qml.py

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
import torch
2+
import torchvision.transforms as transforms
3+
from torchvision import datasets
4+
from torch.utils.data import DataLoader
5+
import pennylane as qml
6+
7+
# Load MNIST Dataset
8+
transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5,), (0.5,))])
9+
train_dataset = datasets.MNIST(root='./data', train=True, download=True, transform=transform)
10+
train_loader = DataLoader(dataset=train_dataset, batch_size=64, shuffle=True)
11+
12+
# Define Quantum Device
13+
dev = qml.device('default.qubit', wires=4)
14+
15+
@qml.qnode(dev)
16+
def circuit(inputs):
17+
# Encode classical data into quantum states
18+
for i in range(len(inputs)):
19+
qml.RY(inputs[i], wires=i)
20+
21+
# Example: Apply some gates (you can modify this part)
22+
qml.CNOT(wires=[0, 1])
23+
qml.CNOT(wires=[2, 3])
24+
25+
return [qml.expval(qml.PauliZ(i)) for i in range(4)]
26+
27+
class QuantumMLP(torch.nn.Module):
28+
def __init__(self):
29+
super(QuantumMLP, self).__init__()
30+
self.fc1 = torch.nn.Linear(28 * 28, 128) # Input layer to hidden layer
31+
32+
def forward(self, x):
33+
x = x.view(-1, 28 * 28) # Flatten the input image
34+
x = torch.relu(self.fc1(x))
35+
36+
# Pass through the quantum circuit - adjust inputs accordingly.
37+
outputs = []
38+
for i in range(len(x)):
39+
output = circuit(x[i].detach().numpy())
40+
outputs.append(output)
41+
42+
return torch.tensor(outputs)
43+
44+
# Initialize Model and Optimizer
45+
model = QuantumMLP()
46+
optimizer = torch.optim.Adam(model.parameters(), lr=0.001)
47+
criterion = torch.nn.CrossEntropyLoss()
48+
49+
# Training Loop
50+
for epoch in range(5): # Number of epochs
51+
for images, labels in train_loader:
52+
optimizer.zero_grad()
53+
54+
outputs = model(images.float())
55+
56+
loss = criterion(outputs.view(-1), labels)
57+
loss.backward()
58+
59+
optimizer.step()
60+
61+
print(f'Epoch [{epoch+1}/5], Loss: {loss.item():.4f}')
62+
63+
print("Training Complete")

0 commit comments

Comments
 (0)