Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

qamomile.circuit.serialization

Persist one unbound qkernel and reconstruct it without Python source.

The protobuf format preserves the highest target-neutral static semantics: the qkernel interface, hierarchical IR body, shared callable definitions, and all value-identity relationships needed by later compiler passes. Random process-local UUID and logical-ID spellings are replaced by canonical graph-local identities. Invocation bindings, runtime values, prepared compiler modules, backend artifacts, resource estimates, and Python evaluation performed during tracing are outside the format.

After :func:deserialize, pass the returned :class:SerializedQKernel to an ordinary Qamomile transpiler with fresh bindings and parameters.

Registered compile-time object arguments are stored only as typed binding slots. Their concrete values are deliberately absent from the payload and must be supplied through bindings after deserialization.

Overview

FunctionDescription
deserializeDeserialize protobuf bytes into a static qkernel-like object.
serializeSerialize one unbound qkernel to canonical protobuf bytes.
ClassDescription
SerializedQKernelA qkernel whose Python-independent semantic IR was deserialized.

Constants

Functions

deserialize [source]

def deserialize(payload: bytes) -> SerializedQKernel

Deserialize protobuf bytes into a static qkernel-like object.

Parameters:

NameTypeDescription
payloadbytesBytes produced by :func:serialize.

Returns:

SerializedQKernel — Reconstructed qkernel accepted by transpilers.

Raises:


serialize [source]

def serialize(kernel: QKernelLike) -> bytes

Serialize one unbound qkernel to canonical protobuf bytes.

Independently traced equivalent qkernels produce identical bytes because process-local value identities are normalized before protobuf encoding.

Parameters:

NameTypeDescription
kernelQKernelLikeStatic qkernel-like object to serialize.

Returns:

bytes — Deterministic protobuf encoding.

Raises:

Classes

SerializedQKernel [source]

class SerializedQKernel

A qkernel whose Python-independent semantic IR was deserialized.

The object implements the compiler-facing qkernel protocol. Its body is a static, unbound hierarchical block, so :meth:build specializes existing IR values instead of executing the original Python function again.

Constructor

def __init__(
    self,
    name: str,
    signature: inspect.Signature,
    input_types: dict[str, Any],
    output_types: list[Any],
    _block: Block,
    _callable_definition: CallableDef,
) -> None

Attributes

Methods

build
def build(self, parameters: list[str] | None = None, **kwargs: Any = {}) -> Block

Specialize the preserved IR for bindings and runtime parameters.

This method mirrors the public qkernel argument contract while avoiding Python re-tracing. Compile-time values replace the corresponding formal IR values; runtime parameters remain symbolic.

Parameters:

NameTypeDescription
parameterslist[str] | NoneNames retained as backend runtime parameters. None auto-detects unbound parameterizable arguments.
**kwargsAnyCompile-time bindings keyed by qkernel argument.

Returns:

Block — Specialized traced-stage body accepted by the normal Qamomile compiler pipeline.

Raises:


qamomile.circuit.serialization.canonical

Canonicalize process-local identities in serialized qkernel graphs.

Overview

FunctionDescription
canonicalize_graphReplace random value identities with deterministic graph-local IDs.

Functions

canonicalize_graph [source]

def canonicalize_graph(envelope: dict[str, Any]) -> dict[str, Any]

Replace random value identities with deterministic graph-local IDs.

Value-table order is the semantic encoder’s deterministic first-visit order. The rewrite preserves every equality and reference relationship while making independently traced instances of the same qkernel byte-identical.

Parameters:

NameTypeDescription
envelopedict[str, Any]Complete internal qkernel graph envelope.

Returns:

dict[str, Any] — dict[str, Any]: A deep-copied envelope with canonical UUID and logical-ID strings.

Raises:


qamomile.circuit.serialization.decode

Decode one static qkernel from the semantic protobuf graph model.

Overview

FunctionDescription
build_param_slotsBuild a ParamSlot tuple for the classical arguments of a kernel.
from_dictReconstruct a static qkernel from an internal graph envelope.
get_static_binding_by_type_keyReturn the adapter registered under a stable serialization key.
handle_type_mapMap Handle type to ValueType.
validate_qkernel_irValidate every operation and nested region reachable from a qkernel.
validate_static_binding_slotValidate a serialized IR slot against its installed adapter.
ClassDescription
ArrayValueAn array of typed IR values.
SerializedQKernelA qkernel whose Python-independent semantic IR was deserialized.

Constants

Functions

build_param_slots [source]

def build_param_slots(
    signature: inspect.Signature,
    input_types: dict[str, Any],
    *,
    parameters: list[str] | None = None,
    kwargs: dict[str, Any] | None = None,
    qubit_sizes: dict[str, int] | None = None,
    bind_defaults: bool,
) -> tuple[ParamSlot, ...]

Build a ParamSlot tuple for the classical arguments of a kernel.

Mirrors the argument-classification logic in qkernel_build.create_traced_block so the resulting slot list reflects the same decisions that drive symbolic-vs-bound input creation. Classical scalar / array arguments are always included; a Dict argument is included only when it is a runtime parameter (its slot carries a DictType). Pure-quantum arguments, Tuple arguments, and compile-time-bound Dict arguments are excluded and live in Block.input_values instead.

Parameters:

NameTypeDescription
signatureinspect.SignatureThe kernel function’s signature.
input_typesdict[str, Any]Resolved frontend type annotations keyed by argument name (typically QKernel.input_types or the equivalent computed in func_to_block).
parameterslist[str] | NoneNames explicitly requested as runtime parameters via parameters=[...]. None is treated as an empty list.
kwargsdict[str, Any] | NoneConcrete values supplied via bindings / direct kwargs. None is treated as an empty dict.
qubit_sizesdict[str, int] | NoneOptional mapping from Vector[Qubit] parameter names to their integer sizes; these are quantum inputs and are not included in the slot list.
bind_defaultsboolWhen True, Python signature defaults are treated as COMPILE_TIME_BOUND with bound_value=default. When False (e.g., the func_to_block path that does not bake in defaults), defaulted arguments stay RUNTIME_PARAMETER and the default appears only in ParamSlot.default.

Returns:

tuple[ParamSlot, ...] — tuple[ParamSlot, ...]: One slot per classical argument, in the order they appear in signature.parameters.

Raises:


from_dict [source]

def from_dict(envelope: dict[str, Any]) -> SerializedQKernel

Reconstruct a static qkernel from an internal graph envelope.

Parameters:

NameTypeDescription
envelopedict[str, Any]Dictionary produced by :func:to_dict.

Returns:

SerializedQKernel — QKernel-like object accepted by normal transpilers.

Raises:


get_static_binding_by_type_key [source]

def get_static_binding_by_type_key(type_key: str) -> StaticBindingSpec

Return the adapter registered under a stable serialization key.

Parameters:

NameTypeDescription
type_keystrStable type key from serialized IR.

Returns:

StaticBindingSpec — Matching registered adapter.

Raises:


handle_type_map [source]

def handle_type_map(handle_type: type[Handle] | type) -> ValueType

Map Handle type to ValueType.


validate_qkernel_ir [source]

def validate_qkernel_ir(block: Block) -> None

Validate every operation and nested region reachable from a qkernel.

Parameters:

NameTypeDescription
blockBlockRoot unbound hierarchical qkernel block.

Raises:


validate_static_binding_slot [source]

def validate_static_binding_slot(spec: StaticBindingSpec, slot: StaticBindingSlot) -> None

Validate a serialized IR slot against its installed adapter.

Parameters:

NameTypeDescription
specStaticBindingSpecInstalled adapter contract.
slotStaticBindingSlotIR manifest entry to validate.

Raises:

Classes

ArrayValue [source]

class ArrayValue(Value[T])

An array of typed IR values.

When slice_of is set, this array is a strided view over another array. Element accesses on a sliced ArrayValue resolve to physical slots on the root parent via the affine map parent_index = slice_start + slice_step * view_local_index, applied recursively along slice_of chains. The emit-time resolver walks this chain to produce the final qubit index; passes that substitute or clone values must treat slice_of / slice_start / slice_step as Value references that need to track through the same mapping as parent_array.

Constructor
def __init__(
    self,
    type: T,
    name: str,
    version: int = 0,
    metadata: ValueMetadata = ValueMetadata(),
    uuid: str = (lambda: str(uuid.uuid4()))(),
    logical_id: str = (lambda: str(uuid.uuid4()))(),
    parent_array: ArrayValue | None = None,
    element_indices: tuple[Value, ...] = (),
    shape: tuple[Value, ...] = tuple(),
    slice_of: 'ArrayValue | None' = None,
    slice_start: 'Value | None' = None,
    slice_step: 'Value | None' = None,
) -> None
Attributes
Methods
is_slice
def is_slice(self) -> bool

Return True if this array is a strided view of another array.

Returns:

boolTrue iff slice_of is non-None.

next_version
def next_version(self) -> ArrayValue[T]

SerializedQKernel [source]

class SerializedQKernel

A qkernel whose Python-independent semantic IR was deserialized.

The object implements the compiler-facing qkernel protocol. Its body is a static, unbound hierarchical block, so :meth:build specializes existing IR values instead of executing the original Python function again.

Constructor
def __init__(
    self,
    name: str,
    signature: inspect.Signature,
    input_types: dict[str, Any],
    output_types: list[Any],
    _block: Block,
    _callable_definition: CallableDef,
) -> None
Attributes
Methods
build
def build(self, parameters: list[str] | None = None, **kwargs: Any = {}) -> Block

Specialize the preserved IR for bindings and runtime parameters.

This method mirrors the public qkernel argument contract while avoiding Python re-tracing. Compile-time values replace the corresponding formal IR values; runtime parameters remain symbolic.

Parameters:

NameTypeDescription
parameterslist[str] | NoneNames retained as backend runtime parameters. None auto-detects unbound parameterizable arguments.
**kwargsAnyCompile-time bindings keyed by qkernel argument.

Returns:

Block — Specialized traced-stage body accepted by the normal Qamomile compiler pipeline.

Raises:


qamomile.circuit.serialization.encode

Encode one unbound qkernel into the semantic protobuf graph model.

Overview

FunctionDescription
canonicalize_graphReplace random value identities with deterministic graph-local IDs.
get_static_binding_by_annotationReturn the adapter registered for a qkernel annotation.
handle_type_mapMap Handle type to ValueType.
is_array_typeCheck if type is a Vector, Matrix, or Tensor subclass.
is_dict_typeCheck if type is a Dict handle type.
is_tuple_typeCheck if type is a Tuple handle type.
qkernel_callable_attrsReturn compiler attrs for a qkernel invocation.
qkernel_callable_refReturn the compiler-facing callable reference for a qkernel.
to_dictEncode an unbound qkernel into an internal graph envelope.
validate_qkernel_irValidate every operation and nested region reachable from a qkernel.
validate_static_binding_slotValidate a serialized IR slot against its installed adapter.
ClassDescription
BlockKindClassification of block structure for pipeline stages.
CallPolicyDescribe the default lowering policy for a callable call.
CallableDefDescribe a compiler-facing callable definition.
ParamKindLifecycle classification for a classical kernel argument.
QKernelLikeDescribe the frontend surface required by compiler entrypoints.
ValueBaseNominal base for every typed IR value.

Constants

Functions

canonicalize_graph [source]

def canonicalize_graph(envelope: dict[str, Any]) -> dict[str, Any]

Replace random value identities with deterministic graph-local IDs.

Value-table order is the semantic encoder’s deterministic first-visit order. The rewrite preserves every equality and reference relationship while making independently traced instances of the same qkernel byte-identical.

Parameters:

NameTypeDescription
envelopedict[str, Any]Complete internal qkernel graph envelope.

Returns:

dict[str, Any] — dict[str, Any]: A deep-copied envelope with canonical UUID and logical-ID strings.

Raises:


get_static_binding_by_annotation [source]

def get_static_binding_by_annotation(annotation: Any) -> StaticBindingSpec | None

Return the adapter registered for a qkernel annotation.

Parameters:

NameTypeDescription
annotationAnyResolved qkernel parameter annotation.

Returns:

StaticBindingSpec | None — StaticBindingSpec | None: Registered adapter, or None for an StaticBindingSpec | None — ordinary qkernel argument.


handle_type_map [source]

def handle_type_map(handle_type: type[Handle] | type) -> ValueType

Map Handle type to ValueType.


is_array_type [source]

def is_array_type(t: Any) -> bool

Check if type is a Vector, Matrix, or Tensor subclass.


is_dict_type [source]

def is_dict_type(t: Any) -> bool

Check if type is a Dict handle type.


is_tuple_type [source]

def is_tuple_type(t: Any) -> bool

Check if type is a Tuple handle type.


qkernel_callable_attrs [source]

def qkernel_callable_attrs(kernel: Any) -> dict[str, Any]

Return compiler attrs for a qkernel invocation.

Composite metadata lives directly on QKernel. This helper is the single translation point from that frontend state into serializer-safe IR attributes, so direct, controlled, and inverse calls share one identity.

Parameters:

NameTypeDescription
kernelAnyQKernel-like object carrying callable metadata.

Returns:

dict[str, Any] — dict[str, Any]: Serializer-friendly callable attributes.


qkernel_callable_ref [source]

def qkernel_callable_ref(kernel: Any) -> CallableRef

Return the compiler-facing callable reference for a qkernel.

Parameters:

NameTypeDescription
kernelAnyQKernel-like object carrying callable metadata.

Returns:

CallableRef — Stable reference used by InvokeOperation call sites.


to_dict [source]

def to_dict(kernel: QKernelLike) -> dict[str, Any]

Encode an unbound qkernel into an internal graph envelope.

Parameters:

NameTypeDescription
kernelQKernelLikeQKernel-like frontend object whose static body is preserved.

Returns:

dict[str, Any] — dict[str, Any]: Internal graph record consumed by the protobuf bridge.

Raises:


validate_qkernel_ir [source]

def validate_qkernel_ir(block: Block) -> None

Validate every operation and nested region reachable from a qkernel.

Parameters:

NameTypeDescription
blockBlockRoot unbound hierarchical qkernel block.

Raises:


validate_static_binding_slot [source]

def validate_static_binding_slot(spec: StaticBindingSpec, slot: StaticBindingSlot) -> None

Validate a serialized IR slot against its installed adapter.

Parameters:

NameTypeDescription
specStaticBindingSpecInstalled adapter contract.
slotStaticBindingSlotIR manifest entry to validate.

Raises:

Classes

BlockKind [source]

class BlockKind(Enum)

Classification of block structure for pipeline stages.

Attributes

CallPolicy [source]

class CallPolicy(enum.Enum)

Describe the default lowering policy for a callable call.

Attributes

CallableDef [source]

class CallableDef

Describe a compiler-facing callable definition.

Parameters:

