Skip to main content

rqm-compiler

Backend-neutral optimization and rewriting engine for the RQM ecosystem.

rqm-compiler owns the internal compiler circuit model and the optimization pipeline. The canonical external/public circuit schema is defined by rqm-circuits; rqm-compiler is the next layer after that boundary.


RQM Technical Canon v2

u1q is a compact, backend-neutral, standard-compatible compiler IR. It preserves tested quaternion/SU(2) semantics; it is not a quantum-mechanically richer state representation.

EXP-009 Track B did not establish a compiler-runtime advantage: the tested Python quaternion fusion path lost runtime to the matrix baseline, and its serialized-size benefit did not pass the frozen universal gate. Correctness, determinism, integration, and future optimization remain valid engineering goals. See RQM_TECHNICAL_CANON_V2.md.


Installation

pip install rqm-compiler

Or in development mode from the repository root:

pip install -e ".[dev]"

Quickstart

Note for external integrations: Callers coming from the RQM API, Studio, or any external integration will typically enter the ecosystem through rqm-circuits, which owns the canonical public circuit schema. rqm-compiler is the next layer: it receives a parsed/validated circuit object and runs the optimization pipeline before handing off to a backend adapter.

from rqm_compiler import Circuit, optimize_circuit, lower_circuit_for_backend

c = Circuit(2)
c.h(0)
c.cx(0, 1)
c.measure_all()

# Recommended: optimize and export
optimized, report = optimize_circuit(c)
print(report)

# Optional backend-targeted lowering stage (example: Braket gate model).
# Internal optimization IR remains canonical u1q unless this is requested.
lowered = lower_circuit_for_backend(optimized, backend_family="braket_gate_model")
descriptors = lowered.to_descriptors()

Public API Hierarchy

rqm-compiler exposes a tiered API. Most users should use Tier 1. Lower tiers exist for transformations and advanced workflows.

Tier Entrypoint When to use Stability
1 — Build Circuit, Operation Construct programs in the compiler's internal model Stable
2 — Transform compile_circuit(...), optimize_circuit(...), lower_circuit_for_backend(...), compile_for_backend(...) Run optimization passes, then optional backend-targeted lowering/export Experimental
3 — Internal low-level IR utilities Advanced use Subject to change

Architecture

rqm-core
    ↓
rqm-circuits   ← canonical external/public circuit IR
    ↓
rqm-compiler   ← this repo (internal optimization engine)
    ↓
rqm-qiskit / rqm-braket   ← backend lowering and execution bridges
    ↓ (optional)
rqm-optimize
Layer Responsibility
rqm-core Quaternion algebra, SU(2), Bloch sphere, spinor math
rqm-entanglement Two-qubit tensor structure, arbitrary SU(4) quaternion–Cartan decomposition, Weyl classification, nonlocal fingerprints
rqm-circuits Canonical external/public circuit schema, including RXX/RYY/RZZ
rqm-compiler Backend-neutral optimization and opt-in internal su4q block IR
rqm-qiskit / rqm-braket Backend candidate synthesis, lowering, and execution bridges
rqm-optimize Optional backend-adjacent optimization and compression

rqm-compiler does not implement decomposition math and does not import any vendor SDK. Quaternion/SU(2) work is delegated to rqm-core; arbitrary SU(4) decomposition, reconstruction, Weyl classification, and fingerprints are delegated to rqm-entanglement.


What rqm-compiler owns

  • Circuit — the internal compiler circuit model used by optimization passes
  • Operation — the internal instruction model used by compiler transforms
  • Gate semantics and supported gate set (compiler-internal)
  • Circuit structure and composition rules
  • Pass pipelines: normalization, canonicalization, gate fusion, cancellation
  • Serialization helpers (circuit_to_dict, circuit_from_dict)
  • Internal backend-neutral descriptor export for translation and debugging
  • Compiler reports and optimization metadata (CompilerReport)
  • Opt-in proof-gated extraction of internal su4q candidates

What rqm-compiler does NOT own

  • The canonical public/external circuit schema — belongs in rqm-circuits
  • API wire format or Studio payload format — belongs in rqm-circuits
  • Quaternion algebra — belongs in rqm-core
  • Spinor math — belongs in rqm-core
  • SU(2) or Bloch sphere math — belongs in rqm-core
  • Qiskit objects or imports — belongs in rqm-qiskit
  • Amazon Braket objects or imports — belongs in rqm-braket
  • Any execution or simulation logic

Internal compiler descriptor format

Every gate operation inside the compiler is represented as a plain dictionary. This is the internal compiler descriptor format — useful for debugging, backend translation, and pass inspection. It is not the canonical external public circuit schema (that lives in rqm-circuits).

