├── .readthedocs.yaml ├── Makefile ├── make.bat ├── requirements.txt └── source ├── conf.py ├── index.rst └── rst ├── CHANGELOG.rst ├── FAQ.rst ├── QTensor.rst ├── images ├── Barren_Plateau_mean.png ├── Barren_Plateau_variance.png ├── HQCNNAccuracy.png ├── HQCNNLOSS.png ├── Kmeans.jpg ├── QAE_Quantum_Cir.png ├── QMLP.png ├── QP-acc.png ├── QP-cir.png ├── QP-data.png ├── QP-pic.png ├── QTransferLearning_cir.png ├── Qcnn_circuit.png ├── Unet.png ├── Unet_data_imshow.png ├── VQC-SVM.png ├── all_singles_doubles.png ├── classic-quantum.PNG ├── dropout_sin.png ├── dsgd.png ├── ep_1.png ├── ep_9.png ├── eval_test.png ├── express.png ├── f1.png ├── f2.png ├── f3.png ├── final_quantum_circuit.png ├── gbp_arch.png ├── haar-fidelity.png ├── hqcnn_quantum_cir.png ├── hqcnn_train_loss.png ├── hqcnnarch.PNG ├── hqcnnmodel.PNG ├── loss3d.png ├── maxcut.png ├── mnsit_data_examples.png ├── mpi_bug.png ├── noise_1.PNG ├── noise_2.PNG ├── onnxsupport.csv ├── origin_circle.png ├── parallel_model.png ├── parallel_model_circuit.png ├── parallel_model_result.png ├── parallel_model_result_no_train.png ├── peft1.png ├── pqccir1.png ├── pqccir2.png ├── pqcloss.png ├── qae_train_loss.png ├── qaoa_demo.png ├── qcnn.png ├── qcnn_cir.png ├── qcnn_structrue.png ├── qcnn_transfer_learning_classical.png ├── qcnn_transfer_learning_predict.png ├── qcnn_vqnet.png ├── qcnn_vqnet_result.png ├── qdrl.png ├── qdrl_accuracy.png ├── qdrl_for_simple.png ├── qgan-arch.PNG ├── qgan-loss.png ├── qgan-pdf.png ├── qiskit_eval_test.png ├── qiskit_hqcnn_train_loss.png ├── qlinear_cir.png ├── qng_all_cir.png ├── qng_subcir1.png ├── qng_subcir2.png ├── qng_vs_sgd.png ├── qsvd.png ├── qsvd_algorithm.png ├── qsvm-arch.png ├── qsvm-kernel.png ├── quanvo.png ├── qunet_cir.png ├── qunet_eval_1.jpg ├── qunet_eval_2.jpg ├── qunet_eval_3.jpg ├── qunet_quantum.png ├── qunet_train_loss.png ├── qvc_accuracy.png ├── qvc_circuit.png ├── resnet_onnx.png ├── result_QDRL.gif ├── result_qcnn_small.png ├── rotosolve.png ├── same_apis_from_tn.csv ├── same_apis_from_vqc.csv ├── single_qubit_model.png ├── single_qubit_model_circuit.png ├── single_qubit_model_result.png ├── single_qubit_model_result_no_train.png ├── stochastic_parameter-shift.png ├── vsql_0.png ├── vsql_1.png ├── vsql_2.png ├── vsql_3.png ├── vsql_4.png ├── vsql_5.png ├── vsql_6.png ├── vsql_7.png ├── vsql_8.png ├── vsql_cacc.PNG ├── vsql_closs.PNG ├── vsql_model.PNG ├── vsql_qacc.PNG └── vsql_qloss.PNG ├── install.rst ├── llm.rst ├── nn.rst ├── qml_demo.rst ├── qnn.rst ├── qnn_pq3.rst ├── torch_api.rst ├── utils.rst ├── vqc.rst └── vqc_demo.rst /.readthedocs.yaml: -------------------------------------------------------------------------------- 1 | # Read the Docs configuration file for Sphinx projects 2 | # See https://docs.readthedocs.io/en/stable/config-file/v2.html for details 3 | 4 | # Required 5 | version: 2 6 | 7 | # Set the OS, Python version and other tools you might need 8 | build: 9 | os: ubuntu-22.04 10 | tools: 11 | python: "3.7" 12 | # You can also specify other tool versions: 13 | # nodejs: "20" 14 | # rust: "1.70" 15 | # golang: "1.20" 16 | 17 | # Build documentation in the "docs/" directory with Sphinx 18 | sphinx: 19 | configuration: source/conf.py 20 | # You can configure Sphinx to use a different builder, for instance use the dirhtml builder for simpler URLs 21 | # builder: "dirhtml" 22 | # Fail on all warnings to avoid broken references 23 | # fail_on_warning: true 24 | 25 | # Optionally build your docs in additional formats such as PDF and ePub 26 | # formats: 27 | # - pdf 28 | # - epub 29 | 30 | # Optional but recommended, declare the Python requirements required 31 | # to build your documentation 32 | # See https://docs.readthedocs.io/en/stable/guides/reproducible-builds.html 33 | python: 34 | install: 35 | - requirements: requirements.txt -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | # Minimal makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line, and also 5 | # from the environment for the first two. 6 | SPHINXOPTS ?= 7 | SPHINXBUILD ?= sphinx-build 8 | SOURCEDIR = source 9 | BUILDDIR = build 10 | 11 | # Put it first so that "make" without argument is like "make help". 12 | help: 13 | @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) 14 | 15 | .PHONY: help Makefile 16 | 17 | # Catch-all target: route all unknown targets to Sphinx using the new 18 | # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). 19 | %: Makefile 20 | @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) 21 | -------------------------------------------------------------------------------- /make.bat: -------------------------------------------------------------------------------- 1 | @ECHO OFF 2 | 3 | pushd %~dp0 4 | 5 | REM Command file for Sphinx documentation 6 | 7 | if "%SPHINXBUILD%" == "" ( 8 | set SPHINXBUILD=sphinx-build 9 | ) 10 | set SOURCEDIR=source 11 | set BUILDDIR=build 12 | 13 | if "%1" == "" goto help 14 | 15 | %SPHINXBUILD% >NUL 2>NUL 16 | if errorlevel 9009 ( 17 | echo. 18 | echo.The 'sphinx-build' command was not found. Make sure you have Sphinx 19 | echo.installed, then set the SPHINXBUILD environment variable to point 20 | echo.to the full path of the 'sphinx-build' executable. Alternatively you 21 | echo.may add the Sphinx directory to PATH. 22 | echo. 23 | echo.If you don't have Sphinx installed, grab it from 24 | echo.http://sphinx-doc.org/ 25 | exit /b 1 26 | ) 27 | 28 | if "%1" == "pdf" ( 29 | %sphinxBUILD% -b pdf %SPHINXOPTS% %SOURCEDIR% %BUILDDIR%/pdf 30 | if errorlevel 1 exit /b 1 31 | echo. 32 | echo.Build finished. The pdf files are in %BUILDDIR%/pdf. 33 | goto end 34 | ) 35 | 36 | 37 | %SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O% 38 | goto end 39 | 40 | :help 41 | %SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O% 42 | 43 | :end 44 | popd 45 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | sphinx-rtd-theme -------------------------------------------------------------------------------- /source/conf.py: -------------------------------------------------------------------------------- 1 | # Configuration file for the Sphinx documentation builder. 2 | # 3 | # This file only contains a selection of the most common options. For a full 4 | # list see the documentation: 5 | # https://www.sphinx-doc.org/en/master/usage/configuration.html 6 | 7 | # -- Path setup -------------------------------------------------------------- 8 | 9 | # If extensions (or modules to document with autodoc) are in another directory, 10 | # add these directories to sys.path here. If the directory is relative to the 11 | # documentation root, use os.path.abspath to make it absolute, like shown here. 12 | # 13 | import sphinx_rtd_theme 14 | # -- Project information ----------------------------------------------------- 15 | 16 | project = 'VQNET' 17 | copyright = '2022, Original Quantum' 18 | author = 'Original Quantum' 19 | 20 | # The full version, including alpha/beta/rc tags 21 | release = 'v2.15.0' 22 | 23 | 24 | # -- General configuration --------------------------------------------------- 25 | 26 | # Add any Sphinx extension module names here, as strings. They can be 27 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom 28 | # ones. 29 | extensions = ['sphinx.ext.autodoc', 'sphinx.ext.napoleon','sphinx.ext.autosummary'] 30 | 31 | # Add any paths that contain templates here, relative to this directory. 32 | templates_path = ['_templates'] 33 | 34 | # The language for content autogenerated by Sphinx. Refer to documentation 35 | # for a list of supported languages. 36 | # 37 | # This is also used if you do content translation via gettext catalogs. 38 | # Usually you set "language" from the command line for these cases. 39 | language = 'en' 40 | 41 | # List of patterns, relative to source directory, that match files and 42 | # directories to ignore when looking for source files. 43 | # This pattern also affects html_static_path and html_extra_path. 44 | exclude_patterns = [] 45 | 46 | 47 | # -- Options for HTML output ------------------------------------------------- 48 | 49 | # The theme to use for HTML and HTML Help pages. See the documentation for 50 | # a list of builtin themes. 51 | # 52 | html_theme = "sphinx_rtd_theme" 53 | 54 | html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] 55 | # Add any paths that contain custom static files (such as style sheets) here, 56 | # relative to this directory. They are copied after the builtin static files, 57 | # so a file named "default.css" will overwrite the builtin "default.css". 58 | html_static_path = ['_static'] 59 | 60 | # -- Options for PDF output -------------------------------------------------- 61 | 62 | # Grouping the document tree into PDF files. List of tuples 63 | # (source start file,target name,title,author,options). 64 | # 65 | # If there is more than one author,separate them with \\. 66 | # For example: r'Guido van Rossum\\Fred L. Drake,Jr.,editor' 67 | # 68 | # The options element is a dictionary that lets you override 69 | # this config per-document. 70 | # For example,# ('index',u'MyProject',u'My Project',u'Author Name',# dict(pdf_compressed = True)) 71 | # would mean that specific document would be compressed 72 | # regardless of the global pdf_compressed setting. 73 | 74 | pdf_documents = [ 75 | ('index',u'HanLP Handbook',u'hankcs'),] 76 | 77 | # A comma-separated list of custom stylesheets. Example: 78 | pdf_stylesheets = ['a3'] 79 | 80 | # Create a compressed PDF 81 | # Use True/False or 1/0 82 | # Example: compressed=True 83 | #pdf_compressed = False 84 | 85 | # A colon-separated list of folders to search for fonts. Example: 86 | pdf_font_path = ['C:\\Windows\\Fonts'] 87 | 88 | 89 | 90 | # Mode for literal blocks wider than the frame. Can be 91 | # overflow,shrink or truncate 92 | pdf_fit_mode = "shrink" 93 | 94 | # Section level that forces a break page. 95 | # For example: 1 means top-level sections start in a new page 96 | # 0 means disabled 97 | #pdf_break_level = 0 98 | 99 | # When a section starts in a new page,force it to be 'even','odd',# or just use 'any' 100 | #pdf_breakside = 'any' 101 | 102 | # Insert footnotes where they are defined instead of 103 | # at the end. 104 | #pdf_inline_footnotes = True 105 | 106 | # verbosity level. 0 1 or 2 107 | #pdf_verbosity = 0 108 | 109 | # If false,no index is generated. 110 | #pdf_use_index = True 111 | 112 | # If false,no modindex is generated. 113 | #pdf_use_modindex = True 114 | 115 | # If false,no coverpage is generated. 116 | #pdf_use_coverpage = True 117 | 118 | # Documents to append as an appendix to all manuals. 119 | #pdf_appendices = [] 120 | 121 | # Enable experimental feature to split table cells. Use it 122 | # if you get "DelayedTable too big" errors 123 | #pdf_splittables = False 124 | 125 | # Set the default DPI for images 126 | #pdf_default_dpi = 72 127 | 128 | # Enable rst2pdf extension modules (default is only vectorpdf) 129 | # you need vectorpdf if you want to use sphinx's graphviz support 130 | #pdf_extensions = ['vectorpdf'] 131 | 132 | # Page template name for "regular" pages 133 | #pdf_page_template = 'cutePage' 134 | 135 | # Show Table Of Contents at the beginning? 136 | pdf_use_toc = False 137 | 138 | # How many levels deep should the table of contents be? 139 | pdf_toc_depth = 2 140 | 141 | # Add section number to section references 142 | pdf_use_numbered_links = False 143 | 144 | # Background images fitting mode 145 | pdf_fit_background_mode = 'scale' 146 | 147 | 148 | latex_engine = 'xelatex' 149 | latex_elements = { 150 | 'papersize': 'a4paper', 151 | 'pointsize': '11pt', 152 | 'preamble': r''' 153 | \usepackage{xeCJK} 154 | \setCJKmainfont[BoldFont=STZhongsong, ItalicFont=STKaiti]{STSong} 155 | \setCJKsansfont[BoldFont=STHeiti]{STXihei} 156 | \setCJKmonofont{STFangsong} 157 | \XeTeXlinebreaklocale "zh" 158 | \XeTeXlinebreakskip = 0pt plus 1pt 159 | \parindent 2em 160 | \definecolor{VerbatimColor}{rgb}{0.95,0.95,0.95} 161 | \setcounter{tocdepth}{3} 162 | \renewcommand\familydefault{\ttdefault} 163 | \renewcommand\CJKfamilydefault{\CJKrmdefault} 164 | ''' 165 | } 166 | -------------------------------------------------------------------------------- /source/index.rst: -------------------------------------------------------------------------------- 1 | .. VQNet documentation master file, created by 2 | sphinx-quickstart on Tue Jul 27 15:25:07 2021. 3 | You can adapt this file completely to your liking, but it should at least 4 | contain the root `toctree` directive. 5 | 6 | VQNet 7 | ================================= 8 | 9 | 10 | 11 | VQNet 是由本源量子自主研发的量子机器学习计算框架,专注于为用户提供一个灵活、高效的开发平台,支持构建和运行混合量子-经典机器学习算法,并调用本源量子芯片进行变分量子线路训练。 12 | 本使用文档是VQNet的api以及示例文档。英文版本可见: `VQNet API DOC. `_ 13 | 14 | 15 | VQNet 的核心特点 16 | ----------------- 17 | 18 | 多平台兼容性与跨环境支持 19 | ~~~~~~~~~~~~~~~~~~~~~~~~~ 20 | 21 | VQNet 支持用户在多种硬件和操作系统环境中进行量子与经典机器学习的研究与开发。无论是使用CPU、GPU进行量子计算模拟,还是通过本源量子云服务调用真实量子芯片,VQNet都能提供无缝支持。目前,VQNet 已兼容 Windows、Linux 和 macOS 系统的python3.9,python3.10,python3.11版本。 22 | 23 | 完善的接口设计与易用性 24 | ~~~~~~~~~~~~~~~~~~~~~~~ 25 | 26 | VQNet 采用 Python 作为前端语言,提供类似于主流神经网络训练框架的编程接口,并可自由选择多种计算后端实现经典与量子机器学习模型的自动微分功能。框架内置了:100+ 常用 Tensor 计算接口、100+ 量子变分线路计算接口、50+ 经典神经网络接口。这些接口覆盖了从经典机器学习到量子机器学习的完整开发流程,并且将持续更新。 27 | 28 | 高效的计算性能与扩展能力 29 | ~~~~~~~~~~~~~~~~~~~~~~~~~ 30 | 31 | 32 | - **真实量子芯片实验支持**:对于需要真实量子芯片实验的用户,VQNet 集成了 本源 pyQPanda 接口,并结合本源司南的高效调度能力,可实现快速的量子线路模拟计算和真实芯片运行。 33 | - **本地计算优化**:对于本地计算需求,VQNet 提供基于 CPU 或 GPU 的量子机器学习编程接口,利用自动微分技术进行量子变分线路梯度计算,相比传统参数漂移法(如 Qiskit)速度提升明显。 34 | - **分布式计算支持**:VQNet 支持基于 MPI 的分布式计算,可在多个节点上实现训练分布式混合量子-经典神经网络模型的功能。 35 | 36 | 丰富的应用场景与示例支持 37 | ~~~~~~~~~~~~~~~~~~~~~~~~~ 38 | 39 | VQNet 不仅是一个强大的开发工具,还在公司内部多个项目中得到了广泛应用,包括 电力优化、医疗数据分析、图像处理 等领域。为了帮助用户快速上手,VQNet 在官网和 API 在线文档中提供了涵盖从基础教程到高级应用的多种场景。这些资源让用户能够轻松理解如何利用 VQNet 解决实际问题,并快速构建自己的量子机器学习应用。 40 | 41 | 42 | 43 | .. toctree:: 44 | :caption: 安装介绍 45 | :maxdepth: 2 46 | 47 | rst/install.rst 48 | 49 | .. toctree:: 50 | :caption: 上手实例 51 | :maxdepth: 2 52 | 53 | rst/vqc_demo.rst 54 | rst/qml_demo.rst 55 | 56 | .. toctree:: 57 | :caption: 经典神经网络接口介绍 58 | :maxdepth: 2 59 | 60 | rst/QTensor.rst 61 | rst/nn.rst 62 | 63 | rst/utils.rst 64 | 65 | .. toctree:: 66 | :caption: 使用pyqpanda的量子神经网络接口 67 | :maxdepth: 2 68 | 69 | rst/qnn.rst 70 | rst/qnn_pq3.rst 71 | 72 | .. toctree:: 73 | :caption: 量子神经网络自动微分模拟接口 74 | :maxdepth: 2 75 | 76 | rst/vqc.rst 77 | 78 | .. toctree:: 79 | :caption: 量子大模型微调 80 | :maxdepth: 2 81 | 82 | rst/llm.rst 83 | 84 | .. toctree:: 85 | :caption: 其他 86 | :maxdepth: 2 87 | 88 | rst/torch_api.rst 89 | rst/FAQ.rst 90 | rst/CHANGELOG.rst 91 | 92 | 93 | 94 | 95 | 96 | -------------------------------------------------------------------------------- /source/rst/CHANGELOG.rst: -------------------------------------------------------------------------------- 1 | 2 | VQNet Changelog 3 | ###################### 4 | 5 | [v2.17.0] - 2025-4-22 6 | *************************** 7 | 8 | Added 9 | =================== 10 | 11 | - 增加了张量网络后端实现量子线路模块功能,增加基础逻辑门、测量、复杂量子线路支持。 12 | - 增加了张量网络后端对大比特量子线路构建功能实现。 13 | - 增加QTensor.swapaxes接口,为swapaxis的别名。 14 | 15 | Changed 16 | =================== 17 | - 使用openblas进行矩阵运算。 18 | - 使用sleef进行CPU SIMD运算。 19 | - 删除qnn.MeasurePauliSum。 20 | - 当torch低于2.4.0版本时候,使用torch后端计算抛出警告。 21 | 22 | 23 | Fixed 24 | =================== 25 | - 解决保存和载入模型时候QMachine states无法载入的问题。 26 | - 解决layernorm,groupnorm当affine=False时候的问题。 27 | - 解决 QuantumLayerAdjoint在eval模式下的问题。 28 | - 解决 `toCPU()` 的bug。 29 | - 解决 BatchNorm1d,BatchNorm2d, BatchNormNd 在affine=False 的bug。 30 | 31 | [v2.16.0] - 2025-1-15 32 | *************************** 33 | 34 | Added 35 | =================== 36 | 37 | - 增加使用pyqpanda3进行量子线路计算的接口。 38 | - MeasureAll接口支持复合泡利算符。 39 | - 增加DataParallelVQCAdjointLayer以及DataParallelVQCLayer接口。 40 | 41 | Changed 42 | =================== 43 | 44 | - 移除ONNX过时功能,移除集成pyqpanda的绝大部分接口,保留示例代码中使用的部分接口。 45 | - VQC_QuantumEmbedding接口修改 46 | - 安装本软件包时不再同时安装pyqpanda, 而是同时安装pyqpanda3. 47 | - VQC接口支持入参使用 `x[,:2]`,原先只支持 `x[:,[2]]` 形式。 48 | - 本软件支持3.9,3.10,3.11版本python 不再支持python3.8 49 | 50 | Fixed 51 | =================== 52 | - 解决发现的内存泄漏问题; 53 | - 解决发现的GPU随机数问题; 54 | - reduce相关操作,可支持的数组的最大维度从8提升到30; 55 | - 优化代码,提升了部分情况下的python代码运行速度; 56 | 57 | [v2.15.0] - 2024-11-19 58 | *************************** 59 | 60 | Added 61 | =================== 62 | 63 | - 增加 `pyvqnet.backends.set_backend()` 接口, 在用户安装 `torch` 时候, 可使用 `torch` 进行QTensor的矩阵计算, 变分量子线路计算, 具体见文档 :ref:`torch_api` 。 64 | - 增加 `pyvqnet.nn.torch` 下继承于 `torch.nn.Module` 的神经网络接口, 变分量子线路神经接口等, 具体见文档 :ref:`torch_api` 。 65 | - 增加量子大模型微调模块微调训练介绍,具体步骤可以见文档 :ref:`llm` 。 66 | 67 | Changed 68 | =================== 69 | - diag接口修改。 70 | - 修改all_gather实现与torch.distributed.all_gather一致。 71 | - 修改 `QTensor` 最大支持30维度数据。 72 | - 修改分布式功能所需 `mpi4py` 需要4.0.1版本以上 73 | 74 | Fixed 75 | =================== 76 | - 部分随机数实现由于omp无法固定种子。 77 | - 修复分布式启动的部分bug。 78 | 79 | 80 | [v2.14.0] - 2024-09-30 81 | *************************** 82 | 83 | Added 84 | =================== 85 | 86 | - 增加 `VQC_LCU`, `VQC_FABLE`, `VQC_QSVT` 的block-encoding算法, 以及qpanda算法实现 `QPANDA_QSVT`, `QPANDA_LCU`, `QPANDA_FABLE` 接口. 87 | - 增加整数加到量子比特上 `vqc_qft_add_to_register`, 两个量子比特上的数加法 `vqc_qft_add_two_register`,两个量子比特上的数乘法的 `vqc_qft_mul`. 88 | - 增加混合qpanda与vqc的训练模块 `HybirdVQCQpandaQVMLayer`. 89 | - 增加 `einsum`, `moveaxis`, `eigh`, `dignoal` 等接口实现. 90 | - 增加分布式计算中张量并行计算功能 `ColumnParallelLinear`, `RowParallelLinear`. 91 | - 增加分布式计算中Zero stage-1 功能 `ZeroModelInitial`. 92 | - `QuantumBatchAsyncQcloudLayer` 指定 diff_method == "random_coordinate_descent" 时候不会使用PSR而是随机对量子参数选择一个进行梯度计算. 93 | 94 | Changed 95 | =================== 96 | - 移除了xtensor部分。 97 | - api文档进行部分修改。区分了基于自动微分的量子机器学习示例以及基于qpanda的机器学习示例,区别基于自动微分的量子机器学习接口以及基于qpanda的机器学习示例接口。 98 | - `matmul` 支持1d@1d,2d@1d,1d@2d。 99 | - 增加了一些量子计算层别名: `QpandaQCircuitVQCLayer`` = `QuantumLayer` , `QpandaQCircuitVQCLayerLite` = `QuantumLayerV2`, `QpandaQProgVQCLayer` = `QuantumLayerV3`. 100 | 101 | Fixed 102 | =================== 103 | - 修改分布式计算功能中底层通信接口 `allreduce`, `allgather`, `reduce`, `broadcast` , 添加对 `core.Tensor` 数据通信支持 104 | - 解决随机数生成的bug。 105 | - 解决了 VQC的 `RXX`, `RYY`, `RZZ`, `RZX` 转换成originIR的错误。 106 | 107 | 108 | [v2.13.0] - 2024-07-30 109 | *************************** 110 | 111 | Added 112 | =================== 113 | 114 | - 增加 `no_grad`, `GroupNorm`, `Interpolate`, `contiguous`, `QuantumLayerV3`, `fuse_model`, `SDPA`, `quantum_fisher` 接口。 115 | - 为解决量子机器学习过程中出现的过拟合问题添加量子Dropout样例. 116 | 117 | Changed 118 | =================== 119 | 120 | - `BatchNorm`, `LayerNorm`, `GroupNorm` 增加affine接口。 121 | - `diag` 接口在2d输入时候现在返回对角线上的1d输出,与torch一致。 122 | - slice,permute等操作会尝试使用view方式返回共享内存的QTensor。 123 | - 所有接口支持非contiguous的输入。 124 | - `Adam` 支持 weight_decay 参数。 125 | 126 | Fixed 127 | =================== 128 | - 修改 VQC 部分逻辑门分解函数的错误。 129 | - 修复部分函数的内存泄露问题。 130 | - 修复 `QuantumLayerMultiProcess` 不支持GPU输入的问题。 131 | - 修改 `Linear` 的默认参数初始化话方式 132 | 133 | 134 | [v2.12.0] - 2024-05-01 135 | *************************** 136 | 137 | Added 138 | =================== 139 | 140 | - 添加流水线并行PipelineParallelTrainingWrapper接口。 141 | - 添加 `Gelu`, `DropPath`, `binomial`, `adamW` 接口。 142 | - 添加 `QuantumBatchAsyncQcloudLayer` 支持pyqpanda的本地虚拟机模拟计算。 143 | - 添加 xtensor的 `QuantumBatchAsyncQcloudLayer` 支持pyqpanda的本地虚拟机模拟计算以及真机计算。 144 | - 使得QTensor 可以被deepcopy以及pickle。 145 | - 添加分布式计算启动命令 `vqnetrun`, 使用分布式计算接口时使用。 146 | - 添加ES梯度计算方法真机接口 `QuantumBatchAsyncQcloudLayerES` 支持pyqpanda的本地虚拟机模拟计算以及真机计算。 147 | - 添加在分布式计算中支持QTensor的数据通信接口 `allreduce`, `reduce`, `broadcast`, `allgather`, `send`, `recv` 等。 148 | 149 | Changed 150 | =================== 151 | 152 | - 安装包新加入依赖 "Pillow", "hjson", linux系统下安装包添加新依赖 "psutil"。 "cloudpickle"。 153 | - 优化softmax以及tranpose在GPU下运行速度。 154 | - 使用cuda11.8编译。 155 | - 整合了基于cpu、gpu下的分布式计算接口。 156 | 157 | Fixed 158 | =================== 159 | - 降低Linux-GPU版本启动时候的显存消耗。 160 | - 修复select以及power函数的内存泄露问题。 161 | - 移除了cpu、gpu下基于reduce方法的模型参数以及梯度更新方法 `nccl_average_parameters_reduce`, `nccl_average_grad_reduce`。 162 | 163 | [v2.11.0] - 2024-03-01 164 | *************************** 165 | 166 | Added 167 | =================== 168 | 169 | - 添加新的 `QNG` (量子自然梯度)API 和演示。 170 | - 添加量子电路优化,例如 `wrapper_single_qubit_op_fuse` , `wrapper_commute_controlled` , `wrapper_merge_rotations` api 和 demo。 171 | - 添加 `CY`, `SparseHamiltonian` , `HermitianExpval` 。 172 | - 添加 `is_csr`、 `is_dense`、 `dense_to_csr` 、 `csr_to_dense` 。 173 | - 添加 `QuantumBatchAsyncQcloudLayer` 支持pyqpanda的QCloud真实芯片计算, `expval_qcloud`。 174 | - 添加基于NCCL的单节点下多GPU分布式计算数据并行模型训练的相关接口实现 `nccl_average_parameters_allreduce`, `nccl_average_parameters_reduce`, `nccl_average_grad_allreduce`, `nccl_average_grad_reduce` 以及控制NCCL初始化以及相关操作的类 `NCCL_api`。 175 | - 添加量子线路进化策略梯度计算方法 `QuantumLayerES` 接口。 176 | 177 | Changed 178 | =================== 179 | 180 | - 将 `VQC_CSWAP` 电路重构为 `CSWAP`。 181 | - 移除旧的 QNG 文档。 182 | - 从 `pyvqnet.qnn.vqc` 中移除函数和类无用的 `num_wires` 参数。 183 | - 重构 `MeasureAll`, `Probability` api。 184 | - 为 `QuantumMeasure` 增加qtype参数。 185 | 186 | Fixed 187 | =================== 188 | - 将 `QuantumMeasure` 的 slots 改为 shots。 189 | 190 | [v2.10.0] - 2023-12-30 191 | *************************** 192 | 193 | Added 194 | =========== 195 | - 增加了pyvqnet.qnn.vqc下的新接口:IsingXX、IsingXY、IsingYY、IsingZZ、SDG、TDG、PhaseShift、MutliRZ、MultiCnot、MultixCnot、ControlledPhaseShift、SingleExcitation、DoubleExcitation、VQC_AllSinglesDoubles,ExpressiveEntanglingAnsatz等; 196 | - 支持adjoint梯度计算的pyvqnet.qnn.vqc.QuantumLayerAdjoint接口; 197 | - 支持originIR与VQC相互转换的功能; 198 | - 支持统计VQC模型中的经典和量子模块信息; 199 | - 增加量子经典神经网络混合模型下的两个案例: 基于小样本的量子卷积神经网络模型、用于手写数字识别的量子核函数模型; 200 | - 增加对arm芯片Mac的支持; 201 | 202 | 203 | [v2.9.0] - 2023-11-15 204 | *************************** 205 | 206 | Added 207 | =========== 208 | - 增加了xtensor接口定义,支持经典神经网络模块自动并行和CPU/GPU多后端,包含对多维数组的常用数学,逻辑,矩阵计算,以及常见的经典神经网络层,优化器等150余个接口。 209 | 210 | Changed 211 | =========== 212 | - 从本版本开始,版本号从2.0.8 升级为2.9.0。 213 | - 自本版本开始,软件包上传到 https://pypi.originqc.com.cn, 使用 ``pip install pyvqnet --index-url https://pypi.originqc.com.cn`` 安装。 214 | 215 | [v2.0.8] - 2023-09-26 216 | *************************** 217 | 218 | Added 219 | =========== 220 | - 增加了现有接口支持complex128、complex64、double、float、uint8、int8、bool、int16、int32、int64等类型计算。 221 | - Linux版本支持gpu下的计算,需要cuda11.7版本cudatoolkit以及nvidia驱动。 222 | - 基于vqc的基础逻辑门: Hadamard、CNOT、I、RX、RY、PauliZ、PauliX、PauliY、S、RZ、RXX、RYY、RZZ、RZX、X1、Y1、Z1、U1、U2、U3、T、SWAP、P、TOFFOLI、CZ、CR。 223 | - 基于vqc的组合量子线路: VQC_HardwareEfficientAnsatz、VQC_BasicEntanglerTemplate、VQC_StronglyEntanglingTemplate、VQC_QuantumEmbedding、VQC_RotCircuit、VQC_CRotCircuit、VQC_CSWAPcircuit、VQC_Controlled_Hadamard、VQC_CCZ、VQC_FermionicSingleExcitation、VQC_FermionicDoubleExcitation、VQC_UCCSD、VQC_QuantumPoolingCircuit、VQC_BasisEmbedding、VQC_AngleEmbedding、VQC_AmplitudeEmbedding、VQC_IQPEmbedding。 224 | - 基于vqc的测量方法: VQC_Purity、VQC_VarMeasure、VQC_DensityMatrixFromQstate、Probability、MeasureAll。 225 | 226 | 227 | [v2.0.7] - 2023-07-03 228 | *************************** 229 | 230 | Added 231 | =========== 232 | - 经典神经网络,增加kron,gather,scatter,broadcast_to接口。 233 | - 增加对不同数据精度支持: 数据类型dtype支持kbool,kuint8,kint8,kint16,kint32,kint64,kfloat32,kfloat64,kcomplex64,kcomplex128.分别代表C++的 bool,uint8_t,int8_t,int16_t,int32_t,int64_t,float,double,complex,complex. 234 | - 支持python 3.8,3.9,3.10三个版本。 235 | 236 | Changed 237 | =========== 238 | - QTensor 以及Module类的init函数增加 `dtype` 参数。对QTensor索引、 部分神经网络层的输入进行了类型限制。 239 | - 量子神经网络,由于MacOS兼容性问题,去掉了Mnist_Dataset,CIFAR10_Dataset接口。 240 | 241 | [v2.0.6] - 2023-02-22 242 | *************************** 243 | 244 | 245 | Added 246 | =========== 247 | 248 | - 经典神经网络,增加接口: multinomial,pixel_shuffle,pixel_unshuffle,为QTensor增加numel,增加CPU动态内存池功能,为Parameter增加init_from_tensor接口。 249 | - 经典神经网络,增加接口: Dynamic_LSTM,Dynamic_RNN,Dynamic_GRU。 250 | - 经典神经网络,增加接口: pad_sequence,pad_packed_sequence,pack_pad_sequence。 251 | - 量子神经网络,增加接口: CCZ,Controlled_Hadamard,FermionicSingleExcitation,UCCSD,QuantumPoolingCircuit, 252 | - 量子神经网络,增加接口: Quantum_Embedding,Mnist_Dataset,CIFAR10_Dataset,grad,Purity。 253 | - 量子神经网络,增加示例: 基于梯度裁剪,quanvolution,量子线路表达力,贫瘠高原,量子强化学习QDRL。 254 | 255 | Changed 256 | =========== 257 | 258 | - API文档,重构内容结构,增加 `量子机器学习研究` 模块,将 `VQNet2ONNX模块` 改为 `其他函数` 。 259 | 260 | 261 | 262 | Fixed 263 | =========== 264 | 265 | - 经典神经网络,解决相同随机种子跨平台产生不同正态分布的问题。 266 | - 量子神经网络,实现expval,ProbMeasure,QuantumMeasure 对QPanda GPU虚拟机的支持。 267 | 268 | 269 | [v2.0.5] - 2022-12-25 270 | *************************** 271 | 272 | 273 | Added 274 | =========== 275 | 276 | - 经典神经网络,增加log_softmax实现,增加模型转ONNX的接口export_model函数。 277 | - 经典神经网络,支持当前已有的绝大多数经典神经网络模块转换为ONNX,详情参考API文档 “VQNet2ONNX模块”。 278 | - 量子神经网络,增加VarMeasure,MeasurePauliSum,Quantum_Embedding,SPSA等接口 279 | - 量子神经网络,增加LinearGNN,ConvGNN,ConvGNN,QMLP,量子自然梯度,量子随机parameter-shift算法,DoublySGD算法等。 280 | 281 | 282 | Changed 283 | =========== 284 | 285 | - 经典神经网络,为BN1d,BN2d接口增加维度检查。 286 | 287 | Fixed 288 | =========== 289 | 290 | - 解决maxpooling参数检查的bug。 291 | - 解决[::-1]的切片bug。 292 | 293 | 294 | [v2.0.4] - 2022-09-20 295 | *************************** 296 | 297 | 298 | Added 299 | =========== 300 | 301 | - 经典神经网络,增加LayernormNd实现,支持多维数据layernorm计算。 302 | - 经典神经网络,增加CrossEntropyLoss以及NLL_Loss损失函数计算接口,支持1维~N维输入。 303 | - 量子神经网络,增加常用线路模板: HardwareEfficientAnsatz,StronglyEntanglingTemplate,BasicEntanglerTemplate。 304 | - 量子神经网络,增加计算量子比特子系统互信息的Mutal_info接口、Von Neumann 熵VB_Entropy、密度矩阵DensityMatrixFromQstate。 305 | - 量子神经网络,增加量子感知器算法例子QuantumNeuron,增加量子傅里叶级数算法例子。 306 | - 量子神经网络,增加支持多进程加速运行量子线路的接口QuantumLayerMultiProcess。 307 | 308 | Changed 309 | =========== 310 | 311 | - 经典神经网络,支持组卷积参数group,空洞卷积dilation_rate,任意数值padding作为一维卷积Conv1d、二维卷积Conv2d、反卷积ConvT2d的参数。 312 | - 在相同维度的数据跳过广播操作,减少不必要运行逻辑。 313 | 314 | Fixed 315 | =========== 316 | 317 | - 解决stack函数在部分参数下计算错误的问题。 318 | 319 | 320 | [v2.0.3] - 2022-07-15 321 | *************************** 322 | 323 | 324 | Added 325 | =========== 326 | 327 | - 增加支持stack,双向的循环神经网络接口: RNN, LSTM, GRU 328 | - 增加常用计算性能指标的接口: MSE,RMSE, MAE, R_Square, precision_recall_f1_2_score, precision_recall_f1_Multi_scoreprecision_recall_f1_N_score, auc_calculate 329 | - 增加量子核SVM的算法示例 330 | 331 | Changed 332 | =========== 333 | 334 | - 加快QTensor数据过多时候的print速度 335 | - Windows和linux下使用openmp加速运算。 336 | 337 | Fixed 338 | =========== 339 | 340 | - 解决部分python import方式无法导入的问题 341 | - 解决批归一化BN层重复计算的问题 342 | - 解决QTensor.reshape,transpose接口无法计算梯度的bug 343 | - 为tensor.power接口增加入参形状判断 344 | 345 | [v2.0.2] - 2022-05-15 346 | *************************** 347 | 348 | Added 349 | =========== 350 | 351 | - 增加topK, argtoK 352 | - 增加cumsum 353 | - 增加masked_fill 354 | - 增加triu,tril 355 | - 增加QGAN生成随机分布的示例 356 | 357 | Changed 358 | =========== 359 | 360 | - 支持高级切片索引和普通切片索引 361 | - matmul支持3D,4D张量运算 362 | - 修改HardSigmoid函数实现 363 | 364 | Fixed 365 | =========== 366 | 367 | - 解决卷积,批归一化,反卷积,池化层等层没有缓存内部变量,导致一次前传后多次反传时计算梯度的问题 368 | - 修正QLinear层的实现和示例 369 | - 解决MAC在conda环境中导入VQNet时候 Image not load的问题。 370 | 371 | 372 | 373 | 374 | [v2.0.1] - 2022-03-30 375 | *************************** 376 | 377 | 378 | Added 379 | =========== 380 | 381 | - 增加基本数据结构QTensor接口100余个,包括创建函数,逻辑函数,数学函数,矩阵操作。 382 | - 增加基本神经网络网络函数14个,包括卷积,反卷积,池化等。 383 | - 增加损失函数4个,包括MSE,BCE,CCE,SCE等。 384 | - 增加激活函数10个,包括ReLu,Sigmoid,ELU等。 385 | - 增加优化器6个,包括SGD,RMSPROP,ADAM等。 386 | - 增加机器学习示例: QVC,QDRL,Q-KMEANS,QUnet,HQCNN,VSQL,量子自编码器。 387 | - 增加量子机器学习层: QuantumLayer,NoiseQuantumLayer。 -------------------------------------------------------------------------------- /source/rst/FAQ.rst: -------------------------------------------------------------------------------- 1 | 常见问题 2 | ================ 3 | 4 | **问: VQNet有哪些特性** 5 | 6 | 答: VQNet是基于本源量子pyQPanda开发的量子机器学习工具集。VQNet提供了丰富、易用的经典神经网络计算模块接口,可以方便地进行机器学习的优化, 7 | 模型定义方式与主流机器学习框架一致,降低了用户学习成本。 8 | 同时,基于本源量子研发的高性能量子模拟器pyQPanda,VQNet在个人笔记本电脑上也能支持大数量量子比特的运算。最后,VQNet还有丰富的 :doc:`./qml_demo` 供大家参考和学习。 9 | 10 | **问: 如何使用VQNet进行量子机器学习模型的训练** 11 | 12 | 答: 量子机器学习算法中有一类是基于量子变分线路构建可微的量子机器学习模型。 13 | VQNet可以使用梯度下降法对这类量子机器学习模型进行训练。一般步骤如下: 首先在本地计算机上,用户可以通过pyQPanda构建虚拟机,并结合VQNet中提供的接口构建量子、量子经典混合模型 ``Module`` ; 其次,调用 ``Module`` 的 ``forward()`` 可按用户定义的运行方式进行量子线路模拟以及经典神经网络前向运算; 14 | 当调用 ``Module`` 的 ``backward()`` 用户构建的模型可以像PyTorch等经典机器学习框架一样进行自动微分,计算量子变分线路以及经典计算层中的参数梯度;最后结合优化器的 ``step()`` 功能进行参数的优化。 15 | 16 | 在VQNet中,我们使用 `parameter-shift `_ 计算量子变分线路的梯度。用户可使用 17 | VQNet提供的 :ref:`QuantumLayer_pq3` 下的接口已经封装了量子变分线路的自动微分,用户仅需按一定格式定义量子变分线路作为参数构建以上类即可。 18 | 19 | 在VQNet中,我们还可以使用基于自动微分的方法计算量子变分线路的梯度。用户可使用 :ref:`vqc_api` 中的接口构建可训练的线路,该线路不依赖pyQPanda,而是将线路中编码、逻辑门演化、测量拆分成可微分的算子,从而达到对其中参数梯度计算的功能。。 20 | 21 | 具体可参考本文档相关接口以及示例代码。 22 | 23 | **问: 在Windows中,安装VQNet遇到错误: “importError: DLL load failed while importing _core: 找不到指定的模块。”** 24 | 25 | 答: 用户在Windows上可能需要安装VC++ 运行时库。 26 | 可参考 https://learn.microsoft.com/en-us/cpp/windows/latest-supported-vc-redist?view=msvc-170 安装合适的运行库。 27 | 此外,VQNet当前仅支持python3.9, 3.10, 3.11 版本,故请确认你的python版本。 28 | 29 | **问: 如何调用本源量子云以及量子芯片进行计算** 30 | 31 | 答: 可以在量子线路模拟中使用本源量子的高性能计算机集群或真实的量子计算机,用云计算的方式替代本地量子线路模拟,请参考 https://qcloud.originqc.com.cn/zh。 32 | 在VQNet中,用户可使用 ``QuantumBatchAsyncQcloudLayer`` 构建变分量子线路模块,输入在本源官网上申请的API KEYS提交任务到真机运行。 33 | 34 | 35 | 36 | **问: 为什么我定义的模型参数在训练时候不更新** 37 | 38 | 答: 构建VQNet的模型需要保证其中所使用的所有模块是可微分。当模型某个模块无法计算梯度,则会导致该模块以及之前的模块无法使用链式法则计算梯度。 39 | 若用户自定义一个量子变分线路,请使用VQNet提供的 :ref:`QuantumLayer_pq3` 下的接口。对于经典机器学习模块,需要使用 :doc:`./QTensor` 以及 :doc:`./nn` 定义的接口,这些接口封装了梯度计算的函数,VQNet可以进行自动微分。 40 | 41 | 若用户想在 `Module` 中使用包含多个模块的列表作为子模块,请不要使用python自带的List,需要使用 pyvqnet.nn.module.ModuleList 代替 List。这样,子模块的训练参数可以被注册到整个模型中,可以进行自动微分训练。以下是例子: 42 | 43 | Example:: 44 | 45 | from pyvqnet.tensor import * 46 | from pyvqnet.nn import Module,Linear,ModuleList 47 | from pyvqnet.qnn import ProbsMeasure,QuantumLayer 48 | import pyqpanda as pq #请自行安装pyqpanda 49 | def pqctest (input,param,qubits,cubits,m_machine): 50 | circuit = pq.QCircuit() 51 | circuit.insert(pq.H(qubits[0])) 52 | circuit.insert(pq.H(qubits[1])) 53 | circuit.insert(pq.H(qubits[2])) 54 | circuit.insert(pq.H(qubits[3])) 55 | 56 | circuit.insert(pq.RZ(qubits[0],input[0])) 57 | circuit.insert(pq.RZ(qubits[1],input[1])) 58 | circuit.insert(pq.RZ(qubits[2],input[2])) 59 | circuit.insert(pq.RZ(qubits[3],input[3])) 60 | 61 | circuit.insert(pq.CNOT(qubits[0],qubits[1])) 62 | circuit.insert(pq.RZ(qubits[1],param[0])) 63 | circuit.insert(pq.CNOT(qubits[0],qubits[1])) 64 | 65 | circuit.insert(pq.CNOT(qubits[1],qubits[2])) 66 | circuit.insert(pq.RZ(qubits[2],param[1])) 67 | circuit.insert(pq.CNOT(qubits[1],qubits[2])) 68 | 69 | circuit.insert(pq.CNOT(qubits[2],qubits[3])) 70 | circuit.insert(pq.RZ(qubits[3],param[2])) 71 | circuit.insert(pq.CNOT(qubits[2],qubits[3])) 72 | #print(circuit) 73 | 74 | prog = pq.QProg() 75 | prog.insert(circuit) 76 | 77 | rlt_prob = ProbsMeasure([0,2],prog,m_machine,qubits) 78 | return rlt_prob 79 | 80 | 81 | class M(Module): 82 | def __init__(self): 83 | super(M, self).__init__() 84 | #应该使用ModuleList构建 85 | self.pqc2 = ModuleList([QuantumLayer(pqctest,3,"cpu",4,1), Linear(4,1) 86 | ]) 87 | #直接使用list 是无法保存pqc3中的参数的。 88 | #self.pqc3 = [QuantumLayer(pqctest,3,"cpu",4,1), Linear(4,1) 89 | #] 90 | def forward(self, x, *args, **kwargs): 91 | y = self.pqc2[0](x) + self.pqc2[1](x) 92 | return y 93 | 94 | mm = M() 95 | print(mm.state_dict().keys()) 96 | 97 | **问: 为什么原先的代码在2.0.7及以后版本无法运行** 98 | 99 | 答: 自v2.0.7版本中,我们为QTensor增加了不同数据类型,dtype属性,并参照pytorch对输入进行了限制。例如: Emedding层输入需要为kint64,CategoricalCrossEntropy, SoftmaxCrossEntropy, NLL_Loss, CrossEntropyLoss 的标签需要为kint64。 100 | 你可以使用 `astype()` 接口进行类型转化为指定数据类型,或使用对应的数据类型numpy数组初始化QTensor。 101 | 102 | **问: VQNet依赖torch么** 103 | 104 | 答: VQNet不依赖torch,也不自动安装torch。 105 | 106 | 使用以下功能需要自行安装torch>=2.4.0。自v2.15.0版本,我们支持使用 `torch >=2.4.0 `_ 作为计算后端,进行经典神经网络、量子变分线路、分布式等计算。 107 | 使用 ``pyvqnet.backends.set_backend("torch")`` 后,接口保持不变,但VQNet的 ``QTensor`` 的 ``data`` 成员变量均使用 ``torch.Tensor`` 储存数据, 108 | 并使用torch计算。 ``pyvqnet.nn.torch`` 以及 ``pyvqnet.qnn.vqc.torch`` 下的类继承于 ``torch.nn.Module`` ,可以构成 ``torch`` 模型。 -------------------------------------------------------------------------------- /source/rst/images/Barren_Plateau_mean.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/Barren_Plateau_mean.png -------------------------------------------------------------------------------- /source/rst/images/Barren_Plateau_variance.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/Barren_Plateau_variance.png -------------------------------------------------------------------------------- /source/rst/images/HQCNNAccuracy.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/HQCNNAccuracy.png -------------------------------------------------------------------------------- /source/rst/images/HQCNNLOSS.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/HQCNNLOSS.png -------------------------------------------------------------------------------- /source/rst/images/Kmeans.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/Kmeans.jpg -------------------------------------------------------------------------------- /source/rst/images/QAE_Quantum_Cir.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/QAE_Quantum_Cir.png -------------------------------------------------------------------------------- /source/rst/images/QMLP.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/QMLP.png -------------------------------------------------------------------------------- /source/rst/images/QP-acc.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/QP-acc.png -------------------------------------------------------------------------------- /source/rst/images/QP-cir.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/QP-cir.png -------------------------------------------------------------------------------- /source/rst/images/QP-data.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/QP-data.png -------------------------------------------------------------------------------- /source/rst/images/QP-pic.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/QP-pic.png -------------------------------------------------------------------------------- /source/rst/images/QTransferLearning_cir.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/QTransferLearning_cir.png -------------------------------------------------------------------------------- /source/rst/images/Qcnn_circuit.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/Qcnn_circuit.png -------------------------------------------------------------------------------- /source/rst/images/Unet.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/Unet.png -------------------------------------------------------------------------------- /source/rst/images/Unet_data_imshow.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/Unet_data_imshow.png -------------------------------------------------------------------------------- /source/rst/images/VQC-SVM.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/VQC-SVM.png -------------------------------------------------------------------------------- /source/rst/images/all_singles_doubles.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/all_singles_doubles.png -------------------------------------------------------------------------------- /source/rst/images/classic-quantum.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/classic-quantum.PNG -------------------------------------------------------------------------------- /source/rst/images/dropout_sin.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/dropout_sin.png -------------------------------------------------------------------------------- /source/rst/images/dsgd.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/dsgd.png -------------------------------------------------------------------------------- /source/rst/images/ep_1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/ep_1.png -------------------------------------------------------------------------------- /source/rst/images/ep_9.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/ep_9.png -------------------------------------------------------------------------------- /source/rst/images/eval_test.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/eval_test.png -------------------------------------------------------------------------------- /source/rst/images/express.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/express.png -------------------------------------------------------------------------------- /source/rst/images/f1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/f1.png -------------------------------------------------------------------------------- /source/rst/images/f2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/f2.png -------------------------------------------------------------------------------- /source/rst/images/f3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/f3.png -------------------------------------------------------------------------------- /source/rst/images/final_quantum_circuit.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/final_quantum_circuit.png -------------------------------------------------------------------------------- /source/rst/images/gbp_arch.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/gbp_arch.png -------------------------------------------------------------------------------- /source/rst/images/haar-fidelity.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/haar-fidelity.png -------------------------------------------------------------------------------- /source/rst/images/hqcnn_quantum_cir.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/hqcnn_quantum_cir.png -------------------------------------------------------------------------------- /source/rst/images/hqcnn_train_loss.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/hqcnn_train_loss.png -------------------------------------------------------------------------------- /source/rst/images/hqcnnarch.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/hqcnnarch.PNG -------------------------------------------------------------------------------- /source/rst/images/hqcnnmodel.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/hqcnnmodel.PNG -------------------------------------------------------------------------------- /source/rst/images/loss3d.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/loss3d.png -------------------------------------------------------------------------------- /source/rst/images/maxcut.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/maxcut.png -------------------------------------------------------------------------------- /source/rst/images/mnsit_data_examples.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/mnsit_data_examples.png -------------------------------------------------------------------------------- /source/rst/images/mpi_bug.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/mpi_bug.png -------------------------------------------------------------------------------- /source/rst/images/noise_1.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/noise_1.PNG -------------------------------------------------------------------------------- /source/rst/images/noise_2.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/noise_2.PNG -------------------------------------------------------------------------------- /source/rst/images/onnxsupport.csv: -------------------------------------------------------------------------------- 1 | operator,operator,operator 2 | ones,floor,nonzero 3 | ons_like,ceil,isfinite 4 | full,round,isinf 5 | full_like,sort,isnan 6 | zeros,argosrt,isneginf 7 | zeros_like,topK,isposinf 8 | arange,argtopK,logical_and 9 | linspace,add,logical_or 10 | logspace,sub,logical_not 11 | eye,mul,logical_xor 12 | randu,divide,greater 13 | randn,sums,greater_equal 14 | tiru,cumsum,less 15 | tril,mean,less_equal 16 | __getitem__,median,equal 17 | __setitem__,std,not_equal 18 | concatenate,var,Conv2D 19 | stack,matmul,Conv1D 20 | permute,reciprocal,ConvT2D 21 | transpose,sign,Linear 22 | tile,neg,Sigmoid 23 | squeeze,exp,Softplus 24 | unsqueeze,acos,Softsign 25 | swapaxis,asin,Softmax 26 | masked_fill,atan,HardSigmoid 27 | flatten,sin,ReLu 28 | reshape,cos,LeakyReLu 29 | flip,tan,ELU 30 | maximum,tanh,Tanh 31 | minimum,sinh,BatchNorm2d 32 | min,cosh,BatchNorm1d 33 | max,power,Dropout 34 | clip,abs,Embedding 35 | where,log,LayerNormNd 36 | ,sqrt,LayerNorm1d 37 | ,square,LayerNorm2d 38 | ,frobenius_norm,MaxPool1D 39 | ,log_softmax,MaxPool2D 40 | ,,AvgPool2D 41 | ,,AvgPool1D 42 | ,,GRU 43 | ,,LSTM 44 | ,,RNN 45 | -------------------------------------------------------------------------------- /source/rst/images/origin_circle.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/origin_circle.png -------------------------------------------------------------------------------- /source/rst/images/parallel_model.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/parallel_model.png -------------------------------------------------------------------------------- /source/rst/images/parallel_model_circuit.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/parallel_model_circuit.png -------------------------------------------------------------------------------- /source/rst/images/parallel_model_result.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/parallel_model_result.png -------------------------------------------------------------------------------- /source/rst/images/parallel_model_result_no_train.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/parallel_model_result_no_train.png -------------------------------------------------------------------------------- /source/rst/images/peft1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/peft1.png -------------------------------------------------------------------------------- /source/rst/images/pqccir1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/pqccir1.png -------------------------------------------------------------------------------- /source/rst/images/pqccir2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/pqccir2.png -------------------------------------------------------------------------------- /source/rst/images/pqcloss.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/pqcloss.png -------------------------------------------------------------------------------- /source/rst/images/qae_train_loss.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/qae_train_loss.png -------------------------------------------------------------------------------- /source/rst/images/qaoa_demo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/qaoa_demo.png -------------------------------------------------------------------------------- /source/rst/images/qcnn.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/qcnn.png -------------------------------------------------------------------------------- /source/rst/images/qcnn_cir.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/qcnn_cir.png -------------------------------------------------------------------------------- /source/rst/images/qcnn_structrue.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/qcnn_structrue.png -------------------------------------------------------------------------------- /source/rst/images/qcnn_transfer_learning_classical.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/qcnn_transfer_learning_classical.png -------------------------------------------------------------------------------- /source/rst/images/qcnn_transfer_learning_predict.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/qcnn_transfer_learning_predict.png -------------------------------------------------------------------------------- /source/rst/images/qcnn_vqnet.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/qcnn_vqnet.png -------------------------------------------------------------------------------- /source/rst/images/qcnn_vqnet_result.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/qcnn_vqnet_result.png -------------------------------------------------------------------------------- /source/rst/images/qdrl.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/qdrl.png -------------------------------------------------------------------------------- /source/rst/images/qdrl_accuracy.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/qdrl_accuracy.png -------------------------------------------------------------------------------- /source/rst/images/qdrl_for_simple.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/qdrl_for_simple.png -------------------------------------------------------------------------------- /source/rst/images/qgan-arch.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/qgan-arch.PNG -------------------------------------------------------------------------------- /source/rst/images/qgan-loss.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/qgan-loss.png -------------------------------------------------------------------------------- /source/rst/images/qgan-pdf.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/qgan-pdf.png -------------------------------------------------------------------------------- /source/rst/images/qiskit_eval_test.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/qiskit_eval_test.png -------------------------------------------------------------------------------- /source/rst/images/qiskit_hqcnn_train_loss.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/qiskit_hqcnn_train_loss.png -------------------------------------------------------------------------------- /source/rst/images/qlinear_cir.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/qlinear_cir.png -------------------------------------------------------------------------------- /source/rst/images/qng_all_cir.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/qng_all_cir.png -------------------------------------------------------------------------------- /source/rst/images/qng_subcir1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/qng_subcir1.png -------------------------------------------------------------------------------- /source/rst/images/qng_subcir2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/qng_subcir2.png -------------------------------------------------------------------------------- /source/rst/images/qng_vs_sgd.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/qng_vs_sgd.png -------------------------------------------------------------------------------- /source/rst/images/qsvd.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/qsvd.png -------------------------------------------------------------------------------- /source/rst/images/qsvd_algorithm.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/qsvd_algorithm.png -------------------------------------------------------------------------------- /source/rst/images/qsvm-arch.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/qsvm-arch.png -------------------------------------------------------------------------------- /source/rst/images/qsvm-kernel.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/qsvm-kernel.png -------------------------------------------------------------------------------- /source/rst/images/quanvo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/quanvo.png -------------------------------------------------------------------------------- /source/rst/images/qunet_cir.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/qunet_cir.png -------------------------------------------------------------------------------- /source/rst/images/qunet_eval_1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/qunet_eval_1.jpg -------------------------------------------------------------------------------- /source/rst/images/qunet_eval_2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/qunet_eval_2.jpg -------------------------------------------------------------------------------- /source/rst/images/qunet_eval_3.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/qunet_eval_3.jpg -------------------------------------------------------------------------------- /source/rst/images/qunet_quantum.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/qunet_quantum.png -------------------------------------------------------------------------------- /source/rst/images/qunet_train_loss.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/qunet_train_loss.png -------------------------------------------------------------------------------- /source/rst/images/qvc_accuracy.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/qvc_accuracy.png -------------------------------------------------------------------------------- /source/rst/images/qvc_circuit.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/qvc_circuit.png -------------------------------------------------------------------------------- /source/rst/images/resnet_onnx.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/resnet_onnx.png -------------------------------------------------------------------------------- /source/rst/images/result_QDRL.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/result_QDRL.gif -------------------------------------------------------------------------------- /source/rst/images/result_qcnn_small.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/result_qcnn_small.png -------------------------------------------------------------------------------- /source/rst/images/rotosolve.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/rotosolve.png -------------------------------------------------------------------------------- /source/rst/images/same_apis_from_tn.csv: -------------------------------------------------------------------------------- 1 | i,u3,phaseshift 2 | hadamard,cy,multirz 3 | t,cnot,sdg 4 | s,cr,tdg 5 | paulix,swap,controlledphaseshift 6 | pauliy,cswap,single_excitation 7 | pauliz,iswap,double_excitation 8 | x1,cz, 9 | rx,rxx, 10 | ry,ryy, 11 | rz,rzz, 12 | crx,rzx, 13 | cry,toffoli, 14 | crz,isingxx, 15 | p,isingyy, 16 | u1,isingzz, 17 | u2,isingxy, 18 | -------------------------------------------------------------------------------- /source/rst/images/same_apis_from_vqc.csv: -------------------------------------------------------------------------------- 1 | i,u3,phaseshift 2 | hadamard,cy,multirz 3 | t,cnot,sdg 4 | s,cr,tdg 5 | paulix,swap,controlledphaseshift 6 | pauliy,cswap,multicontrolledx 7 | pauliz,iswap,single_excitation 8 | x1,cz,double_excitation 9 | rx,rxx,vqc_to_originir_list 10 | ry,ryy,originir_to_vqc 11 | rz,rzz,model_summary 12 | crx,rzx,wrapper_single_qubit_op_fuse 13 | cry,toffoli,wrapper_commute_controlled 14 | crz,isingxx,wrapper_merge_rotations 15 | p,isingyy,wrapper_compile 16 | u1,isingzz, 17 | u2,isingxy, 18 | -------------------------------------------------------------------------------- /source/rst/images/single_qubit_model.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/single_qubit_model.png -------------------------------------------------------------------------------- /source/rst/images/single_qubit_model_circuit.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/single_qubit_model_circuit.png -------------------------------------------------------------------------------- /source/rst/images/single_qubit_model_result.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/single_qubit_model_result.png -------------------------------------------------------------------------------- /source/rst/images/single_qubit_model_result_no_train.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/single_qubit_model_result_no_train.png -------------------------------------------------------------------------------- /source/rst/images/stochastic_parameter-shift.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/stochastic_parameter-shift.png -------------------------------------------------------------------------------- /source/rst/images/vsql_0.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/vsql_0.png -------------------------------------------------------------------------------- /source/rst/images/vsql_1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/vsql_1.png -------------------------------------------------------------------------------- /source/rst/images/vsql_2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/vsql_2.png -------------------------------------------------------------------------------- /source/rst/images/vsql_3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/vsql_3.png -------------------------------------------------------------------------------- /source/rst/images/vsql_4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/vsql_4.png -------------------------------------------------------------------------------- /source/rst/images/vsql_5.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/vsql_5.png -------------------------------------------------------------------------------- /source/rst/images/vsql_6.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/vsql_6.png -------------------------------------------------------------------------------- /source/rst/images/vsql_7.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/vsql_7.png -------------------------------------------------------------------------------- /source/rst/images/vsql_8.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/vsql_8.png -------------------------------------------------------------------------------- /source/rst/images/vsql_cacc.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/vsql_cacc.PNG -------------------------------------------------------------------------------- /source/rst/images/vsql_closs.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/vsql_closs.PNG -------------------------------------------------------------------------------- /source/rst/images/vsql_model.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/vsql_model.PNG -------------------------------------------------------------------------------- /source/rst/images/vsql_qacc.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/vsql_qacc.PNG -------------------------------------------------------------------------------- /source/rst/images/vsql_qloss.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OriginQ/VQNET2.0-tutorial/3f1fbf5f8b8f93dd73ebc69ad86b37131a0ab0eb/source/rst/images/vsql_qloss.PNG -------------------------------------------------------------------------------- /source/rst/install.rst: -------------------------------------------------------------------------------- 1 | VQNet 安装步骤 2 | ================================== 3 | 4 | VQNet python包安装 5 | ---------------------------------- 6 | 7 | 我们提供了Linux, Windows, x86_64 OSX >=10.12, arm64 OSX>=13.0 上的python预编译包供安装,需要 **python3.9, 3.10, 3.11** 。 8 | 9 | 对于Windows, Linux系统,pyvqnet提供了基于Nvidia GPU对经典神经网络计算加速功能,当您的电脑的GPU是GTX10系列及其以后的型号,可使用pyvqnet的GPU功能运行模型。 10 | 11 | .. code-block:: 12 | 13 | pip install pyvqnet 14 | 15 | 或者: 16 | 17 | .. code-block:: 18 | 19 | pip install pyvqnet --index-url https://pypi.originqc.com.cn 20 | 21 | 如果您遇到网络问题导致无法下载,可尝试增加timeout。 22 | 23 | .. code-block:: 24 | 25 | pip install pyvqnet --index-url https://pypi.originqc.com.cn --default-timeout=100 26 | 27 | VQNet 测试安装成功 28 | ---------------------------------- 29 | 30 | .. code-block:: 31 | 32 | import pyvqnet 33 | from pyvqnet.tensor import * 34 | a = arange(1,25).reshape([2, 3, 4]) 35 | print(a) 36 | 37 | VQNet 测试GPU功能 38 | ---------------------------------- 39 | 40 | .. code-block:: 41 | 42 | from pyvqnet import DEV_GPU_0 43 | from pyvqnet.tensor import * 44 | a = ones([4,5],device = DEV_GPU_0) 45 | print(a) 46 | 47 | VQNet 的一个简单例子 48 | --------------------- 49 | 50 | 这里使用VQNet的经典神经网络模块以及量子模块完成一个机器学习模型的整体流程的例子介绍。该例子参考 `Data re-uploading for a universal quantum classifier `_ 51 | 。 52 | 量子机器学习中的量子计算模块一般有如下几个部分: 53 | 54 | (1)编码线路(Encoder),用于将经典数据编码到量子数据; 55 | (2)可变参数的量子线路(Ansatz),用于训练带参量子门中的参数; 56 | (3)测量模块(Measurement),用于检测测量值(也就是某个量子比特的量子态在某些轴上的投影)。 57 | 58 | 量子计算模块与经典神经网络的运算模块一样是可微分的,是量子经典神经网络混合模型的理论基础。 59 | VQNet支持将量子计算模块与经典计算模块(例如: 卷积,池化,全连接层,激活函数等)一起构成混合机器学习模型,提供多种优化算法优化参数。 60 | 61 | .. figure:: ./images/classic-quantum.PNG 62 | 63 | 在量子计算模块,VQNet支持使用本源量子高效的量子软件计算包 `pyqpanda `_ 进行量子模块构建。 64 | 使用pyQPanda提供的各种常用 `量子逻辑门函数接口 `_ , `量子线路接口 `_ , `量子虚拟机函数接口 `_ , `测量函数接口 `_,用户可以快速构建量子计算模块。 65 | 66 | 接下来的例子我们使用pyQPanda构建了一个量子计算模块。通过VQNet,该量子计算模块可以直接嵌入到混合机器学习模型中进行量子线路参数训练。 67 | 本例使用1个量子比特,使用了多个带参数的旋转门 `RZ`,`RY`,`RZ` 对输入x进行编码,并使用 `prob_run_dict()` 函数观测量子比特的概率测量结果作为输出。 68 | 69 | .. code-block:: 70 | 71 | import pyqpanda as pq 72 | def qdrl_circuit(input,weights,qlist,clist,machine): 73 | 74 | x1 = input.squeeze() 75 | param1 = weights.squeeze() 76 | #使用pyqpanda接口构建量子线路实例 77 | circult = pq.QCircuit() 78 | #使用pyqpanda接口在第一个量子比特上插入逻辑门RZ门,参数位x1[0] 79 | circult.insert(pq.RZ(qlist[0], x1[0])) 80 | #使用pyqpanda接口在第一个量子比特上插入逻辑门RY门,参数位x1[1] 81 | circult.insert(pq.RY(qlist[0], x1[1])) 82 | #使用pyqpanda接口在第一个量子比特上插入逻辑门RZ门,参数位x1[2] 83 | circult.insert(pq.RZ(qlist[0], x1[2])) 84 | #使用pyqpanda接口在第一个量子比特上插入逻辑门RZ门,参数位param1[0] 85 | circult.insert(pq.RZ(qlist[0], param1[0])) 86 | #使用pyqpanda接口在第一个量子比特上插入逻辑门RY门,参数位param1[1] 87 | circult.insert(pq.RY(qlist[0], param1[1])) 88 | #使用pyqpanda接口在第一个量子比特上插入逻辑门RZ门,参数位param1[2] 89 | circult.insert(pq.RZ(qlist[0], param1[2])) 90 | #使用pyqpanda接口在第一个量子比特上插入逻辑门RZ门,参数位x1[0] 91 | circult.insert(pq.RZ(qlist[0], x1[0])) 92 | #使用pyqpanda接口在第一个量子比特上插入逻辑门RY门,参数位x1[1] 93 | circult.insert(pq.RY(qlist[0], x1[1])) 94 | #使用pyqpanda接口在第一个量子比特上插入逻辑门RZ门,参数位x1[2] 95 | circult.insert(pq.RZ(qlist[0], x1[2])) 96 | #使用pyqpanda接口在第一个量子比特上插入逻辑门RZ门,参数位param1[3] 97 | circult.insert(pq.RZ(qlist[0], param1[3])) 98 | #使用pyqpanda接口在第一个量子比特上插入逻辑门RY门,参数位param1[4] 99 | circult.insert(pq.RY(qlist[0], param1[4])) 100 | #使用pyqpanda接口在第一个量子比特上插入逻辑门RZ门,参数位param1[5] 101 | circult.insert(pq.RZ(qlist[0], param1[5])) 102 | #使用pyqpanda接口在第一个量子比特上插入逻辑门RZ门,参数位x1[0] 103 | circult.insert(pq.RZ(qlist[0], x1[0])) 104 | #使用pyqpanda接口在第一个量子比特上插入逻辑门RY门,参数位x1[1] 105 | circult.insert(pq.RY(qlist[0], x1[1])) 106 | #使用pyqpanda接口在第一个量子比特上插入逻辑门RZ门,参数位x1[2] 107 | circult.insert(pq.RZ(qlist[0], x1[2])) 108 | #使用pyqpanda接口在第一个量子比特上插入逻辑门RZ门,参数位param1[6] 109 | circult.insert(pq.RZ(qlist[0], param1[6])) 110 | #使用pyqpanda接口在第一个量子比特上插入逻辑门RY门,参数位param1[7] 111 | circult.insert(pq.RY(qlist[0], param1[7])) 112 | #使用pyqpanda接口在第一个量子比特上插入逻辑门RZ门,参数位param1[8] 113 | circult.insert(pq.RZ(qlist[0], param1[8])) 114 | #构建量子程序 115 | prog = pq.QProg() 116 | prog.insert(circult) 117 | #获取概率测量值 118 | prob = machine.prob_run_dict(prog, qlist, -1) 119 | prob = list(prob.values()) 120 | return prob 121 | 122 | 本例子中机器学习的任务是对随机生成的数据根据进行二分类,其中下图是该数据样例,零为圆点,半径为1以内红色的二维点为一类,蓝色的点为另一类。 123 | 124 | .. figure:: ./images/origin_circle.png 125 | 126 | 训练测试代码流程 127 | 128 | .. code-block:: 129 | 130 | #导入必须的库和函数 131 | from pyvqnet.qnn.qdrl.vqnet_model import qdrl_circuit 132 | from pyvqnet.qnn.quantumlayer import QuantumLayer 133 | from pyvqnet.optim import adam 134 | from pyvqnet.nn.loss import CategoricalCrossEntropy 135 | from pyvqnet.tensor import QTensor 136 | import numpy as np 137 | from pyvqnet.nn.module import Module 138 | 139 | 140 | 定义模型Model,其中 `__init__` 函数定义内部各个神经网络模块以及量子模块,`forward` 函数定义前传函数。`QuantumLayer` 为封装量子计算的抽象类。 141 | 您只需将刚才定义的量子计算函数 `qdrl_circuit`,待训练参数个数 `param_num` ,运行后端配置 `"cpu"` , 量子比特数 `qbit_num` 输入参数,该类就在 `VQNet` 中自动计算参数梯度。 142 | 143 | .. code-block:: 144 | 145 | #待训练参数个数 146 | param_num = 9 147 | #量子计算模块量子比特数 148 | qbit_num = 1 149 | #定义一个继承于Module的机器学习模型类 150 | class Model(Module): 151 | def __init__(self): 152 | super(Model, self).__init__() 153 | #使用QuantumLayer类,可以把带训练参数的量子线路纳入VQNet的自动微分的训练流程中 154 | self.pqc = QuantumLayer(qdrl_circuit,param_num,"cpu",qbit_num) 155 | #定义模型前向函数 156 | def forward(self, x): 157 | x = self.pqc(x) 158 | return x 159 | 160 | 定义一些训练模型需要的函数 161 | 162 | .. code-block:: 163 | 164 | # 随机产生待训练数据的函数 165 | def circle(samples:int, rads = np.sqrt(2/np.pi)) : 166 | data_x, data_y = [], [] 167 | for i in range(samples): 168 | x = 2*np.random.rand(2) - 1 169 | y = [0,1] 170 | if np.linalg.norm(x) < rads: 171 | y = [1,0] 172 | data_x.append(x) 173 | data_y.append(y) 174 | return np.array(data_x,dtype=np.float32), np.array(data_y,np.int64) 175 | 176 | # 数据载入函数 177 | def get_minibatch_data(x_data, label, batch_size): 178 | for i in range(0,x_data.shape[0]-batch_size+1,batch_size): 179 | idxs = slice(i, i + batch_size) 180 | yield x_data[idxs], label[idxs] 181 | 182 | #计算准确率的函数 183 | def get_score(pred, label): 184 | pred, label = np.array(pred.data), np.array(label.data) 185 | pred = np.argmax(pred,axis=1) 186 | score = np.argmax(label,1) 187 | score = np.sum(pred == score) 188 | return score 189 | 190 | VQNet遵循机器学习一般的训练测试流程: 迭代进行载入数据,前传计算,损失函数计算,反向计算,更新参数的操作。 191 | 192 | .. code-block:: 193 | 194 | #实例化定义的模型 195 | model = Model() 196 | #定义一个优化器,这里用的是Adam 197 | optimizer = adam.Adam(model.parameters(),lr =0.6) 198 | #定义一个损失函数,这里用的交叉熵损失函数 199 | Closs = CategoricalCrossEntropy() 200 | 201 | 训练模型部分的函数 202 | 203 | .. code-block:: 204 | 205 | def train(): 206 | 207 | # 随机产生待训练数据 208 | x_train, y_train = circle(500) 209 | x_train = np.hstack((x_train, np.zeros((x_train.shape[0], 1),dtype=np.float32))) 210 | # 定义每个批次训练的数据个数 211 | batch_size = 32 212 | # 最大训练迭代次数 213 | epoch = 10 214 | print("start training...........") 215 | for i in range(epoch): 216 | model.train() 217 | accuracy = 0 218 | count = 0 219 | loss = 0 220 | for data, label in get_minibatch_data(x_train, y_train,batch_size): 221 | # 优化器中缓存梯度清零 222 | optimizer.zero_grad() 223 | # 模型前向计算 224 | output = model(data) 225 | # 损失函数计算 226 | losss = Closs(label, output) 227 | # 损失反向传播 228 | losss.backward() 229 | # 优化器参数更新 230 | optimizer._step() 231 | # 计算准确率等指标 232 | accuracy += get_score(output,label) 233 | 234 | loss += losss.item() 235 | count += batch_size 236 | 237 | print(f"epoch:{i}, train_accuracy:{accuracy/count}") 238 | print(f"epoch:{i}, train_loss:{loss/count}\n") 239 | 240 | 验证模型部分的函数 241 | 242 | .. code-block:: 243 | 244 | def test(): 245 | 246 | batch_size = 1 247 | model.eval() 248 | print("start eval...................") 249 | xtest, y_test = circle(500) 250 | test_accuracy = 0 251 | count = 0 252 | x_test = np.hstack((xtest, np.zeros((xtest.shape[0], 1),dtype=np.float32))) 253 | 254 | for test_data, test_label in get_minibatch_data(x_test,y_test, batch_size): 255 | 256 | test_data, test_label = QTensor(test_data),QTensor(test_label) 257 | output = model(test_data) 258 | test_accuracy += get_score(output, test_label) 259 | count += batch_size 260 | 261 | print(f"test_accuracy:{test_accuracy/count}") 262 | 263 | 训练测试结果图: 264 | 265 | .. code-block:: 266 | 267 | start training........... 268 | epoch:0, train_accuracy:0.6145833333333334 269 | epoch:0, train_loss:0.020432369535168013 270 | 271 | epoch:1, train_accuracy:0.6854166666666667 272 | epoch:1, train_loss:0.01872217481335004 273 | 274 | epoch:2, train_accuracy:0.8104166666666667 275 | epoch:2, train_loss:0.016634768371780715 276 | 277 | epoch:3, train_accuracy:0.7479166666666667 278 | epoch:3, train_loss:0.016975031544764835 279 | 280 | epoch:4, train_accuracy:0.7875 281 | epoch:4, train_loss:0.016502128106852372 282 | 283 | epoch:5, train_accuracy:0.8083333333333333 284 | epoch:5, train_loss:0.0163204787299037 285 | 286 | epoch:6, train_accuracy:0.8083333333333333 287 | epoch:6, train_loss:0.01634311651190122 288 | 289 | epoch:7, train_loss:0.016330583145221074 290 | 291 | epoch:8, train_accuracy:0.8125 292 | epoch:8, train_loss:0.01629052646458149 293 | 294 | epoch:9, train_accuracy:0.8083333333333333 295 | epoch:9, train_loss:0.016270687493185203 296 | 297 | start eval................... 298 | test_accuracy:0.826 299 | 300 | .. figure:: ./images/qdrl_for_simple.png 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308 | -------------------------------------------------------------------------------- /source/rst/llm.rst: -------------------------------------------------------------------------------- 1 | .. _llm: 2 | 3 | 量子大模型微调示例 4 | *********************************** 5 | 6 | 近些年随着大模型的普及,以及大模型规模的逐渐增加,导致训练大规模的量子机器学习模型会导致训练成本显著增加,为了减少大模型在微调过程中所需要的训练资源, 7 | 一些大模型微调方法被提出,不再对大模型全参数进行微调,而是通过提出的微调方法对少量的参数进行训练,从而使大模型在下游任务中依旧能取得不弱于全参数微调的效果, 8 | 而基于量子线路来进行微调的方式尚未得到普及。 9 | 10 | ``VQNet`` 通过与 ``Llama factory``, ``peft`` 结合, 实现基于量子线路来进行大模型微调任务。 11 | 12 | 量子大模型微调依赖包安装 13 | ------------------------- 14 | 15 | 该模块介绍在使用量子线路用于大模型微调中, 如何去对所需依赖包进行安装。 16 | 17 | 18 | 使用量子大模型微调, 主要需要 ``quantum-llm`` 和 ``pyvqnet`` 两个包即可, ``pyvqnet`` 版本要求 ``2.15.0`` 或者以上即可。 19 | 20 | 21 | 首先介绍 ``quantum-llm`` 库的安装 22 | 23 | .. code-block:: 24 | 25 | git clone https://gitee.com/craftsman_lei/quantum-llm.git 26 | 27 | 28 | 随后根据 ``quantum-llm`` 中 ``README.md`` 文档中内容完成其他依赖库以及文件安装 29 | 30 | .. code-block:: 31 | 32 | # 下载其他依赖库 33 | pip install -r requirements.txt 34 | 35 | # 安装peft_vqc 36 | cd peft_vqc && pip install -e . 37 | 38 | 完成 ``quantum-llm`` 库以及依赖库安装后,则对 ``pyvqnet`` 进行安装 39 | 40 | .. code-block:: 41 | 42 | # 安装VQNet 43 | pip install pyvqnet # pyvqnet>=2.15.0 44 | 45 | 46 | 量子大模型微调训练步骤 47 | ------------------------- 48 | 49 | 完成需求包安装后, 可以参考文件目录 ``/quantum-llm/examples/qlora_single_gpu/`` 下 ``train.sh`` 等脚本, 根据脚本指定训练基准模型,微调模块选择,微调模块输出路径等参数. 50 | 51 | 下载 Qwen2.5-0.5B 模型可在网址 https://huggingface.co/Qwen/Qwen2.5-0.5B?clone=true 上下载, 其他模型一样, 若无法下载,则可以针对网址上文件单一进行下载后使用: 52 | 53 | .. code-block:: 54 | 55 | # 下载Qwen2.5-0.5B 56 | git clone https://huggingface.co/Qwen/Qwen2.5-0.5B 57 | 58 | 59 | ``train.sh`` 脚本样例如下,确定基准模型、数据集、输出的路径等参数信息, 其中 ``model_name_or_path`` 放入指定模型,如果不能访问,则自行下载基准模型后,放入基准模型的绝对路径。 60 | 61 | .. note:: 62 | ``train.sh`` ``eval.sh`` ``cli.sh`` 等脚本文件均在 ``/quantum-llm/examples/qlora_single_gpu/`` 目录下执行 63 | 64 | .. code-block:: 65 | 66 | #!/bin/bash 67 | 68 | CUDA_VISIBLE_DEVICES=1 python ../../src/train_bash.py \ 69 | --stage sft \ 70 | --model_name_or_path /下载路径/Qwen2.5-0.5B/ \ 71 | --dataset alpaca_gpt4_en \ 72 | --tokenized_path ../../data/tokenized/alpaca_gpt4_en/ \ 73 | --dataset_dir ../../data \ 74 | --template qwen \ 75 | --finetuning_type vqc \ 76 | --lora_target q_proj,v_proj \ 77 | --output_dir ../../saves/Qwen2.5-0.5B/vqc/alpaca_gpt4_en \ 78 | --overwrite_cache \ 79 | --overwrite_output_dir \ 80 | --cutoff_len 1024 \ 81 | --preprocessing_num_workers 16 \ 82 | --per_device_train_batch_size 1 \ 83 | --per_device_eval_batch_size 1 \ 84 | --gradient_accumulation_steps 8 \ 85 | --lr_scheduler_type cosine \ 86 | --logging_steps 10 \ 87 | --warmup_steps 20 \ 88 | --save_steps 100 \ 89 | --eval_steps 100 \ 90 | --evaluation_strategy steps \ 91 | --load_best_model_at_end \ 92 | --learning_rate 5e-5 \ 93 | --num_train_epochs 3.0 \ 94 | --max_samples 1000 \ 95 | --val_size 0.1 \ 96 | --plot_loss \ 97 | --fp16 \ 98 | --do-train \ 99 | 100 | # 在命令行执行 101 | sh train.sh 102 | 103 | 在量子大模型微调模块中, 相较经典的大模型微调模块, 添加了三种额外的微调方式, 分别为: 104 | 105 | ``vqc`` : 基于VQNet实现的vqc微调模块 106 | 107 | ``quanTA`` : 量子张量分解模块 108 | 109 | ``tq`` : 基于torch quantum实现的vqc模块 110 | 111 | 上述的 ``train.sh`` 样例中是 ``vqc`` 模块微调的脚本样例, 若使用另外两种微调模块则将 ``finetuning_type`` 改为 ``quanTA`` , ``tq`` 即可,将三个模块实验结果记录并绘图, 结果如下: 112 | 113 | .. image:: ./images/peft1.png 114 | :width: 600 px 115 | :align: center 116 | 117 | | 118 | 119 | 上图则是基于 ``Qwen2.5-0.5B`` 基准模型在数据集 ``alpaca_gpt4_en`` 下的训练结果, 其中, 可以观察到, 基于VQNet的 ``vqc`` 模块取得了最好的损失收敛效果,以此证明了基于量子线路来做大模型微调任务的有效性。 120 | 121 | 122 | 通过 ``train.sh`` 训练脚本,可以将微调训练后的模块参数通过 ``--output_dir`` 参数保存到指定目录下, 123 | 随后通过同样目录 ``/quantum-llm/examples/qlora_single_gpu/`` 下的 ``eval.sh`` 脚本进行评估, 脚本内容如下: 124 | 125 | .. code-block:: 126 | 127 | #!/bin/bash 128 | 129 | CUDA_VISIBLE_DEVICES=1 python ../../src/evaluate.py \ 130 | --model_name_or_path /下载路径/Qwen2.5-0.5B/ \ 131 | --template qwen \ 132 | --finetuning_type vqc \ 133 | --task cmmlu \ 134 | --task_dir ../../evaluation/ \ 135 | --adapter_name_or_path ../../saves/Qwen2.5-0.5B/vqc/alpaca_gpt4_en \ 136 | 137 | # 在命令行执行 138 | sh eval.sh 139 | 140 | 通过 ``--model_name_or_path`` 指定基准模型路径, 以及根据 ``--adapter_name_or_path`` 加载已经训练好的模块来在相关任务上进行评估, ``--task`` 参数可取 ``cmmlu`` ``ceval`` ``mmlu`` 进行评估。 141 | 142 | 随后通过调用 ``cli_demo.py`` 文件来进行问答,同样根据当前目录下的 ``cli.sh`` 脚本执行,脚本内容如下: 143 | 144 | .. code-block:: 145 | 146 | #!/bin/bash 147 | 148 | CUDA_VISIBLE_DEVICES=1 python ../../src/cli_demo.py \ 149 | --model_name_or_path /下载路径/Qwen2.5-0.5B/ \ 150 | --template qwen \ 151 | --finetuning_type vqc \ 152 | --adapter_name_or_path ../../saves/Qwen2.5-0.5B/vqc/alpaca_gpt4_en \ 153 | --max_new_tokens 1024 154 | 155 | 156 | # 在命令行执行 157 | sh cli.sh 158 | 159 | 更多相关参数具体介绍 160 | ------------------------- 161 | 162 | ============================== =================================================================== 163 | 微调模块参数介绍 164 | ------------------------------------------------------------------------------------------------------ 165 | 参数名 详细介绍 166 | ============================== =================================================================== 167 | stage 确定大模型训练模式, pt为预训练, sft为微调阶段, 实验为sft. 168 | model_name_or_path 选择基准模型的路径. 169 | dataset 选择数据集, 如identity, alpaca_gpt4_zh等. 170 | tokenized_path 选择数据集tokenized路径. 171 | dataset_dir 选择数据集路径. 172 | template 模型模板类型, 如llama3等. 173 | finetuning_type 指定微调方法, 如lora, tq, vqc, quanTA. 174 | lora_target 作用模块为q_proj,v_proj 175 | output_dir 微调模块保存路径 176 | overwrite_cache 是否覆盖缓存的训练集和评估集 177 | overwrite_output_dir 是否覆盖输出目录中已存在的文件 178 | cutoff_len 指定处理数据时的截断长度 179 | preprocessing_num_workers 指定预处理数据时使用的工作进程数量 180 | per_device_train_batch_size 每个gpu的批处理大小, 训练参数 181 | per_device_eval_batch_size 评估时批次,训练参数 182 | gradient_accumulation_steps 梯度累计的步数,训练参数 183 | lr_scheduler_type 学习率调度器,训练参数 184 | logging_steps 打印间隔 185 | warmup_steps 预热步数 186 | save_steps 模型保存间隔 187 | eval_steps 评估保存间隔 188 | evaluation_strategy 评估策略,这里设置为按步骤评估 189 | load_best_model_at_end 训练结束时加载表现最好的模型 190 | learning_rate 学习率,训练参数 191 | num_train_epochs 需要执行的训练轮数,训练参数 192 | max_samples 训练最大样本数 193 | val_size 验证集大小 194 | plot_loss 是否保存训练损失曲线 195 | fp16 是否使用fp16混合精度训练, 在vqc模块使用float32 196 | do-train 是否指定是训练任务 197 | adapter_name_or_path 选择训练结束后生成文件路径 198 | task 选择任务, 目前支持ceval, cmmlu, mmlu 199 | task_dir 指定任务路径 200 | q_d 指定quanTA模块的张量分解数量, 默认为4 201 | per_dim_features 指定quanTA模块的张量分解特征数, 默认为[16,8,4,2] 202 | ============================== =================================================================== 203 | -------------------------------------------------------------------------------- /source/rst/qnn.rst: -------------------------------------------------------------------------------- 1 | 使用pyqpanda2量子机器学习模块 2 | ################################# 3 | 4 | .. warning:: 5 | 6 | 以下接口的量子计算部分使用pyqpanda2 https://pyqpanda-toturial.readthedocs.io/zh/latest/。 7 | 8 | 您需要自行安装pyqpanda2, `pip install pyqpanda` 9 | 10 | 量子计算层 11 | *********************************** 12 | 13 | .. _QuantumLayer: 14 | 15 | QuantumLayer 16 | ============================ 17 | 18 | QuantumLayer是一个支持量子含参线路作为参数的自动求导模块的封装类。用户定义一个函数作为参数 ``qprog_with_measure`` ,该函数需要包含pyqpanda2定义的量子线路:一般包含量子线路的编码线路,演化线路和测量操作。 19 | 该类可以嵌入量子经典混合机器学习模型,通过经典的梯度下降法,使得量子经典混合模型的目标函数或损失函数最小。 20 | 用户可通过参数 ``diff_method`` 指定 ``QuantumLayer`` 层中量子线路参数的梯度计算方式, ``QuantumLayer`` 当前支持有限差分法 ``finite_diff`` 以及 ``parameter-shift`` 方法。 21 | 22 | 有限差分法是估算函数梯度最传统和最常用的数值方法之一。主要思想是用差分代替偏导数: 23 | 24 | .. math:: 25 | 26 | f^{\prime}(x)=\lim _{h \rightarrow 0} \frac{f(x+h)-f(x)}{h} 27 | 28 | 29 | 若使用 ``parameter-shift`` 方法,我们使用如下目标函数: 30 | 31 | .. math:: O(\theta)=\left\langle 0\left|U^{\dagger}(\theta) H U(\theta)\right| 0\right\rangle 32 | 33 | 理论上可以通过 ``parameter-shift`` 这一更精确的方法计算量子线路中参数对哈密顿量的梯度: 34 | 35 | .. math:: 36 | 37 | \nabla O(\theta)= 38 | \frac{1}{2}\left[O\left(\theta+\frac{\pi}{2}\right)-O\left(\theta-\frac{\pi}{2}\right)\right] 39 | 40 | .. py:class:: pyvqnet.qnn.quantumlayer.QuantumLayer(qprog_with_measure,para_num,machine_type_or_cloud_token,num_of_qubits:int,num_of_cbits:int = 1,diff_method:str = "parameter_shift",delta:float = 0.01,dtype=None,name="") 41 | 42 | 变分量子层的抽象计算模块。对一个参数化的量子线路进行仿真,得到测量结果。该变分量子层继承了VQNet框架的梯度计算模块,可以计算线路参数的梯度,训练变分量子线路模型或将变分量子线路嵌入混合量子和经典模型。 43 | 44 | :param qprog_with_measure: 用pyqpanda2构建的量子线路运行和测量函数。 45 | :param para_num: `int` - 参数个数。 46 | :param machine_type_or_cloud_token: qpanda量子虚拟机类型 "CPU"。 47 | :param num_of_qubits: 量子比特数。 48 | :param num_of_cbits: 经典比特数,默认为1。 49 | :param diff_method: 求解量子线路参数梯度的方法,“参数位移”或“有限差分”,默认参数偏移。 50 | :param delta: 有限差分计算梯度时的 \delta。 51 | :param dtype: 参数的数据类型,defaults:None,使用默认数据类型:kfloat32,代表32位浮点数。 52 | :param name: 这个模块的名字, 默认为""。 53 | 54 | :return: 一个可以计算量子线路的模块。 55 | 56 | .. note:: 57 | qprog_with_measure是pyqpanda2中定义的量子线路函数 :https://pyqpanda-toturial.readthedocs.io/zh/latest/QCircuit.html。 58 | 59 | 此函数必须包含以下参数作为函数入参(即使某个参数未实际使用),否则无法在QuantumLayer中正常运行。 60 | 61 | qprog_with_measure (input,param,qubits,cbits,machine) 62 | 63 | `input`: 输入一维经典数据。如果没有输入可以输入 None。 64 | 65 | `param`: 输入一维的变分量子线路的待训练参数。 66 | 67 | `qubits`: 该QuantumLayer分配的量子比特,类型为pyQpanda.Qubits。 68 | 69 | `cbits`: 由QuantumLayer分配的经典比特,用来辅助测量函数,类型为 pyQpanda.ClassicalCondition。如果线路不使用cbits,也应保留此参数。 70 | 71 | `machine`: 由QuantumLayer创建的模拟器,例如CPUQVM,GPUQVM,QCloud等。 72 | 73 | 使用QuantumLayer的 `m_para` 属性获取变分量子线路的训练参数。该参数为QTensor类,可使用to_numpy()接口转化为numpy数组。 74 | 75 | .. note:: 76 | 77 | 该类具有别名 `QpandaQCircuitVQCLayer` 。 78 | 79 | .. note:: 80 | 81 | 该类计算梯度需要额外使用pyqpanda进行线路计算个数与参数个数、数据个数、数据维度的乘积线性相关。 82 | 83 | Example:: 84 | 85 | import pyqpanda as pq 86 | from pyvqnet.qnn.measure import ProbsMeasure 87 | from pyvqnet.qnn.quantumlayer import QuantumLayer 88 | import numpy as np 89 | from pyvqnet.tensor import QTensor 90 | def pqctest (input,param,qubits,cbits,machine): 91 | circuit = pq.QCircuit() 92 | circuit.insert(pq.H(qubits[0])) 93 | circuit.insert(pq.H(qubits[1])) 94 | circuit.insert(pq.H(qubits[2])) 95 | circuit.insert(pq.H(qubits[3])) 96 | 97 | circuit.insert(pq.RZ(qubits[0],input[0])) 98 | circuit.insert(pq.RZ(qubits[1],input[1])) 99 | circuit.insert(pq.RZ(qubits[2],input[2])) 100 | circuit.insert(pq.RZ(qubits[3],input[3])) 101 | 102 | circuit.insert(pq.CNOT(qubits[0],qubits[1])) 103 | circuit.insert(pq.RZ(qubits[1],param[0])) 104 | circuit.insert(pq.CNOT(qubits[0],qubits[1])) 105 | 106 | circuit.insert(pq.CNOT(qubits[1],qubits[2])) 107 | circuit.insert(pq.RZ(qubits[2],param[1])) 108 | circuit.insert(pq.CNOT(qubits[1],qubits[2])) 109 | 110 | circuit.insert(pq.CNOT(qubits[2],qubits[3])) 111 | circuit.insert(pq.RZ(qubits[3],param[2])) 112 | circuit.insert(pq.CNOT(qubits[2],qubits[3])) 113 | 114 | prog = pq.QProg() 115 | prog.insert(circuit) 116 | # pauli_dict = {'Z0 X1':10,'Y2':-0.543} 117 | rlt_prob = ProbsMeasure([0,2],prog,machine,qubits) 118 | return rlt_prob 119 | 120 | pqc = QuantumLayer(pqctest,3,"CPU",4,1) 121 | #classic data as input 122 | input = QTensor([[1,2,3,4],[40,22,2,3],[33,3,25,2.0]] ) 123 | #forward circuits 124 | rlt = pqc(input) 125 | grad = QTensor(np.ones(rlt.data.shape)*1000) 126 | #backward circuits 127 | rlt.backward(grad) 128 | print(rlt) 129 | # [ 130 | # [0.2500000, 0.2500000, 0.2500000, 0.2500000], 131 | # [0.2500000, 0.2500000, 0.2500000, 0.2500000], 132 | # [0.2500000, 0.2500000, 0.2500000, 0.2500000] 133 | # ] 134 | 135 | 如果使用GPU,参考下面的例子: 136 | 137 | 138 | Example:: 139 | 140 | import pyqpanda as pq 141 | from pyvqnet.qnn.measure import ProbsMeasure 142 | from pyvqnet.qnn.quantumlayer import QuantumLayer 143 | import numpy as np 144 | from pyvqnet.tensor import QTensor,DEV_GPU_0 145 | def pqctest (input,param,qubits,cbits,machine): 146 | circuit = pq.QCircuit() 147 | circuit.insert(pq.H(qubits[0])) 148 | circuit.insert(pq.H(qubits[1])) 149 | circuit.insert(pq.H(qubits[2])) 150 | circuit.insert(pq.H(qubits[3])) 151 | 152 | circuit.insert(pq.RZ(qubits[0],input[0])) 153 | circuit.insert(pq.RZ(qubits[1],input[1])) 154 | circuit.insert(pq.RZ(qubits[2],input[2])) 155 | circuit.insert(pq.RZ(qubits[3],input[3])) 156 | 157 | circuit.insert(pq.CNOT(qubits[0],qubits[1])) 158 | circuit.insert(pq.RZ(qubits[1],param[0])) 159 | circuit.insert(pq.CNOT(qubits[0],qubits[1])) 160 | 161 | circuit.insert(pq.CNOT(qubits[1],qubits[2])) 162 | circuit.insert(pq.RZ(qubits[2],param[1])) 163 | circuit.insert(pq.CNOT(qubits[1],qubits[2])) 164 | 165 | circuit.insert(pq.CNOT(qubits[2],qubits[3])) 166 | circuit.insert(pq.RZ(qubits[3],param[2])) 167 | circuit.insert(pq.CNOT(qubits[2],qubits[3])) 168 | 169 | prog = pq.QProg() 170 | prog.insert(circuit) 171 | # pauli_dict = {'Z0 X1':10,'Y2':-0.543} 172 | rlt_prob = ProbsMeasure([0,2],prog,machine,qubits) 173 | return rlt_prob 174 | 175 | #这里的"CPU" 指的是qpanda量子计算模拟器使用CPU,跟pyvqnet是否使用GPU无关。 176 | pqc = QuantumLayer(pqctest,3,"CPU",4,1) 177 | #这里使用toGPU将QuantumLayer 移动到GPU上 178 | pqc.toGPU() 179 | #classic data as input 180 | input = QTensor([[1,2,3,4],[40,22,2,3],[33,3,25,2.0]] ) 181 | input.toGPU() 182 | #forward circuits 183 | rlt = pqc(input) 184 | grad = QTensor(np.ones(rlt.data.shape)*1000,device=DEV_GPU_0) 185 | #backward circuits 186 | rlt.backward(grad) 187 | print(rlt) 188 | 189 | 190 | QpandaQCircuitVQCLayerLite 191 | ============================ 192 | 193 | 如您更加熟悉pyqpanda2语法,可以使用该接口QpandaQCircuitVQCLayerLite,自定义量子比特 ``qubits`` ,经典比特 ``cbits`` ,后端模拟器 ``machine`` 加入QpandaQCircuitVQCLayerLite的参数 ``qprog_with_measure`` 函数中。 194 | 195 | .. py:class:: pyvqnet.qnn.quantumlayer.QpandaQCircuitVQCLayerLite(qprog_with_measure,para_num,diff_method:str = "parameter_shift",delta:float = 0.01,dtype=None,name="") 196 | 197 | 变分量子层的抽象计算模块。对一个参数化的量子线路使用pyqpanda2进行仿真,得到测量结果。该变分量子层继承了VQNet框架的梯度计算模块,可以使用参数漂移法等计算线路参数的梯度,训练变分量子线路模型或将变分量子线路嵌入混合量子和经典模型。 198 | 199 | :param qprog_with_measure: 用pyQPand构建的量子线路运行和测量函数。 200 | :param para_num: `int` - 参数个数。 201 | :param diff_method: 求解量子线路参数梯度的方法,“参数位移”或“有限差分”,默认参数偏移。 202 | :param delta: 有限差分计算梯度时的 \delta。 203 | :param dtype: 参数的数据类型,defaults:None,使用默认数据类型:kfloat32,代表32位浮点数。 204 | :param name: 这个模块的名字, 默认为""。 205 | 206 | :return: 一个可以计算量子线路的模块。 207 | 208 | .. note:: 209 | qprog_with_measure是pyqpanda2中定义的量子线路函数 :https://pyqpanda-toturial.readthedocs.io/zh/latest/QCircuit.html。 210 | 211 | 此函数必须包含以下参数作为函数入参(即使某个参数未实际使用),否则无法在QpandaQCircuitVQCLayerLite中正常运行。 212 | 213 | 与QuantumLayer相比。该接口传入的变分线路运行函数中,用户应该手动创建量子比特和模拟器: https://pyqpanda-toturial.readthedocs.io/zh/latest/QuantumMachine.html, 214 | 215 | 如果qprog_with_measure需要quantum measure,用户还需要手动创建需要分配cbits: https://pyqpanda-toturial.readthedocs.io/zh/latest/Measure.html 216 | 217 | 量子线路函数 qprog_with_measure (input,param,nqubits,ncubits)的使用可参考下面的例子。 218 | 219 | `input`: 输入一维经典数据。如果没有,输入 None。 220 | 221 | `param`: 输入一维的变分量子线路的待训练参数。 222 | 223 | .. note:: 224 | 225 | 该类具有别名 `QuantumLayerV2` 。 226 | 227 | .. note:: 228 | 229 | 该类计算梯度需要额外使用pyqpanda进行线路计算个数与参数个数、数据个数、数据维度的乘积线性相关。 230 | 231 | Example:: 232 | 233 | import pyqpanda as pq 234 | from pyvqnet.qnn.measure import ProbsMeasure 235 | from pyvqnet.qnn.quantumlayer import QpandaQCircuitVQCLayerLite 236 | import numpy as np 237 | from pyvqnet.tensor import QTensor 238 | def pqctest (input,param): 239 | num_of_qubits = 4 240 | 241 | machine = pq.CPUQVM() 242 | machine.init_qvm() 243 | qubits = machine.qAlloc_many(num_of_qubits) 244 | 245 | circuit = pq.QCircuit() 246 | circuit.insert(pq.H(qubits[0])) 247 | circuit.insert(pq.H(qubits[1])) 248 | circuit.insert(pq.H(qubits[2])) 249 | circuit.insert(pq.H(qubits[3])) 250 | 251 | circuit.insert(pq.RZ(qubits[0],input[0])) 252 | circuit.insert(pq.RZ(qubits[1],input[1])) 253 | circuit.insert(pq.RZ(qubits[2],input[2])) 254 | circuit.insert(pq.RZ(qubits[3],input[3])) 255 | 256 | circuit.insert(pq.CNOT(qubits[0],qubits[1])) 257 | circuit.insert(pq.RZ(qubits[1],param[0])) 258 | circuit.insert(pq.CNOT(qubits[0],qubits[1])) 259 | 260 | circuit.insert(pq.CNOT(qubits[1],qubits[2])) 261 | circuit.insert(pq.RZ(qubits[2],param[1])) 262 | circuit.insert(pq.CNOT(qubits[1],qubits[2])) 263 | 264 | circuit.insert(pq.CNOT(qubits[2],qubits[3])) 265 | circuit.insert(pq.RZ(qubits[3],param[2])) 266 | circuit.insert(pq.CNOT(qubits[2],qubits[3])) 267 | 268 | prog = pq.QProg() 269 | prog.insert(circuit) 270 | rlt_prob = ProbsMeasure([0,2],prog,machine,qubits) 271 | return rlt_prob 272 | 273 | pqc = QpandaQCircuitVQCLayerLite(pqctest,3) 274 | 275 | #classic data as input 276 | input = QTensor([[1.0,2,3,4],[4,2,2,3],[3,3,2,2]] ) 277 | 278 | #forward circuits 279 | rlt = pqc(input) 280 | 281 | grad = QTensor(np.ones(rlt.data.shape)*1000) 282 | #backward circuits 283 | rlt.backward(grad) 284 | print(rlt) 285 | 286 | # [ 287 | # [0.2500000, 0.2500000, 0.2500000, 0.2500000], 288 | # [0.2500000, 0.2500000, 0.2500000, 0.2500000], 289 | # [0.2500000, 0.2500000, 0.2500000, 0.2500000] 290 | # ] 291 | 292 | 如果使用GPU,参考下面的例子: 293 | 294 | 295 | Example:: 296 | 297 | import pyqpanda as pq 298 | from pyvqnet.qnn.measure import ProbsMeasure 299 | from pyvqnet.qnn.quantumlayer import QpandaQCircuitVQCLayerLite 300 | import numpy as np 301 | from pyvqnet.tensor import QTensor,DEV_GPU_0 302 | def pqctest (input,param): 303 | num_of_qubits = 4 304 | 305 | machine = pq.CPUQVM() 306 | machine.init_qvm() 307 | qubits = machine.qAlloc_many(num_of_qubits) 308 | 309 | circuit = pq.QCircuit() 310 | circuit.insert(pq.H(qubits[0])) 311 | circuit.insert(pq.H(qubits[1])) 312 | circuit.insert(pq.H(qubits[2])) 313 | circuit.insert(pq.H(qubits[3])) 314 | 315 | circuit.insert(pq.RZ(qubits[0],input[0])) 316 | circuit.insert(pq.RZ(qubits[1],input[1])) 317 | circuit.insert(pq.RZ(qubits[2],input[2])) 318 | circuit.insert(pq.RZ(qubits[3],input[3])) 319 | 320 | circuit.insert(pq.CNOT(qubits[0],qubits[1])) 321 | circuit.insert(pq.RZ(qubits[1],param[0])) 322 | circuit.insert(pq.CNOT(qubits[0],qubits[1])) 323 | 324 | circuit.insert(pq.CNOT(qubits[1],qubits[2])) 325 | circuit.insert(pq.RZ(qubits[2],param[1])) 326 | circuit.insert(pq.CNOT(qubits[1],qubits[2])) 327 | 328 | circuit.insert(pq.CNOT(qubits[2],qubits[3])) 329 | circuit.insert(pq.RZ(qubits[3],param[2])) 330 | circuit.insert(pq.CNOT(qubits[2],qubits[3])) 331 | 332 | prog = pq.QProg() 333 | prog.insert(circuit) 334 | rlt_prob = ProbsMeasure([0,2],prog,machine,qubits) 335 | return rlt_prob 336 | 337 | pqc = QpandaQCircuitVQCLayerLite(pqctest,3) 338 | #layer move to gpu 339 | pqc.toGPU() 340 | #classic data as input 341 | input = QTensor([[1.0,2,3,4],[4,2,2,3],[3,3,2,2]] ) 342 | #data move to gpu 343 | input.toGPU(DEV_GPU_0) 344 | #forward circuits 345 | rlt = pqc(input) 346 | 347 | grad = QTensor(np.ones(rlt.data.shape)*1000,device= DEV_GPU_0) 348 | #backward circuits 349 | rlt.backward(grad) 350 | print(rlt) 351 | 352 | 353 | 354 | QuantumBatchAsyncQcloudLayer 355 | ================================= 356 | 357 | 当您安装最新版本pyqpanda,可以使用本接口定义一个变分线路,并提交到originqc的真实芯片上运行。 358 | 359 | .. py:class:: pyvqnet.qnn.quantumlayer.QuantumBatchAsyncQcloudLayer(origin_qprog_func, qcloud_token, para_num, num_qubits, num_cubits, pauli_str_dict=None, shots = 1000, initializer=None, dtype=None, name="", diff_method="parameter_shift", submit_kwargs={}, query_kwargs={}) 360 | 361 | 使用 pyqpanda QCloud 从版本 3.8.2.2 开始的本源量子真实芯片的抽象计算模块。 它提交参数化量子电路到真实芯片并获得测量结果。 362 | 如果 diff_method == "random_coordinate_descent" ,该层将随机选择单个参数来计算梯度,其他参数将保持为零。参考:https://arxiv.org/abs/2311.00088 363 | 364 | .. note:: 365 | 366 | qcloud_token 为您到 https://qcloud.originqc.com.cn/ 中申请的api token。 367 | origin_qprog_func 需要返回pypqanda.QProg类型的数据,如果没有设置pauli_str_dict,需要保证该QProg中已经插入了measure。 368 | origin_qprog_func 的形式必须按照如下: 369 | 370 | origin_qprog_func(input,param,qubits,cbits,machine) 371 | 372 | `input`: 输入1~2维经典数据,二维的情况下,第一个维度为批处理大小。 373 | 374 | `param`: 输入一维的变分量子线路的待训练参数。 375 | 376 | `machine`: 由QuantumBatchAsyncQcloudLayer创建的模拟器QCloud,无需用户额外在函数中定义。 377 | 378 | `qubits`: 由QuantumBatchAsyncQcloudLayer创建的模拟器QCloud创建的量子比特,数量为 `num_qubits`, 类型为pyQpanda.Qubits,无需用户额外在函数中定义。 379 | 380 | `cbits`: 由QuantumBatchAsyncQcloudLayer分配的经典比特, 数量为 `num_cubits`, 类型为 pyQpanda.ClassicalCondition,无需用户额外在函数中定义。。 381 | 382 | .. note:: 383 | 384 | 该类计算梯度需要额外使用真实芯片进行线路计算个数与参数个数、数据个数、数据维度的乘积线性相关。 385 | 386 | :param origin_qprog_func: QPanda 构建的变分量子电路函数,必须返回QProg。 387 | :param qcloud_token: `str` - 量子机的类型或用于执行的云令牌。 388 | :param para_num: `int` - 参数数量,参数是大小为[para_num]的QTensor。 389 | :param num_qubits: `int` - 量子电路中的量子比特数量。 390 | :param num_cubits: `int` - 量子电路中用于测量的经典比特数量。 391 | :param pauli_str_dict: `dict|list` - 表示量子电路中泡利运算符的字典或字典列表。 默认为“无”,则进行测量操作,如果输入泡利算符的字典,则会计算单个期望或者多个期望。 392 | :param shot: `int` - 测量次数。 默认值为 1000。 393 | :param initializer: 参数值的初始化器。 默认为“无”,使用0~2*pi正态分布。 394 | :param dtype: 参数的数据类型。 默认值为 None,即使用默认数据类型pyvqnet.kfloat32。 395 | :param name: 模块的名称。 默认为空字符串。 396 | :param diff_method: 梯度计算的微分方法。 默认为“parameter_shift”,"random_coordinate_descent"。 397 | :param submit_kwargs: 用于提交量子电路的附加关键字参数,默认:{"chip_id":pyqpanda.real_chip_type.origin_72,"is_amend":True,"is_mapping":True,"is_optimization":True,"compile_level":3,"default_task_group_size":200,"test_qcloud_fake":False},当设置test_qcloud_fake为True则本地CPUQVM模拟。 398 | :param query_kwargs: 用于查询量子结果的附加关键字参数,默认:{"timeout":2,"print_query_info":True,"sub_circuits_split_size":1}。 399 | :return: 一个可以计算量子电路的模块。 400 | 401 | Example:: 402 | 403 | import numpy as np 404 | import pyqpanda as pq 405 | import pyvqnet 406 | from pyvqnet.qnn import QuantumLayer,QuantumBatchAsyncQcloudLayer 407 | from pyvqnet.qnn import expval_qcloud 408 | 409 | def qfun(input,param, m_machine, m_qlist,cubits): 410 | measure_qubits = [0,2] 411 | m_prog = pq.QProg() 412 | cir = pq.QCircuit() 413 | cir.insert(pq.RZ(m_qlist[0],input[0])) 414 | cir.insert(pq.CNOT(m_qlist[0],m_qlist[1])) 415 | cir.insert(pq.RY(m_qlist[1],param[0])) 416 | cir.insert(pq.CNOT(m_qlist[0],m_qlist[2])) 417 | cir.insert(pq.RZ(m_qlist[1],input[1])) 418 | cir.insert(pq.RY(m_qlist[2],param[1])) 419 | cir.insert(pq.H(m_qlist[2])) 420 | m_prog.insert(cir) 421 | 422 | for idx, ele in enumerate(measure_qubits): 423 | m_prog << pq.Measure(m_qlist[ele], cubits[idx]) 424 | return m_prog 425 | 426 | l = QuantumBatchAsyncQcloudLayer(qfun, 427 | "3047DE8A59764BEDAC9C3282093B16AF1", 428 | 2, 429 | 6, 430 | 6, 431 | pauli_str_dict=None, 432 | shots = 1000, 433 | initializer=None, 434 | dtype=None, 435 | name="", 436 | diff_method="parameter_shift", 437 | submit_kwargs={}, 438 | query_kwargs={}) 439 | x = pyvqnet.tensor.QTensor([[0.56,1.2],[0.56,1.2],[0.56,1.2],[0.56,1.2],[0.56,1.2]],requires_grad= True) 440 | y = l(x) 441 | print(y) 442 | y.backward() 443 | print(l.m_para.grad) 444 | print(x.grad) 445 | 446 | def qfun2(input,param, m_machine, m_qlist,cubits): 447 | measure_qubits = [0,2] 448 | m_prog = pq.QProg() 449 | cir = pq.QCircuit() 450 | cir.insert(pq.RZ(m_qlist[0],input[0])) 451 | cir.insert(pq.CNOT(m_qlist[0],m_qlist[1])) 452 | cir.insert(pq.RY(m_qlist[1],param[0])) 453 | cir.insert(pq.CNOT(m_qlist[0],m_qlist[2])) 454 | cir.insert(pq.RZ(m_qlist[1],input[1])) 455 | cir.insert(pq.RY(m_qlist[2],param[1])) 456 | cir.insert(pq.H(m_qlist[2])) 457 | m_prog.insert(cir) 458 | 459 | return m_prog 460 | l = QuantumBatchAsyncQcloudLayer(qfun2, 461 | "3047DE8A59764BEDAC9C3282093B16AF", 462 | 2, 463 | 6, 464 | 6, 465 | pauli_str_dict={'Z0 X1':10,'':-0.5,'Y2':-0.543}, 466 | shots = 1000, 467 | initializer=None, 468 | dtype=None, 469 | name="", 470 | diff_method="parameter_shift", 471 | submit_kwargs={}, 472 | query_kwargs={}) 473 | x = pyvqnet.tensor.QTensor([[0.56,1.2],[0.56,1.2],[0.56,1.2],[0.56,1.2]],requires_grad= True) 474 | y = l(x) 475 | print(y) 476 | y.backward() 477 | print(l.m_para.grad) 478 | print(x.grad) 479 | 480 | 481 | QuantumLayerMultiProcess 482 | ============================ 483 | 484 | 如您更加熟悉pyqpanda2语法,可以使用QuantumLayerMultiProcess,自定义量子比特 ``qubits`` ,经典比特 ``cbits`` ,后端模拟器 ``machine`` 加入QuantumLayerMultiProcess的参数 ``qprog_with_measure`` 函数中。 485 | 486 | .. py:class:: pyvqnet.qnn.quantumlayer.QuantumLayerMultiProcess(qprog_with_measure,para_num,num_of_qubits: int,num_of_cbits: int = 1,diff_method:str = "parameter_shift",delta:float = 0.01, dtype=None,name="") 487 | 488 | 变分量子层的抽象计算模块。使用多进程技术对一个批次数据计算梯度时候的量子线路进行加速。对于线路深度较少的线路,该层的多线程加速效果并不明显。 489 | 490 | 该层对一个参数化的量子线路进行仿真,得到测量结果。该变分量子层继承了VQNet框架的梯度计算模块,可以计算线路参数的梯度,训练变分量子线路模型或将变分量子线路嵌入混合量子和经典模型。 491 | 492 | :param qprog_with_measure: 用pyqpanda2构建的量子线路运行和测量函数。 493 | :param para_num: `int` - 参数个数。 494 | :param num_of_qubits: 量子比特数。 495 | :param num_of_cbits: 经典比特数,默认为1。 496 | :param diff_method: 求解量子线路参数梯度的方法,“参数位移”或“有限差分”,默认参数偏移。 497 | :param delta: 有限差分计算梯度时的 \delta。 498 | :param dtype: 参数的数据类型,defaults:None,使用默认数据类型:kfloat32,代表32位浮点数。 499 | :param name: 这个模块的名字, 默认为""。 500 | 501 | :return: 一个可以计算量子线路的模块。 502 | 503 | .. note:: 504 | qprog_with_measure是pyqpanda2中定义的量子线路函数 :https://pyqpanda-toturial.readthedocs.io/zh/latest/QCircuit.html。 505 | 506 | 此函数应包含以下参数,否则无法在QuantumLayerMultiProcess中正常运行。 507 | 508 | 与QpandaQCircuitVQCLayerLite类似,该接口传入的变分线路运行函数中,用户应该手动创建量子比特和模拟器: https://pyqpanda-toturial.readthedocs.io/zh/latest/QuantumMachine.html, 509 | 510 | 如果qprog_with_measure需要quantum measure,用户应该手动创建cbits: https://pyqpanda-toturial.readthedocs.io/zh/latest/Measure.html 511 | 512 | 量子线路函数 qprog_with_measure(input,param,nqubits,ncubits) 的使用可参考下面的例子。对于线路深度较少的线路,该层的多线程加速效果并不明显。 513 | 514 | `input`: 输入一维经典数据。 515 | 516 | `param`: 输入一维量子线路的参数。 517 | 518 | `nqubits`: 预先设定的量子比特数量。如果没有,输入 0。 519 | 520 | `ncubits`: 预先设定的经典比特数量。如果没有,输入 0。 521 | 522 | 523 | .. note:: 524 | 525 | 该类计算梯度需要额外使用pyqpanda进行线路计算个数与参数个数、数据个数、数据维度的乘积线性相关。 526 | 527 | Example:: 528 | 529 | import pyqpanda as pq 530 | from pyvqnet.qnn.measure import ProbsMeasure 531 | from pyvqnet.qnn.quantumlayer import QuantumLayerMultiProcess 532 | import numpy as np 533 | from pyvqnet.tensor import QTensor 534 | 535 | def pqctest (input,param,nqubits,ncubits): 536 | machine = pq.CPUQVM() 537 | machine.init_qvm() 538 | qubits = machine.qAlloc_many(nqubits) 539 | circuit = pq.QCircuit() 540 | circuit.insert(pq.H(qubits[0])) 541 | circuit.insert(pq.H(qubits[1])) 542 | circuit.insert(pq.H(qubits[2])) 543 | circuit.insert(pq.H(qubits[3])) 544 | 545 | circuit.insert(pq.RZ(qubits[0],input[0])) 546 | circuit.insert(pq.RZ(qubits[1],input[1])) 547 | circuit.insert(pq.RZ(qubits[2],input[2])) 548 | circuit.insert(pq.RZ(qubits[3],input[3])) 549 | 550 | circuit.insert(pq.CNOT(qubits[0],qubits[1])) 551 | circuit.insert(pq.RZ(qubits[1],param[0])) 552 | circuit.insert(pq.CNOT(qubits[0],qubits[1])) 553 | 554 | circuit.insert(pq.CNOT(qubits[1],qubits[2])) 555 | circuit.insert(pq.RZ(qubits[2],param[1])) 556 | circuit.insert(pq.CNOT(qubits[1],qubits[2])) 557 | 558 | circuit.insert(pq.CNOT(qubits[2],qubits[3])) 559 | circuit.insert(pq.RZ(qubits[3],param[2])) 560 | circuit.insert(pq.CNOT(qubits[2],qubits[3])) 561 | 562 | prog = pq.QProg() 563 | prog.insert(circuit) 564 | 565 | rlt_prob = ProbsMeasure([0,2],prog,machine,qubits) 566 | return rlt_prob 567 | 568 | 569 | pqc = QuantumLayerMultiProcess(pqctest,3,4,1) 570 | #classic data as input 571 | input = QTensor([[1.0,2,3,4],[4,2,2,3],[3,3,2,2]] ) 572 | #forward circuits 573 | rlt = pqc(input) 574 | grad = QTensor(np.ones(rlt.data.shape)*1000) 575 | #backward circuits 576 | rlt.backward(grad) 577 | print(rlt) 578 | 579 | # [ 580 | # [0.2500000, 0.2500000, 0.2500000, 0.2500000], 581 | # [0.2500000, 0.2500000, 0.2500000, 0.2500000], 582 | # [0.2500000, 0.2500000, 0.2500000, 0.2500000] 583 | # ] 584 | 585 | 586 | NoiseQuantumLayer 587 | ========================= 588 | 589 | 在真实的量子计算机中,受制于量子比特自身的物理特性,常常存在不可避免的计算误差。为了能在量子虚拟机中更好的模拟这种误差,VQNet同样支持含噪声量子虚拟机。含噪声量子虚拟机的模拟更贴近真实的量子计算机,我们可以自定义支持的逻辑门类型,自定义逻辑门支持的噪声模型。 590 | 现有可支持的量子噪声模型依据QPanda中定义,具体参考链接 `QPANDA2 `_ 中的介绍。 591 | 592 | 使用 NoiseQuantumLayer 定义一个量子线路自动微分类,该类支持QPanda噪声虚拟机。用户定义一个函数作为参数 ``qprog_with_measure`` ,该函数需要包含pyqpanda2定义的量子线路,同样需要传入一个参数 ``noise_set_config``,使用pyqpanda2接口,设置噪声模型。 593 | 594 | .. py:class:: pyvqnet.qnn.quantumlayer.NoiseQuantumLayer(qprog_with_measure,para_num,machine_type,num_of_qubits:int,num_of_cbits:int=1,diff_method:str= "parameter_shift",delta:float=0.01,noise_set_config = None, dtype=None,name="") 595 | 596 | 变分量子层的抽象计算模块。对一个参数化的量子线路进行仿真,得到测量结果。该变分量子层继承了VQNet框架的梯度计算模块,可以计算线路参数的梯度,训练变分量子线路模型或将变分量子线路嵌入混合量子和经典模型。 597 | 598 | 这一层可以在量子线路中使用噪声模型。 599 | 600 | :param qprog_with_measure: 用pyqpanda2构建的量子线路运行和测量函数。 601 | :param para_num: `int` - 参数个数。 602 | :param machine_type: qpanda机器类型。 603 | :param num_of_qubits: 量子比特数。 604 | :param num_of_cbits: 经典比特数,默认为1。 605 | :param diff_method: 求解量子线路参数梯度的方法,“参数位移”或“有限差分”,默认参数偏移。 606 | :param delta: 有限差分计算梯度时的 \delta。 607 | :param noise_set_config: 噪声设置函数。 608 | :param dtype: 参数的数据类型,defaults:None,使用默认数据类型:kfloat32,代表32位浮点数。 609 | :param name: 这个模块的名字, 默认为""。 610 | 611 | :return: 一个可以计算含噪声量子线路的模块。 612 | 613 | 614 | .. note:: 615 | qprog_with_measure是pyqpanda2中定义的量子线路函数 :https://pyqpanda-toturial.readthedocs.io/zh/latest/QCircuit.html。 616 | 617 | 此函数必须包含以下参数作为函数入参(即使某个参数未实际使用),否则无法在NoiseQuantumLayer中正常运行。 618 | 619 | qprog_with_measure (input,param,qubits,cbits,machine) 620 | 621 | `input`: 输入一维经典数据。如果没有输入可以输入 None。 622 | 623 | `param`: 输入一维的变分量子线路的待训练参数。 624 | 625 | `qubits`: 该NoiseQuantumLayer分配的量子比特,类型为pyQpanda.Qubits。 626 | 627 | `cbits`: cbits由NoiseQuantumLayer分配的经典比特,用来辅助测量函数,类型为 pyQpanda.ClassicalCondition。如果线路不使用cbits,也应保留此参数。 628 | 629 | `machine`: 由NoiseQuantumLayer创建的模拟器。 630 | 631 | .. note:: 632 | 633 | 该类计算梯度需要额外使用pyqpanda进行线路计算个数与参数个数、数据个数、数据维度的乘积线性相关。 634 | 635 | 636 | Example:: 637 | 638 | import pyqpanda as pq 639 | from pyvqnet.qnn.measure import ProbsMeasure 640 | from pyvqnet.qnn.quantumlayer import NoiseQuantumLayer 641 | import numpy as np 642 | from pyqpanda import * 643 | from pyvqnet.tensor import QTensor 644 | def circuit(weights,param,qubits,cbits,machine): 645 | 646 | circuit = pq.QCircuit() 647 | 648 | circuit.insert(pq.H(qubits[0])) 649 | circuit.insert(pq.RY(qubits[0], weights[0])) 650 | circuit.insert(pq.RY(qubits[0], param[0])) 651 | prog = pq.QProg() 652 | prog.insert(circuit) 653 | prog << measure_all(qubits, cbits) 654 | 655 | result = machine.run_with_configuration(prog, cbits, 100) 656 | 657 | counts = np.array(list(result.values())) 658 | states = np.array(list(result.keys())).astype(float) 659 | # Compute probabilities for each state 660 | probabilities = counts / 100 661 | # Get state expectation 662 | expectation = np.sum(states * probabilities) 663 | return expectation 664 | 665 | def default_noise_config(qvm,q): 666 | 667 | p = 0.01 668 | qvm.set_noise_model(NoiseModel.BITFLIP_KRAUS_OPERATOR, GateType.PAULI_X_GATE, p) 669 | qvm.set_noise_model(NoiseModel.BITFLIP_KRAUS_OPERATOR, GateType.PAULI_Y_GATE, p) 670 | qvm.set_noise_model(NoiseModel.BITFLIP_KRAUS_OPERATOR, GateType.PAULI_Z_GATE, p) 671 | qvm.set_noise_model(NoiseModel.BITFLIP_KRAUS_OPERATOR, GateType.RX_GATE, p) 672 | qvm.set_noise_model(NoiseModel.BITFLIP_KRAUS_OPERATOR, GateType.RY_GATE, p) 673 | qvm.set_noise_model(NoiseModel.BITFLIP_KRAUS_OPERATOR, GateType.RZ_GATE, p) 674 | qvm.set_noise_model(NoiseModel.BITFLIP_KRAUS_OPERATOR, GateType.RY_GATE, p) 675 | qvm.set_noise_model(NoiseModel.BITFLIP_KRAUS_OPERATOR, GateType.HADAMARD_GATE, p) 676 | qves =[] 677 | for i in range(len(q)-1): 678 | qves.append([q[i],q[i+1]])# 679 | qves.append([q[len(q)-1],q[0]]) 680 | qvm.set_noise_model(NoiseModel.DAMPING_KRAUS_OPERATOR, GateType.CNOT_GATE, p, qves) 681 | 682 | return qvm 683 | 684 | qvc = NoiseQuantumLayer(circuit,24,"noise",1,1,diff_method= "parameter_shift", delta=0.01,noise_set_config = default_noise_config) 685 | input = QTensor([ 686 | [0., 1., 1., 1.], 687 | 688 | [0., 0., 1., 1.], 689 | 690 | [1., 0., 1., 1.] 691 | ] ) 692 | rlt = qvc(input) 693 | grad = QTensor(np.ones(rlt.data.shape)*1000) 694 | 695 | rlt.backward(grad) 696 | print(qvc.m_para.grad) 697 | 698 | #[1195., 105., 70., 0., 699 | # 45., -45., 50., 15., 700 | # -80., 50., 10., -30., 701 | # 10., 60., 75., -110., 702 | # 55., 45., 25., 5., 703 | # 5., 50., -25., -15.] 704 | 705 | 下面给出一个 ``noise_set_config`` 的例子,这里使得 ``RX`` , ``RY`` , ``RZ`` , ``X`` , ``Y`` , ``Z`` , ``H`` 等逻辑门加入了 p = 0.01 的 BITFLIP_KRAUS_OPERATOR噪声模型。 706 | 707 | .. code-block:: 708 | 709 | def noise_set_config(qvm,q): 710 | 711 | p = 0.01 712 | qvm.set_noise_model(NoiseModel.BITFLIP_KRAUS_OPERATOR, GateType.PAULI_X_GATE, p) 713 | qvm.set_noise_model(NoiseModel.BITFLIP_KRAUS_OPERATOR, GateType.PAULI_Y_GATE, p) 714 | qvm.set_noise_model(NoiseModel.BITFLIP_KRAUS_OPERATOR, GateType.PAULI_Z_GATE, p) 715 | qvm.set_noise_model(NoiseModel.BITFLIP_KRAUS_OPERATOR, GateType.RX_GATE, p) 716 | qvm.set_noise_model(NoiseModel.BITFLIP_KRAUS_OPERATOR, GateType.RY_GATE, p) 717 | qvm.set_noise_model(NoiseModel.BITFLIP_KRAUS_OPERATOR, GateType.RZ_GATE, p) 718 | qvm.set_noise_model(NoiseModel.BITFLIP_KRAUS_OPERATOR, GateType.RY_GATE, p) 719 | qvm.set_noise_model(NoiseModel.BITFLIP_KRAUS_OPERATOR, GateType.HADAMARD_GATE, p) 720 | qves =[] 721 | for i in range(len(q)-1): 722 | qves.append([q[i],q[i+1]])# 723 | qves.append([q[len(q)-1],q[0]]) 724 | qvm.set_noise_model(NoiseModel.DAMPING_KRAUS_OPERATOR, GateType.CNOT_GATE, p, qves) 725 | 726 | return qvm 727 | 728 | 729 | 730 | 731 | DataParallelHybirdVQCQpandaQVMLayer 732 | ============================================================ 733 | 734 | .. py:class:: pyvqnet.qnn.DataParallelHybirdVQCQpandaQVMLayer(vqc_module: Module,qcloud_token: str,num_qubits: int,num_cubits: int,pauli_str_dict: Union[List[Dict], Dict, None] = None,shots: int = 1000,dtype: Union[int, None] = None,name: str = "",submit_kwargs: Dict = {},query_kwargs: Dict = {}) 735 | 736 | 混合 vqc 和 qpanda QVM 层。该层将用户 `forward` 函数定义的VQNet编写的量子线路计算转化为QPanda OriginIR,可在QPanda 本地虚拟机或者云端服务上进行前向运行,并在本地CPU上模拟计算线路参数梯度,降低了使用参数漂移法计算的时间复杂度。 737 | 使用数据并行将输入数据第一个维度 批处理数量 根据 `CommController` 中分配的进程数进行分割,在多个进程中基于 `mpi` 或者 `nccl` 进行数据并行。请注意一个进程对应一个节点上的GPU设备。 738 | 每个进程中的该模块在前向计算时提交 批处理数量/节点数 个数据产生的量子线路,反向计算中计算 批处理数量/节点数 个数据贡献的梯度,并通过all_reduce计算多个节点上参数的平均梯度。 739 | 740 | .. note:: 741 | 742 | 该模块内部对输入切分,并将数据移动到对应设备上。第0个进程计算[0,批处理数量/节点数]数据,第k个进程计算[(k-1)批处理数量/节点数,k*批处理数量/节点数] 743 | 744 | :param vqc_module: 带有 forward() 的 vqc_module。 745 | :param qcloud_token: `str` - 量子机器的类型或用于执行的云令牌。 746 | :param num_qubits: `int` - 量子电路中的量子比特数。 747 | :param num_cubits: `int` - 量子电路中用于测量的经典比特数。 748 | :param pauli_str_dict: `dict|list` - 表示量子电路中泡利算子的字典或字典列表。默认值为 None。 749 | :param shots: `int` - 量子线路测量次数。默认值为 1000。 750 | :param name: 模块名称。默认值为空字符串。 751 | :param submit_kwargs: 提交量子电路的附加关键字参数,默认值: 752 | {"chip_id":pyqpanda.real_chip_type.origin_72, 753 | "is_amend":True,"is_mapping":True, 754 | "is_optimization":True, 755 | "default_task_group_size":200, 756 | "test_qcloud_fake":True}。 757 | :param query_kwargs: 查询量子结果的附加关键字参数,默认值:{"timeout":2,"print_query_info":True,"sub_circuits_split_size":1}。 758 | 759 | 以下是使用cpu计算的mpi例子,单节点双进程的命令如下: mpirun -n 2 python xxx.py 760 | 761 | Example:: 762 | 763 | from pyvqnet.distributed import * 764 | 765 | Comm_OP = CommController("mpi") 766 | from pyvqnet.qnn import * 767 | from pyvqnet.qnn.vqc import * 768 | import pyvqnet 769 | from pyvqnet.nn import Module, Linear 770 | from pyvqnet.device import DEV_GPU_0 771 | pyvqnet.utils.set_random_seed(42) 772 | 773 | 774 | class Hybird(Module): 775 | def __init__(self): 776 | self.cl1 = Linear(3, 3) 777 | self.ql = QModel(num_wires=6, dtype=pyvqnet.kcomplex64) 778 | self.cl2 = Linear(1, 2) 779 | 780 | def forward(self, x): 781 | x = self.cl1(x) 782 | x = self.ql(x) 783 | x = self.cl2(x) 784 | return x 785 | 786 | 787 | class QModel(Module): 788 | def __init__(self, num_wires, dtype, grad_mode=""): 789 | super(QModel, self).__init__() 790 | 791 | self._num_wires = num_wires 792 | self._dtype = dtype 793 | self.qm = QMachine(num_wires, 794 | dtype=dtype, 795 | grad_mode=grad_mode, 796 | save_ir=True) 797 | self.rx_layer = RX(has_params=True, trainable=False, wires=0) 798 | self.ry_layer = RY(has_params=True, trainable=False, wires=1) 799 | self.rz_layer = RZ(has_params=True, trainable=False, wires=1) 800 | self.u1 = U1(has_params=True, trainable=True, wires=[2]) 801 | self.u2 = U2(has_params=True, trainable=True, wires=[3]) 802 | self.u3 = U3(has_params=True, trainable=True, wires=[1]) 803 | self.i = I(wires=[3]) 804 | self.s = S(wires=[3]) 805 | self.x1 = X1(wires=[3]) 806 | self.y1 = Y1(wires=[3]) 807 | self.z1 = Z1(wires=[3]) 808 | self.x = PauliX(wires=[3]) 809 | self.y = PauliY(wires=[3]) 810 | self.z = PauliZ(wires=[3]) 811 | self.swap = SWAP(wires=[2, 3]) 812 | self.cz = CZ(wires=[2, 3]) 813 | self.cr = CR(has_params=True, trainable=True, wires=[2, 3]) 814 | self.rxx = RXX(has_params=True, trainable=True, wires=[2, 3]) 815 | self.rzz = RYY(has_params=True, trainable=True, wires=[2, 3]) 816 | self.ryy = RZZ(has_params=True, trainable=True, wires=[2, 3]) 817 | self.rzx = RZX(has_params=True, trainable=False, wires=[2, 3]) 818 | self.toffoli = Toffoli(wires=[2, 3, 4], use_dagger=True) 819 | self.h = Hadamard(wires=[1]) 820 | 821 | self.iSWAP = iSWAP( wires=[0, 2]) 822 | self.tlayer = T(wires=1) 823 | self.cnot = CNOT(wires=[0, 1]) 824 | self.measure = MeasureAll(obs={'Z0': 2, 'Y3': 3}) 825 | 826 | def forward(self, x, *args, **kwargs): 827 | self.qm.reset_states(x.shape[0]) 828 | self.i(q_machine=self.qm) 829 | self.s(q_machine=self.qm) 830 | self.swap(q_machine=self.qm) 831 | self.cz(q_machine=self.qm) 832 | self.x(q_machine=self.qm) 833 | self.x1(q_machine=self.qm) 834 | self.y(q_machine=self.qm) 835 | self.y1(q_machine=self.qm) 836 | self.z(q_machine=self.qm) 837 | self.z1(q_machine=self.qm) 838 | self.ryy(q_machine=self.qm) 839 | self.rxx(q_machine=self.qm) 840 | self.rzz(q_machine=self.qm) 841 | self.rzx(q_machine=self.qm, params=x[:, [1]]) 842 | self.cr(q_machine=self.qm) 843 | self.u1(q_machine=self.qm) 844 | self.u2(q_machine=self.qm) 845 | self.u3(q_machine=self.qm) 846 | self.rx_layer(params=x[:, [0]], q_machine=self.qm) 847 | self.cnot(q_machine=self.qm) 848 | self.h(q_machine=self.qm) 849 | self.iSWAP(q_machine=self.qm) 850 | self.ry_layer(params=x[:, [1]], q_machine=self.qm) 851 | self.tlayer(q_machine=self.qm) 852 | self.rz_layer(params=x[:, [2]], q_machine=self.qm) 853 | self.toffoli(q_machine=self.qm) 854 | rlt = self.measure(q_machine=self.qm) 855 | 856 | return rlt 857 | 858 | input_x = tensor.QTensor([[0.1, 0.2, 0.3]]) 859 | input_x = tensor.broadcast_to(input_x, [20, 3]) 860 | input_x.requires_grad = True 861 | 862 | 863 | 864 | qunatum_model = QModel(num_wires=6, dtype=pyvqnet.kcomplex64) 865 | 866 | l = DataParallelHybirdVQCQpandaQVMLayer( 867 | Comm_OP, 868 | qunatum_model, 869 | "3047DE8A59764BEDAC9C3282093B16AF1", 870 | 871 | num_qubits=6, 872 | num_cubits=6, 873 | pauli_str_dict={ 874 | 'Z0': 2, 875 | 'Y3': 3 876 | }, 877 | shots=1000, 878 | name="", 879 | submit_kwargs={"test_qcloud_fake": True}, 880 | query_kwargs={}) 881 | 882 | y = l(input_x) 883 | print(y) 884 | y.backward() 885 | for p in qunatum_model.parameters(): 886 | print(p.grad) 887 | 888 | 889 | 890 | 以下是使用gpu计算的nccl例子,单节点双进程的命令如下: mpirun -n 2 python xxx.py 891 | 892 | Example:: 893 | 894 | from pyvqnet.distributed import * 895 | 896 | Comm_OP = CommController("nccl") 897 | input_x = tensor.QTensor([[0.1, 0.2, 0.3]],device=Comm_OP.get_local_rank() + pyvqnet.DEV_GPU_0) 898 | #rest code not changed 899 | 900 | 901 | 以下是进行多节点多进程并行计算的例子,请保证在不同节点的相同路径下,相同python环境下运行该脚本,并在每个节点下 902 | 编写ip地址映射文件 `hosts`,格式参考 :ref:`hostfile` 。 903 | 904 | Example:: 905 | 906 | #hosts示例 907 | 10.10.7.107 slots=2 908 | 10.10.7.109 slots=2 909 | 910 | 使用 mpi 进行2节点每节点2进程共4进程并行,则可以运行 `vqnetrun -np 4 -f hosts python xxx.py` 911 | 912 | Example:: 913 | 914 | from pyvqnet.distributed import * 915 | Comm_OP = CommController("mpi") 916 | #rest code not changed 917 | 918 | 使用 nccl 进行2节点每节点2进程共4进程并行,则可以运行 `vqnetrun -np 4 -f hosts python xxx.py` 919 | 920 | Example:: 921 | 922 | from pyvqnet.distributed import * 923 | Comm_OP = CommController("nccl") 924 | input_x = tensor.QTensor([[0.1, 0.2, 0.3]],device=Comm_OP.get_local_rank() + pyvqnet.DEV_GPU_0) 925 | #rest code not changed 926 | 927 | 量子逻辑门 928 | *********************************** 929 | 930 | 处理量子比特的方式就是量子逻辑门。 使用量子逻辑门,我们有意识的使量子态发生演化。量子逻辑门是构成量子算法的基础。 931 | 932 | 933 | 基本量子逻辑门 934 | ============================ 935 | 936 | 在VQNet中,我们使用本源量子自研的 `pyqpanda2 `_ 的各个逻辑门搭建量子线路,进行量子模拟。 937 | 当前pyqpanda2支持的逻辑门可参考pyqpanda2 `量子逻辑门 `_ 部分的定义。 938 | 此外VQNet还封装了部分在量子机器学习中常用的量子逻辑门组合,这里仅留下了pyqpanda2版本的振幅编码,更多接口可使用参考 :ref: `pq3_gate` 中集成pyqpanda3的接口。 939 | 940 | 941 | 942 | 943 | AmplitudeEmbeddingCircuit 944 | ============================ 945 | 946 | .. py:function:: pyvqnet.qnn.template.AmplitudeEmbeddingCircuit(input_feat,qubits) 947 | 948 | 将 :math:`2^n` 特征编码为 :math:`n` 量子比特的振幅向量。为了表示一个有效的量子态向量, ``features`` 的L2范数必须是1。 949 | 950 | :param input_feat: 表示参数的numpy数组。 951 | :param qubits: pyqpanda2分配的量子比特列表。 952 | :return: 量子线路。 953 | 954 | Example:: 955 | 956 | import numpy as np 957 | import pyqpanda as pq 958 | from pyvqnet.qnn.template import AmplitudeEmbeddingCircuit 959 | input_feat = np.array([2.2, 1, 4.5, 3.7]) 960 | machine = pq.init_quantum_machine(pq.QMachineType.CPU) 961 | m_qlist = machine.qAlloc_many(2) 962 | m_clist = machine.cAlloc_many(2) 963 | m_prog = pq.QProg() 964 | cir = AmplitudeEmbeddingCircuit(input_feat,m_qlist) 965 | print(cir) 966 | pq.destroy_quantum_machine(machine) 967 | 968 | # ┌────────────┐ ┌────────────┐ 969 | # q_0: |0>─────────────── ─── ┤RY(0.853255)├ ─── ┤RY(1.376290)├ 970 | # ┌────────────┐ ┌─┐ └──────┬─────┘ ┌─┐ └──────┬─────┘ 971 | # q_1: |0>─┤RY(2.355174)├ ┤X├ ───────■────── ┤X├ ───────■────── 972 | # └────────────┘ └─┘ └─┘ 973 | 974 | 975 | 976 | 977 | 978 | 979 | 基于pyqpanda2量子机器学习算法封装接口 980 | **************************************** 981 | 982 | 以下使用pyqpanda2构建线路,并在pyvqnet中实现了一些经典量子机器学习算法。 983 | 984 | QGAN制备任意分布初态 985 | ======================= 986 | 987 | 基于2019年 Christa Zoufal 的论文 `Quantum Generative Adversarial Networks for learning and loading random distributions `_ , VQNet提供了一个QGAN制备任意分布初态的例子。该算法使用纯量子变分线路制备特定随机分布的生成量子态,可以减少原先生成特定量子态所需的逻辑门,降低量子线路复杂度。 988 | QGAN使用经典的GAN模型结构,分为Generator生成器与Discriminator鉴别器两个子模型,Generator为量子线路产生特定分布,而Generator生成的分布generated data samples 以及真实的随机分布training data samples 输入Discriminator模型进行鉴别真伪。 989 | 990 | .. image:: ./images/qgan-arch.PNG 991 | :width: 600 px 992 | :align: center 993 | 994 | | 995 | 996 | 997 | 构建VQNet的量子生成对抗网络接口 ``QGANAPI`` 类,我们可以对真实分布的数据 real_data 使用量子生成器进行初态制备。这里使用量子比特数为3,量子生成器内部含参线路模块重复次数为1。 998 | 使用的评价指标为KL散度。 999 | 1000 | .. code-block:: 1001 | 1002 | import pickle 1003 | import os 1004 | import pyqpanda as pq 1005 | from pyvqnet.qnn.qgan.qgan_utils import QGANAPI 1006 | import numpy as np 1007 | 1008 | 1009 | ################################## 1010 | num_of_qubits = 3 # paper config 1011 | rep = 1 1012 | 1013 | number_of_data = 10000 1014 | # Load data samples from different distributions 1015 | mu = 1 1016 | sigma = 1 1017 | real_data = np.random.lognormal(mean=mu, sigma=sigma, size=number_of_data) 1018 | 1019 | 1020 | # intial 1021 | save_dir = None 1022 | qgan_model = QGANAPI( 1023 | real_data, 1024 | # numpy generated data distribution, 1 - dim. 1025 | num_of_qubits, 1026 | batch_size=2000, 1027 | num_epochs=2000, 1028 | q_g_cir=None, 1029 | bounds = [0.0,2**num_of_qubits -1], 1030 | reps=rep, 1031 | metric="kl", 1032 | tol_rel_ent=0.01, 1033 | if_save_param_dir=save_dir 1034 | ) 1035 | 1036 | 接下来使用其训练接口 ``train`` 训练。 1037 | 1038 | .. code-block:: 1039 | 1040 | # train 1041 | qgan_model.train() # train qgan 1042 | 1043 | ``eval`` 画出其与真实分布之间的概率分布函数对比: 1044 | 1045 | .. code-block:: 1046 | 1047 | # show probability distribution function of generated distribution and real distribution 1048 | qgan_model.eval(real_data) #draw pdf 1049 | 1050 | 1051 | ``get_trained_quantum_parameters`` 获取训练参数并输出为一个numpy数组形式。如果 ``save_dir`` 不为空,则该类将保存参数到文件中。可以通过 ``load_param_and_eval`` 函数载入参数,并可以通过 1052 | ``get_circuits_with_trained_param`` 获取训练完参数的量子生成器pyqpanda2线路。 1053 | 1054 | .. code-block:: 1055 | 1056 | # get trained quantum parameters 1057 | param = qgan_model.get_trained_quantum_parameters() 1058 | print(f" trained param {param}") 1059 | 1060 | #load saved parameters files 1061 | if save_dir is not None: 1062 | path = os.path.join( 1063 | save_dir, qgan_model._start_time + "trained_qgan_param.pickle") 1064 | with open(path, "rb") as file: 1065 | t3 = pickle.load(file) 1066 | param = t3["quantum_parameters"] 1067 | print(f" trained param {param}") 1068 | 1069 | #show probability distribution function of generated distribution and real distribution 1070 | qgan_model.load_param_and_eval(param) 1071 | 1072 | #calculate metric 1073 | print(qgan_model.eval_metric(param, "kl")) 1074 | 1075 | #get generator quantum circuit 1076 | machine = pq.CPUQVM() 1077 | machine.init_qvm() 1078 | qubits = machine.qAlloc_many(num_of_qubits) 1079 | qpanda_cir = qgan_model.get_circuits_with_trained_param(qubits) 1080 | print(qpanda_cir) 1081 | 1082 | 生成lognormal分布的损失函数以及概率分布函数图,一般来说需要使用不同的随机种子多次训练该模型可得到较好结果: 1083 | 1084 | .. image:: ./images/qgan-loss.png 1085 | :width: 600 px 1086 | :align: center 1087 | 1088 | | 1089 | 1090 | .. image:: ./images/qgan-pdf.png 1091 | :width: 600 px 1092 | :align: center 1093 | 1094 | | 1095 | 1096 | 量子核SVM算法 1097 | ========================= 1098 | 1099 | 在机器学习任务中,数据通常不能被原始空间中的超平面分隔。寻找此类超平面的一种常见技术是对数据应用非线性变换函数。 1100 | 此函数称为特征映射,通过特征映射,我们可以在这个新的特征空间中计算数据点之间的距离有多近,从而进行机器学习的分类任务。 1101 | 1102 | 本例参照 `Supervised learning with quantum enhanced feature spaces `_ 论文的第一个方法构建变分线路进行数据分类任务。 1103 | ``gen_vqc_qsvm_data`` 为生成该例子所需的数据。 ``vqc_qsvm`` 为变分量子线路类,用来对输入数据进行分类。 1104 | ``vqc_qsvm.plot()`` 函数可视化了数据的分布情况。 1105 | 1106 | .. image:: ./images/VQC-SVM.png 1107 | :width: 600 px 1108 | :align: center 1109 | 1110 | | 1111 | 1112 | .. code-block:: 1113 | 1114 | 1115 | from pyvqnet.qnn.svm import vqc_qsvm, gen_vqc_qsvm_data 1116 | import matplotlib.pyplot as plt 1117 | import numpy as np 1118 | 1119 | batch_size = 40 1120 | maxiter = 40 1121 | training_size = 20 1122 | test_size = 10 1123 | gap = 0.3 1124 | #线路模块重复次数 1125 | rep = 3 1126 | 1127 | #定义接口类 1128 | VQC_QSVM = vqc_qsvm(batch_size, maxiter, rep) 1129 | #随机生成数据 1130 | train_features, test_features, train_labels, test_labels, samples = \ 1131 | gen_vqc_qsvm_data(training_size=training_size, test_size=test_size, gap=gap) 1132 | VQC_QSVM.plot(train_features, test_features, train_labels, test_labels, samples) 1133 | #训练 1134 | VQC_QSVM.train(train_features, train_labels) 1135 | #测试数据测试 1136 | rlt, acc_1 = VQC_QSVM.predict(test_features, test_labels) 1137 | print(f"testing_accuracy {acc_1}") 1138 | 1139 | 1140 | 1141 | 除了上述直接用变分量子线路将经典数据特征映射到量子特征空间,在论文 `Supervised learning with quantum enhanced feature spaces `_ 1142 | 中还介绍了使用量子线路直接估计核函数,并使用经典支持向量机进行分类的方法。类比经典SVM中的各种核函数 :math:`K(i,j)` , 使用量子核函数定义经典数据在量子特征空间 :math:`\phi(\mathbf{x}_i)` 的内积 : 1143 | 1144 | .. math:: 1145 | |\langle \phi(\mathbf{x}_j) | \phi(\mathbf{x}_i) \rangle |^2 = |\langle 0 | U^\dagger(\mathbf{x}_j) U(\mathbf{x}_i) | 0 \rangle |^2 1146 | 1147 | 使用VQNet和pyqpanda2,我们定义一个 ``QuantumKernel_VQNet`` 产生量子核函数,并使用 ``sklearn`` 的 ``SVC`` 进行分类: 1148 | 1149 | .. image:: ./images/qsvm-kernel.png 1150 | :width: 600 px 1151 | :align: center 1152 | 1153 | | 1154 | 1155 | .. code-block:: 1156 | 1157 | import numpy as np 1158 | import pyqpanda as pq 1159 | from sklearn.svm import SVC 1160 | from pyqpanda import * 1161 | from pyqpanda.Visualization.circuit_draw import * 1162 | from pyvqnet.qnn.svm import QuantumKernel_VQNet, gen_vqc_qsvm_data 1163 | import matplotlib 1164 | try: 1165 | matplotlib.use('TkAgg') 1166 | except: 1167 | pass 1168 | 1169 | train_features, test_features,train_labels, test_labels, samples = gen_vqc_qsvm_data(20,5,0.3) 1170 | quantum_kernel = QuantumKernel_VQNet(n_qbits=2) 1171 | quantum_svc = SVC(kernel=quantum_kernel.evaluate) 1172 | quantum_svc.fit(train_features, train_labels) 1173 | score = quantum_svc.score(test_features, test_labels) 1174 | print(f"quantum kernel classification test score: {score}") 1175 | 1176 | 1177 | 1178 | 同时扰动随机近似优化器 1179 | ============================ 1180 | 1181 | .. py:class:: pyvqnet.qnn.SPSA(maxiter: int = 1000, last_avg: int = 1, c0: float = _C0, c1: float = 0.2, c2: float = 0.602, c3: float = 0.101, c4: float = 0, init_para=None, model=None, calibrate_flag=False) 1182 | 1183 | 同时扰动随机近似 (SPSA) 优化器。 1184 | 1185 | SPSA 提供了一种用于逼近多元可微成本函数梯度的随机方法。 1186 | 为实现这一点,使用扰动参数向量对成本函数进行两次评估:原始参数向量的每个分量同时随随机生成的值移动。 1187 | `SPSA 网站 `__ 上提供了进一步的介绍。 1188 | 1189 | :param maxiter: 要执行的最大迭代次数。默认值:1000。 1190 | :param last_avg: last_avg 迭代的平均参数。 1191 | 如果 last_avg = 1,则只考虑最后一次迭代。默认值:1。 1192 | :param c0: 初始a。更新参数的步长。默认值:0.2*pi 1193 | :param c1: 初始的c。用于近似梯度的步长。默认值:0.1。 1194 | :param c2: 论文中的alpha,用于在每次迭代时调整a(c0)。默认值:0.602。 1195 | :param c3: 论文中的gamma,每次迭代时用来调整c(c1)。默认值:0.101。 1196 | :param c4: 同样用来控制a的参数。默认值:0。 1197 | :param init_para: 初始化参数。默认值:无。 1198 | :param model: 参数模型:模型。默认值:无。 1199 | :param calibrate_flag: 是否校准超参数 a 和 c,默认值:False。 1200 | 1201 | :return: 一个SPSA优化器实例 1202 | 1203 | 1204 | .. warning:: 1205 | 1206 | SPSA只支持一维的输入参数。 1207 | 1208 | Example:: 1209 | 1210 | from pyvqnet.qnn import AngleEmbeddingCircuit, expval, QpandaQCircuitVQCLayerLite, SPSA 1211 | from pyvqnet.qnn.template import BasicEntanglerTemplate 1212 | import pyqpanda as pq 1213 | from pyvqnet.nn.module import Module 1214 | #定义一个量子变分线路模型 1215 | class Model_spsa(Module): 1216 | def __init__(self): 1217 | super(Model_spsa, self).__init__() 1218 | self.qvc = QpandaQCircuitVQCLayerLite(layer_fn_spsa_pq, 3) 1219 | 1220 | def forward(self, x): 1221 | y = self.qvc(x) 1222 | return y 1223 | 1224 | #本例线路是最小化该VQC的期望值 1225 | def layer_fn_spsa_pq(input, weights): 1226 | num_of_qubits = 1 1227 | 1228 | machine = pq.CPUQVM() 1229 | machine.init_qvm() 1230 | qubits = machine.qAlloc_many(num_of_qubits) 1231 | c1 = AngleEmbeddingCircuit(input, qubits) 1232 | weights =weights.reshape([4,1]) 1233 | bc_class = BasicEntanglerTemplate(weights, 1) 1234 | c2 = bc_class.create_circuit(qubits) 1235 | m_prog = pq.QProg() 1236 | m_prog.insert(c1) 1237 | m_prog.insert(c2) 1238 | pauli_dict = {'Z0': 1} 1239 | exp2 = expval(machine, m_prog, pauli_dict, qubits) 1240 | 1241 | return exp2 1242 | 1243 | model = Model_spsa() 1244 | #定义一个SPSA优化器 1245 | optimizer = SPSA(maxiter=20, 1246 | init_para=model.parameters(), 1247 | model=model, 1248 | ) 1249 | 1250 | 1251 | .. py:method:: pyvqnet.qnn.SPSA._step(input_data) 1252 | 1253 | 优化 sapa 优化器 1254 | 1255 | :param input_data: 输入训练数据QTensor 1256 | :return: 1257 | 1258 | train_para:最终参数。 1259 | 1260 | theta_best:最后 `last_avg` 次优化后的平均参数。 1261 | 1262 | Example:: 1263 | 1264 | import numpy as np 1265 | import pyqpanda as pq 1266 | 1267 | import sys 1268 | sys.path.insert(0, "../") 1269 | import pyvqnet 1270 | 1271 | from pyvqnet.nn.module import Module 1272 | from pyvqnet.qnn import SPSA 1273 | from pyvqnet.tensor.tensor import QTensor 1274 | from pyvqnet.qnn import AngleEmbeddingCircuit, expval, QpandaQCircuitVQCLayerLite, expval 1275 | from pyvqnet.qnn.template import BasicEntanglerTemplate 1276 | 1277 | #定义一个量子变分线路模型 1278 | class Model_spsa(Module): 1279 | def __init__(self): 1280 | super(Model_spsa, self).__init__() 1281 | self.qvc = QpandaQCircuitVQCLayerLite(layer_fn_spsa_pq, 3) 1282 | 1283 | def forward(self, x): 1284 | y = self.qvc(x) 1285 | return y 1286 | 1287 | #本例线路是最小化该VQC的期望值 1288 | def layer_fn_spsa_pq(input, weights): 1289 | num_of_qubits = 1 1290 | 1291 | machine = pq.CPUQVM() 1292 | machine.init_qvm() 1293 | qubits = machine.qAlloc_many(num_of_qubits) 1294 | c1 = AngleEmbeddingCircuit(input, qubits) 1295 | weights =weights.reshape([4,1]) 1296 | bc_class = BasicEntanglerTemplate(weights, 1) 1297 | c2 = bc_class.create_circuit(qubits) 1298 | m_prog = pq.QProg() 1299 | m_prog.insert(c1) 1300 | m_prog.insert(c2) 1301 | pauli_dict = {'Z0': 1} 1302 | exp2 = expval(machine, m_prog, pauli_dict, qubits) 1303 | 1304 | return exp2 1305 | 1306 | model = Model_spsa() 1307 | #定义一个SPSA优化器 1308 | optimizer = SPSA(maxiter=20, 1309 | init_para=model.parameters(), 1310 | model=model, 1311 | ) 1312 | #初始化参数 1313 | data = QTensor(np.array([[0.27507603]])) 1314 | p = model.parameters() 1315 | p[0].data = pyvqnet._core.Tensor( np.array([3.97507603, 3.12950603, 1.00854038, 1316 | 1.25907603])) 1317 | #调用SPSA进行迭代优化 1318 | optimizer._step(input_data=data) 1319 | 1320 | #计算优化后的VQC期望值 1321 | y = model(data) 1322 | print(y) 1323 | -------------------------------------------------------------------------------- /source/rst/qnn_pq3.rst: -------------------------------------------------------------------------------- 1 | 使用pyqpanda3量子机器学习模块 2 | ################################# 3 | 4 | .. warning:: 5 | 6 | 以下接口的量子计算部分使用pyqpanda3 https://qcloud.originqc.com.cn/document/qpanda-3/index.html。 7 | 8 | 9 | 量子计算层 10 | *********************************** 11 | 12 | .. _QuantumLayer_pq3: 13 | 14 | QuantumLayer 15 | ============================ 16 | 17 | 如您熟悉pyqpanda3语法,可以使用该接口QuantumLayer,自定义pyqpanda3模拟器进行计算。 18 | 19 | .. py:class:: pyvqnet.qnn.pq3.quantumlayer.QuantumLayer(qprog_with_measure,para_num,diff_method:str = "parameter_shift",delta:float = 0.01,dtype=None,name="") 20 | 21 | 变分量子层的抽象计算模块。对一个参数化的量子线路使用pyqpanda3进行仿真,得到测量结果。该变分量子层继承了VQNet框架的梯度计算模块,可以使用参数漂移法等计算线路参数的梯度,训练变分量子线路模型或将变分量子线路嵌入混合量子和经典模型。 22 | 23 | :param qprog_with_measure: 用pyQPand构建的量子线路运行和测量函数。 24 | :param para_num: `int` - 参数个数。 25 | :param diff_method: 求解量子线路参数梯度的方法,“参数位移”或“有限差分”,默认参数偏移。 26 | :param delta: 有限差分计算梯度时的 \delta。 27 | :param dtype: 参数的数据类型,defaults:None,使用默认数据类型:kfloat32,代表32位浮点数。 28 | :param name: 这个模块的名字, 默认为""。 29 | 30 | :return: 一个可以计算量子线路的模块。 31 | 32 | .. note:: 33 | qprog_with_measure是pyQPanda中定义的量子线路函数 :https://qcloud.originqc.com.cn/document/qpanda-3/dc/d12/tutorial_quantum_program.html。 34 | 35 | 此函数必须包含输入和参数两个参数作为函数入参(即使某个参数未实际使用),输出为线路的测量结果或者期望值(需要为np.ndarray或包含数值的列表),否则无法在QpandaQCircuitVQCLayerLite中正常运行。 36 | 37 | 38 | 量子线路函数 qprog_with_measure (input,param)的使用可参考下面的例子。 39 | 40 | `input`: 输入一维经典数据。如果没有,输入 None。 41 | 42 | `param`: 输入一维的变分量子线路的待训练参数。 43 | 44 | .. note:: 45 | 46 | 该类具有别名 `QuantumLayerV2`, `QpandaQCircuitVQCLayerLite`。 47 | 48 | 49 | .. note:: 50 | 51 | 该类计算梯度需要额外使用pyqpanda3进行线路计算个数与参数个数、数据个数、数据维度的乘积线性相关。 52 | 53 | 54 | Example:: 55 | 56 | from pyvqnet.qnn.pq3.measure import ProbsMeasure 57 | from pyvqnet.qnn.pq3.quantumlayer import QuantumLayer 58 | from pyvqnet.tensor import QTensor,ones 59 | import pyqpanda3.core as pq 60 | def pqctest (input,param): 61 | num_of_qubits = 4 62 | 63 | m_machine = pq.CPUQVM() 64 | 65 | qubits = range(num_of_qubits) 66 | 67 | circuit = pq.QCircuit() 68 | circuit<`_ 。 585 | 586 | :param input_channels: `int` - 输入通道数。 587 | :param output_channels: `int` - 输出通道数。 588 | :param quantum_number: `int` - 单个内核的大小。 589 | :param stride: `tuple` - 步长,默认为(1,1)。 590 | :param padding: `tuple` - 填充,默认为(0,0)。 591 | :param kernel_initializer: `callable` - 默认为正态分布。 592 | :param machine: `str` - 使用的虚拟机,默认使用CPU模拟。 593 | :param dtype: 参数的数据类型,defaults:None,使用默认数据类型:kfloat32,代表32位浮点数。 594 | :param name: 这个模块的名字, 默认为""。 595 | 596 | 597 | :return: 量子卷积层。 598 | 599 | Example:: 600 | 601 | from pyvqnet.tensor import tensor 602 | from pyvqnet.qnn.qcnn.qconv import QConv 603 | x = tensor.ones([1,3,4,4]) 604 | layer = QConv(input_channels=3, output_channels=2, quantum_number=4, stride=(2, 2)) 605 | y = layer(x) 606 | print(y) 607 | 608 | # [ 609 | # [[[-0.0889078, -0.0889078], 610 | # [-0.0889078, -0.0889078]], 611 | # [[0.7992646, 0.7992646], 612 | # [0.7992646, 0.7992646]]] 613 | # ] 614 | 615 | 616 | 617 | 量子逻辑门 618 | *********************************** 619 | 620 | 处理量子比特的方式就是量子逻辑门。 使用量子逻辑门,我们有意识的使量子态发生演化。量子逻辑门是构成量子算法的基础。 621 | 622 | 623 | 基本量子逻辑门 624 | ============================ 625 | 626 | 在VQNet中,我们使用本源量子自研的 `pyqpanda3 `_ 的各个逻辑门搭建量子线路,进行量子模拟。 627 | 当前pyQPanda支持的逻辑门可参考pyqpanda3 `量子逻辑门 `_ 部分的定义。 628 | 此外VQNet还封装了部分在量子机器学习中常用的量子逻辑门组合: 629 | 630 | 631 | .. _pq3_gate: 632 | 633 | BasicEmbeddingCircuit 634 | ============================ 635 | 636 | .. py:function:: pyvqnet.qnn.pq3.template.BasicEmbeddingCircuit(input_feat,qlist) 637 | 638 | 将n个二进制特征编码为n个量子比特的基态。 639 | 640 | 例如, 对于 ``features=([0, 1, 1])``, 在量子系统下其基态为 :math:`|011 \rangle`。 641 | 642 | :param input_feat: ``(n)`` 大小的二进制输入。 643 | :param qlist: 构建该模板线路量子比特。 644 | :return: 量子线路。 645 | 646 | Example:: 647 | 648 | from pyvqnet.qnn.pq3.template import BasicEmbeddingCircuit 649 | import pyqpanda3.core as pq 650 | from pyvqnet import tensor 651 | input_feat = tensor.QTensor([1,1,0]) 652 | 653 | qlist = range(3) 654 | circuit = BasicEmbeddingCircuit(input_feat,qlist) 655 | print(circuit) 656 | 657 | AngleEmbeddingCircuit 658 | ============================ 659 | 660 | .. py:function:: pyvqnet.qnn.pq3.template.AngleEmbeddingCircuit(input_feat,qubits,rotation:str='X') 661 | 662 | 将 :math:`N` 特征编码到 :math:`n` 量子比特的旋转角度中, 其中 :math:`N \leq n`。 663 | 664 | 旋转可以选择为 : 'X' , 'Y' , 'Z', 如 ``rotation`` 的参数定义为: 665 | 666 | * ``rotation='X'`` 将特征用作RX旋转的角度。 667 | 668 | * ``rotation='Y'`` 将特征用作RY旋转的角度。 669 | 670 | * ``rotation='Z'`` 将特征用作RZ旋转的角度。 671 | 672 | ``features`` 的长度必须小于或等于量子比特的数量。如果 ``features`` 中的长度少于量子比特,则线路不应用剩余的旋转门。 673 | 674 | :param input_feat: 表示参数的numpy数组。 675 | :param qubits: 量子比特索引。 676 | :param rotation: 使用什么旋转,默认为“X”。 677 | :return: 量子线路。 678 | 679 | Example:: 680 | 681 | from pyvqnet.qnn.pq3.template import AngleEmbeddingCircuit 682 | import numpy as np 683 | m_qlist = range(2) 684 | 685 | input_feat = np.array([2.2, 1]) 686 | C = AngleEmbeddingCircuit(input_feat,m_qlist,'X') 687 | print(C) 688 | C = AngleEmbeddingCircuit(input_feat,m_qlist,'Y') 689 | print(C) 690 | C = AngleEmbeddingCircuit(input_feat,m_qlist,'Z') 691 | print(C) 692 | 693 | 694 | IQPEmbeddingCircuits 695 | ============================ 696 | 697 | .. py:function:: pyvqnet.qnn.pq3.template.IQPEmbeddingCircuits(input_feat,qubits,rep:int = 1) 698 | 699 | 使用IQP线路的对角门将 :math:`n` 特征编码为 :math:`n` 量子比特。 700 | 701 | 编码是由 `Havlicek et al. (2018) `_ 提出。 702 | 703 | 通过指定 ``n_repeats`` ,可以重复基本IQP线路。 704 | 705 | :param input_feat: 表示参数的numpy数组。 706 | :param qubits: 量子比特索引列表。 707 | :param rep: 重复量子线路块,默认次数1。 708 | :return: 量子线路。 709 | 710 | Example:: 711 | 712 | import numpy as np 713 | from pyvqnet.qnn.pq3.template import IQPEmbeddingCircuits 714 | input_feat = np.arange(1,100) 715 | qlist = range(3) 716 | circuit = IQPEmbeddingCircuits(input_feat,qlist,rep = 3) 717 | print(circuit) 718 | 719 | RotCircuit 720 | ============================ 721 | 722 | .. py:function:: pyvqnet.qnn.pq3.template.RotCircuit(para,qubits) 723 | 724 | 任意单量子比特旋转。qlist的数量应该是1,参数的数量应该是3。 725 | 726 | .. math:: 727 | 728 | R(\phi,\theta,\omega) = RZ(\omega)RY(\theta)RZ(\phi)= \begin{bmatrix} 729 | e^{-i(\phi+\omega)/2}\cos(\theta/2) & -e^{i(\phi-\omega)/2}\sin(\theta/2) \\ 730 | e^{-i(\phi-\omega)/2}\sin(\theta/2) & e^{i(\phi+\omega)/2}\cos(\theta/2) 731 | \end{bmatrix}. 732 | 733 | 734 | :param para: 表示参数 :math:`[\phi, \theta, \omega]` 的numpy数组。 735 | :param qubits: 量子比特索引,只接受单个量子比特。 736 | :return: 量子线路。 737 | 738 | Example:: 739 | 740 | from pyvqnet.qnn.pq3.template import RotCircuit 741 | import pyqpanda3.core as pq 742 | from pyvqnet import tensor 743 | 744 | m_qlist = 1 745 | 746 | param =tensor.QTensor([3,4,5]) 747 | c = RotCircuit(param,m_qlist) 748 | print(c) 749 | 750 | 751 | CRotCircuit 752 | ============================ 753 | 754 | .. py:function:: pyvqnet.qnn.pq3.template.CRotCircuit(para,control_qubits,rot_qubits) 755 | 756 | 受控Rot操作符。 757 | 758 | .. math:: CR(\phi, \theta, \omega) = \begin{bmatrix} 759 | 1 & 0 & 0 & 0 \\ 760 | 0 & 1 & 0 & 0\\ 761 | 0 & 0 & e^{-i(\phi+\omega)/2}\cos(\theta/2) & -e^{i(\phi-\omega)/2}\sin(\theta/2)\\ 762 | 0 & 0 & e^{-i(\phi-\omega)/2}\sin(\theta/2) & e^{i(\phi+\omega)/2}\cos(\theta/2) 763 | \end{bmatrix}. 764 | 765 | :param para: 表示参数 :math:`[\phi, \theta, \omega]` 的numpy数组。 766 | :param control_qubits: 量子比特索引,量子比特的数量应为1。 767 | :param rot_qubits: Rot量子比特索引,量子比特的数量应为1。 768 | :return: 量子线路。 769 | 770 | Example:: 771 | 772 | from pyvqnet.qnn.pq3.template import CRotCircuit 773 | import pyqpanda3.core as pq 774 | import numpy as np 775 | m_qlist = range(1) 776 | control_qlist = [1] 777 | param = np.array([3,4,5]) 778 | cir = CRotCircuit(param,control_qlist,m_qlist) 779 | 780 | print(cir) 781 | 782 | 783 | CSWAPcircuit 784 | ============================ 785 | 786 | .. py:function:: pyvqnet.qnn.pq3.template.CSWAPcircuit(qubits) 787 | 788 | 受控SWAP线路。 789 | 790 | .. math:: CSWAP = \begin{bmatrix} 791 | 1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ 792 | 0 & 1 & 0 & 0 & 0 & 0 & 0 & 0 \\ 793 | 0 & 0 & 1 & 0 & 0 & 0 & 0 & 0 \\ 794 | 0 & 0 & 0 & 1 & 0 & 0 & 0 & 0 \\ 795 | 0 & 0 & 0 & 0 & 1 & 0 & 0 & 0 \\ 796 | 0 & 0 & 0 & 0 & 0 & 0 & 1 & 0 \\ 797 | 0 & 0 & 0 & 0 & 0 & 1 & 0 & 0 \\ 798 | 0 & 0 & 0 & 0 & 0 & 0 & 0 & 1 799 | \end{bmatrix}. 800 | 801 | .. note:: 提供的第一个量子比特对应于 **control qubit** 。 802 | 803 | :param qubits: 量子比特索引列表第一个量子比特是控制量子比特。qlist的长度必须为3。 804 | :return: 量子线路。 805 | 806 | Example:: 807 | 808 | from pyvqnet.qnn.pq3 import CSWAPcircuit 809 | import pyqpanda3.core as pq 810 | m_machine = pq.CPUQVM() 811 | 812 | m_qlist = range(3) 813 | 814 | c =CSWAPcircuit([m_qlist[1],m_qlist[2],m_qlist[0]]) 815 | print(c) 816 | 817 | Controlled_Hadamard 818 | ======================= 819 | 820 | .. py:function:: pyvqnet.qnn.pq3.template.Controlled_Hadamard(qubits) 821 | 822 | 受控Hadamard逻辑门 823 | 824 | .. math:: CH = \begin{bmatrix} 825 | 1 & 0 & 0 & 0 \\ 826 | 0 & 1 & 0 & 0 \\ 827 | 0 & 0 & \frac{1}{\sqrt{2}} & \frac{1}{\sqrt{2}} \\ 828 | 0 & 0 & \frac{1}{\sqrt{2}} & -\frac{1}{\sqrt{2}} 829 | \end{bmatrix}. 830 | 831 | :param qubits: 量子比特索引。 832 | 833 | Examples:: 834 | 835 | import pyqpanda3.core as pq 836 | 837 | machine = pq.CPUQVM() 838 | 839 | qubits =range(2) 840 | from pyvqnet.qnn.pq3 import Controlled_Hadamard 841 | 842 | cir = Controlled_Hadamard(qubits) 843 | print(cir) 844 | 845 | CCZ 846 | ============== 847 | 848 | .. py:function:: pyvqnet.qnn.pq3.template.CCZ(qubits) 849 | 850 | 受控-受控-Z (controlled-controlled-Z) 逻辑门。 851 | 852 | .. math:: 853 | 854 | CCZ = 855 | \begin{pmatrix} 856 | 1 & 0 & 0 & 0 & 0 & 0 & 0 & 0\\ 857 | 0 & 1 & 0 & 0 & 0 & 0 & 0 & 0\\ 858 | 0 & 0 & 1 & 0 & 0 & 0 & 0 & 0\\ 859 | 0 & 0 & 0 & 1 & 0 & 0 & 0 & 0\\ 860 | 0 & 0 & 0 & 0 & 1 & 0 & 0 & 0\\ 861 | 0 & 0 & 0 & 0 & 0 & 1 & 0 & 0\\ 862 | 0 & 0 & 0 & 0 & 0 & 0 & 1 & 0\\ 863 | 0 & 0 & 0 & 0 & 0 & 0 & 0 & -1 864 | \end{pmatrix} 865 | 866 | :param qubits: 量子比特索引。 867 | 868 | :return: 869 | pyqpanda QCircuit 870 | 871 | Example:: 872 | 873 | import pyqpanda3.core as pq 874 | 875 | machine = pq.CPUQVM() 876 | 877 | qubits = range(3) 878 | from pyvqnet.qnn.pq3 import CCZ 879 | 880 | cir = CCZ(qubits) 881 | 882 | 883 | FermionicSingleExcitation 884 | ============================ 885 | 886 | .. py:function:: pyvqnet.qnn.pq3.template.FermionicSingleExcitation(weight, wires, qubits) 887 | 888 | 对泡利矩阵的张量积求幂的耦合簇单激励算子。矩阵形式下式给出: 889 | 890 | .. math:: 891 | 892 | \hat{U}_{pr}(\theta) = \mathrm{exp} \{ \theta_{pr} (\hat{c}_p^\dagger \hat{c}_r 893 | -\mathrm{H.c.}) \}, 894 | 895 | :param weight: 量子比特 p 上的变参. 896 | :param wires: 表示区间[r, p]中的量子比特索引子集。最小长度必须为2。第一索引值被解释为r,最后一个索引值被解释为p。 897 | 中间的索引被CNOT门作用,以计算量子位集的奇偶校验。 898 | :param qubits: 量子比特索引。 899 | 900 | :return: 901 | pyqpanda QCircuit 902 | 903 | Examples:: 904 | 905 | from pyvqnet.qnn.pq3 import FermionicSingleExcitation, expval 906 | 907 | weight = 0.5 908 | import pyqpanda3.core as pq 909 | machine = pq.CPUQVM() 910 | 911 | qlists = range(3) 912 | 913 | cir = FermionicSingleExcitation(weight, [1, 0, 2], qlists) 914 | 915 | 916 | 917 | FermionicDoubleExcitation 918 | ============================ 919 | 920 | .. py:function:: pyvqnet.qnn.pq3.template.FermionicDoubleExcitation(weight, wires1, wires2, qubits) 921 | 922 | 对泡利矩阵的张量积求幂的耦合聚类双激励算子,矩阵形式由下式给出: 923 | 924 | .. math:: 925 | 926 | \hat{U}_{pqrs}(\theta) = \mathrm{exp} \{ \theta (\hat{c}_p^\dagger \hat{c}_q^\dagger 927 | \hat{c}_r \hat{c}_s - \mathrm{H.c.}) \}, 928 | 929 | 其中 :math:`\hat{c}` 和 :math:`\hat{c}^\dagger` 是费米子湮灭和 930 | 创建运算符和索引 :math:`r, s` 和 :math:`p, q` 在占用的和 931 | 分别为空分子轨道。 使用 `Jordan-Wigner 变换 932 | `_ 上面定义的费米子算子可以写成 933 | 根据 Pauli 矩阵(有关更多详细信息,请参见 934 | `arXiv:1805.04340 `_) 935 | 936 | .. math:: 937 | 938 | \hat{U}_{pqrs}(\theta) = \mathrm{exp} \Big\{ 939 | \frac{i\theta}{8} \bigotimes_{b=s+1}^{r-1} \hat{Z}_b \bigotimes_{a=q+1}^{p-1} 940 | \hat{Z}_a (\hat{X}_s \hat{X}_r \hat{Y}_q \hat{X}_p + 941 | \hat{Y}_s \hat{X}_r \hat{Y}_q \hat{Y}_p +\\ \hat{X}_s \hat{Y}_r \hat{Y}_q \hat{Y}_p + 942 | \hat{X}_s \hat{X}_r \hat{X}_q \hat{Y}_p - \mathrm{H.c.} ) \Big\} 943 | 944 | :param weight: 可变参数 945 | :param wires1: 代表的量子比特的索引列表区间 [s, r] 中占据量子比特的子集。第一个索引被解释为 s,最后一索引被解释为 r。 CNOT 门对中间的索引进行操作,以计算一组量子位的奇偶性。 946 | :param wires2: 代表的量子比特的索引列表区间 [q, p] 中占据量子比特的子集。第一根索引被解释为 q,最后一索引被解释为 p。 CNOT 门对中间的索引进行操作,以计算一组量子位的奇偶性。 947 | :param qubits: 量子比特索引。 948 | 949 | :return: 950 | pyqpanda QCircuit 951 | 952 | Examples:: 953 | 954 | import pyqpanda3.core as pq 955 | from pyvqnet.qnn.pq3 import FermionicDoubleExcitation, expval 956 | machine = pq.CPUQVM() 957 | 958 | qlists = range(5) 959 | weight = 1.5 960 | cir = FermionicDoubleExcitation(weight, 961 | wires1=[0, 1], 962 | wires2=[2, 3, 4], 963 | qubits=qlists) 964 | 965 | UCCSD 966 | ================== 967 | 968 | .. py:function:: pyvqnet.qnn.pq3.template.UCCSD(weights, wires, s_wires, d_wires, init_state, qubits) 969 | 970 | 实现酉耦合簇单激发和双激发拟设(UCCSD)。UCCSD 是 VQE 拟设,通常用于运行量子化学模拟。 971 | 972 | 在一阶 Trotter 近似内,UCCSD 酉函数由下式给出: 973 | 974 | .. math:: 975 | 976 | \hat{U}(\vec{\theta}) = 977 | \prod_{p > r} \mathrm{exp} \Big\{\theta_{pr} 978 | (\hat{c}_p^\dagger \hat{c}_r-\mathrm{H.c.}) \Big\} 979 | \prod_{p > q > r > s} \mathrm{exp} \Big\{\theta_{pqrs} 980 | (\hat{c}_p^\dagger \hat{c}_q^\dagger \hat{c}_r \hat{c}_s-\mathrm{H.c.}) \Big\} 981 | 982 | 其中 :math:`\hat{c}` 和 :math:`\hat{c}^\dagger` 是费米子湮灭和 983 | 创建运算符和索引 :math:`r, s` 和 :math:`p, q` 在占用的和 984 | 分别为空分子轨道。(更多细节见 985 | `arXiv:1805.04340 `_): 986 | 987 | 988 | :param weights: 包含参数的大小 ``(len(s_wires)+ len(d_wires))`` 张量 989 | :math:`\theta_{pr}` 和 :math:`\theta_{pqrs}` 输入 Z 旋转 990 | ``FermionicSingleExcitation`` 和 ``FermionicDoubleExcitation`` 。 991 | :param wires: 模板作用的量子比特索引 992 | :param s_wires: 包含量子比特索引的列表序列 ``[r,...,p]`` 993 | 由单一激发产生 994 | :math:`\vert r, p \rangle = \hat{c}_p^\dagger \hat{c}_r \vert \mathrm{HF} \rangle`, 995 | 其中 :math:`\vert \mathrm{HF} \rangle` 表示 Hartee-Fock 参考态。 996 | :param d_wires: 列表序列,每个列表包含两个列表 997 | 指定索引 ``[s, ...,r]`` 和 ``[q,..., p]`` 998 | 定义双激励 :math:`\vert s, r, q, p \rangle = \hat{c}_p^\dagger \hat{c}_q^\dagger \hat{c}_r\hat{c}_s \vert \mathrm{HF} \rangle` 。 999 | :param init_state: 长度 ``len(wires)`` occupation-number vector 表示 1000 | 高频状态。 ``init_state`` 在量子比特初始化状态。 1001 | :param qubits: 量子比特索引。 1002 | 1003 | Examples:: 1004 | 1005 | import pyqpanda3.core as pq 1006 | from pyvqnet.tensor import tensor 1007 | from pyvqnet.qnn.pq3 import UCCSD, expval 1008 | machine = pq.CPUQVM() 1009 | 1010 | qlists = range(6) 1011 | weight = tensor.zeros([8]) 1012 | cir = UCCSD(weight,wires = [0,1,2,3,4,5,6], 1013 | s_wires=[[0, 1, 2], [0, 1, 2, 3, 4], [1, 2, 3], [1, 2, 3, 4, 5]], 1014 | d_wires=[[[0, 1], [2, 3]], [[0, 1], [2, 3, 4, 5]], [[0, 1], [3, 4]], [[0, 1], [4, 5]]], 1015 | init_state=[1, 1, 0, 0, 0, 0], 1016 | qubits=qlists) 1017 | 1018 | 1019 | 1020 | QuantumPoolingCircuit 1021 | ============================ 1022 | 1023 | .. py:function:: pyvqnet.qnn.pq3.template.QuantumPoolingCircuit(sources_wires, sinks_wires, params,qubits) 1024 | 1025 | 对数据进行降采样的量子电路。 1026 | 1027 | 为了减少电路中的量子位数量,首先在系统中创建成对的量子位。在最初配对所有量子位之后,将广义2量子位酉元应用于每一对量子位上。并在应用这两个量子位酉元之后,在神经网络的其余部分忽略每对量子位中的一个量子位。 1028 | 1029 | :param sources_wires: 将被忽略的源量子位索引。 1030 | :param sinks_wires: 将保留的目标量子位索引。 1031 | :param params: 输入参数。 1032 | :param qubits: 量子比特索引。 1033 | 1034 | :return: 1035 | pyqpanda QCircuit 1036 | 1037 | Examples:: 1038 | 1039 | from pyvqnet.qnn.pq3.template import QuantumPoolingCircuit 1040 | import pyqpanda3.core as pq 1041 | from pyvqnet import tensor 1042 | 1043 | qlists = range(4) 1044 | p = tensor.full([6], 0.35) 1045 | cir = QuantumPoolingCircuit([0, 1], [2, 3], p, qlists) 1046 | print(cir) 1047 | 1048 | 常用量子线路组合 1049 | *********************************** 1050 | VQNet提供了量子机器学习研究中常用的一些量子线路 1051 | 1052 | 1053 | HardwareEfficientAnsatz 1054 | ============================ 1055 | 1056 | .. py:class:: pyvqnet.qnn.pq3.ansatz.HardwareEfficientAnsatz(qubits,single_rot_gate_list,entangle_gate="CNOT",entangle_rules='linear',depth=1) 1057 | 1058 | 论文介绍的Hardware Efficient Ansatz的实现: `Hardware-efficient Variational Quantum Eigensolver for Small Molecules `__ 。 1059 | 1060 | 通过其成员函数 ``create_ansatz`` 返回 `pyqpanda3` 的量子线路。 1061 | 1062 | :param qubits: 量子比特索引。 1063 | :param single_rot_gate_list: 单个量子位旋转门列表由一个或多个作用于每个量子位的旋转门构成。目前支持 Rx、Ry、Rz。 1064 | :param entangle_gate: 非参数化纠缠门。支持CNOT、CZ。默认: CNOT。 1065 | :param entangle_rules: 电路中如何使用纠缠门。 ``linear`` 意味着纠缠门将作用于每个相邻的量子位。 ``all`` 意味着纠缠门将作用于任何两个 qbuits。 默认值:``linear``。 1066 | :param depth: ansatz 的深度,默认:1。 1067 | 1068 | Example:: 1069 | 1070 | import pyqpanda3.core as pq 1071 | from pyvqnet.tensor import QTensor,tensor 1072 | from pyvqnet.qnn.pq3.ansatz import HardwareEfficientAnsatz 1073 | machine = pq.CPUQVM() 1074 | 1075 | qlist = range(4) 1076 | c = HardwareEfficientAnsatz(qlist,["rx", "RY", "rz"], 1077 | entangle_gate="cnot", 1078 | entangle_rules="linear", 1079 | depth=1) 1080 | w = tensor.ones([c.get_para_num()]) 1081 | 1082 | cir = c.create_ansatz(w) 1083 | print(cir) 1084 | 1085 | BasicEntanglerTemplate 1086 | ============================ 1087 | 1088 | .. py:class:: pyvqnet.qnn.pq3.template.BasicEntanglerTemplate(weights=None, num_qubits=1, rotation=pyqpanda.RX) 1089 | 1090 | 由每个量子位上的单参数单量子位旋转组成的层,后跟一个闭合链或环组合的多个CNOT 门。 1091 | 1092 | CNOT 门环将每个量子位与其邻居连接起来,最后一个量子位被认为是第一个量子位的邻居。 1093 | 1094 | 层数 :math:`L` 由参数 ``weights`` 的第一个维度决定。 1095 | 1096 | 通过其成员函数 ``create_circuit`` 返回 `pyqpanda3` 的量子线路。 1097 | 1098 | :param weights: 形状的权重张量 `(L, len(qubits))`。 每个权重都用作量子含参门中的参数。默认值为: ``None`` ,则使用 `(1,1)` 正态分布随机数作为权重。 1099 | :param num_qubits: 量子比特数,默认为1。 1100 | :param rotation: 使用单参数单量子比特门,``pyqpanda.RX`` 被用作默认值。 1101 | 1102 | Example:: 1103 | 1104 | import pyqpanda3.core as pq 1105 | import numpy as np 1106 | from pyvqnet.qnn.pq3 import BasicEntanglerTemplate 1107 | np.random.seed(42) 1108 | num_qubits = 5 1109 | shape = [1, num_qubits] 1110 | weights = np.random.random(size=shape) 1111 | 1112 | machine = pq.CPUQVM() 1113 | 1114 | qubits = range(num_qubits) 1115 | 1116 | circuit = BasicEntanglerTemplate(weights=weights, num_qubits=num_qubits, rotation=pq.RZ) 1117 | result = circuit.compute_circuit() 1118 | cir = circuit.create_circuit(qubits) 1119 | circuit.print_circuit(qubits) 1120 | 1121 | 1122 | StronglyEntanglingTemplate 1123 | ============================ 1124 | 1125 | .. py:class:: pyvqnet.qnn.pq3.template.StronglyEntanglingTemplate(weights=None, num_qubits=1, ranges=None) 1126 | 1127 | 由单个量子比特旋转和纠缠器组成的层,参考 `circuit-centric classifier design `__ . 1128 | 1129 | 参数 ``weights`` 包含每一层的权重。 因此得出层数 :math:`L` 等于 ``weights`` 的第一个维度。 1130 | 1131 | 其包含2-qubit CNOT 门,作用于 :math:`M` 个量子比特上,:math:`i = 1,...,M`。 每个门的第二个量子位标号由公式 :math:`(i+r)\mod M` 给出,其中 :math:`r` 是一个称为 ``range`` 的超参数,并且 :math:`0 < r < M`。 1132 | 1133 | 通过其成员函数 ``create_circuit`` 返回 `pyqpanda3` 的量子线路。 1134 | 1135 | :param weights: 形状为 ``(L, M, 3)`` 的权重张量,默认值:None,使用形状为 ``(1,1,3)`` 的随机张量。 1136 | :param num_qubits: 量子比特数,默认值:1。 1137 | :param ranges: 确定每个后续层的范围超参数的序列; 默认值:None,使用 :math:`r=l \ mod M` 作为ranges 的值。 1138 | 1139 | Example:: 1140 | 1141 | from pyvqnet.qnn.pq3 import StronglyEntanglingTemplate 1142 | import pyqpanda3.core as pq 1143 | from pyvqnet.tensor import * 1144 | import numpy as np 1145 | np.random.seed(42) 1146 | num_qubits = 3 1147 | shape = [2, num_qubits, 3] 1148 | weights = np.random.random(size=shape) 1149 | 1150 | machine = pq.CPUQVM() 1151 | 1152 | qubits = range(num_qubits) 1153 | 1154 | circuit = StronglyEntanglingTemplate(weights, num_qubits=num_qubits ) 1155 | result = circuit.compute_circuit() 1156 | cir = circuit.create_circuit(qubits) 1157 | circuit.print_circuit(qubits) 1158 | 1159 | 1160 | ComplexEntangelingTemplate 1161 | ============================ 1162 | 1163 | .. py:class:: pyvqnet.qnn.pq3.ComplexEntangelingTemplate(weights,num_qubits,depth) 1164 | 1165 | 1166 | 由 U3 门和 CNOT 门组成的强纠缠层。 1167 | 此线路模板来自以下论文:https://arxiv.org/abs/1804.00633。 1168 | 1169 | 通过其成员函数 ``create_circuit`` 返回 `pyqpanda3` 的量子线路。 1170 | 1171 | :param weights: 参数,[depth,num_qubits,3]的形状 1172 | :param num_qubits: 量子比特数。 1173 | :param depth: 子电路的深度。 1174 | 1175 | Example:: 1176 | 1177 | from pyvqnet.qnn.pq3 import ComplexEntangelingTemplate 1178 | import pyqpanda3.core as pq 1179 | from pyvqnet.tensor import * 1180 | depth =3 1181 | num_qubits = 8 1182 | shape = [depth, num_qubits, 3] 1183 | weights = tensor.randn(shape) 1184 | 1185 | machine = pq.CPUQVM() 1186 | 1187 | qubits = range(num_qubits) 1188 | 1189 | circuit = ComplexEntangelingTemplate(weights, num_qubits=num_qubits,depth=depth) 1190 | result = circuit.create_circuit(qubits) 1191 | circuit.print_circuit(qubits) 1192 | 1193 | Quantum_Embedding 1194 | ============================ 1195 | 1196 | .. py:class:: pyvqnet.qnn.pq3.Quantum_Embedding(qubits, machine, num_repetitions_input, depth_input, num_unitary_layers, num_repetitions) 1197 | 1198 | 使用 RZ,RY,RZ 创建变分量子电路,将经典数据编码为量子态。 1199 | 参考 `Quantum embeddings for machine learning `_。 1200 | 在初始化该类后,其成员函数 ``compute_circuit`` 为运行函数,可作为参数输入 ``QpandaQCircuitVQCLayerLite`` 类构成量子机器学习模型的一层。 1201 | 1202 | :param qubits: 使用pyqpanda 申请的量子比特。 1203 | :param machine: 使用pyqpanda 申请的量子虚拟机。 1204 | :param num_repetitions_input: 在子模块中对输入进行编码的重复次数。 1205 | :param depth_input: 输入数据的特征维度。 1206 | :param num_unitary_layers: 每个子模块中变分量子门的重复次数。 1207 | :param num_repetitions: 子模块的重复次数。 1208 | 1209 | Example:: 1210 | 1211 | from pyvqnet.qnn.pq3 import QpandaQCircuitVQCLayerLite,Quantum_Embedding 1212 | from pyvqnet.tensor import tensor 1213 | import pyqpanda3.core as pq 1214 | depth_input = 2 1215 | num_repetitions = 2 1216 | num_repetitions_input = 2 1217 | num_unitary_layers = 2 1218 | 1219 | loacl_machine = pq.CPUQVM() 1220 | 1221 | nq = depth_input * num_repetitions_input 1222 | qubits = range(nq) 1223 | cubits = range(nq) 1224 | 1225 | data_in = tensor.ones([12, depth_input]) 1226 | data_in.requires_grad = True 1227 | 1228 | qe = Quantum_Embedding(nq, loacl_machine, num_repetitions_input, 1229 | depth_input, num_unitary_layers, num_repetitions) 1230 | qlayer = QpandaQCircuitVQCLayerLite(qe.compute_circuit, 1231 | qe.param_num) 1232 | 1233 | data_in.requires_grad = True 1234 | y = qlayer.forward(data_in) 1235 | y.backward() 1236 | print(data_in.grad) 1237 | 1238 | 1239 | 1240 | 对量子线路进行测量 1241 | *********************************** 1242 | 1243 | 1244 | expval 1245 | ============================ 1246 | 1247 | .. py:function:: pyvqnet.qnn.pq3.measure.expval(machine,prog,pauli_str_dict) 1248 | 1249 | 提供的哈密顿量观测值的期望值。 1250 | 1251 | 如果观测值是 :math:`0.7Z\otimes X\otimes I+0.2I\otimes Z\otimes I`, 1252 | 那么 Hamiltonian dict 将是 ``{{'Z0, X1':0.7} ,{'Z1':0.2}}`` 。 1253 | 1254 | expval api现在支持pyqpanda3 的模拟器 。 1255 | 1256 | :param machine: 由pyQPanda创建的量子虚拟机。 1257 | :param prog: pyQPanda创建的量子工程。 1258 | :param pauli_str_dict: 哈密顿量观测值。 1259 | 1260 | :return: 期望值。 1261 | 1262 | 1263 | Example:: 1264 | 1265 | import pyqpanda3.core as pq 1266 | from pyvqnet.qnn.pq3.measure import expval 1267 | input = [0.56, 0.1] 1268 | m_machine = pq.CPUQVM() 1269 | 1270 | m_qlist = range(3) 1271 | cir = pq.QCircuit(3) 1272 | cir<111 开始。 1379 | :param indices: 所考虑子系统中的量子比特索引列表。 1380 | :return: 大小为“(2**len(indices), 2**len(indices))”的密度矩阵。 1381 | 1382 | Example:: 1383 | 1384 | from pyvqnet.qnn.pq3.measure import DensityMatrixFromQstate 1385 | qstate = [(0.9306699299765968+0j), (0.18865613455240968+0j), (0.1886561345524097+0j), (0.03824249173404786+0j), -0.048171819846746615j, -0.00976491131165138j, -0.23763904794287155j, -0.048171819846746615j] 1386 | print(DensityMatrixFromQstate(qstate,[0,1])) 1387 | # [[0.86846704+0.j 0.1870241 +0.j 0.17604699+0.j 0.03791166+0.j] 1388 | # [0.1870241 +0.j 0.09206345+0.j 0.03791166+0.j 0.01866219+0.j] 1389 | # [0.17604699+0.j 0.03791166+0.j 0.03568649+0.j 0.00768507+0.j] 1390 | # [0.03791166+0.j 0.01866219+0.j 0.00768507+0.j 0.00378301+0.j]] 1391 | 1392 | VN_Entropy 1393 | ============== 1394 | .. py:function:: pyvqnet.qnn.pq3.measure.VN_Entropy(state, indices, base=None) 1395 | 1396 | 根据给定 qubits 列表上的状态向量计算Von Neumann熵 。 1397 | 1398 | .. math:: 1399 | S( \rho ) = -\text{Tr}( \rho \log ( \rho )) 1400 | 1401 | :param state: 一维列表状态向量。 这个列表的大小应该是 ``(2**N,)`` 对于量子比特个数 ``N`` ,qstate 应该从 000 ->111 开始。 1402 | :param indices: 所考虑子系统中的量子比特索引列表。 1403 | :param base: 对数的底。 如果没有,则使用自然对数。 1404 | 1405 | :return: 冯诺依曼熵的浮点值. 1406 | 1407 | Example:: 1408 | 1409 | from pyvqnet.qnn.pq3.measure import VN_Entropy 1410 | qstate = [(0.9022961387408862 + 0j), -0.06676534788028633j, 1411 | (0.18290448232350312 + 0j), -0.3293638014158896j, 1412 | (0.03707657410649268 + 0j), -0.06676534788028635j, 1413 | (0.18290448232350312 + 0j), -0.013534006039561714j] 1414 | print(VN_Entropy(qstate, [0, 1])) 1415 | #0.14592917648464448 1416 | 1417 | Mutal_Info 1418 | ============== 1419 | .. py:function:: pyvqnet.qnn.pq3.measure.Mutal_Info(state, indices0, indices1, base=None) 1420 | 1421 | 根据给定两个子 qubits 列表上的状态向量计算互信息 。 1422 | 1423 | .. math:: 1424 | 1425 | I(A, B) = S(\rho^A) + S(\rho^B) - S(\rho^{AB}) 1426 | 1427 | 其中 :math:`S` 是冯诺依曼熵。 1428 | 1429 | 互信息是衡量两个子系统之间相关性的指标。更具体地说,它量化了一个系统通过测量另一个系统获得的信息量。 1430 | 1431 | 每个状态都可以作为计算基础中的状态向量给出。 1432 | 1433 | :param state: 一维列表状态向量。 这个列表的大小应该是 ``(2**N,)`` 对于量子比特个数 ``N`` , qstate 应该从 000 ->111 开始。 1434 | :param indices0: 第一个子系统中的量子比特索引列表。 1435 | :param indices1: 第二个子系统中的量子比特索引列表。 1436 | :param base: 对数的底。 如果为None,则使用自然对数,默认为None。 1437 | 1438 | :return: 子系统之间的相互信息 1439 | 1440 | Example:: 1441 | 1442 | from pyvqnet.qnn.pq3.measure import Mutal_Info 1443 | qstate = [(0.9022961387408862 + 0j), -0.06676534788028633j, 1444 | (0.18290448232350312 + 0j), -0.3293638014158896j, 1445 | (0.03707657410649268 + 0j), -0.06676534788028635j, 1446 | (0.18290448232350312 + 0j), -0.013534006039561714j] 1447 | print(Mutal_Info(qstate, [0], [2], 2)) 1448 | #0.13763425302805887 1449 | 1450 | 1451 | 1452 | Purity 1453 | ========================= 1454 | 1455 | .. py:function:: pyvqnet.qnn.pq3.measure.Purity(state, qubits_idx) 1456 | 1457 | 1458 | 从态矢中计算特定量子比特上的纯度。 1459 | 1460 | .. math:: 1461 | \gamma = \text{Tr}(\rho^2) 1462 | 1463 | 式中 :math:`\rho` 为密度矩阵。标准化量子态的纯度满足 :math:`\frac{1}{d} \leq \gamma \leq 1` , 1464 | 其中 :math:`d` 是希尔伯特空间的维数。 1465 | 纯态的纯度是1。 1466 | 1467 | :param state: 从pyqpanda get_qstate()获取的量子态 1468 | :param qubits_idx: 要计算纯度的量子比特位索引 1469 | 1470 | :return: 1471 | 纯度 1472 | 1473 | Examples:: 1474 | 1475 | from pyvqnet.qnn.pq3.measure import Purity 1476 | qstate = [(0.9306699299765968 + 0j), (0.18865613455240968 + 0j), 1477 | (0.1886561345524097 + 0j), (0.03824249173404786 + 0j), 1478 | -0.048171819846746615j, -0.00976491131165138j, -0.23763904794287155j, 1479 | -0.048171819846746615j] 1480 | pp = Purity(qstate, [1]) 1481 | print(pp) 1482 | #0.902503479761881 1483 | -------------------------------------------------------------------------------- /source/rst/utils.rst: -------------------------------------------------------------------------------- 1 | 实用函数 2 | ###################### 3 | 4 | 5 | 6 | 随机种子生成 7 | ******************************************* 8 | 9 | set_random_seed 10 | ============================== 11 | 12 | .. py:function:: pyvqnet.utils.set_random_seed(seed) 13 | 14 | 设定全局随机种子。 15 | 16 | :param seed: 随机数种子。 17 | 18 | .. note:: 19 | 当指定固定随机数种子时,随机分布将依据随机种子产生固定的伪随机分布。 20 | 影响包括: `tensor.randu` , `tensor.randn` ,含参经典神经网络以及量子计算层的参数初始化。 21 | 22 | Example:: 23 | 24 | import pyvqnet.tensor as tensor 25 | from pyvqnet.utils import get_random_seed, set_random_seed 26 | 27 | set_random_seed(256) 28 | 29 | 30 | rn = tensor.randn([2, 3]) 31 | print(rn) 32 | rn = tensor.randn([2, 3]) 33 | print(rn) 34 | rn = tensor.randu([2, 3]) 35 | print(rn) 36 | rn = tensor.randu([2, 3]) 37 | print(rn) 38 | 39 | print("########################################################") 40 | from pyvqnet.nn.parameter import Parameter 41 | from pyvqnet.utils.initializer import he_normal, he_uniform, xavier_normal, xavier_uniform, uniform, quantum_uniform, normal 42 | print(Parameter(shape=[2, 3], initializer=he_normal)) 43 | print(Parameter(shape=[2, 3], initializer=he_uniform)) 44 | print(Parameter(shape=[2, 3], initializer=xavier_normal)) 45 | print(Parameter(shape=[2, 3], initializer=xavier_uniform)) 46 | print(Parameter(shape=[2, 3], initializer=uniform)) 47 | print(Parameter(shape=[2, 3], initializer=quantum_uniform)) 48 | print(Parameter(shape=[2, 3], initializer=normal)) 49 | # [ 50 | # [-1.2093765, 1.1265280, 0.0796480], 51 | # [0.2420146, 1.2623813, 0.2844022] 52 | # ] 53 | # [ 54 | # [-1.2093765, 1.1265280, 0.0796480], 55 | # [0.2420146, 1.2623813, 0.2844022] 56 | # ] 57 | # [ 58 | # [0.3151870, 0.6721524, 0.0416874], 59 | # [0.8232620, 0.6537889, 0.9672953] 60 | # ] 61 | # [ 62 | # [0.3151870, 0.6721524, 0.0416874], 63 | # [0.8232620, 0.6537889, 0.9672953] 64 | # ] 65 | # ######################################################## 66 | # [ 67 | # [-0.9874518, 0.9198063, 0.0650323], 68 | # [0.1976041, 1.0307300, 0.2322134] 69 | # ] 70 | # [ 71 | # [-0.2134037, 0.1987845, -0.5292138], 72 | # [0.3732708, 0.1775801, 0.5395861] 73 | # ] 74 | # [ 75 | # [-0.7648768, 0.7124789, 0.0503738], 76 | # [0.1530635, 0.7984000, 0.1798717] 77 | # ] 78 | # [ 79 | # [-0.4049051, 0.3771670, -1.0041126], 80 | # [0.7082316, 0.3369346, 1.0237927] 81 | # ] 82 | # [ 83 | # [0.3151870, 0.6721524, 0.0416874], 84 | # [0.8232620, 0.6537889, 0.9672953] 85 | # ] 86 | # [ 87 | # [1.9803783, 4.2232580, 0.2619299], 88 | # [5.1727076, 4.1078768, 6.0776958] 89 | # ] 90 | # [ 91 | # [-1.2093765, 1.1265280, 0.0796480], 92 | # [0.2420146, 1.2623813, 0.2844022] 93 | # ] 94 | 95 | get_random_seed 96 | ============================== 97 | 98 | .. py:function:: pyvqnet.utils.get_random_seed() 99 | 100 | 获取当前随机数种子。 101 | 102 | Example:: 103 | 104 | import pyvqnet.tensor as tensor 105 | from pyvqnet.utils import get_random_seed, set_random_seed 106 | 107 | set_random_seed(256) 108 | print(get_random_seed()) 109 | #256 110 | 111 | --------------------------------------------------------------------------------