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)
- 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']}")
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.0 (stable ABI 0.6.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.0 (ABI 0.6.0)
Release files for moonlab 1.2.0
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.0-py3-none-win_arm64.whl | Python 3 | none | Windows ARM64 | Details |
| moonlab-1.2.0-py3-none-win_amd64.whl | Python 3 | none | Windows x86-64 | Details |
| moonlab-1.2.0-py3-none-musllinux_1_2_x86_64.whl | Python 3 | none | Linux musl 1.2+ x86-64 | Details |
| moonlab-1.2.0-py3-none-musllinux_1_2_aarch64.whl | Python 3 | none | Linux musl 1.2+ ARM64 | Details |
| moonlab-1.2.0-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.0-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.0-py3-none-macosx_11_0_arm64.whl | Python 3 | none | macOS 11.0+ ARM64 | Details |
| moonlab-1.2.0-py3-none-macosx_10_15_x86_64.whl | Python 3 | none | macOS 10.15+ x86-64 | Details |
Total release size: 58.0 MB
Release files / moonlab-1.2.0-py3-none-win_arm64.whl
| Download URL | moonlab-1.2.0-py3-none-win_arm64.whl |
|---|---|
| Size | 613.9 kB |
| Tags | Python 3 Windows ARM64 |
|
SHA-256 checksum How to use checksums |
49de83ef28ed38cd642e6856f0d8d8f7e7284dcae24ffaaedc7c4f729b7e5efa
|
|
BLAKE2b-256 checksum How to use checksums |
2f07b1efd98bb1cbb85ca75c5f7d29ccc948d6123de5da168db179c526fdfa1e
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.12.13
|
Release files / moonlab-1.2.0-py3-none-win_amd64.whl
| Download URL | moonlab-1.2.0-py3-none-win_amd64.whl |
|---|---|
| Size | 681.4 kB |
| Tags | Python 3 Windows x86-64 |
|
SHA-256 checksum How to use checksums |
b20dc98d9d8568cc39c276a9e73160e369cbcbfba7ceb6229ca010fe22349af6
|
|
BLAKE2b-256 checksum How to use checksums |
16dc21ee1fd412c88108df20aac2920bab0ba14eaa8cdf77c1447ebd6f681e3e
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.12.13
|
Release files / moonlab-1.2.0-py3-none-musllinux_1_2_x86_64.whl
| Download URL | moonlab-1.2.0-py3-none-musllinux_1_2_x86_64.whl |
|---|---|
| Size | 17.2 MB |
| Tags | Linux musl 1.2+ x86-64 Python 3 |
|
SHA-256 checksum How to use checksums |
c9762196b43d485b120f9096ffcac99bbfce9b2d408d4d38fe5b710afb936201
|
|
BLAKE2b-256 checksum How to use checksums |
7010fea5a8501d6e27775995038911cdf67ec1c1b8f1f36342f7b8cfd32bf4a4
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.12.13
|
Release files / moonlab-1.2.0-py3-none-musllinux_1_2_aarch64.whl
| Download URL | moonlab-1.2.0-py3-none-musllinux_1_2_aarch64.whl |
|---|---|
| Size | 10.6 MB |
| Tags | Linux musl 1.2+ ARM64 Python 3 |
|
SHA-256 checksum How to use checksums |
4a01032eb7e3b0ab0eb19491ac7bdf06c62d4af3f40487d20dc4cfd13df4e742
|
|
BLAKE2b-256 checksum How to use checksums |
3f5996b3904d4c5179b878e2517d0c8ff5c50de6090d8a027851357829ea9a0e
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.12.13
|
Release files / moonlab-1.2.0-py3-none-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl
| Download URL | moonlab-1.2.0-py3-none-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl |
|---|---|
| Size | 17.4 MB |
| Tags | Linux glibc 2.27+ x86-64 Linux glibc 2.28+ x86-64 Python 3 |
|
SHA-256 checksum How to use checksums |
740e60a158ac9791f9c6c29c990e016f53cd8e5c276ffc38a4fb676aa4eea85d
|
|
BLAKE2b-256 checksum How to use checksums |
e1f945001afd8113119defca8897d870221c9b33ef32831492a1ac94acf70650
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.12.13
|
Release files / moonlab-1.2.0-py3-none-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl
| Download URL | moonlab-1.2.0-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 |
9e4d3b0f8594fd0b23704c833d451e4ef5394173318968f5087b6e84d0015c15
|
|
BLAKE2b-256 checksum How to use checksums |
a3c81b19bbb5212e37fb3d0b3b30719d37477c905c66d95aa30f2ff2fb543fa4
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.12.13
|
Release files / moonlab-1.2.0-py3-none-macosx_11_0_arm64.whl
| Download URL | moonlab-1.2.0-py3-none-macosx_11_0_arm64.whl |
|---|---|
| Size | 720.7 kB |
| Tags | Python 3 macOS 11.0+ ARM64 |
|
SHA-256 checksum How to use checksums |
c27b6121e63009938205e5db22a6253799a65df21a3ac2559dbeb539330e40f2
|
|
BLAKE2b-256 checksum How to use checksums |
7db5182a3c8ad63235f6a4d09cbaedadc9dc2f968a3833a4dcf81df8ac31ff36
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.12.13
|
Release files / moonlab-1.2.0-py3-none-macosx_10_15_x86_64.whl
| Download URL | moonlab-1.2.0-py3-none-macosx_10_15_x86_64.whl |
|---|---|
| Size | 803.7 kB |
| Tags | Python 3 macOS 10.15+ x86-64 |
|
SHA-256 checksum How to use checksums |
3b0e0a97b41a9636d4c053e10a0054bacfaec3f33e9155f5c58f25d29bc8bfb1
|
|
BLAKE2b-256 checksum How to use checksums |
560cc61fff21d28e720b74d11a80c2b78f7db6ac8904a02e7479dcb5be2f4dbc
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.12.13
|