You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

mindquantum_grad.py 3.4 kB

5 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. # Copyright 2021 Huawei Technologies Co., Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. # ============================================================================
  15. """Benchmakr for gradient calculation of mindquantum."""
  16. import time
  17. import os
  18. from _parse_args import parser
  19. args = parser.parse_args()
  20. os.environ['OMP_NUM_THREADS'] = str(args.omp_num_threads)
  21. import numpy as np
  22. from mindquantum.ops import QubitOperator
  23. from mindquantum import Circuit, X, H, XX, ZZ, RX, Hamiltonian
  24. from mindquantum.nn import generate_pqc_operator
  25. import mindspore.context as context
  26. from mindspore import Tensor
  27. import tqdm
  28. context.set_context(mode=context.GRAPH_MODE, device_target="CPU")
  29. class CircuitLayerBuilder():
  30. """CircuitLayerBuilder"""
  31. def __init__(self, data_qubits, readout):
  32. self.data_qubits = data_qubits
  33. self.readout = readout
  34. def add_layer(self, circuit, gate, prefix):
  35. for i, qubit in enumerate(self.data_qubits):
  36. symbol = prefix + '-' + str(i)
  37. circuit.append(gate({symbol: np.pi / 2}).on([qubit, self.readout]))
  38. def convert_to_circuit(image, data_qubits=None):
  39. """convert_to_circuit"""
  40. values = np.ndarray.flatten(image)
  41. if data_qubits is None:
  42. data_qubits = range(len(values))
  43. c = Circuit()
  44. for i, value in enumerate(values[:len(data_qubits)]):
  45. if value:
  46. c += X.on(data_qubits[i])
  47. return c
  48. def create_quantum_model(n_qubits):
  49. """Create QNN."""
  50. data_qubits = range(1, n_qubits)
  51. readout = 0
  52. c = Circuit()
  53. c = c + X.on(readout) + H.on(readout)
  54. builder = CircuitLayerBuilder(data_qubits=data_qubits, readout=readout)
  55. builder.add_layer(c, XX, 'xx1')
  56. builder.add_layer(c, ZZ, 'zz1')
  57. c += H.on(readout)
  58. return c, Hamiltonian(QubitOperator('Z{}'.format(readout)))
  59. n_qubits = 17
  60. data = np.load('./mnist_resize.npz')
  61. x_train_bin, y_train_nocon, x_test_bin, y_test_nocon = data['arr_0'], data[
  62. 'arr_1'], data['arr_2'], data['arr_3']
  63. x_train_circ = [convert_to_circuit(x, range(1, n_qubits)) for x in x_train_bin]
  64. ansatz, ham = create_quantum_model(n_qubits)
  65. model_para_names = ansatz.parameter_resolver().para_name
  66. ops = generate_pqc_operator(model_para_names, ['null'],
  67. RX('null').on(0) + ansatz,
  68. ham,
  69. n_threads=args.parallel_worker)
  70. t0 = time.time()
  71. eval_time = []
  72. for x in tqdm.tqdm(x_train_circ[:args.num_sampling]):
  73. eval_time.append(time.time())
  74. ops(Tensor(np.random.normal(size=(1, 16)).astype(np.float32)),
  75. Tensor(np.array([0]).astype(np.float32)))
  76. eval_time[-1] = time.time() - eval_time[-1]
  77. eval_time = np.sort(eval_time[1:])
  78. t1 = time.time()
  79. print("Eval grad mean time:{}".format(eval_time[1:-1].mean()))
  80. print("Total time:{}".format(t1 - t0))

MindQuantum是结合MindSpore和HiQ开发的量子机器学习框架,支持多种量子神经网络的训练和推理。得益于华为HiQ团队的量子计算模拟器和MindSpore高性能自动微分能力,MindQuantum能够高效处理量子机器学习、量子化学模拟和量子优化等问题,性能达到业界TOP1,为广大的科研人员、老师和学生提供了快速设计和验证量子机器学习算法的高效平台。