### Verify VQNet Installation Source: https://github.com/originq/vqnet2.0-tutorial/blob/main/source/rst/install.md This Python snippet imports VQNet and its tensor module to create and print a sample tensor, confirming a successful installation. ```default import pyvqnet from pyvqnet.tensor import * a = arange(1,25).reshape([2, 3, 4]) print(a) ``` -------------------------------- ### Install quantum-llm Dependencies Source: https://github.com/originq/vqnet2.0-tutorial/blob/main/source/rst/llm.md Install the required dependencies for the quantum-llm library using pip and the provided requirements file. This includes installing the peft_vqc module. ```bash # 下载其他依赖库 pip install -r requirements.txt # 安装peft_vqc cd peft_vqc && pip install -e . ``` -------------------------------- ### RXX Gate Example with PyTorch Source: https://github.com/originq/vqnet2.0-tutorial/blob/main/source/rst/torch_api.md Shows how to use the RXX gate, which can have trainable parameters, within the PyTorch framework. The example initializes a QMachine and applies the RXX layer. ```default from pyvqnet.qnn.vqc.torch import RXX,QMachine import pyvqnet pyvqnet.backends.set_backend("torch") device = QMachine(4) layer = RXX(has_params= True, trainable= True, wires=[0,2]) batchsize = 2 device.reset_states(batchsize) layer(q_machine = device) print(device.states) ``` -------------------------------- ### Install Triton Source: https://github.com/originq/vqnet2.0-tutorial/blob/main/source/rst/nn.md Install the Triton library using pip. This is a prerequisite for using Triton-compatible code. ```bash pip install triton ``` -------------------------------- ### SGD Optimizer Example Source: https://github.com/originq/vqnet2.0-tutorial/blob/main/source/rst/nn.md Shows a basic example of using the Stochastic Gradient Descent (SGD) optimizer. This requires the Pyvqnet tensor and optimizer libraries. ```default import numpy as np from pyvqnet.optim import sgd from pyvqnet.tensor import QTensor w = np.arange(24).reshape(1,2,3,4).astype(np.float64) param = QTensor(w) param.grad = QTensor(np.arange(24).reshape(1,2,3,4).astype(np.float64)) params = [param] opti = sgd.SGD(params) for i in range(1,3): opti._step() print(param) ``` -------------------------------- ### Install pyvqnet Source: https://github.com/originq/vqnet2.0-tutorial/blob/main/source/rst/llm.md Install the pyvqnet package, ensuring it meets the version requirement of 2.15.0 or higher for quantum large model fine-tuning. ```bash # 安装VQNet pip install pyvqnet # pyvqnet>=2.15.0 ``` -------------------------------- ### Install VQNet Python Package Source: https://github.com/originq/vqnet2.0-tutorial/blob/main/source/rst/install.md Use this command to install the VQNet Python package. It is recommended to upgrade to the latest version. ```default pip install pyvqnet --upgrade ``` -------------------------------- ### Initialize and Inspect QMachine States with PyTorch Backend Source: https://github.com/originq/vqnet2.0-tutorial/blob/main/source/rst/torch_api.md This example shows how to initialize a QMachine simulator using the PyTorch backend and inspect its initial states. Ensure the PyTorch backend is set before creating the QMachine. ```default from pyvqnet.qnn.vqc.torch import QMachine import pyvqnet pyvqnet.backends.set_backend("torch") qm = QMachine(4) print(qm.states) ``` -------------------------------- ### QNSPSAOptimizer Usage Example Source: https://github.com/originq/vqnet2.0-tutorial/blob/main/source/rst/vqc.md Demonstrates how to use the QNSPSAOptimizer to train a quantum circuit defined by a QModule. Ensure necessary imports and initialize parameters and the optimizer. ```Python from pyvqnet.tensor import QTensor,ones,randu from pyvqnet.qnn.vqc import rx,cry,QMachine,MeasureAll,QModule num_qubits = 2 class QModuleDemo(QModule): def __init__(self, name=""): super().__init__(name) self.qm = QMachine(num_qubits) self.ma = MeasureAll({"Z1 Z0":1}) def forward(self,params): qm = self.qm qm.reset_states(1) rx(qm, 0, params[0]) cry(qm, [0, 1], params[1]) return self.ma(qm) qmd = QModuleDemo() from pyvqnet.qnn.vqc.qnspsa import QNSPSAOptimizer params = QTensor([0.37454012, 0.95071431]) params.requires_grad = True opt = QNSPSAOptimizer(stepsize=5e-2,seed=1) for i in range(51): params = opt.step(qmd, params) loss =qmd(params) if i % 10 == 0: print(f"Step {i}: cost = {loss}") ``` -------------------------------- ### RZZ Gate Example with PyTorch Source: https://github.com/originq/vqnet2.0-tutorial/blob/main/source/rst/torch_api.md Provides an example of using the RZZ gate within a PyTorch model. The code shows how to set up the RZZ gate with trainable parameters and apply it to a quantum machine. ```default from pyvqnet.qnn.vqc.torch import RZZ,QMachine import pyvqnet pyvqnet.backends.set_backend("torch") device = QMachine(4) layer = RZZ(has_params= True, trainable= True, wires=[0,2]) batchsize = 2 device.reset_states(batchsize) layer(q_machine = device) print(device.states) ``` -------------------------------- ### Initializing QMachine Simulator States Source: https://github.com/originq/vqnet2.0-tutorial/blob/main/source/rst/vqc.md This example demonstrates how to initialize the quantum state vectors within the QMachine simulator. It's crucial to call `reset_states(batchsize)` before each forward pass to ensure the quantum states are reset to their initial configuration, adapted for batch processing. ```Python from pyvqnet.qnn.vqc import QMachine vim = QMachine(4) print(vim.states) ``` -------------------------------- ### RYY Gate Example with PyTorch Source: https://github.com/originq/vqnet2.0-tutorial/blob/main/source/rst/torch_api.md Illustrates the usage of the RYY gate in PyTorch. This example demonstrates initializing the RYY gate with trainable parameters and applying it to a QMachine. ```default from pyvqnet.qnn.vqc.torch import RYY,QMachine import pyvqnet pyvqnet.backends.set_backend("torch") device = QMachine(4) layer = RYY(has_params= True, trainable= True, wires=[0,2]) batchsize = 2 device.reset_states(batchsize) layer(q_machine = device) print(device.states) ``` -------------------------------- ### CSWAP Gate Example with PyTorch Source: https://github.com/originq/vqnet2.0-tutorial/blob/main/source/rst/torch_api.md Demonstrates how to instantiate and use the CSWAP gate from pyvqnet.qnn.vqc.torch within a PyTorch environment. Ensure the backend is set to 'torch' and a QMachine is initialized. ```default from pyvqnet.qnn.vqc.torch import CSWAP,QMachine import pyvqnet pyvqnet.backends.set_backend("torch") device = QMachine(4) layer = CSWAP(wires=[0,1,2]) batchsize = 2 device.reset_states(batchsize) layer(q_machine = device) print(device.states) ``` -------------------------------- ### MNIST Dataset Download and Setup Source: https://github.com/originq/vqnet2.0-tutorial/blob/main/source/rst/vqc_demo.md Provides functions to download the MNIST dataset and set up global variables for the training process. It includes a download helper and the main download function for the dataset files. ```Python url_base = 'https://ossci-datasets.s3.amazonaws.com/mnist/' key_file = { "train_img": "train-images-idx3-ubyte.gz", "train_label": "train-labels-idx1-ubyte.gz", "test_img": "t10k-images-idx3-ubyte.gz", "test_label": "t10k-labels-idx1-ubyte.gz" } #GLOBAL VAR n = 10 n_qsc = 2 depth = 1 def _download(dataset_dir, file_name): """ Download function for mnist dataset file """ file_path = dataset_dir + "/" + file_name if os.path.exists(file_path): with gzip.GzipFile(file_path) as file: file_path_ungz = file_path[:-3].replace("\", "/") if not os.path.exists(file_path_ungz): open(file_path_ungz, "wb").write(file.read()) return print("Downloading " + file_name + " ... ") urllib.request.urlretrieve(url_base + file_name, file_path) if os.path.exists(file_path): with gzip.GzipFile(file_path) as file: file_path_ungz = file_path[:-3].replace("\", "/") file_path_ungz = file_path_ungz.replace("-idx", ".idx") if not os.path.exists(file_path_ungz): open(file_path_ungz, "wb").write(file.read()) print("Done") def download_mnist(dataset_dir): for v in key_file.values(): _download(dataset_dir, v) if not os.path.exists("./result"): os.makedirs("./result") else: pass def load_mnist(dataset="training_data", digits=np.arange(2), path="examples"): """ load mnist data """ from array import array as pyarray download_mnist(path) if dataset == "training_data": fname_image = os.path.join(path, "train-images.idx3-ubyte").replace( "\", "/") fname_label = os.path.join(path, "train-labels.idx1-ubyte").replace( "\", "/") elif dataset == "testing_data": ``` -------------------------------- ### Quantum LLM Fine-tuning Training Script (tq) Source: https://github.com/originq/vqnet2.0-tutorial/blob/main/source/rst/llm.md Example training script for fine-tuning a large language model using the tq module (based on torch quantum). Change the finetuning_type parameter to 'tq' to use this module. ```bash #!/bin/bash CUDA_VISIBLE_DEVICES=1 python ../../src/train_bash.py \ --stage sft \ --model_name_or_path /下载路径/Qwen2.5-0.5B/ \ --dataset alpaca_gpt4_en \ --tokenized_path ../../data/tokenized/alpaca_gpt4_en/ \ --dataset_dir ../../data \ --template qwen \ --finetuning_type tq \ --lora_target q_proj,v_proj \ --output_dir ../../saves/Qwen2.5-0.5B/tq/alpaca_gpt4_en \ --overwrite_cache \ --overwrite_output_dir \ --cutoff_len 1024 \ --preprocessing_num_workers 16 \ --per_device_train_batch_size 1 \ --per_device_eval_batch_size 1 \ --gradient_accumulation_steps 8 \ --lr_scheduler_type cosine \ --logging_steps 10 \ --warmup_steps 20 \ --save_steps 100 \ --eval_steps 100 \ --evaluation_strategy steps \ --load_best_model_at_end \ --learning_rate 5e-5 \ --num_train_epochs 3.0 \ --max_samples 1000 \ --val_size 0.1 \ --plot_loss \ --fp16 \ --do-train \ # 在命令行执行 sh train.sh ``` -------------------------------- ### Quantum LLM Fine-tuning Training Script (quanTA) Source: https://github.com/originq/vqnet2.0-tutorial/blob/main/source/rst/llm.md Example training script for fine-tuning a large language model using the quanTA module. Change the finetuning_type parameter to 'quanTA' to use this module. ```bash #!/bin/bash CUDA_VISIBLE_DEVICES=1 python ../../src/train_bash.py \ --stage sft \ --model_name_or_path /下载路径/Qwen2.5-0.5B/ \ --dataset alpaca_gpt4_en \ --tokenized_path ../../data/tokenized/alpaca_gpt4_en/ \ --dataset_dir ../../data \ --template qwen \ --finetuning_type quanTA \ --lora_target q_proj,v_proj \ --output_dir ../../saves/Qwen2.5-0.5B/quanTA/alpaca_gpt4_en \ --overwrite_cache \ --overwrite_output_dir \ --cutoff_len 1024 \ --preprocessing_num_workers 16 \ --per_device_train_batch_size 1 \ --per_device_eval_batch_size 1 \ --gradient_accumulation_steps 8 \ --lr_scheduler_type cosine \ --logging_steps 10 \ --warmup_steps 20 \ --save_steps 100 \ --eval_steps 100 \ --evaluation_strategy steps \ --load_best_model_at_end \ --learning_rate 5e-5 \ --num_train_epochs 3.0 \ --max_samples 1000 \ --val_size 0.1 \ --plot_loss \ --fp16 \ --do-train \ # 在命令行执行 sh train.sh ``` -------------------------------- ### Define and Use a PyTorch-based Quantum Circuit Layer Source: https://github.com/originq/vqnet2.0-tutorial/blob/main/source/rst/torch_api.md This example demonstrates how to define a quantum circuit using pyQPanda and integrate it as a PyTorch layer with VQNet. It shows input data preparation, forward and backward passes, and gradient calculation. ```default import pyqpanda3.core as pq from pyvqnet.qnn.pq3 import ProbsMeasure import numpy as np from pyvqnet.tensor import QTensor import pyvqnet pyvqnet.backends.set_backend("torch") from pyvqnet.qnn.vqc.torch import TorchQpanda3QuantumLayer def pqctest (input,param): num_of_qubits = 4 m_machine = pq.CPUQVM()# outside qubits =range(num_of_qubits) circuit = pq.QCircuit() circuit<II", flbl.read(8)) lbl = pyarray("b", flbl.read()) flbl.close() fimg = open(fname_image, 'rb') magic_nr, size, rows, cols = struct.unpack(">IIII", fimg.read(16)) img = pyarray("B", fimg.read()) fimg.close() ind = [k for k in range(size) if lbl[k] in digits] N = len(ind) images = np.zeros((N, rows, cols)) labels = np.zeros((N, 1), dtype=int) for i in range(len(ind)): images[i] = np.array(img[ind[i] * rows * cols: (ind[i] + 1) * rows * cols]).reshape((rows, cols)) labels[i] = lbl[ind[i]] return images, labels def run2(): ##load dataset x_train, y_train = load_mnist("training_data") # 下载训练数据 x_train = x_train / 255 # 将数据进行归一化处理[0,1] x_test, y_test = load_mnist("testing_data") x_test = x_test / 255 x_train = x_train.reshape([-1, 1, 28, 28]) x_test = x_test.reshape([-1, 1, 28, 28]) x_train = x_train[:100, :, :, :] x_train = np.resize(x_train, [x_train.shape[0], 1, 2, 2]) x_test = x_test[:10, :, :, :] x_test = np.resize(x_test, [x_test.shape[0], 1, 2, 2]) encode_qubits = 4 latent_qubits = 2 trash_qubits = encode_qubits - latent_qubits total_qubits = 1 + trash_qubits + encode_qubits print("model start") model = Model(trash_qubits, total_qubits) optimizer = Adam(model.parameters(), lr=0.005) model.train() F1 = open("rlt.txt", "w") loss_list = [] loss_list_test = [] fidelity_train = [] fidelity_val = [] for epoch in range(1, 10): running_fidelity_train = 0 running_fidelity_val = 0 print(f"epoch {epoch}") model.train() full_loss = 0 n_loss = 0 n_eval = 0 batch_size = 1 correct = 0 ``` -------------------------------- ### PyTorch RNN Module Example Source: https://github.com/originq/vqnet2.0-tutorial/blob/main/source/rst/torch_api.md Shows how to instantiate and use a multi-layer, bidirectional RNN module with the PyTorch backend. The backend must be set to 'torch' and relevant classes imported. ```python import pyvqnet pyvqnet.backends.set_backend("torch") from pyvqnet.nn.torch import RNN from pyvqnet.tensor import tensor rnn2 = RNN(4, 6, 2, batch_first=False, bidirectional = True) input = tensor.ones([5, 3, 4]) h0 = tensor.ones([4, 3, 6]) output, hn = rnn2(input, h0) ``` -------------------------------- ### Triton Fused Layer Normalization Backward Pass (Input Gradient) Source: https://github.com/originq/vqnet2.0-tutorial/blob/main/source/rst/nn.md A Triton kernel for the backward pass of layer normalization, specifically computing the input gradient (dx). This kernel requires careful setup and specific library installations. It also handles accumulation of weight and bias gradients. ```python import torch as real_torch import pyvqnet as torch import triton import triton.language as tl @triton.jit def _layer_norm_bwd_dx_fused(DX, # pointer to the input gradient DY, # pointer to the output gradient DW, # pointer to the partial sum of weights gradient DB, # pointer to the partial sum of biases gradient X, # pointer to the input W, # pointer to the weights Mean, # pointer to the mean Rstd, # pointer to the 1/std Lock, # pointer to the lock stride, # how much to increase the pointer when moving by 1 row N, # number of columns in X GROUP_SIZE_M: tl.constexpr, BLOCK_SIZE_N: tl.constexpr): # Map the program id to the elements of X, DX, and DY it should compute. row = tl.program_id(0) cols = tl.arange(0, BLOCK_SIZE_N) mask = cols < N X += row * stride DY += row * stride DX += row * stride # Offset locks and weights/biases gradient pointer for parallel reduction lock_id = row % GROUP_SIZE_M Lock += lock_id Count = Lock + GROUP_SIZE_M DW = DW + lock_id * N + cols DB = DB + lock_id * N + cols # Load data to SRAM x = tl.load(X + cols, mask=mask, other=0).to(tl.float32) dy = tl.load(DY + cols, mask=mask, other=0).to(tl.float32) w = tl.load(W + cols, mask=mask).to(tl.float32) mean = tl.load(Mean + row) rstd = tl.load(Rstd + row) # Compute dx xhat = (x - mean) * rstd wdy = w * dy xhat = tl.where(mask, xhat, 0.) wdy = tl.where(mask, wdy, 0.) c1 = tl.sum(xhat * wdy, axis=0) / N c2 = tl.sum(wdy, axis=0) / N dx = (wdy - (xhat * c1 + c2)) * rstd # Write dx tl.store(DX + cols, dx, mask=mask) # Accumulate partial sums for dw/db partial_dw = (dy * xhat).to(w.dtype) partial_db = (dy).to(w.dtype) while tl.atomic_cas(Lock, 0, 1) == 1: pass count = tl.load(Count) # First store doesn't accumulate if count == 0: tl.atomic_xchg(Count, 1) else: partial_dw += tl.load(DW, mask=mask) partial_db += tl.load(DB, mask=mask) tl.store(DW, partial_dw, mask=mask) tl.store(DB, partial_db, mask=mask) # need a barrier to ensure all threads finished before # releasing the lock tl.debug_barrier() # Release the lock tl.atomic_xchg(Lock, 0) ``` -------------------------------- ### QLSTM Initialization and Usage Source: https://github.com/originq/vqnet2.0-tutorial/blob/main/source/rst/vqc.md Demonstrates how to initialize and use the QLSTM layer for processing sequential data. Ensure necessary imports are included. ```python import numpy as np from pyvqnet.tensor import tensor from pyvqnet.qnn.qlstm import QLSTM from pyvqnet.dtype import * para_num = 4 num_of_qubits = 4 input_size = 4 hidden_size = 20 batch_size = 3 seq_length = 5 qlstm = QLSTM(para_num, num_of_qubits, input_size, hidden_size, batch_first=True) x = tensor.QTensor(np.random.randn(batch_size, seq_length, input_size), dtype=kfloat32) output, (h_t, c_t) = qlstm(x) print("Output shape:", output.shape) print("h_t shape:", h_t.shape) print("c_t shape:", c_t.shape) ``` -------------------------------- ### Quantum Classic Neural Network Transfer Learning Demo Setup Source: https://github.com/originq/vqnet2.0-tutorial/blob/main/source/rst/qml_demo.md This script sets up the environment for a quantum-classical neural network transfer learning demo. It includes necessary imports for VQNet components, quantum operations, data handling, and visualization, along with utility functions for downloading and preparing the MNIST dataset. ```Python """ Quantum Classic Nerual Network Transfer Learning demo """ import os import sys sys.path.insert(0,'../') import numpy as np import matplotlib.pyplot as plt from pyvqnet.nn.module import Module from pyvqnet.nn.linear import Linear from pyvqnet.nn.conv import Conv2D from pyvqnet.utils.storage import load_parameters, save_parameters from pyvqnet.nn import activation as F from pyvqnet.nn.pooling import MaxPool2D from pyvqnet.nn.batch_norm import BatchNorm2d from pyvqnet.nn.loss import SoftmaxCrossEntropy from pyvqnet.optim.sgd import SGD from pyvqnet.optim.adam import Adam from pyvqnet.data.data import data_generator from pyvqnet.tensor import tensor from pyvqnet.tensor.tensor import QTensor import pyqpanda as pq from pyqpanda import * import matplotlib from pyvqnet.nn.module import * from pyvqnet.utils.initializer import * from pyvqnet.qnn.quantumlayer import QuantumLayer try: matplotlib.use('TkAgg') except: pass try: import urllib.request except ImportError: raise ImportError('You should use Python 3.x') import os.path import gzip url_base = 'https://ossci-datasets.s3.amazonaws.com/mnist/' key_file = { 'train_img':'train-images-idx3-ubyte.gz', 'train_label':'train-labels-idx1-ubyte.gz', 'test_img':'t10k-images-idx3-ubyte.gz', 'test_label':'t10k-labels-idx1-ubyte.gz' } def _download(dataset_dir,file_name): file_path = dataset_dir + "/" + file_name if os.path.exists(file_path): with gzip.GzipFile(file_path) as f: file_path_ungz = file_path[:-3].replace('\\', '/') if not os.path.exists(file_path_ungz): open(file_path_ungz,"wb").write(f.read()) return print("Downloading " + file_name + " ... ") urllib.request.urlretrieve(url_base + file_name, file_path) if os.path.exists(file_path): with gzip.GzipFile(file_path) as f: file_path_ungz = file_path[:-3].replace('\\', '/') file_path_ungz = file_path_ungz.replace('-idx', '.idx') if not os.path.exists(file_path_ungz): open(file_path_ungz,"wb").write(f.read()) print("Done") def download_mnist(dataset_dir): for v in key_file.values(): _download(dataset_dir,v) if not os.path.exists("./result"): os.makedirs("./result") else: pass ``` -------------------------------- ### Download Qwen2.5-0.5B Model Source: https://github.com/originq/vqnet2.0-tutorial/blob/main/source/rst/llm.md Download the Qwen2.5-0.5B base model for fine-tuning. If direct cloning is not possible, individual files can be downloaded from the provided Hugging Face link. ```bash # 下载Qwen2.5-0.5B git clone https://huggingface.co/Qwen/Qwen2.5-0.5B ``` -------------------------------- ### QMLPModel Initialization and Usage Source: https://github.com/originq/vqnet2.0-tutorial/blob/main/source/rst/vqc.md Shows how to initialize and use the QMLPModel for hybrid quantum-classical neural network tasks. Requires specifying kernel, stride, and padding for pooling operations. ```python import numpy as np from pyvqnet.tensor import tensor from pyvqnet.qnn.qmlp.qmlp import QMLPModel from pyvqnet.dtype import * input_channels = 16 output_channels = 10 num_qubits = 4 kernel = (2, 2) stride = (2, 2) padding = "valid" batch_size = 8 model = QMLPModel(input_channels=num_qubits, output_channels=output_channels, num_qubits=num_qubits, kernel=kernel, stride=stride, padding=padding) x = tensor.QTensor(np.random.randn(batch_size, input_channels, 32, 32),dtype=kfloat32) output = model(x) print("Output shape:", output.shape) ``` -------------------------------- ### Initialize QTensor and QModel Source: https://github.com/originq/vqnet2.0-tutorial/blob/main/source/rst/vqc.md Initializes a QTensor with input data and sets up QModel and QModel_before instances for a quantum circuit. ```Python import pyvqnet import pyvqnet.tensor as tensor input_x = tensor.QTensor([[0.1, 0.2, 0.3, 0.4], [0.1, 0.2, 0.3, 0.4]], dtype=pyvqnet.kfloat64) input_x.requires_grad = True num_wires = 3 qunatum_model = QModel(num_wires=num_wires, dtype=pyvqnet.kcomplex128) qunatum_model_before = QModel_before(num_wires=num_wires, dtype=pyvqnet.kcomplex128) ``` -------------------------------- ### Getting QTensor Element Count (numel) Source: https://github.com/originq/vqnet2.0-tutorial/blob/main/source/rst/QTensor.md Returns the total number of elements in a QTensor, similar to the size property. This method is useful for quickly getting the total count of elements. ```python from pyvqnet.tensor import QTensor a = QTensor([2.0, 3.0, 4.0, 5.0], requires_grad=True) print(a.numel()) ``` -------------------------------- ### QRLModel Initialization and Usage Source: https://github.com/originq/vqnet2.0-tutorial/blob/main/source/rst/vqc.md Demonstrates the initialization and usage of the QRLModel for quantum deep reinforcement learning. This model uses variational quantum circuits. ```python from pyvqnet.tensor import tensor, QTensor from pyvqnet.qnn.qrl import QRLModel num_qubits = 4 model = QRLModel(num_qubits=num_qubits, n_layers=2) batch_size = 3 x = QTensor([[1.1, 0.3, 1.2, 0.6], [0.2, 1.1, 0, 1.1], [1.3, 1.3, 0.3, 0.3]]) output = model(x) output.backward() print("Model output:", output) ``` -------------------------------- ### qprog_with_measure Function Example Source: https://github.com/originq/vqnet2.0-tutorial/blob/main/source/rst/torch_api.md Example demonstrating the usage of the qprog_with_measure function, which is a quantum circuit function defined in pyQPanda. It requires specific parameters like input, param, nqubits, and ncubits to function correctly. ```APIDOC ## qprog_with_measure Function ### Description This function defines a quantum circuit using pyQPanda and is designed to work within the PyVNet framework when using the PyTorch backend. It requires specific input parameters to define the circuit's behavior and measurements. ### Parameters - **input** (array-like): Input 1D classical data. If none, input `None`. - **param** (array-like): Trainable parameters for the variational quantum circuit. - **nqubits** (int): The total number of qubits to be used in the circuit. - **ncubits** (int): The number of qubits to be measured. ### Example ```python import pyqpanda3.core as pq from pyvqnet.qnn.pq3 import ProbsMeasure import numpy as np from pyvqnet.tensor import QTensor import pyvqnet pyvqnet.backends.set_backend("torch") from pyvqnet.qnn.vqc.torch import TorchQpanda3QuantumLayer def pqctest (input,param): num_of_qubits = 4 m_machine = pq.CPUQVM()# outside qubits =range(num_of_qubits) circuit = pq.QCircuit() circuit<=12" ``` -------------------------------- ### RMSProp Optimizer Example Source: https://github.com/originq/vqnet2.0-tutorial/blob/main/source/rst/nn.md Illustrates how to use the RMSProp optimizer for parameter updates. Ensure Pyvqnet tensor and optimizer modules are imported. ```default import numpy as np from pyvqnet.optim import rmsprop from pyvqnet.tensor import QTensor w = np.arange(24).reshape(1,2,3,4).astype(np.float64) param = QTensor(w) param.grad = QTensor(np.arange(24).reshape(1,2,3,4).astype(np.float64)) params = [param] opti = rmsprop.RMSProp(params) for i in range(1,3): opti._step() print(param) ``` -------------------------------- ### Adamax Optimizer Example Source: https://github.com/originq/vqnet2.0-tutorial/blob/main/source/rst/nn.md Demonstrates the usage of the Adamax optimizer for updating model parameters. Requires Pyvqnet tensor and optimizer modules. ```default import numpy as np from pyvqnet.optim import adamax from pyvqnet.tensor import QTensor w = np.arange(24).reshape(1,2,3,4).astype(np.float64) param = QTensor(w) param.grad = QTensor(np.arange(24).reshape(1,2,3,4).astype(np.float64)) params = [param] opti = adamax.Adamax(params) for i in range(1,3): opti._step() print(param) ``` -------------------------------- ### Building a VQC Model with Input Encoding Source: https://github.com/originq/vqnet2.0-tutorial/blob/main/source/rst/vqc.md This example demonstrates constructing a hybrid quantum-classical neural network using VQC. It shows how to encode input data into quantum gates (RZ) and perform probability measurements. Ensure QMachine.reset_states() is called at the beginning of the forward function for proper state initialization. ```Python from pyvqnet.nn import Module,Linear,ModuleList from pyvqnet.qnn.vqc.qcircuit import VQC_HardwareEfficientAnsatz,RZZ,RZ from pyvqnet.qnn.vqc import Probability,QMachine from pyvqnet import tensor class QM(Module): def __init__(self, name=""): super().__init__(name) self.linearx = Linear(4,2) self.ansatz = VQC_HardwareEfficientAnsatz(4, ["rx", "RY", "rz"], entangle_gate="cnot", entangle_rules="linear", depth=2) #基于VQC的RZ 在0比特上 self.encode1 = RZ(wires=0) #基于VQC的RZ 在1比特上 self.encode2 = RZ(wires=1) #基于VQC的概率测量 在0,2比特上 self.measure = Probability(wires=[0,2]) #量子设备QMachine,使用4个比特。 self.device = QMachine(4) def forward(self, x, *args, **kwargs): #必须要将states reset到与输入一样的batchsize。 self.device.reset_states(x.shape[0]) y = self.linearx(x) #将输入编码到RZ门上,注意输入必须是 [batchsize,1]的shape self.encode1(params = y[:, 0],q_machine = self.device,) #将输入编码到RZ门上,注意输入必须是 [batchsize,1]的shape self.encode2(params = y[:, 1],q_machine = self.device,) self.ansatz(q_machine =self.device) return self.measure(q_machine =self.device) bz =3 inputx = tensor.arange(1.0,bz*4+1).reshape([bz,4]) inputx.requires_grad= True #像其他Module一样定义 qlayer = QM() #前传 y = qlayer(inputx) #反传 y.backward() print(y) ``` -------------------------------- ### Conv2D Layer Example Source: https://github.com/originq/vqnet2.0-tutorial/blob/main/source/rst/nn.md Demonstrates the application of the Conv2D layer for 2D convolution. Input shape is (batch_size, input_channels, height, width). ```python import numpy as np from pyvqnet.tensor import QTensor from pyvqnet.nn import Conv2D import pyvqnet b= 2 ic =3 oc = 2 test_conv = Conv2D(ic,oc,(3,3),(2,2),"same") x0 = QTensor(np.arange(1,b*ic*5*5+1).reshape([b,ic,5,5]),requires_grad=True,dtype=pyvqnet.kfloat32) x = test_conv.forward(x0) print(x) ``` -------------------------------- ### Getting QTensor Shape Source: https://github.com/originq/vqnet2.0-tutorial/blob/main/source/rst/QTensor.md Retrieves the shape of a QTensor, which is a list representing the size of each dimension. This helps in understanding the tensor's dimensions. ```python from pyvqnet.tensor import QTensor a = QTensor([2.0, 3.0, 4.0, 5.0], requires_grad=True) print(a.shape) ``` -------------------------------- ### Set PyTorch Backend Source: https://github.com/originq/vqnet2.0-tutorial/blob/main/source/rst/torch_api.md Configures VQNet to use PyTorch for backend computations. Ensure you have the correct PyTorch version installed, especially for GPU support. ```default import pyvqnet pyvqnet.backends.set_backend("torch") ``` -------------------------------- ### VQNet Demo: Data Preparation and Kernel Calculation Source: https://github.com/originq/vqnet2.0-tutorial/blob/main/source/rst/vqc_demo.md Prepares dataset (digits) by reducing dimensionality with PCA, scaling, and normalizing. It then computes both standard and projected quantum kernels for training and testing sets. ```python import time qubits = [2, 4, 8] for n in qubits: n_qubits = n x_tr, x_te , y_tr , y_te = train_test_split(digits.data, digits.target, test_size=0.3, random_state=22) pca = PCA(n_components=n_qubits).fit(x_tr) x_tr_reduced = pca.transform(x_tr) x_te_reduced = pca.transform(x_te) # normalize and scale std = StandardScaler().fit(x_tr_reduced) x_tr_norm = std.transform(x_tr_reduced) x_te_norm = std.transform(x_te_reduced) samples = np.append(x_tr_norm, x_te_norm, axis=0) minmax = MinMaxScaler((-1,1)).fit(samples) x_tr_norm = minmax.transform(x_tr_norm) x_te_norm = minmax.transform(x_te_norm) # select only 100 training and 20 test data tr_size = 100 x_tr = x_tr_norm[:tr_size] y_tr = y_tr[:tr_size] te_size = 20 x_te = x_te_norm[:te_size] y_te = y_te[:te_size] quantum_kernel_tr = vqnet_quantum_kernel(X_1=x_tr) projected_kernel_tr = vqnet_projected_quantum_kernel(X_1=x_tr) quantum_kernel_te = vqnet_quantum_kernel(X_1=x_te, X_2=x_tr) projected_kernel_te = vqnet_projected_quantum_kernel(X_1=x_te, X_2=x_tr) quantum_accuracy.append(calculate_generalization_accuracy(quantum_kernel_tr, y_tr, quantum_kernel_te, y_te)) ```