Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Docs Successfully Compiling #231

Closed
wants to merge 27 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
f538629
[Test]Single qubit density matrix test compared with qiskit.
Feb 3, 2024
4f90e92
[Test] Add two qubit gate tests for density matrix.
Feb 3, 2024
70e4224
[Test] Add three qubit gate tests for density matrix.
Feb 3, 2024
9b441c1
[Fix] Test code for density matrix operation on arbitrary num of qubits.
Feb 3, 2024
dfde51e
[Test] Add one,two,three qubit gate random layer tests.
Feb 3, 2024
0593e68
[Test] Mix random layer test for density matrix module.
Feb 3, 2024
d529c51
[Test] Add trace preserving test for density matrix.
Feb 3, 2024
c42dbb9
[Bug]Fix a small bug. The mat_dict reference in sx.py should be _sx_m…
Feb 3, 2024
3b38095
[Example] Add the minist example that run on noisedevice
Feb 3, 2024
135446b
[Bug] Fix a minor bug in batch multiplication of density matrix.
Feb 3, 2024
8f0bbd0
[minor] update OneQubitEulerDecomposer
01110011011101010110010001101111 Feb 4, 2024
02a81c3
[minor] adding yaml file for docs
01110011011101010110010001101111 Feb 10, 2024
efff2e4
[minor] fixing the version
01110011011101010110010001101111 Feb 10, 2024
9700cb9
[minor] rm furo import
01110011011101010110010001101111 Feb 10, 2024
830747f
[minor] add proper docs imports
01110011011101010110010001101111 Feb 10, 2024
36abad4
[minor
01110011011101010110010001101111 Feb 10, 2024
74d2702
[minor] reduced number of imports
01110011011101010110010001101111 Feb 10, 2024
f6f950b
[minor] add recommonmark
01110011011101010110010001101111 Feb 10, 2024
defac19
[minor] adding tq?
01110011011101010110010001101111 Feb 10, 2024
112c5e4
[minor] lowering the python version if that helps
01110011011101010110010001101111 Feb 10, 2024
a805b43
[minor] add opt_einsum
01110011011101010110010001101111 Feb 10, 2024
0b00979
[major] removed deprecated IBMQ dependency and restricted to qiskit<1…
01110011011101010110010001101111 Feb 21, 2024
b985192
[minor] added missing dependency
01110011011101010110010001101111 Feb 21, 2024
1f7bcf0
[minor] flipping order of imports
01110011011101010110010001101111 Feb 21, 2024
d6fffa1
[minor] updating the requirements
01110011011101010110010001101111 Feb 21, 2024
d344de8
Merge pull request #237 from mit-han-lab/tq_bugfix
01110011011101010110010001101111 Feb 21, 2024
511fbfa
[minor] moved density tests to not be included for now
01110011011101010110010001101111 Feb 21, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/functional_tests.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,8 @@ jobs:
- name: Install dependencies
run: |
python -m pip install --upgrade pip
python -m pip install flake8 pytest qiskit-aer qiskit-ibmq-provider
if [ -f requirements.txt ]; then pip install -r requirements.txt; fi
python -m pip install flake8 pytest qiskit-aer qiskit_ibm_runtime
- name: Lint with flake8
run: |
# stop the build if there are Python syntax errors or undefined names
Expand Down
6 changes: 6 additions & 0 deletions docs/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
furo @ git+https://github.com/frogcjn/torchquantum-doc-furo-theme.git
nbsphinx
recommonmark

torchquantum>=0.1
opt_einsum
3 changes: 1 addition & 2 deletions docs/source/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@
import sys
import os
sys.path.insert(0, os.path.abspath('../..'))
import furo

#import pathlib
#sys.path.insert(0, pathlib.Path(__file__).parents[2].resolve().as_posix())
Expand Down Expand Up @@ -160,4 +159,4 @@
display_gitlab = False
show_source = True
# -- Options for EPUB output
epub_show_urls = 'footnote'
epub_show_urls = 'footnote'
250 changes: 250 additions & 0 deletions examples/mnist/mnist_noise.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,250 @@
"""
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 torch.nn.functional as F
import torch.optim as optim
import argparse
import random
import numpy as np

import torchquantum as tq
from torchquantum.plugin import (
tq2qiskit_measurement,
qiskit_assemble_circs,
op_history2qiskit,
op_history2qiskit_expand_params,
)

from torchquantum.dataset import MNIST
from torch.optim.lr_scheduler import CosineAnnealingLR


class QFCModel(tq.QuantumModule):
class QLayer(tq.QuantumModule):
def __init__(self):
super().__init__()
self.n_wires = 4
self.random_layer = tq.RandomLayer(
n_ops=50, wires=list(range(self.n_wires))
)

# gates with trainable parameters
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, qdev: tq.NoiseDevice):
self.random_layer(qdev)

# some trainable gates (instantiated 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) # type: ignore
qdev.sx(wires=2) # type: ignore
qdev.cnot(wires=[3, 0]) # type: ignore
qdev.rx(
wires=1,
params=torch.tensor([0.1]),
static=self.static_mode,
parent_graph=self.graph,
) # type: ignore

def __init__(self):
super().__init__()
self.n_wires = 4
self.encoder = tq.GeneralEncoder(tq.encoder_op_list_name_dict["4x4_u3_h_rx"])

self.q_layer = self.QLayer()
self.measure = tq.MeasureAll(tq.PauliZ)

def forward(self, x, use_qiskit=False):
qdev = tq.NoiseDevice(
n_wires=self.n_wires, bsz=x.shape[0], device=x.device, record_op=True
)

bsz = x.shape[0]
x = F.avg_pool2d(x, 6).view(bsz, 16)
devi = x.device

if use_qiskit:
# use qiskit to process the circuit
# create the qiskit circuit for encoder
self.encoder(qdev, x)
op_history_parameterized = qdev.op_history
qdev.reset_op_history()
encoder_circs = op_history2qiskit_expand_params(self.n_wires, op_history_parameterized, bsz=bsz)

# create the qiskit circuit for trainable quantum layers
self.q_layer(qdev)
op_history_fixed = qdev.op_history
qdev.reset_op_history()
q_layer_circ = op_history2qiskit(self.n_wires, op_history_fixed)

# create the qiskit circuit for measurement
measurement_circ = tq2qiskit_measurement(qdev, self.measure)

# assemble the encoder, trainable quantum layers, and measurement circuits
assembled_circs = qiskit_assemble_circs(
encoder_circs, q_layer_circ, measurement_circ
)

# call the qiskit processor to process the circuit
x0 = self.qiskit_processor.process_ready_circs(qdev, assembled_circs).to( # type: ignore
devi
)
x = x0

else:
# use torchquantum to process the circuit
self.encoder(qdev, x)
qdev.reset_op_history()
self.q_layer(qdev)
x = self.measure(qdev)

x = x.reshape(bsz, 2, 2).sum(-1).squeeze()
x = F.log_softmax(x, dim=1)

return x


def train(dataflow, model, device, optimizer):
for feed_dict in dataflow["train"]:
inputs = feed_dict["image"].to(device)
targets = feed_dict["digit"].to(device)

outputs = model(inputs)
loss = F.nll_loss(outputs, targets)
optimizer.zero_grad()
loss.backward()
optimizer.step()
print(f"loss: {loss.item()}", end="\r")


def valid_test(dataflow, split, model, device, qiskit=False):
target_all = []
output_all = []
with torch.no_grad():
for feed_dict in dataflow[split]:
inputs = feed_dict["image"].to(device)
targets = feed_dict["digit"].to(device)

outputs = model(inputs, use_qiskit=qiskit)

target_all.append(targets)
output_all.append(outputs)
target_all = torch.cat(target_all, dim=0)
output_all = torch.cat(output_all, dim=0)

_, indices = output_all.topk(1, dim=1)
masks = indices.eq(target_all.view(-1, 1).expand_as(indices))
size = target_all.shape[0]
corrects = masks.sum().item()
accuracy = corrects / size
loss = F.nll_loss(output_all, target_all).item()

print(f"{split} set accuracy: {accuracy}")
print(f"{split} set loss: {loss}")


def main():
parser = argparse.ArgumentParser()
parser.add_argument(
"--static", action="store_true", help="compute with " "static mode"
)
parser.add_argument("--pdb", action="store_true", help="debug with pdb")
parser.add_argument(
"--wires-per-block", type=int, default=2, help="wires per block int static mode"
)
parser.add_argument(
"--epochs", type=int, default=2, help="number of training epochs"
)

args = parser.parse_args()

if args.pdb:
import pdb

pdb.set_trace()

seed = 0
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)

dataset = MNIST(
root="./mnist_data",
train_valid_split_ratio=[0.9, 0.1],
digits_of_interest=[3, 6],
n_test_samples=75,
)
dataflow = dict()

for split in dataset:
sampler = torch.utils.data.RandomSampler(dataset[split])
dataflow[split] = torch.utils.data.DataLoader(
dataset[split],
batch_size=256,
sampler=sampler,
num_workers=8,
pin_memory=True,
)

use_cuda = torch.cuda.is_available()
device = torch.device("cuda" if use_cuda else "cpu")

model = QFCModel().to(device)

n_epochs = args.epochs
optimizer = optim.Adam(model.parameters(), lr=5e-3, weight_decay=1e-4)
scheduler = CosineAnnealingLR(optimizer, T_max=n_epochs)

if args.static:
# optionally to switch to the static mode, which can bring speedup
# on training
model.q_layer.static_on(wires_per_block=args.wires_per_block)

for epoch in range(1, n_epochs + 1):
# train
print(f"Epoch {epoch}:")
train(dataflow, model, device, optimizer)
print(optimizer.param_groups[0]["lr"])

# valid
valid_test(dataflow, "valid", model, device)
scheduler.step()

# test
valid_test(dataflow, "test", model, device, qiskit=False)




if __name__ == "__main__":
main()
35 changes: 35 additions & 0 deletions readthedocs.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# Read the Docs configuration file for Sphinx projects
# See https://docs.readthedocs.io/en/stable/config-file/v2.html for details

# Required
version: 2

# Set the OS, Python version and other tools you might need
build:
os: ubuntu-22.04
tools:
python: "3.10"
# You can also specify other tool versions:
# nodejs: "20"
# rust: "1.70"
# golang: "1.20"

# Build documentation in the "docs/" directory with Sphinx
sphinx:
configuration: docs/source/conf.py
# You can configure Sphinx to use a different builder, for instance use the dirhtml builder for simpler URLs
# builder: "dirhtml"
# Fail on all warnings to avoid broken references
# fail_on_warning: true

# Optionally build your docs in additional formats such as PDF and ePub
# formats:
# - pdf
# - epub

# Optional but recommended, declare the Python requirements required
# to build your documentation
# See https://docs.readthedocs.io/en/stable/guides/reproducible-builds.html
python:
install:
- requirements: docs/requirements.txt
2 changes: 1 addition & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ opt_einsum
pathos>=0.2.7
pylatexenc>=2.10
pyscf>=2.0.1
qiskit>=0.39.0
qiskit>=0.39.0,<1.0.0
recommonmark

scipy>=1.5.2
Expand Down
24 changes: 24 additions & 0 deletions test/density/_test_density_measure.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import torchquantum as tq
import numpy as np

import qiskit.circuit.library.standard_gates as qiskit_gate
from qiskit.quantum_info import DensityMatrix as qiskitDensity

from unittest import TestCase



class density_measure_test(TestCase):
def test_single_qubit_random_layer(self):
return

def test_two_qubit_random_layer(self):
return


def test_three_qubit_random_layer(self):
return


def test_mixed_layer(self):
return
Loading
Loading