Qfim metric tensor verify diagonal elements

import pennylane as qml
from pennylane import numpy as np


n_qubits = 2
dev = qml.device("default.qubit", wires=n_qubits)


weights = np.random.random(size=(n_qubits, 2), requires_grad=True)  
x = np.random.random(size=(2,)) 


@qml.qnode(dev)
def circuit(weights, x):
   
    for i in range(n_qubits):
        qml.RX(x[i], wires=i)
        qml.RY(weights[i, 0], wires=i)
        qml.RZ(weights[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, x)
print(qfim)
print("\nGradient (ggrad):")
print(ggrad)

metric_fn = qml.metric_tensor(circuit, approx="diag")(weights, x)

print(metric_fn)

It works, but how can i have diag elements or block-diagonal elements of qfim. Second question is qfim=4. metric tensor (qml.gradients.quantum_fisher — PennyLane 0.38.1 documentation). But on verification, it did not 4 times of metric tensor elements. is there anything mistake. Can you please help.

Name: PennyLane
Version: 0.38.0
Summary: PennyLane is a cross-platform Python library for quantum computing, quantum machine learning, and quantum chemistry. Train a quantum computer the same way as a neural network.
Home-page: https://github.com/PennyLaneAI/pennylane
Author: 
Author-email: 
License: Apache License 2.0
Location: /home/bhatia87/.conda/envs/cent7/2020.11-py38/xyz2/lib/python3.10/site-packages
Requires: appdirs, autograd, autoray, cachetools, networkx, numpy, packaging, pennylane-lightning, requests, rustworkx, scipy, toml, typing-extensions
Required-by: PennyLane_Lightning

Platform info:           Linux-3.10.0-1160.108.1.el7.x86_64-x86_64-with-glibc2.17
Python version:          3.10.14
Numpy version:           1.23.5
Scipy version:           1.10.0
Installed devices:
- lightning.qubit (PennyLane_Lightning-0.38.0)
- default.clifford (PennyLane-0.38.0)
- default.gaussian (PennyLane-0.38.0)
- default.mixed (PennyLane-0.38.0)
- default.qubit (PennyLane-0.38.0)
- default.qubit.autograd (PennyLane-0.38.0)
- default.qubit.jax (PennyLane-0.38.0)
- default.qubit.legacy (PennyLane-0.38.0)
- default.qubit.tf (PennyLane-0.38.0)
- default.qubit.torch (PennyLane-0.38.0)
- default.qutrit (PennyLane-0.38.0)
- default.qutrit.mixed (PennyLane-0.38.0)
- default.tensor (PennyLane-0.38.0)
- null.qubit (PennyLane-0.38.0)

Hi @Amandeep ,

how can i have diag elements or block-diagonal elements of qfim

I guess you can calculate the variance of the parameters as shown in the PennyLane demo on Quantum natural gradient.
Look at the section on the block-diagonal metric tensor and you’ll see that the diagonal terms are given by the variance.

Regarding your question about comparing the metric tensor (MT) to the quantum fisher information matrix (QFIM), there were several issues in your code. On one hand you were computing the diagonal approximation of the metric tensor. If you want to compare the QFIM to the MT you need to use the full MT, not using approximations.
Note that to get the full MT you need an auxiliary qubit.

On the other hand you had trouble comparing because of the shape of weights. I would recommend making it one-dimensional so that you can compare properly. See an example below. This requires a slight change in how you specify the parameters in the gates in your circuit, as seen in the code below.

Finally, since you don’t want to calculate the metric tensor with respect to x you must set requires_grad=False when you define it.

Now you can make a proper comparison and see that quantum_fisher coincides with the metric_tensor with a prefactor of 4.

# modified example
import pennylane as qml
from pennylane import numpy as np


n_qubits = 2
dev = qml.device("default.qubit", wires=n_qubits)


weights = np.random.random(size=(4, ), requires_grad=True)  # mod
x = np.random.random(size=(2,), requires_grad=False) # mod


@qml.qnode(dev)
def circuit(weights, x):
   
    for i in range(n_qubits):
        qml.RX(x[i], wires=i)
        qml.RY(weights[2*i], wires=i) #mod
        qml.RZ(weights[2*i + 1], wires=i) #mod
 
    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, x)
print(qfim)
print("\nGradient (ggrad):")
print(ggrad)

# added
dev2 = qml.device("default.qubit", wires=n_qubits+1)

@qml.qnode(dev2)
def circuit2(weights, x):
   
    for i in range(n_qubits):
        qml.RX(x[i], wires=i)
        qml.RY(weights[2*i], wires=i) #mod
        qml.RZ(weights[2*i + 1], wires=i) #mod
 
    return qml.expval(qml.PauliZ(0))

