def test_batching_wave_functions_and_parameters(): N = 3 d = 13 qc = QuantumCircuit(N, [RX(wires=[ 0, ]), RX(wires=[ 1, ])], batch_params=True, device="CPU") psi = tf.placeholder(dtype=tf.complex64, shape=(None, *[2 for _ in range(N)])) theta = tf.convert_to_tensor([np.pi, np.pi]) with pytest.raises( AssertionError, match= "expected tensor with 3 dimensions, received tensor with shape"): qc.set_parameters(theta) qc.set_parameters(tf.reshape(theta, (1, 2, 1))) with pytest.raises( AssertionError, match= "We cannot have a batch of wave functions and a batch of parameters at the same time" ): qc.circuit(psi)
def test_batch_params_argument(): N = 3 theta = tf.placeholder(dtype=tf.float32, shape=(None, 2, 1)) qc = QuantumCircuit(N, [RX(wires=[ 0, ]), RX(wires=[ 1, ])]) with pytest.raises( AssertionError, match= " pass the batch_params=True argument to the QuantumCircuit class to enable batches of parameters." ): qc.set_parameters(theta) qc.circuit(qc.phi)
def test_external_input_dtype(): N = 3 qc = QuantumCircuit(N, [RX(wires=[ 0, ]), RX(wires=[ 1, ])], batch_params=True, device="CPU") with pytest.raises(TypeError, match="External input Tensor must have type "): theta = tf.placeholder(dtype=tf.complex64, shape=(None, 2, 1)) qc.set_parameters(theta) with pytest.raises(TypeError, match="External input Tensor must have type "): theta = tf.placeholder(dtype=tf.float64, shape=(None, 2, 1)) qc.set_parameters(theta)
def test_hybrid_neural_network_gradient_tracking(): N = 2 gates = [RX(wires=[ 0, ]), RX(wires=[ 1, ])] qc = QuantumCircuit(N, gates=gates, tensorboard=True, device="CPU") # Make a neural network NN = tf.keras.Sequential([ tf.keras.layers.Dense(qc.nparams * 10, activation=tf.keras.activations.tanh), tf.keras.layers.Dense(2, activation=tf.keras.activations.tanh), tf.keras.layers.Lambda(lambda x: x * 2 * np.pi) ]) x_in = tf.ones((qc.nparams, 1)) * 0.01 theta = NN(x_in) theta = tf.reduce_mean(theta, axis=0) theta = tf.reshape(theta, (1, -1, 1)) qc.set_parameters(theta) phi = qc.circuit(qc.phi) obs = Observable("x", wires=[ 0, ]), Observable("x", wires=[ 1, ]), Observable("z", wires=[ 1, ]) expval_layer = ExpectationValue(obs) expvals = expval_layer(phi) # Get energy for each timstep energy = tf.reduce_sum(expvals) opt = tf.compat.v1.train.AdamOptimizer(0.0001) grads = opt.compute_gradients(energy) qc.initialize() g = qc._sess.run(grads)
def test_multiple_thetas(): N = 3 d = 13 theta = tf.placeholder(dtype=tf.float32, shape=(None, 2, 1)) qc = QuantumCircuit(N, [RX(wires=[ 0, ]), RX(wires=[ 1, ])], batch_params=True, device="CPU") qc.set_parameters(theta) phi_dim_1 = qc.circuit(qc.phi) obs = [ Observable("x", wires=[ 0, ]), Observable("x", wires=[ 1, ]), Observable("x", wires=[ 2, ]), Observable("y", wires=[ 0, ]), Observable("y", wires=[ 1, ]), Observable("y", wires=[ 2, ]) ] expval_layer = ExpectationValue(obs) expvals_dim_1 = expval_layer(phi_dim_1) qc.initialize() qc._sess.run([expvals_dim_1], feed_dict={theta: np.random.randn(d, 2, 1)})