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,
input_format: Literal["stim", "qasm2"] = "stim",
) -> Program
Compile a quantum circuit string to an executable sampling program.
Ordinary compilation runs parse -> trace -> [HIR optimize], then plans and prepares the result as a reusable sampling program.
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 text in the format selected by | 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 |
input_format | Literal['stim', 'qasm2'] |
| 'stim' |
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.parse_qasm2 ¶
parse_qasm2(text: str) -> clifft._clifft_core.Qasm2Import parse_qasm2(text: str, max_ops: int) -> clifft._clifft_core.Qasm2Import
Overloaded function.
parse_qasm2(text: str) -> clifft._clifft_core.Qasm2Import
Parse and lower a unitary OpenQASM 2 circuit.
parse_qasm2(text: str, max_ops: int) -> clifft._clifft_core.Qasm2Import
Parse and lower a unitary OpenQASM 2 circuit with an explicit AST node limit.
clifft.parse_qasm2_file ¶
parse_qasm2_file(path: str) -> clifft._clifft_core.Qasm2Import parse_qasm2_file(path: str, max_ops: int) -> clifft._clifft_core.Qasm2Import
Overloaded function.
parse_qasm2_file(path: str) -> clifft._clifft_core.Qasm2Import
Parse and lower a unitary OpenQASM 2 circuit file.
parse_qasm2_file(path: str, max_ops: int) -> clifft._clifft_core.Qasm2Import
Parse and lower a unitary OpenQASM 2 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. Single-qubit rotations within 1e-12 half-turns of a Clifford angle are canonicalized.
clifft.lower ¶
lower(
hir: HirModule,
postselection_mask: Sequence[int] = [],
expected_detectors: Sequence[int] = [],
expected_observables: Sequence[int] = [],
) -> Program
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 an executable sampling program.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hir | HirModule | The Heisenberg IR module to lower. | required |
postselection_mask | Sequence[int] | 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 | Sequence[int] | Optional noiseless reference parities for detectors. | [] |
expected_observables | Sequence[int] | Optional noiseless reference parities for observables. | [] |
clifft.ParseError ¶
Bases: builtins.Exception
Sampling¶
The four fixed-plan functions share CPU batching and threading arguments. See CPU Execution and Tuning for their interaction and compatibility limits.
clifft.sample ¶
sample(
program: Program,
shots: int,
seed: int | None = None,
threads: int | Literal["auto"] = 1,
thread_layout: tuple[int, int] | None = None,
intra_shot_min_active_width: int | None = None,
batch_size: int | Literal["auto", "tune"] = "auto",
*,
tuning_budget_seconds: float | None = None,
) -> clifft.SampleResult
sample(program: Program, shots: int, seed: int | None = None, threads: int | typing.Literal['auto'] = 1, thread_layout: tuple[int, int] | None = None, intra_shot_min_active_width: int | None = None, batch_size: int | typing.Literal['auto', 'tune'] = 'auto', *, tuning_budget_seconds: float | None = None) -> clifft.SampleResult
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. threads is a positive total worker budget or 'auto' to use the implementation-reported hardware concurrency; it defaults to 1. Automatic scheduling uses either cross-shot or intra-shot workers. thread_layout=(shot_workers, intra_shot_workers) overrides that choice and ignores threads; intra-shot counts above 1 require OpenMP support. intra_shot_min_active_width overrides the default threshold of 18 for an explicit layout. batch_size='auto' uses the conservative plan policy; 1 forces scalar execution, and a positive integer requests a packed lane-capacity limit. Seeded results replay within one batching configuration, but individual rows may differ between scalar and packed modes or different capacities.
batch_size='tune' calibrates before running all requested shots. tuning_budget_seconds is a soft calibration deadline, defaulting to 0.25 seconds. Trials are extra work and are excluded from returned rows and counts. The selected configuration and timings are in result.batch_tuning. Timing-based selection need not replay for a fixed seed; pin a numeric batch_size for debugging.
Returns a SampleResult with .measurements, .detectors, .observables attributes. Supports tuple unpacking: m, d, o = clifft.sample(prog, shots)
clifft.sample_survivors ¶
sample_survivors(
program: Program,
shots: int,
seed: int | None = None,
keep_records: bool = False,
threads: int | Literal["auto"] = 1,
thread_layout: tuple[int, int] | None = None,
intra_shot_min_active_width: int | None = None,
batch_size: int | Literal["auto", "tune"] = "auto",
*,
tuning_budget_seconds: float | None = None,
) -> clifft.SampleResult
sample_survivors(program: Program, shots: int, seed: int | None = None, keep_records: bool = False, threads: int | typing.Literal['auto'] = 1, thread_layout: tuple[int, int] | None = None, intra_shot_min_active_width: int | None = None, batch_size: int | typing.Literal['auto', 'tune'] = 'auto', *, tuning_budget_seconds: float | None = None) -> clifft.SampleResult
Sample shots and return results only for surviving (non-discarded) shots.
If seed is None (default), uses hardware entropy. threads is a positive total worker budget or 'auto' to use the implementation-reported hardware concurrency; it defaults to 1. thread_layout=(shot_workers, intra_shot_workers) overrides automatic scheduling. intra_shot_min_active_width overrides the default threshold of 18 for an explicit layout. batch_size='auto' uses the conservative plan policy and remains scalar when the program has postselection; 1 forces scalar execution, and a positive integer requests a packed lane-capacity limit.
batch_size='tune' calibrates before running all requested shots. tuning_budget_seconds is a soft calibration deadline, defaulting to 0.25 seconds. Trials are extra work and are excluded from returned rows and counts. The selected configuration and timings are in result.batch_tuning. Timing-based selection need not replay for a fixed seed; pin a numeric batch_size for debugging.
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: Program,
shots: int,
k: int,
seed: int | None = None,
threads: int | Literal["auto"] = 1,
thread_layout: tuple[int, int] | None = None,
intra_shot_min_active_width: int | None = None,
batch_size: int | Literal["auto", "tune"] = "auto",
*,
tuning_budget_seconds: float | None = None,
) -> clifft.SampleResult
sample_k(program: Program, shots: int, k: int, seed: int | None = None, threads: int | typing.Literal['auto'] = 1, thread_layout: tuple[int, int] | None = None, intra_shot_min_active_width: int | None = None, batch_size: int | typing.Literal['auto', 'tune'] = 'auto', *, tuning_budget_seconds: float | None = None) -> clifft.SampleResult
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. threads is a positive total worker budget or 'auto' to use the implementation-reported hardware concurrency; it defaults to 1. thread_layout=(shot_workers, intra_shot_workers) overrides automatic scheduling. intra_shot_min_active_width overrides the default threshold of 18 for an explicit layout. batch_size='auto' uses the conservative plan policy; 1 forces scalar execution, and a positive integer requests a packed lane-capacity limit.
batch_size='tune' calibrates before running all requested shots. tuning_budget_seconds is a soft calibration deadline, defaulting to 0.25 seconds. Trials are extra work and are excluded from returned rows and counts. The selected configuration and timings are in result.batch_tuning. Timing-based selection need not replay for a fixed seed; pin a numeric batch_size for debugging.
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: Program,
shots: int,
k: int,
seed: int | None = None,
keep_records: bool = False,
threads: int | Literal["auto"] = 1,
thread_layout: tuple[int, int] | None = None,
intra_shot_min_active_width: int | None = None,
batch_size: int | Literal["auto", "tune"] = "auto",
*,
tuning_budget_seconds: float | None = None,
) -> clifft.SampleResult
sample_k_survivors(program: Program, shots: int, k: int, seed: int | None = None, keep_records: bool = False, threads: int | typing.Literal['auto'] = 1, thread_layout: tuple[int, int] | None = None, intra_shot_min_active_width: int | None = None, batch_size: int | typing.Literal['auto', 'tune'] = 'auto', *, tuning_budget_seconds: float | None = None) -> clifft.SampleResult
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. threads is a positive total worker budget or 'auto' to use the implementation-reported hardware concurrency; it defaults to 1. thread_layout=(shot_workers, intra_shot_workers) overrides automatic scheduling. intra_shot_min_active_width overrides the default threshold of 18 for an explicit layout. batch_size='auto' uses the conservative plan policy and remains scalar when the program has postselection; 1 forces scalar execution, and a positive integer requests a packed lane-capacity limit.
batch_size='tune' calibrates before running all requested shots. tuning_budget_seconds is a soft calibration deadline, defaulting to 0.25 seconds. Trials are extra work and are excluded from returned rows and counts. The selected configuration and timings are in result.batch_tuning. Timing-based selection need not replay for a fixed seed; pin a numeric batch_size for debugging.
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).
Optional Sinter Integration¶
Install clifft[sinter] for this optional integration with Stim/Sinter 1.16. See Using with Sinter for a runnable collection example.
clifft.sinter.PerfectionistSampler dataclass ¶
Bases: Sampler
Count logical errors after rejecting every shot with a detection event.
An absent postselection mask selects every detector. An explicit mask must be a little-endian packed uint8 NumPy array selecting every detector, with one byte per eight detectors, rounded up. Padding bits are ignored; with no detectors, an absent or empty mask is accepted.
Detector and observable bits are normalized against the noiseless reference. On surviving shots, any observable flip counts as one error, using zero observable prediction. Observable postselection and arbitrary decoders are unsupported. Leave Sinter's count_detection_events and count_observable_error_combos options false; Sinter rejects these options for custom samplers.
Tasks must contain a resolved stim.Circuit using instructions supported by Clifft. Heralded noise, sweep-bit controls, and Pauli targets in OBSERVABLE_INCLUDE are unsupported. Stim tags are ignored when compiling without modifying the task's circuit. A supplied detector error model participates in Sinter's task identity but is not used to predict corrections.
Register an instance in sinter.collect(custom_decoders=...). Its configuration is pickle-safe; each worker compiles its own Clifft program and uses one native thread. Sampling returns aggregate counts without materializing survivor rows. Each call uses fresh native randomness; this adapter does not expose a seed or a retained random stream. Direct sample(0) calls return zero counts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
batch_size | int | Literal['auto'] | Native lane capacity, defaulting to 1024. Each call uses at most the requested number of shots and 2048 lanes; larger capacities are capped, not rejected. This is separate from Sinter's | 1024 |
compiled_sampler_for_task ¶
Validate an all-detector task and compile its normalized circuit.
Source code in .venv/lib/python3.12/site-packages/clifft/sinter.py
Experimental Hardware Backends¶
Experimental
These APIs require backend-specific source builds and may change without compatibility guarantees. They are not selected by the regular CPU API.
See HIP Backend and CUDA Backend for the current hardware and workflow limits.
clifft.experimental.hip.is_built ¶
clifft.experimental.hip.is_available ¶
clifft.experimental.hip.backend_info ¶
Describe the optional extension and any devices visible to HIP.
Source code in .venv/lib/python3.12/site-packages/clifft/experimental/hip.py
clifft.experimental.hip.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,
) -> Program
Compile Stim text through the shared HIR and SamplingPlan pipeline.
Source code in .venv/lib/python3.12/site-packages/clifft/experimental/hip.py
clifft.experimental.hip.Program ¶
An immutable, backend-private lowering of a SamplingPlan.
Source code in .venv/lib/python3.12/site-packages/clifft/experimental/hip.py
num_records property ¶
Return the visible plus hidden record width required by replay.
clifft.experimental.hip.Sampler ¶
Sampler(
program: Program,
*,
precision: Precision = "fp64",
max_batch_shots: int | None = None,
tier: Tier = "auto",
)
A synchronous sampler with one uploaded program and retained workspace.
Calls on one instance must not overlap. Use a separate sampler per caller.
Source code in .venv/lib/python3.12/site-packages/clifft/experimental/hip.py
replay_shot ¶
Force every record value to probe one measurement branch exactly.
Source code in .venv/lib/python3.12/site-packages/clifft/experimental/hip.py
sample ¶
Sample fixed rows while reusing the retained device workspace.
Source code in .venv/lib/python3.12/site-packages/clifft/experimental/hip.py
sample_survivors ¶
sample_survivors(
shots: int,
*,
keep_records: bool = False,
seed: int | None = None,
block_size: int | None = None,
) -> SampleResult
Sample and retain only shots that pass postselection.
Source code in .venv/lib/python3.12/site-packages/clifft/experimental/hip.py
clifft.experimental.hip.ReplayResult dataclass ¶
Result of one forced-record path through the HIP interpreter.
clifft.experimental.cuda.is_built ¶
clifft.experimental.cuda.is_available ¶
Return whether the extension loaded and can see an NVIDIA GPU.
clifft.experimental.cuda.backend_info ¶
Describe the optional extension and any devices visible to CUDA.
Source code in .venv/lib/python3.12/site-packages/clifft/experimental/cuda.py
clifft.experimental.cuda.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,
) -> Program
Compile Stim text through the shared HIR and SamplingPlan pipeline.
Source code in .venv/lib/python3.12/site-packages/clifft/experimental/cuda.py
clifft.experimental.cuda.selected_tier ¶
Report the execution tier automatic selection picks on the current device.
Source code in .venv/lib/python3.12/site-packages/clifft/experimental/cuda.py
clifft.experimental.cuda.Program ¶
An immutable, backend-private lowering of a SamplingPlan.
Source code in .venv/lib/python3.12/site-packages/clifft/experimental/cuda.py
num_records property ¶
Return the visible plus hidden record width required by replay.
clifft.experimental.cuda.Sampler ¶
Sampler(
program: Program,
*,
precision: Precision = "fp64",
max_batch_shots: int | None = None,
tier: Tier = "auto",
max_concurrent_shots: int = 0,
)
A synchronous sampler with one uploaded program and retained workspace.
Calls on one instance must not overlap. Use a separate sampler per caller.
Source code in .venv/lib/python3.12/site-packages/clifft/experimental/cuda.py
max_concurrent_shots property ¶
Return how many shots the cooperative tiers keep resident per launch.
replay_shot ¶
Force every record value to probe one measurement branch exactly.
Source code in .venv/lib/python3.12/site-packages/clifft/experimental/cuda.py
sample ¶
Sample fixed rows while reusing the retained device workspace.
Source code in .venv/lib/python3.12/site-packages/clifft/experimental/cuda.py
sample_survivors ¶
sample_survivors(
shots: int,
*,
keep_records: bool = False,
seed: int | None = None,
block_size: int | None = None,
) -> SampleResult
Sample and retain only shots that pass postselection.
Source code in .venv/lib/python3.12/site-packages/clifft/experimental/cuda.py
clifft.experimental.cuda.ReplayResult dataclass ¶
Result of one forced-record path through the CUDA interpreter.
Leakage and Loss¶
Sampling under a five-level leakage/loss model. See the Leakage and Loss guide and Partner Interactions for model defaults, directional overrides, and circuit annotation ordering.
clifft.noncomp.sample ¶
sample(
circuit: Circuit | str,
model: Model,
shots: int,
seed: int | None = None,
max_active_width: int | None = None,
threads: int | Literal["auto"] = 1,
) -> NonComputationalSample
Sample circuit under model for shots shots.
On a leaked or lost site, M, MX, MY, MR, MRX, and MRY sample the classifier without regard to measurement basis. A model that can leak or lose sites requires a classifier when the circuit measures a physical site. Parity measurements (MPP) and EXP_VAL probes are not supported with such models.
HERALD_LEAKAGE_EVENT and HERALD_LOSS_EVENT append nondestructive status checks to the ordinary measurement record. They take no arguments; use READOUT_NOISE to model probe errors. They require no classifier and leave their entries in the classifier heralds sidecar zero.
LEAKAGE_INTERACTION and LOSS_INTERACTION apply conditional partner effects without adding records. Model-generated interactions precede the gate's level-transition hooks. Explicit annotations evaluate status at their own expanded position and compose with generated effects.
Continuations are compiled with the default optimization passes that preserve measurement-record order and instrument-prefix stability, omitting StatevectorSqueezePass. Reordering can change the placement of internal collapse outcomes relative to later records. This API does not currently accept custom pass managers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
circuit | Circuit | str | Parsed | required |
model | Model | Leakage and loss model. | required |
shots | int | Number of trajectories to sample. | required |
seed | int | None | Seed for reproducible sampling. The same seed and arguments produce identical results. When | None |
max_active_width | int | None | Optional cap on the peak active width of every compiled continuation. The check is conservative because a continuation may contain branches that the current shot will not take. | None |
threads | int | Literal['auto'] | Number of cross-shot workers. Defaults to 1. Pass | 1 |
Returns:
| Type | Description |
|---|---|
NonComputationalSample | |
NonComputationalSample | containing measurement, detector, observable, herald, and final-status |
NonComputationalSample | arrays. |
Raises:
| Type | Description |
|---|---|
ValueError | If a model or circuit contract is violated, an annotation is malformed, or a continuation exceeds |
Source code in .venv/lib/python3.12/site-packages/clifft/noncomp.py
clifft.noncomp.Model ¶
Model(
initial_state: Sequence[float] | None = None,
transitions: Mapping[str, Matrix] | None = None,
classifier: Classifier | None = None,
reset_restores_lost: bool = False,
damping: str = "exact",
*,
gate_partner_effects: Mapping[str, PartnerEffect]
| None = None,
interactions: Sequence[InteractionRule] | None = None,
)
A noncomputational trajectory model over the built-in five-level set.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
initial_state | Sequence[float] | None | probability per level, | None |
transitions | Mapping[str, Matrix] | None | maps a name to its | None |
classifier | Classifier | None | Optional Classifier supplying leaked/lost measurement outcomes and computational readout confusion. | None |
reset_restores_lost | bool | if true, a reset on a lost qubit restores it to a computational state; if false (default), the reset acts on the vacated site and is dropped. | False |
damping | str | handling of the no-transition update when the total transition probability differs between | 'exact' |
gate_partner_effects | Mapping[str, PartnerEffect] | None | Defaults keyed by | None |
interactions | Sequence[InteractionRule] | None | Specific InteractionRule overrides. Each replaces the whole matching default. Generated interactions run after the gate and before its level-transition hooks. Explicit circuit annotations run at their own expanded position and compose with generated effects without overriding them. | None |
By default, an operation with no representable effect on a leaked or lost operand -- e.g. a two-qubit gate onto a vacated site -- is dropped, acting as the identity on the surviving operands. Configured partner interactions replace that identity with Pauli noise and optional leakage spreading. Single-qubit measurements (M, MX, MY) keep their record slot; once the qubit has left the computational subspace the readout basis is incidental and the classifier supplies the bit. A measure-and-reset (MR/MRX/MRY) keeps its record the same way; its reset half re-prepares the site only when the reset restores it (a leaked qubit always; a lost qubit only with reset_restores_lost). Parity measurements (MPP) are not supported when the model can leak or lose qubits -- they have no faithful single-bit classifier substitution -- and raise before sampling begins. A model that can leak or lose qubits also requires a classifier when the circuit measures a qubit.
Construction validates shapes, probabilities, gate keys, policy values, and level table consistency. Invalid values raise ValueError; effect and rule objects of the wrong type raise TypeError.
Source code in .venv/lib/python3.12/site-packages/clifft/noncomp.py
clifft.noncomp.PartnerEffect dataclass ¶
Noise on a computational partner of a leaked or lost operand.
pauli=(px, py, pz) specifies mutually exclusive X, Y, and Z errors; identity has probability 1 - px - py - pz. Full depolarization is (0.25, 0.25, 0.25). The optional leakage attempt happens after the Pauli channel, with source-preserving g -> leak_g and e -> leak_e semantics on the partner. Spreading is supported only for leaked sources. Both effects default to zero. Values are validated and copied on creation.
Source code in .venv/lib/python3.12/site-packages/clifft/noncomp.py
clifft.noncomp.InteractionRule dataclass ¶
InteractionRule(
*,
gate: str,
source_operand: int,
source_status: Literal["leaked", "lost"],
effect: PartnerEffect,
)
Replace a gate's default effect for one source status and direction.
source_operand is 0 for the first operand in each ordered gate pair, or 1 for the second. source_status is "leaked" (either leaked level) or "lost". The other operand must be computational. The entire effect replaces the matching default; PartnerEffect() disables it. Model validates gate support and rejects duplicate canonical rules, including aliases such as CX and CNOT. Rules do not affect virtual feedback.
clifft.noncomp.Classifier ¶
A measurement classifier: P[symbol][level] stochastic matrix.
The matrix must have two or three rows, and every level column must sum to one. The first two rows give the probabilities of recording 0 or 1. An optional third row heralds the measurement, typically for loss. NonComputationalSample.heralds reports that symbol separately while the binary measurement record receives a uniformly sampled placeholder.
For M and MR on a computational site, the g and e columns can model Z-basis readout confusion after the quantum measurement. Computational MX, MY, MRX, and MRY measurements do not use those columns. On a leaked or lost site, every supported single-site measurement uses the corresponding classifier column regardless of basis. A computational column may not assign probability to the herald symbol.
Source code in .venv/lib/python3.12/site-packages/clifft/noncomp.py
clifft.noncomp.NonComputationalSample ¶
NonComputationalSample(
measurements: NDArray[uint8],
detectors: NDArray[uint8],
observables: NDArray[uint8],
final_status: NDArray[uint8],
heralds: NDArray[uint8],
num_qubits: int,
num_measurements: int,
num_detectors: int,
num_observables: int,
)
Measurement results and final site statuses returned by sample().
Attributes:
| Name | Type | Description |
|---|---|---|
measurements, | (detectors, observables) | uint8 arrays, shape (shots, width). |
final_status | uint8 array (shots, num_qubits) of QubitStatus values. Reports the definite noncomputational level per site and shot: | |
heralds | uint8 array (shots, num_measurements); 1 where the classifier sampled the herald (third) symbol for that slot, else 0. | |
shots, | (num_qubits, num_measurements, num_detectors, num_observables) | ints. |
Source code in .venv/lib/python3.12/site-packages/clifft/noncomp.py
symbols ¶
Return measurement symbols, using 2 for heralded slots.
This returns a copy of measurements with each heralded placeholder replaced by 2.
Source code in .venv/lib/python3.12/site-packages/clifft/noncomp.py
clifft.noncomp.Level ¶
Bases: IntEnum
Indices of the built-in five-level model, for naming matrix rows/columns.
clifft.noncomp.QubitStatus ¶
Bases: IntEnum
Per-site status stored in NonComputationalSample.final_status.
These are per-site status codes, not matrix indices. Level names matrix rows and columns (indices 0--4); QubitStatus names per-qubit outcomes (codes 0--3). The two enums share member names (LEAK_G, LEAK_E, LOST) with different integer values -- never substitute one for the other.
LEAK_G and LEAK_E are individually distinguishable in final_status, unlike the coarse leaked/lost grouping some tools use.
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.get_statevector ¶
get_statevector(program: clifft._clifft_core.Program) -> numpy.ndarray[dtype=complex128, order='C']
Return a dense representative of a compiled pure-unitary program's final state.
The result is normalized and defined only up to global phase. Relative amplitudes and phases are preserved, but the global phase may vary across equivalent source circuits, compiler pass configurations, or Clifft versions.
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,
batch_tuning: BatchTuningReport | 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) batch_tuning: calibration report when batch_size="tune", otherwise None
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
clifft.BatchTuningReport ¶
Calibration outcome and reusable batch size. sufficient_measurements says whether the automatic choice and an alternative were compared; stop_reason records why calibration ended, including budget exhaustion even when falling back to auto.
trials property ¶
(self) -> list[clifft._clifft_core.BatchTuningTrial]
clifft.BatchTuningTrial ¶
Timing for one batch-size candidate. The first probe is recorded as warmup; its throughput is used when no subsequent measurement is available.
shots_per_second property ¶
Attempted-shot throughput used for selection, or zero without timing data.
Compiled Programs¶
clifft.Program ¶
A reusable compiled sampling program
noise_site_probabilities property ¶
Per-site total fault probabilities: quantum noise sites followed by readout noise.
peak_active_width property ¶
Largest active width reached by the compiled program.
inspect method descriptor ¶
inspect(self) -> str
Deterministic human-readable diagnostic text for the whole lowered CPU program.
The format is diagnostic output for debugging and tooling, not a stable machine-readable interface.
inspect_action method descriptor ¶
inspect_action(self, action: int) -> str
Deterministic human-readable diagnostic text for a single action in the lowered CPU program.
The format is diagnostic output for debugging and tooling, not a stable machine-readable interface.
Circuit and IR Inspection¶
clifft.Circuit ¶
clifft.Qasm2Import ¶
A natively parsed unitary OpenQASM 2 circuit and its source phase correction
clifft.AstNode ¶
A single circuit operation
clifft.Target ¶
Encoded quantum target
clifft.HirModule ¶
clifft.HeisenbergOp ¶
A single abstract operation in the Heisenberg IR
as_dict method descriptor ¶
as_dict(self) -> dict
Return a JSON-friendly dictionary representation.
clifft.OpType ¶
Bases: enum.Enum
Heisenberg IR operation types
clifft.GateType ¶
Bases: enum.Enum
Quantum gate types
Pass Managers¶
clifft.HirPass ¶
Abstract base class for HIR optimization passes.
clifft.HirPassManager ¶
Runs a sequence of optimization passes over an HirModule.
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.
HIR Passes¶
clifft.PeepholeFusionPass ¶
Bases: clifft._clifft_core.HirPass
Symplectic peephole optimization: cancels and fuses T/T-dag gates, canonicalizes rotations within 1e-12 half-turns, and removes terminal phases consumed by same-axis measurements.
init(self) -> None
clifft.PhasePolynomialPass ¶
Bases: clifft._clifft_core.HirPass
Reduce commuting T rotations using constraints from the circuit's |0> input. Run after peephole fusion and before squeezing or scheduling.
init(self, max_variables: int = 32) -> None
clifft.RotationSimplificationPass ¶
Bases: clifft._clifft_core.HirPass
Simplify Pauli rotations using outcome-independent stabilizer constraints. Run after PhasePolynomialPass and before squeezing or scheduling.
init(self, max_region_ops: int = 256, max_region_passes: int = 8) -> None
clifft.StatevectorSqueezePass ¶
Bases: clifft._clifft_core.HirPass
Bidirectional bubble sort: moves measurements leftward and non-Clifford gates rightward to minimize peak active width.
init(self) -> None
clifft.active_width_trace ¶
active_width_trace(hir: clifft._clifft_core.HirModule) -> dict
Structural active-width trace of an HIR module, without lowering it to an executable program.
Returns a dict with 'initial', 'peak', and 'final' width, plus per-op 'widths' (the width after each op) and 'effects' (a lower-case effect name per op).
clifft.ActiveWidthSchedulePass ¶
ActiveWidthSchedulePass(
noise_transparent: bool = True,
beam_width: int = 8,
search_budget: float | None = 16.0,
sink_neutral_rotations: bool = True,
)
Bases: clifft._clifft_core.HirPass
State-aware beam search over the schedule-dependence trace class that reduces peak active width, then a dense-work estimate. Opt in by adding it after PeepholeFusionPass and StatevectorSqueezePass.
init(self, noise_transparent: bool = True, beam_width: int = 8, search_budget: float | None = 16.0, sink_neutral_rotations: bool = True) -> 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
Utilities¶
clifft.runtime_isa ¶
runtime_isa() -> str
Return the resolved kernel ISA: 'scalar', 'neon', 'avx2', 'avx512', or a 'trap:...' value when CLIFFT_FORCE_ISA requests an unavailable backend
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.