def generate_model_data(self, graphs, path): num_samples = len(graphs) self.save_graphs(graphs, path) qaoa_circuits, qaoa_parameters, cost_hams = self.generate_QAOA_Circuit_Batch( graphs) circuits = tfq.convert_to_tensor(qaoa_circuits) cost_hams = tfq.convert_to_tensor([cost_hams]) cost_hams = tf.transpose(cost_hams) symbols = tf.convert_to_tensor( [str(element) for element in qaoa_parameters]) # Generate Random Initial Parameters initial_mu = tf.convert_to_tensor( np.zeros(shape=(num_samples, self.qaoa_depth * 2)).astype(np.float32)) intitial_std = tf.convert_to_tensor( np.ones(shape=(num_samples, self.qaoa_depth * 2)).astype(np.float32)) graph_laplacians = [ np.asarray(nx.normalized_laplacian_matrix(graph).todense()) for graph in graphs ] data = [ circuits, cost_hams, symbols, initial_mu, intitial_std, graphs, graph_laplacians ] return data
def test_swap_overlap_identical(self): random_rotations = generate_random_rotation_batch( self.num_qubits_of_a_state, self.circuit_batch_size) circuit_input1 = tfq.convert_to_tensor( act_gate_batch_on_qubits(random_rotations, self.state1, as_circuits=True)) circuit_input2 = tfq.convert_to_tensor( act_gate_batch_on_qubits(random_rotations, self.state2, as_circuits=True)) swap_layer: SWAPTestOutputLayer = SWAPTestOutputLayer( circuit_prepend_of_state1=cirq.Circuit( [cirq.rx(sympy.Symbol("theta"))(self.state1[0])]), circuit_prepend_of_state2=cirq.Circuit( [cirq.rx(sympy.Symbol("theta"))(self.state2[0])]), state1=self.state1, state2=self.state2) output: tf.Tensor = swap_layer([circuit_input1, circuit_input2]) print(output) self.assertTrue( tf_allclose(output, tf.convert_to_tensor([[1.0]] * self.circuit_batch_size), rtol=1e-2))
def make_data(qubits): train, train_label = [], [] # 0 XOR 0 cir = cirq.Circuit() cir.append([cirq.I(qubits[0])]) cir.append([cirq.I(qubits[1])]) train.append(cir) train_label.append(-1) # 1 XOR 0 cir = cirq.Circuit() cir.append([cirq.X(qubits[0])]) cir.append([cirq.I(qubits[1])]) train.append(cir) train_label.append(1) # 0 XOR 1 cir = cirq.Circuit() cir.append([cirq.I(qubits[0])]) cir.append([cirq.X(qubits[1])]) train.append(cir) train_label.append(1) # 1 XOR 1 cir = cirq.Circuit() cir.append([cirq.X(qubits[0])]) cir.append([cirq.X(qubits[1])]) train.append(cir) train_label.append(-1) return tfq.convert_to_tensor(train), np.array( train_label), tfq.convert_to_tensor(train), np.array(train_label)
def make_data(n1, n2): qubit = cirq.GridQubit(0, 0) train, test = [], [] train_label, test_label = [], [] for _ in range(n1): cir = cirq.Circuit() rot = random.uniform( 0, 0.1) if random.random() < 0.5 else random.uniform(0.9, 1) cir.append([cirq.X(qubit)**rot]) train.append(cir) if rot < 0.5: train_label.append(1) else: train_label.append(-1) for _ in range(n2): cir = cirq.Circuit() rot = random.uniform( 0, 0.1) if random.random() < 0.5 else random.uniform(0.9, 1) cir.append([cirq.X(qubit)**rot]) test.append(cir) if rot < 0.5: test_label.append(1) else: test_label.append(-1) return tfq.convert_to_tensor(train), np.array( train_label), tfq.convert_to_tensor(test), np.array(test_label)
def test_swap_overlap_orthogonal(self): random_rotations = [ General1BitRotation(sympy.Symbol(f"theta_q{i}_1"), sympy.Symbol(f"theta_q{i}_2"), sympy.Symbol(f"theta_q{i}_3")) for i in range(self.num_qubits_of_a_state) ] circuit_input1 = tfq.convert_to_tensor([cirq.Circuit()] * self.circuit_batch_size) circuit_input2 = tfq.convert_to_tensor( [cirq.Circuit(cirq.X.on_each(self.state2))] * self.circuit_batch_size) swap_layer = SWAPTestOutputLayer( circuit_prepend_of_state1=act_gate_batch_on_qubits( [random_rotations], self.state1, as_circuits=True)[0], circuit_prepend_of_state2=act_gate_batch_on_qubits( [random_rotations], self.state2, as_circuits=True)[0], state1=self.state1, state2=self.state2) output: tf.Tensor = swap_layer([circuit_input1, circuit_input2]) print(output) self.assertTrue( tf_allclose(output, tf.convert_to_tensor([[0.0]] * self.circuit_batch_size), rtol=1e-5, atol=1e-5))
def test_empty_circuit(self): circuit_input1 = tfq.convert_to_tensor([cirq.Circuit()]) circuit_input2 = tfq.convert_to_tensor([cirq.Circuit()]) theta = sympy.Symbol("theta") input1_layer = tf.keras.layers.Input(shape=(), dtype=tf.string) input2_layer = tf.keras.layers.Input(shape=(), dtype=tf.string) swap_layer: SWAPTestOutputLayer = SWAPTestOutputLayer( circuit_prepend_of_state1=cirq.Circuit([ cirq.rx(theta)(self.state1[0]), cirq.ry(theta)(self.state1[1]) ]), circuit_prepend_of_state2=cirq.Circuit([ cirq.rx(theta)(self.state2[0]), cirq.ry(theta)(self.state2[1]) ]), state1=self.state1, state2=self.state2) swap_layer.set_weights([tf.convert_to_tensor([0.0])]) output_layer: tf.Tensor = swap_layer([input1_layer, input2_layer], add_metric=True) model = tf.keras.models.Model(inputs=[input1_layer, input2_layer], outputs=output_layer) model.summary() model.compile(optimizer=tf.keras.optimizers.Adam(), loss=tf.keras.losses.MeanSquaredError()) history = model.evaluate(x=[circuit_input1, circuit_input2], y=tf.convert_to_tensor([[1.0]])) print(history)
def test_circuit(self): circuit_input1 = tfq.convert_to_tensor( [cirq.Circuit([cirq.X.on_each(*self.state1)])] * 2) # NECESSARY to *2! circuit_input2 = tfq.convert_to_tensor([ cirq.Circuit([cirq.X.on_each(*self.state2)]), cirq.Circuit(cirq.I.on_each(*self.state2)) ]) output: tf.Tensor = SWAPTestOutputLayer( operators=[ cirq.PauliString(cirq.Z(self.state1[0]), cirq.Z(self.state2[0])), cirq.PauliString(cirq.Z(self.state1[1]), cirq.Z(self.state2[1])) ], circuit_prepend_of_state1=cirq.Circuit( [cirq.rx(sympy.Symbol("theta1"))(self.state1[0])]), circuit_prepend_of_state2=cirq.Circuit( [cirq.rx(sympy.Symbol("theta2"))(self.state2[0])]), circuit_append=cirq.Circuit([ cirq.rx(-sympy.Symbol("theta1"))(self.state1[0]), cirq.rx(-sympy.Symbol("theta2"))(self.state2[0]) ]), state1=self.state1, state2=self.state2)([circuit_input1, circuit_input2]) print(output) self.assertTrue(output.shape == (2, 2 + 1))
def test_swap_overlap_orthogonal(self): random_rotations = generate_random_rotation_batch( self.num_qubits_of_a_state, self.circuit_batch_size) circuit_input1 = tfq.convert_to_tensor( act_gate_batch_on_qubits(random_rotations, self.state1, as_circuits=True)) circuit_input2 = tfq.convert_to_tensor( act_gate_batch_on_qubits(random_rotations, self.state2, as_circuits=True)) circuit_input2 = tfq_utility_ops.tfq_append_circuit( tfq.convert_to_tensor( [cirq.Circuit([cirq.X.on_each(self.state2)])] * self.circuit_batch_size), circuit_input2) swap_layer: SWAPTestLayer = SWAPTestLayer(self.state1, self.state2) swap_test: tf.Tensor = swap_layer([circuit_input1, circuit_input2]) output: tf.Tensor = tfq.layers.Expectation()( swap_test, operators=[cirq.Z(swap_layer.auxiliary_qubit)]) print(output) self.assertTrue( tf_allclose(output, tf.convert_to_tensor([[0.0]] * self.circuit_batch_size), rtol=1e-5, atol=1e-5))
def load_circuit(self): self.train_circ = self.create_circuit(self.train_Data) self.test_circ = self.create_circuit(self.test_Data) self.val_circ = self.create_circuit(self.val_Data) self.train_circ = tfq.convert_to_tensor(self.train_circ) self.test_circ = tfq.convert_to_tensor(self.test_circ) self.val_circ = tfq.convert_to_tensor(self.val_circ)
def convert_data(data, qubits, test=False): cs = [] for i in data: cir = cirq.Circuit() for j in qubits: cir += cirq.rx(i[0] * np.pi).on(j) cir += cirq.ry(i[1] * np.pi).on(j) cs.append(cir) if test: return tfq.convert_to_tensor([cs]) return tfq.convert_to_tensor(cs)
def convert_to_tensors(self, x_train_circ, x_test_circ): """ Converts Cirq circuits to TFQ tensors. CREDIT: https://www.tensorflow.org/quantum/tutorials/mnist CREDIT: https://arxiv.org/pdf/1802.06002.pdf """ x_train_tfcirc = tfq.convert_to_tensor(x_train_circ) x_test_tfcirc = tfq.convert_to_tensor(x_test_circ) self.Helpers.logger.info("Converted Cirq circuits to TFQ tensors!") return x_train_tfcirc, x_test_tfcirc
def test_circuit(self): circuit_input1 = tfq.convert_to_tensor( [cirq.Circuit([cirq.X.on_each(*self.state1)])] * 2) # NECESSARY to *2! circuit_input2 = tfq.convert_to_tensor([ cirq.Circuit([cirq.X.on_each(*self.state2)]), cirq.Circuit(cirq.I.on_each(*self.state2)) ]) output: tf.Tensor = SWAPTestLayer( self.state1, self.state2)([circuit_input1, circuit_input2]) # print(output) print(tfq.from_tensor(output)) self.assertTrue(output.shape == (2, ))
def generate_dataset(qubit, theta_a, theta_b, num_samples): """Generate a dataset of points on `qubit` near the two given angles; labels for the two clusters use a one-hot encoding. """ q_data = [] bloch = {"a": [[], [], []], "b": [[], [], []]} labels = [] blob_size = abs(theta_a - theta_b) / 5 for _ in range(num_samples): coin = random.random() spread_x = np.random.uniform(-blob_size, blob_size) spread_y = np.random.uniform(-blob_size, blob_size) if coin < 0.5: label = [1, 0] angle = theta_a + spread_y source = "a" else: label = [0, 1] angle = theta_b + spread_y source = "b" labels.append(label) q_data.append(cirq.Circuit(cirq.ry(-angle)(qubit), cirq.rx(-spread_x)(qubit))) bloch[source][0].append(np.cos(angle)) bloch[source][1].append(np.sin(angle)*np.sin(spread_x)) bloch[source][2].append(np.sin(angle)*np.cos(spread_x)) return tfq.convert_to_tensor(q_data), np.array(labels), bloch
def setUp(self) -> None: # 输入线路数据(张量) self.input_circuit_tensors = tfq.convert_to_tensor([ cirq.Circuit(cirq.X(qubit)), cirq.Circuit(cirq.Y(qubit)), cirq.Circuit(cirq.H(qubit)) ]) # 需要添加的参数化线路 self.theta = sympy.Symbol("theta") self.parameterized_circuit = cirq.Circuit( (cirq.X**self.theta).on(qubit)) # AddPQC 层 self.add_layer: AddPQC = AddPQC( self.parameterized_circuit, constraint=tf.keras.constraints.MinMaxNorm(min_value=0, max_value=2)) # added_tensor_0 = add_layer( # input_circuit_tensors, append=True # ) # added_tensor = add_layer( # added_tensor_0, append=True # ) self.expectation_layer = tfq.layers.Expectation( differentiator=tfq.differentiators.ForwardDifference( grid_spacing=0.0001))
def test_model_fit(self): batch_size = 5 input_tensor = tfq.convert_to_tensor([cirq.Circuit(cirq.X(qubit))] * batch_size) y_tensor = tf.convert_to_tensor([[1]] * batch_size) input_layer = tf.keras.layers.Input(shape=(), dtype=tf.string) x = self.add_layer(input_layer, append=True) print(self.add_layer.parameters) output_layer = self.expectation_layer( x, operators=[cirq.Z(qubit)], symbol_names=[self.theta], symbol_values=self.add_layer.get_parameters()) # output_layer = tfq.layers.PQC( # self.parameterized_circuit, # operators=[cirq.Z(qubit)], # constraint=tf.keras.constraints.MinMaxNorm( # min_value=0, max_value=2 # ) # )(input_layer) model = tf.keras.models.Model(inputs=input_layer, outputs=output_layer) model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=0.05), loss=tf.keras.losses.MeanSquaredError()) print(model.get_weights()) print(model.summary()) history = model.fit(input_tensor, y_tensor, batch_size, epochs=20, verbose=1) print(model.get_weights())
def convert_data(self, data): self.qbits = self.make_bits(4) ret = [] data[0] += 4.8 data[0] *= 2*math.pi/9.6 data[1] = tf.clip_by_value(data[1], -1, 1) data[1] += 2 data[1] *= 2*math.pi/4 data[2] += 0.48 data[2] *= 2*math.pi/0.96 data[3] = tf.clip_by_value(data[3], -1, 1) data[3] += 2 data[3] *= 2*math.pi/4 for i, ang in enumerate(data): rx_g = cirq.rx(np.pi*ang) ret.append(rx_g(self.qbits[i])) rz_g = cirq.rz(np.pi*ang) ret.append(rz_g(self.qbits[i])) ''' for i, ang in enumerate(data): ang = 0 if ang < 0 else 1 rx_g = cirq.rx(np.pi*ang) ret.append(rx_g(self.qbits[i])) rz_g = cirq.rz(np.pi*ang) ret.append(rz_g(self.qbits[i])) ''' a = cirq.Circuit() a.append(ret) inputs = tfq.convert_to_tensor([a]) return inputs
def test_swap_overlap_random_rotations(self): circuit_input1 = tfq.convert_to_tensor( act_gate_batch_on_qubits(generate_random_rotation_batch( self.num_qubits_of_a_state, self.circuit_batch_size), self.state1, as_circuits=True)) circuit_input2 = tfq.convert_to_tensor( [cirq.Circuit([cirq.I.on_each(*self.state2)])] * self.circuit_batch_size) swap_layer: SWAPTestLayer = SWAPTestLayer(self.state1, self.state2) swap_test: tf.Tensor = swap_layer([circuit_input1, circuit_input2]) output: tf.Tensor = tfq.layers.Expectation()( swap_test, operators=[cirq.Z(swap_layer.auxiliary_qubit)]) print(output)
def call(self, theta_inp): """Keras call function. Input options: `inputs`, `symbol_names`, `symbol_values`: see `input_checks.expand_circuits` Output shape: `tf.RaggedTensor` with shape: [batch size of symbol_values, <size of state>, <size of state>] or [number of circuits, <size of state>, <size of state>] """ wx = cirq.Circuit(cirq.rx(2 * theta_inp)) self.rot_zs = [ cirq.Circuit(cirq.rz(2 * self.phi[k])(self.q)) for k in range(self.poly_deg) ] full_circuit = self.rot_zs[0] full_circuit_test = cirq.Circuit( cirq.rz(2 * self.symbol_names[0])(self.q), cirq.rx(2 * self.symbol_names[-1])(self.q), cirq.rz(2 * self.symbol_names[0])(self.q)) phi_values = tf.expand_dims(self.phi, axis=0) symbol_values = tf.expand_dims(tf.concat([self.phi, [4]], 0), 0) tensor_full_circuit_test = tfq.convert_to_tensor([full_circuit_test]) tfq.from_tensor( tfq.resolve_parameters(tensor_full_circuit_test, self.symbol_names, symbol_values)) return full_circuit_test.unitary()[0, 0]
def convert_data(self, classical_data, flag=True): ops = cirq.Circuit() for i, ang in enumerate(classical_data): ang = 0 if ang < 0 else 1 ops.append(cirq.rx(np.pi * ang).on(self.qubits[i])) ops.append(cirq.rz(np.pi * ang).on(self.qubits[i])) if flag: return tfq.convert_to_tensor([ops]) else: return ops
def make_data(qubits): train, train_label = [], [] # 0 XOR 0 cir = convert_data(qubits, cirq.Circuit(), [0, 0]) train.append(cir) train_label.append(-1) # 1 XOR 0 cir = convert_data(qubits, cirq.Circuit(), [1, 0]) train.append(cir) train_label.append(1) # 0 XOR 1 cir = convert_data(qubits, cirq.Circuit(), [0, 1]) train.append(cir) train_label.append(1) # 1 XOR 1 cir = convert_data(qubits, cirq.Circuit(), [1, 1]) train.append(cir) train_label.append(-1) return tfq.convert_to_tensor(train), np.array( train_label), tfq.convert_to_tensor(train), np.array(train_label)
def generate_data(qubits): """Generate training and testing data.""" n_rounds = 20 # Produces n_rounds * n_qubits datapoints. excitations = [] labels = [] for n in range(n_rounds): for bit in qubits: rng = np.random.uniform(-np.pi, np.pi) excitations.append(cirq.Circuit(cirq.rx(rng)(bit))) labels.append(1 if (-np.pi / 2) <= rng <= (np.pi / 2) else -1) split_ind = int(len(excitations) * 0.7) train_excitations = excitations[:split_ind] test_excitations = excitations[split_ind:] train_labels = labels[:split_ind] test_labels = labels[split_ind:] return tfq.convert_to_tensor(train_excitations), np.array(train_labels), \ tfq.convert_to_tensor(test_excitations), np.array(test_labels)
def generate_circuit_batch(self, graph_ids, p): ''' #randomly generate graphs and their descriptions ''' graphs = self.fetch_graphs_from_ID(graph_ids) qaoa_circuits = [] cost_hams = [] for graph_index, graph in enumerate(graphs): qaoa_circuit, qaoa_parameters, cost_ham = self.qaoa_circuit_from_graph( graph, p) qaoa_circuits.append(qaoa_circuit) cost_hams.append(cost_ham) qaoa_circuits = tfq.convert_to_tensor(qaoa_circuits) cost_hams = tfq.convert_to_tensor([cost_hams]) cost_hams = tf.transpose(cost_hams) return qaoa_circuits, qaoa_parameters, cost_hams, graph_ids
def train(self): batch_indices = np.random.choice(min(self.counter, self.buff), self.batch) state_batch = tfq.convert_to_tensor([self.convert_data(i, False) for i in self.states[batch_indices]]) action_batch = tf.convert_to_tensor(self.actions[batch_indices], dtype=tf.int32) action_batch = [[i, action_batch[i][0]] for i in range(len(action_batch))] reward_batch = tf.convert_to_tensor(self.rewards[batch_indices], dtype=tf.float32) dones_batch = tf.convert_to_tensor(self.dones[batch_indices], dtype=tf.float32) next_state_batch = tfq.convert_to_tensor([self.convert_data(i, False) for i in self.next_states[batch_indices]]) with tf.GradientTape() as tape: next_q = self.q_network(next_state_batch) next_q = tf.expand_dims(tf.reduce_max(next_q, axis=1), -1) y = reward_batch + (1 - dones_batch) * self.gamma * next_q q_guess = self.q_network(state_batch, training=True) pred = tf.gather_nd(q_guess, action_batch) pred = tf.reshape(pred, [self.batch, 1]) msbe = tf.math.reduce_mean(tf.math.square(y - pred)) grads = tape.gradient(msbe, self.q_network.trainable_variables) self.opt.apply_gradients(zip(grads, self.q_network.trainable_variables)) if self.epsilon > self.epsilon_min: self.epsilon *= self.epsilon_decay
def __init__(self, num_q, lays, num_actions) -> None: super(NoReUpPolicy, self).__init__() self.qubits = [cirq.GridQubit(0, i) for i in range(num_q)] self.num_params = 2 * lays * len(self.qubits) self.phi = tf.Variable(initial_value=np.random.uniform(0, 2 * np.pi, (1, self.num_params)), dtype="float32", trainable=True) self.lamb = tf.Variable(initial_value=np.ones((1, 2 * len(self.qubits))), dtype="float32", trainable=True) self.w = tf.Variable(initial_value=np.random.uniform(0, 2 * np.pi, (len(self.qubits), num_actions)), dtype="float32", trainable=True) self.total_params = self.num_params + 2 * len(self.qubits) self.params = sympy.symbols("params0:%d"%self.total_params) self.readout_ops = [cirq.Z(i) for i in self.qubits] self.model = tfq.layers.ControlledPQC(self.make_circuit(lays, self.params), self.readout_ops, differentiator=tfq.differentiators.Adjoint()) self.in_circuit = tfq.convert_to_tensor([cirq.Circuit()]) self.beta = 1
def get_mnist(img_dim=4, preprocessor_name=X_FLIP, num_examples=500): # Load MNIST (x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data() # Rescale the images from [0,255] to the [0.0,1.0] range. x_train, x_test = x_train[..., np.newaxis] / 255.0, x_test[..., np.newaxis] / 255.0 def filter_36(x, y): keep = (y == 3) | (y == 6) x, y = x[keep], y[keep] y = y == 3 return x, y x_train, y_train = filter_36(x_train, y_train) x_test, y_test = filter_36(x_test, y_test) if img_dim is not None: # Scale images x_train = tf.image.resize(x_train, (img_dim, img_dim)).numpy() x_test = tf.image.resize(x_test, (img_dim, img_dim)).numpy() # Remove contradicting images x_train, y_train = remove_contradicting(x_train, y_train) x_train = x_train[:num_examples] y_train = y_train[:num_examples] preprocessor = get_preprocessor(preprocessor_name) x_train_circ = [preprocessor(x, img_dim) for x in x_train] x_test_circ = [preprocessor(x, img_dim) for x in x_test] # Convert to tensor x_train_tfcirc = tfq.convert_to_tensor(x_train_circ) x_test_tfcirc = tfq.convert_to_tensor(x_test_circ) return (x_train_tfcirc, y_train), (x_test_tfcirc, y_test)
def test_swap_overlap_random_rotations(self): circuit_input1 = tfq.convert_to_tensor( act_gate_batch_on_qubits(generate_random_rotation_batch( self.num_qubits_of_a_state, self.circuit_batch_size), self.state1, as_circuits=True)) circuit_input2 = tfq.convert_to_tensor([cirq.Circuit()] * self.circuit_batch_size) swap_layer = SWAPTestOutputLayer( circuit_prepend_of_state1=cirq.Circuit( [cirq.rx(sympy.Symbol("theta1"))(self.state1[0])]), circuit_prepend_of_state2=cirq.Circuit( [cirq.rx(sympy.Symbol("theta2"))(self.state2[0])]), circuit_append=cirq.Circuit([ cirq.rx(-sympy.Symbol("theta1"))(self.state1[0]), cirq.rx(-sympy.Symbol("theta2"))(self.state2[0]) ]), state1=self.state1, state2=self.state2) output: tf.Tensor = swap_layer([circuit_input1, circuit_input2]) print(output) self.assertEqual(output.shape, (5, 1))
def test_model(self): circuit_input1 = tfq.convert_to_tensor( [cirq.Circuit([cirq.X.on_each(*self.state1)])] * 2) # NECESSARY to *2! circuit_input2 = tfq.convert_to_tensor([ cirq.Circuit([cirq.X.on_each(*self.state2)]), cirq.Circuit(cirq.I.on_each(*self.state2)) ]) input1_layer = tf.keras.layers.Input(shape=(), dtype=tf.string) input2_layer = tf.keras.layers.Input(shape=(), dtype=tf.string) output_layer: tf.Tensor = SWAPTestOutputLayer( operators=[ cirq.PauliString(cirq.Z(self.state1[0]), cirq.Z(self.state2[0])), cirq.PauliString(cirq.Z(self.state1[1]), cirq.Z(self.state2[1])) ], circuit_prepend_of_state1=cirq.Circuit( [cirq.rx(sympy.Symbol("theta1"))(self.state1[0])]), circuit_prepend_of_state2=cirq.Circuit( [cirq.rx(sympy.Symbol("theta2"))(self.state2[0])]), circuit_append=cirq.Circuit([ cirq.rx(-sympy.Symbol("theta1"))(self.state1[0]), cirq.rx(-sympy.Symbol("theta2"))(self.state2[0]) ]), state1=self.state1, state2=self.state2)([input1_layer, input2_layer]) model = tf.keras.models.Model(inputs=[input1_layer, input2_layer], outputs=output_layer) model.summary() output_tensor = model([circuit_input1, circuit_input2]) print(output_tensor) self.assertTrue(output_tensor.shape == (2, 2 + 1))
def __init__(self, qubit, layers, obs) -> None: super(ReUploadPQC, self).__init__() self.num_params = len(qubit) * 3 * layers self.layers = layers self.qubits = qubit self.theta = tf.Variable(initial_value=np.random.uniform( 0, 2 * np.pi, (1, self.num_params)), dtype="float32", trainable=True) self.w = tf.Variable(initial_value=np.random.uniform( 0, 2 * np.pi, (1, self.num_params)), dtype="float32", trainable=True) self.params = sympy.symbols("params0:%d" % self.num_params) self.model = tfq.layers.ControlledPQC( self.make_circuit(layers, self.params), obs, differentiator=tfq.differentiators.Adjoint()) self.in_circuit = tfq.convert_to_tensor([cirq.Circuit()])
def grad_variance(circuits, qubits, symbol, reps, ops): if ops == "all": readout_ops = sum([cirq.Z(i) for i in qubits]) else: readout_ops = [cirq.Z(qubits[0]) * cirq.Z(qubits[1])] rep = reps diff = tfq.differentiators.ParameterShift() expectation = tfq.layers.SampledExpectation(differentiator=diff) circuit_tensor = tfq.convert_to_tensor(circuits) values_tensor = tf.convert_to_tensor(np.random.uniform(0, 2 * np.pi, (len(circuits), 1)).astype(np.float32)) with tf.GradientTape() as tape: tape.watch(values_tensor) forward = expectation(circuit_tensor, operators=readout_ops, repetitions=rep, symbol_names=[symbol], symbol_values=values_tensor) grads = tape.gradient(forward, values_tensor) grad_var = tf.math.reduce_std(grads, axis=0) return grad_var.numpy()[0]
qaoa_circuit = cirq.Circuit() p = 1 qaoa_parameters = [] for i in range(p): name = "a" * (i + 1) cost_parameter = sympy.symbols(name) name = "b" * (i + 1) mixing_parameter = sympy.symbols(name) qaoa_parameters.append(cost_parameter) qaoa_parameters.append(mixing_parameter) qaoa_circuit += tfq.util.exponential( operators=[cost_hamiltonian, mixing_hamiltonian], coefficients=[cost_parameter, mixing_parameter]) inputs = tfq.convert_to_tensor([initial]) ins = tf.keras.layers.Input(shape=(), dtype=tf.dtypes.string) outs = tfq.layers.PQC(qaoa_circuit, cost_hamiltonian)(ins) qaoa = tf.keras.models.Model(inputs=ins, outputs=outs) qaoa.compile(loss=tf.keras.losses.MAE, optimizer=tf.keras.optimizers.Adam()) optimal = np.array([0]) history = qaoa.fit(inputs, optimal, epochs=800) plt.plot(history.history['loss']) plt.title("QAOA with TFQ") plt.xlabel("Iteration") plt.ylabel("Loss") plt.show() params = qaoa.trainable_variables