# Optimizing the parameters of MottonenStatePreparation produces the following error

**URL:** <https://discuss.pennylane.ai/t/optimizing-the-parameters-of-mottonenstatepreparation-produces-the-following-error/2307>\
**Category:** PennyLane Help\
**Created:** [November 22, 2022, 3:16pm UTC](https://discuss.pennylane.ai/t/optimizing-the-parameters-of-mottonenstatepreparation-produces-the-following-error/2307 "2022-11-22T15:16:38Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![RX1](https://yyz2.discourse-cdn.com/flex012/user_avatar/discuss.pennylane.ai/rx1/32/698_2.png) [@RX1](https://discuss.pennylane.ai/u/RX1)\
**Post date:** [November 22, 2022, 3:16pm UTC](https://discuss.pennylane.ai/t/optimizing-the-parameters-of-mottonenstatepreparation-produces-the-following-error/2307/1 "2022-11-22T15:16:38Z")

</div>

```auto
def layer(W):
    for i in range(6):
        qml.Rot(W[i, 0], W[i, 1], W[i, 2], wires=i)
    for i in range(4):
        qml.CNOT(wires=[i, i + 1])
    qml.CNOT(wires=[5, 0])
    
def statepreparation(x):
    qml.MottonenStatePreparation(Norm1DArray(x), wires=[i for i in range(6)])
    
@qml.qnode(dev1)   
def conv_net(weights, x):

    statepreparation(x)

    
    for W in weights:
        layer(W)

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

```

```auto

opt = qml.NesterovMomentumOptimizer(0.05)
batch_size = 5

# train the variational classifier
weights = para_init
bias = bias_init

for it in range(60):

    # Update the weights by one optimizer step
    batch_index = np.random.randint(0, num_train, (batch_size,))
    x_train_batch = x_train[batch_index]
    y_train_batch = y_train[batch_index]
    weights, bias, _, _ = opt.step(cost, weights, bias, x_train_batch, y_train_batch)
    print(weights)

    # Compute predictions on train and validation set
    predictions_train = [np.sign(variational_classifier(weights, bias, f)) for f in x_train]
    predictions_val = [np.sign(variational_classifier(weights, bias, f)) for f in x_test]

    # Compute accuracy on train and validation set
    acc_train = accuracy(y_train, predictions_train)
    acc_val = accuracy(y_test, predictions_val)

    print(
        "Iter: {:5d} | Cost: {:0.7f} | Acc train: {:0.7f} | Acc validation: {:0.7f} "
        "".format(it + 1, cost(weights, bias, x_train, y_train), acc_train, acc_val)
    )# cost(para, bias, features, labels):

```

* * *

ValueError Traceback (most recent call last)  
Input In [28], in \<cell line: 8\>()  
12 x\_train\_batch = x\_train[batch\_index]  
13 y\_train\_batch = y\_train[batch\_index]  
—\> 14 weights, bias, \_, \_ = opt.step(cost, weights, bias, x\_train\_batch, y\_train\_batch)  
15 print(weights)  
17 # Compute predictions on train and validation set

File d:\miniconda3\lib\site-packages\pennylane\optimize\gradient\_descent.py:88, in GradientDescentOptimizer.step(self, objective\_fn, grad\_fn, \*args, \*\*kwargs)  
70 def step(self, objective\_fn, \*args, grad\_fn=None, \*\*kwargs):  
71 “”“Update trainable arguments with one step of the optimizer.  
72  
73 Args:  
(…)  
85 If single arg is provided, list [array] is replaced by array.  
86 “””  
—\> 88 g, \_ = self.compute\_grad(objective\_fn, args, kwargs, grad\_fn=grad\_fn)  
89 new\_args = self.apply\_grad(g, args)  
91 # unwrap from list if one argument, cleaner return

File d:\miniconda3\lib\site-packages\pennylane\optimize\nesterov\_momentum.py:71, in NesterovMomentumOptimizer.compute\_grad(self, objective\_fn, args, kwargs, grad\_fn)  
68 shifted\_args[index] = args[index] - self.momentum \* self.accumulation[index]  
70 g = get\_gradient(objective\_fn) if grad\_fn is None else grad\_fn  
—\> 71 grad = g(\*shifted\_args, \*\*kwargs)  
72 forward = getattr(g, “forward”, None)  
74 grad = (grad,) if len(trainable\_indices) == 1 else grad

File d:\miniconda3\lib\site-packages\pennylane\_grad.py:115, in grad. **call** (self, \*args, \*\*kwargs)  
112 self.\_forward = self.\_fun(\*args, \*\*kwargs)  
113 return ()  
 → 115 grad\_value, ans = grad\_fn(\*args, \*\*kwargs)  
116 self.\_forward = ans  
118 return grad\_value

File d:\miniconda3\lib\site-packages\autograd\wrap\_util.py:20, in unary\_to\_nary..nary\_operator..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 d:\miniconda3\lib\site-packages\pennylane\_grad.py:133, in grad.\_grad\_with\_forward(fun, x)  
127 @staticmethod  
128 @unary\_to\_nary  
129 def \_grad\_with\_forward(fun, x):  
130 “”“This function is a replica of `autograd.grad`, with the only  
131 difference being that it returns both the gradient _and_ the forward pass  
132 value.”“”  
 → 133 vjp, ans = \_make\_vjp(fun, x)  
135 if not vspace(ans).size == 1:  
136 raise TypeError(  
137 "Grad only applies to real scalar-output functions. "  
138 “Try jacobian, elementwise\_grad or holomorphic\_grad.”  
139 )

File d:\miniconda3\lib\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 d:\miniconda3\lib\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 d:\miniconda3\lib\site-packages\autograd\wrap\_util.py:15, in unary\_to\_nary..nary\_operator..nary\_f..unary\_f(x)  
13 else:  
14 subargs = subvals(args, zip(argnum, x))  
—\> 15 return fun(\*subargs, \*\*kwargs)

Input In [24], in cost(para, bias, features, labels)  
202 def cost(para, bias, features, labels):  
 → 203 predictions = [variational\_classifier(para, bias, f) for f in features]  
204 return square\_loss(labels, predictions)

Input In [24], in (.0)  
202 def cost(para, bias, features, labels):  
 → 203 predictions = [variational\_classifier(para, bias, f) for f in features]  
204 return square\_loss(labels, predictions)

Input In [24], in variational\_classifier(para, bias, features)  
199 def variational\_classifier(para, bias, features):  
 → 200 return conv\_net(para, features) + bias

File d:\miniconda3\lib\site-packages\pennylane\qnode.py:611, in QNode. **call** (self, \*args, \*\*kwargs)  
608 set\_shots(self.\_original\_device, override\_shots)(self.\_update\_gradient\_fn)()  
610 # construct the tape  
 → 611 self.construct(args, kwargs)  
613 cache = self.execute\_kwargs.get(“cache”, False)  
614 using\_custom\_cache = (  
615 hasattr(cache, “ **getitem** ”)  
616 and hasattr(cache, “ **setitem** ”)  
617 and hasattr(cache, “ **delitem** ”)  
618 )

File d:\miniconda3\lib\site-packages\pennylane\qnode.py:526, in QNode.construct(self, args, kwargs)  
523 self.\_tape = qml.tape.QuantumTape()  
525 with self.tape:  
 → 526 self.\_qfunc\_output = self.func(\*args, \*\*kwargs)  
527 self.\_tape.\_qfunc\_output = self.\_qfunc\_output  
529 params = self.tape.get\_parameters(trainable\_only=False)

Input In [24], in conv\_net(weights, x)  
172 @qml.qnode(dev1)  
173 def conv\_net(weights, x):  
 → 175 statepreparation(x)  
178 for W in weights:  
179 layer(W)

Input In [24], in statepreparation(x)  
169 def statepreparation(x):  
 → 170 qml.MottonenStatePreparation(Norm1DArray(x), wires=[i for i in range(6)])

File d:\miniconda3\lib\site-packages\pennylane\templates\state\_preparations\mottonen.py:314, in MottonenStatePreparation. **init** (self, state\_vector, wires, do\_queue, id)  
312 norm = qml.math.sum(qml.math.abs(state) \*\* 2)  
313 if not qml.math.allclose(norm, 1.0, atol=1e-3):  
 → 314 raise ValueError(  
315 f"State vectors have to be of norm 1.0, vector {i} has norm {norm}"  
316 )  
318 super(). **init** (state\_vector, wires=wires, do\_queue=do\_queue, id=id)

`ValueError: State vectors have to be of norm 1.0, vector 0 has norm Autograd ArrayBox with value nan`  
@Maria_Schuld  
@isaacdevlugt

---

<div class="post-metadata">

**Author:** ![CatalinaAlbornoz](https://yyz2.discourse-cdn.com/flex012/user_avatar/discuss.pennylane.ai/catalinaalbornoz/32/1196_2.png) [@CatalinaAlbornoz](https://discuss.pennylane.ai/u/CatalinaAlbornoz)\
**Post date:** [November 23, 2022, 5:09pm UTC](https://discuss.pennylane.ai/t/optimizing-the-parameters-of-mottonenstatepreparation-produces-the-following-error/2307/2 "2022-11-23T17:09:10Z")

</div>

Hi @RX1 ,

Unfortunately due to non-trivial classical processing of the state vector, the [MottonenStatePreparation](https://docs.pennylane.ai/en/stable/code/api/pennylane.MottonenStatePreparation.html) template is not always fully differentiable.

I’m not sure if this is the cause of the problem though because I wasn’t able to reproduce your problem since the code you have shared doesn’t include everything that I would need to run it. If you share the rest of your code including the creation of the device, para\_init, and other variables I can try to see if I can reproduce your problem.

I hope this is helpful.  
Please let me know if you have any additional questions!

---

<div class="post-metadata">

**Author:** ![RX1](https://yyz2.discourse-cdn.com/flex012/user_avatar/discuss.pennylane.ai/rx1/32/698_2.png) [@RX1](https://discuss.pennylane.ai/u/RX1)\
**Post date:** [November 23, 2022, 11:46pm UTC](https://discuss.pennylane.ai/t/optimizing-the-parameters-of-mottonenstatepreparation-produces-the-following-error/2307/3 "2022-11-23T23:46:03Z")

</div>

So if I convert MottonenStatePreparation to controlled RY and CNOT gates via compute\_decomposition and re-express MottonenStatePreparation in terms of basic quantum gates, is this fully differentiable? Like this:

 ![图片1](https://canada1.discourse-cdn.com/flex012/uploads/pennylane/original/2X/a/a90ef88b441169e099683a93d788946354b93abd.png)

 ![image](https://canada1.discourse-cdn.com/flex012/uploads/pennylane/original/2X/5/5d988709fca3fd4b4e09320ee8942b155cf03bd5.png)

@CatalinaAlbornoz  
@isaacdevlugt

---

<div class="post-metadata">

**Author:** ![CatalinaAlbornoz](https://yyz2.discourse-cdn.com/flex012/user_avatar/discuss.pennylane.ai/catalinaalbornoz/32/1196_2.png) [@CatalinaAlbornoz](https://discuss.pennylane.ai/u/CatalinaAlbornoz)\
**Post date:** [December 23, 2022, 10:01pm UTC](https://discuss.pennylane.ai/t/optimizing-the-parameters-of-mottonenstatepreparation-produces-the-following-error/2307/4 "2022-12-23T22:01:38Z")

</div>

Hi @RX1 , I still don’t think this can be fully differentiable but you can try.
