-
Notifications
You must be signed in to change notification settings - Fork 90
Issue of shape with Quantum Fisher information #231
-
import time
import numpy as np
import tensorflow as tf
import torch
import tensorcircuit as tc
from tensorcircuit.experimental import qng
K = tc.set_backend("tensorflow")
Load and preprocess MNIST data
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
x_train = x_train[..., np.newaxis] / 255.0
def filter_pair(x, y, a, b):
keep = (y == a) | (y == b)
x, y = x[keep], y[keep]
y = y == a
return x, y
x_train, y_train = filter_pair(x_train, y_train, 1, 5)
x_train_small = tf.image.resize(x_train, (3, 3)).numpy()
x_train_bin = np.array(x_train_small > 0.5, dtype=np.float32)
x_train_bin = np.squeeze(x_train_bin).reshape([-1, 9])
y_train_torch = torch.tensor(y_train, dtype=torch.float32)
x_train_torch = torch.tensor(x_train_bin)
print(x_train_torch.shape, y_train_torch.shape)
n = 9 # Number of qubits
nlayers = 1 # Number of variational layers
Quantum predictions function with proper tensor dimensions
def qpreds(x, weights):
print("Input shape (x):", x.shape)
print("Weights shape:", weights.shape)
c = tc.Circuit(n)
for i in range(n):
c.rx(i, theta=x[i]) # Apply rotation gate for input
for j in range(nlayers):
for i in range(n - 1):
c.cnot(i, i + 1) # Apply CNOT gates
for i in range(n):
c.rx(i, theta=weights[i]) # Apply RX gates with quantum weights
# Return expectation values for each qubit
ypred = c.expectation_ps(z=[n // 2])
ypred = K.real(ypred)
return K.sigmoid(ypred)
qpreds_vmap = K.vmap(qpreds, vectorized_argnums=0)
qpreds_batch = tc.interfaces.torch_interface(qpreds_vmap, jit=True)
Define the QuantumNetV3 model
class QuantumNetV3(torch.nn.Module):
def init(self):
super().init()
self.q_weights = torch.tensor(np.ones(n), dtype=torch.float32) # Quantum weights (9-dimensional)
print(self.q_weights.shape)
def forward(self, inputs):
ypred = qpreds_batch(inputs, self.q_weights) # Call the batch version of qpreds
return ypred
model = QuantumNetV3()
def compute_qfi_for_weights(model, d):
quantum_weights = model.q_weights
print("Quantum weights shape:", quantum_weights.shape)
print("Quantum weights:", quantum_weights[0]) # Check the weights
def wrapped_psi(thetas):
return qpreds(d, thetas)
qfi_fun = K.jit(qng(wrapped_psi))
qfi_value = qfi_fun(quantum_weights)
return qfi_value
qfi_value = compute_qfi_for_weights(model, x_train_torch[0])
print("QFI for Quantum Weights:")
print(qfi_value.numpy()) # Should print QFI values torch.Size([9])
it gives a value error ---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Cell In[2], line 91
88 return qfi_value
90 # Compute and print the QFI for the model's quantum weights
---> 91 qfi_value = compute_qfi_for_weights(model, x_train_torch[0])
93 print("QFI for Quantum Weights:")
94 print(qfi_value.numpy())
Cell In[2], line 86, in compute_qfi_for_weights(model, d)
83 # Apply the qng function in a simple way first
84 qfi_fun = K.jit(qng(wrapped_psi))
---> 86 qfi_value = qfi_fun(quantum_weights) # Pass the quantum weights to compute QFI
88 return qfi_value
File ~/.conda/envs/cent7/2020.11-py38/new/lib/python3.8/site-packages/tensorflow/python/util/traceback_utils.py:153, in filter_traceback..error_handler(*args, **kwargs)
151 except Exception as e:
152 filtered_tb = _process_traceback_frames(e.traceback)
--> 153 raise e.with_traceback(filtered_tb) from None
154 finally:
155 del filtered_tb
File ~/.conda/envs/cent7/2020.11-py38/new/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py:1129, in func_graph_from_py_func..autograph_handler(*args, **kwargs)
1127 except Exception as e: # pylint:disable=broad-except
1128 if hasattr(e, "ag_error_metadata"):
-> 1129 raise e.ag_error_metadata.to_exception(e)
1130 else:
1131 raise
ValueError: in user code:
File "/home/bhatia87/.conda/envs/cent7/2020.11-py38/new/lib/python3.8/site-packages/tensorcircuit/experimental.py", line 111, in ij *
return _vdot(i, j) - _vdot(i, psi) * _vdot(psi, j)
File "/home/bhatia87/.conda/envs/cent7/2020.11-py38/new/lib/python3.8/site-packages/tensorcircuit/experimental.py", line 88, in _vdot *
return backend.tensordot(backend.conj(i), j, 1)
File "/home/bhatia87/.conda/envs/cent7/2020.11-py38/new/lib/python3.8/site-packages/tensorcircuit/backends/tensorflow_backend.py", line 77, in _tensordot_tf *
return tf.tensordot(a, b, axes)
ValueError: `axes` must not be larger than the number of dimensions of tensor Tensor("loop_body_1/loop_body/GatherV2:0", shape=(), dtype=float32). Received 1, vs tensor dimensions 0.
Could you please check. What can be the issue at backend tensorflow. I need to print QFI wrt to parameters and sample of data.
Beta Was this translation helpful? Give feedback.
All reactions
Replies: 1 comment
-
wrapped_psi should return the shape of output wavefunction instead of the predicted labels in order to be used in qng function
Beta Was this translation helpful? Give feedback.