NameTypeDescription
refCallableRefStable callable identity.
signatureSignature | NoneOptional callable signature.
bodyBlock | NoneStandard IR body, or None for opaque calls.
body_refCallableBodyRef | NoneReference to a standard body that is intentionally deferred. Defaults to None.
implementationslist[CallableImplementation]Alternative native or strategy-specific implementations.
opaque_costAny | NoneExplicit cost contract for a bodyless callable. Body-backed callables must leave this as None.
default_policyCallPolicyDefault call lowering policy.
attrsdict[str, Any]Serializer-friendly definition metadata.
Constructor
def __init__(
    self,
    ref: CallableRef,
    signature: Signature | None = None,
    body: Block | None = None,
    body_ref: CallableBodyRef | None = None,
    implementations: list[CallableImplementation] = list(),
    opaque_cost: Any | None = None,
    default_policy: CallPolicy = CallPolicy.INLINE,
    attrs: dict[str, Any] = dict(),
) -> None
Attributes
Methods
effects_for
def effects_for(self, transform: CallTransform = CallTransform.DIRECT) -> 'KernelEffect'

Return cached semantic effects for one call transform.

Parameters:

NameTypeDescription
transformCallTransformRequested call transform. Defaults to CallTransform.DIRECT.

Returns:

'KernelEffect' — Union of relevant implementation-body effects.

implementation_for
def implementation_for(
    self,
    *,
    transform: CallTransform = CallTransform.DIRECT,
    backend: str | None = None,
    strategy: str | None = None,
) -> CallableImplementation | None

Return the best matching implementation candidate.

Parameters:

NameTypeDescription
transformCallTransformRequested call transform.
backendstr | NoneRequested backend name.
strategystr | NoneRequested strategy name.

Returns:

CallableImplementation | None — CallableImplementation | None: Matching implementation, if any.

measurement_result_indices_for
def measurement_result_indices_for(self, transform: CallTransform = CallTransform.DIRECT) -> frozenset[int]

Return measured result positions for one call transform.

Parameters:

NameTypeDescription
transformCallTransformRequested call transform. Defaults to CallTransform.DIRECT.

Returns:

frozenset[int] — frozenset[int]: Result indices carrying measurement provenance.


ParamKind [source]

class ParamKind(enum.Enum)

Lifecycle classification for a classical kernel argument.

Values:

RUNTIME_PARAMETER: The argument is intended to be bound at execution time by the backend (or, more generally, by the outer caller in a hybrid loop). It survives the compilation pipeline as a symbolic parameter. COMPILE_TIME_BOUND: The argument was provided as a binding (or via a Python default) and is folded into the IR by resolve_parameter_shapes / partial_eval. No symbolic counterpart remains in the emitted circuit.

Attributes

QKernelLike [source]

class QKernelLike(Protocol)

Describe the frontend surface required by compiler entrypoints.

This protocol is intentionally structural. It lets decorator-created composites reuse the qkernel inspection and build interface without making them inherit from QKernel or exposing the compiler-facing callable descriptor model as a frontend concept.

Attributes
Methods
build
def build(self, parameters: list[str] | None = None, **kwargs: Any = {}) -> Block

Build a traced body block.

Parameters:

NameTypeDescription
parameterslist[str] | NoneRuntime parameter names to preserve. Defaults to None.
**kwargsAnyCompile-time bindings for non-parameter arguments.

Returns:

Block — Traced hierarchical body block.


ValueBase [source]

class ValueBase

Nominal base for every typed IR value.

Runtime compiler passes inspect values in their innermost loops. A nominal base keeps those checks constant-time; a runtime-checkable protocol would repeatedly scan the protocol members on Python versions that do not cache structural checks.

Attributes
Methods
get_const
def get_const(self) -> int | float | bool | None

Return the scalar constant carried by this value.

Returns:

int | float | bool | None — int | float | bool | None: Constant value, or None when the value is not constant.

is_constant
def is_constant(self) -> bool

Return whether this value carries a scalar constant.

Returns:

bool — Whether scalar constant metadata is present.

is_parameter
def is_parameter(self) -> bool

Return whether this value represents a runtime parameter.

Returns:

bool — Whether parameter metadata is present.

next_version
def next_version(self) -> ValueBase

Create the next SSA version of this value.

Returns:

ValueBase — A value with a fresh version UUID and preserved logical identity.

parameter_name
def parameter_name(self) -> str | None

Return the public parameter name carried by this value.

Returns:

str | None — str | None: Parameter name, or None for a non-parameter value.


qamomile.circuit.serialization.graph_protobuf

Convert semantic IR graph records to the qkernel protobuf schema.

Overview

FunctionDescription
graph_dict_from_qkernelConvert a qkernel protobuf into the internal semantic graph record.
qkernel_from_graph_dictConvert the internal static-qkernel graph record into protobuf.

Constants

Functions

graph_dict_from_qkernel [source]

def graph_dict_from_qkernel(message: pb.QKernel) -> dict[str, Any]

Convert a qkernel protobuf into the internal semantic graph record.

Parameters:

NameTypeDescription
messagepb.QKernelParsed qkernel graph.

Returns:

dict[str, Any] — dict[str, Any]: Graph record accepted by the semantic decoders.

Raises:


qkernel_from_graph_dict [source]

def qkernel_from_graph_dict(envelope: dict[str, Any]) -> pb.QKernel

Convert the internal static-qkernel graph record into protobuf.

This bridge keeps graph construction separate from the canonical wire schema. The resulting bytes contain only protobuf fields, never JSON or a pickled Python dictionary.

Parameters:

NameTypeDescription
envelopedict[str, Any]Validated graph record from the qkernel encoder.

Returns:

pb.QKernel — pb.QKernel: Canonical qkernel protobuf graph.

Raises:


qamomile.circuit.serialization.graph_protobuf.pb

Generated protocol buffer code.

Overview

Constants

Classes

ArrayRuntimeMetadata [source]

class ArrayRuntimeMetadata(_message.Message)
Constructor
def __init__(
    self,
    const_array: _Optional[_Union[Payload, _Mapping]] = ...,
    element_uuids: _Optional[_Iterable[str]] = ...,
    element_logical_ids: _Optional[_Iterable[str]] = ...,
    element_parent_uuids: _Optional[_Iterable[_Union[OptionalString, _Mapping]]] = ...,
    element_parent_indices: _Optional[_Iterable[_Union[OptionalInteger, _Mapping]]] = ...,
) -> None
Attributes

BigInteger [source]

class BigInteger(_message.Message)
Constructor
def __init__(self, negative: bool = ..., magnitude: _Optional[bytes] = ...) -> None
Attributes

Block [source]

class Block(_message.Message)
Constructor
def __init__(
    self,
    kind: _Optional[str] = ...,
    name: _Optional[str] = ...,
    label_args: _Optional[_Iterable[_Union[Payload, _Mapping]]] = ...,
    input_value_refs: _Optional[_Iterable[str]] = ...,
    output_value_refs: _Optional[_Iterable[str]] = ...,
    output_names: _Optional[_Iterable[str]] = ...,
    parameters: _Optional[_Iterable[_Union[NamedReference, _Mapping]]] = ...,
    static_bindings: _Optional[_Iterable[_Union[StaticBindingSlot, _Mapping]]] = ...,
    operations: _Optional[_Iterable[_Union[Operation, _Mapping]]] = ...,
) -> None
Attributes

BranchRebind [source]

class BranchRebind(_message.Message)
Constructor
def __init__(
    self,
    var_name: _Optional[str] = ...,
    before_ref: _Optional[str] = ...,
    rebound_in_true: bool = ...,
    rebound_in_false: bool = ...,
) -> None
Attributes

CallableBodyRef [source]

class CallableBodyRef(_message.Message)
Constructor
def __init__(
    self,
    ref: _Optional[_Union[CallableRef, _Mapping]] = ...,
    kind: _Optional[str] = ...,
    attrs: _Optional[_Union[Payload, _Mapping]] = ...,
) -> None
Attributes

CallableDefinition [source]

class CallableDefinition(_message.Message)
Constructor
def __init__(
    self,
    ref: _Optional[_Union[CallableRef, _Mapping]] = ...,
    signature: _Optional[_Union[Signature, _Mapping]] = ...,
    body: _Optional[_Union[Block, _Mapping]] = ...,
    body_ref: _Optional[_Union[CallableBodyRef, _Mapping]] = ...,
    implementations: _Optional[_Iterable[_Union[CallableImplementation, _Mapping]]] = ...,
    default_policy: _Optional[str] = ...,
    attrs: _Optional[_Union[Payload, _Mapping]] = ...,
) -> None
Attributes

CallableEntry [source]

class CallableEntry(_message.Message)
Constructor
def __init__(
    self,
    id: _Optional[str] = ...,
    definition: _Optional[_Union[CallableDefinition, _Mapping]] = ...,
) -> None
Attributes

CallableImplementation [source]

class CallableImplementation(_message.Message)
Constructor
def __init__(
    self,
    transform: _Optional[str] = ...,
    backend: _Optional[str] = ...,
    strategy: _Optional[str] = ...,
    body: _Optional[_Union[Block, _Mapping]] = ...,
    body_ref: _Optional[_Union[CallableBodyRef, _Mapping]] = ...,
    attrs: _Optional[_Union[Payload, _Mapping]] = ...,
) -> None
Attributes

CallableRef [source]

class CallableRef(_message.Message)
Constructor
def __init__(
    self,
    namespace: _Optional[str] = ...,
    name: _Optional[str] = ...,
    version: _Optional[str] = ...,
) -> None
Attributes

CastMetadata [source]

class CastMetadata(_message.Message)
Constructor
def __init__(
    self,
    source_uuid: _Optional[str] = ...,
    qubit_uuids: _Optional[_Iterable[str]] = ...,
    source_logical_id: _Optional[str] = ...,
    qubit_logical_ids: _Optional[_Iterable[str]] = ...,
) -> None
Attributes

Complex64 [source]

class Complex64(_message.Message)
Constructor
def __init__(self, real_bits: _Optional[int] = ..., imag_bits: _Optional[int] = ...) -> None
Attributes

DictRuntimeMetadata [source]

class DictRuntimeMetadata(_message.Message)
Constructor
def __init__(
    self,
    bound_data: _Optional[_Iterable[_Union[PayloadEntry, _Mapping]]] = ...,
) -> None
Attributes

Float64 [source]

class Float64(_message.Message)
Constructor
def __init__(self, bits: _Optional[int] = ...) -> None
Attributes

FrontendAnnotation [source]

class FrontendAnnotation(_message.Message)
Constructor
def __init__(
    self,
    kind: _Optional[_Union[FrontendAnnotationKind, str]] = ...,
    arguments: _Optional[_Iterable[_Union[FrontendAnnotation, _Mapping]]] = ...,
) -> None
Attributes

FrontendAnnotationKind [source]

class FrontendAnnotationKind(int)
Attributes

Hamiltonian [source]

class Hamiltonian(_message.Message)
Constructor
def __init__(
    self,
    terms: _Optional[_Iterable[_Union[HamiltonianTerm, _Mapping]]] = ...,
    constant: _Optional[_Union[Number, _Mapping]] = ...,
    num_qubits: _Optional[int] = ...,
) -> None
Attributes

HamiltonianTerm [source]

class HamiltonianTerm(_message.Message)
Constructor
def __init__(
    self,
    operators: _Optional[_Iterable[_Union[PauliOperator, _Mapping]]] = ...,
    coefficient: _Optional[_Union[Number, _Mapping]] = ...,
) -> None
Attributes

IntegerOrReference [source]

class IntegerOrReference(_message.Message)
Constructor
def __init__(
    self,
    integer: _Optional[_Union[BigInteger, _Mapping]] = ...,
    value_ref: _Optional[str] = ...,
) -> None
Attributes

KernelParameter [source]

class KernelParameter(_message.Message)
Constructor
def __init__(
    self,
    name: _Optional[str] = ...,
    type: _Optional[_Union[KernelType, _Mapping]] = ...,
    kind: _Optional[_Union[ParameterKind, str]] = ...,
    has_default: bool = ...,
    default: _Optional[_Union[Payload, _Mapping]] = ...,
    differentiable: bool = ...,
    static_binding_type: _Optional[str] = ...,
) -> None
Attributes

KernelType [source]

class KernelType(_message.Message)
Constructor
def __init__(
    self,
    value_type: _Optional[_Union[ValueType, _Mapping]] = ...,
    ndim: _Optional[int] = ...,
    annotation: _Optional[_Union[FrontendAnnotation, _Mapping]] = ...,
) -> None
Attributes

LoopCarriedRebind [source]

class LoopCarriedRebind(_message.Message)
Constructor
def __init__(
    self,
    var_name: _Optional[str] = ...,
    before_ref: _Optional[str] = ...,
    after_ref: _Optional[str] = ...,
    before_synthesized: bool = ...,
) -> None
Attributes

NamedReference [source]

class NamedReference(_message.Message)
Constructor
def __init__(self, name: _Optional[str] = ..., value_ref: _Optional[str] = ...) -> None
Attributes

NullValue [source]

class NullValue(_message.Message)
Constructor
def __init__(self) -> None

Number [source]

class Number(_message.Message)
Constructor
def __init__(
    self,
    integer: _Optional[_Union[BigInteger, _Mapping]] = ...,
    floating: _Optional[_Union[Float64, _Mapping]] = ...,
    complex: _Optional[_Union[Complex64, _Mapping]] = ...,
) -> None
Attributes

NumpyValue [source]

class NumpyValue(_message.Message)
Constructor
def __init__(
    self,
    dtype: _Optional[str] = ...,
    shape: _Optional[_Iterable[int]] = ...,
    data: _Optional[bytes] = ...,
) -> None
Attributes

Operation [source]

