Error executing "Kernel-based training of quantum models with scikit-learn" notebook


I am trying to execute in my server pennylane’s " Kernel-based training of quantum models with scikit-learn" notebook but I obtain the following error:

RuntimeError                              Traceback (most recent call last)
Cell In[13], line 4
      2 batch_size = 20
      3 steps = 100
----> 4 trained_params, trained_bias, loss_history = quantum_model_train(n_layers, steps, batch_size)
      6 pred_test = quantum_model_predict(X_test, trained_params, trained_bias)
      7 print("accuracy on test set:", accuracy_score(pred_test, y_test))

Cell In[12], line 37, in quantum_model_train(n_layers, steps, batch_size)
     34         loss.backward()
     35         return loss
---> 37     opt.step(closure)
     39 return params_torch, bias_torch, loss_history

File ~\AppData\Local\miniconda3\envs\cuantica\Lib\site-packages\torch\optim\, in Optimizer.profile_hook_step.<locals>.wrapper(*args, **kwargs)
    368         else:
    369             raise RuntimeError(
    370                 f"{func} must return None or a tuple of (new_args, new_kwargs), but got {result}."
    371             )
--> 373 out = func(*args, **kwargs)
    374 self._optimizer_step_code()
    376 # call optimizer step post hooks

File ~\AppData\Local\miniconda3\envs\cuantica\Lib\site-packages\torch\optim\, in _use_grad_for_differentiable.<locals>._use_grad(self, *args, **kwargs)
     74     torch.set_grad_enabled(self.defaults['differentiable'])
     75     torch._dynamo.graph_break()
---> 76     ret = func(self, *args, **kwargs)
     77 finally:
     78     torch._dynamo.graph_break()

File ~\AppData\Local\miniconda3\envs\cuantica\Lib\site-packages\torch\optim\, in Adam.step(self, closure)
    141 if closure is not None:
    142     with torch.enable_grad():
--> 143         loss = closure()
    145 for group in self.param_groups:
    146     params_with_grad = [x]

Cell In[12], line 34, in quantum_model_train.<locals>.closure()
     31 if i % 10 == 0:
     32     print("step", i, ", loss", current_loss)
---> 34 loss.backward()
     35 return loss

File ~\AppData\Local\miniconda3\envs\cuantica\Lib\site-packages\torch\, in Tensor.backward(self, gradient, retain_graph, create_graph, inputs)
    482 if has_torch_function_unary(self):
    483     return handle_torch_function(
    484         Tensor.backward,
    485         (self,),
    490         inputs=inputs,
    491     )
--> 492 torch.autograd.backward(
    493     self, gradient, retain_graph, create_graph, inputs=inputs
    494 )

File ~\AppData\Local\miniconda3\envs\cuantica\Lib\site-packages\torch\autograd\, in backward(tensors, grad_tensors, retain_graph, create_graph, grad_variables, inputs)
    246     retain_graph = create_graph
    248 # The reason we repeat the same comment below is that
    249 # some Python versions print out the first line of a multi-line function
    250 # calls in the traceback and some print out the last line
--> 251 Variable._execution_engine.run_backward(  # Calls into the C++ engine to run the backward pass
    252     tensors,
    253     grad_tensors_,
    254     retain_graph,
    255     create_graph,
    256     inputs,
    257     allow_unreachable=True,
    258     accumulate_grad=True,
    259 )

RuntimeError: element 0 of tensors does not require grad and does not have a grad_fn

I dont know how to solve it. If someone could help me I would be very pleased.


Hey @Guillermo_Valverde! Welcome back :slight_smile:

The demo runs perfectly fine for me with up-to-date versions of scikit-learn, PyTorch, and PennyLane. I’m not sure what package versions are on your server, but I bet if you update everything to the latest versions that it will work :+1:. If you’re using a virtual environment, you can do this:

python -m pip install --upgrade pennylane torch scikit-learn

One thing to note is that num_executions is no longer an attribute, so I had to modify the demo a bit. I’ve already made a PR for that here:

Let me know if this helps!

1 Like

Problem solved. Thank you very much Isaac! It is very rewarding to have a forum like this that helps you solve your problems when you encounter difficulties.

1 Like

Awesome! Glad I could help :slight_smile: thank you for the positive feedback, as well! I’m happy our work doesn’t go unnoticed :star_struck:

By the way, we have a very small survey for PennyLane v0.33, and it would be awesome if you’d give us some feedback and tell us about your needs. Thank you! :grin: