Note

LLM Benchmarks are at the bottom.

SMQ Quantum Engine

An Attention-Native Quantum Simulator and Learned Quantum Circuit Model

SMQ is a quantum circuit execution framework built around an alternative representation of quantum computation: Matrix Product States expressed as causal linear attention.

Rather than storing a quantum register as an exponentially growing statevector, SMQ represents the register as a tensor network. Its attention mechanism performs the sequential contractions required to calculate quantum amplitudes, while its tensor bonds carry the correlations between qubits.

The project contains two complementary execution systems:

  • SMQ Quantum Transformer: An exact, tensor-network quantum simulator.
  • SMQ Quantum LLM: A trainable autoregressive model that learns quantum measurement distributions from the exact simulator.

Together, they explore two different approaches to quantum computation: directly evolving the mathematical state of a circuit and learning to predict its observable output.


1. The Core Architecture

Quantum Computation as Linear Attention

The central observation behind SMQ is that a Matrix Product State can be represented as a causal linear-attention computation.

Each qubit corresponds to a site in the tensor network.

The virtual bond connecting neighboring sites corresponds to the running key/value state of a linear-attention mechanism.

A measurement bitstring is evaluated through sequential attention readout:

[ h_{k+1}=h_k K_k[b_k] ]

where:

  • (h_k) is the running attention state.
  • (K_k) is the local tensor associated with qubit (k).
  • (b_k) is the selected computational-basis bit.

The resulting contraction recovers the corresponding quantum amplitude.

This makes the MPS bond dimension the effective attention-state dimension.

Tensor-Network Execution

SMQ evolves quantum states through local tensor contractions and singular value decompositions (SVD).

Instead of allocating (2^n) complex amplitudes for an (n)-qubit register, the simulator stores the tensor representation of the state.

The computational cost is consequently governed by the bond dimension (\chi), which reflects the entanglement structure of the circuit.

Many state-analysis operations scale as:

[ O(n\chi^3) ]

This allows circuits with very large numbers of qubits to remain tractable when their entanglement structure admits a compact representation.

The implementation uses complex128 arithmetic and configurable SVD truncation parameters.

Importantly, this is not a claim that arbitrary highly entangled quantum states become inexpensive. The bond dimension can grow substantially as circuit entanglement increases.


2. SMQ Quantum Transformer

The exact simulator is implemented in smq_transformer.py.

It provides a complete quantum circuit interface and an MPS-based execution backend.

Supported Quantum Operations

Single-qubit gates

  • I, X, Y, Z, H
  • S, SDG, T, TDG
  • SX, SXDG
  • RX, RY, RZ
  • P / U1, U2, U3

Two-qubit gates

  • CX / CNOT
  • CY, CZ, CH
  • SWAP, ISWAP
  • CP
  • CRX, CRY, CRZ
  • RXX, RYY, RZZ

Three-qubit operations

  • CCX (Toffoli)
  • CSWAP (Fredkin)
  • CCZ

Dynamic Quantum Circuits

SMQ also supports non-unitary and mid-circuit operations:

  • Projective measurement with wavefunction collapse.
  • Mid-circuit qubit reset.
  • Classical conditional execution through c_if.
  • Classical feed-forward.
  • Circuit barriers.

These operations allow dynamic algorithms such as quantum teleportation to be represented and executed.

State Analysis

The MPS register exposes:

  • Individual and batched quantum amplitudes.
  • Sequential attention-state readout.
  • Pauli-string expectation values.
  • Hamiltonian expectation values.
  • Inner products and state fidelity.
  • Single-qubit reduced density matrices.
  • Bipartite entanglement entropy.
  • Bond dimensions and bond entropies.
  • Register memory usage and truncation diagnostics.
  • Computational-basis sampling.

The full statevector can also be reconstructed for small systems. For larger systems, the native MPS operations avoid materializing the exponentially large statevector.

OpenQASM 2.0

The exact simulator supports OpenQASM 2.0 circuit import and export.

Circuits can also be executed directly from QASM files through the command-line interface.


3. SMQ Quantum LLM

Implemented in smq_llm.py, the second component is a trainable decoder-only Transformer designed to learn quantum circuit behavior.

It approaches quantum execution as a sequence-modeling problem.

Instead of directly evolving a quantum state, the model receives a serialized circuit and predicts its final computational-basis measurement distribution.

Circuit Representation

A circuit is serialized into a structured token stream:

BOS β†’ N β†’ GATES β†’ SEP β†’ MEASUREMENT BITS