class Operation(_message.Message)
Constructor
def __init__(
    self,
    operation_type: _Optional[_Union[OperationType, str]] = ...,
    operand_refs: _Optional[_Iterable[str]] = ...,
    result_refs: _Optional[_Iterable[str]] = ...,
    gate_type: _Optional[str] = ...,
    axis: _Optional[str] = ...,
    num_bits: _Optional[int] = ...,
    int_bits: _Optional[int] = ...,
    key_arity: _Optional[int] = ...,
    source_type: _Optional[_Union[ValueType, _Mapping]] = ...,
    target_type: _Optional[_Union[ValueType, _Mapping]] = ...,
    qubit_mapping: _Optional[_Iterable[str]] = ...,
    expression_kind: _Optional[str] = ...,
    loop_var: _Optional[str] = ...,
    loop_var_value_ref: _Optional[str] = ...,
    key_vars: _Optional[_Iterable[str]] = ...,
    value_var: _Optional[str] = ...,
    key_is_vector: bool = ...,
    key_var_value_refs: _Optional[_Iterable[str]] = ...,
    has_key_var_value_refs: bool = ...,
    value_var_value_ref: _Optional[str] = ...,
    max_iterations: _Optional[int] = ...,
    loop_carried_rebinds: _Optional[_Iterable[_Union[LoopCarriedRebind, _Mapping]]] = ...,
    region_args: _Optional[_Iterable[_Union[RegionArg, _Mapping]]] = ...,
    body: _Optional[_Iterable[_Union[Operation, _Mapping]]] = ...,
    true_body: _Optional[_Iterable[_Union[Operation, _Mapping]]] = ...,
    false_body: _Optional[_Iterable[_Union[Operation, _Mapping]]] = ...,
    true_yield_refs: _Optional[_Iterable[str]] = ...,
    false_yield_refs: _Optional[_Iterable[str]] = ...,
    branch_rebinds: _Optional[_Iterable[_Union[BranchRebind, _Mapping]]] = ...,
    capture_refs: _Optional[_Iterable[str]] = ...,
    true_capture_refs: _Optional[_Iterable[str]] = ...,
    false_capture_refs: _Optional[_Iterable[str]] = ...,
    num_controls: _Optional[int] = ...,
    num_controls_ref: _Optional[str] = ...,
    power: _Optional[_Union[IntegerOrReference, _Mapping]] = ...,
    control_index_refs: _Optional[_Iterable[str]] = ...,
    has_control_index_refs: bool = ...,
    num_control_args: _Optional[int] = ...,
    unitary_block: _Optional[_Union[Block, _Mapping]] = ...,
    callable_ref: _Optional[_Union[CallableRef, _Mapping]] = ...,
    callable_attrs: _Optional[_Union[Payload, _Mapping]] = ...,
    control_value: _Optional[_Union[BigInteger, _Mapping]] = ...,
    target: _Optional[_Union[CallableRef, _Mapping]] = ...,
    transform: _Optional[str] = ...,
    attrs: _Optional[_Union[Payload, _Mapping]] = ...,
    definition_ref: _Optional[str] = ...,
    num_control_qubits: _Optional[int] = ...,
    num_target_qubits: _Optional[int] = ...,
    custom_name: _Optional[str] = ...,
    source_block: _Optional[_Union[Block, _Mapping]] = ...,
    implementation_block: _Optional[_Union[Block, _Mapping]] = ...,
    num_index_qubits: _Optional[int] = ...,
    case_blocks: _Optional[_Iterable[_Union[Block, _Mapping]]] = ...,
    num_index_qubits_ref: _Optional[str] = ...,
    num_index_args: _Optional[int] = ...,
) -> None
Attributes

OperationType [source]

class OperationType(int)
Attributes

OptionalInteger [source]

class OptionalInteger(_message.Message)
Constructor
def __init__(self, value: _Optional[int] = ...) -> None
Attributes

OptionalString [source]

class OptionalString(_message.Message)
Constructor
def __init__(self, value: _Optional[str] = ...) -> None
Attributes

ParamHint [source]

class ParamHint(_message.Message)
Constructor
def __init__(
    self,
    present: bool = ...,
    name: _Optional[str] = ...,
    type: _Optional[_Union[ValueType, _Mapping]] = ...,
) -> None
Attributes

ParameterKind [source]

class ParameterKind(int)
Attributes

PauliOperator [source]

class PauliOperator(_message.Message)
Constructor
def __init__(self, pauli: _Optional[str] = ..., index: _Optional[int] = ...) -> None
Attributes

Payload [source]

class Payload(_message.Message)
Constructor
def __init__(
    self,
    null_value: _Optional[_Union[NullValue, _Mapping]] = ...,
    bool_value: bool = ...,
    integer_value: _Optional[_Union[BigInteger, _Mapping]] = ...,
    float_value: _Optional[_Union[Float64, _Mapping]] = ...,
    string_value: _Optional[str] = ...,
    bytes_value: _Optional[bytes] = ...,
    list_value: _Optional[_Union[PayloadList, _Mapping]] = ...,
    tuple_value: _Optional[_Union[PayloadList, _Mapping]] = ...,
    set_value: _Optional[_Union[PayloadList, _Mapping]] = ...,
    frozenset_value: _Optional[_Union[PayloadList, _Mapping]] = ...,
    map_value: _Optional[_Union[PayloadMap, _Mapping]] = ...,
    complex_value: _Optional[_Union[Complex64, _Mapping]] = ...,
    numpy_array: _Optional[_Union[NumpyValue, _Mapping]] = ...,
    numpy_scalar: _Optional[_Union[NumpyValue, _Mapping]] = ...,
    hamiltonian: _Optional[_Union[Hamiltonian, _Mapping]] = ...,
) -> None
Attributes

PayloadEntry [source]

class PayloadEntry(_message.Message)
Constructor
def __init__(
    self,
    key: _Optional[_Union[Payload, _Mapping]] = ...,
    value: _Optional[_Union[Payload, _Mapping]] = ...,
) -> None
Attributes

PayloadList [source]

class PayloadList(_message.Message)
Constructor
def __init__(self, items: _Optional[_Iterable[_Union[Payload, _Mapping]]] = ...) -> None
Attributes

PayloadMap [source]

class PayloadMap(_message.Message)
Constructor
def __init__(
    self,
    entries: _Optional[_Iterable[_Union[PayloadEntry, _Mapping]]] = ...,
) -> None
Attributes

QFixedMetadata [source]

class QFixedMetadata(_message.Message)
Constructor
def __init__(
    self,
    qubit_uuids: _Optional[_Iterable[str]] = ...,
    num_bits: _Optional[int] = ...,
    int_bits: _Optional[int] = ...,
) -> None
Attributes

QKernel [source]

class QKernel(_message.Message)
Constructor
def __init__(
    self,
    qamomile_version: _Optional[str] = ...,
    name: _Optional[str] = ...,
    parameters: _Optional[_Iterable[_Union[KernelParameter, _Mapping]]] = ...,
    results: _Optional[_Iterable[_Union[KernelType, _Mapping]]] = ...,
    body: _Optional[_Union[Block, _Mapping]] = ...,
    value_table: _Optional[_Iterable[_Union[ValueNode, _Mapping]]] = ...,
    callable_table: _Optional[_Iterable[_Union[CallableEntry, _Mapping]]] = ...,
    callable_definition: _Optional[_Union[CallableDefinition, _Mapping]] = ...,
    return_annotation: _Optional[_Union[FrontendAnnotation, _Mapping]] = ...,
) -> None
Attributes

ReferencePair [source]

class ReferencePair(_message.Message)
Constructor
def __init__(self, key_ref: _Optional[str] = ..., value_ref: _Optional[str] = ...) -> None
Attributes

RegionArg [source]

class RegionArg(_message.Message)
Constructor
def __init__(
    self,
    var_name: _Optional[str] = ...,
    init_ref: _Optional[str] = ...,
    block_arg_ref: _Optional[str] = ...,
    yielded_ref: _Optional[str] = ...,
    result_ref: _Optional[str] = ...,
) -> None
Attributes

RegisterWidth [source]

class RegisterWidth(_message.Message)
Constructor
def __init__(self, concrete: _Optional[int] = ..., value_ref: _Optional[str] = ...) -> None
Attributes

ScalarMetadata [source]

class ScalarMetadata(_message.Message)
Constructor
def __init__(
    self,
    const_value: _Optional[_Union[Payload, _Mapping]] = ...,
    parameter_name: _Optional[str] = ...,
) -> None
Attributes

Signature [source]

class Signature(_message.Message)
Constructor
def __init__(
    self,
    operands: _Optional[_Iterable[_Union[ParamHint, _Mapping]]] = ...,
    results: _Optional[_Iterable[_Union[ParamHint, _Mapping]]] = ...,
) -> None
Attributes

StaticBindingField [source]

class StaticBindingField(_message.Message)
Constructor
def __init__(self, name: _Optional[str] = ..., value_ref: _Optional[str] = ...) -> None
Attributes

StaticBindingSlot [source]

class StaticBindingSlot(_message.Message)
Constructor
def __init__(
    self,
    name: _Optional[str] = ...,
    type_key: _Optional[str] = ...,
    fields: _Optional[_Iterable[_Union[StaticBindingField, _Mapping]]] = ...,
) -> None
Attributes

ValueKind [source]

class ValueKind(int)
Attributes

ValueMetadata [source]

class ValueMetadata(_message.Message)
Constructor
def __init__(
    self,
    scalar: _Optional[_Union[ScalarMetadata, _Mapping]] = ...,
    cast: _Optional[_Union[CastMetadata, _Mapping]] = ...,
    qfixed: _Optional[_Union[QFixedMetadata, _Mapping]] = ...,
    array_runtime: _Optional[_Union[ArrayRuntimeMetadata, _Mapping]] = ...,
    dict_runtime: _Optional[_Union[DictRuntimeMetadata, _Mapping]] = ...,
) -> None
Attributes

ValueNode [source]

class ValueNode(_message.Message)
Constructor
def __init__(
    self,
    value_kind: _Optional[_Union[ValueKind, str]] = ...,
    uuid: _Optional[str] = ...,
    logical_id: _Optional[str] = ...,
    name: _Optional[str] = ...,
    version: _Optional[int] = ...,
    value_type: _Optional[_Union[ValueType, _Mapping]] = ...,
    metadata: _Optional[_Union[ValueMetadata, _Mapping]] = ...,
    parent_array_ref: _Optional[str] = ...,
    element_index_refs: _Optional[_Iterable[str]] = ...,
    shape_refs: _Optional[_Iterable[str]] = ...,
    slice_of_ref: _Optional[str] = ...,
    slice_start_ref: _Optional[str] = ...,
    slice_step_ref: _Optional[str] = ...,
    element_refs: _Optional[_Iterable[str]] = ...,
    entry_refs: _Optional[_Iterable[_Union[ReferencePair, _Mapping]]] = ...,
) -> None
Attributes

ValueType [source]

class ValueType(_message.Message)
Constructor
def __init__(
    self,
    kind: _Optional[_Union[ValueTypeKind, str]] = ...,
    element_types: _Optional[_Iterable[_Union[ValueType, _Mapping]]] = ...,
    key_type: _Optional[_Union[ValueType, _Mapping]] = ...,
    value_type: _Optional[_Union[ValueType, _Mapping]] = ...,
    integer_bits: _Optional[_Union[RegisterWidth, _Mapping]] = ...,
    fractional_bits: _Optional[_Union[RegisterWidth, _Mapping]] = ...,
    width: _Optional[_Union[RegisterWidth, _Mapping]] = ...,
) -> None
Attributes

ValueTypeKind [source]

class ValueTypeKind(int)
Attributes

qamomile.circuit.serialization.kernel

Static qkernel implementation reconstructed from serialized IR.

Overview

FunctionDescription
auto_detect_parametersDetect unbound classical arguments that should be runtime parameters.
build_param_slotsBuild a ParamSlot tuple for the classical arguments of a kernel.
build_specialized_blockTrace a specialized sub-block for a call site.
create_bound_inputCreate a frontend handle for a compile-time-bound value.
get_array_element_typeExtract the element type from an array type annotation.
get_static_binding_by_annotationReturn the adapter registered for a qkernel annotation.
get_static_binding_by_type_keyReturn the adapter registered under a stable serialization key.
is_array_typeCheck if type is a Vector, Matrix, or Tensor subclass.
materialize_static_fieldExtract and validate one registered scalar field.
materialize_static_memberExtract one registered qkernel-like member.
qkernel_callable_defBuild the inline-by-default callable definition for a qkernel block.
validate_bindings_parameters_disjointEnforce the project rule that bindings and parameters are disjoint.
validate_kwargsValidate compile-time bindings for QKernel.build.
validate_parametersValidate the explicit runtime parameter list.
validate_static_bindingValidate one concrete compile-time object binding.
validate_static_binding_slotValidate a serialized IR slot against its installed adapter.
ClassDescription
ArrayValueAn array of typed IR values.
BlockUnified block representation for all pipeline stages.
BlockKindClassification of block structure for pipeline stages.
CInitOperationInitialize the classical values (const, arguments etc)
CallPolicyDescribe the default lowering policy for a callable call.
CallTransformDescribe the requested transform of a callable implementation.
CallableDefDescribe a compiler-facing callable definition.
CallableImplementationDescribe one implementation candidate for a callable.
CallableRefIdentify a callable independently of its Python object.
CompositeGateTypeClassify standard boxed quantum callables.
ControlledUOperationBase class for controlled-U operations.
DictValueA dictionary value stored as stable ordered entries.
HasNestedOpsMixin for operations that contain nested operation lists.
InverseBlockOperationRepresent an inverse qkernel/block as a first-class IR operation.
InvokeOperationRepresent a composite, stdlib, or oracle call.
KernelEffectDescribe non-unitary behavior reachable from a kernel body.
SelectOperationQuantum multiplexer: apply case_blocks[i] when the index reads i.
SerializedQKernelA qkernel whose Python-independent semantic IR was deserialized.
StaticBindingMemberSpecDescribe one deferred qkernel-valued member of a static binding.
StaticBindingSpecRegister the closed qkernel surface of one compile-time object type.
TupleValueA tuple of IR values for structured data.
ValueA typed SSA value in the IR.
ValueBaseNominal base for every typed IR value.
ValueSubstitutorSubstitute IR values in operations using a UUID-keyed mapping.

Constants

Functions

auto_detect_parameters [source]

def auto_detect_parameters(
    signature: inspect.Signature,
    input_types: dict[str, type],
    kwargs: dict[str, Any],
) -> list[str]

Detect unbound classical arguments that should be runtime parameters.

Parameters:

NameTypeDescription
signatureinspect.SignaturePython signature of the qkernel.
input_typesdict[str, type]Resolved frontend annotations keyed by parameter name.
kwargsdict[str, Any]Compile-time bindings supplied to QKernel.build.

Returns:

list[str] — list[str]: Parameter names that should remain symbolic.


build_param_slots [source]

def build_param_slots(
    signature: inspect.Signature,
    input_types: dict[str, Any],
    *,
    parameters: list[str] | None = None,
    kwargs: dict[str, Any] | None = None,
    qubit_sizes: dict[str, int] | None = None,
    bind_defaults: bool,
) -> tuple[ParamSlot, ...]

Build a ParamSlot tuple for the classical arguments of a kernel.

Mirrors the argument-classification logic in qkernel_build.create_traced_block so the resulting slot list reflects the same decisions that drive symbolic-vs-bound input creation. Classical scalar / array arguments are always included; a Dict argument is included only when it is a runtime parameter (its slot carries a DictType). Pure-quantum arguments, Tuple arguments, and compile-time-bound Dict arguments are excluded and live in Block.input_values instead.

Parameters:

