Skip to content

[python] Use separate context for kernel builder#3940

Closed
lmondada wants to merge 1 commit intoNVIDIA:mainfrom
lmondada:lm/builder-ctx
Closed

[python] Use separate context for kernel builder#3940
lmondada wants to merge 1 commit intoNVIDIA:mainfrom
lmondada:lm/builder-ctx

Conversation

@lmondada
Copy link
Collaborator

This PR fixes the following crash

import cudaq

kernel = cudaq.make_kernel()

@cudaq.kernel()
def kernel2():
    pass

kernel.qalloc(1) # this (or any other MLIR modification) crashes

Error: RuntimeError: the operation has been invalidated

The reason for this is that kernel2 was getting compiled using compile_to_mlir in python/cudaq/kernel/ast_bridge.py. This calls context._clear_live_operations() at the end of the function. However, the context is global, thus it also clears the context for the kernel builder. This invalidates the insertion point stored in the builder, hence any further modifications of the kernel builder fails.

This PR proposes to use a separate context for the kernel builder. When a kernel builder gets invoked and needs to be jitted, we then output the module as string and reload it into the global context. This will come at some performance cost, but only affects kernels defined using the builder and only at the first invocation (as the compiled MLIR module is cached).

@lmondada lmondada force-pushed the lm/builder-ctx branch 2 times, most recently from 4c97fda to 21e2e30 Compare February 12, 2026 18:30
Signed-off-by: Luca Mondada <luca@mondada.net>
@github-actions
Copy link

CUDA Quantum Docs Bot: A preview of the documentation can be found here.

@lmondada
Copy link
Collaborator Author

We'll have to discuss a plan to fix this. For now I've disabled using the kernel builder with kernels that have deferred compilation.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant