def __init__(self): super().__init__() self.conv1 = nn.Conv2d(1, 32, 3, 1) self.conv2 = nn.Conv2d(32, 64, 3, 1) self.dropout1 = nn.Dropout(0.25) self.dropout2 = nn.Dropout(0.5) self.fc1 = nn.Linear(9216, 128) self.fc2 = nn.Linear(128, 10) self.sigmoid = nn.Sigmoid() self.q_device0 = tq.QuantumDevice(n_wires=12) self.q_device0_1 = tq.QuantumDevice(n_wires=10) self.q_layer0 = tq.TrainableOpAll(n_gate=12, op=tq.RX) # self.q_layer1 = OpAll(n_gate=10, op=tq.RY) self.q_layer2 = tq.RX(has_params=True, trainable=False, init_params=-np.pi / 4) self.q_layer3 = tq.RZ(has_params=True, trainable=True) self.q_device1 = tq.QuantumDevice(n_wires=3) self.q_layer4 = tq.CY() self.q_layer5 = tq.Toffoli() self.q_layer6 = tq.PhaseShift(has_params=True, trainable=True) self.q_layer7 = tq.Rot(has_params=True, trainable=True) self.q_layer8 = tq.MultiRZ(has_params=True, trainable=True, n_wires=5) self.q_layer9 = tq.CRX(has_params=True, trainable=True) self.q_layer10 = tq.CRY(has_params=True, trainable=True) self.q_layer11 = tq.CRZ(has_params=True, trainable=True) self.q_layer12 = tq.CRot( has_params=True, trainable=False, init_params=[-np.pi / 4, np.pi / 4, np.pi / 2]) self.q_layer13 = tq.U1(has_params=True, trainable=False, init_params=np.pi / 7) self.q_layer14 = tq.U2(has_params=True, trainable=True, init_params=[np.pi / 7, np.pi / 8.8]) self.q_layer15 = tq.U3(has_params=True, trainable=True) self.q_layer16 = tq.QubitUnitary(has_params=True, trainable=False, init_params=[[1, 0], [0, 1]]) self.q_test_layer = TestModule() self.random_layer = tq.RandomLayer(30, wires=[0, 3, 5, 7]) # self.random_layer.static_on(wires_per_block=3) # self.q_test_layer.static_on(wires_per_block=4) self.q_device2 = tq.QuantumDevice(n_wires=3) self.t00 = T00()
def forward(self, q_device: tq.QuantumDevice): self.q_device = q_device res_all = [] for layer in self.obs_list: # create a new q device for each time of measurement q_device_new = tq.QuantumDevice(n_wires=q_device.n_wires) q_device_new.clone_states(existing_states=q_device.states) q_device_new.state = q_device.state observables = [] for wire in range(q_device.n_wires): observables.append(tq.I()) for wire, observable in zip(layer['wires'], layer['observables']): observables[wire] = tq.op_name_dict[observable]() res = expval(q_device_new, wires=list(range(q_device.n_wires)), observables=observables) if self.v_c_reg_mapping is not None: c2v_mapping = self.v_c_reg_mapping['c2v'] """ the measurement is not normal order, need permutation """ perm = [] for k in range(res.shape[-1]): if k in c2v_mapping.keys(): perm.append(c2v_mapping[k]) res = res[:, perm] res_all.append(res) return torch.cat(res_all)
def __init__(self): super().__init__() self.n_wires = 4 self.q_device = tq.QuantumDevice(n_wires=self.n_wires) self.measure = tq.MeasureAll(tq.PauliZ) self.encoder = tq.MultiPhaseEncoder([tqf.rx] * 4 + [tqf.ry] * 4 + [tqf.rz] * 4 + [tqf.rx] * 4) self.super_layers_all = tq.QuantumModuleList() self.normal_layers_all = tq.QuantumModuleList() for k in range(2): self.normal_layers_all.append( tq.Op1QAllLayer(op=tq.RX, n_wires=self.n_wires, has_params=True, trainable=True)) self.normal_layers_all.append( tq.Op1QAllLayer(op=tq.RY, n_wires=self.n_wires, has_params=True, trainable=True)) self.normal_layers_all.append( tq.Op1QAllLayer(op=tq.RZ, n_wires=self.n_wires, has_params=True, trainable=True)) for k in range(2): self.super_layers_all.append( tq.Super1QAllButOneLayer(op=tq.RX, n_wires=self.n_wires, has_params=True, trainable=True)) self.super_layers_all.append( tq.Super1QAllButOneLayer(op=tq.RY, n_wires=self.n_wires, has_params=True, trainable=True)) self.super_layers_all.append( tq.Super1QAllButOneLayer(op=tq.RZ, n_wires=self.n_wires, has_params=True, trainable=True)) self.super_layers_all.append( tq.Super1QSingleWireLayer(op=tq.RX, n_wires=self.n_wires, has_params=True, trainable=True)) self.super_layers_all.append( tq.Super1QSingleWireLayer(op=tq.RY, n_wires=self.n_wires, has_params=True, trainable=True)) self.super_layers_all.append( tq.Super1QSingleWireLayer(op=tq.RZ, n_wires=self.n_wires, has_params=True, trainable=True))
def __init__(self): super().__init__() self.q_device = tq.QuantumDevice(n_wires=5) self.encoder = RxEncoder(n_wires=5) self.encoder.static_on(wires_per_block=5) self.measure = Measure() self.q_layer = tq.RandomLayer(n_ops=1000000, wires=list(range(5))) self.q_layer.static_on(wires_per_block=5)
def __init__(self): super().__init__() self.n_wires = 4 self.q_device = tq.QuantumDevice(n_wires=self.n_wires) self.encoder = tq.GeneralEncoder( tq.encoder_op_list_name_dict['4x4_ryzxy']) self.q_layer = self.QLayer() self.measure = tq.MeasureAll(tq.PauliZ)
def __init__(self, arch): super().__init__() self.arch = arch self.n_wires = arch['n_wires'] self.q_device = tq.QuantumDevice(n_wires=self.n_wires) self.encoder = tq.GeneralEncoder( encoder_op_list_name_dict[arch['encoder_op_list_name']]) self.q_layer = super_layer_name_dict[arch['q_layer_name']](arch) self.measure = tq.MeasureAll(tq.PauliZ) self.sample_arch = None
def __init__(self): super().__init__() self.conv1 = nn.Conv2d(1, 32, 3, 1) self.conv2 = nn.Conv2d(32, 64, 3, 1) self.dropout1 = nn.Dropout(0.25) self.dropout2 = nn.Dropout(0.5) self.fc1 = nn.Linear(9216, 128) self.fc2 = nn.Linear(128, 10) self.sigmoid = nn.Sigmoid() self.q_device0 = tq.QuantumDevice(n_wires=10) self.q_layer0 = tq.TrainableOpAll(n_gate=10, op=tq.RX) self.q_layer1 = tq.ClassicalInOpAll(n_gate=10, op=tq.RX) self.q_layer2 = tq.RX(has_params=True, trainable=False, init_params=-np.pi / 4) self.q_layer3 = tq.RZ(has_params=True, trainable=True) self.q_device1 = tq.QuantumDevice(n_wires=3) self.q_layer4 = tq.CY() self.q_layer5 = tq.Toffoli() self.q_layer6 = tq.PhaseShift(has_params=True, trainable=True) self.q_layer7 = tq.Rot(has_params=True, trainable=True) self.q_layer8 = tq.MultiRZ(has_params=True, trainable=True, n_wires=5) self.q_layer9 = tq.CRX(has_params=True, trainable=True) self.q_layer10 = tq.CRY(has_params=True, trainable=True) self.q_layer11 = tq.CRZ(has_params=True, trainable=True) self.q_layer12 = tq.CRot( has_params=True, trainable=False, init_params=[-np.pi / 4, np.pi / 4, np.pi / 2]) self.q_layer13 = tq.U1(has_params=True, trainable=False, init_params=np.pi / 7) self.q_layer14 = tq.U2(has_params=True, trainable=True, init_params=[np.pi / 7, np.pi / 8.8]) self.q_layer15 = tq.U3(has_params=True, trainable=True) self.q_layer16 = tq.QubitUnitary(has_params=True, trainable=False, init_params=[[1, 0], [0, 1]]) self.q_layer17 = tq.MultiCNOT(n_wires=5) self.q_layer18 = tq.MultiXCNOT(n_wires=5)
def __init__(self, arch, hamil_info): super().__init__() self.arch = arch self.hamil_info = hamil_info self.n_wires = arch['n_wires'] self.q_device = tq.QuantumDevice(n_wires=self.n_wires) self.q_layer = super_layer_name_dict[arch['q_layer_name']](arch) self.measure = tq.MeasureMultipleTimes( obs_list=hamil_info['hamil_list']) self.sample_arch = None
def state_tq_vs_qiskit_test(): bsz = 1 for n_wires in range(2, 10): q_dev = tq.QuantumDevice(n_wires=n_wires) q_dev.reset_states(bsz=bsz) x = torch.randn((1, 100000), dtype=F_DTYPE) q_layer = AllRandomLayer(n_wires=n_wires, wires=list(range(n_wires)), n_ops_rd=500, n_ops_cin=500, n_funcs=500, qiskit_compatible=True) q_layer(q_dev, x) state_tq = q_dev.states.reshape(bsz, -1) state_tq = switch_little_big_endian_state(state_tq.data.numpy()) # qiskit circ = tq2qiskit(q_layer, x) # Select the StatevectorSimulator from the Aer provider simulator = Aer.get_backend('statevector_simulator') # Execute and get counts result = execute(circ, simulator).result() state_qiskit = result.get_statevector(circ) stable_threshold = 1e-5 try: # WARNING: need to remove the global phase! The qiskit simulated # results sometimes has global phase shift. global_phase = find_global_phase(state_tq, np.expand_dims(state_qiskit, 0), stable_threshold) if global_phase is None: logger.exception(f"Cannot find a stable enough factor to " f"reduce the global phase, increase the " f"stable_threshold and try again") raise RuntimeError assert np.allclose(state_tq * global_phase, state_qiskit, atol=1e-6) logger.info(f"PASS tq vs qiskit [n_wires]={n_wires}") except AssertionError: logger.exception(f"FAIL tq vs qiskit [n_wires]={n_wires}") raise AssertionError except RuntimeError: raise RuntimeError logger.info(f"PASS tq vs qiskit statevector test")
def __init__(self): super().__init__() self.n_gate = 9 self.h_all0 = tq.FixedOpAll(n_gate=9, op=tq.Hadamard) self.rx_all0 = tq.ClassicalInOpAll(n_gate=9, op=tq.RX) self.trainable_rx_all0 = tq.TrainableOpAll(n_gate=9, op=tq.RX) self.ry_all0 = tq.ClassicalInOpAll(n_gate=9, op=tq.RY) self.trainable_ry_all0 = tq.TrainableOpAll(n_gate=9, op=tq.RY) self.rz_all0 = tq.ClassicalInOpAll(n_gate=9, op=tq.RZ) self.trainable_rz_all0 = tq.TrainableOpAll(n_gate=9, op=tq.RZ) self.q_device0 = tq.QuantumDevice(n_wires=9) self.cnot_all = tq.TwoQAll(n_gate=9, op=tq.CNOT)
def measurement_tq_vs_qiskit_test(): bsz = 1 for n_wires in range(2, 10): q_dev = tq.QuantumDevice(n_wires=n_wires) q_dev.reset_states(bsz=bsz) x = torch.randn((1, 100000), dtype=F_DTYPE) q_layer = AllRandomLayer(n_wires=n_wires, wires=list(range(n_wires)), n_ops_rd=500, n_ops_cin=500, n_funcs=500, qiskit_compatible=True) q_layer(q_dev, x) measurer = tq.MeasureAll(obs=tq.PauliZ) # flip because qiskit is from N to 0, tq is from 0 to N measured_tq = np.flip(measurer(q_dev).data[0].numpy()) # qiskit circ = tq2qiskit(q_layer, x) circ.measure(list(range(n_wires)), list(range(n_wires))) # Select the QasmSimulator from the Aer provider simulator = Aer.get_backend('qasm_simulator') # Execute and get counts result = execute(circ, simulator, shots=1000000).result() counts = result.get_counts(circ) measured_qiskit = get_expectations_from_counts(counts, n_wires=n_wires) try: # WARNING: the measurement has randomness, so tolerate larger # differences (MAX 20%) between tq and qiskit # typical mean difference is less than 1% diff = np.abs(measured_tq - measured_qiskit).mean() diff_ratio = (np.abs( (measured_tq - measured_qiskit) / measured_qiskit)).mean() logger.info(f"Diff: tq vs qiskit {diff} \t Diff Ratio: " f"{diff_ratio}") assert np.allclose(measured_tq, measured_qiskit, atol=1e-4, rtol=2e-1) logger.info(f"PASS tq vs qiskit [n_wires]={n_wires}") except AssertionError: logger.exception(f"FAIL tq vs qiskit [n_wires]={n_wires}") raise AssertionError logger.info(f"PASS tq vs qiskit measurement test")
def unitary_tq_vs_qiskit_test(): for n_wires in range(2, 10): q_dev = tq.QuantumDevice(n_wires=n_wires) x = torch.randn((1, 100000), dtype=F_DTYPE) q_layer = AllRandomLayer(n_wires=n_wires, wires=list(range(n_wires)), n_ops_rd=500, n_ops_cin=500, n_funcs=500, qiskit_compatible=True) unitary_tq = q_layer.get_unitary(q_dev, x) unitary_tq = switch_little_big_endian_matrix(unitary_tq.data.numpy()) # qiskit circ = tq2qiskit(q_layer, x) simulator = Aer.get_backend('unitary_simulator') result = execute(circ, simulator).result() unitary_qiskit = result.get_unitary(circ) stable_threshold = 1e-5 try: # WARNING: need to remove the global phase! The qiskit simulated # results sometimes has global phase shift. global_phase = find_global_phase(unitary_tq, unitary_qiskit, stable_threshold) if global_phase is None: logger.exception(f"Cannot find a stable enough factor to " f"reduce the global phase, increase the " f"stable_threshold and try again") raise RuntimeError assert np.allclose(unitary_tq * global_phase, unitary_qiskit, atol=1e-6) logger.info(f"PASS tq vs qiskit [n_wires]={n_wires}") except AssertionError: logger.exception(f"FAIL tq vs qiskit [n_wires]={n_wires}") raise AssertionError except RuntimeError: raise RuntimeError logger.info(f"PASS tq vs qiskit unitary test")
def test_tq2qiskit(): import pdb pdb.set_trace() inputs = torch.ones((1, 1)) * 0.42 q_dev = tq.QuantumDevice(n_wires=10) test_module = TestModule(q_dev) circuit = tq2qiskit(test_module, inputs) simulator = Aer.get_backend('unitary_simulator') result = execute(circuit, simulator).result() unitary_qiskit = result.get_unitary(circuit) unitary_tq = test_module.get_unitary(q_dev, inputs) unitary_tq = switch_little_big_endian_matrix(unitary_tq.data.numpy()) print(unitary_qiskit) print(unitary_tq) assert np.allclose(unitary_qiskit, unitary_tq, atol=1e-6)
def test_qiskit2tq(): import pdb pdb.set_trace() n_wires = 4 q_dev = tq.QuantumDevice(n_wires=n_wires) circ = QuantumCircuit(n_wires, n_wires) circ.h(0) circ.h(0) circ.rx(theta=0.1, qubit=2) circ.ry(theta=0.2, qubit=3) circ.rz(phi=0.3, qubit=2) circ.sx(2) circ.sx(3) circ.crx(theta=0.4, control_qubit=0, target_qubit=1) circ.cnot(control_qubit=2, target_qubit=1) circ.u3(theta=-0.1, phi=-0.2, lam=-0.4, qubit=3) circ.cnot(control_qubit=3, target_qubit=0) circ.cnot(control_qubit=0, target_qubit=2) circ.x(2) circ.x(3) circ.u2(phi=-0.2, lam=-0.9, qubit=3) circ.x(0) m = qiskit2tq(circ) simulator = Aer.get_backend('unitary_simulator') result = execute(circ, simulator).result() unitary_qiskit = result.get_unitary(circ) unitary_tq = m.get_unitary(q_dev) unitary_tq = switch_little_big_endian_matrix(unitary_tq.data.numpy()) circ_from_m = tq2qiskit(q_dev, m) assert circ_from_m == circ phase = find_global_phase(unitary_tq, unitary_qiskit, 1e-4) assert np.allclose(unitary_tq * phase, unitary_qiskit, atol=1e-6)
def build_module_description_test(): import pdb from torchquantum.plugins import tq2qiskit pdb.set_trace() from examples.core.models.q_models import QFCModel12 q_model = QFCModel12({'n_blocks': 4}) desc = build_module_op_list(q_model.q_layer) print(desc) q_dev = tq.QuantumDevice(n_wires=4) m = build_module_from_op_list(desc) tq2qiskit(q_dev, m, draw=True) desc = build_module_op_list( tq.RandomLayerAllTypes(n_ops=200, wires=[0, 1, 2, 3], qiskit_compatible=True)) print(desc) m1 = build_module_from_op_list(desc) tq2qiskit(q_dev, m1, draw=True)
def __init__(self, arch, act_norm, node_id): super().__init__() self.arch = arch self.q_device = tq.QuantumDevice(n_wires=arch['n_wires']) self.encoder = tq.GeneralEncoder(encoder_op_list_name_dict[ arch['encoder_op_list_name']]) self.q_layer = layer_name_dict[arch['q_layer_name']](arch) self.measure = tq.MeasureAll(tq.PauliZ) self.act_norm = act_norm self.x_before_add_noise = None self.x_before_add_noise_second = None self.x_before_act_quant = None self.x_before_norm = None if self.act_norm == 'batch_norm' or \ self.act_norm == 'batch_norm_no_last': self.bn = torch.nn.BatchNorm1d( num_features=arch['n_wires'], momentum=None, affine=False, track_running_stats=False ) self.node_id = node_id self.pre_specified_mean_std = None
def test_tq2qiskit_parameterized(): import pdb pdb.set_trace() inputs = torch.randn((1, 16)) q_dev = tq.QuantumDevice(n_wires=4) test_module = TestModuleParameterized() test_module(q_dev, inputs) unitary_tq = test_module.get_unitary(q_dev, inputs) unitary_tq = switch_little_big_endian_matrix(unitary_tq.data.numpy()) circuit, params = tq2qiskit_parameterized(q_dev, test_module.encoder.func_list) binds = {} for k, x in enumerate(inputs[0]): binds[params[k]] = x.item() simulator = Aer.get_backend('unitary_simulator') result = execute(circuit, simulator, parameter_binds=[binds]).result() unitary_qiskit = result.get_unitary(circuit) # print(unitary_qiskit) # print(unitary_tq) assert np.allclose(unitary_qiskit, unitary_tq, atol=1e-6)
def __init__(self, arch=None): super().__init__() self.arch = arch self.n_wires = arch['n_wires'] self.q_device = tq.QuantumDevice(n_wires=self.n_wires) self.encoder = tq.GeneralEncoder([{ 'input_idx': [0], 'func': 'ry', 'wires': [0] }, { 'input_idx': [1], 'func': 'ry', 'wires': [1] }, { 'input_idx': [2], 'func': 'ry', 'wires': [2] }, { 'input_idx': [3], 'func': 'ry', 'wires': [3] }, { 'input_idx': [4], 'func': 'rz', 'wires': [0] }, { 'input_idx': [5], 'func': 'rz', 'wires': [1] }, { 'input_idx': [6], 'func': 'rz', 'wires': [2] }, { 'input_idx': [7], 'func': 'rz', 'wires': [3] }, { 'input_idx': [8], 'func': 'rx', 'wires': [0] }, { 'input_idx': [9], 'func': 'rx', 'wires': [1] }, { 'input_idx': [10], 'func': 'rx', 'wires': [2] }, { 'input_idx': [11], 'func': 'rx', 'wires': [3] }, { 'input_idx': [12], 'func': 'ry', 'wires': [0] }, { 'input_idx': [13], 'func': 'ry', 'wires': [1] }, { 'input_idx': [14], 'func': 'ry', 'wires': [2] }, { 'input_idx': [15], 'func': 'ry', 'wires': [3] }]) self.q_layer = self.QLayer(arch=arch) self.measure = tq.MeasureAll(tq.PauliZ) self.sample_arch = None
def __init__(self): super().__init__() self.n_wires = 4 self.q_device = tq.QuantumDevice(n_wires=self.n_wires) self.measure = tq.MeasureAll(tq.PauliZ) self.q_layer = self.QLayer(n_wires=self.n_wires)
def __init__(self, arch=None): super().__init__() self.arch = arch self.n_wires = arch['n_wires'] self.q_device = tq.QuantumDevice(n_wires=self.n_wires) self.encoder = tq.GeneralEncoder([ { 'input_idx': [0], 'func': 'ry', 'wires': [0] }, { 'input_idx': [1], 'func': 'ry', 'wires': [1] }, { 'input_idx': [2], 'func': 'ry', 'wires': [2] }, { 'input_idx': [3], 'func': 'ry', 'wires': [3] }, { 'input_idx': [4], 'func': 'ry', 'wires': [4] }, { 'input_idx': [5], 'func': 'ry', 'wires': [5] }, { 'input_idx': [6], 'func': 'ry', 'wires': [6] }, { 'input_idx': [7], 'func': 'ry', 'wires': [7] }, { 'input_idx': [8], 'func': 'ry', 'wires': [8] }, { 'input_idx': [9], 'func': 'ry', 'wires': [9] }, { 'input_idx': [10], 'func': 'rz', 'wires': [0] }, { 'input_idx': [11], 'func': 'rz', 'wires': [1] }, { 'input_idx': [12], 'func': 'rz', 'wires': [2] }, { 'input_idx': [13], 'func': 'rz', 'wires': [3] }, { 'input_idx': [14], 'func': 'rz', 'wires': [4] }, { 'input_idx': [15], 'func': 'rz', 'wires': [5] }, { 'input_idx': [16], 'func': 'rz', 'wires': [6] }, { 'input_idx': [17], 'func': 'rz', 'wires': [7] }, { 'input_idx': [18], 'func': 'rz', 'wires': [8] }, { 'input_idx': [19], 'func': 'rz', 'wires': [9] }, { 'input_idx': [20], 'func': 'rx', 'wires': [0] }, { 'input_idx': [21], 'func': 'rx', 'wires': [1] }, { 'input_idx': [22], 'func': 'rx', 'wires': [2] }, { 'input_idx': [23], 'func': 'rx', 'wires': [3] }, { 'input_idx': [24], 'func': 'rx', 'wires': [4] }, { 'input_idx': [25], 'func': 'rx', 'wires': [5] }, { 'input_idx': [26], 'func': 'rx', 'wires': [6] }, { 'input_idx': [27], 'func': 'rx', 'wires': [7] }, { 'input_idx': [28], 'func': 'rx', 'wires': [8] }, { 'input_idx': [29], 'func': 'rx', 'wires': [9] }, { 'input_idx': [30], 'func': 'ry', 'wires': [0] }, { 'input_idx': [31], 'func': 'ry', 'wires': [1] }, { 'input_idx': [32], 'func': 'ry', 'wires': [2] }, { 'input_idx': [33], 'func': 'ry', 'wires': [3] }, { 'input_idx': [34], 'func': 'ry', 'wires': [4] }, { 'input_idx': [35], 'func': 'ry', 'wires': [5] }, ]) self.q_layer = self.QLayer(arch=arch) self.measure = tq.MeasureAll(tq.PauliZ)