PennyLaneAI / catalyst

A JIT compiler for hybrid quantum programs in PennyLane
https://docs.pennylane.ai/projects/catalyst
Apache License 2.0
109 stars 28 forks source link

Users can perform runtime validation within QJIT functions #823

Open dime10 opened 1 month ago

dime10 commented 1 month ago

Context

JITing Python functions can provide order(s) of magnitude performance boost during execution, by extracting a representation of the computation and turning it into optimized binary code. However, it also makes it more difficult to understand and debug the program when things go wrong, for instance by not having access to the Python debugger or being able to easily reason about the program's execution.

To counter-act this, we can introduce new utility functions for users that help increase the confidence in their programs and detect error states at runtime.

Goal

We would like to add a debugging function catalyst.assert(bool, str) that asserts at runtime that the given condition holds, and if not raises the provided error message.

@qjit
def f(x: int):
    catalyst.assert(x < 5, "expected x to be less than 5")
    return 2*x

>>> f(3)
6
>>> f(5)
RuntimeError: expected x to be less than 5

Requirements:

Technical Details

Generally speaking adding a new operator to Catalyst involves providing a representation across its different representations:

Once the Operation can be created and lowered all the way to the runtime, we want to make sure we are able to disable it using the aforementioned compiler pass. Write a small transformation pass using the pattern rewriter in MLIR that eliminates all instances of the assert operations from the IR. It can then be included as an optional pass in the Quantum Compilation Pass Pipeline.

Installation Help

Refer to the Catalyst installation guide for how to install a source build of the project.