SMQ Quantum-LLM Engine & Circuit API
A single-file quantum circuit simulator built on Matrix Product States (MPS) with a Qiskit-style circuit builder, mid-circuit measurement and classical feed-forward, OpenQASM 2.0 import/export, and an autoregressive Neural Quantum State (NQS) Transformer that can be distilled from an MPS.
Because an MPS stores a state as a chain of small tensors instead of a dense 2^n vector, memory and time grow polynomially in the number of qubits for states with limited entanglement. That lets you simulate 64+ qubit circuits like GHZ states on a laptop. Highly entangled states still require a large bond dimension chi (see Limitations).
Features
| Area | What's supported |
|---|---|
| 1-qubit gates | I, X, Y, Z, H, S, SDG, T, TDG, SX, SXDG, RX, RY, RZ, P/U1, U2, U3 |
| 2-qubit gates | CX/CNOT, CY, CZ, CH, SWAP, ISWAP, CP, CRX, CRY, CRZ, RXX, RYY, RZZ |
| 3-qubit gates | CCX (Toffoli), CCZ, CSWAP (Fredkin), built from 1- and 2-qubit gates |
| Dynamic circuits | Mid-circuit measure with true wavefunction collapse, reset, barrier, and classical conditions via .c_if(cbit, val) |
| Observables | Pauli-string expectations, Pauli-sum Hamiltonians, inner product, fidelity, single-qubit reduced density matrix, per-bond entanglement entropy |
| Sampling | Exact chain-rule Born sampling from the MPS (no full statevector needed) |
| Interop | OpenQASM 2.0 export (to_qasm) and import (from_qasm) |
| NQS | Autoregressive Transformer wavefunction with exact sampling and MPS distillation |
Installation
Requires Python 3.10+ and:
pip install numpy torch
No other dependencies. Drop the file into your project and import from it.
Quick start
Build and run a circuit
from smq_quantum import QuantumCircuit, QuantumSimulator
# 64-qubit GHZ state
n = 64
qc = QuantumCircuit(n, name="ghz_64")
qc.h(0)
for q in range(n - 1):
qc.cx(q, q + 1)
qc.measure_all()
sim = QuantumSimulator(max_bond_dim=64)
res = sim.run(qc, shots=1000, observables=["Z0", "Z0 Z63"])
print(res.counts) # {'000...0': ~500, '111...1': ~500}
print(res.expectations) # {'Z0': ~0.0, 'Z0 Z63': 1.0}
print(res.register.memory_bytes, "bytes")
Gate methods are chainable, so qc.h(0).cx(0, 1).measure_all() works.
Mid-circuit measurement and feed-forward (teleportation)
qc = QuantumCircuit(3, 2, name="teleport")
qc.u3(1.2345, 0.6789, -0.5432, 0) # secret state on q0
qc.h(1).cx(1, 2) # Bell pair (q1, q2)
qc.cx(0, 1).h(0) # Bell-basis rotation
qc.measure(0, 0).measure(1, 1) # collapse into classical bits
qc.x(2).c_if(1, 1) # if c1 == 1: X on q2
qc.z(2).c_if(0, 1) # if c0 == 1: Z on q2
res = QuantumSimulator().run(qc, shots=16, seed=99)
rho_bob = res.register.reduced_density_matrix_1q(2)
.c_if(cbit, val) attaches to the most recently added operation. For ccx, ccz, and cswap, that means every gate in their decomposition, so the whole gate is conditioned.
Work with the MPS register directly
from smq_quantum import MPSQuantumRegister
reg = MPSQuantumRegister(n_qubits=10, max_bond_dim=32)
reg.apply_1q("H", 0)
reg.apply_2q("CNOT", 0, 1)
reg.apply_1q("RX", 3, 0.5) # params: float or tuple
reg.expectation_pauli_string("Z0 Z1") # indexed syntax
reg.expectation_pauli_string("ZZIIIIIIII") # dense syntax (length n)
reg.expectation_hamiltonian({"Z0 Z1": -1.0, "X0": -0.5})
reg.sample_bitstrings(num_shots=100, seed=1)
reg.bond_entropies # natural-log entropy per bond
OpenQASM 2.0
qasm_text = qc.to_qasm()
qc2 = QuantumCircuit.from_qasm(qasm_text)
Neural Quantum State distillation
from smq_quantum import AutoregressiveNQS
nqs = AutoregressiveNQS(n_qubits=12, d_model=48, n_heads=4, n_layers=2)
fid = nqs.distill_from_mps(reg12, steps=50, batch_size=64, lr=1.5e-2)
samples = nqs.sample_exact(batch_size=256) # (256, 12) tensor of 0/1
Command-line usage
# Run the built-in verification suite (default if no flags are given)
python smq_quantum.py --self-test
# Execute an OpenQASM 2.0 file and print JSON results
python smq_quantum.py --qasm circuit.qasm --shots 2048 --max-bond-dim 128
The JSON output includes counts, probabilities, expectations, the maximum bond dimension reached, per-bond entropies, memory use, and elapsed time.
API reference
QuantumCircuit(n_qubits, n_cbits=None, name="circuit")
n_cbits defaults to n_qubits.
- Gates:
id, h, x, y, z, s, sdg, t, tdg, sx, sxdg, rx, ry, rz, p, u2, u3, cx, cnot, cy, cz, ch, swap, iswap, cp, crx, cry, crz, rxx, ryy, rzz, ccx, toffoli, ccz, cswap - Non-unitary:
measure(q, cbit=None),measure_all(),reset(q),barrier(*qubits) - Control:
c_if(cbit, val) - Serialization:
to_qasm(),QuantumCircuit.from_qasm(src) - Angle arguments come first, as in Qiskit:
rx(theta, q),cp(theta, ctrl, targ).
QuantumSimulator(max_bond_dim=64, svd_cutoff=1e-12, device="cpu")
run(circuit, shots=1024, seed=42, observables=None) -> ExecutionResult
- Static circuits (gates plus terminal measurements): the MPS is evolved once, then all shots are sampled from it.
- Dynamic circuits (resets,
c_if, or gates after a measurement): the deterministic prefix is evolved once, then the remainder is re-executed from a clone for every shot. - Pass
shots=0to skip sampling and just evolve the state.
ExecutionResult
counts, probabilities, most_frequent(), expectations, register, elapsed_sec, to_dict().
MPSQuantumRegister(n_qubits, n_cbits=None, max_bond_dim=64, svd_cutoff=1e-12, device="cpu")
| Method / property | Description |
|---|---|
apply_1q(name, q, params=()) |
Apply a 1-qubit gate |
apply_2q(name, q_ctrl, q_targ, params=()) |
Apply a 2-qubit gate; non-adjacent qubits are handled with SWAP chains |
measure_qubit(q, cbit=None, rng=None, force_outcome=None) |
Z-basis projective measurement with collapse and renormalization |
reset_qubit(q) |
Measure, then flip to ` |
reset() |
Reinitialize the whole register to ` |
expectation_single(pauli, q) |
<P_q> |
expectation_pauli_string(s) |
<P...>; accepts "X0 Z3 Y5" or a dense "XIIZY" string |
expectation_hamiltonian({pauli: coeff}) |
Sum of weighted Pauli strings |
reduced_density_matrix_1q(q) |
Exact 2x2 reduced density matrix |
inner_product(other) / fidelity(other) |
`<self |
sample_bitstrings(num_shots, seed) |
Born-rule samples, sorted by frequency |
amplitude(bitstring) |
Single amplitude `<bitstring |
statevector() |
Dense vector (limited to 20 qubits) |
clone() |
Deep copy |
bond_dims, max_current_bond, memory_bytes |
Resource diagnostics |
bond_entropies, truncation_error_accum |
Entanglement and accuracy diagnostics |
gate_count_1q, gate_count_2q, measurement_count |
Counters |
AutoregressiveNQS(n_qubits, d_model=64, n_heads=4, n_layers=2)
A causal Transformer that outputs, for each qubit, conditional log-probabilities and phases given the preceding qubits.
forward_conditionals(spins)returns(log_probs, phases)log_psi(spins)returns complexlog psi(s)sample_exact(batch_size)draws exact autoregressive samplesdistill_from_mps(mps, steps, batch_size, lr)fits the network to an MPS and returns a fidelity estimate
How it works
- State representation. Each qubit holds a tensor of shape
(chi_left, 2, chi_right), stored ascomplex128. Memory isO(n * chi^2). - Gates. 1-qubit gates are a local contraction. 2-qubit gates contract two neighboring tensors, apply the 4x4 unitary, and split with an SVD, truncating to
max_bond_dimand discarding singular values belowsvd_cutoff(TEBD-style). Non-adjacent gates are routed with SWAPs and then un-swapped. - Measurement. The marginal probability comes from the reduced density matrix, an outcome is drawn, the other physical index is zeroed, and the tensor is renormalized.
- Observables. Pauli strings are evaluated by sweeping a transfer environment across the chain in
O(n * chi^3). - Sampling. Bitstrings are drawn qubit by qubit from exact conditional probabilities using precomputed right environments.
- 3-qubit gates.
CCX,CCZ, andCSWAPare expanded into 1- and 2-qubit gates at circuit-build time.
Limitations and accuracy notes
- Entanglement limits scale. MPS is exact only while the bond dimension needed stays within
max_bond_dim. Deep or highly entangling circuits (random circuits, for example) will truncate. Checkregister.truncation_error_accumandmax_current_bond, and raisemax_bond_dimif the discarded weight is not negligible. - Truncation is local. The MPS is not kept in canonical form, so truncations are not guaranteed to be globally optimal.
- Long-range gates are costly. Each non-adjacent 2-qubit gate adds a chain of SWAPs, each with its own SVD.
- Dynamic circuits cost one execution per shot, and
ExecutionResult.registerholds only the last shot's state. bond_entropiesare updated when a 2-qubit gate touches a bond. They are not refreshed by measurement or reset, and untouched bonds report 0.barrieris a no-op for simulation (it is kept for QASM round-tripping).- OpenQASM support is 2.0 only, with a single
qregand a singlecreg. Register names are ignored. Exported QASM can contain gate names missing from the standardqelib1.inc(e.g.iswap,ryy), which other tools may reject.ccx/ccz/cswapare exported as their decomposed gates, with anyc_ifcondition repeated on each. Conditions are written in a single-bit form,if(c[0]==1), which this module reads back but which is not valid standard OpenQASM 2.0 (the spec only allows comparing a whole register, e.g.if(c==1)), so other tools may reject conditional circuits. - Do not parse untrusted QASM.
from_qasmevaluates gate-parameter expressions with a restrictedeval, which is convenient forpi/4-style expressions but not a hardened parser. - NQS fidelity is a sample-based estimate.
distill_from_mpstrains on a small set of bitstrings sampled from the MPS and reports overlap over that set, not over the full2^nHilbert space. It is a training-fit indicator, not a rigorous state fidelity. For largen, treat it as a diagnostic. statevector()raises an error above 20 qubits.
Self-test suite
python smq_quantum.py --self-test runs five checks:
- 64-qubit GHZ: verifies
<Z0> = 0and<Z0 Z63> = 1, and reports memory use. - Quantum teleportation: mid-circuit collapse plus
c_if; Bob's reduced density matrix must match the prepared state to1e-12. - 3-qubit Grover search for
|101>: exercises theCCZ/Toffoli decomposition and expectsP(|101>)near the theoretical 78.1%. - OpenQASM round trip: export, re-import, execute, and verify the teleportation result.
- 12-qubit transverse-field Ising evolution: computes
<H>and runs NQS distillation.
Project layout
Everything lives in one file, organized into sections:
- Exact unitary gate library (
gate_1q,gate_2q) InstructionandQuantumCircuit(builder plus OpenQASM)MPSQuantumRegister(tensor-network backend)ExecutionResultandQuantumSimulator(execution engine)AutoregressiveNQS(Transformer wavefunction)- Self-test suite and CLI
License
Apache 2.0