Python API Reference¶
Compilation¶
clifft.compile ¶
compile(
stim_text: str,
postselection_mask: list[int] | None = None,
expected_detectors: list[int] | None = None,
expected_observables: list[int] | None = None,
normalize_syndromes: bool = False,
hir_passes: HirPassManager
| None
| _DefaultPasses = _DEFAULT_PASSES,
bytecode_passes: BytecodePassManager
| None
| _DefaultPasses = _DEFAULT_PASSES,
) -> Program
Compile a quantum circuit string to executable bytecode.
Runs the full pipeline: parse -> trace -> [HIR optimize] -> lower -> [bytecode optimize].
By default both optimization stages run with their default pass managers. To skip optimization, pass hir_passes=None and/or bytecode_passes=None. To use a custom pipeline, pass an explicit HirPassManager / BytecodePassManager.
When normalize_syndromes=True, a noiseless reference shot is executed internally to extract expected detector and observable parities. Detectors and observables are then XOR-normalized so that 0 means 'matches noiseless reference' and 1 means 'error'.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
stim_text | str | Circuit in .stim text format. | required |
postselection_mask | list[int] | None | Optional list of uint8 flags, one per detector. Detectors where mask[i] != 0 become post-selection checks that abort the shot early if their parity is non-zero. | None |
expected_detectors | list[int] | None | Optional noiseless reference parities for detectors. | None |
expected_observables | list[int] | None | Optional noiseless reference parities for observables. | None |
normalize_syndromes | bool | If True, auto-compute reference parities from a noiseless reference shot (mutually exclusive with explicit parities). | False |
hir_passes | HirPassManager | None | _DefaultPasses | HirPassManager to run on the HIR before lowering. Defaults to | _DEFAULT_PASSES |
bytecode_passes | BytecodePassManager | None | _DefaultPasses | BytecodePassManager to run after lowering. Defaults to | _DEFAULT_PASSES |
Source code in .venv/lib/python3.12/site-packages/clifft/__init__.py
clifft.parse ¶
parse(text: str) -> clifft._clifft_core.Circuit parse(text: str, max_ops: int) -> clifft._clifft_core.Circuit
Overloaded function.
parse(text: str) -> clifft._clifft_core.Circuit
Parse a quantum circuit from a string.
parse(text: str, max_ops: int) -> clifft._clifft_core.Circuit
Parse a quantum circuit from a string with an explicit AST node limit.
clifft.parse_file ¶
parse_file(path: str) -> clifft._clifft_core.Circuit parse_file(path: str, max_ops: int) -> clifft._clifft_core.Circuit
Overloaded function.
parse_file(path: str) -> clifft._clifft_core.Circuit
Parse a quantum circuit from a file.
parse_file(path: str, max_ops: int) -> clifft._clifft_core.Circuit
Parse a quantum circuit from a file with an explicit AST node limit.
clifft.trace ¶
trace(circuit: clifft._clifft_core.Circuit) -> clifft._clifft_core.HirModule
Trace a parsed circuit through the Clifford front-end to produce the Heisenberg IR.
clifft.lower ¶
lower(hir: clifft._clifft_core.HirModule, postselection_mask: collections.abc.Sequence[int] = [], expected_detectors: collections.abc.Sequence[int] = [], expected_observables: collections.abc.Sequence[int] = []) -> clifft._clifft_core.Program
Lower a Heisenberg IR module to executable VM bytecode.
To optimize the bytecode, use a BytecodePassManager after lowering: prog = clifft.lower(hir) bpm = clifft.default_bytecode_pass_manager() bpm.run(prog)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hir | The Heisenberg IR module to lower. | required | |
postselection_mask | Optional list of uint8 flags, one per detector. Detectors where mask[i] != 0 become post-selection checks that abort the shot early if their parity is non-zero. | required | |
expected_detectors | Optional noiseless reference parities for detectors. | required | |
expected_observables | Optional noiseless reference parities for observables. | required |
clifft.ParseError ¶
Bases: builtins.Exception
Sampling¶
clifft.sample ¶
sample(program: clifft._clifft_core.Program, shots: int, seed: int | None = None) -> object
Run a compiled program and return a SampleResult.
Raises ValueError for post-selected programs because fixed-row output cannot represent discarded shots. Use sample_survivors() instead.
If seed is None (default), uses hardware entropy.
Returns a SampleResult with .measurements, .detectors, .observables attributes. Supports tuple unpacking: m, d, o = clifft.sample(prog, shots)
clifft.sample_survivors ¶
sample_survivors(program: clifft._clifft_core.Program, shots: int, seed: int | None = None, keep_records: bool = False) -> object
Sample shots and return results only for surviving (non-discarded) shots.
If seed is None (default), uses hardware entropy.
Returns a SampleResult. Survivor metadata is always populated via .total_shots, .passed_shots, .discards, .logical_errors, and .observable_ones. Per-shot record arrays (.measurements, .detectors, .observables, .exp_vals) are only filled when keep_records=True; otherwise they are empty (rows=0).
clifft.sample_k ¶
sample_k(program: clifft._clifft_core.Program, shots: int, k: int, seed: int | None = None) -> object
Sample with exactly k forced faults per shot (importance sampling).
Sites are drawn from the exact conditional Poisson-Binomial distribution. Results are conditioned on K=k and must be combined across strata with P(K=k) weights for correct error rate estimation. Raises ValueError for post-selected programs because fixed-row output cannot represent discarded shots. Use sample_k_survivors() instead.
For post-selected circuits, weight numerator and denominator separately via sample_k_survivors(): p_fail = sum(P(K=k)errors_k/shots_k) / sum(P(K=k)passed_k/shots_k).
Raises ValueError if the k-fault stratum has zero probability mass (e.g. k exceeds the number of non-zero-probability sites).
When all site probabilities are equal, an O(k) Fisher-Yates sampler is used automatically.
Returns a SampleResult with .measurements, .detectors, .observables attributes. Supports tuple unpacking: m, d, o = clifft.sample_k(prog, shots, k)
clifft.sample_k_survivors ¶
sample_k_survivors(program: clifft._clifft_core.Program, shots: int, k: int, seed: int | None = None, keep_records: bool = False) -> object
Sample survivors with exactly k forced faults per shot.
Results are conditioned on K=k. To estimate the overall logical error rate across strata, weight numerator and denominator separately to account for k-dependent survival probability: p_fail = sum(P(K=k)logical_errors_k/shots_k) / sum(P(K=k)passed_k/shots_k)
Raises ValueError if the k-fault stratum has zero probability mass.
Returns a SampleResult. Survivor metadata is always populated via .total_shots, .passed_shots, .discards, .logical_errors, and .observable_ones. Per-shot record arrays (.measurements, .detectors, .observables, .exp_vals) are only filled when keep_records=True; otherwise they are empty (rows=0).
Strong Simulation¶
clifft.basis_probabilities ¶
basis_probabilities(
program: Program,
bitstrings: BasisBitstrings,
*,
bit_order: str = "big",
return_log: bool = False,
) -> npt.NDArray[np.float64]
Exact Born probabilities of computational-basis bitstrings.
Requires a unitary program (no measurements, feedback, noise, detectors, observables, or post-selection). For circuits with measurements, use :func:record_probabilities instead.
bit_order="big" maps the first character or array column to qubit 0. bit_order="little" maps the last character or array column to qubit 0.
Pass return_log=True to get natural-log probabilities. Zero probabilities map to -inf in log output.
Source code in .venv/lib/python3.12/site-packages/clifft/__init__.py
clifft.record_probabilities ¶
record_probabilities(
program: Program,
records: MeasurementRecords,
*,
return_log: bool = False,
) -> npt.NDArray[np.float64]
Exact joint probabilities of measurement records under sample().
Requires at least one measurement. For a purely unitary program with no measurements, use :func:basis_probabilities instead.
records is one of: a single record string (e.g. "010"), a sequence of record strings, or a 2D bool / uint8 array of shape (num_records, program.num_measurements). Each record is interpreted in measurement order -- position i is the i-th entry sample().measurements would emit.
Records the program cannot emit are reported as 0.0 (or -inf when return_log=True). For deep circuits whose probabilities underflow float64, pass return_log=True so the log-domain values survive.
Source code in .venv/lib/python3.12/site-packages/clifft/__init__.py
State Inspection¶
clifft.execute ¶
execute(program: clifft._clifft_core.Program, state: clifft._clifft_core.State) -> None
Execute a compiled program, updating the state in-place.
clifft.get_statevector ¶
get_statevector(program: clifft._clifft_core.Program, state: clifft._clifft_core.State) -> numpy.ndarray[dtype=complex128, order='C']
Expand the SVM state into a dense statevector.
For unitary programs, compilation preserves the API-visible global phase across optimization passes. Retained final-tableau expansion uses Stim's complex
Result Types¶
clifft.SampleResult ¶
SampleResult(
measurements: NDArray[uint8],
detectors: NDArray[uint8],
observables: NDArray[uint8],
total_shots: int | None = None,
passed_shots: int | None = None,
logical_errors: int | None = None,
observable_ones: NDArray[uint64] | None = None,
exp_vals: NDArray[float64] | None = None,
)
Structured result from Clifft sampling functions.
Common attributes
measurements: uint8 array, shape (shots, num_measurements) detectors: uint8 array, shape (shots, num_detectors) observables: uint8 array, shape (shots, num_observables)
Survivor-only attributes
total_shots: total number of shots attempted passed_shots: number of shots that survived post-selection discards: number of discarded shots (total_shots - passed_shots) logical_errors: number of surviving shots with at least one observable flipped observable_ones: uint64 array of per-observable error counts
Supports tuple unpacking for backward compatibility:
m, d, o = clifft.sample(prog, shots)
Source code in .venv/lib/python3.12/site-packages/clifft/_sample_result.py
Compiled Programs and Execution State¶
clifft.Program ¶
A compiled quantum program
Initialize self. See help(type(self)) for accurate signature.
active_k_history property ¶
Active dimension k after each instruction (list of uint32).
has_postselection property ¶
True if the program contains OP_POSTSELECT instructions.
noise_site_probabilities property ¶
Per-site total fault probabilities: quantum noise sites followed by readout noise entries. Use for Poisson-Binomial PMF computation.
as_dict method descriptor ¶
as_dict(self) -> dict
Return a JSON-friendly dictionary representation.
clifft.State ¶
Schrodinger VM execution state
init(self, *, peak_rank: int, num_measurements: int, num_detectors: int = 0, num_observables: int = 0, num_exp_vals: int = 0, seed: int | None = None) -> None
Circuit and IR Inspection¶
clifft.Circuit ¶
clifft.AstNode ¶
A single circuit operation
Initialize self. See help(type(self)) for accurate signature.
clifft.Target ¶
Encoded quantum target
Initialize self. See help(type(self)) for accurate signature.
clifft.HirModule ¶
Heisenberg Intermediate Representation
Initialize self. See help(type(self)) for accurate signature.
as_dict method descriptor ¶
as_dict(self) -> dict
Return a JSON-friendly dictionary representation.
clifft.HeisenbergOp ¶
A single abstract operation in the Heisenberg IR
Initialize self. See help(type(self)) for accurate signature.
as_dict method descriptor ¶
as_dict(self) -> dict
Return a JSON-friendly dictionary representation.
clifft.Instruction ¶
A localized VM operation
Initialize self. See help(type(self)) for accurate signature.
clifft.Opcode ¶
Bases: enum.Enum
Virtual Machine opcodes
clifft.OpType ¶
Bases: enum.Enum
Heisenberg IR operation types
clifft.GateType ¶
Bases: enum.Enum
Quantum gate types
Pass Managers¶
clifft.HirPassManager ¶
Runs a sequence of optimization passes over an HirModule.
init(self) -> None
clifft.BytecodePassManager ¶
Runs a sequence of bytecode optimization passes over a Program.
init(self) -> None
clifft.default_hir_pass_manager ¶
default_hir_pass_manager() -> clifft._clifft_core.HirPassManager
Return an HirPassManager pre-loaded with the default passes.
clifft.default_bytecode_pass_manager ¶
default_bytecode_pass_manager() -> clifft._clifft_core.BytecodePassManager
Return a BytecodePassManager pre-loaded with the default passes.
HIR Passes¶
clifft.PeepholeFusionPass ¶
clifft.StatevectorSqueezePass ¶
Bases: clifft._clifft_core.HirPass
Bidirectional bubble sort: moves measurements leftward and non-Clifford gates rightward to minimize peak active rank.
init(self) -> None
clifft.RemoveNoisePass ¶
Bases: clifft._clifft_core.HirPass
Strips all stochastic noise and readout noise ops from the HIR. Not included in the default pass list. Used internally by compute_reference_syndrome() for noiseless reference shots.
init(self) -> None
clifft.DropNonUnitaryPass ¶
Bases: clifft._clifft_core.HirPass
Drops non-evolution HIR ops so the remaining program is a unitary skeleton. Not included in the default pass list and not semantics-preserving.
init(self) -> None
Bytecode Passes¶
clifft.NoiseBlockPass ¶
Bases: clifft._clifft_core.BytecodePass
Coalesces contiguous OP_NOISE instructions into OP_NOISE_BLOCK.
init(self) -> None
clifft.ExpandTPass ¶
Bases: clifft._clifft_core.BytecodePass
Fuses OP_EXPAND + OP_ARRAY_T into single OP_EXPAND_T instructions.
init(self) -> None
clifft.ExpandRotPass ¶
Bases: clifft._clifft_core.BytecodePass
Fuses OP_EXPAND + OP_ARRAY_ROT into single OP_EXPAND_ROT instructions.
init(self) -> None
clifft.SwapMeasPass ¶
Bases: clifft._clifft_core.BytecodePass
Fuses OP_ARRAY_SWAP + OP_MEAS_ACTIVE_INTERFERE into OP_SWAP_MEAS_INTERFERE.
init(self) -> None
clifft.MultiGatePass ¶
Bases: clifft._clifft_core.BytecodePass
Fuses sequences of same-type 2-qubit gates into multi-target ops.
init(self) -> None
clifft.SingleAxisFusionPass ¶
Bases: clifft._clifft_core.BytecodePass
Fuses consecutive single-axis ops into OP_ARRAY_U2 with precomputed 2x2 matrices.
init(self) -> None
Utilities¶
clifft.get_num_threads ¶
get_num_threads() -> int
Return the current maximum number of OpenMP threads.
Threading only activates for circuits with peak rank >= 18 (statevector >= 4 MB).
Returns 1 if Clifft was built without OpenMP support.
clifft.set_num_threads ¶
set_num_threads(num_threads: int) -> None
Set the number of OpenMP threads for multi-core statevector operations.
Threading only activates for circuits with peak rank >= 18 (statevector >= 4 MB). Pure Clifford and low-T-count circuits run single-threaded regardless of this setting.
When using multiprocessing (e.g. sinter), set num_threads=1 in each worker to avoid oversubscription.
Has no effect if Clifft was built without OpenMP support.
clifft.svm_backend ¶
svm_backend() -> str
Return the active SVM dispatch backend.
Reflects the resolved runtime kernel path or the CLIFFT_FORCE_ISA environment override. In normal operation returns one of 'avx512', 'avx2', or 'scalar' ('scalar' names the generic/base SVM path).
If CLIFFT_FORCE_ISA names an ISA the host CPU cannot execute, or is set to an unrecognized value, the backend instead reports one of 'trap:avx512', 'trap:avx2', or 'trap:unknown'. The next execute() call throws RuntimeError with a message naming the missing features or accepted values.
clifft.compute_reference_syndrome ¶
compute_reference_syndrome(hir: clifft._clifft_core.HirModule) -> dict
Compute noiseless reference syndrome for an HirModule.
Returns a dict with 'detectors' and 'observables' lists.