NameTypeDescription
signatureinspect.SignatureThe kernel function’s signature.
input_typesdict[str, Any]Resolved frontend type annotations keyed by argument name (typically QKernel.input_types or the equivalent computed in func_to_block).
parameterslist[str] | NoneNames explicitly requested as runtime parameters via parameters=[...]. None is treated as an empty list.
kwargsdict[str, Any] | NoneConcrete values supplied via bindings / direct kwargs. None is treated as an empty dict.
qubit_sizesdict[str, int] | NoneOptional mapping from Vector[Qubit] parameter names to their integer sizes; these are quantum inputs and are not included in the slot list.
bind_defaultsboolWhen True, Python signature defaults are treated as COMPILE_TIME_BOUND with bound_value=default. When False (e.g., the func_to_block path that does not bake in defaults), defaulted arguments stay RUNTIME_PARAMETER and the default appears only in ParamSlot.default.

Returns:

tuple[ParamSlot, ...] — tuple[ParamSlot, ...]: One slot per classical argument, in the order they appear in signature.parameters.

Raises:


build_specialized_block [source]

def build_specialized_block(
    kernel: Any,
    *,
    parameters: list[str],
    bindings: dict[str, Any],
    qubit_sizes: dict[str, int],
) -> Block

Trace a specialized sub-block for a call site.

Parameters:

NameTypeDescription
kernelAnyQKernel-like object to trace.
parameterslist[str]Classical argument names that remain symbolic in the specialized block.
bindingsdict[str, Any]Concrete Python values for classical arguments and caller-owned proxies for unresolved static bindings.
qubit_sizesdict[str, int]First-axis sizes for Vector[Qubit] arguments supplied by the caller.

Returns:

Block — Specialized hierarchical block ready to be invoked from the Block — caller’s trace.


create_bound_input [source]

def create_bound_input(param_type: Any, name: str, value: Any) -> Handle

Create a frontend handle for a compile-time-bound value.

Parameters:

NameTypeDescription
param_typeAnyFrontend type annotation.
namestrQKernel parameter name.
valueAnyConcrete compile-time binding.

Returns:

Handle — Frontend handle carrying constant or runtime metadata.

Raises:


get_array_element_type [source]

def get_array_element_type(param_type: Any) -> type | None

Extract the element type from an array type annotation.

Parameters:

NameTypeDescription
param_typeAnyFrontend annotation such as Vector[Qubit].

Returns:

type | None — type | None: Element type when present, otherwise None.


get_static_binding_by_annotation [source]

def get_static_binding_by_annotation(annotation: Any) -> StaticBindingSpec | None

Return the adapter registered for a qkernel annotation.

Parameters:

NameTypeDescription
annotationAnyResolved qkernel parameter annotation.

Returns:

StaticBindingSpec | None — StaticBindingSpec | None: Registered adapter, or None for an StaticBindingSpec | None — ordinary qkernel argument.


get_static_binding_by_type_key [source]

def get_static_binding_by_type_key(type_key: str) -> StaticBindingSpec

Return the adapter registered under a stable serialization key.

Parameters:

NameTypeDescription
type_keystrStable type key from serialized IR.

Returns:

StaticBindingSpec — Matching registered adapter.

Raises:


is_array_type [source]

def is_array_type(t: Any) -> bool

Check if type is a Vector, Matrix, or Tensor subclass.


materialize_static_field [source]

def materialize_static_field(spec: StaticBindingSpec, binding: Any, field_name: str) -> int | float

Extract and validate one registered scalar field.

Parameters:

NameTypeDescription
specStaticBindingSpecRegistered object contract.
bindingAnyValidated concrete object.
field_namestrRegistered field name.

Returns:

int | float — int | float: Scalar value suitable for IR constant metadata.

Raises:


materialize_static_member [source]

def materialize_static_member(
    spec: StaticBindingSpec,
    binding: Any,
    member_name: str,
) -> tuple[Any, StaticBindingMemberSpec]

Extract one registered qkernel-like member.

Parameters:

NameTypeDescription
specStaticBindingSpecRegistered object contract.
bindingAnyValidated concrete object.
member_namestrRegistered member name.

Returns:

Any — tuple[Any, StaticBindingMemberSpec]: Concrete member and its adapter StaticBindingMemberSpec — contract.

Raises:


qkernel_callable_def [source]

def qkernel_callable_def(kernel: Any, block: Block) -> CallableDef

Build the inline-by-default callable definition for a qkernel block.

Parameters:

NameTypeDescription
kernelAnyQKernel-like object carrying callable metadata.
blockBlockImplementation body for the qkernel.

Returns:

CallableDef — Compiler-facing definition for the qkernel.


validate_bindings_parameters_disjoint [source]

def validate_bindings_parameters_disjoint(bindings: dict[str, Any] | None, parameters: list[str] | None) -> None

Enforce the project rule that bindings and parameters are disjoint.

A kernel argument name must be resolved exactly one way: compile-time bound (in bindings, baked into the emitted circuit) or runtime symbolic (in parameters, surviving as a backend parameter). Listing the same name in both is ambiguous and historically caused silent miscompilation — the binding won the resolution race and the runtime parameter was silently dropped from the emitted circuit (see #354). This is the single shared checker so the rule is enforced identically at every entry point (QKernel.build / Transpiler.to_block / Transpiler.emit / Transpiler.transpile), not only in the top-level transpile wrapper.

Parameters:

NameTypeDescription
bindingsdict[str, Any] | NoneCompile-time bindings keyed by argument name, or None. None is treated as empty.
parameterslist[str] | NoneArgument names to keep as runtime parameters, or None. None is treated as empty.

Returns:

None — None

Raises:

Example:

>>> validate_bindings_parameters_disjoint({"theta": 0.5}, ["phi"])
>>> validate_bindings_parameters_disjoint({"theta": 0.5}, ["theta"])
Traceback (most recent call last):
    ...
ValueError: Parameter name(s) ['theta'] appear in both ...

validate_kwargs [source]

def validate_kwargs(
    signature: inspect.Signature,
    input_types: dict[str, type],
    parameters: list[str],
    kwargs: dict[str, Any],
) -> None

Validate compile-time bindings for QKernel.build.

Parameters:

NameTypeDescription
signatureinspect.SignaturePython signature of the qkernel.
input_typesdict[str, type]Resolved frontend annotations keyed by parameter name.
parameterslist[str]Runtime parameter names.
kwargsdict[str, Any]Compile-time bindings.

Raises:


validate_parameters [source]

def validate_parameters(input_types: dict[str, type], parameters: list[str]) -> None

Validate the explicit runtime parameter list.

Parameters:

NameTypeDescription
input_typesdict[str, type]Resolved qkernel input annotations.
parameterslist[str]Requested runtime parameter names.

Raises:


validate_static_binding [source]

def validate_static_binding(annotation: Any, name: str, value: Any) -> Any

Validate one concrete compile-time object binding.

Parameters:

NameTypeDescription
annotationAnyRegistered qkernel parameter annotation.
namestrParameter name used in diagnostics.
valueAnyCandidate binding value.

Returns:

Any — The validated binding value.

Raises:


validate_static_binding_slot [source]

def validate_static_binding_slot(spec: StaticBindingSpec, slot: StaticBindingSlot) -> None

Validate a serialized IR slot against its installed adapter.

Parameters:

NameTypeDescription
specStaticBindingSpecInstalled adapter contract.
slotStaticBindingSlotIR manifest entry to validate.

Raises:

Classes

ArrayValue [source]

class ArrayValue(Value[T])

An array of typed IR values.

When slice_of is set, this array is a strided view over another array. Element accesses on a sliced ArrayValue resolve to physical slots on the root parent via the affine map parent_index = slice_start + slice_step * view_local_index, applied recursively along slice_of chains. The emit-time resolver walks this chain to produce the final qubit index; passes that substitute or clone values must treat slice_of / slice_start / slice_step as Value references that need to track through the same mapping as parent_array.

Constructor
def __init__(
    self,
    type: T,
    name: str,
    version: int = 0,
    metadata: ValueMetadata = ValueMetadata(),
    uuid: str = (lambda: str(uuid.uuid4()))(),
    logical_id: str = (lambda: str(uuid.uuid4()))(),
    parent_array: ArrayValue | None = None,
    element_indices: tuple[Value, ...] = (),
    shape: tuple[Value, ...] = tuple(),
    slice_of: 'ArrayValue | None' = None,
    slice_start: 'Value | None' = None,
    slice_step: 'Value | None' = None,
) -> None
Attributes
Methods
is_slice
def is_slice(self) -> bool

Return True if this array is a strided view of another array.

Returns:

boolTrue iff slice_of is non-None.

next_version
def next_version(self) -> ArrayValue[T]

Block [source]

class Block

Unified block representation for all pipeline stages.

Replaces the older traced and callable IR wrappers with a single structure. The kind field indicates which pipeline stage this block is at.

Constructor
def __init__(
    self,
    name: str = '',
    label_args: list[str] = list(),
    input_values: list[ValueLike] = list(),
    output_values: list[ValueLike] = list(),
    output_names: list[str] = list(),
    operations: list['Operation'] = list(),
    kind: BlockKind = BlockKind.HIERARCHICAL,
    parameters: dict[str, Value] = dict(),
    param_slots: tuple[ParamSlot, ...] = tuple(),
    static_bindings: tuple[StaticBindingSlot, ...] = tuple(),
) -> None
Attributes
Methods
call
def call(self, **kwargs: ValueLike = {}) -> 'InvokeOperation'

Create an inline callable invocation against this block.

Parameters:

NameTypeDescription
**kwargsValueLikeActual argument values keyed by self.label_args.

Returns:

'InvokeOperation' — Inline-policy invocation whose callable definition points at this block.

Raises:

is_affine
def is_affine(self) -> bool

Return whether this block has passed affine validation.

Returns:

bool — True for AFFINE and ANALYZED blocks.

unbound_parameters
def unbound_parameters(self) -> list[str]

Return list of unbound parameter names.


BlockKind [source]

class BlockKind(Enum)

Classification of block structure for pipeline stages.

Attributes

CInitOperation [source]

class CInitOperation(Operation)

Initialize the classical values (const, arguments etc)

Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
Attributes

CallPolicy [source]

class CallPolicy(enum.Enum)

Describe the default lowering policy for a callable call.

Attributes

CallTransform [source]

class CallTransform(enum.Enum)

Describe the requested transform of a callable implementation.

Attributes

CallableDef [source]

class CallableDef

Describe a compiler-facing callable definition.

Parameters:

NameTypeDescription
refCallableRefStable callable identity.
signatureSignature | NoneOptional callable signature.
bodyBlock | NoneStandard IR body, or None for opaque calls.
body_refCallableBodyRef | NoneReference to a standard body that is intentionally deferred. Defaults to None.
implementationslist[CallableImplementation]Alternative native or strategy-specific implementations.
opaque_costAny | NoneExplicit cost contract for a bodyless callable. Body-backed callables must leave this as None.
default_policyCallPolicyDefault call lowering policy.
attrsdict[str, Any]Serializer-friendly definition metadata.
Constructor
def __init__(
    self,
    ref: CallableRef,
    signature: Signature | None = None,
    body: Block | None = None,
    body_ref: CallableBodyRef | None = None,
    implementations: list[CallableImplementation] = list(),
    opaque_cost: Any | None = None,
    default_policy: CallPolicy = CallPolicy.INLINE,
    attrs: dict[str, Any] = dict(),
) -> None
Attributes
Methods
effects_for
def effects_for(self, transform: CallTransform = CallTransform.DIRECT) -> 'KernelEffect'

Return cached semantic effects for one call transform.

Parameters:

NameTypeDescription
transformCallTransformRequested call transform. Defaults to CallTransform.DIRECT.

Returns:

'KernelEffect' — Union of relevant implementation-body effects.

implementation_for
def implementation_for(
    self,
    *,
    transform: CallTransform = CallTransform.DIRECT,
    backend: str | None = None,
    strategy: str | None = None,
) -> CallableImplementation | None

Return the best matching implementation candidate.

Parameters:

NameTypeDescription
transformCallTransformRequested call transform.
backendstr | NoneRequested backend name.
strategystr | NoneRequested strategy name.

Returns:

CallableImplementation | None — CallableImplementation | None: Matching implementation, if any.

measurement_result_indices_for
def measurement_result_indices_for(self, transform: CallTransform = CallTransform.DIRECT) -> frozenset[int]

Return measured result positions for one call transform.

Parameters:

NameTypeDescription
transformCallTransformRequested call transform. Defaults to CallTransform.DIRECT.

Returns:

frozenset[int] — frozenset[int]: Result indices carrying measurement provenance.


CallableImplementation [source]

class CallableImplementation

Describe one implementation candidate for a callable.

Parameters:

NameTypeDescription
transformCallTransformTransform this implementation realizes.
backendstr | NoneBackend name for native implementations.
strategystr | NoneStrategy name such as "standard".
bodyBlock | NoneIR implementation body. A transform-specific body realizes that transform completely; a controlled body therefore includes control operands in its signature.
body_refCallableBodyRef | NoneReference to a body that should be materialized by a later resolver. Defaults to None.
emitterAnyBackend-native emitter object.
attrsdict[str, Any]Serializer-friendly implementation metadata.
Constructor
def __init__(
    self,
    transform: CallTransform = CallTransform.DIRECT,
    backend: str | None = None,
    strategy: str | None = None,
    body: Block | None = None,
    body_ref: CallableBodyRef | None = None,
    emitter: Any = None,
    attrs: dict[str, Any] = dict(),
) -> None
Attributes

CallableRef [source]

class CallableRef

Identify a callable independently of its Python object.

Parameters:

NameTypeDescription
namespacestrStable namespace such as "qamomile.stdlib" or "user".
namestrStable callable name within the namespace.
versionstrSchema or behavior version for the callable.
Constructor
def __init__(self, namespace: str, name: str, version: str = '1') -> None
Attributes

CompositeGateType [source]

class CompositeGateType(enum.Enum)

Classify standard boxed quantum callables.

Attributes

ControlledUOperation [source]

class ControlledUOperation(Operation)

Base class for controlled-U operations.

Two concrete subclasses handle distinct operand layouts:

All isinstance(op, ControlledUOperation) checks match every subclass.

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    power: int | Value = 1,
    block: Block | None = None,
    num_controls: int | Value = 1,
    callable_ref: CallableRef | None = None,
    callable_attrs: dict[str, Any] = dict(),
) -> None
Attributes
Methods
all_input_values
def all_input_values(self) -> list[ValueBase]
replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

DictValue [source]

class DictValue(_MetadataValueMixin, ValueBase)

A dictionary value stored as stable ordered entries.

Constructor
def __init__(
    self,
    name: str,
    entries: tuple[tuple[TupleValue | Value, Value], ...] = tuple(),
    metadata: ValueMetadata = ValueMetadata(),
    uuid: str = (lambda: str(uuid.uuid4()))(),
    logical_id: str = (lambda: str(uuid.uuid4()))(),
) -> None
Attributes
Methods
is_constant
def is_constant(self) -> bool
next_version
def next_version(self) -> DictValue

