Qiskit / qiskit

Qiskit is an open-source SDK for working with quantum computers at the level of extended quantum circuits, operators, and primitives.
https://www.ibm.com/quantum/qiskit
Apache License 2.0
5.25k stars 2.36k forks source link

VQE Error #10277

Closed ethraj2001 closed 1 year ago

ethraj2001 commented 1 year ago

Informations

What is the current behavior?

  ---------------------------------------------------------------------------
IBMRuntimeError                           Traceback (most recent call last)
File ~\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\qiskit\algorithms\minimum_eigensolvers\vqe.py:253, in VQE._get_evaluate_energy..evaluate_energy(parameters)
    252 try:
--> 253     job = self.estimator.run(batch_size * [ansatz], batch_size * [operator], parameters)
    254     estimator_result = job.result()

File ~\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\qiskit_ibm_runtime\estimator.py:179, in Estimator.run(self, circuits, observables, parameter_values, **kwargs)
    178 user_kwargs = {"_user_kwargs": kwargs}
--> 179 return super().run(
    180     circuits=circuits,
    181     observables=observables,
    182     parameter_values=parameter_values,
    183     **user_kwargs,
    184 )

File ~\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\qiskit\primitives\base\base_estimator.py:185, in BaseEstimator.run(self, circuits, observables, parameter_values, **run_options)
    183 run_opts.update_options(**run_options)
--> 185 return self._run(
    186     circuits,
    187     observables,
    188     parameter_values,
    189     **run_opts.__dict__,
    190 )

File ~\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\qiskit_ibm_runtime\estimator.py:262, in Estimator._run(self, circuits, observables, parameter_values, **kwargs)
    260         backend_obj.check_faulty(circ)
--> 262 return self._session.run(
    263     program_id=self._PROGRAM_ID,
    264     inputs=inputs,
    265     options=Options._get_runtime_options(combined),
    266     callback=combined.get("environment", {}).get("callback", None),
    267     result_decoder=DEFAULT_DECODERS.get(self._PROGRAM_ID),
    268 )

File ~\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\qiskit_ibm_runtime\session.py:39, in _active_session.._wrapper(self, *args, **kwargs)
     38     raise RuntimeError("The session is closed.")
---> 39 return func(self, *args, **kwargs)

File ~\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\qiskit_ibm_runtime\session.py:182, in Session.run(self, program_id, inputs, options, callback, result_decoder)
    180     options["session_time"] = self._max_time
--> 182 job = self._service.run(
    183     program_id=program_id,
    184     options=options,
    185     inputs=inputs,
    186     session_id=self._session_id,
    187     start_session=self._session_id is None,
    188     callback=callback,
    189     result_decoder=result_decoder,
    190 )
    192 if self._session_id is None:

File ~\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\qiskit_ibm_runtime\qiskit_runtime_service.py:1022, in QiskitRuntimeService.run(self, program_id, inputs, options, callback, result_decoder, session_id, start_session)
   1019         raise RuntimeProgramNotFound(
   1020             f"Program not found: {ex.message}"
   1021         ) from None
-> 1022     raise IBMRuntimeError(f"Failed to run program: {ex}") from None
   1024 backend = self.backend(name=response["backend"], instance=hgp_name)

IBMRuntimeError: 'Failed to run program: \'400 Client Error: Bad Request for url: https://runtime-us-east.quantum-computing.ibm.com/jobs. {"errors":[{"code":1217,"message":"Session has been closed.","solution":"Reduce time between submitting subsequent jobs in a session.","more_info":"https://cloud.ibm.com/apidocs/quantum-computing#error-handling"}],"trace":"ci3hdtm1o26hu34621sg"}\''

The above exception was the direct cause of the following exception:

AlgorithmError                            Traceback (most recent call last)
Cell In[6], line 20
     18 with Session(service=service, backend=backend) as session: 
     19     estimator = RuntimeEstimator(session=session)
---> 20     converge_cnts, converge_vals, result = Run_VQE(a, optimizers, params, estimator)

Cell In[5], line 22, in Run_VQE(a, optimizer, params, estimator)
     20 values = []
     21 vqe = VQE(estimator=estimator, ansatz=a, optimizer=optimizer, initial_point=params, callback=store_intermediate_result)
---> 22 results = vqe.compute_minimum_eigenvalue(operator=h_dvr_p0)
     23 print()
     24 if (best_res1 is None) or (values[-1] <= best_res1):

File ~\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\qiskit\algorithms\minimum_eigensolvers\vqe.py:191, in VQE.compute_minimum_eigenvalue(self, operator, aux_operators)
    186 else:
    187     # we always want to submit as many estimations per job as possible for minimal
    188     # overhead on the hardware
    189     was_updated = _set_default_batchsize(self.optimizer)