metric_fn = qml.metric_tensor(circuit2)(weights, x) # mod approx="diag"

print(metric_fn)

# 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))

Hi @CatalinaAlbornoz The code worked. Thank you.
But when i put amplitude encoding and increase the qubits. It started giving an error.
Although the same code worked with angleembedding.
Could you please look into it?

import pennylane as qml

from pennylane import numpy as np

n_qubits = 4
dev = qml.device("default.qubit", wires=n_qubits)

@qml.qnode(dev, diff_method="backprop")
def circuit(weights, x):
   
    qml.AmplitudeEmbedding(x, wires=range(n_qubits), normalize=True)
    for i in range(n_qubits):
        qml.RY(weights[2 * i], wires=i)  # mod
        qml.RX(weights[2 * i + 1], wires=i)  # mod
            
    for i in range(n_qubits - 1):
        qml.CNOT(wires=[i, i + 1])

    return qml.expval(qml.PauliZ(0))

x_train = np.random.random(size=(20, 16), requires_grad=False)  
y_train = np.random.choice([1, -1], size=(20,), requires_grad=False)
weights = np.random.random(size=(8,), requires_grad=True)

opt = qml.AdamOptimizer(stepsize=0.1)
num_epochs = 20
batch_size = 4

num_batches = len(x_train) // batch_size  # Total number of batches per epoch
print(weights)

def cost(weights, X, Y, circuit, batch_size):
    # Get the circuit output
    output = 5* np.array(circuit(weights, X)).transpose()
    
    # Calculate the Mean Squared Error
    mse = np.mean((Y - output) ** 2)
    
    return mse

for j in range(num_batches):
    batch_index = np.array(range(batch_size * j, batch_size * (j + 1)))
    x = x_train[batch_index]
    y = y_train[batch_index]
    weights, _, _, _, _ = opt.step(cost, weights, x, y, circuit, batch_size)

print("Done")
qfim = qml.gradients.quantum_fisher(circuit)(weights, x)
    
print(qfim)

Error: ValueError: Broadcasting with MottonenStatePreparation is not supported. Please use the qml.transforms.broadcast_expand transform to use broadcasting with MottonenStatePreparation.

The second case is if the code works, and i am using 10 qubits, then it at this line takes several hours stucks qfim = qml.gradients.quantum_fisher(circuit)(weights, x[0])

I thought to expedite it with lightning.qubit, but my pennylane version is 0.38.1 and it gives an errror on using lightning qubit
ImportError: Pre-compiled binaries for lightning.qubit are not available. To manually compile from source, follow the instructions at Installation — Lightning 0.39.0 documentation.

qml.about()
Name: PennyLane
Version: 0.38.1
Summary: PennyLane is a cross-platform Python library for quantum computing, quantum machine learning, and quantum chemistry. Train a quantum computer the same way as a neural network.
Home-page: GitHub - PennyLaneAI/pennylane: PennyLane is a cross-platform Python library for quantum computing, quantum machine learning, and quantum chemistry. Train a quantum computer the same way as a neural network.
Author:
Author-email:
License: Apache License 2.0
Location: /home/bhatia87/.conda/envs/cent7/2020.11-py38/tqc/lib/python3.9/site-packages
Requires: appdirs, autograd, autoray, cachetools, networkx, numpy, packaging, pennylane-lightning, requests, rustworkx, scipy, toml, typing-extensions
Required-by: PennyLane_Lightning

Platform info: Linux-3.10.0-1160.108.1.el7.x86_64-x86_64-with-glibc2.17
Python version: 3.9.17
Numpy version: 1.23.5
Scipy version: 1.10.1
Installed devices:

  • default.clifford (PennyLane-0.38.1)
  • default.gaussian (PennyLane-0.38.1)
  • default.mixed (PennyLane-0.38.1)
  • default.qubit (PennyLane-0.38.1)
  • default.qubit.autograd (PennyLane-0.38.1)
  • default.qubit.jax (PennyLane-0.38.1)
  • default.qubit.legacy (PennyLane-0.38.1)
  • default.qubit.tf (PennyLane-0.38.1)
  • default.qubit.torch (PennyLane-0.38.1)
  • default.qutrit (PennyLane-0.38.1)
  • default.qutrit.mixed (PennyLane-0.38.1)
  • default.tensor (PennyLane-0.38.1)
  • null.qubit (PennyLane-0.38.1)
  • lightning.qubit (PennyLane-Lightning-0.38.0)

At last, I tried argnum[0] in qml.gradients.quantum_fisher for getting only qfim of parameters but it did not work out. It gives an TypeError: _expand_trainable_multipar() got an unexpected keyword argument ‘argnum’.

