Skip to content

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_hir_pass_manager(). Pass None to skip.

_DEFAULT_PASSES
bytecode_passes BytecodePassManager | None | _DefaultPasses

BytecodePassManager to run after lowering. Defaults to default_bytecode_pass_manager(). Pass None to skip.

_DEFAULT_PASSES
Source code in .venv/lib/python3.12/site-packages/clifft/__init__.py
def 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'.

    Args:
        stim_text: Circuit in .stim text format.
        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.
        expected_detectors: Optional noiseless reference parities for detectors.
        expected_observables: Optional noiseless reference parities for observables.
        normalize_syndromes: If True, auto-compute reference parities from a
            noiseless reference shot (mutually exclusive with explicit parities).
        hir_passes: HirPassManager to run on the HIR before lowering.
            Defaults to ``default_hir_pass_manager()``. Pass ``None`` to skip.
        bytecode_passes: BytecodePassManager to run after lowering.
            Defaults to ``default_bytecode_pass_manager()``. Pass ``None`` to skip.
    """
    if isinstance(hir_passes, _DefaultPasses):
        hir_passes = default_hir_pass_manager()
    if isinstance(bytecode_passes, _DefaultPasses):
        bytecode_passes = default_bytecode_pass_manager()
    return _compile_core(
        stim_text,
        postselection_mask if postselection_mask is not None else [],
        expected_detectors if expected_detectors is not None else [],
        expected_observables if expected_observables is not None else [],
        normalize_syndromes,
        hir_passes,
        bytecode_passes,
    )

clifft.parse

parse(*args, **kwargs)

parse(text: str) -> clifft._clifft_core.Circuit parse(text: str, max_ops: int) -> clifft._clifft_core.Circuit

Overloaded function.

  1. parse(text: str) -> clifft._clifft_core.Circuit

Parse a quantum circuit from a string.

  1. 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(*args, **kwargs)

parse_file(path: str) -> clifft._clifft_core.Circuit parse_file(path: str, max_ops: int) -> clifft._clifft_core.Circuit

Overloaded function.

  1. parse_file(path: str) -> clifft._clifft_core.Circuit

Parse a quantum circuit from a file.

  1. 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(*args, **kwargs)

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(*args, **kwargs)

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(*args, **kwargs)

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(*args, **kwargs)

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(*args, **kwargs)

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(*args, **kwargs)

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
def 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.
    """
    probs = cast(
        npt.NDArray[np.float64],
        _basis_probabilities_from_bitmasks(
            program, _basis_masks_from_bitstrings(program, bitstrings, bit_order)
        ),
    )
    if return_log:
        # TODO: move logspace accumulation into the C++ amplitude walk so
        # very-rare-bitstring queries don't lose precision through the
        # linear->log conversion. Current path is symmetric with
        # record_probabilities() at the API surface but does not give the
        # precision benefit; that benefit only kicks in once the underlying
        # |amplitude|^2 sum is itself tracked in logspace.
        with np.errstate(divide="ignore"):
            return np.log(probs)
    return probs

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
def 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.
    """
    # Reject zero-measurement programs up front so a user who passes a real
    # record string against a unitary program gets the right hint rather
    # than the wrapper's record-length mismatch error.
    if program.num_measurements == 0:
        raise ValueError(
            "record_probabilities() requires a program with at least one "
            "measurement; use clifft.basis_probabilities() for unitary circuits."
        )
    record_array = _records_from_outcomes(program, records)
    log_probs = cast(
        npt.NDArray[np.float64],
        _record_probabilities_from_records(program, record_array),
    )
    # C++ marks unreachable records with the finite sentinel
    # numpy.finfo(float64).min (-DBL_MAX). Translate it back to the
    # Pythonic -inf for log output, and rely on the natural underflow
    # to 0.0 under np.exp for the linear case.
    if return_log:
        return np.where(log_probs == np.finfo(np.float64).min, -np.inf, log_probs)
    return np.exp(log_probs)

State Inspection

clifft.execute

execute(*args, **kwargs)

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(*args, **kwargs)

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 unitary path, so those amplitudes have float-scale precision. After measurements or noise, only relative amplitudes and probabilities are meaningful; overall phase may differ between compilations.

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
def __init__(
    self,
    measurements: npt.NDArray[np.uint8],
    detectors: npt.NDArray[np.uint8],
    observables: npt.NDArray[np.uint8],
    total_shots: int | None = None,
    passed_shots: int | None = None,
    logical_errors: int | None = None,
    observable_ones: npt.NDArray[np.uint64] | None = None,
    exp_vals: npt.NDArray[np.float64] | None = None,
) -> None:
    self.measurements = measurements
    self.detectors = detectors
    self.observables = observables
    self.exp_vals = (
        exp_vals
        if exp_vals is not None
        else np.empty((measurements.shape[0], 0), dtype=np.float64)
    )
    self.total_shots = total_shots
    self.passed_shots = passed_shots
    self.discards = (
        None if total_shots is None or passed_shots is None else total_shots - passed_shots
    )
    self.logical_errors = logical_errors
    self.observable_ones = observable_ones

Compiled Programs and Execution State

clifft.Program

Program(*args, **kwargs)

A compiled quantum program

Initialize self. See help(type(self)) for accurate signature.

active_k_history property

active_k_history

Active dimension k after each instruction (list of uint32).

has_postselection property

has_postselection

True if the program contains OP_POSTSELECT instructions.

noise_site_probabilities property

noise_site_probabilities

Per-site total fault probabilities: quantum noise sites followed by readout noise entries. Use for Poisson-Binomial PMF computation.

num_detectors property

num_detectors

(self) -> int

num_exp_vals property

num_exp_vals

(self) -> int

num_instructions property

num_instructions

(self) -> int

num_measurements property

num_measurements

(self) -> int

num_observables property

num_observables

(self) -> int

num_qubits property

num_qubits

(self) -> int

peak_rank property

peak_rank

(self) -> int

source_map property

source_map

Source line mapping parallel to bytecode (list of list of uint32).

as_dict method descriptor

as_dict()

as_dict(self) -> dict

Return a JSON-friendly dictionary representation.

clifft.State

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

det_record property

det_record

(self) -> list[int]

dust_clamps property

dust_clamps

(self) -> int

exp_vals property

exp_vals

(self) -> list[float]

meas_record property

meas_record

(self) -> list[int]

obs_record property

obs_record

(self) -> list[int]

reseed method descriptor

reseed()

reseed(self, seed: int) -> None

reset method descriptor

reset()

reset(self) -> None

Circuit and IR Inspection

clifft.Circuit

Circuit(*args, **kwargs)

A parsed quantum circuit

Initialize self. See help(type(self)) for accurate signature.

nodes property

nodes

(self) -> list[clifft._clifft_core.AstNode]

num_measurements property

num_measurements

(self) -> int

num_qubits property

num_qubits

(self) -> int

clifft.AstNode

AstNode(*args, **kwargs)

A single circuit operation

Initialize self. See help(type(self)) for accurate signature.

arg property

arg

(self) -> float

args property

args

(self) -> list[float]

gate property

gate

(self) -> clifft._clifft_core.GateType

source_line property

source_line

(self) -> int

targets property

targets

(self) -> list[clifft._clifft_core.Target]

clifft.Target

Target(*args, **kwargs)

Encoded quantum target

Initialize self. See help(type(self)) for accurate signature.

has_pauli property

has_pauli

(self) -> bool

is_inverted property

is_inverted

(self) -> bool

is_rec property

is_rec

(self) -> bool

pauli property

pauli

(self) -> int

pauli_char property

pauli_char

(self) -> str

value property

value

(self) -> int

clifft.HirModule

HirModule(*args, **kwargs)

Heisenberg Intermediate Representation

Initialize self. See help(type(self)) for accurate signature.

num_detectors property

num_detectors

(self) -> int

num_exp_vals property

num_exp_vals

(self) -> int

num_measurements property

num_measurements

(self) -> int

num_observables property

num_observables

(self) -> int

num_ops property

num_ops

(self) -> int

num_qubits property

num_qubits

(self) -> int

num_t_gates property

num_t_gates

(self) -> int

source_map property

source_map

Source line mapping parallel to ops (list of list of uint32).

as_dict method descriptor

as_dict()

as_dict(self) -> dict

Return a JSON-friendly dictionary representation.

clifft.HeisenbergOp

HeisenbergOp(*args, **kwargs)

A single abstract operation in the Heisenberg IR

Initialize self. See help(type(self)) for accurate signature.

is_dagger property

is_dagger

(self) -> bool

is_hidden property

is_hidden

(self) -> bool

op_type property

op_type

(self) -> clifft._clifft_core.OpType

pauli_string property

pauli_string

(self) -> str

sign property

sign

(self) -> bool

as_dict method descriptor

as_dict()

as_dict(self) -> dict

Return a JSON-friendly dictionary representation.

clifft.Instruction

Instruction(*args, **kwargs)

A localized VM operation

Initialize self. See help(type(self)) for accurate signature.

axis_1 property

axis_1

(self) -> int

axis_2 property

axis_2

(self) -> int

flags property

flags

(self) -> int

opcode property

opcode

(self) -> clifft._clifft_core.Opcode

as_dict method descriptor

as_dict()

as_dict(self) -> dict

Return a JSON-friendly dictionary representation.

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

HirPassManager()

Runs a sequence of optimization passes over an HirModule.

init(self) -> None

add method descriptor

add()

add(self, pass: clifft._clifft_core.HirPass) -> None

Add an optimization pass. Passes run in the order added.

run method descriptor

run()

run(self, hir: clifft._clifft_core.HirModule) -> None

Run all passes on the HIR module in sequence.

clifft.BytecodePassManager

BytecodePassManager()

Runs a sequence of bytecode optimization passes over a Program.

init(self) -> None

add method descriptor

add()

add(self, pass: clifft._clifft_core.BytecodePass) -> None

Add a bytecode optimization pass. Passes run in the order added.

run method descriptor

run()

run(self, program: clifft._clifft_core.Program) -> None

Run all bytecode passes on the program in sequence.

clifft.default_hir_pass_manager

default_hir_pass_manager(*args, **kwargs)

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(*args, **kwargs)

default_bytecode_pass_manager() -> clifft._clifft_core.BytecodePassManager

Return a BytecodePassManager pre-loaded with the default passes.

HIR Passes

clifft.PeepholeFusionPass

PeepholeFusionPass()

Bases: clifft._clifft_core.HirPass

Symplectic peephole fusion: cancels and fuses T/T-dag gates on the same virtual Pauli axis.

init(self) -> None

cancellations property

cancellations

(self) -> int

fusions property

fusions

(self) -> int

clifft.StatevectorSqueezePass

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

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

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

NoiseBlockPass()

Bases: clifft._clifft_core.BytecodePass

Coalesces contiguous OP_NOISE instructions into OP_NOISE_BLOCK.

init(self) -> None

clifft.ExpandTPass

ExpandTPass()

Bases: clifft._clifft_core.BytecodePass

Fuses OP_EXPAND + OP_ARRAY_T into single OP_EXPAND_T instructions.

init(self) -> None

clifft.ExpandRotPass

ExpandRotPass()

Bases: clifft._clifft_core.BytecodePass

Fuses OP_EXPAND + OP_ARRAY_ROT into single OP_EXPAND_ROT instructions.

init(self) -> None

clifft.SwapMeasPass

SwapMeasPass()

Bases: clifft._clifft_core.BytecodePass

Fuses OP_ARRAY_SWAP + OP_MEAS_ACTIVE_INTERFERE into OP_SWAP_MEAS_INTERFERE.

init(self) -> None

clifft.MultiGatePass

MultiGatePass()

Bases: clifft._clifft_core.BytecodePass

Fuses sequences of same-type 2-qubit gates into multi-target ops.

init(self) -> None

clifft.SingleAxisFusionPass

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(*args, **kwargs)

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(*args, **kwargs)

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(*args, **kwargs)

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.version

version(*args, **kwargs)

version() -> str

Return the Clifft version string

clifft.compute_reference_syndrome

compute_reference_syndrome(*args, **kwargs)

compute_reference_syndrome(hir: clifft._clifft_core.HirModule) -> dict

Compute noiseless reference syndrome for an HirModule.

Returns a dict with 'detectors' and 'observables' lists.

Type Aliases

clifft.BasisBitstrings module-attribute

BasisBitstrings: TypeAlias = (
    str | Sequence[str] | NDArray[bool_] | NDArray[uint8]
)

clifft.MeasurementRecords module-attribute

MeasurementRecords: TypeAlias = (
    str | Sequence[str] | NDArray[bool_] | NDArray[uint8]
)