1
$\begingroup$

I'm not sure how to properly bind parameters in the circuit. I don't know why I got the following traceback even though I used .bind_parameters() in my earlier code here:

def run(self, thetas):

    self._circuit = self._circuit.bind_parameters({self.theta: thetas[0]})
    self.mitiq_circuit = convert_to_mitiq(self._circuit)[0]
    self.cirq_circuit = convert_from_mitiq(self.mitiq_circuit, "cirq")
    
    def simulate(circuit: cirq.Circuit) -> np.ndarray:
        return compute_density_matrix(circuit, noise_level=(0.0,))

    mitigated_measurement = cdr.execute_with_cdr(
        self.cirq_circuit,
        compute_density_matrix,
        observable=self.obs,
        simulator=simulate,
        seed=0,
        scale_factors=(1.0, 3.0),
    ).real
    
    return np.array([mitigated_measurement]) 

I ran the following code:

circuit = QuantumCircuit(1, simulator, 100)
print('Expected value for rotation pi {}'.format(circuit.run([np.pi])[0]))

Error traceback:

    ---------------------------------------------------------------------------
CircuitError                              Traceback (most recent call last)
/Users/colinhong/Library/CloudStorage/OneDrive-NanyangTechnologicalUniversity/Summer 2022/QML Intern/Qiskit Tutorials/machine-learning-qiskit-pytorch.ipynb Cell 24 in <cell line: 9>()
     16 loss = loss_func(output, target)
     17 # Backward pass
---> 18 loss.backward()
     19 # Optimize the weights
     20 optimizer.step()

File /Users/Shared/anaconda3/envs/mitiq-env/lib/python3.8/site-packages/torch/_tensor.py:396, in Tensor.backward(self, gradient, retain_graph, create_graph, inputs)
    387 if has_torch_function_unary(self):
    388     return handle_torch_function(
    389         Tensor.backward,
    390         (self,),
   (...)
    394         create_graph=create_graph,
    395         inputs=inputs)
--> 396 torch.autograd.backward(self, gradient, retain_graph, create_graph, inputs=inputs)

File /Users/Shared/anaconda3/envs/mitiq-env/lib/python3.8/site-packages/torch/autograd/__init__.py:173, in backward(tensors, grad_tensors, retain_graph, create_graph, grad_variables, inputs)
    168     retain_graph = create_graph
    170 # The reason we repeat same the comment below is that
    171 # some Python versions print out the first line of a multi-line function
    172 # calls in the traceback and some print out the last line
--> 173 Variable._execution_engine.run_backward(  # Calls into the C++ engine to run the backward pass
    174     tensors, grad_tensors_, retain_graph, create_graph, inputs,
    175     allow_unreachable=True, accumulate_grad=True)

File /Users/Shared/anaconda3/envs/mitiq-env/lib/python3.8/site-packages/torch/autograd/function.py:253, in BackwardCFunction.apply(self, *args)
    249     raise RuntimeError("Implementing both 'backward' and 'vjp' for a custom "
    250                        "Function is not allowed. You should only implement one "
    251                        "of them.")
    252 user_fn = vjp_fn if vjp_fn is not Function.vjp else backward_fn
--> 253 return user_fn(self, *args)

/Users/colinhong/Library/CloudStorage/OneDrive-NanyangTechnologicalUniversity/Summer 2022/QML Intern/Qiskit Tutorials/machine-learning-qiskit-pytorch.ipynb Cell 24 in HybridFunction.backward(ctx, grad_output)
     25 gradients = []
     26 for i in range(len(input_list)):
---> 27     expectation_right = ctx.quantum_circuit.run(shift_right[i])
     28     expectation_left  = ctx.quantum_circuit.run(shift_left[i])
     30     gradient = torch.tensor([expectation_right]) - torch.tensor([expectation_left])

/Users/colinhong/Library/CloudStorage/OneDrive-NanyangTechnologicalUniversity/Summer 2022/QML Intern/Qiskit Tutorials/machine-learning-qiskit-pytorch.ipynb Cell 24 in QuantumCircuit.run(self, thetas)
     28 def run(self, thetas):
     29 
     30     # self.thetas = qiskit.circuit.ParameterVector('theta', 1)
     31     # self._circuit = self._circuit.bind_parameters({self.theta: n for n in thetas})
---> 32     self._circuit = self._circuit.bind_parameters({self.theta: thetas[0]})
     33     self.mitiq_circuit = convert_to_mitiq(self._circuit)[0]
     34     self.cirq_circuit = convert_from_mitiq(self.mitiq_circuit, "cirq")

File /Users/Shared/anaconda3/envs/mitiq-env/lib/python3.8/site-packages/qiskit/circuit/quantumcircuit.py:2622, in QuantumCircuit.bind_parameters(self, values)
   2618     if any(isinstance(value, ParameterExpression) for value in values.values()):
   2619         raise TypeError(
   2620             "Found ParameterExpression in values; use assign_parameters() instead."
   2621         )
-> 2622     return self.assign_parameters(values)
   2623 else:
   2624     if any(isinstance(value, ParameterExpression) for value in values):

File /Users/Shared/anaconda3/envs/mitiq-env/lib/python3.8/site-packages/qiskit/circuit/quantumcircuit.py:2577, in QuantumCircuit.assign_parameters(self, parameters, inplace)
   2571 params_not_in_circuit = [
   2572     param_key
   2573     for param_key in unrolled_param_dict
   2574     if param_key not in unsorted_parameters
   2575 ]
   2576 if len(params_not_in_circuit) > 0:
-> 2577     raise CircuitError(
   2578         "Cannot bind parameters ({}) not present in the circuit.".format(
   2579             ", ".join(map(str, params_not_in_circuit))
   2580         )
   2581     )
   2583 # replace the parameters with a new Parameter ("substitute") or numeric value ("bind")
   2584 for parameter, value in unrolled_param_dict.items():

CircuitError: 'Cannot bind parameters (theta) not present in the circuit.'
$\endgroup$

1 Answer 1

1
$\begingroup$

Qiskit is complaining because apparently self.theta is not present in the circuit. There's two solutions to this:

  1. Ensure that self.theta is the Parameter instance that's used in self._circuit
  2. Just bind the parameters via array, then you don't have to bother about which Parameter instance is used:
    self._circuit = self._circuit.bind_parameters([thetas[0]])
    
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.