Paddle_VQSD.py 4.0 KB
Newer Older
Q
Quleaf 已提交
1
# Copyright (c) 2020 Institute for Quantum Computing, Baidu Inc. All Rights Reserved.
Q
Quleaf 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""
Paddle_VQSD: To learn more about the functions and properties of this application,
you could check the corresponding Jupyter notebook under the Tutorial folder.
"""

import numpy
from paddle import fluid
from paddle_quantum.circuit import UAnsatz
Q
Quleaf 已提交
23
from paddle_quantum.utils import dagger
Q
Quleaf 已提交
24 25
from paddle.complex import matmul, trace
from paddle_quantum.VQSD.HGenerator import generate_rho_sigma
Q
Quleaf 已提交
26

Q
Quleaf 已提交
27
SEED = 14
Q
Quleaf 已提交
28 29 30 31 32 33 34 35 36 37

__all__ = [
    "U_theta",
    "Net",
    "Paddle_VQSD",
]


def U_theta(theta, N):
    """
Q
Quleaf 已提交
38
    Quantum Neural Network
Q
Quleaf 已提交
39 40
    """

Q
Quleaf 已提交
41
    # 按照量子比特数量/网络宽度初始化量子神经网络
Q
Quleaf 已提交
42 43
    cir = UAnsatz(N)

Q
Quleaf 已提交
44 45
    # 调用内置的量子神经网络模板
    cir.universal_2_qubit_gate(theta)
Q
Quleaf 已提交
46

Q
Quleaf 已提交
47 48
    # 返回量子神经网络所模拟的酉矩阵 U
    return cir.U
Q
Quleaf 已提交
49 50 51 52 53 54 55


class Net(fluid.dygraph.Layer):
    """
    Construct the model net
    """

Q
Quleaf 已提交
56 57
    def __init__(self, shape, rho, sigma, param_attr=fluid.initializer.Uniform(low=0.0, high=2 * numpy.pi, seed=SEED),
                 dtype='float64'):
Q
Quleaf 已提交
58 59
        super(Net, self).__init__()

Q
Quleaf 已提交
60
        # 将 Numpy array 转换成 Paddle 动态图模式中支持的 variable
Q
Quleaf 已提交
61 62 63
        self.rho = fluid.dygraph.to_variable(rho)
        self.sigma = fluid.dygraph.to_variable(sigma)

Q
Quleaf 已提交
64 65
        # 初始化 theta 参数列表,并用 [0, 2*pi] 的均匀分布来填充初始值
        self.theta = self.create_parameter(shape=shape, attr=param_attr, dtype=dtype, is_bias=False)
Q
Quleaf 已提交
66

Q
Quleaf 已提交
67
    # 定义损失函数和前向传播机制
Q
Quleaf 已提交
68
    def forward(self, N):
Q
Quleaf 已提交
69 70 71 72
        # 施加量子神经网络
        U = U_theta(self.theta, N)

        # rho_tilde 是将 U 作用在 rho 后得到的量子态 U*rho*U^dagger
Q
Quleaf 已提交
73
        rho_tilde = matmul(matmul(U, self.rho), dagger(U))
Q
Quleaf 已提交
74 75

        # 计算损失函数
Q
Quleaf 已提交
76 77 78 79 80
        loss = trace(matmul(self.sigma, rho_tilde))

        return loss.real, rho_tilde


Q
Quleaf 已提交
81 82
def Paddle_VQSD(rho, sigma, N=2, THETA_SIZE=15, ITR=50, LR=0.1):
    r"""
Q
Quleaf 已提交
83
    Paddle_VQSD
Q
Quleaf 已提交
84 85 86 87 88 89 90
    :param rho: 待对角化的量子态
    :param sigma: 输入用来标记的量子态sigma
    :param N: 量子神经网络的宽度
    :param THETA_SIZE: 量子神经网络中参数的数量
    :param ITR: 设置训练的总的迭代次数
    :param LR: 设置学习速率
    :return: 优化之后量子态rho接近对角态的numpy形式
Q
Quleaf 已提交
91
    """
Q
Quleaf 已提交
92
    # 初始化paddle动态图机制
Q
Quleaf 已提交
93
    with fluid.dygraph.guard():
Q
Quleaf 已提交
94
        # 确定网络的参数维度
Q
Quleaf 已提交
95 96
        net = Net(shape=[THETA_SIZE], rho=rho, sigma=sigma)

Q
Quleaf 已提交
97 98 99 100
        # 一般来说,我们利用Adam优化器来获得相对好的收敛,当然你可以改成SGD或者是RMS prop.
        opt = fluid.optimizer.AdagradOptimizer(learning_rate=LR, parameter_list=net.parameters())

        # 优化循环
Q
Quleaf 已提交
101 102
        for itr in range(ITR):

Q
Quleaf 已提交
103 104
            # 前向传播计算损失函数并返回估计的能谱
            loss, rho_tilde = net(N)
Q
Quleaf 已提交
105
            rho_tilde_np = rho_tilde.numpy()
Q
Quleaf 已提交
106 107

            # 在动态图机制下,反向传播极小化损失函数
Q
Quleaf 已提交
108 109 110 111
            loss.backward()
            opt.minimize(loss)
            net.clear_gradients()

Q
Quleaf 已提交
112 113 114
            # 打印训练结果
            if itr % 10 == 0:
                print('iter:', itr, 'loss:', '%.4f' % loss.numpy()[0])
Q
Quleaf 已提交
115
    return rho_tilde_np
Q
Quleaf 已提交
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131


def main():

    D = [0.5, 0.3, 0.1, 0.1]

    rho, sigma = generate_rho_sigma()

    rho_tilde_np = Paddle_VQSD(rho, sigma)

    print("The estimated spectrum is:", numpy.real(numpy.diag(rho_tilde_np)))
    print('The target spectrum is:', D)


if __name__ == '__main__':
    main()