From bf6bb6f2cf493c7a99cc1fa6ef69cff1a75c6e93 Mon Sep 17 00:00:00 2001 From: dsdsdshe Date: Thu, 16 May 2024 19:50:57 +0800 Subject: [PATCH 1/4] fix many hams bug in mqmatrix --- .../densitymatrix/densitymatrix_state.tpp | 8 +-- .../test_simulator/test_method_of_mqmatrix.py | 53 +++++++++++++++++++ 2 files changed, 57 insertions(+), 4 deletions(-) diff --git a/ccsrc/include/simulator/densitymatrix/densitymatrix_state.tpp b/ccsrc/include/simulator/densitymatrix/densitymatrix_state.tpp index 477cb6001..0ef16c5ea 100644 --- a/ccsrc/include/simulator/densitymatrix/densitymatrix_state.tpp +++ b/ccsrc/include/simulator/densitymatrix/densitymatrix_state.tpp @@ -781,8 +781,6 @@ auto DensityMatrixState::GetExpectationWithReversibleGradOneMulti( n_thread = n_hams; } VT f_and_g(n_hams, py_qs_datas_t((1 + p_map.size()), 0)); - derived_t sim_qs = *this; - sim_qs.ApplyCircuit(circ, pr); int n_group = n_hams / n_thread; if (n_hams % n_thread) { n_group += 1; @@ -793,6 +791,8 @@ auto DensityMatrixState::GetExpectationWithReversibleGradOneMulti( if (end > static_cast(n_hams)) { end = n_hams; } + derived_t sim_qs = *this; + sim_qs.ApplyCircuit(circ, pr); std::vector sim_hams(end - start); for (int j = start; j < end; j++) { f_and_g[j][0] = GetStateExpectation(sim_qs.qs, *hams[j], dim); @@ -946,8 +946,6 @@ auto DensityMatrixState::GetExpectationWithNoiseGradOneMulti( n_thread = n_hams; } VT f_and_g(n_hams, py_qs_datas_t((1 + p_map.size()), 0)); - derived_t sim_qs = *this; - sim_qs.ApplyCircuit(circ, pr); int n_group = n_hams / n_thread; if (n_hams % n_thread) { n_group += 1; @@ -958,6 +956,8 @@ auto DensityMatrixState::GetExpectationWithNoiseGradOneMulti( if (end > static_cast(n_hams)) { end = n_hams; } + derived_t sim_qs = *this; + sim_qs.ApplyCircuit(circ, pr); std::vector sim_hams(end - start); for (int j = start; j < end; j++) { f_and_g[j][0] = GetStateExpectation(sim_qs.qs, *hams[j], dim); diff --git a/tests/st/test_simulator/test_method_of_mqmatrix.py b/tests/st/test_simulator/test_method_of_mqmatrix.py index a737ba960..521f0710b 100644 --- a/tests/st/test_simulator/test_method_of_mqmatrix.py +++ b/tests/st/test_simulator/test_method_of_mqmatrix.py @@ -253,6 +253,59 @@ def test_get_expectation_with_grad(config): assert np.allclose(g, ref_g, atol=1e-4) +@pytest.mark.level0 +@pytest.mark.platform_x86_gpu_training +@pytest.mark.platform_x86_cpu +@pytest.mark.env_onecard +@pytest.mark.parametrize("config", list(filter(lambda x: x != 'stabilizer', SUPPORTED_SIMULATOR))) +def test_get_expectation_with_grad_batch_hams(config): + """ + Description: test get expectation with gradient with batch hams + Expectation: success. + """ + # pylint: disable=too-many-locals + virtual_qc, dtype = config + init_state_circ = UN(G.H, range(5)) + ansatz = mq.MaxCutAnsatz([(0, 1), (1, 2), (2, 3), (3, 4), (0, 4), (0, 2)], 4).circuit + circ = init_state_circ + ansatz + sim = Simulator(virtual_qc, 5, dtype=dtype) + + def numbers_to_binary_matrix(n): + max_bits = int(np.ceil(np.log2(n))) + binary_matrix = np.zeros((n, max_bits), dtype=int) + for i in range(n): + binary_representation = list(bin(i)[2:]) + binary_matrix[i, -len(binary_representation) :] = list(map(int, binary_representation)) + return binary_matrix + + qubit_num = 5 + output_dim = 2**qubit_num + max_bits = int(np.ceil(np.log2(output_dim))) + hams = [None] * output_dim + hams_sign = numbers_to_binary_matrix(output_dim) + for index in range(output_dim): + ham = QubitOperator('I0', 1) + for jndex in range(max_bits): + ham *= QubitOperator(f'I{jndex}', 0.5) + (-1) ** hams_sign[index, jndex] * QubitOperator(f'Z{jndex}', 0.5) + hams[index] = Hamiltonian(ham, dtype=dtype) + grad_ops = sim.get_expectation_with_grad(hams, circ) + rng = np.random.default_rng(10) + p0 = rng.random(size=len(circ.params_name)) * np.pi * 2 - np.pi + f, g = grad_ops(p0) + ref_f = [] + init_state = np.zeros(2**5) + init_state[0] = 1 + for ham in hams: + ref_f.append( + init_state.T.conj() + @ circ.hermitian().matrix(dict(zip(circ.params_name, p0))) + @ ham.hamiltonian.matrix(5) + @ circ.matrix(dict(zip(circ.params_name, p0))) + @ init_state + ) + assert np.allclose(f, ref_f, atol=1e-4) + + def three_qubits_dm_evolution_in_py(dm, g, dtype): """ Description: test three qubits density matrix -- Gitee From 810443e29fb8bb75e20e8da598fd4447db2cc34c Mon Sep 17 00:00:00 2001 From: dsdsdshe Date: Thu, 16 May 2024 20:27:39 +0800 Subject: [PATCH 2/4] fix reverse_qubits bug when add gate without order --- mindquantum/core/circuit/circuit.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/mindquantum/core/circuit/circuit.py b/mindquantum/core/circuit/circuit.py index 759e91321..72b49fe5e 100644 --- a/mindquantum/core/circuit/circuit.py +++ b/mindquantum/core/circuit/circuit.py @@ -1484,7 +1484,9 @@ class Circuit(list): # pylint: disable=too-many-instance-attributes,too-many-pu q3: ──┨ H ┠───■─────────── ┗━━━┛ """ - return apply(self, [self.n_qubits - 1 - i for i in self.all_qubits.keys()]) + all_qubits = self.all_qubits.keys() + all_qubits.sort() + return apply(self, [self.n_qubits - 1 - i for i in all_qubits]) def svg(self, style=None, width=None, scale=None): """ -- Gitee From 61420574618757651d8fb20e5fd825a64c6939fd Mon Sep 17 00:00:00 2001 From: dsdsdshe Date: Thu, 16 May 2024 20:36:44 +0800 Subject: [PATCH 3/4] make example code clear --- mindquantum/core/circuit/circuit.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/mindquantum/core/circuit/circuit.py b/mindquantum/core/circuit/circuit.py index 72b49fe5e..0612cef40 100644 --- a/mindquantum/core/circuit/circuit.py +++ b/mindquantum/core/circuit/circuit.py @@ -974,7 +974,8 @@ class Circuit(list): # pylint: disable=too-many-instance-attributes,too-many-pu >>> circ = UN(H, 3).x(0, 1).x(1, 2).measure_all() >>> circ += H.on(0) >>> circ += Measure('q0_1').on(0) - >>> circ.remove_measure_on_qubits(0) + >>> circ = circ.remove_measure_on_qubits(0) + >>> circ ┏━━━┓ ┏━━━┓ ┏━━━┓ q0: ──┨ H ┠─┨╺╋╸┠─┨ H ┠──────────── ┗━━━┛ ┗━┳━┛ ┗━━━┛ @@ -1473,7 +1474,8 @@ class Circuit(list): # pylint: disable=too-many-instance-attributes,too-many-pu ┏━━━┓ ┏━┻━┓ q3: ──┨ Y ┠───────┨╺╋╸┠─── ┗━━━┛ ┗━━━┛ - >>> circ.reverse_qubits() + >>> circ = circ.reverse_qubits() + >>> circ ┏━━━┓ ┏━━━┓ q0: ──┨ Y ┠───────┨╺╋╸┠─── ┗━━━┛ ┗━┳━┛ -- Gitee From 3ffd86492066cfc69100206f44c95ff6c01eff0e Mon Sep 17 00:00:00 2001 From: dsdsdshe Date: Fri, 17 May 2024 18:14:22 +0800 Subject: [PATCH 4/4] fix example code mistake --- mindquantum/core/operators/fermion_operator.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mindquantum/core/operators/fermion_operator.py b/mindquantum/core/operators/fermion_operator.py index 77593b027..d1ea5fac6 100644 --- a/mindquantum/core/operators/fermion_operator.py +++ b/mindquantum/core/operators/fermion_operator.py @@ -537,7 +537,7 @@ class FermionOperator(FermionOperator_): >>> from mindquantum.core.operators import FermionOperator >>> a = FermionOperator("0^ 1", {"a": 1 + 2j}) >>> a.hermitian() - (-1 + 2j)*a [1 0^] + (1 - 2j)*a [1^ 0] """ return FermionOperator(FermionOperator_.hermitian_conjugated(self), internal=True) -- Gitee