The representation includes:

  • Qubit-count information.
  • Gate identities.
  • Qubit operands.
  • Continuous gate parameters.
  • Autoregressive measurement-bit targets.

Continuous gate angles use Fourier-feature embeddings rather than ordinary discrete angle bins.

This preserves the continuous nature and periodicity of rotational gates.

Teacher-Based Training

Training examples are generated using the exact SMQ Quantum Transformer.

The exact simulator supplies the reference Born distribution:

[ p_{\mathrm{exact}}(x)=|\langle x|\psi\rangle|^2 ]

The LLM learns a normalized autoregressive distribution:

[ q_\theta(x)= \prod_{k=0}^{n-1} q_\theta(x_k\mid x_{<k},C) ]

where (C) is the input circuit.

The training objective uses forward KL divergence:

[ D_{\mathrm{KL}}(p_{\mathrm{exact}}\Vert q_\theta) ]

The outcome model predicts one measurement bit at a time, with a normalized binary probability distribution at every step.

Training can use sampled teacher outcomes or exact weighted outcome evaluation for smaller circuits.

Training Infrastructure

The training implementation includes:

  • Rotary positional embeddings.
  • Causal self-attention.
  • CUDA acceleration.
  • BF16 autocasting when supported.
  • AdamW optimization.
  • Learning-rate warmup and cosine decay.
  • Gradient clipping.
  • Variable circuit sizes and depths.
  • Structured and randomized circuit generation.
  • Curriculum learning across qubit counts.
  • Validation using Total Variation Distance and fidelity.
  • Worst-performing circuit diagnostics.
  • Atomic checkpoint saving.
  • Full training resumption.

Checkpoints include best.pt, last.pt, and final.pt, alongside optional rotating epoch snapshots.

Learned Execution

The trained model exposes:

  • distribution() β€” obtain the predicted outcome distribution.
  • execute() β€” autoregressively sample measurement bitstrings.
  • execute_qasm() β€” execute a supported OpenQASM circuit.

The distribution interface enumerates outcomes and is limited by a configurable maximum qubit count (14 by default). Sampling through execute() does not require explicitly enumerating every possible outcome.

The LLM is an approximation, not an exact replacement for the tensor-network simulator. Its accuracy depends on its training corpus, model capacity, circuit structure, and the range of circuits encountered during training.


4. Graphical QASM Interface

smq_qasm_gui.py provides a desktop interface for running circuits through a trained Quantum LLM.

Features include:

  • OpenQASM 2.0 editor.
  • Circuit file loading.
  • Model checkpoint selection.
  • CPU and CUDA device selection.
  • Configurable measurement shots.
  • Temperature and random seed controls.
  • Predicted measurement distributions.
  • Optional comparison against the exact simulator.
  • Total Variation Distance reporting.
  • CSV export.

The GUI is built with Python's standard Tkinter interface.

The LLM QASM parser supports a subset of OpenQASM 2.0. Custom gate declarations, conditional QASM statements, reset, and opaque instructions are not supported by that parser.


5. Installation

Requirements:

  • Python 3.10+
  • PyTorch
  • NumPy
  • Tkinter (for the graphical interface)

Clone the repository:

git clone https://huggingface.co/CompressedGemma/QuantumLLM
cd QuantumLLM

Install dependencies:

pip install numpy torch

CUDA is optional. PyTorch uses CUDA when configured and available.


6. Quick Start: Exact Quantum Simulation

Run the built-in verification suite:

python smq_transformer.py --self-test

Execute an OpenQASM circuit:

python smq_transformer.py \
    --qasm circuit.qasm \
    --shots 4096 \
    --verbose

Inspect the QASM without executing it:

python smq_transformer.py \
    --qasm circuit.qasm \
    --parse-only

Python API

from smq_transformer import QuantumCircuit, QuantumSimulator

# Create a Bell-pair circuit
qc = QuantumCircuit(2, 2)

qc.h(0)
qc.cx(0, 1)
qc.measure_all()

# Execute
sim = QuantumSimulator(
    max_bond_dim=10000,
    svd_cutoff=1e-12
)

result = sim.run(
    qc,
    shots=1000,
    seed=42,
    observables=["Z0 Z1"]
)

print("Measurement counts:", result.counts)
print("Expectations:", result.expectations)
print("Maximum bond dimension:", result.register.max_current_bond)
print("Memory:", result.register.memory_bytes)

For direct state analysis, execute without sampling:

qc = QuantumCircuit(2, 2)
qc.h(0)
qc.cx(0, 1)

