Qx.CalcFast (Qx - Quantum Computing Simulator v0.6.0)

View Source

Optimized quantum gate operations using direct statevector manipulation.

This module provides high-performance implementations that apply gates directly to statevectors without building full 2^n x 2^n gate matrices. All functions are compiled with Nx.Defn for GPU/CPU acceleration.

Performance

Compared to the original matrix-based approach:

  • Memory: O(2^n) instead of O(2^(2n))
  • Speed: 10-1000x faster depending on circuit size
  • GPU-friendly: All operations use Nx primitives that compile to XLA

Implementation Notes

These implementations follow the approach used by production quantum simulators like Qiskit-Aer and Cirq, manipulating statevector amplitudes directly rather than constructing and multiplying large matrices.

Summary

Functions

apply_cnot(state, control_qubit, target_qubit, num_qubits)

Applies a CNOT gate directly to a statevector.

CNOT flips the target qubit if and only if the control qubit is |1⟩.

Parameters

  • state - State vector (2^n dimensional complex tensor)
  • control_qubit - Index of control qubit
  • target_qubit - Index of target qubit
  • num_qubits - Total number of qubits in the system

Algorithm

For each basis state in the statevector:

  1. Check if control qubit is |1⟩
  2. If yes, swap amplitude with state that has target qubit flipped
  3. If no, leave amplitude unchanged

This is much faster than building a 2^n x 2^n CNOT matrix.

apply_cswap(state, control, target_a, target_b, num_qubits)

Applies a Toffoli (CCX) gate directly to a statevector.

Toffoli flips the target qubit if and only if both control qubits are |1⟩.

Parameters

  • state - State vector (2^n dimensional complex tensor)
  • control1 - Index of first control qubit
  • control2 - Index of second control qubit
  • target - Index of target qubit
  • num_qubits - Total number of qubits in the system

apply_single_qubit_gate(state, gate_matrix, target_qubit, num_qubits)

Applies a single-qubit gate directly to a statevector.

This function applies a 2x2 gate matrix to a specific qubit in an n-qubit system by manipulating the statevector amplitudes directly.

Parameters

  • state - State vector (2^n dimensional complex tensor)
  • gate_matrix - 2x2 gate matrix (from Qx.Gates)
  • target_qubit - Index of qubit to apply gate to (0-based)
  • num_qubits - Total number of qubits in the system

Algorithm

For a gate applied to qubit k in an n-qubit system:

  1. Iterate through statevector indices in pairs that differ only in qubit k
  2. Apply 2x2 gate matrix to each pair of amplitudes
  3. Update statevector in-place

This avoids building a 2^n x 2^n matrix, using only O(2^n) memory.

apply_single_qubit_gate_compiled(state, gate_matrix, target_qubit, num_qubits)

apply_toffoli(state, control1, control2, target, num_qubits)