{
    "gate": "rx",       # lowercase gate name
    "targets": [0],     # list of target qubit indices (always present)
    "controls": [],     # list of control qubit indices (always present)
    "params": {"angle": 1.5707963267948966}  # parameter dict (always present)
}

Circuit builder API (Tier 1)

from rqm_compiler import Circuit

c = Circuit(3)

# Single-qubit gates
c.i(0); c.x(0); c.y(1); c.z(2); c.h(0); c.s(1); c.t(2)

# Parameterised single-qubit gates
c.rx(0, 1.57).ry(1, 0.78).rz(2, 3.14).phaseshift(0, 0.5)

# Two-qubit gates
c.cx(0, 1).cy(1, 2).cz(0, 2)
c.swap(0, 1).iswap(1, 2)
c.rxx(0, 1, 0.25).ryy(1, 2, 0.5).rzz(0, 2, 0.75)

# Measurement
c.measure(0, key="m0")
c.measure_all()   # measures all qubits with default keys

# Barrier
c.barrier()

# Export to internal compiler descriptor list
descriptors = c.to_descriptors()

# Reconstruct from a descriptor list (inverse of to_descriptors)
restored = Circuit.from_descriptors(descriptors, num_qubits=3)

Opt-in internal su4q analysis

su4q means a universal two-qubit quaternion–Cartan compiler block. It is an internal compiler descriptor, not part of the public rqm-circuits wire format and not a claim of quaternionic composite mechanics.

from rqm_compiler import analyze_two_qubit_blocks, extract_su4q_blocks

report = analyze_two_qubit_blocks(circuit)  # default: no replacement

candidate_view, report = extract_su4q_blocks(circuit, mode="emit_candidate")
assert candidate_view.to_descriptors() == circuit.to_descriptors()

lowering_input, report = extract_su4q_blocks(
    circuit,
    mode="replace_if_backend_requests",
    backend_requests_su4q=True,
)

Only maximal, same-pair, resolved unitary windows below the dense-verification limit are considered. Measurement, reset-like unsupported operations, barrier, classical conditions, a third qubit, unresolved parameters, ordering failures, or reconstruction error cause fail-closed preservation of the original operations. The normal optimize_circuit pipeline never introduces su4q.


Transformation API (Tier 2 — Experimental)

optimize_circuit is the recommended Tier 2 entry point. It runs the full optimization pipeline (validate → normalize → canonicalize → flatten → to_u1q → gate merging → cancellation) and returns an optimized circuit plus a :class:CompilerReport. Use this as your default mental model for backend integration.

Important: u1q is the canonical internal single-qubit optimization IR. Named-gate lowering (e.g. rz/ry/rz) is an explicit backend-targeted stage via lower_circuit_for_backend(...) or compile_for_backend(...). The u1q convention is inherited from rqm-core: q = w + xi + yj + zk maps to [[w-iz, -y-ix], [y-ix, w+iz]]. With this convention Quaternion.from_axis_angle("x", θ) agrees with Rx(θ), and likewise for Ry and Rz. The sign pair q/-q is only folded in phase-invariant, uncontrolled u1q contexts: it is the same SO(3)/Bloch rotation, while the SU(2) matrices differ by global phase.

compile_circuit is the lightweight alternative when you only need validation and normalization without optimization.

Both functions are optional — basic circuit construction works without them.

from rqm_compiler import optimize_circuit, compile_circuit

# Preferred: optimize first, then export to backend
optimized, report = optimize_circuit(c)
print(report)
for op in optimized.to_descriptors():
    translate_to_backend(op)

# Lightweight alternative: validate + normalize + export (no optimization)
compiled = compile_circuit(c)
compiled.descriptors   # list of internal compiler descriptor dicts
compiled.num_qubits    # int
compiled.metadata      # dict with compilation metadata

Semantic verification in optimize_circuit

optimize_circuit is proof-gated and fail-closed. It always follows:

  1. build a candidate optimized circuit
  2. run mandatory semantic verification
  3. commit only if verification is VERIFIED
  4. otherwise withhold optimization and return the original circuit unchanged

This means no successful optimization output is ever unverified.

CompilerReport records:

  • equivalence_status: always VERIFIED for the returned circuit
  • equivalence_verified: always True for the returned circuit
  • equivalence_guaranteed: explicit proof-gated guarantee for the returned circuit
  • optimization_applied: True only when a verified candidate was committed
  • fallback_reason: "verification_not_established" when optimization is withheld
  • equivalence_report: structured payload for the committed output, plus internal_candidate_proof_result for development diagnostics
  • equivalence_report["comparison"]: structured comparison metadata covering exact descriptor identity, exact single-qubit matrix equality where known, equality up to global phase, quaternion sign/Bloch equivalence, and whether an optimization candidate was withheld