state = sim.run(qc, shots=0).register

print(state.amplitude("00"))
print(state.amplitude("11"))
print(state.entanglement_entropy(0))

7. Training the Quantum LLM

Generate a training corpus and train the autoregressive model:

python smq_llm.py train \
    --out-dir runs/experiment \
    --train-circuits 5000 \
    --val-circuits 300 \
    --epochs 40

Resume an interrupted training run:

python smq_llm.py train \
    --out-dir runs/experiment \
    --resume auto

Evaluate a checkpoint:

python smq_llm.py eval \
    --checkpoint runs/experiment/best.pt \
    --circuits 200

Run a demonstration:

python smq_llm.py demo \
    --checkpoint runs/experiment/best.pt \
    --qubits 6 \
    --gates 30

Execute a QASM file through the learned model:

python smq_llm.py qasm \
    --checkpoint runs/experiment/best.pt \
    --file circuit.qasm \
    --shots 4096 \
    --compare

The --compare option evaluates the predicted distribution against the exact simulator.


8. Running the GUI

Launch the graphical interface:

python smq_qasm_gui.py \
    --checkpoint runs/experiment/best.pt

A sample circuit is loaded automatically.

You can also supply a QASM file:

python smq_qasm_gui.py \
    --checkpoint runs/experiment/best.pt \
    --qasm circuit.qasm

9. Verification and Experiments

The exact simulator includes a built-in verification suite covering several independent aspects of quantum execution.

Test Verification
64-qubit GHZ Long-range entanglement and correlated sampling
Quantum teleportation Mid-circuit collapse and classical feed-forward
3-qubit Grover Amplitude amplification
OpenQASM 2.0 Circuit serialization and round-trip execution
12-qubit TFIM Hamiltonian expectation against dense Pauli algebra
Attention readout Amplitude, observable, density-matrix and entropy comparisons against a dense statevector
512-qubit circuit Exact low-bond-dimension attention/MPS evolution

The 512-qubit verification is particularly significant.

The test constructs a 512-qubit entangled state using a Hadamard, a phase gate, and a chain of controlled-NOT operations.

It verifies:

[ \langle X^{\otimes512}\rangle =\cos(\pi/4) ]

and

[ \langle Z^{\otimes512}\rangle=1 ]

while retaining a maximum bond dimension of only:

[ \chi=2 ]

The register represents a system with (2^{512}) possible computational-basis amplitudes without materializing the full statevector.

This demonstrates the advantage of an entanglement-adaptive representation for circuits whose states possess compact tensor-network structure.

Run the verification suite yourself:

python smq_transformer.py --self-test

10. Computational Considerations

SMQ is designed to make the structure of quantum states, rather than the raw number of computational-basis configurations, central to its resource requirements.

However, performance is circuit-dependent.

The exact simulator's practical memory and computational cost depend primarily on the MPS bond dimensions generated during execution.

Highly entangled circuits can require substantially larger bonds.

The following configuration parameters are exposed:

Parameter Default Purpose
max_bond_dim 10,000 Maximum allowed bond dimension
svd_cutoff 1e-12 SVD truncation threshold
device CPU Execution device
verbose False Execution diagnostics

The simulator reports bond dimensions, memory consumption, and accumulated truncation diagnostics so that computational behavior can be inspected rather than hidden.

For the LLM, prediction quality must be evaluated independently from the exact engine. Good performance on small circuits does not establish generalization to arbitrary larger circuits.


11. Project Structure

QuantumLLM/
β”‚
β”œβ”€β”€ smq_transformer.py
β”‚   └── Exact MPS / linear-attention quantum simulator
β”‚
β”œβ”€β”€ smq_llm.py
β”‚   └── Trainable autoregressive quantum circuit model
β”‚
β”œβ”€β”€ smq_qasm_gui.py
β”‚   └── Graphical OpenQASM execution interface
β”‚
└── README.md
    └── Documentation

License

Apache License 2.0.

Copyright belongs to the respective project contributors.

LLM Benchmark

--d-model 48 --heads 4 --layers 2 --d-ff 96 --angle-freqs 8

Trained Qubit count: 6

Size: 590.7 KiB

Bell Pair: image Anti-correlated Bell Pair: image 4-Qubit GHZ: image 6-Qubit GHZ: image GHZ phase interference: image Grover: image Grover: image Cluster State: image Angle: image Angle: image

Downloads last month

-

Downloads are not tracked for this model. How to track
Inference Providers NEW
This model isn't deployed by any Inference Provider. πŸ™‹ Ask for provider support