Moonlab Python Bindings
Python interface for the Moonlab Quantum Simulator
Fast, feature-complete quantum computing in Python with PyTorch integration.
Quick Start
from moonlab import QuantumState
# Create Bell state (maximal entanglement)
state = QuantumState(2)
state.h(0).cnot(0, 1)
# Measure probabilities
probs = state.probabilities()
print(probs) # [0.5, 0.0, 0.0, 0.5] - |00⟩ and |11⟩
Installation
Prerequisites
The published wheel is self-contained: the Python build pins
QSIM_ENABLE_OPENMP=OFF (see bindings/python/pyproject.toml), so
pip install moonlab needs no libomp install.
libomp is only relevant if you build libquantumsim yourself with
OpenMP turned on (the top-level CMake default), e.g. for a non-Python
build or local development against a custom CMake configuration:
# macOS with Apple Silicon
brew install libomp
# Linux
sudo apt-get install libomp-dev
Build & Install
# 1. Build C library
cd /path/to/moonlab
make
# 2. Install Python package
cd bindings/python
pip install -e .
# 3. Test installation
python test_moonlab.py
Features
Core Quantum Operations
- 32-qubit simulation (4.3 billion states)
- Complete universal gate set (H, X, Y, Z, CNOT, Toffoli, rotations)
- Bell inequality violation on explicit Bell states (CHSH ~ 2.87 measured at 10k samples on |Phi+>, vs the Tsirelson bound 2.828). The CHSH test now correctly honours whatever state you pass in -- the previous release silently overwrote the input with |Phi+>, making every CHSH result read 2.828 by fiat. Separable inputs now give CHSH ~ 0 as physics requires.
- SIMD-dispatched C core (AVX-512 / AVX2 / NEON / SVE) with an optional Metal GPU backend on Apple Silicon; see the reproducible-benchmark harness for host-specific numbers rather than a single multiplier
Quantum Algorithms
- VQE - Variational Quantum Eigensolver for molecular simulation, with native reverse-mode autograd (adjoint-method gradient) for the hardware-efficient ansatz in noise-free simulation
- QAOA - Quantum optimization (MaxCut, Ising models)
- Quantum annealing - Exact logical transverse-field Ising and full-QUBO evolution with deterministic samples and ground-state diagnostics
- Grover - Quantum search algorithm
- Bell Tests - CHSH, Mermin (3-qubit GHZ), and Mermin-Klyshko N-qubit nonlocality inequalities
Native Autograd (moonlab.diff)
Reverse-mode gradients for parameterised circuits, without a PyTorch dependency:
from moonlab import QuantumState
from moonlab.diff import DiffCircuit, PauliTerm, OBS_Z, OBS_X
circ = DiffCircuit(num_qubits=2).ry(0, 0.3).ry(1, -0.4).cnot(0, 1)
H = [PauliTerm(1.0, [0], [OBS_Z]),
PauliTerm(0.5, [0, 1], [OBS_Z, OBS_Z])]
state = QuantumState(2)
circ.forward(state)
cost = DiffCircuit.expect_pauli_sum(state, H)
grad = circ.backward_pauli_sum(state, H) # ndarray, shape (n_params,)
Supported gates: RX / RY / RZ / H / X / Y / Z / CNOT / CZ / CRX / CRY / CRZ.
Post-Quantum Cryptography (moonlab.crypto)
FIPS 202 SHA-3 / SHAKE and FIPS 203 ML-KEM (512 / 768 / 1024), with health-tested, Bell-gated, SHAKE256-conditioned RNG convenience wrappers:
from moonlab.crypto import sha3, mlkem
digest = sha3.sha3_256(b"quantum randomness") # 32 bytes
stream = sha3.shake256(b"seed", outlen=1024) # XOF
# Alice keygens with Moonlab's conditioned hybrid RNG
ek, dk = mlkem.keygen768_qrng() # 1184-byte pk, 2400-byte sk
# Bob encapsulates a shared secret
ct, K_bob = mlkem.encaps768_qrng(ek) # 1088-byte ciphertext
# Alice decapsulates
K_alice = mlkem.decaps768(ct, dk)
assert K_alice == K_bob # same 32-byte shared secret
All NIST SHA-3 / SHAKE known-answer vectors pass; ML-KEM is validated
against the pq-crystals reference via AES-256-CTR_DRBG-derived NIST
count=0 seed (see docs/security/pqc.md for the full threat model).
Quantum Machine Learning
- Feature Maps: Angle, Amplitude, IQP encoding
- Quantum Kernels: Exponential feature spaces
- QSVM: Quantum Support Vector Machine
- Quantum PCA: Principal component analysis
- PyTorch Integration: QuantumLayer with autograd
Examples
Basic Quantum Circuit
from moonlab import QuantumState, Gates
# Create 3-qubit GHZ state
state = QuantumState(3)
Gates.H(state, 0)
Gates.CNOT(state, 0, 1)
Gates.CNOT(state, 1, 2)
# Get state vector
sv = state.get_statevector()
print(f"|GHZ⟩ = {sv}")
Quantum Machine Learning
from moonlab.ml import QSVM, IQPEncoding
import numpy as np
# Prepare data
X_train = np.random.randn(50, 4)
y_train = np.random.choice([-1, 1], 50)
# Train Quantum SVM
qsvm = QSVM(num_qubits=4, feature_map='iqp')
qsvm.fit(X_train, y_train)
# Predict
y_pred = qsvm.predict(X_test)
accuracy = qsvm.score(X_test, y_test)
print(f"Accuracy: {accuracy:.1%}")
PyTorch Integration
import torch
import torch.nn as nn
from moonlab.torch_layer import QuantumLayer
# Build hybrid quantum-classical network
model = nn.Sequential(
nn.Linear(28*28, 16),
nn.Tanh(),
QuantumLayer(num_qubits=16, depth=3),
nn.Linear(16, 10)
)
# Train with standard PyTorch
optimizer = torch.optim.Adam(model.parameters())
for epoch in range(10):
outputs = model(train_data)
loss = criterion(outputs, labels)
loss.backward() # Quantum gradients via parameter shift!
optimizer.step()
Quantum PCA
from moonlab.ml import QuantumPCA
# Dimensionality reduction with quantum advantage
qpca = QuantumPCA(num_components=2, num_qubits=3)
qpca.fit(X_highdim)
X_reduced = qpca.transform(X_highdim)
print(f"Explained variance: {qpca.explained_variance_}")
Advanced Usage
Custom Feature Maps
from moonlab.ml import QuantumFeatureMap
from moonlab import QuantumState
class CustomEncoding(QuantumFeatureMap):
def encode(self, x, state):
state.reset()
for i, val in enumerate(x):
state.ry(i, val)
state.rz(i, val**2)
# Add entanglement
for i in range(state.num_qubits - 1):
state.cnot(i, i+1)
Variational Quantum Circuits
from moonlab.ml import VariationalCircuit
from moonlab import QuantumState
circuit = VariationalCircuit(num_qubits=8, num_layers=4)
state = QuantumState(8)
circuit(state) # Apply parameterized circuit
Quantum Kernels
from moonlab.ml import QuantumKernel, IQPEncoding
# Create quantum kernel
encoder = IQPEncoding(num_qubits=4, num_layers=2)
kernel = QuantumKernel(encoder)
# Compute kernel matrix
K = kernel.compute_matrix(X_train)
# Use in any kernel method (SVM, Ridge, etc.)
from sklearn.svm import SVC
svm = SVC(kernel='precomputed')
svm.fit(K, y_train)
Applications
Drug Discovery (VQE)
from moonlab.algorithms import VQE
# Simulate H₂ molecule
vqe = VQE(num_qubits=4, num_layers=3)
result = vqe.solve_h2(bond_distance=0.74)
print(f"Ground state energy: {result['energy']:.6f} Ha")
print(f"Converged: {result['converged']}")
Graph Optimization (QAOA)
from moonlab.algorithms import QAOA
# Solve MaxCut problem on a 5-vertex graph
qaoa = QAOA(num_qubits=5, num_layers=3)
result = qaoa.solve_maxcut(
edges=[(0,1), (1,2), (2,3), (3,4), (4,0), (0,2)]
)
print(f"Best cut: {bin(result['best_bitstring'])}")
print(f"Cut value: {result['best_cost']}")
Quantum Annealing (QUBO)
from moonlab.annealing import AnnealConfig, anneal_qubo
result = anneal_qubo(
[[-1.0, 1.0], [1.0, -1.0]], offset=1.0,
config=AnnealConfig(total_time=12, num_steps=1200,
num_samples=128, seed=0x123456789abcdef0),
)
print(result.best_bitstring, result.best_energy,
result.success_probability)
Few-Shot Learning
from moonlab.torch_layer import QuantumClassifier
# Quantum classifier for small datasets
model = QuantumClassifier(
num_features=16,
num_qubits=8,
num_classes=5,
depth=3
)
# Train on small dataset (quantum advantage!)
train_with_few_samples(model, X_train_small, y_train_small)
Performance
| Operation | Speed | Notes |
|---|---|---|
| 20-qubit circuit | <1ms | SIMD + parallel optimized |
| VQE H₂ molecule | 2-5s | Chemical accuracy |
| QAOA 10-vertex MaxCut | 10-30s | Near-optimal solutions |
| Quantum kernel (n=100) | 5-15s | Exponential feature space |
vs Other Frameworks
| Framework | Speed (rel.) | Features | Apple Silicon |
|---|---|---|---|
| Moonlab | 1.0× (fastest) | Complete | ✅ Optimized |
| Qiskit | 10-50× slower | Excellent | ⚠️ Not optimized |
| Cirq | 15-40× slower | Good | ⚠️ Not optimized |
Testing
# Run test suite
python test_moonlab.py
# Tests include:
# - Core quantum operations
# - Quantum ML algorithms
# - PyTorch integration
# - End-to-end workflows
API Reference
moonlab.core
-
QuantumState(num_qubits) - Quantum state vector
- Methods:
h(),x(),y(),z(),cnot(),rx(),ry(),rz() - Properties:
probabilities(),get_statevector()
- Methods:
-
Gates - Static gate interface
Gates.H(state, qubit),Gates.CNOT(state, c, t), etc.
moonlab.ml
- AngleEncoding - Simple rotation-based encoding
- AmplitudeEncoding - Exponential data compression
- IQPEncoding - Quantum kernel feature map
- QuantumKernel - Kernel computation K(x,x') = |⟨φ(x)|φ(x')⟩|²
- QSVM - Quantum Support Vector Machine
- QuantumPCA - Quantum Principal Component Analysis
moonlab.torch_layer
- QuantumLayer - Parameterized quantum circuit as nn.Module
- QuantumClassifier - Complete quantum classifier
- HybridQNN - Hybrid quantum-classical network
- VariationalCircuit - General variational ansatz
moonlab.algorithms
- VQE - Variational Quantum Eigensolver
- QAOA - Quantum Approximate Optimization
- Grover - Quantum search
- BellTest - CHSH inequality verification
Contributing
See CONTRIBUTING.md for development guidelines.
License
MIT License - See LICENSE file.
Links
- Documentation: https://github.com/tsotchke/moonlab
- GitHub: https://github.com/tsotchke/moonlab
- Issues: https://github.com/tsotchke/moonlab/issues
Citation
If you use Moonlab in research, please cite:
@software{moonlab2026,
title={Moonlab: High-Performance Quantum Computing for Apple Silicon},
author={Tsotchke},
year={2026},
url={https://github.com/tsotchke/moonlab}
}
Support
- Issues: https://github.com/tsotchke/moonlab/issues
- Email: support@tsotchke.ai
References
This library implements algorithms from the following foundational works:
Quantum Computing:
- Nielsen, M. A. & Chuang, I. L. (2010). Quantum Computation and Quantum Information. Cambridge University Press.
Variational Algorithms:
- Peruzzo, A. et al. (2014). "A variational eigenvalue solver on a photonic quantum processor." Nat. Commun. 5, 4213.
- Farhi, E., Goldstone, J., & Gutmann, S. (2014). "A quantum approximate optimization algorithm." arXiv:1411.4028.
Quantum Machine Learning:
- Schuld, M. & Petruccione, F. (2021). Machine Learning with Quantum Computers. Springer.
- Benedetti, M. et al. (2019). "Parameterized quantum circuits as machine learning models." Quantum Sci. Technol. 4, 043001.
Historical: what shipped in v0.3.0
This package is currently at v1.2.1 (stable ABI 0.8.0); see
CHANGELOG.md at the repo root and docs/PARITY_MATRIX.md for the
full v0.4-v1.1 history, including the v1.1 GPU (CUDA) state API,
control-plane job scheduling, and QRNG status surface added since the
notes below. The v0.3 highlights are kept here because the
module-level docs they reference (docs/reference/qgt-api.md,
docs/reference/mpdo-api.md) are unchanged since:
Quantum geometric tensor and topology (moonlab.topology):
chern_qwz_proj(m, N),chern_qwz_parallel_transport(m, N)— gauge-invariant projector-trace and parallel-transport-gauge Chern integrators on the Qi-Wu-Zhang model.kane_mele_z2(t, lambda_so, lambda_r, lambda_v, N)— 4-band Z_2 invariant via Fukui-Hatsugai (2007).bhz_z2(A, B, M, N)— HgTe quantum-well topological insulator (Bernevig-Hughes-Zhang 2006).kitaev_chain_z2(t, mu, delta)— 1D BdG Z_2 from Pfaffian-sign product at the time-reversal-invariant momenta (Kitaev 2001).hofstadter_chern(p, q, n_occupied, t, N)— magnetic-Bloch sub-band Chern numbers (Hofstadter 1976).
Matrix-product density operator noise simulator
(moonlab.mpdo.Mpdo):
- Polynomial-cost noisy-circuit simulation per Verstraete, Garcia- Ripoll, and Cirac (Phys. Rev. Lett. 93, 207204, 2004).
- Six named single-qubit Kraus channels (depolarising, amplitude damping, phase damping, bit / phase / bit-phase flip).
- User-supplied Kraus operators via NumPy complex arrays.
- Pauli expectation values (string or integer Pauli code).
Other v0.3 additions:
moonlab.var_d_run,moonlab.var_d_run_v2— CA-MPS variational-D withconvergence_eps.- All v0.2 noise channels and Bell-variants harness remain available.
MOONLAB_LIB_PATH and MOONLAB_LIB_DIR environment variables now
override the dylib search path (parity with the Rust binding's
MOONLAB_LIB_DIR). See docs/reference/qgt-api.md and
docs/reference/mpdo-api.md for the corresponding C ABI contracts,
and docs/tutorials/{topological_band_structure,mpdo_noise}.md for
worked examples.
Current release: v1.2.1 (ABI 0.8.0)
Release files for moonlab 1.2.1
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Built distributions (wheels)
| File | Reset | |||
|---|---|---|---|---|
| moonlab-1.2.1-py3-none-win_arm64.whl | Python 3 | none | Windows ARM64 | Details |
| moonlab-1.2.1-py3-none-win_amd64.whl | Python 3 | none | Windows x86-64 | Details |
| moonlab-1.2.1-py3-none-musllinux_1_2_x86_64.whl | Python 3 | none | Linux musl 1.2+ x86-64 | Details |
| moonlab-1.2.1-py3-none-musllinux_1_2_aarch64.whl | Python 3 | none | Linux musl 1.2+ ARM64 | Details |
| moonlab-1.2.1-py3-none-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl | Python 3 | none | Linux glibc 2.28+ x86-64, Linux glibc 2.27+ x86-64 | Details |
| moonlab-1.2.1-py3-none-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl | Python 3 | none | Linux glibc 2.28+ ARM64, Linux glibc 2.27+ ARM64 | Details |
| moonlab-1.2.1-py3-none-macosx_11_0_arm64.whl | Python 3 | none | macOS 11.0+ ARM64 | Details |
| moonlab-1.2.1-py3-none-macosx_10_15_x86_64.whl | Python 3 | none | macOS 10.15+ x86-64 | Details |
Total release size: 58.6 MB
Release files / moonlab-1.2.1-py3-none-win_arm64.whl
| Download URL | moonlab-1.2.1-py3-none-win_arm64.whl |
|---|---|
| Size | 669.7 kB |
| Tags | Python 3 Windows ARM64 |
|
SHA-256 checksum How to use checksums |
db595377f51a9b43d42462514f8046e3635d564cbf7e333c4c3a672fd3e2475f
|
|
BLAKE2b-256 checksum How to use checksums |
a6c3a214cdf19e4b0d5ce393e5036e1126b6d8c76228a8af963a4b18672228ed
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.12.14
|
Release files / moonlab-1.2.1-py3-none-win_amd64.whl
| Download URL | moonlab-1.2.1-py3-none-win_amd64.whl |
|---|---|
| Size | 740.7 kB |
| Tags | Python 3 Windows x86-64 |
|
SHA-256 checksum How to use checksums |
2da1a5ebc7c77d11c79c6d57c46a4417cff6b2190fd95ce515a9b712a684e91c
|
|
BLAKE2b-256 checksum How to use checksums |
77ad6159060853f5ec37b99459b25441407d0c1ea75ac52baa8fd7cef890e6f2
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.12.14
|
Release files / moonlab-1.2.1-py3-none-musllinux_1_2_x86_64.whl
| Download URL | moonlab-1.2.1-py3-none-musllinux_1_2_x86_64.whl |
|---|---|
| Size | 17.3 MB |
| Tags | Linux musl 1.2+ x86-64 Python 3 |
|
SHA-256 checksum How to use checksums |
2e40384476cc458607d3b7f4cd998eecc526c01934fc76bb90cd6a75338bbad3
|
|
BLAKE2b-256 checksum How to use checksums |
750bf8ace9d8ca7e7631b6e19525ad2eb091b62c49b35ad0c89f1c5a61bea62c
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.12.14
|
Release files / moonlab-1.2.1-py3-none-musllinux_1_2_aarch64.whl
| Download URL | moonlab-1.2.1-py3-none-musllinux_1_2_aarch64.whl |
|---|---|
| Size | 10.7 MB |
| Tags | Linux musl 1.2+ ARM64 Python 3 |
|
SHA-256 checksum How to use checksums |
1e2e0f91090a2a846759f1550f611c2b5ab0f2914a2398d0f812199821216b9e
|
|
BLAKE2b-256 checksum How to use checksums |
8859a0c9d71c77117b5469d5477d919686719a1e675aff9ab0777415c3acb7d4
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.12.14
|
Release files / moonlab-1.2.1-py3-none-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl
| Download URL | moonlab-1.2.1-py3-none-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl |
|---|---|
| Size | 17.5 MB |
| Tags | Linux glibc 2.27+ x86-64 Linux glibc 2.28+ x86-64 Python 3 |
|
SHA-256 checksum How to use checksums |
d40c7f86c59b770eb8349f1673d644e8c4f7525c948d670254ba7cb353afd371
|
|
BLAKE2b-256 checksum How to use checksums |
56f24b48b3e52ce54196edcf966f9642d4c2fbea3be2a38a3c3246e54d90367a
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.12.14
|
Release files / moonlab-1.2.1-py3-none-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl
| Download URL | moonlab-1.2.1-py3-none-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl |
|---|---|
| Size | 10.0 MB |
| Tags | Linux glibc 2.27+ ARM64 Linux glibc 2.28+ ARM64 Python 3 |
|
SHA-256 checksum How to use checksums |
4efb8e82952ac0e4e1c4db5ee128d6bb734980fe5e449c55684410d4ce97a967
|
|
BLAKE2b-256 checksum How to use checksums |
1a445a3916aefc551fb1748dcde6ef14bbca99709ee0bdc614957ba90124a32e
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.12.14
|
Release files / moonlab-1.2.1-py3-none-macosx_11_0_arm64.whl
| Download URL | moonlab-1.2.1-py3-none-macosx_11_0_arm64.whl |
|---|---|
| Size | 783.8 kB |
| Tags | Python 3 macOS 11.0+ ARM64 |
|
SHA-256 checksum How to use checksums |
83539bc260652ee81483b28de3596a937adf01fb4857e722adb702d4d73c3c02
|
|
BLAKE2b-256 checksum How to use checksums |
e818d4808358ddd6b7111bca0174b4a50b71714c70c6b2af514b46175d97e5a7
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.12.14
|
Release files / moonlab-1.2.1-py3-none-macosx_10_15_x86_64.whl
| Download URL | moonlab-1.2.1-py3-none-macosx_10_15_x86_64.whl |
|---|---|
| Size | 864.7 kB |
| Tags | Python 3 macOS 10.15+ x86-64 |
|
SHA-256 checksum How to use checksums |
f16194c63cf08c265aacdedb1e76cf2c9f71175f115ed016c44077abaa832899
|
|
BLAKE2b-256 checksum How to use checksums |
49e615f7bd0c3a166b23e7da09983b15738ab6b4db28d51a5ba0c1124078e910
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.12.14
|