--> 191     optimizer_result = self.optimizer.minimize(
    192         fun=evaluate_energy, x0=initial_point, jac=evaluate_gradient, bounds=bounds
    193     )
    195     # reset to original value
    196     if was_updated:

File ~\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\qiskit\algorithms\optimizers\spsa.py:558, in SPSA.minimize(self, fun, x0, jac, bounds)
    556 iteration_start = time()
    557 # compute update
--> 558 fx_estimate, update = self._compute_update(fun, x, k, next(eps), lse_solver)
    560 # trust region
    561 if self.trust_region:

File ~\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\qiskit\algorithms\optimizers\spsa.py:489, in SPSA._compute_update(self, loss, x, k, eps, lse_solver)
    486     num_samples = self.resamplings
    488 # accumulate the number of samples
--> 489 value, gradient, hessian = self._point_estimate(loss, x, eps, num_samples)
    491 # precondition gradient with inverse Hessian, if specified
    492 if self.second_order:

File ~\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\qiskit\algorithms\optimizers\spsa.py:466, in SPSA._point_estimate(self, loss, x, eps, num_samples)
    463 delta1 = deltas1[i]
    464 delta2 = deltas2[i] if self.second_order else None
--> 466 value_sample, gradient_sample, hessian_sample = self._point_sample(
    467     loss, x, eps, delta1, delta2
    468 )
    469 value_estimate += value_sample
    470 gradient_estimate += gradient_sample

File ~\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\qiskit\algorithms\optimizers\spsa.py:427, in SPSA._point_sample(self, loss, x, eps, delta1, delta2)
    424     self._nfev += 2
    426 # batch evaluate the points (if possible)
--> 427 values = _batch_evaluate(loss, points, self._max_evals_grouped)
    429 plus = values[0]
    430 minus = values[1]

File ~\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\qiskit\algorithms\optimizers\spsa.py:748, in _batch_evaluate(function, points, max_evals_grouped, unpack_points)
    746         results += _as_list(function(*batch))
    747     else:
--> 748         results += _as_list(function(batch))
    750 return results

File ~\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\qiskit\algorithms\minimum_eigensolvers\vqe.py:256, in VQE._get_evaluate_energy..evaluate_energy(parameters)
    254     estimator_result = job.result()
    255 except Exception as exc:
--> 256     raise AlgorithmError("The primitive job to evaluate the energy failed!") from exc
    258 values = estimator_result.values
    260 if self.callback is not None:

AlgorithmError: 'The primitive job to evaluate the energy failed!' 

Steps to reproduce the problem

Not very sure to be honest, but here is my code. I am very new to this so please forgive my vague answers:

from qiskit.algorithms import VQE
def Run_VQE(a, optimizer, params, estimator):
    """ This is the function that runs the VQE."""
    repeat = 1
    params = None
    # params = np.array([float(i) for i in result.optimal_parameters.values()])
    converge_cnts1 = []
    converge_vals1 = []

    print('Optimizer: {}        '.format(type(optimizer).__name__))

    def store_intermediate_result(eval_count, parameters, mean, std):
        counts.append(eval_count)
        values.append(mean)
        print(f'\r{eval_count}, {mean}', end='')
    best_res1 = None

    for j in range(repeat):
        counts = []
        values = []
        vqe = VQE(estimator=estimator, ansatz=a, optimizer=optimizer, initial_point=params, callback=store_intermediate_result)
        results = vqe.compute_minimum_eigenvalue(operator=h_dvr_p0)
        print()
        if (best_res1 is None) or (values[-1] <= best_res1):
            best_res1 = values[-1]
            converge_cnts1 = np.asarray(counts)
            converge_vals1 = np.asarray(values)
    print('\nOptimization complete ')
    return converge_cnts1, converge_vals1, results

What is the expected behavior?

It's just supposed to run at least once properly.

Suggested solutions

max time of the algorithm could be changed?

woodsp-ibm commented 1 year ago

IBMRuntimeError: 'Failed to run program: \'400 Client Error: Bad Request for url: https://runtime-us-east.quantum-computing.ibm.com/jobs. {"errors":[{"code":1217,"message":"Session has been closed.","solution":"Reduce time between submitting subsequent jobs in a session.","more_info":"https://cloud.ibm.com/apidocs/quantum-computing#error-handling"}],"trace":"ci3hdtm1o26hu34621sg"}\''

This is discussed here https://qiskit.slack.com/archives/C7SJ0PJ5A/p1686610666043249

As I pointed out to you there, there is max time limit for usage - for open usage on a real device this is 4hrs which in that thread is about the time that your code ran before its Session was closed. Maybe break the loop and do it as different jobs on different Session/Estimator.

There is not a problem with VQE, as such, more that Runtime is limiting the usage - hence I am closing this.