CUDA-Q backend transpiler implementation.
This module provides CudaqTranspiler for converting Qamomile QKernels into CUDA-Q decorator-kernel artifacts, along with CudaqExecutor.
All circuits (static and runtime) are emitted through a single
CudaqKernelEmitter codegen path. The emitter produces
CudaqKernelArtifact instances whose execution_mode determines
whether cudaq.sample() / cudaq.observe() / cudaq.get_state()
(STATIC) or cudaq.run() (RUNNABLE) is used for execution.
Overview¶
| Class | Description |
|---|---|
BoundCudaqKernelArtifact | Hold a CUDA-Q kernel with runtime parameters bound. |
CudaqExecutor | CUDA-Q quantum executor. |
CudaqKernelArtifact | Compiled CUDA-Q decorator-kernel artifact. |
CudaqMaterializer | Convert verified circuit IR to a CUDA-Q source-built kernel. |
CudaqTranspiler | CUDA-Q transpiler for qamomile.circuit module. |
EmitPass | Base class for backend-specific emission passes. |
ExecutionMode | Execution mode for a CUDA-Q kernel artifact. |
SegmentationPass | Segment a block into a strategy-specific executable program plan. |
Transpiler | Base class for backend-specific transpilers. |
Classes¶
BoundCudaqKernelArtifact [source]¶
class BoundCudaqKernelArtifactHold a CUDA-Q kernel with runtime parameters bound.
Parameters:
| Name | Type | Description |
|---|---|---|
kernel_func | Any | Decorated CUDA-Q kernel. |
num_qubits | int | Number of physical qubits. |
num_clbits | int | Number of logical measurement bits. |
param_values | list[float] | Bound parameter values in backend order. |
execution_mode | ExecutionMode | Runtime API required by the kernel. |
Constructor¶
def __init__(
self,
kernel_func: Any,
num_qubits: int,
num_clbits: int,
param_values: list[float],
execution_mode: ExecutionMode = ExecutionMode.STATIC,
) -> NoneAttributes¶
execution_mode: ExecutionModekernel_func: Anynum_clbits: intnum_qubits: intparam_values: list[float]
CudaqExecutor [source]¶
class CudaqExecutor(QuantumExecutor[CudaqKernelArtifact])CUDA-Q quantum executor.
Supports sampling via cudaq.sample / cudaq.run and expectation
value estimation via cudaq.observe. Dispatches to the appropriate
CUDA-Q runtime API based on the artifact’s execution_mode:
STATICartifacts (no mid-circuit measurement or runtime control flow) support both sampling (cudaq.sample) and expectation-value estimation (cudaq.observe).RUNNABLEartifacts (mid-circuit measurement or measurement-dependent control flow such asif bit:/while bit:) support sampling only, viacudaq.run.
Expectation-value estimation is therefore static-only: calling
:meth:estimate on a RUNNABLE artifact raises TypeError because
cudaq.observe cannot consume a kernel that requires cudaq.run.
See :meth:estimate for the full rationale.
Parameters:
| Name | Type | Description |
|---|---|---|
target | str | None | CUDA-Q target name (e.g., "qpp-cpu"). If None, uses the default CUDA-Q target. |
Constructor¶
def __init__(self, target: str | None = None)Methods¶
bind_parameters¶
def bind_parameters(
self,
circuit: Any,
bindings: dict[str, Any],
parameter_metadata: ParameterMetadata,
) -> BoundCudaqKernelArtifactBind parameters to a circuit for execution.
Returns a BoundCudaqKernelArtifact with the execution mode
inherited from the source artifact.
estimate¶
def estimate(
self,
circuit: Any,
hamiltonian: 'qm_o.Hamiltonian',
params: Sequence[float] | None = None,
) -> floatEstimate an expectation value using cudaq.observe.
Expectation-value estimation on the CUDA-Q backend is static-only.
It is supported exclusively for STATIC-mode artifacts, which are
evaluated with cudaq.observe(). RUNNABLE-mode artifacts (a
kernel containing mid-circuit measurement or measurement-dependent
control flow such as if bit: / while bit:) are emitted for
cudaq.run(), and cudaq.observe() cannot consume them. Such
artifacts therefore raise TypeError rather than silently returning
a meaningless value.
This is a CUDA-Q API limitation, not merely a Qamomile gap:
cudaq.observe() evaluates the analytic expectation value of a
deterministic state-preparation kernel and has no execution path for a
kernel that requires the per-shot cudaq.run() runtime. There is no
safe alternative that preserves the exact-expectation contract of this
method, so the TypeError path is intentional. Under the current
affine model a single Qamomile kernel also cannot be both RUNNABLE
and carry a terminal qmc.expval (reusing a measured qubit is
rejected), so the ExecutableProgram.run expval path does not reach
this guard; it is reached only when estimate is called directly on
a RUNNABLE artifact.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | A CUDA-Q artifact (CudaqKernelArtifact or BoundCudaqKernelArtifact). Must be STATIC-mode; RUNNABLE-mode artifacts are rejected. |
hamiltonian | qm_o.Hamiltonian | The observable to measure. A qamomile.observable.Hamiltonian is converted to a CUDA-Q SpinOperator; an already-converted operator is used as-is. |
params | Sequence[float] | None | Values for the kernel’s runtime parameters slots, in declared parameter order. Compile- time-bound parameters are already baked into the artifact and are not included here. Defaults to None for a non-parametric or already-bound (BoundCudaqKernelArtifact) kernel. |
Returns:
float — The estimated expectation value <psi|H|psi>.
Raises:
TypeError— Ifcircuitis aRUNNABLE-mode artifact, sincecudaq.observe()only accepts static state-preparation kernels (see the static-only note above).
Example:
>>> transpiler = CudaqTranspiler()
>>> exe = transpiler.transpile(static_ansatz, bindings={"H": H})
>>> executor = transpiler.executor()
>>> value = executor.estimate(exe.get_first_circuit(), H)execute¶
def execute(self, circuit: Any, shots: int) -> dict[str, int]Execute circuit and return canonical big-endian bitstring counts.
Dispatches based on execution_mode:
STATIC: usescudaq.sample()on the decorator kernel.RUNNABLE: usescudaq.run()on the runnable kernel.
Both paths return bitstrings in big-endian format (highest qubit
index = leftmost bit). An artifact without quantum or classical bits
returns {"": shots} without calling the CUDA-Q runtime.
CudaqKernelArtifact [source]¶
class CudaqKernelArtifactCompiled CUDA-Q decorator-kernel artifact.
Wraps a @cudaq.kernel decorated function produced by
CudaqKernelEmitter. The execution_mode field determines
which CUDA-Q runtime APIs are valid for this artifact.
Parameters:
| Name | Type | Description |
|---|---|---|
kernel_func | Any | The @cudaq.kernel decorated function, or None before finalize() is called. |
num_qubits | int | Number of qubits in the circuit. |
num_clbits | int | Number of classical bits in the circuit. |
source | str | Generated Python source code (for debugging). |
entry_source | str | Generated Python source for the entry-point kernel only. This is identical to source in the single-entrypoint materialization path. |
execution_mode | ExecutionMode | Whether this is a STATIC or RUNNABLE kernel. |
param_count | int | Number of variational parameters. |
Constructor¶
def __init__(
self,
kernel_func: Any,
num_qubits: int,
num_clbits: int,
source: str = '',
entry_source: str = '',
execution_mode: ExecutionMode = ExecutionMode.STATIC,
param_count: int = 0,
) -> NoneAttributes¶
entry_source: strexecution_mode: ExecutionModekernel_func: Anynum_clbits: intnum_qubits: intparam_count: intsource: str
CudaqMaterializer [source]¶
class CudaqMaterializerConvert verified circuit IR to a CUDA-Q source-built kernel.
Attributes¶
capabilities: CircuitCapabilities Declare CUDA-Q’s circuit-IR capabilities.
Methods¶
materialize¶
def materialize(
self,
program: CircuitProgram,
parameter_names: tuple[str, ...] = (),
) -> MaterializedCircuit[Any]Build a CUDA-Q kernel and its execution metadata.
Parameters:
| Name | Type | Description |
|---|---|---|
program | CircuitProgram | Verified circuit-family program. |
parameter_names | tuple[str, ...] | Public runtime-parameter ABI in positional order. Defaults to an empty tuple. |
Returns:
MaterializedCircuit[Any] — MaterializedCircuit[Any]: CUDA-Q artifact, runtime parameters, and
static measurement mapping.
Raises:
EmitError— If CUDA-Q cannot represent an instruction.
CudaqTranspiler [source]¶
class CudaqTranspiler(Transpiler[CudaqKernelArtifact])CUDA-Q transpiler for qamomile.circuit module.
Converts Qamomile QKernels into CUDA-Q decorator-kernel artifacts.
Example:
from qamomile.cudaq import CudaqTranspiler
import qamomile.circuit as qm
@qm.qkernel
def bell_state(q0: qm.Qubit, q1: qm.Qubit) -> tuple[qm.Bit, qm.Bit]:
q0 = qm.h(q0)
q0, q1 = qm.cx(q0, q1)
return qm.measure(q0), qm.measure(q1)
transpiler = CudaqTranspiler()
executable = transpiler.transpile(bell_state)Methods¶
executor¶
def executor(self, target: str | None = None) -> CudaqExecutorCreate a CUDA-Q executor.
Parameters:
| Name | Type | Description |
|---|---|---|
target | str | None | CUDA-Q target name (e.g., "qpp-cpu"). If None, uses the default CUDA-Q target. |
EmitPass [source]¶
class EmitPass(Pass[ProgramPlan, ExecutableProgram[T]], Generic[T])Base class for backend-specific emission passes.
Subclasses implement _emit_quantum_segment() to generate backend-specific quantum circuits.
Input: ProgramPlan Output: ExecutableProgram with compiled segments
Constructor¶
def __init__(
self,
bindings: dict[str, Any] | None = None,
parameters: list[str] | None = None,
)Initialize with optional parameter bindings.
Parameters:
| Name | Type | Description |
|---|---|---|
bindings | dict[str, Any] | None | Values to bind parameters to. If not provided, parameters must be bound at execution time. |
parameters | list[str] | None | List of parameter names to preserve as backend parameters. |
Raises:
ValueError— If a name appears in bothbindingsandparameters. This is the innermost emit-side choke point: it catches the overlap even when anEmitPassis constructed directly (e.g. viaTranspiler._create_emit_pass), bypassing thetranspile/emitwrappers. A name in both is ambiguous and would otherwise silently bake the binding while dropping the runtime parameter (see #354).
Attributes¶
bindingsname: strparameters
Methods¶
run¶
def run(self, input: ProgramPlan) -> ExecutableProgram[T]Emit backend code from a program plan.
Parameters:
| Name | Type | Description |
|---|---|---|
input | ProgramPlan | Segmented plan whose quantum and classical steps should be compiled. |
Returns:
ExecutableProgram[T] — ExecutableProgram[T]: Executable program containing all compiled
segments and the public output contract.
ExecutionMode [source]¶
class ExecutionMode(enum.Enum)Execution mode for a CUDA-Q kernel artifact.
Determines which CUDA-Q runtime API is used for execution:
STATIC: Compatible withcudaq.sample(),cudaq.get_state(), andcudaq.observe(). The kernel has no explicit terminal measurements and no return value.RUNNABLE: Compatible withcudaq.run(). The kernel has explicit mid-circuit measurements and returnsmz(q)(list[bool]).
Attributes¶
RUNNABLESTATIC
SegmentationPass [source]¶
class SegmentationPass(Pass[Block, ProgramPlan])Segment a block into a strategy-specific executable program plan.
This pass:
Materializes return operations (syncs output_values from ReturnOperation)
Splits the operation list into quantum and classical segments
Builds a ProgramPlan via the configured segmentation strategy
Input: Block (typically ANALYZED or AFFINE) Output: ProgramPlan
Constructor¶
def __init__(self, strategy: SegmentationStrategy | None = None) -> NoneAttributes¶
name: str
Methods¶
run¶
def run(self, input: Block) -> ProgramPlanLower and segment a block into a program plan.
Parameters:
| Name | Type | Description |
|---|---|---|
input | Block | Block whose while contract and hybrid operations should be lowered before segmentation. |
Returns:
ProgramPlan — Strategy-produced execution plan.
Raises:
ValidationError— If a runtime while violates its contract.SeparationError— If the strategy finds no quantum segment.MultipleQuantumSegmentsError— If the strategy finds multiple quantum segments.
Transpiler [source]¶
class Transpiler(ABC, Generic[T])Base class for backend-specific transpilers.
Provides the full compilation pipeline from qkernel-like frontend objects to executable programs.
Example:
>>> from qamomile.circuit.transpiler import TranspilerConfig
>>> from qamomile.qiskit import QiskitTranspiler
>>> transpiler = QiskitTranspiler()
>>> executable = transpiler.transpile(kernel, bindings={"theta": 0.5})
>>> circuit = executable.get_first_circuit()
>>> config = TranspilerConfig.with_strategies({"qft": "approximate_k2"})
>>> transpiler.set_config(config)Attributes¶
MAX_UNROLL_DEPTH: intconfig: TranspilerConfig Get the transpiler configuration.
Methods¶
affine_validate¶
def affine_validate(self, block: Block) -> BlockPass 1.5: Validate affine type semantics.
This is a safety net to catch affine type violations that may have bypassed frontend checks. Validates that quantum values are used at most once.
analyze¶
def analyze(self, block: Block) -> BlockPass 2: Validate and analyze dependencies.
array_bounds_check¶
def array_bounds_check(self, block: Block) -> BlockPass 1.85: Reject reachable accesses outside resolved array bounds.
Runs after :meth:partial_eval so binding-dependent view extents and
indices are concrete where possible, and before declarative slice
operations are stripped. Statically zero-trip loop bodies are skipped
because their element accesses are unreachable.
Parameters:
| Name | Type | Description |
|---|---|---|
block | Block | Post-fold affine or hierarchical block to validate. |
Returns:
Block — The input block unchanged after successful validation.
Raises:
ValidationError— If a reachable constant element index is outside a resolved root-array or view-local extent.
classical_lowering¶
def classical_lowering(self, block: Block) -> BlockPass 2.25: Lower measurement-derived classical ops.
Identifies CompOp / CondOp / NotOp / BinOp
instances whose operand dataflow traces back to a measurement and
rewrites them to RuntimeClassicalExpr. Compile-time-foldable
and emit-time-foldable (loop-bound, parameter-bound) classical
ops are left unchanged.
Runs after analyze so the measurement-taint analysis has the
full dependency graph available, and before
validate_symbolic_shapes / plan / emit so downstream
passes can rely on the cleaner IR (in particular: future
segmentation work can dispatch on RuntimeClassicalExpr type
instead of the BitType-only heuristic).
constant_fold¶
def constant_fold(self, block: Block, bindings: dict[str, Any] | None = None) -> BlockPass 1.5: Fold constant expressions.
Evaluates BinOp operations when all operands are constants
or bound parameters. This prevents quantum segment splitting
from parametric expressions like phase * 2.
emit¶
def emit(
self,
separated: ProgramPlan,
bindings: dict[str, Any] | None = None,
parameters: list[str] | None = None,
) -> ExecutableProgram[T]Pass 4: Generate backend-specific code.
Parameters:
| Name | Type | Description |
|---|---|---|
separated | ProgramPlan | The separated program to emit |
bindings | dict[str, Any] | None | Parameter values to bind at compile time |
parameters | list[str] | None | Parameter names to preserve as backend parameters |
Raises:
ValueError— If a name appears in bothbindingsandparameters. This check also runs intranspileandto_block/build, butemitis a public step-by-step entry point that bypasses those, so the guard is repeated here to prevent a name from being silently baked in (its runtime parameter dropped) when the step-by-step API is driven directly.
executor¶
def executor(self, **kwargs: Any = {}) -> QuantumExecutor[T]Create a quantum executor for this backend.
inline¶
def inline(self, block: Block) -> BlockPass 1: Inline all inline-policy callable invocations.
lower_compile_time_ifs¶
def lower_compile_time_ifs(self, block: Block, bindings: dict[str, Any] | None = None) -> BlockPass 1.75: Lower compile-time resolvable IfOperations.
Evaluates IfOperation conditions (including expression-derived conditions via CompOp/CondOp/NotOp) and replaces resolved ones with selected-branch operations. Merge outputs are substituted with selected-branch values throughout the block.
This prevents SegmentationPass from seeing classical-only compile-time IfOperations that would otherwise split quantum segments.
partial_eval¶
def partial_eval(self, block: Block, bindings: dict[str, Any] | None = None) -> BlockPass 1.75: Fold constants and lower compile-time control flow.
plan¶
def plan(self, block: Block) -> ProgramPlanPass 3: Lower and split into a program plan.
Validates C→Q→C pattern with single quantum segment.
plan_circuit¶
def plan_circuit(
self,
prepared: PreparedModule,
bindings: dict[str, Any] | None = None,
) -> ProgramPlanLower a prepared semantic module into the circuit execution model.
This is the destructive circuit-family path: inline-policy calls are
flattened, compile-time structure is evaluated, affine and borrow
invariants are checked, measurement-dependent classical expressions
are classified, and the result is segmented into C-to-Q-to-C steps.
Program-graph targets must compile :class:PreparedModule directly
instead of invoking this method.
Parameters:
| Name | Type | Description |
|---|---|---|
prepared | PreparedModule | Hierarchical semantic program returned by :meth:prepare. |
bindings | dict[str, Any] | None | Compile-time bindings used for recursion unrolling and partial evaluation. Defaults to None. |
Returns:
ProgramPlan — Circuit-family host-orchestrated execution plan.
Raises:
QamomileCompileError— If validation, partial evaluation, or segmentation rejects the program.
prepare¶
def prepare(
self,
kernel: QKernelLike,
bindings: dict[str, Any] | None = None,
parameters: list[str] | None = None,
) -> PreparedModulePrepare a qkernel for target-specific planning and lowering.
This phase preserves callable boundaries. It performs tracing, entrypoint validation, configured substitutions, and parameter-shape resolution, then collects the reachable callable graph into a program-level semantic view.
Parameters:
| Name | Type | Description |
|---|---|---|
kernel | QKernelLike | QKernel or qkernel-like frontend object to prepare as a top-level entrypoint. |
bindings | dict[str, Any] | None | Compile-time values used while tracing and resolving parameter shapes. Defaults to None. |
parameters | list[str] | None | Argument names preserved as runtime parameters. Defaults to None. |
Returns:
PreparedModule — Hierarchical entrypoint, reachable callables,
call graph, and public ABI.
Raises:
ValueError— If a name appears in bothbindingsandparameters.EntrypointValidationError— If the top-level kernel uses quantum inputs or outputs.
resolve_parameter_shapes¶
def resolve_parameter_shapes(self, block: Block, bindings: dict[str, Any] | None = None) -> BlockPass 0.75: Resolve symbolic Vector parameter shape dims.
Qamomile circuits are compile-time fixed-structure. Parameter
Vector[Float] / Vector[UInt] inputs carry symbolic
{name}_dim{i} shape Values so frontend code like
arr.shape[0] returns a usable handle. This pass looks at
bindings and, for every parameter array that has a concrete
binding, substitutes those symbolic dims with constants so that
downstream loop-bound resolution sees fixed lengths.
Parameters without a concrete binding are left as-is; their symbolic dims are harmless as long as no compile-time structure decision depends on them (the library QAOA pattern).
set_config¶
def set_config(self, config: TranspilerConfig) -> NoneSet the transpiler configuration.
Parameters:
| Name | Type | Description |
|---|---|---|
config | TranspilerConfig | Transpiler configuration to use |
slice_borrow_check¶
def slice_borrow_check(self, block: Block) -> BlockPass 1.9: Post-fold slice-view linearity checker.
Runs after :meth:partial_eval has resolved slice bounds to
concrete values. Catches the slice-view linearity violations
that the trace-time frontend check cannot detect on its own —
specifically, slices whose bounds were symbolic at trace
time (so the frontend bulk-borrow tracker had to skip them)
and aliasing scenarios that only become visible once those
bounds are folded to constants:
A view whose newly-concrete coverage overlaps another live view of the same root parent.
A view whose newly-concrete coverage hits a slot that was consumed by a destructive operation earlier in the block.
Slice ownership changes that cannot be represented safely across control-flow boundaries.
Creating a direct element borrow (q[i]) emits no IR operation,
so this pass cannot observe the borrow site itself. Later uses of
that element do appear as operation operands and are checked for
conflicts with live slice views. Trace-time validation in
:func:qamomile.circuit.frontend.func_to_block._validate_returned_arrays
covers unreturned direct-element borrows that have no observable
operand use.
The pass is a pass-through for the IR — it only raises on violations and leaves the block unchanged on success.
Parameters:
| Name | Type | Description |
|---|---|---|
block | Block | Post-fold affine or hierarchical block to validate. |
Returns:
Block — The input block unchanged after successful validation.
Raises:
QubitBorrowConflictError— If live slice ownership conflicts with another view or direct access.QubitConsumedError— If a slice or operand accesses a slot already destroyed by a destructive operation.ValidationError— If the block kind is invalid or ownership cannot be propagated safely through control flow.
strip_slice_ops¶
def strip_slice_ops(self, block: Block) -> BlockPass 1.95: Remove SliceArrayOperation nodes from the block.
PartialEvaluationPass keeps these declarative ops through
constant folding so :meth:slice_borrow_check can use them
as view-declaration markers. Once the linearity check has run,
segmentation and downstream passes expect a classical-op-free
quantum stream — this pass performs that cleanup.
substitute¶
def substitute(self, block: Block) -> BlockPass 0.5: Apply substitutions (optional).
This pass rewrites inline callable targets and sets strategy names on boxed InvokeOperations based on config.
Parameters:
| Name | Type | Description |
|---|---|---|
block | Block | Block to transform |
Returns:
Block — Block with substitutions applied
to_block¶
def to_block(
self,
kernel: QKernelLike,
bindings: dict[str, Any] | None = None,
parameters: list[str] | None = None,
) -> BlockConvert a qkernel-like frontend object to a Block.
Parameters:
| Name | Type | Description |
|---|---|---|
kernel | QKernelLike | QKernel or qkernel-like frontend object to convert. |
bindings | dict[str, Any] | None | Concrete values to bind at trace time, including values used to resolve array shapes. |
parameters | list[str] | None | Names to keep as unbound runtime parameters. |
Returns:
Block — Hierarchical block for the frontend object.
Raises:
ValueError— If a name appears in bothbindingsandparameters(propagated fromkernel.build), violating the bindings/parameters disjointness rule.
Always uses kernel.build() so Python defaults, required arguments,
runtime parameters, and array shapes follow one validated entry path.
to_circuit¶
def to_circuit(self, kernel: QKernelLike, bindings: dict[str, Any] | None = None) -> TCompile and extract just the quantum circuit.
This is a convenience method for when you just want the backend circuit without the full executable.
Parameters:
| Name | Type | Description |
|---|---|---|
kernel | QKernelLike | QKernel or qkernel-like frontend object to compile. |
bindings | dict[str, Any] | None | Parameter values to bind. |
Returns:
T — Backend-specific quantum circuit.
transpile¶
def transpile(
self,
kernel: QKernelLike,
bindings: dict[str, Any] | None = None,
parameters: list[str] | None = None,
) -> ExecutableProgram[T]Full compilation pipeline from a qkernel-like object to executable.
Parameters:
| Name | Type | Description |
|---|---|---|
kernel | QKernelLike | QKernel or qkernel-like frontend object to compile. |
bindings | dict[str, Any] | None | Parameter values to bind (also resolves array shapes). Names in bindings and parameters must be disjoint — a name is either compile-time bound or runtime symbolic, never both. |
parameters | list[str] | None | Parameter names to preserve as backend parameters. Scalars/arrays of float/int/UInt are supported, plus Dict[K, Float]: each constant-key subscript lookup (d[key]) becomes one backend parameter named "d[<key>]", and the execution-time binding bindings={"d": {...}} is decomposed per key onto those parameters. A Dict runtime parameter is recorded in Block.param_slots as a slot whose type is a DictType (compile-time-bound Dicts and Tuple arguments stay out of the slot manifest); its emitted per-key parameters are visible via ExecutableProgram.parameter_names. |
Returns:
ExecutableProgram[T] — ExecutableProgram[T]: Executable wrapping the backend circuit
and the parameter metadata needed to re-bind runtime
parameters, ready for execution.
Raises:
ValueError— If a name appears in bothbindingsandparameters. A name being in both is ambiguous (placeholder value vs runtime symbol) and used to silently miscompile control-flow predicates that depended on parameter-array elements; rejecting the overlap up front keeps the contract unambiguous.QamomileCompileError— If compilation fails (validation, dependency errors)
Pipeline:
prepare: Trace and validate the entrypoint, apply configured substitutions, resolve parameter shapes, and preserve the reachable callable graph.
plan_circuit: Inline inline-policy calls, unroll recursion, validate affine and borrow rules, partially evaluate compile-time structure, analyze dependencies, and segment the program into the host-orchestrated C-to-Q-to-C model.
lower: Convert each quantum segment to immutable, backend-neutral
CircuitProgramIR.legalize: Select native intrinsics and Pauli-evolution realizations from target capabilities and compilation policy.
verify: Prove circuit structure and target legality before constructing backend objects.
materialize: Convert the legalized circuit IR to backend-native artifacts and preserve the executable ABI.
unroll_recursion¶
def unroll_recursion(self, block: Block, bindings: dict[str, Any] | None = None) -> BlockFixed-point loop of inline ↔ partial_eval for self-recursive kernels.
Each iteration unrolls one layer of self-referential inline
callable invocation and then folds the base-case
IfOperation via partial_eval. Terminates when no
inline callable invocation remains (success), when every residual call
is trapped inside an operation-owned block whose recursive callable
contract is unsupported (control / inverse / select over a recursive
kernel — raises a targeted error, see below), or when
MAX_UNROLL_DEPTH is reached (genuinely non-terminating top-level
recursion — raises).
Parameters:
| Name | Type | Description |
|---|---|---|
block | Block | The block to unroll. May be HIERARCHICAL (still containing self-referential callable invocations) or already AFFINE (returned unchanged). |
bindings | dict[str, Any] | None | Compile-time bindings used by partial_eval to fold the base-case condition. Defaults to None, meaning no bindings are applied. |
Returns:
Block — The fully unrolled, AFFINE block once no
inline callable invocation remains. Returned unchanged when the
input already has no calls.
Raises:
FrontendTransformError— If every remaining inline callable invocation is trapped inside aControlledUOperation.block, anInverseBlockOperationblock, or aSelectOperation.case_blocksentry (a self-recursive kernel was passed toqmc.control,qmc.inverse, orqmc.select), or if a genuinely non-terminating top-level recursion does not converge withinMAX_UNROLL_DEPTHiterations. The two cases carry distinct, cause-specific messages.
validate_symbolic_shapes¶
def validate_symbolic_shapes(self, block: Block) -> BlockPass 2.5: Reject unresolvable ForOperation loop bounds.
Runs after analyze so dependency info is complete. Raises
QamomileCompileError with an actionable message when a
gamma_dim0-style symbolic Value reaches a ForOperation
bound without being folded to a constant by
ParameterShapeResolutionPass, or when a loop bound depends
(directly or through classical arithmetic) on a runtime
parameter — loop bounds are compile-time structure and must be
provided via bindings, not parameters.
Parameters:
| Name | Type | Description |
|---|---|---|
block | Block | The analyzed block to validate. |
Returns:
Block — block, unchanged, when validation succeeds.
Raises:
QamomileCompileError— If a loop bound is an unresolved parameter shape dim or depends on a runtime parameter.