@CatalinaAlbornoz Thank you for response.
One thing, i made few changes in the above code, increased the features. If i have 15 features, 4 qubits, and use padding the code worked. but when i have 16, 4 qubits, gives an error
import pennylane as qml
from pennylane import numpy as np
n_qubits = 4 # changed
dev = qml.device("default.qubit", wires=n_qubits)
weights = np.random.random(size=(n_qubits*2, ), requires_grad=True)
x1 = np.random.random(size=(10,16), requires_grad=False)
y1 = np.random.choice([1, -1], size=(10,))
@qml.qnode(dev)
def circuit(weights, x):
print(x.shape)
qml.AmplitudeEmbedding(x, wires=range(n_qubits), normalize=True) # added
for i in range(n_qubits):
#qml.RX(x[i], wires=i) # removed
qml.RY(weights[2*i], wires=i)
qml.RZ(weights[2*i + 1], wires=i)
return qml.expval(qml.PauliZ(0))
def compute_qfim_and_ggrad(weights, x):
cost_fn = lambda w: circuit(w, x)
qfim = qml.gradients.quantum_fisher(circuit)(weights, x)
ggrad = qml.grad(cost_fn)(weights)
return qfim, ggrad
qfim, ggrad = compute_qfim_and_ggrad(weights, x1[0])
#print(qfim, qfim.shape)
metric_fn = qml.metric_tensor(circuit, approx="block-diag")(weights, x1[0])
#print(metric_fn, metric_fn.shape)
# Check if they coincide with a prefactor of 4
print('quantum_fisher coincides with the metric_tensor with a prefactor of 4: ',np.allclose(qfim,4*metric_fn))
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Cell In[32], line 38
33 ggrad = qml.grad(cost_fn)(weights)
35 return qfim, ggrad
---> 38 qfim, ggrad = compute_qfim_and_ggrad(weights, x1[0])
39 #print(qfim, qfim.shape)
41 metric_fn = qml.metric_tensor(circuit, approx="block-diag")(weights, x1[0])
Cell In[32], line 30, in compute_qfim_and_ggrad(weights, x)
25 def compute_qfim_and_ggrad(weights, x):
27 cost_fn = lambda w: circuit(w, x)
---> 30 qfim = qml.gradients.quantum_fisher(circuit)(weights, x)
33 ggrad = qml.grad(cost_fn)(weights)
35 return qfim, ggrad
File ~/.conda/envs/cent7/2020.11-py38/xtra/lib/python3.10/site-packages/pennylane/workflow/qnode.py:987, in QNode.__call__(self, *args, **kwargs)
985 if qml.capture.enabled():
986 return qml.capture.qnode_call(self, *args, **kwargs)
--> 987 return self._impl_call(*args, **kwargs)
File ~/.conda/envs/cent7/2020.11-py38/xtra/lib/python3.10/site-packages/pennylane/workflow/qnode.py:977, in QNode._impl_call(self, *args, **kwargs)
974 self._interface = interface
976 try:
--> 977 res = self._execution_component(args, kwargs)
978 finally:
979 if old_interface == "auto":
File ~/.conda/envs/cent7/2020.11-py38/xtra/lib/python3.10/site-packages/pennylane/workflow/qnode.py:923, in QNode._execution_component(self, args, kwargs)
917 full_transform_program.insert_front_transform(
918 qml.transform(gradient_fn.expand_transform),
919 **gradient_kwargs,
920 )
922 # Calculate the classical jacobians if necessary
--> 923 full_transform_program.set_classical_component(self, args, kwargs)
924 _prune_dynamic_transform(full_transform_program, inner_transform_program)
926 execute_kwargs["mcm_config"] = mcm_config
File ~/.conda/envs/cent7/2020.11-py38/xtra/lib/python3.10/site-packages/pennylane/transforms/core/transform_program.py:350, in TransformProgram.set_classical_component(self, qnode, args, kwargs)
348 if hybrid:
349 argnums = self[-1].kwargs.pop("argnums", None) # pylint: disable=no-member
--> 350 self._set_all_classical_jacobians(qnode, args, kwargs, argnums)
351 self._set_all_argnums(qnode, args, kwargs, argnums)
File ~/.conda/envs/cent7/2020.11-py38/xtra/lib/python3.10/site-packages/pennylane/transforms/core/transform_program.py:456, in TransformProgram._set_all_classical_jacobians(self, qnode, args, kwargs, argnums)
452 raise qml.QuantumFunctionError(
453 "argnum does not work with the Jax interface. You should use argnums instead."
454 )
455 sub_program = TransformProgram(self[0:index])
--> 456 classical_jacobian = jacobian(
457 classical_preprocessing, sub_program, argnums, *args, **kwargs
458 )
459 qnode.construct(args, kwargs)
460 tapes, _ = sub_program((qnode.tape,))
File ~/.conda/envs/cent7/2020.11-py38/xtra/lib/python3.10/site-packages/pennylane/transforms/core/transform_program.py:412, in TransformProgram._set_all_classical_jacobians.<locals>.jacobian(classical_function, program, argnums, *args, **kwargs)
410 jac = None
411 if qnode.interface == "autograd":
--> 412 jac = qml.jacobian(classical_function, argnum=argnums)(*args, **kwargs)
414 if qnode.interface == "tf":
415 import tensorflow as tf # pylint: disable=import-outside-toplevel
File ~/.conda/envs/cent7/2020.11-py38/xtra/lib/python3.10/site-packages/pennylane/_grad.py:517, in jacobian.<locals>._jacobian_function(*args, **kwargs)
511 if not _argnum:
512 warnings.warn(
513 "Attempted to differentiate a function with no trainable parameters. "
514 "If this is unintended, please add trainable parameters via the "
515 "'requires_grad' attribute or 'argnum' keyword."
516 )
--> 517 jac = tuple(_jacobian(func, arg)(*args, **kwargs) for arg in _argnum)
519 return jac[0] if unpack else jac
File ~/.conda/envs/cent7/2020.11-py38/xtra/lib/python3.10/site-packages/pennylane/_grad.py:517, in <genexpr>(.0)
511 if not _argnum:
512 warnings.warn(
513 "Attempted to differentiate a function with no trainable parameters. "
514 "If this is unintended, please add trainable parameters via the "
515 "'requires_grad' attribute or 'argnum' keyword."
516 )
--> 517 jac = tuple(_jacobian(func, arg)(*args, **kwargs) for arg in _argnum)
519 return jac[0] if unpack else jac
File ~/.conda/envs/cent7/2020.11-py38/xtra/lib/python3.10/site-packages/autograd/wrap_util.py:20, in unary_to_nary.<locals>.nary_operator.<locals>.nary_f(*args, **kwargs)
18 else:
19 x = tuple(args[i] for i in argnum)
---> 20 return unary_operator(unary_f, x, *nary_op_args, **nary_op_kwargs)
File ~/.conda/envs/cent7/2020.11-py38/xtra/lib/python3.10/site-packages/autograd/differential_operators.py:60, in jacobian(fun, x)
50 @unary_to_nary
51 def jacobian(fun, x):
52 """
53 Returns a function which computes the Jacobian of `fun` with respect to
54 positional argument number `argnum`, which must be a scalar or array. Unlike
(...)
58 (out1, out2, ...) then the Jacobian has shape (out1, out2, ..., in1, in2, ...).
59 """
---> 60 vjp, ans = _make_vjp(fun, x)
61 ans_vspace = vspace(ans)
62 jacobian_shape = ans_vspace.shape + vspace(x).shape
File ~/.conda/envs/cent7/2020.11-py38/xtra/lib/python3.10/site-packages/autograd/core.py:10, in make_vjp(fun, x)
8 def make_vjp(fun, x):
9 start_node = VJPNode.new_root()
---> 10 end_value, end_node = trace(start_node, fun, x)
11 if end_node is None:
12 def vjp(g): return vspace(x).zeros()
File ~/.conda/envs/cent7/2020.11-py38/xtra/lib/python3.10/site-packages/autograd/tracer.py:10, in trace(start_node, fun, x)
8 with trace_stack.new_trace() as t:
9 start_box = new_box(x, t, start_node)
---> 10 end_box = fun(start_box)
11 if isbox(end_box) and end_box._trace == start_box._trace:
12 return end_box._value, end_box._node
File ~/.conda/envs/cent7/2020.11-py38/xtra/lib/python3.10/site-packages/autograd/wrap_util.py:15, in unary_to_nary.<locals>.nary_operator.<locals>.nary_f.<locals>.unary_f(x)
13 else:
14 subargs = subvals(args, zip(argnum, x))
---> 15 return fun(*subargs, **kwargs)
File ~/.conda/envs/cent7/2020.11-py38/xtra/lib/python3.10/site-packages/pennylane/transforms/core/transform_program.py:392, in TransformProgram._set_all_classical_jacobians.<locals>.classical_preprocessing(program, *args, **kwargs)
390 tape = qnode.qtape
391 tapes, _ = program((tape,))
--> 392 res = tuple(qml.math.stack(tape.get_parameters(trainable_only=True)) for tape in tapes)
393 if len(tapes) == 1:
394 return res[0]
File ~/.conda/envs/cent7/2020.11-py38/xtra/lib/python3.10/site-packages/pennylane/transforms/core/transform_program.py:392, in <genexpr>(.0)
390 tape = qnode.qtape
391 tapes, _ = program((tape,))
--> 392 res = tuple(qml.math.stack(tape.get_parameters(trainable_only=True)) for tape in tapes)
393 if len(tapes) == 1:
394 return res[0]
File ~/.conda/envs/cent7/2020.11-py38/xtra/lib/python3.10/site-packages/pennylane/math/multi_dispatch.py:152, in multi_dispatch.<locals>.decorator.<locals>.wrapper(*args, **kwargs)
149 interface = interface or get_interface(*dispatch_args)
150 kwargs["like"] = interface
--> 152 return fn(*args, **kwargs)
File ~/.conda/envs/cent7/2020.11-py38/xtra/lib/python3.10/site-packages/pennylane/math/multi_dispatch.py:503, in stack(values, axis, like)
474 """Stack a sequence of tensors along the specified axis.
475
476 .. warning::
(...)
500 [5.00e+00, 8.00e+00, 1.01e+02]], dtype=float32)>
501 """
502 values = np.coerce(values, like=like)
--> 503 return np.stack(values, axis=axis, like=like)
File ~/.conda/envs/cent7/2020.11-py38/xtra/lib/python3.10/site-packages/autoray/autoray.py:81, in do(fn, like, *args, **kwargs)
79 backend = _choose_backend(fn, args, kwargs, like=like)
80 func = get_lib_fn(backend, fn)
---> 81 return func(*args, **kwargs)
File ~/.conda/envs/cent7/2020.11-py38/xtra/lib/python3.10/site-packages/pennylane/numpy/wrapper.py:117, in tensor_wrapper.<locals>._wrapped(*args, **kwargs)
114 tensor_kwargs["requires_grad"] = _np.any([i.requires_grad for i in tensor_args])
116 # evaluate the original object
--> 117 res = obj(*args, **kwargs)
119 if isinstance(res, _np.ndarray):
120 # only if the output of the object is a ndarray,
121 # then convert to a PennyLane tensor
122 res = tensor(res, **tensor_kwargs)
File ~/.conda/envs/cent7/2020.11-py38/xtra/lib/python3.10/site-packages/autograd/numpy/numpy_wrapper.py:94, in stack(arrays, axis)
92 shapes = set(arr.shape for arr in arrays)
93 if len(shapes) != 1:
---> 94 raise ValueError('all input arrays must have the same shape')
96 result_ndim = arrays[0].ndim + 1
97 if not -result_ndim <= axis < result_ndim:
ValueError: all input arrays must have the same shape