qfim = qml.gradients.quantum_fisher(circ, approx=“block-diag”)(weights, x[0])
with extra wire. it gives an error of TypeError: _expand_trainable_multipar() got an unexpected keyword argument ‘approx’, but this approx keyword works with metrix tensor not working with qfim. Could you please help in these queries.

Hi @Amandeep ,

You’ve made a lot of modifications so it’s normal for your code not to work. For the future could you please try just making one modification at a time?

Also, I recommend that you update your PennyLane version to v0.39.

Below is a modified version of my previous code, where I changed the number of qubits, changed the weights to match the new number of qubits, and use qml.AmplitudeEmbedding with pad_with=0.. This is important because otherwise you get an error when using it unless you have 2^{nqubits} features.

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)  # modify size to match the indexes called within the circuit
x = np.random.random(size=(2,), requires_grad=False) 


@qml.qnode(dev)
def circuit(weights, x):
    
    qml.AmplitudeEmbedding(x, pad_with=0., 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, x)
print(qfim)
print("\nGradient (ggrad):")
print(ggrad)


dev2 = qml.device("default.qubit", wires=n_qubits+1)

@qml.qnode(dev2)
def circuit2(weights, x):
    
    qml.AmplitudeEmbedding(x, pad_with=0., 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))


metric_fn = qml.metric_tensor(circuit2)(weights, x) 

print(metric_fn)

# 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))

I hope this helps