Current verifier methods used internally:

  • U1Q_CANONICAL: exact single-qubit canonical-u1q comparison
  • UNITARY_NUMERICAL: dense unitary comparison up to global phase for supported small circuits
  • GATEWISE_IDENTITY: exact descriptor identity check for fully-resolved circuits

Important semantics:

  • Only verified candidates are committed as optimized output.
  • If proof fails, is unsupported, or errors, optimization is not committed.
  • Unsupported proof coverage causes optimization refusal/fallback, not uncertain output.

Backend repos should prefer optimize_circuit because it runs gate merging and cancellation before translation — circuits with redundant or adjacent single-qubit gates will be cheaper to execute after optimization. Verify the trade-off for your specific circuit patterns.


Reconstructing a circuit from descriptors

Circuit.from_descriptors(descriptors, num_qubits) is the inverse of to_descriptors(). It reconstructs a compiler Circuit from the internal descriptor format — useful for debugging, reproducibility, backend roundtrips, and tests. This is not the canonical external public IR boundary (which is owned by rqm-circuits).

from rqm_compiler import Circuit, optimize_circuit

c = Circuit(2)
c.h(0).cx(0, 1).measure_all()

# Optimize and capture the internal compiler descriptor IR
optimized, report = optimize_circuit(c)
descriptors = optimized.to_descriptors()

# Later: reconstruct a Circuit from those descriptors
restored = Circuit.from_descriptors(descriptors, num_qubits=optimized.num_qubits)
assert restored.to_descriptors() == descriptors

IO helpers

from rqm_compiler.io import circuit_to_dict, circuit_from_dict

data = circuit_to_dict(c)          # serialize to JSON-compatible dict
restored = circuit_from_dict(data)  # reconstruct Circuit from dict

Supported gates (v0)

Category Gates
Single-qubit i x y z h s t
Parameterised single-qubit rx ry rz phaseshift (param: angle)
Two-qubit cx cy cz swap iswap rxx ryy rzz
Internal structured two-qubit su4q (nested versioned QuaternionCartanBlock)
Other measure barrier

Development

# Install with dev dependencies
pip install -e ".[dev]"

# Run tests
pytest

Architecture rules

See AGENTS.md for the full list of contributor boundary rules. See docs/EXP012_SU4Q_BOUNDARY.md for the validated source and claim boundary.

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

rqm_compiler-0.2.2.tar.gz (68.2 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

rqm_compiler-0.2.2-py3-none-any.whl (52.8 kB view details)

Uploaded Python 3

File details

Details for the file rqm_compiler-0.2.2.tar.gz.

File metadata

  • Download URL: rqm_compiler-0.2.2.tar.gz
  • Upload date:
  • Size: 68.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.14

File hashes

Hashes for rqm_compiler-0.2.2.tar.gz
Algorithm Hash digest
SHA256 2694599c0512c25a7057952275ee336a15cf0aadf1e72a67eaaabd3516931384
MD5 9138d924c42f723ffba924877eaf2f2d
BLAKE2b-256 35a7c59b9508c3a6bcbc39587dfb5ed43bc1c4c96057038cea339c40e0c04ce9

See more details on using hashes here.

Provenance

The following attestation bundles were made for rqm_compiler-0.2.2.tar.gz:

Publisher: publish.yml on RQM-Technologies-dev/rqm-compiler

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file rqm_compiler-0.2.2-py3-none-any.whl.

File metadata

  • Download URL: rqm_compiler-0.2.2-py3-none-any.whl
  • Upload date:
  • Size: 52.8 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.14

File hashes

Hashes for rqm_compiler-0.2.2-py3-none-any.whl
Algorithm Hash digest
SHA256 1b9d1fe929d267054ff8bf495b498430162eb259e7f1f257b68304cd2e58802a
MD5 529c7ad3d9e978cf78d75cf6207c38fc
BLAKE2b-256 c386195eb499eb4e3ff6a0bd07431a5289f328db6b503b3f46465d0c59891aac

See more details on using hashes here.

Provenance

The following attestation bundles were made for rqm_compiler-0.2.2-py3-none-any.whl:

Publisher: publish.yml on RQM-Technologies-dev/rqm-compiler

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Release history Release notifications | RSS feed

0.3.0

2 files

This release

0.2.2 This release

2 files

0.2.1

2 files

0.2.0

2 files

0.1.5

2 files

0.1.0

2 files

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page