HasNestedOps [source]

class HasNestedOps

Mixin for operations that contain nested operation lists.

nested_regions() is the canonical traversal API because it exposes operations together with block arguments, captures, and yields. nested_op_lists() / rebuild_nested() remain compatibility helpers for specialized consumers while they migrate to the region interface.

Methods
nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]

Return all nested operation lists in this control flow op.

nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return uniform views of every nested operation region.

Subclasses with explicit block arguments, captures, or yields override this method. The fallback keeps legacy operation-owned blocks visible while consumers migrate from nested_op_lists.

Returns:

tuple[Region, ...] — tuple[Region, ...]: Region views in nested_op_lists order.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation

Return a copy with nested operation lists replaced.

new_lists must have the same length/order as nested_op_lists().

rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Return a copy with replacement region operation sequences.

Concrete control-flow operations override this method to rebuild both their body operations and boundary values. The fallback supports legacy region owners whose boundary remains operation-specific.

Parameters:

NameTypeDescription
regionsSequence[Region]Replacement regions in nested_regions order.

Returns:

Operation — Rebuilt control-flow operation.

Raises:


InverseBlockOperation [source]

class InverseBlockOperation(Operation)

Represent an inverse qkernel/block as a first-class IR operation.

The operation stores both the original forward block and a Qamomile-built inverse implementation block. Emitters may use source_block with a backend-native inverse/adjoint primitive, then fall back to implementation_block when native inversion is unavailable.

Operands are ordered as scalar control qubits, target quantum operands, then classical/object parameters. Results mirror the quantum operand layout: control results first, then one target result per target operand. Vector target operands therefore count as one operand/result while contributing their scalar width to num_target_qubits.

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    num_control_qubits: int = 0,
    num_target_qubits: int = 0,
    custom_name: str = '',
    source_block: Block | None = None,
    implementation_block: Block | None = None,
    callable_ref: CallableRef | None = None,
    callable_attrs: dict[str, Any] = dict(),
    control_value: int | None = None,
) -> None
Attributes

InvokeOperation [source]

class InvokeOperation(Operation)

Represent a composite, stdlib, or oracle call.

Parameters:

NameTypeDescription
operandslist[ValueLike]Input values consumed by the call.
resultslist[ValueLike]Output values produced by the call.
targetCallableRefCallable identity.
transformCallTransformDirect, inverse, or controlled invocation.
attrsdict[str, Any]Compile-time attributes for strategy, arity, and resource/lowering decisions. control_value is reserved for a controlled invocation’s LSB-first activation value. Values must be serializer-friendly.
definitionCallableDef | NoneOptional callable definition.
Constructor
def __init__(
    self,
    operands: Sequence[ValueLike] | None = None,
    results: Sequence[ValueLike] | None = None,
    *,
    target: CallableRef | None = None,
    transform: CallTransform = CallTransform.DIRECT,
    attrs: dict[str, Any] | None = None,
    definition: CallableDef | None = None,
) -> None

Initialize an invocation operation.

Parameters:

NameTypeDescription
operandsSequence[ValueLike] | NoneInput values consumed by the call. Defaults to None, meaning no operands.
resultsSequence[ValueLike] | NoneOutput values produced by the call. Defaults to None, meaning no results.
targetCallableRef | NoneCallable identity. Defaults to an anonymous user callable when omitted.
transformCallTransformRequested call transform. Defaults to CallTransform.DIRECT.
attrsdict[str, Any] | NoneSerializer-friendly call attributes. Defaults to an empty dict.
definitionCallableDef | NoneCallable definition. Defaults to None, in which case one is created from target.

Raises:

Attributes
Methods
effective_body
def effective_body(
    self,
    *,
    backend: str | None = None,
    strategy: str | None = None,
) -> Block | None

Return the implementation body selected for this invocation.

Parameters:

NameTypeDescription
backendstr | NoneBackend name to match. Defaults to None.
strategystr | NoneStrategy name to match. Defaults to the invocation’s strategy_name attribute.

Returns:

Block | None — Block | None: Selected implementation body, or the callable’s Block | None — default body when no transform-specific implementation exists. Block | None — A compiler may synthesize inverse or controlled behavior from this Block | None — fallback body.

implementation_for
def implementation_for(
    self,
    *,
    backend: str | None = None,
    strategy: str | None = None,
) -> CallableImplementation | None

Return the selected implementation for this invocation.

Parameters:

NameTypeDescription
backendstr | NoneBackend name to match. Defaults to None, which only selects backend-generic implementations.
strategystr | NoneStrategy name to match. Defaults to None, meaning the invocation’s strategy_name attribute is used.

Returns:

CallableImplementation | None — CallableImplementation | None: Matching implementation candidate, CallableImplementation | None — or None when the callable definition has no match.


KernelEffect [source]

class KernelEffect(enum.Flag)

Describe non-unitary behavior reachable from a kernel body.

KernelEffect.NONE is the empty effect set and denotes unitary behavior. Flags compose with bitwise union so one kernel can expose measurement, reset, and measurement-backed feed-forward together.

Attributes
Methods
labels
def labels(self) -> tuple[str, ...]

Return stable effect names for diagnostics and serialization.

Returns:

tuple[str, ...] — tuple[str, ...]: Active flag names in declaration order.


SelectOperation [source]

class SelectOperation(Operation)

Quantum multiplexer: apply case_blocks[i] when the index reads i.

Concrete operand layout: [idx_0, ..., idx_{k-1}, tgt_0, ..., tgt_m, params...]. Symbolic-width operand layout: [idx_arg_0, ..., idx_arg_{a-1}, tgt_0, ..., tgt_m, params...]. Results mirror the quantum operand grouping.

A concrete index register is normalized to one scalar Qubit operand per physical index qubit. A symbolic-width register instead retains each leading caller argument as one scalar or array operand until its bound shape is known. Whole-Vector[Qubit] / scalar targets follow and keep their shapes, and classical parameters shared across every case come last.

Index bit order is LSB-first: idx_0 is the least-significant bit, matching Qamomile’s qubit-zero convention. Case i is selected when index qubit j reads bit j of i. len(case_blocks) need not be a power of two; index values >= len(case_blocks) apply no operation (identity).

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    num_index_qubits: int | Value = 0,
    case_blocks: list[Block] = list(),
    num_index_args: int = 0,
) -> None
Attributes
Methods
all_input_values
def all_input_values(self) -> list[ValueBase]

Return every value consumed by the SELECT operation.

Returns:

list[ValueBase] — list[ValueBase]: Ordinary operands plus the symbolic index-width value when present.

replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

Replace operand and symbolic-width values by UUID.

Parameters:

NameTypeDescription
mappingdict[str, ValueBase]UUID-keyed replacement values.

Returns:

Operation — Rebuilt SELECT operation with matching values replaced.


SerializedQKernel [source]

class SerializedQKernel

A qkernel whose Python-independent semantic IR was deserialized.

The object implements the compiler-facing qkernel protocol. Its body is a static, unbound hierarchical block, so :meth:build specializes existing IR values instead of executing the original Python function again.

Constructor
def __init__(
    self,
    name: str,
    signature: inspect.Signature,
    input_types: dict[str, Any],
    output_types: list[Any],
    _block: Block,
    _callable_definition: CallableDef,
) -> None
Attributes
Methods
build
def build(self, parameters: list[str] | None = None, **kwargs: Any = {}) -> Block

Specialize the preserved IR for bindings and runtime parameters.

This method mirrors the public qkernel argument contract while avoiding Python re-tracing. Compile-time values replace the corresponding formal IR values; runtime parameters remain symbolic.

Parameters:

NameTypeDescription
parameterslist[str] | NoneNames retained as backend runtime parameters. None auto-detects unbound parameterizable arguments.
**kwargsAnyCompile-time bindings keyed by qkernel argument.

Returns:

Block — Specialized traced-stage body accepted by the normal Qamomile compiler pipeline.

Raises:


StaticBindingMemberSpec [source]

class StaticBindingMemberSpec

Describe one deferred qkernel-valued member of a static binding.

Parameters:

NameTypeDescription
input_typesMapping[str, Any]Ordered frontend input annotations.
output_typestuple[Any, ...]Ordered frontend result annotations.
return_annotationAnyComplete Python return annotation.
getterCallable[[Any], Any]Extractor returning the concrete qkernel-like member.
qubit_width_fieldsMapping[str, str]Input-name to scalar field-name mapping used to specialize quantum vector widths.
Constructor
def __init__(
    self,
    input_types: Mapping[str, Any],
    output_types: tuple[Any, ...],
    return_annotation: Any,
    getter: Callable[[Any], Any],
    qubit_width_fields: Mapping[str, str] = dict(),
) -> None
Attributes

StaticBindingSpec [source]

class StaticBindingSpec

Register the closed qkernel surface of one compile-time object type.

Parameters:

NameTypeDescription
annotationtype[Any]Public qkernel parameter annotation.
type_keystrStable serialization key.
fieldsMapping[str, StaticBindingFieldSpec]Scalar projections available while tracing.
membersMapping[str, StaticBindingMemberSpec]Deferred callable members available while tracing.
Constructor
def __init__(
    self,
    annotation: type[Any],
    type_key: str,
    fields: Mapping[str, StaticBindingFieldSpec],
    members: Mapping[str, StaticBindingMemberSpec],
) -> None
Attributes

TupleValue [source]

class TupleValue(_MetadataValueMixin, ValueBase)

A tuple of IR values for structured data.

Constructor
def __init__(
    self,
    name: str,
    elements: tuple[ValueLike, ...] = tuple(),
    metadata: ValueMetadata = ValueMetadata(),
    uuid: str = (lambda: str(uuid.uuid4()))(),
    logical_id: str = (lambda: str(uuid.uuid4()))(),
) -> None
Attributes
Methods
is_constant
def is_constant(self) -> bool
next_version
def next_version(self) -> TupleValue

Value [source]

class Value(_MetadataValueMixin, ValueBase, Generic[T])

A typed SSA value in the IR.

The name field is display-only: it labels the value for visualization and error messages and has no role in identity. Identity is carried by uuid (per-version) and logical_id (across versions).

An empty string (name="") is the anonymous marker used by auto-generated tmp values (arithmetic results, comparison results, coerced constants). Compiler-internal identity and writes use UUIDs or explicit parameter metadata. Compatibility readers may consult a non-empty label only after those identity channels, so anonymous temporaries cannot collide through a shared display key.

Constructor
def __init__(
    self,
    type: T,
    name: str,
    version: int = 0,
    metadata: ValueMetadata = ValueMetadata(),
    uuid: str = (lambda: str(uuid.uuid4()))(),
    logical_id: str = (lambda: str(uuid.uuid4()))(),
    parent_array: ArrayValue | None = None,
    element_indices: tuple[Value, ...] = (),
) -> None
Attributes
Methods
is_array_element
def is_array_element(self) -> bool
next_version
def next_version(self) -> Value[T]

Create a new Value with incremented version and fresh UUID.

Metadata is intentionally preserved across versions so that parameter bindings and constant annotations remain accessible after the value is updated (e.g. by a gate application or a classical operation). The logical_id also stays the same: it identifies the same logical variable across SSA versions, independently of backend resource allocation. This applies to every Value regardless of its type (Qubit, Float, Bit, ...) -- it is not specific to qubits.


ValueBase [source]

class ValueBase

Nominal base for every typed IR value.

Runtime compiler passes inspect values in their innermost loops. A nominal base keeps those checks constant-time; a runtime-checkable protocol would repeatedly scan the protocol members on Python versions that do not cache structural checks.

Attributes
Methods
get_const
def get_const(self) -> int | float | bool | None

Return the scalar constant carried by this value.

Returns:

int | float | bool | None — int | float | bool | None: Constant value, or None when the value is not constant.

is_constant
def is_constant(self) -> bool

Return whether this value carries a scalar constant.

Returns:

bool — Whether scalar constant metadata is present.

is_parameter
def is_parameter(self) -> bool

Return whether this value represents a runtime parameter.

Returns:

bool — Whether parameter metadata is present.

next_version
def next_version(self) -> ValueBase

Create the next SSA version of this value.

Returns:

ValueBase — A value with a fresh version UUID and preserved logical identity.

parameter_name
def parameter_name(self) -> str | None

Return the public parameter name carried by this value.

Returns:

str | None — str | None: Parameter name, or None for a non-parameter value.


ValueSubstitutor [source]

class ValueSubstitutor

Substitute IR values in operations using a UUID-keyed mapping.

Parameters:

NameTypeDescription
value_mapMapping[str, ValueBase]Mapping from original value UUIDs to replacement values.
transitiveboolWhether substitutions should chase chains such as A -> B -> C to the terminal value. Defaults to False.
Constructor
def __init__(self, value_map: Mapping[str, ValueBase], transitive: bool = False)

Initialize the substitutor.

Parameters:

NameTypeDescription
value_mapMapping[str, ValueBase]Mapping from original value UUIDs to replacement values.
transitiveboolWhether substitutions should chase chains to their terminal value. Defaults to False.
Methods
substitute_operation
def substitute_operation(self, op: Operation) -> Operation

Substitute values in an operation.

Parameters:

NameTypeDescription
opOperationOperation whose operands, results, and subclass-specific value fields should be substituted.

Returns:

Operation — Operation with all mapped value references replaced.

substitute_value
def substitute_value(self, value: ValueBase) -> ValueBase

Substitute a single value.

Parameters:

NameTypeDescription
valueValueBaseValue to replace or rebuild.

Returns:

ValueBase — Replacement value, rebuilt value with substituted ValueBase — metadata, or the original value when nothing maps.


qamomile.circuit.serialization.proto

Generated protobuf schema for one target-neutral static qkernel.


qamomile.circuit.serialization.protobuf

Serialize and deserialize one static qkernel with protobuf.

Overview

FunctionDescription
deserializeDeserialize protobuf bytes into a static qkernel-like object.
graph_dict_from_qkernelConvert a qkernel protobuf into the internal semantic graph record.
qkernel_from_graph_dictConvert the internal static-qkernel graph record into protobuf.
serializeSerialize one unbound qkernel to canonical protobuf bytes.
ClassDescription
QKernelLikeDescribe the frontend surface required by compiler entrypoints.
SerializedQKernelA qkernel whose Python-independent semantic IR was deserialized.

Functions

deserialize [source]

def deserialize(payload: bytes) -> SerializedQKernel

Deserialize protobuf bytes into a static qkernel-like object.

Parameters:

NameTypeDescription
payloadbytesBytes produced by :func:serialize.

Returns:

SerializedQKernel — Reconstructed qkernel accepted by transpilers.

Raises:


graph_dict_from_qkernel [source]

