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.

tensorflow_quantum_grad.py 3.9 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  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 tensorflow quantum."""
  16. import time
  17. import numpy as np
  18. import tensorflow as tf
  19. from _parse_args import parser
  20. args = parser.parse_args()
  21. tf.config.threading.set_intra_op_parallelism_threads(args.omp_num_threads)
  22. import tensorflow_quantum as tfq
  23. import cirq
  24. import sympy
  25. import tqdm
  26. def convert_to_circuit(image):
  27. """Encode truncated classical image into quantum datapoint."""
  28. values = np.ndarray.flatten(image)
  29. qubits = cirq.GridQubit.rect(4, 4)
  30. circuit = cirq.Circuit()
  31. for i, value in enumerate(values):
  32. if value:
  33. circuit.append(cirq.X(qubits[i]))
  34. return circuit
  35. class CircuitLayerBuilder():
  36. """CircuitLayerBuilder"""
  37. def __init__(self, data_qubits, readout):
  38. self.data_qubits = data_qubits
  39. self.readout = readout
  40. def add_layer(self, circuit, gate, prefix):
  41. for i, qubit in enumerate(self.data_qubits):
  42. symbol = sympy.Symbol(prefix + '-' + str(i))
  43. circuit.append(gate(qubit, self.readout)**symbol)
  44. def create_quantum_model():
  45. """Create a QNN model circuit and readout operation to go along with it."""
  46. data_qubits = cirq.GridQubit.rect(4, 4) # a 4x4 grid.
  47. readout = cirq.GridQubit(-1, -1) # a single qubit at [-1,-1]
  48. circuit = cirq.Circuit()
  49. # Prepare the readout qubit.
  50. circuit.append(cirq.X(readout))
  51. circuit.append(cirq.H(readout))
  52. builder = CircuitLayerBuilder(data_qubits=data_qubits, readout=readout)
  53. # Then add layers (experiment by adding more).
  54. builder.add_layer(circuit, cirq.XX, "xx1")
  55. builder.add_layer(circuit, cirq.ZZ, "zz1")
  56. # Finally, prepare the readout qubit.
  57. circuit.append(cirq.H(readout))
  58. return circuit, cirq.Z(readout)
  59. n_qubits = 17
  60. data = np.load('./mnist_resize.npz')
  61. x_train_bin, y_train_nocon, x_test_bin, y_test = data['arr_0'], data[
  62. 'arr_1'], data['arr_2'], data['arr_3']
  63. x_train_circ = [convert_to_circuit(x) for x in x_train_bin]
  64. x_test_circ = [convert_to_circuit(x) for x in x_test_bin]
  65. model_circuit, model_readout = create_quantum_model()
  66. names = sorted(list(model_circuit._parameter_names_()))
  67. init = np.random.random(len(names))[None, :].astype(np.float32)
  68. values_tensor = tf.convert_to_tensor(init)
  69. for c in x_train_circ:
  70. c.append(model_circuit)
  71. expectation_calculation = tfq.layers.Expectation(
  72. differentiator=tfq.differentiators.Adjoint())
  73. t0 = time.time()
  74. eval_time = []
  75. for circuit in tqdm.tqdm(x_train_circ[:args.num_sampling]):
  76. eval_time.append(time.time())
  77. with tf.GradientTape() as g:
  78. g.watch(values_tensor)
  79. exact_outputs = expectation_calculation(model_circuit,
  80. operators=model_readout,
  81. symbol_names=names,
  82. symbol_values=values_tensor)
  83. g.gradient(exact_outputs, values_tensor)
  84. eval_time[-1] = time.time() - eval_time[-1]
  85. eval_time = np.sort(eval_time[1:])
  86. t1 = time.time()
  87. print("Eval grad mean time:{}".format(eval_time[1:-1].mean()))
  88. print("Total time:{}".format(t1 - t0))

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