Thank you for your response @CatalinaAlbornoz . When I have 10 qubits and 1024 features, ```
qml.gradients.quantum_fisher(circuit)(weights, x)

The code worked. But when i use 3.9 pennylane version, then also qfim = qml.gradients.quantum_fisher(circuit, approx=“diag”)(weights, x). It gives an error TypeError: _expand_trainable_multipar() got an unexpected keyword argument ‘approx’
[/quote]

Hi @Amandeep,

You should use at least Python version 3.10 and you should avoid using approx=“diag” since this gives you an approximation that I think you don’t want in this case.

Let me know if this solves your issues.

Hi @CatalinaAlbornoz
I have installed python 0.39 and python 3.10.15.
this error still occurs
qml.gradients.quantum_fisher(circuit, approx=“diag”)(weights, x) It gives an error TypeError: _expand_trainable_multipar() got an unexpected keyword argument ‘approx’

I need to fetch QFIM diag elements on passing weights and x.

Hi @Amandeep ,

I was able to run the previous code example I shared, changing the qfim line to qfim = qml.gradients.quantum_fisher(circuit, approx="diag")(weights, x). It runs with no issues on Google Colab.

Are you making any additional changes to the code? I encourage you to debug those additional changes that you may have made.

I tried on my system not on google colab without any additional changes.

@CatalinaAlbornoz But did not work.

@Amandeep Can you please post the output of qml.about() and your full error traceback?
My guess is that your system has incompatible versions of packages, so I’d recommend using Google Colab or qBraid if possible to avoid these issues in the future.

Name: PennyLane
Version: 0.39.0
Summary: PennyLane is a cross-platform Python library for quantum computing, quantum machine learning, and quantum chemistry. Train a quantum computer the same way as a neural network.
Home-page: GitHub - PennyLaneAI/pennylane: PennyLane is a cross-platform Python library for quantum computing, quantum machine learning, and quantum chemistry. Train a quantum computer the same way as a neural network.
Author:
Author-email:
License: Apache License 2.0
Location: /home/bhatia87/.conda/envs/cent7/2020.11-py38/xtra/lib/python3.11/site-packages
Requires: appdirs, autograd, autoray, cachetools, networkx, numpy, packaging, pennylane-lightning, requests, rustworkx, scipy, toml, typing-extensions
Required-by: PennyLane_Lightning

Platform info: Linux-3.10.0-1160.108.1.el7.x86_64-x86_64-with-glibc2.17
Python version: 3.11.10
Numpy version: 2.0.2
Scipy version: 1.14.1
Installed devices:

  • default.clifford (PennyLane-0.39.0)
  • default.gaussian (PennyLane-0.39.0)
  • default.mixed (PennyLane-0.39.0)
  • default.qubit (PennyLane-0.39.0)
  • default.qutrit (PennyLane-0.39.0)
  • default.qutrit.mixed (PennyLane-0.39.0)
  • default.tensor (PennyLane-0.39.0)
  • null.qubit (PennyLane-0.39.0)
  • reference.qubit (PennyLane-0.39.0)
  • lightning.qubit (PennyLane_Lightning-0.39.0)
    @CatalinaAlbornoz

TypeError Traceback (most recent call last)
Cell In[2], line 39
34 ggrad = qml.grad(cost_fn)(weights)
36 return qfim, ggrad
—> 39 qfim, ggrad = compute_qfim_and_ggrad(weights, x1[0])
40 #print(qfim, qfim.shape)
41 diagonal_elements = np.diag(qfim)

Cell In[2], line 31, in compute_qfim_and_ggrad(weights, x)
26 def compute_qfim_and_ggrad(weights, x):
28 cost_fn = lambda w: circuit(w, x)
—> 31 qfim = qml.gradients.quantum_fisher(circuit, approx=“diag”)(weights, x)
34 ggrad = qml.grad(cost_fn)(weights)
36 return qfim, ggrad

File ~/.conda/envs/cent7/2020.11-py38/xtra/lib/python3.11/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.11/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.11/site-packages/pennylane/workflow/qnode.py:935, in QNode._execution_component(self, args, kwargs)
932 interface = None if self.interface == “numpy” else self.interface
934 # pylint: disable=unexpected-keyword-arg
→ 935 res = qml.execute(
936 (self._tape,),
937 device=self.device,
938 gradient_fn=gradient_fn,
939 interface=interface,
940 transform_program=full_transform_program,
941 inner_transform=inner_transform_program,
942 config=config,
943 gradient_kwargs=gradient_kwargs,
944 **execute_kwargs,
945 )
946 res = res[0]
948 # convert result to the interface in case the qfunc has no parameters

File ~/.conda/envs/cent7/2020.11-py38/xtra/lib/python3.11/site-packages/pennylane/workflow/execution.py:516, in execute(tapes, device, gradient_fn, interface, transform_program, inner_transform, config, grad_on_execution, gradient_kwargs, cache, cachesize, max_diff, device_vjp, mcm_config)
513 execute_fn = inner_execute_with_empty_jac
515 #### Executing the configured setup #####
→ 516 tapes, post_processing = transform_program(tapes)
518 if transform_program.is_informative:
519 return post_processing(tapes)

File ~/.conda/envs/cent7/2020.11-py38/xtra/lib/python3.11/site-packages/pennylane/transforms/core/transform_program.py:515, in TransformProgram.call(self, tapes)
513 if self._argnums is not None and self._argnums[i] is not None:
514 tape.trainable_params = self._argnums[i][j]
→ 515 new_tapes, fn = transform(tape, *targs, **tkwargs)
516 execution_tapes.extend(new_tapes)
518 fns.append(fn)

File ~/.conda/envs/cent7/2020.11-py38/xtra/lib/python3.11/site-packages/pennylane/gradients/fisher.py:389, in quantum_fisher(tape, device, *args, **kwargs)
385 return 4 * processing_fn(res)
387 return tapes, processing_fn_multiply
→ 389 res = adjoint_metric_tensor(tape, *args, **kwargs)
391 def processing_fn_multiply(r): # pylint: disable=function-redefined
392 r = qml.math.stack(r)

File ~/.conda/envs/cent7/2020.11-py38/xtra/lib/python3.11/site-packages/pennylane/transforms/core/transform_dispatcher.py:95, in TransformDispatcher.call(self, *targs, **tkwargs)
93 if isinstance(obj, qml.tape.QuantumScript):
94 if self._expand_transform:
—> 95 expanded_tapes, expand_processing = self._expand_transform(obj, *targs, **tkwargs)
96 transformed_tapes =
97 processing_and_sclices =

TypeError: _expand_trainable_multipar() got an unexpected keyword argument ‘approx’

Hi @Amandeep ,

Your issue here probably has one of three causes (or a combination of them):

  1. Most likely cause: Your version of glibc is too old. As mentioned in your other post, we require a minimum glibc library of 2.28 (ie RHEL 8 compatible and newer). Yours is glibc 2.17 (RHEL 7) so I would strongly suggest using Google Colab, qBraid, or the system of your choice with glibc >= 2.28.
  2. Somewhat likely: Whatever you’re using as weights and x1[0] is incompatible with some functions. I recommend that you test the code exactly as I shared it so that you can rule out this possible cause.
  3. Unlikely but worth exploring: Your version of NumPy might be causing issues. While PennyLane does support NumPy 2.0, you can rule out a possible NumPy issue by using NumPy 1.x. I ran the code with NumPy 1.26.4 and it worked well for me.

I hope the suggestions above help you solve the issue.

@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

Hi @Amandeep ,

When you edit the shapes of your inputs you must edit and debug your code to make sure that the new shapes match with your existing structures there.

As the error states, “all input arrays must have the same shape”.

Part of the process of working in quantum computing is going through your code and adapting it to match your needs. Why don’t you give it a go at debugging your code and making the dimensions match? This process can really help you learn more about PennyLane and quantum computing!