def graph_dict_from_qkernel(message: pb.QKernel) -> dict[str, Any]

Convert a qkernel protobuf into the internal semantic graph record.

Parameters:

NameTypeDescription
messagepb.QKernelParsed qkernel graph.

Returns:

dict[str, Any] — dict[str, Any]: Graph record accepted by the semantic decoders.

Raises:


qkernel_from_graph_dict [source]

def qkernel_from_graph_dict(envelope: dict[str, Any]) -> pb.QKernel

Convert the internal static-qkernel graph record into protobuf.

This bridge keeps graph construction separate from the canonical wire schema. The resulting bytes contain only protobuf fields, never JSON or a pickled Python dictionary.

Parameters:

NameTypeDescription
envelopedict[str, Any]Validated graph record from the qkernel encoder.

Returns:

pb.QKernel — pb.QKernel: Canonical qkernel protobuf graph.

Raises:


serialize [source]

def serialize(kernel: QKernelLike) -> bytes

Serialize one unbound qkernel to canonical protobuf bytes.

Independently traced equivalent qkernels produce identical bytes because process-local value identities are normalized before protobuf encoding.

Parameters:

NameTypeDescription
kernelQKernelLikeStatic qkernel-like object to serialize.

Returns:

bytes — Deterministic protobuf encoding.

Raises:

Classes

QKernelLike [source]

class QKernelLike(Protocol)

Describe the frontend surface required by compiler entrypoints.

This protocol is intentionally structural. It lets decorator-created composites reuse the qkernel inspection and build interface without making them inherit from QKernel or exposing the compiler-facing callable descriptor model as a frontend concept.

Attributes
Methods
build
def build(self, parameters: list[str] | None = None, **kwargs: Any = {}) -> Block

Build a traced body block.

Parameters:

NameTypeDescription
parameterslist[str] | NoneRuntime parameter names to preserve. Defaults to None.
**kwargsAnyCompile-time bindings for non-parameter arguments.

Returns:

Block — Traced hierarchical body block.


SerializedQKernel [source]

class SerializedQKernel

A qkernel whose Python-independent semantic IR was deserialized.

The object implements the compiler-facing qkernel protocol. Its body is a static, unbound hierarchical block, so :meth:build specializes existing IR values instead of executing the original Python function again.

Constructor
def __init__(
    self,
    name: str,
    signature: inspect.Signature,
    input_types: dict[str, Any],
    output_types: list[Any],
    _block: Block,
    _callable_definition: CallableDef,
) -> None
Attributes
Methods
build
def build(self, parameters: list[str] | None = None, **kwargs: Any = {}) -> Block

Specialize the preserved IR for bindings and runtime parameters.

This method mirrors the public qkernel argument contract while avoiding Python re-tracing. Compile-time values replace the corresponding formal IR values; runtime parameters remain symbolic.

Parameters:

NameTypeDescription
parameterslist[str] | NoneNames retained as backend runtime parameters. None auto-detects unbound parameterizable arguments.
**kwargsAnyCompile-time bindings keyed by qkernel argument.

Returns:

Block — Specialized traced-stage body accepted by the normal Qamomile compiler pipeline.

Raises:


qamomile.circuit.serialization.schema

Expose the exact-distribution version policy for qkernel serialization.

The protobuf payload stores Qamomile’s complete installed distribution version rather than an independent integer schema counter. Development and local build metadata remain significant so different wire implementations cannot claim the same compatibility marker. The format provides no cross-version migration layer.

Constants


qamomile.circuit.serialization.validation

Semantic validation for static qkernel IR at the serialization boundary.

Overview

FunctionDescription
collect_value_like_uuidsCollect UUIDs contained in a value-like IR object.
get_static_binding_by_type_keyReturn the adapter registered under a stable serialization key.
is_plain_intReturn True if value is a Python int but not a bool.
normalize_control_valueNormalize an integer activation state for a control register.
pair_block_operandsPair all block inputs with category-grouped call-site operands.
resolve_root_qubit_addressResolve an array-element value to its root (array_uuid, index).
validate_qkernel_irValidate every operation and nested region reachable from a qkernel.
validate_static_binding_slotValidate a serialized IR slot against its installed adapter.
ClassDescription
ArrayValueAn array of typed IR values.
BinOpBinary arithmetic operation (ADD, SUB, MUL, DIV, FLOORDIV, MOD, POW, MIN).
BinOpKind
BitTypeType representing a classical bit.
BlockUnified block representation for all pipeline stages.
CInitOperationInitialize the classical values (const, arguments etc)
CallPolicyDescribe the default lowering policy for a callable call.
CallTransformDescribe the requested transform of a callable implementation.
CallableDefDescribe a compiler-facing callable definition.
CallableRefIdentify a callable independently of its Python object.
CastOperationType cast operation for creating aliases over the same quantum resources.
CompOpComparison operation (EQ, NEQ, LT, LE, GT, GE).
CompOpKind
ConcreteControlledUControlled-U with concrete (int) number of controls.
CondOpConditional logical operation (AND, OR).
DecodeQFixedOperationDecode measured bits to float (classical operation).
DictGetItemOperationLook up one entry of a Dict by a (possibly symbolic) key.
DictValueA dictionary value stored as stable ordered entries.
FloatTypeType representing a floating-point number.
ForOperationRepresents a for loop operation.
HasNestedOpsMixin for operations that contain nested operation lists.
IfOperationRepresents an if-else conditional operation.
NotOp
ObservableTypeType representing a Hamiltonian observable parameter.
Operation
ParamHint
PauliEvolveOpPauli evolution operation: exp(-i * gamma * H).
QFixedTypeQuantum fixed-point type.
QInitOperationInitialize the qubit
QubitTypeType representing a quantum bit (qubit).
RegionArgExplicit loop-carried value on a loop operation (MLIR-style iter_arg).
ReleaseSliceViewOperationMark a slice view’s borrow as explicitly returned to its parent.
ReturnQuantumArrayElementOperationValidate a branch-selected quantum element’s array return at emit time.
RuntimeClassicalExprA classical expression known to require runtime evaluation.
RuntimeOpKindUnified kind for RuntimeClassicalExpr covering all classical
SliceArrayOperationConstruct a strided view of an ArrayValue.
StaticBindingMemberSpecDescribe one deferred qkernel-valued member of a static binding.
StaticBindingSlotDeclare one typed compile-time object required by a qkernel.
StaticBindingSpecRegister the closed qkernel surface of one compile-time object type.
StoreArrayElementOperationStore a classical scalar into one element of a classical array.
SymbolicControlledUControlled-U with symbolic (Value) number of controls.
TupleValueA tuple of IR values for structured data.
UIntTypeType representing an unsigned integer.
UnaryMathOpRepresent one pure unary mathematical expression.
UnaryMathOpKindIdentify one abstract unary mathematical operation.
ValueA typed SSA value in the IR.
ValueBaseNominal base for every typed IR value.
ValueTypeBase class for all value types in the IR.
WhileOperationRepresents a while loop operation.

Constants

Functions

collect_value_like_uuids [source]

def collect_value_like_uuids(value: 'ValueLike') -> set[str]

Collect UUIDs contained in a value-like IR object.

Parameters:

NameTypeDescription
valueValueLikeValue-like object to inspect.

Returns:

set[str] — set[str]: UUIDs for value itself, recursively contained tuple/dict elements, and array view/element dependencies.


get_static_binding_by_type_key [source]

def get_static_binding_by_type_key(type_key: str) -> StaticBindingSpec

Return the adapter registered under a stable serialization key.

Parameters:

NameTypeDescription
type_keystrStable type key from serialized IR.

Returns:

StaticBindingSpec — Matching registered adapter.

Raises:


is_plain_int [source]

def is_plain_int(value: object) -> bool

Return True if value is a Python int but not a bool.

bool is a subclass of int in Python, so isinstance(True, int) is True. This helper distinguishes a genuine integer from a boolean, which matters wherever a boolean must be rejected in an integer slot — for example, validating decoded wire data or a register width.

Parameters:

NameTypeDescription
valueobjectThe value to test.

Returns:

boolTrue when value is an int and not a bool.


normalize_control_value [source]

def normalize_control_value(control_value: int | None, num_controls: int) -> int | None

Normalize an integer activation state for a control register.

Control qubits follow Qamomile’s LSB-first integer convention: bit j of control_value describes the j-th flattened control operand. None and the all-ones value are the canonical ordinary-control state.

Parameters:

NameTypeDescription
control_valueint | NoneRequired computational-basis value, or None for the ordinary all-ones control state.
num_controlsintConcrete positive control-register width.

Returns:

int | None — int | None: A non-default activation value, or None for all-ones.

Raises:


pair_block_operands [source]

def pair_block_operands(
    block: Block,
    operands: Sequence[ValueBase],
) -> list[tuple[ValueBase, ValueBase]]

Pair all block inputs with category-grouped call-site operands.

Parameters:

NameTypeDescription
blockBlockOperation-owned block whose inputs are being bound.
operandsSequence[ValueBase]Call-site operands after any controls that are external to block have been removed.

Returns:

list[tuple[ValueBase, ValueBase]] — list[tuple[ValueBase, ValueBase]]: Formal/actual pairs in the block’s list[tuple[ValueBase, ValueBase]] — declaration order.


resolve_root_qubit_address [source]

def resolve_root_qubit_address(value: 'Value') -> tuple[str, int] | None

Resolve an array-element value to its root (array_uuid, index).

Walks the parent_array / slice_of chain and composes the nested affine slice maps, so view[i] resolves to (root_uuid, start + step * i) for the composed (start, step). The returned pair is the build-stable identity of the physical qubit slot: the root array’s QInitOperation always registers it as QubitAddress(root_uuid, index), so this address resolves even when the element’s own (per-version) UUID was never registered.

The transpiler’s resource allocator uses the same walk to resolve gate and measurement operands; this shared helper keeps both call sites consistent.

Parameters:

NameTypeDescription
valueValueThe value to resolve. Expected to be an array element (parent_array set with a single constant element_indices entry).

Returns:

tuple[str, int] | None — tuple[str, int] | None: (root_array_uuid, composed_index) when value is an array element with a constant index whose entire slice_of chain has constant slice_start / slice_step. None when value is not an array element, when its index is non-constant, or when any slice bound in the chain is non-constant (those cases are deferred to the emit-time resolver, which has bindings available). Also None for a negative constant index or a chain frame with negative slice_start / non-positive slice_step — composing those would silently address a wrong root slot, so they are refused rather than guessed (the frontend rejects them at trace time; this guard covers programmatically constructed IR).


validate_qkernel_ir [source]

def validate_qkernel_ir(block: Block) -> None

Validate every operation and nested region reachable from a qkernel.

Parameters:

NameTypeDescription
blockBlockRoot unbound hierarchical qkernel block.

Raises:


validate_static_binding_slot [source]

def validate_static_binding_slot(spec: StaticBindingSpec, slot: StaticBindingSlot) -> None

Validate a serialized IR slot against its installed adapter.

Parameters:

NameTypeDescription
specStaticBindingSpecInstalled adapter contract.
slotStaticBindingSlotIR manifest entry to validate.

Raises:

Classes

ArrayValue [source]

class ArrayValue(Value[T])

An array of typed IR values.

When slice_of is set, this array is a strided view over another array. Element accesses on a sliced ArrayValue resolve to physical slots on the root parent via the affine map parent_index = slice_start + slice_step * view_local_index, applied recursively along slice_of chains. The emit-time resolver walks this chain to produce the final qubit index; passes that substitute or clone values must treat slice_of / slice_start / slice_step as Value references that need to track through the same mapping as parent_array.

Constructor
def __init__(
    self,
    type: T,
    name: str,
    version: int = 0,
    metadata: ValueMetadata = ValueMetadata(),
    uuid: str = (lambda: str(uuid.uuid4()))(),
    logical_id: str = (lambda: str(uuid.uuid4()))(),
    parent_array: ArrayValue | None = None,
    element_indices: tuple[Value, ...] = (),
    shape: tuple[Value, ...] = tuple(),
    slice_of: 'ArrayValue | None' = None,
    slice_start: 'Value | None' = None,
    slice_step: 'Value | None' = None,
) -> None
Attributes
Methods
is_slice
def is_slice(self) -> bool

Return True if this array is a strided view of another array.

Returns:

boolTrue iff slice_of is non-None.

next_version
def next_version(self) -> ArrayValue[T]

BinOp [source]

class BinOp(BinaryOperationBase)

Binary arithmetic operation (ADD, SUB, MUL, DIV, FLOORDIV, MOD, POW, MIN).

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    kind: BinOpKind | None = None,
) -> None
Attributes

BinOpKind [source]

class BinOpKind(enum.Enum)
Attributes

BitType [source]

class BitType(ClassicalTypeMixin, ValueType)

Type representing a classical bit.


Block [source]

class Block

Unified block representation for all pipeline stages.

Replaces the older traced and callable IR wrappers with a single structure. The kind field indicates which pipeline stage this block is at.

Constructor
def __init__(
    self,
    name: str = '',
    label_args: list[str] = list(),
    input_values: list[ValueLike] = list(),
    output_values: list[ValueLike] = list(),
    output_names: list[str] = list(),
    operations: list['Operation'] = list(),
    kind: BlockKind = BlockKind.HIERARCHICAL,
    parameters: dict[str, Value] = dict(),
    param_slots: tuple[ParamSlot, ...] = tuple(),
    static_bindings: tuple[StaticBindingSlot, ...] = tuple(),
) -> None
Attributes
Methods
call
def call(self, **kwargs: ValueLike = {}) -> 'InvokeOperation'

Create an inline callable invocation against this block.

Parameters:

NameTypeDescription
**kwargsValueLikeActual argument values keyed by self.label_args.

Returns:

'InvokeOperation' — Inline-policy invocation whose callable definition points at this block.

Raises:

is_affine
def is_affine(self) -> bool

Return whether this block has passed affine validation.

Returns:

bool — True for AFFINE and ANALYZED blocks.

unbound_parameters
def unbound_parameters(self) -> list[str]

Return list of unbound parameter names.


CInitOperation [source]

class CInitOperation(Operation)

Initialize the classical values (const, arguments etc)

Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
Attributes

CallPolicy [source]

class CallPolicy(enum.Enum)

Describe the default lowering policy for a callable call.

Attributes

CallTransform [source]

class CallTransform(enum.Enum)

Describe the requested transform of a callable implementation.

Attributes

CallableDef [source]

class CallableDef

Describe a compiler-facing callable definition.

Parameters:

