Optimization Passes¶
Clifft's public optimization passes operate on the Heisenberg IR before active-coordinate planning and executable-plan preparation.
Default Pipeline¶
The default HIR pipeline:
-
PeepholeFusionPass -- Fuse same-axis T gates and remove terminal phases.
-
PhasePolynomialPass -- Reduce T count using identities among commuting rotations.
-
RotationSimplificationPass -- Simplify arbitrary-angle Pauli rotations using known stabilizers.
-
StatevectorSqueezePass -- Minimizes peak active width by reordering HIR operations.
These passes are complementary; the default manager runs them in the order shown.
Use clifft.default_hir_pass_manager() to get these defaults. To customize a pass configuration while retaining the rest of the pipeline:
import clifft
phase = clifft.PhasePolynomialPass(max_variables=64)
pm = clifft.default_hir_pass_manager(overrides=[phase])
program = clifft.compile("H 0\nT 0\nM 0", hir_passes=pm)
Each override replaces the corresponding pass in its original position, regardless of the order of overrides. The manager retains the supplied instances, so pass statistics such as phase.output_t_count remain accessible. Duplicate pass types and passes outside the default pipeline raise ValueError.
For other pass choices or ordering, build a custom pipeline:
import clifft
pm = clifft.HirPassManager()
pm.add(clifft.PeepholeFusionPass())
pm.add(clifft.PhasePolynomialPass())
pm.add(clifft.RotationSimplificationPass())
pm.add(clifft.StatevectorSqueezePass())
pm.add(clifft.ActiveWidthSchedulePass())
Supply the manager as hir_passes=pm to clifft.compile() to replace the defaults. Omit any pass you want to disable, or use hir_passes=None to skip all HIR optimization.
Optimization passes end at the HIR boundary; SamplingPlan is not a second public pass pipeline. See Software Architecture for the private planning and executable-preparation stages that follow.
Trajectory Safety Metadata¶
Some workflows require measurements to remain in their original order, including hidden measurements introduced by the compiler. In particular, clifft.noncomp.sample may force the result of a hidden trace-out measurement when it resumes a trapped transition. Moving another measurement across that collapse can change quantum correlations.
The noncomputational trajectory driver uses only passes that are enabled by default and preserve both measurement-record order and instrument prefixes. Its HIR pipeline uses PeepholeFusionPass but omits PhasePolynomialPass, RotationSimplificationPass, StatevectorSqueezePass and ActiveWidthSchedulePass.
Record-order preservation is necessary but does not by itself make a continuation compatible with an already-running executor. Trajectory passes must also opt in to instrument-prefix stability: changing the circuit after an instrument may not change optimized output through that instrument. The runtime checks each recompiled prefix before resuming. For this reason, the noncomputational trajectory driver uses a fixed internal pipeline and does not currently accept custom pass managers. See Leakage and Loss for how continuations are compiled and resumed.
Constraints from Measurement and Feedback¶
PhasePolynomialPass and RotationSimplificationPass recover fixed-sign stabilizer constraints through measurement and feedback, including after earlier non-Clifford work. Constraints in SymbolicStabilizers must hold for every trajectory and the noiseless reference; PhasePolynomialPass can additionally recover region-entry constraints from postselected single-record detectors without readout noise when their measurements commute back to the region entry. See Optimization for Simulation for the analysis and reduction principles.
These are static rewrites shared by all shots. Unresolved affine signs do not produce conditional rewrites or per-history specialization. To disable recovered constraint rewrites, omit both passes from a custom HirPassManager, or use hir_passes=None to disable all HIR optimization. Equivalent plans preserve output distributions but do not guarantee historical fixed-seed samples.
HIR Passes¶
PeepholeFusionPass¶
| Kind | HIR (pre-lowering) |
| Default | ✅ Enabled |
| Preserves measurement-record order | Yes |
| Preserves instrument prefix | Yes |
| Python | clifft.PeepholeFusionPass() |
Scans the HIR to cancel or fuse T/T_dag gates acting on the same virtual Pauli axis using the symplectic inner product as a commutation check. T+T fuses to S, T+T_dag cancels to identity. Phase rotations within an absolute tolerance of 1e-12 half-turns of supported Clifford or T angles are canonicalized. It also removes a T gate or Pauli phase rotation when a later same-axis measurement consumes the phase; intervening Pauli noise is left in place.
PhasePolynomialPass¶
| Kind | HIR (pre-lowering) |
| Default | ✅ Enabled |
| Preserves measurement-record order | Yes |
| Preserves instrument prefix | No |
| Python | clifft.PhasePolynomialPass() |
Uses TOHPE from Vandaele, Lower T-count with faster algorithms, Algorithm 2 for T-count reduction. Clifft tracks commuting T rotations as a Boolean phase polynomial and uses Pauli constraints from the all-zero input to separate a non-Clifford core from a Clifford correction. TOHPE synthesizes the core; Clifft supplies the state analysis, measurement/noise handling, and exact Clifford correction.
Pauli measurements, expectation-value probes and classically controlled Pauli gates can move before a phase prefix only when their conjugated axes remain Paulis and all required constraints survive. Pauli noise can cross only when its nonzero-probability channels commute with that prefix and preserve those constraints. Forward constraints must hold on every trajectory and the noiseless reference, so even probability-one noise discards affected constraints; postselected noiseless measurements additionally supply forward and commuting lookahead constraints on surviving trajectories (stopping before probes affected by the prefix). Instruments clear all constraints. Use this pass only on complete circuits with an all-zero input; prior scheduling across noise causes it to skip the circuit.
max_variables is a hard ceiling on independent phase variables analyzed together (default 128, range 0 to 128; zero disables the pass). Circuits can have more physical qubits than this limit. Collection starts at min(32, max_variables), then tries a complete region up to min(64, max_variables). max_variables=32 disables expansion, and max_variables=64 restricts collection to one-word regions.
When max_variables > 64 and the 64-variable attempt is capped, the pass can try a complete contiguous commuting T region up to max_variables using two-word coordinates. This path keeps an ordinary-basis candidate and tries one basis derived from the final Clifford tableau. It crosses no measurement, feedback, noise, or instrument boundaries. Synthesis still supports at most 64 core variables and searches at most 128 odd parity terms. A signature-rank precheck rejects unsupported cores before cubic polynomial expansion.
max_wide_work (default 50000000) bounds deterministic work units shared by all wide attempts and both basis candidates in one pass. The units include polynomial updates, charged row operations, and an allowance for synthesis. Work units are not a wall-clock limit; their cost depends on the polynomial. max_wide_terms (default 200000) bounds each polynomial's size. Setting either to zero (or setting max_variables <= 64) disables the two-word path. Exhaustion retains a completed valid candidate or falls back to the ordinary smaller-region policy. These limits control compiler effort and do not change the execution representation.
Larger complete regions can uncover additional reductions, at extra compilation cost. The pass rejects rewrites that increase T count or peak active width; at unchanged width, estimated sampling work must not increase either. Actual sampling speedups depend on the complete optimization pipeline. Equivalent rewrites preserve sampling distributions but can change samples for a fixed random seed.
After a run, input_t_count, output_t_count, blocks_reduced and pauli_pullbacks describe the accepted rewrite; applied reports acceptance. wide_attempts, wide_rewrites, wide_work, and wide_budget_exhausted report the optional search, including rejected candidates; wide_rewrites counts only accepted rewrites. All counters reset on each run.
RotationSimplificationPass¶
| Kind | HIR (pre-lowering) |
| Default | ✅ Enabled |
| Preserves measurement-record order | Yes |
| Preserves instrument prefix | No |
| Python | clifft.RotationSimplificationPass() |
Uses the circuit's known all-zero initial state to track stabilizer constraints shared by every trajectory. These constraints let the pass combine equivalent commuting Pauli rotations with arbitrary angles and absorb resulting Clifford operations.
Run this pass on complete circuits before squeezing or scheduling. It skips circuits whose noise has already been rescheduled.
Stabilizer constraints must hold for every measurement outcome and noise trajectory, including the noiseless reference. Every nonrotation operation ends a region; instruments discard the known stabilizers and postselection adds none.
| Option | Default | Meaning |
|---|---|---|
max_region_ops | 256 | Maximum rotations retained in a region; range 0 to 4096. Zero disables the pass. |
max_region_passes | 8 | Maximum local retries without adding new rotations; range 1 to 64. |
Rewrites must not increase peak active width or estimated sampling work. Equivalent rewrites preserve output distributions but can change samples for a fixed seed.
After a run, regions_examined and regions_capped describe the attempted search. regions_reduced, rotations_removed and applied describe the accepted rewrite.
StatevectorSqueezePass¶
| Kind | HIR (pre-lowering) |
| Default | ✅ Enabled |
| Preserves measurement-record order | No |
| Preserves instrument prefix | No |
| Python | clifft.StatevectorSqueezePass() |
Attempts to reduce peak_active_width by compacting qubit lifetimes. Sweep 1 (leftward) bubbles MEASURE ops as early as possible. Sweep 2 (rightward) bubbles T_GATE and PHASE_ROTATION ops as late as possible, bypassing other commuting expansions when that exposes a movable non-expanding operation. This prevents a blocked expansion from keeping a later movable expansion live across a measurement. Measurements reduce active width sooner, and non-Clifford expansions are deferred.
ActiveWidthSchedulePass¶
| Kind | HIR (pre-lowering) |
| Default | ❌ Disabled |
| Preserves measurement-record order | No |
| Preserves instrument prefix | No |
| Python | clifft.ActiveWidthSchedulePass() |
Searches legal reorderings of the HIR for one that lowers peak active width first and an estimated dense-work cost second. It accepts a new order when peak width falls, or when peak width is unchanged and estimated dense work falls; otherwise the HIR is left untouched. A deterministic work budget limits search executions, but does not bound classification probes or wall time. Opt in to reduce sampling work at extra compilation cost. Run it after PeepholeFusionPass and StatevectorSqueezePass: reordering across noise can prevent subsequent peephole fusion.
See Compiling Circuits for setup and guidance on when to enable this pass.
| Option | Default | Meaning |
|---|---|---|
beam_width | 8 | Positive number of partial schedules to retain. Larger beams explore more alternatives but do not guarantee better results. |
search_budget | 16.0 | Search executions per HIR operation before switching to greedy continuation. 0 requests greedy continuation after the initial sweep; None disables budget-driven narrowing. |
noise_transparent | True | Allow crossings of Pauli noise, with symbolic sign correction. |
sink_neutral_rotations | True | Delay width-neutral rotations where legal to reduce dense work and expose fusion opportunities. |
The search narrows to one retained candidate at half the execution budget. Ongoing sweeps and replays finish, so the thresholds can be exceeded. This budget does not bound classification probes or wall time: probe counts can grow quadratically on circuits with many independent rotations, and each probe's cost also depends on the qubit count. Budgets must be finite and nonnegative, or None.
After a run, incumbent_peak and result_peak report peak active width before and after scheduling. incumbent_dense_work and result_dense_work estimate work by summing \(2^w\) over operations touching the active array at width \(w\). The pass accepts a lower peak even if that work estimate rises; neither metric measures elapsed time or guarantees a globally optimal schedule.
applied reports whether the order changed. swept_ops counts search executions, including discarded candidates and replays; classification_probes counts checks for expanding operations. These counters exclude graph construction and final analysis. For per-operation widths, use clifft.active_width_trace.
RemoveNoisePass¶
| Kind | HIR (pre-lowering) |
| Default | ❌ Disabled |
| Preserves measurement-record order | No |
| Preserves instrument prefix | No |
| Python | clifft.RemoveNoisePass() |
Removes all stochastic noise and readout noise ops, and clears the noise_sites, readout_noise side-tables and source_map. Not included in the default pipeline. Used internally by compute_reference_syndrome() to produce a noiseless circuit copy for reference-shot extraction.
DropNonUnitaryPass¶
| Kind | HIR (pre-lowering) |
| Default | ❌ Disabled |
| Preserves measurement-record order | No |
| Preserves instrument prefix | No |
| Python | clifft.DropNonUnitaryPass() |
Removes MEASURE, CONDITIONAL_PAULI, NOISE, READOUT_NOISE, DETECTOR, OBSERVABLE, and EXP_VAL ops and clears the matching metadata. Not included in the default pipeline and not semantics-preserving; use only when intentionally querying a unitary-only circuit skeleton.