NameTypeDescription
refCallableRefStable callable identity.
signatureSignature | NoneOptional callable signature.
bodyBlock | NoneStandard IR body, or None for opaque calls.
body_refCallableBodyRef | NoneReference to a standard body that is intentionally deferred. Defaults to None.
implementationslist[CallableImplementation]Alternative native or strategy-specific implementations.
opaque_costAny | NoneExplicit cost contract for a bodyless callable. Body-backed callables must leave this as None.
default_policyCallPolicyDefault call lowering policy.
attrsdict[str, Any]Serializer-friendly definition metadata.
Constructor
def __init__(
    self,
    ref: CallableRef,
    signature: Signature | None = None,
    body: Block | None = None,
    body_ref: CallableBodyRef | None = None,
    implementations: list[CallableImplementation] = list(),
    opaque_cost: Any | None = None,
    default_policy: CallPolicy = CallPolicy.INLINE,
    attrs: dict[str, Any] = dict(),
) -> None
Attributes
Methods
effects_for
def effects_for(self, transform: CallTransform = CallTransform.DIRECT) -> 'KernelEffect'

Return cached semantic effects for one call transform.

Parameters:

NameTypeDescription
transformCallTransformRequested call transform. Defaults to CallTransform.DIRECT.

Returns:

'KernelEffect' — Union of relevant implementation-body effects.

implementation_for
def implementation_for(
    self,
    *,
    transform: CallTransform = CallTransform.DIRECT,
    backend: str | None = None,
    strategy: str | None = None,
) -> CallableImplementation | None

Return the best matching implementation candidate.

Parameters:

NameTypeDescription
transformCallTransformRequested call transform.
backendstr | NoneRequested backend name.
strategystr | NoneRequested strategy name.

Returns:

CallableImplementation | None — CallableImplementation | None: Matching implementation, if any.

measurement_result_indices_for
def measurement_result_indices_for(self, transform: CallTransform = CallTransform.DIRECT) -> frozenset[int]

Return measured result positions for one call transform.

Parameters:

NameTypeDescription
transformCallTransformRequested call transform. Defaults to CallTransform.DIRECT.

Returns:

frozenset[int] — frozenset[int]: Result indices carrying measurement provenance.


CallableRef [source]

class CallableRef

Identify a callable independently of its Python object.

Parameters:

NameTypeDescription
namespacestrStable namespace such as "qamomile.stdlib" or "user".
namestrStable callable name within the namespace.
versionstrSchema or behavior version for the callable.
Constructor
def __init__(self, namespace: str, name: str, version: str = '1') -> None
Attributes

CastOperation [source]

class CastOperation(Operation)

Type cast operation for creating aliases over the same quantum resources.

This operation does NOT allocate new qubits. It creates a new Value that references the same underlying quantum resources with a different type.

Use cases:

operands: [source_value] - The value being cast results: [cast_result] - The new value with target type (same physical qubits)

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    source_type: ValueType | None = None,
    target_type: ValueType | None = None,
    qubit_mapping: list[str] = list(),
) -> None
Attributes

CompOp [source]

class CompOp(BinaryOperationBase)

Comparison operation (EQ, NEQ, LT, LE, GT, GE).

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    kind: CompOpKind | None = None,
) -> None
Attributes

CompOpKind [source]

class CompOpKind(enum.Enum)
Attributes

ConcreteControlledU [source]

class ConcreteControlledU(ControlledUOperation)

Controlled-U with concrete (int) number of controls.

Operand layout: [ctrl_0, ..., ctrl_n, tgt_0, ..., tgt_m, params...] Result layout: [ctrl_0', ..., ctrl_n', tgt_0', ..., tgt_m']

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    power: int | Value = 1,
    block: Block | None = None,
    num_controls: int = 1,
    callable_ref: CallableRef | None = None,
    callable_attrs: dict[str, Any] = dict(),
    control_value: int | None = None,
) -> None
Attributes

CondOp [source]

class CondOp(BinaryOperationBase)

Conditional logical operation (AND, OR).

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    kind: CondOpKind | None = None,
) -> None
Attributes

DecodeQFixedOperation [source]

class DecodeQFixedOperation(Operation)

Decode measured bits to float (classical operation).

This operation converts a sequence of classical bits from qubit measurements into a floating-point number using fixed-point encoding.

The decoding formula for least-significant-first storage:

float_value = Σ bit[i] * 2^(int_bits - num_bits + i)

For QPE phase (int_bits=0): bit[0] has weight 2**(-num_bits) and bit[-1] has weight 0.5.

Example:

bits = [1, 0, 1] with int_bits=0
→ 0.101 (MSB-first display) = 0.5 + 0.125 = 0.625

operands: [ArrayValue of bits (vec[bit])] results: [Float value]

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    num_bits: int = 0,
    int_bits: int = 0,
) -> None
Attributes

DictGetItemOperation [source]

class DictGetItemOperation(Operation)

Look up one entry of a Dict by a (possibly symbolic) key.

This is the IR form of d[key] on a Dict handle. The key components may be symbolic (e.g. loop variables of a for-items loop); the lookup is resolved at emit time when the key values and the dict’s bound data are both concrete.

operands: [DictValue, *key_component_values] results: [looked-up scalar value]

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    key_arity: int = 1,
) -> None
Attributes

DictValue [source]

class DictValue(_MetadataValueMixin, ValueBase)

A dictionary value stored as stable ordered entries.

Constructor
def __init__(
    self,
    name: str,
    entries: tuple[tuple[TupleValue | Value, Value], ...] = tuple(),
    metadata: ValueMetadata = ValueMetadata(),
    uuid: str = (lambda: str(uuid.uuid4()))(),
    logical_id: str = (lambda: str(uuid.uuid4()))(),
) -> None
Attributes
Methods
is_constant
def is_constant(self) -> bool
next_version
def next_version(self) -> DictValue

FloatType [source]

class FloatType(ClassicalTypeMixin, ValueType)

Type representing a floating-point number.


ForOperation [source]

class ForOperation(HasNestedOps, Operation)

Represents a for loop operation.

Example:

for i in range(start, stop, step):
    body
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    loop_var: str = '',
    loop_var_value: Value | None = None,
    operations: list[Operation] = list(),
    loop_carried_rebinds: tuple[LoopCarriedRebind, ...] = (),
    region_args: tuple[RegionArg, ...] = (),
    captures: tuple[ValueBase, ...] = (),
) -> None
Attributes
Methods
all_input_values
def all_input_values(self) -> list[ValueBase]

Include loop_var_value so cloning/substitution stays consistent.

Without this override, UUIDRemapper would clone every body reference to the loop variable to a fresh UUID, but leave loop_var_value pointing at the un-cloned original — emit-time UUID-keyed lookups for the loop variable would then miss. Loop-carried rebind records and region arguments are included for the same reason.

nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]
nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return the range-loop body with its explicit interface.

Returns:

tuple[Region, ...] — tuple[Region, ...]: One body region containing the induction value, carried-value formals, captures, and carried yields.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation
rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Rebuild the range-loop body and complete boundary interface.

Parameters:

NameTypeDescription
regionsSequence[Region]Exactly one replacement body region.

Returns:

Operation — Rebuilt range-loop operation.

Raises:

replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

HasNestedOps [source]

class HasNestedOps

Mixin for operations that contain nested operation lists.

nested_regions() is the canonical traversal API because it exposes operations together with block arguments, captures, and yields. nested_op_lists() / rebuild_nested() remain compatibility helpers for specialized consumers while they migrate to the region interface.

Methods
nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]

Return all nested operation lists in this control flow op.

nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return uniform views of every nested operation region.

Subclasses with explicit block arguments, captures, or yields override this method. The fallback keeps legacy operation-owned blocks visible while consumers migrate from nested_op_lists.

Returns:

tuple[Region, ...] — tuple[Region, ...]: Region views in nested_op_lists order.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation

Return a copy with nested operation lists replaced.

new_lists must have the same length/order as nested_op_lists().

rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Return a copy with replacement region operation sequences.

Concrete control-flow operations override this method to rebuild both their body operations and boundary values. The fallback supports legacy region owners whose boundary remains operation-specific.

Parameters:

NameTypeDescription
regionsSequence[Region]Replacement regions in nested_regions order.

Returns:

Operation — Rebuilt control-flow operation.

Raises:


IfOperation [source]

class IfOperation(HasNestedOps, Operation)

Represents an if-else conditional operation.

Example:

if condition:
    true_body
else:
    false_body
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    true_operations: list[Operation] = list(),
    false_operations: list[Operation] = list(),
    true_yields: list[Value] = list(),
    false_yields: list[Value] = list(),
    branch_rebinds: tuple[BranchRebind, ...] = (),
    true_captures: tuple[ValueBase, ...] = (),
    false_captures: tuple[ValueBase, ...] = (),
) -> None
Attributes
Methods
add_merge
def add_merge(self, true_value: Value, false_value: Value, result: Value) -> None

Append a branch-merge slot to this if-else.

The only sanctioned construction path for merges: it keeps the yield lists and results index-aligned so iter_merges can rely on the invariants it checks.

Parameters:

NameTypeDescription
true_valueValueValue selected when the condition is true.
false_valueValueValue selected when the condition is false. Must have the same type as true_value.
resultValueFresh SSA value representing the merged output. Must have the same type as the branch values.

Raises:

all_input_values
def all_input_values(self) -> list[ValueBase]

Include branch-yield values and rebind records for cloning/substitution.

The yields are subclass-specific Value fields (not operands — see the class docstring), so generic passes reach them through this override, mirroring ForItemsOperation.key_var_values. Branch rebind records follow the loop operations’ rationale: the recorded pre-branch values reference program values by identity, so inline cloning must remap them in lockstep with operands. Read-based checks must not treat the records as reads (see _op_read_uuids in the analyze pass module).

Returns:

list[ValueBase] — list[ValueBase]: Base input values plus the true/false yields and rebind-record values.

iter_merges
def iter_merges(self) -> Iterator[IfMerge]

Iterate the branch-merge slots of this if-else.

This is the single read API for merge semantics: passes must consume merges through it (never through the yield lists directly) so the underlying storage can change without touching consumers.

Yields:

IfMerge — One entry per merged output, in result order.

Raises:

nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]

Return the two branch bodies (merge yields are not operations).

Returns:

list[list[Operation]] — list[list[Operation]]: [true_operations, false_operations]. The branch-merge yields are values, not operations, so they are intentionally absent here.

nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return the true and false branch interfaces.

Returns:

tuple[Region, ...] — tuple[Region, ...]: True and false regions in that order, with branch-local captures and merge yields.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation

Return a copy with the true and false branch bodies replaced.

Parameters:

NameTypeDescription
new_listslist[list[Operation]]The replacement branch bodies in nested_op_lists order ([true_operations, false_operations]).

Returns:

Operation — A copy of this if-else with the branch bodies swapped and all other fields (yields, rebinds) preserved.

rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Rebuild both branches and their complete boundary interfaces.

Parameters:

NameTypeDescription
regionsSequence[Region]True and false replacement regions.

Returns:

Operation — Rebuilt conditional operation.

Raises:

replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

Substitute operand, result, branch-yield, and rebind-record values.

Parameters:

NameTypeDescription
mappingdict[str, ValueBase]UUID-keyed substitution map.

Returns:

Operation — The rewritten operation.


NotOp [source]

class NotOp(Operation)
Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
Attributes

ObservableType [source]

class ObservableType(ObjectTypeMixin, ValueType)

Type representing a Hamiltonian observable parameter.

This is a reference type - the actual qamomile.observable.Hamiltonian is provided via bindings during transpilation. It cannot be constructed or manipulated within qkernels.

Example usage:

import qamomile.circuit as qm
import qamomile.observable as qm_o

# Build Hamiltonian in Python
H = qm_o.Z(0) * qm_o.Z(1)

@qm.qkernel
def vqe(q: qm.Vector[qm.Qubit], H: qm.Observable) -> qm.Float:
    return qm.expval(q, H)

# H is passed as binding
executable = transpiler.transpile(vqe, bindings={"H": H})
Constructor
def __init__(self) -> None

Operation [source]

class Operation(abc.ABC)
Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
Attributes
Methods
all_input_values
def all_input_values(self) -> list[ValueBase]

Return all input Values including subclass-specific fields.

Generic passes should use this instead of accessing operands directly to ensure no Value is missed. Subclasses override this to include extra Value fields (e.g. ControlledUOperation.power).

replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

Return a copy with all Values substituted via mapping.

Handles operands, results, and subclass-specific Value fields. Subclasses override to handle their extra fields.


ParamHint [source]

class ParamHint
Constructor
def __init__(self, name: str, type: ValueType) -> None
Attributes

PauliEvolveOp [source]

class PauliEvolveOp(Operation)

Pauli evolution operation: exp(-i * gamma * H).

This operation applies the time evolution of a Pauli Hamiltonian to a quantum register.

Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
Attributes

QFixedType [source]

class QFixedType(QuantumTypeMixin, ValueType)

Quantum fixed-point type.

Represents a quantum register encoding a fixed-point number with specified integer and fractional bits.

Constructor
def __init__(
    self,
    integer_bits: int | Value[UIntType] = 0,
    fractional_bits: int | Value[UIntType] = 0,
) -> None
Attributes
Methods
label
def label(self) -> str

QInitOperation [source]

class QInitOperation(Operation)

Initialize the qubit

Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
Attributes

QubitType [source]

class QubitType(QuantumTypeMixin, ValueType)

Type representing a quantum bit (qubit).


RegionArg [source]

class RegionArg

Explicit loop-carried value on a loop operation (MLIR-style iter_arg).

A RegionArg makes a loop-carried dependency explicit in the IR, the way MLIR’s scf.for models iter_args / scf.yield:

The loop body’s operations reference block_arg (the frontend substitutes the traced pre-loop reads), and post-loop operations reference result (the frontend rebinds the Python handle when it closes the loop). result is also appended to the loop operation’s results list so dependency analysis sees the loop as its producer.

This subsumes the trace-once staleness that LoopCarriedRebind records exist to reject: a rebind represented as a RegionArg is a supported loop-carried value, not a miscompilation hazard.

Constructor
def __init__(
    self,
    var_name: str,
    init: Value,
    block_arg: Value,
    yielded: Value,
    result: Value,
) -> None
Attributes

ReleaseSliceViewOperation [source]

class ReleaseSliceViewOperation(Operation)

Mark a slice view’s borrow as explicitly returned to its parent.

Emitted by :meth:Vector.__setitem__ when used with a slice index (qs[a:b] = qmc.h(qs[a:b])). This op tells the post-fold linearity checker (:class:~qamomile.circuit.transpiler.passes.slice_borrow_check.SliceBorrowCheckPass) that the view referenced in operands[0] no longer owns its covered parent slots, mirroring the frontend’s VectorView.consume(operation_name="slice assignment") borrow release.

Like :class:SliceArrayOperation, this op is a declarative classical-side marker that does not survive into the emit stream: :class:~qamomile.circuit.transpiler.passes.strip_slice_ops.StripSliceArrayOpsPass removes both :class:SliceArrayOperation and :class:ReleaseSliceViewOperation after :class:SliceBorrowCheckPass has observed them. Reaching emit is a compiler-internal invariant violation and is rejected with a RuntimeError from :mod:standard_emit.

Within a control-flow body (ForOperation / WhileOperation / IfOperation), this op only releases view borrows that were created within the same body. Releasing a borrow that the enclosing block has registered (an “outer-snapshot” borrow) is rejected by SliceBorrowCheckPass with ValidationError — the loop-merge semantics of the pass cannot propagate entry deletions out of the body, so the only way to keep the static check consistent is to forbid that pattern.

Example:

``qs[1:3] = qmc.h(qs[1:3])`` emits, after the broadcast loop::

    ReleaseSliceViewOperation(
        operands=[qmc_h_result_view],  # slice_of=qs_value
        results=[],
    )
Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
Attributes

ReturnQuantumArrayElementOperation [source]

class ReturnQuantumArrayElementOperation(Operation)

Validate a branch-selected quantum element’s array return at emit time.

Most quantum element assignments are verified structurally by the frontend and emit no IR. A compile-time conditional can instead select different element indices on its branches; only the unrolled emit context knows which source index survived. This operation carries both the requested target indices and the conditional source indices so emission can prove they resolve to the same physical slot before treating the assignment as a borrow return.

Operand convention:

[array, returned_qubit, *target_indices, *source_indices]. The target and source halves have equal nonzero arity, inferred from the operand count. The operation has no results and emits no backend gate.

Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
Attributes

RuntimeClassicalExpr [source]

class RuntimeClassicalExpr(Operation)

A classical expression known to require runtime evaluation.

Lowered from CompOp / CondOp / NotOp / BinOp by ClassicalLoweringPass when the op’s operand dataflow traces back to a MeasureOperation (i.e. cannot be folded at compile-time, by emit-time loop unrolling, or by compile_time_if_lowering). Backend emit translates this 1:1 to a backend-native runtime expression (e.g. qiskit.circuit.classical.expr.Expr).

Operand convention:

The single-node + unified-kind shape (vs four parallel subclasses) keeps the backend dispatch a single match op.kind instead of four parallel hooks, and makes the IR self-documenting: a single RuntimeClassicalExpr instance signals “runtime evaluation required” regardless of which classical family it came from.

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    kind: RuntimeOpKind | None = None,
) -> None
Attributes

RuntimeOpKind [source]

class RuntimeOpKind(enum.Enum)

Unified kind for RuntimeClassicalExpr covering all classical op families that can appear at runtime.

The split between this enum and the per-family BinOpKind / CompOpKind / CondOpKind is intentional: compile-time-foldable classical ops keep their original IR types so the existing fold pipeline (constant_foldcompile_time_if_lowering → emit-time evaluate_classical_predicate) is undisturbed. Only ops identified as runtime-evaluation-only by ClassicalLoweringPass get rewritten to RuntimeClassicalExpr with a member of this enum.

Attributes

SliceArrayOperation [source]

class SliceArrayOperation(Operation)

Construct a strided view of an ArrayValue.

The op itself performs no quantum action — it records that the result ArrayValue is a strided view of the operand parent with the given start / step. The result’s slice_of / slice_start / slice_step fields carry the affine map used by the emit-time resolver.

SliceArrayOperation is classified as :attr:OperationKind.CLASSICAL because slicing is pure index selection — no new quantum operation is introduced. The pipeline keeps this op through PartialEvaluationPass (which invokes ConstantFoldingPass(..., strip_slice_ops=False)) so the post-fold :class:~qamomile.circuit.transpiler.passes.slice_borrow_check.SliceBorrowCheckPass can use it as a view-declaration marker; once that check has run, StripSliceArrayOpsPass removes every SliceArrayOperation / ReleaseSliceViewOperation so segmentation (:mod:~qamomile.circuit.transpiler.passes.separate) and the downstream emit stage only see a pure quantum-op stream. By the time :mod:~qamomile.circuit.transpiler.passes.separate runs the op has therefore been stripped — reaching emit is a compiler- internal invariant violation.

Example:

``q[1::2]`` on a ``Vector[Qubit]`` emits::

    SliceArrayOperation(
        operands=[q_value, uint_1, uint_2],
        results=[sliced_value],  # slice_of=q_value, slice_start=uint_1, slice_step=uint_2
    )
Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
Attributes

StaticBindingMemberSpec [source]

class StaticBindingMemberSpec

Describe one deferred qkernel-valued member of a static binding.

Parameters:

NameTypeDescription
input_typesMapping[str, Any]Ordered frontend input annotations.
output_typestuple[Any, ...]Ordered frontend result annotations.
return_annotationAnyComplete Python return annotation.
getterCallable[[Any], Any]Extractor returning the concrete qkernel-like member.
qubit_width_fieldsMapping[str, str]Input-name to scalar field-name mapping used to specialize quantum vector widths.
Constructor
def __init__(
    self,
    input_types: Mapping[str, Any],
    output_types: tuple[Any, ...],
    return_annotation: Any,
    getter: Callable[[Any], Any],
    qubit_width_fields: Mapping[str, str] = dict(),
) -> None
Attributes

StaticBindingSlot [source]

class StaticBindingSlot

Declare one typed compile-time object required by a qkernel.

The object itself is not an SSA value and never reaches a backend. Only registered scalar projections and deferred callable-member references may appear in the hierarchical body. A build must resolve the slot before the block advances to a compiler stage.

Parameters:

NameTypeDescription
namestrQKernel argument name used by bindings.
type_keystrStable key of the registered static-binding adapter.
fieldstuple[StaticBindingField, ...]Scalar projections referenced while tracing the unbound qkernel.
Constructor
def __init__(
    self,
    name: str,
    type_key: str,
    fields: tuple[StaticBindingField, ...] = (),
) -> None
Attributes

StaticBindingSpec [source]

class StaticBindingSpec

Register the closed qkernel surface of one compile-time object type.

Parameters:

NameTypeDescription
annotationtype[Any]Public qkernel parameter annotation.
type_keystrStable serialization key.
fieldsMapping[str, StaticBindingFieldSpec]Scalar projections available while tracing.
membersMapping[str, StaticBindingMemberSpec]Deferred callable members available while tracing.
Constructor
def __init__(
    self,
    annotation: type[Any],
    type_key: str,
    fields: Mapping[str, StaticBindingFieldSpec],
    members: Mapping[str, StaticBindingMemberSpec],
) -> None
Attributes

StoreArrayElementOperation [source]

class StoreArrayElementOperation(Operation)

Store a classical scalar into one element of a classical array.

This is the IR form of array[index] = value for classical element types (Bit / UInt / Float). Classical values are freely copyable, so the store is an ordinary SSA rewrite: the operation consumes the current array version and produces a new ArrayValue version (same logical_id, fresh uuid) whose contents equal the input array with the addressed element replaced. Quantum arrays never use this operation — qubit element assignment is the return half of the borrow-return idiom and emits no IR.

The operation is evaluated in one of two places:

Operand convention:

operands: [array (ArrayValue), stored_value (Value), *index_values] results: [new_array (ArrayValue)]

Example:

@qmc.qkernel
def k() -> qmc.Vector[qmc.Bit]:
    qs = qmc.qubit_array(2, "qs")
    qs[0] = qmc.x(qs[0])
    bits = qmc.measure(qs)
    bits[1] = bits[0]   # emits StoreArrayElementOperation
    return bits
Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
Attributes

SymbolicControlledU [source]

class SymbolicControlledU(ControlledUOperation)

Controlled-U with symbolic (Value) number of controls.

Operand layout: [ctrl_arg_0, ..., ctrl_arg_{k-1}, tgt_0, ..., tgt_m, params...] Result layout: [ctrl_arg_0', ..., ctrl_arg_{k-1}', tgt_0', ..., tgt_m']

The number of control arguments k is recorded in num_control_args; the default k = 1 corresponds to the historical single-pool form (operands[0] is a Vector[Qubit] / VectorView whose length equals num_controls, or whose control_indices-selected subset does). When k > 1 the control prefix is a heterogeneous sequence of scalar Qubit values and ArrayValues whose total qubit count is num_controls; the emit pass walks them in order to recover the per-physical-qubit control set.

When control_indices is None the entire control prefix is used as active controls (one-arg form: len(ctrl_vector) == num_controls; multi-arg form: the qubit-count sum of the prefix args equals num_controls). When non-None, the listed indices select exactly num_controls slots from a single-arg pool to act as controls; combining control_indices with the multi-arg control prefix is rejected at frontend time.

Each control_indices entry is stored as a Value of UIntType regardless of whether the frontend passed an int literal or a UInt handle, so all downstream value-substitution passes see a uniform shape.

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    power: int | Value = 1,
    block: Block | None = None,
    num_controls: Value = (lambda: Value(type=(UIntType()), name=''))(),
    callable_ref: CallableRef | None = None,
    callable_attrs: dict[str, Any] = dict(),
    control_indices: tuple[Value, ...] | None = None,
    num_control_args: int = 1,
) -> None
Attributes
Methods
all_input_values
def all_input_values(self) -> list[ValueBase]
replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

TupleValue [source]

class TupleValue(_MetadataValueMixin, ValueBase)

A tuple of IR values for structured data.

Constructor
def __init__(
    self,
    name: str,
    elements: tuple[ValueLike, ...] = tuple(),
    metadata: ValueMetadata = ValueMetadata(),
    uuid: str = (lambda: str(uuid.uuid4()))(),
    logical_id: str = (lambda: str(uuid.uuid4()))(),
) -> None
Attributes
Methods
is_constant
def is_constant(self) -> bool
next_version
def next_version(self) -> TupleValue

UIntType [source]

class UIntType(ClassicalTypeMixin, ValueType)

Type representing an unsigned integer.


UnaryMathOp [source]

class UnaryMathOp(Operation)

Represent one pure unary mathematical expression.

Parameters:

NameTypeDescription
operandslist[Value]Single numeric input value.
resultslist[Value]Single numeric result value.
kindUnaryMathOpKind | NoneMathematical operation to apply.

Raises:

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    kind: UnaryMathOpKind | None = None,
) -> None
Attributes

UnaryMathOpKind [source]

class UnaryMathOpKind(enum.Enum)

Identify one abstract unary mathematical operation.

Attributes

Value [source]

class Value(_MetadataValueMixin, ValueBase, Generic[T])

A typed SSA value in the IR.

The name field is display-only: it labels the value for visualization and error messages and has no role in identity. Identity is carried by uuid (per-version) and logical_id (across versions).

An empty string (name="") is the anonymous marker used by auto-generated tmp values (arithmetic results, comparison results, coerced constants). Compiler-internal identity and writes use UUIDs or explicit parameter metadata. Compatibility readers may consult a non-empty label only after those identity channels, so anonymous temporaries cannot collide through a shared display key.

Constructor
def __init__(
    self,
    type: T,
    name: str,
    version: int = 0,
    metadata: ValueMetadata = ValueMetadata(),
    uuid: str = (lambda: str(uuid.uuid4()))(),
    logical_id: str = (lambda: str(uuid.uuid4()))(),
    parent_array: ArrayValue | None = None,
    element_indices: tuple[Value, ...] = (),
) -> None
Attributes
Methods
is_array_element
def is_array_element(self) -> bool
next_version
def next_version(self) -> Value[T]

Create a new Value with incremented version and fresh UUID.

Metadata is intentionally preserved across versions so that parameter bindings and constant annotations remain accessible after the value is updated (e.g. by a gate application or a classical operation). The logical_id also stays the same: it identifies the same logical variable across SSA versions, independently of backend resource allocation. This applies to every Value regardless of its type (Qubit, Float, Bit, ...) -- it is not specific to qubits.


ValueBase [source]

class ValueBase

Nominal base for every typed IR value.

Runtime compiler passes inspect values in their innermost loops. A nominal base keeps those checks constant-time; a runtime-checkable protocol would repeatedly scan the protocol members on Python versions that do not cache structural checks.

Attributes
Methods
get_const
def get_const(self) -> int | float | bool | None

Return the scalar constant carried by this value.

Returns:

int | float | bool | None — int | float | bool | None: Constant value, or None when the value is not constant.

is_constant
def is_constant(self) -> bool

Return whether this value carries a scalar constant.

Returns:

bool — Whether scalar constant metadata is present.

is_parameter
def is_parameter(self) -> bool

Return whether this value represents a runtime parameter.

Returns:

bool — Whether parameter metadata is present.

next_version
def next_version(self) -> ValueBase

Create the next SSA version of this value.

Returns:

ValueBase — A value with a fresh version UUID and preserved logical identity.

parameter_name
def parameter_name(self) -> str | None

Return the public parameter name carried by this value.

Returns:

str | None — str | None: Parameter name, or None for a non-parameter value.


ValueType [source]

class ValueType(abc.ABC)

Base class for all value types in the IR.

Type instances are compared by class - all instances of the same type class are considered equal. This allows using type instances as dictionary keys where all QubitType() instances match.

Methods
is_classical
def is_classical(self) -> bool
is_object
def is_object(self) -> bool
is_quantum
def is_quantum(self) -> bool
label
def label(self) -> str

WhileOperation [source]

class WhileOperation(HasNestedOps, Operation)

Represents a while loop operation.

Only measurement-backed conditions are supported: the condition must be a Bit value produced by qmc.measure(). Non-measurement conditions (classical variables, constants, comparisons) are rejected by ValidateWhileContractPass before reaching backend emit.

Example::

bit = qmc.measure(q)
while bit:
    q = qmc.h(q)
    bit = qmc.measure(q)
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    operations: list[Operation] = list(),
    max_iterations: int | None = None,
    loop_carried_rebinds: tuple[LoopCarriedRebind, ...] = (),
    region_args: tuple[RegionArg, ...] = (),
    captures: tuple[ValueBase, ...] = (),
) -> None
Attributes
Methods
all_input_values
def all_input_values(self) -> list[ValueBase]

Include rebind records and region args for cloning/substitution.

Same rationale as ForOperation.all_input_values: rebind records and region arguments reference body/pre-loop values by identity, so inline cloning must remap them in lockstep with body operands.

Returns:

list[ValueBase] — list[ValueBase]: Base input values plus rebind-record and region-argument values.

nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]
nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return the while body with explicit boundary values.

Returns:

tuple[Region, ...] — tuple[Region, ...]: One body region whose block arguments and yields are aligned with region_args. The updated condition, when present, is appended as the final yield.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation
rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Rebuild the while body and its complete boundary interface.

Parameters:

NameTypeDescription
regionsSequence[Region]Exactly one replacement body region.

Returns:

Operation — Rebuilt while operation.

Raises:

replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

Substitute operand, rebind-record, and region-arg values.

Parameters:

NameTypeDescription
mappingdict[str, ValueBase]UUID-keyed substitution map.

Returns:

Operation — The rewritten operation.