# Compute Backends
Source: https://dynex.mintlify.app/annealing/backends
Run on Dynex neuromorphic GPU chips or test locally
# Compute Backends
`DynexConfig` selects which hardware handles your computation. The primary backend for all production workloads is **GPU** — Dynex's own neuromorphic computing chips operated across a distributed GPU network worldwide.
## Overview
| Backend | Hardware | Use case |
| ------- | -------------------------------- | ------------------------------------------ |
| `GPU` | **Dynex neuromorphic GPU chips** | **Production — the primary Dynex backend** |
| `QPU` | Specific QPU hardware models | Targeted QPU hardware runs |
| `CPU` | CPU workers on the network | Lightweight testing on the network |
| `LOCAL` | Local binary (offline) | Unit tests, CI/CD, offline development |
## GPU — Dynex Neuromorphic Chips
**This is the primary compute backend.** Dynex operates thousands of neuromorphic GPU chips distributed globally. When you submit a job with `ComputeBackend.GPU`, it runs directly on this hardware.
The GPU network is Dynex's core infrastructure — the Digital Twin of a neuromorphic quantum computing machine, running on GPUs at scale. This backend delivers:
* **Neuromorphic parallelism** — thousands of chips work on your problem simultaneously
* **No qubit limits** — problems of arbitrary size are supported
* **Always available** — distributed, no single point of failure
* **Linear scaling** — tested up to 64 × 10⁶ variables with linear resource growth
```python theme={null}
from dynex import DynexConfig, ComputeBackend
config = DynexConfig(compute_backend=ComputeBackend.GPU)
```
That's it. Credentials are loaded from `DYNEX_SDK_KEY` and `DYNEX_GRPC_ENDPOINT` environment variables, or from a `.env` file.
### Full production example
```python theme={null}
import dynex
import dimod
from dynex import DynexConfig, ComputeBackend
config = DynexConfig(
compute_backend=ComputeBackend.GPU,
default_description="Portfolio optimization — production run",
default_timeout=600.0,
)
bqm = dimod.BinaryQuadraticModel.from_qubo(Q)
model = dynex.BQM(bqm)
sampler = dynex.DynexSampler(model, config=config)
sampleset = sampler.sample(
num_reads=10000,
annealing_time=1000,
shots=5,
)
print(f"Best energy: {sampleset.first.energy:.4f}")
```
***
## QPU — Quantum Processing Unit
For specialized QPU hardware models built on top of the Dynex GPU infrastructure. Requires specifying a QPU model.
```python theme={null}
from dynex import DynexConfig, ComputeBackend, QPUModel
config = DynexConfig(
compute_backend=ComputeBackend.QPU,
qpu_model=QPUModel.APOLLO_RC1
)
```
### Available QPU models
| Model | Constant | Description |
| -------------- | ----------------------- | -------------------------- |
| `apollo_rc1` | `QPUModel.APOLLO_RC1` | Apollo RC1 |
| `apollo_10000` | `QPUModel.APOLLO_10000` | Apollo 10000 — large-scale |
`qpu_model` is required when `compute_backend=QPU`. Omitting it raises `ValueError`.
QPU hardware has tighter constraints than GPU. Use `num_reads` in the range 1–100, `annealing_time` in 10–1000, and `shots` up to 5.
### Coefficient bounds: `qpu_max_coeff`
The Apollo QPU hardware requires BQM coefficients (linear and quadratic) to stay within a bounded range. The sampler automatically checks and scales your model if needed:
```python theme={null}
sampleset = sampler.sample(
num_reads=50,
annealing_time=200,
qpu_max_coeff=9.0, # Default. Coefficients above this are auto-scaled.
)
```
If any coefficient exceeds `qpu_max_coeff`, the entire BQM is scaled down proportionally so the maximum absolute coefficient equals the threshold. The scaling is transparent — solutions are returned in the original variable space.
| Scenario | Behaviour |
| ---------------------------------- | ------------------------------------------------ |
| All coefficients ≤ `qpu_max_coeff` | No scaling, BQM used as-is |
| Any coefficient > `qpu_max_coeff` | BQM auto-scaled, scaling factor logged |
| Circuit BQM (QASM) | Scaling handled by Apollo API, parameter ignored |
If your QUBO has large coefficients (e.g. penalty terms in CQM conversion), lower `qpu_max_coeff` to bring them into hardware range without manually rescaling the model.
### QPU sampling example
```python theme={null}
from dynex import DynexConfig, ComputeBackend, QPUModel
import dynex, dimod
config = DynexConfig(
compute_backend=ComputeBackend.QPU,
qpu_model=QPUModel.APOLLO_RC1
)
model = dynex.BQM(bqm)
sampler = dynex.DynexSampler(model, config=config)
sampleset = sampler.sample(
num_reads=50, # QPU: 1–100
annealing_time=200, # QPU: 10–1000
shots=1, # QPU: up to 5
qpu_max_coeff=9.0, # Auto-scale coefficients to hardware range
preprocess=True
)
print(f"Best energy: {sampleset.first.energy:.4f}")
```
***
## CPU
CPU workers on the Dynex network. Useful for testing network connectivity and lightweight jobs before moving to GPU.
```python theme={null}
config = DynexConfig(compute_backend=ComputeBackend.CPU)
```
***
## LOCAL
Runs the `dynexcore` binary locally without any network connection. No SDK key required. Intended for offline development and CI/CD pipelines.
```python theme={null}
config = DynexConfig(compute_backend=ComputeBackend.LOCAL)
```
Requires the `dynexcore` binary in a `testnet/` directory. Download from [GitHub releases](https://github.com/Dynex-Development/py-sdk/releases).
LOCAL mode is for development only. Performance does not reflect the Dynex GPU network.
***
## Configuration via environment variables
```bash theme={null}
# .env
DYNEX_SDK_KEY=your_sdk_key
DYNEX_GRPC_ENDPOINT=quantum-router-engine-grpc.hz.dynex.co:3000
DYNEX_COMPUTE_BACKEND=gpu
```
All `DynexConfig` parameters can be set via `DYNEX_*` environment variables. Constructor arguments always take priority.
## Full DynexConfig reference
```python theme={null}
from dynex import DynexConfig, ComputeBackend, QPUModel
config = DynexConfig(
sdk_key=None, # SDK key (or DYNEX_SDK_KEY)
grpc_endpoint=None, # gRPC endpoint (or DYNEX_GRPC_ENDPOINT)
compute_backend=ComputeBackend.GPU, # Primary production backend
qpu_model=None, # Required for QPU only
use_notebook_output=True, # Jupyter-friendly output
default_timeout=300.0, # Timeout in seconds
default_description="Dynex SDK Job", # Job label in dashboard
retry_count=5, # Retries on transient failures
dotenv_path=None,
)
```
## Backend selection by environment
```python theme={null}
import os
from dynex import DynexConfig, ComputeBackend, QPUModel
def get_config() -> DynexConfig:
env = os.getenv("ENV", "development")
if env == "production":
return DynexConfig(compute_backend=ComputeBackend.GPU)
elif env == "qpu":
return DynexConfig(
compute_backend=ComputeBackend.QPU,
qpu_model=QPUModel.APOLLO_RC1
)
else:
return DynexConfig(compute_backend=ComputeBackend.LOCAL)
```
# Defining Models
Source: https://dynex.mintlify.app/annealing/models
BQM, CQM, and DQM — choosing and building the right model
# Defining Models
Dynex SDK supports three model types, each suited to a different class of problems. All models wrap a dimod object and pass through to `DynexSampler`.
## Model Selection Guide
| Problem type | Model | Example |
| ----------------------------------------- | ----- | ---------------------------------------------- |
| Binary variables, no constraints | `BQM` | QUBO, Ising, MaxCut, graph problems |
| Binary/integer variables with constraints | `CQM` | Portfolio optimization, scheduling with budget |
| Multi-valued discrete variables | `DQM` | Multi-class assignment, routing |
***
## BQM — Binary Quadratic Model
The most common model type. Represents an objective function over binary variables (0/1 or ±1).
```python theme={null}
import dynex
import dimod
# Define BQM with dimod
bqm = dimod.BinaryQuadraticModel(
{0: 1.0, 1: -1.0}, # Linear terms: h_i * x_i
{(0, 1): 0.5}, # Quadratic terms: J_ij * x_i * x_j
0.0, # Constant offset
'BINARY' # Variable type: 'BINARY' (0/1) or 'SPIN' (-1/+1)
)
model = dynex.BQM(bqm)
```
### Using PyQUBO
```python theme={null}
from pyqubo import Binary
x0, x1, x2 = Binary('x0'), Binary('x1'), Binary('x2')
H = x0 + x1 - 2*x0*x1 + x2
qubo, offset = H.compile().to_qubo()
bqm = dimod.BinaryQuadraticModel.from_qubo(qubo)
model = dynex.BQM(bqm)
```
### Working with named variables
```python theme={null}
bqm = dimod.BinaryQuadraticModel(
{'a': -1.0, 'b': -1.0, 'c': 1.0},
{('a', 'b'): 2.0, ('b', 'c'): -0.5},
0.0,
'BINARY'
)
model = dynex.BQM(bqm)
```
***
## CQM — Constrained Quadratic Model
For problems where constraints are first-class: equality and inequality constraints are encoded directly without penalty terms.
```python theme={null}
import dynex
import dimod
cqm = dimod.ConstrainedQuadraticModel()
# Define binary variables
x = dimod.Binary('x')
y = dimod.Binary('y')
z = dimod.Binary('z')
# Objective: maximize x + 2y + 3z
cqm.set_objective(-x - 2*y - 3*z)
# Constraint: x + y + z <= 2 (budget constraint)
cqm.add_constraint(x + y + z <= 2, label='budget')
# Constraint: x + z >= 1 (minimum requirement)
cqm.add_constraint(x + z >= 1, label='min_req')
model = dynex.CQM(cqm)
```
CQM is ideal when constraints cannot be easily penalized. The SDK handles constraint-to-QUBO conversion internally.
***
## DQM — Discrete Quadratic Model
For problems with multi-valued variables — where each variable can take one of several discrete values.
```python theme={null}
import dynex
import dimod
dqm = dimod.DiscreteQuadraticModel()
# Add variable 'color' with 3 possible values (0, 1, 2)
dqm.add_variable(3, label='color')
# Add variable 'size' with 4 possible values (0, 1, 2, 3)
dqm.add_variable(4, label='size')
# Set linear biases: prefer color=1 and size=2
dqm.set_linear('color', [1.0, -1.0, 0.5])
dqm.set_linear('size', [0.0, 0.5, -1.0, 0.5])
# Set quadratic interaction between variables
dqm.set_quadratic('color', 'size', {(0, 0): 1.0, (1, 2): -0.5})
model = dynex.DQM(dqm)
```
***
## Preprocessing
For QPU backends, preprocessing can improve solution quality by scaling and normalizing coefficients:
```python theme={null}
from dynex import DynexConfig, ComputeBackend, QPUModel
config = DynexConfig(
compute_backend=ComputeBackend.QPU,
qpu_model=QPUModel.APOLLO_RC1
)
sampler = dynex.DynexSampler(model, config=config)
sampleset = sampler.sample(
num_reads=50, # QPU: 1–100
annealing_time=200, # QPU: 10–1000
preprocess=True # Enable automatic preprocessing
)
```
# Parallel Sampling
Source: https://dynex.mintlify.app/annealing/parallel
Run multiple samplers simultaneously for federated learning and ensemble methods
# Parallel Sampling
`DynexSampler` is thread-safe and can be parallelized using Python's `multiprocessing` module. This is especially useful for:
* **Federated learning** — computing multiple network layers simultaneously
* **Ensemble methods** — collecting diverse solutions from independent runs
* **Hyperparameter search** — testing multiple configurations in parallel
* **Multi-model pipelines** — running different models on the same problem concurrently
## Basic parallel example
```python theme={null}
import dynex
import dimod
import multiprocessing
from multiprocessing import Queue
from dynex import DynexConfig, ComputeBackend, QPUModel, DynexSampler, BQM
def run_sampler(queue, job_id, model):
print(f"Sampler {job_id} started")
config = DynexConfig(
compute_backend=ComputeBackend.QPU,
qpu_model=QPUModel.APOLLO_RC1
)
sampler = DynexSampler(
model,
config=config,
logging=False,
description=f"Parallel job {job_id}"
)
sampleset = sampler.sample(num_reads=50, annealing_time=200) # QPU: num_reads 1–100, annealing_time 10–1000
print(f"Sampler {job_id} finished")
queue.put(sampleset)
if __name__ == "__main__":
# Build the model once, share across workers
bqm = dimod.BinaryQuadraticModel(
{i: float(i % 3 - 1) for i in range(15)},
{(i, i+1): 0.5 for i in range(14)},
0.0,
'BINARY'
)
config = DynexConfig(compute_backend=ComputeBackend.QPU, qpu_model='apollo_rc1')
model = BQM(bqm, config=config)
PARALLEL_INSTANCES = 8
jobs = []
result_queues = []
# Start all parallel samplers
for i in range(PARALLEL_INSTANCES):
q = Queue()
result_queues.append(q)
p = multiprocessing.Process(target=run_sampler, args=(q, i, model))
jobs.append(p)
p.start()
# Wait for all to complete
for job in jobs:
job.join()
# Collect results
results = []
for q in result_queues:
sampleset = q.get()
results.append(sampleset)
print(f"Best energy: {sampleset.first.energy:.4f}")
```
## Federated learning pattern
In federated learning, each parallel job typically handles a different model or data partition:
```python theme={null}
import multiprocessing
from multiprocessing import Queue
import dynex
from dynex import DynexConfig, ComputeBackend, DynexSampler, BQM
def train_layer(queue, layer_id, layer_bqm):
"""Train a single layer of a quantum neural network."""
config = DynexConfig(compute_backend=ComputeBackend.QPU, qpu_model='apollo_rc1')
model = BQM(layer_bqm)
sampler = DynexSampler(model, config=config, logging=False)
sampleset = sampler.sample(num_reads=50, annealing_time=200) # QPU: num_reads 1–100, annealing_time 10–1000
queue.put((layer_id, sampleset.first.sample))
def train_parallel(layer_bqms):
jobs = []
queues = []
for i, bqm in enumerate(layer_bqms):
q = Queue()
queues.append(q)
p = multiprocessing.Process(target=train_layer, args=(q, i, bqm))
jobs.append(p)
p.start()
for job in jobs:
job.join()
# Collect layer weights in order
weights = {}
for q in queues:
layer_id, sample = q.get()
weights[layer_id] = sample
return [weights[i] for i in range(len(layer_bqms))]
```
## Thread pool for I/O-bound workflows
For lighter workloads where GIL contention is not a concern, `ThreadPoolExecutor` can be used:
```python theme={null}
from concurrent.futures import ThreadPoolExecutor, as_completed
import dynex
from dynex import DynexConfig, ComputeBackend, DynexSampler, BQM
def run_job(args):
job_id, bqm = args
config = DynexConfig(compute_backend=ComputeBackend.GPU)
model = BQM(bqm)
sampler = DynexSampler(model, config=config, logging=False)
sampleset = sampler.sample(num_reads=500, annealing_time=100)
return job_id, sampleset.first.energy
bqms = [build_bqm(i) for i in range(4)] # Your model-building function
with ThreadPoolExecutor(max_workers=4) as executor:
futures = {executor.submit(run_job, (i, bqm)): i for i, bqm in enumerate(bqms)}
for future in as_completed(futures):
job_id, energy = future.result()
print(f"Job {job_id} best energy: {energy:.4f}")
```
Use `multiprocessing.Process` (not threads) for CPU-intensive sampling. Python's GIL prevents true parallelism with threads for compute-heavy workloads.
## Performance considerations
* All parallel jobs are submitted to the Dynex network simultaneously — they compete for the same worker pool
* For QPU backends, each parallel job consumes QPU resources independently
* Set `logging=False` in parallel workers to avoid interleaved output
* Use `description` to tag jobs for identification in the Dynex dashboard
# Sampling Models
Source: https://dynex.mintlify.app/annealing/sampling
Sampling parameters, backends, and result interpretation
# Sampling Models
After defining your model and configuring a backend, sampling is the core operation. The `DynexSampler` translates your model into a neuromorphic circuit and runs it on the selected compute backend.
## Common pattern
```python theme={null}
import dynex
from dynex import DynexConfig, ComputeBackend
# GPU — Dynex neuromorphic chips, recommended for all production workloads
config = DynexConfig(compute_backend=ComputeBackend.GPU)
model = dynex.BQM(bqm) # or CQM, DQM
sampler = dynex.DynexSampler(model, config=config)
sampleset = sampler.sample(num_reads=1000, annealing_time=200)
```
## Core parameters
```python theme={null}
sampleset = sampler.sample(
num_reads=1000, # Number of independent reads (parallel samples)
annealing_time=200, # ODE integration depth (higher = more thorough search)
shots=5, # Minimum worker-returned solutions (network backends)
preprocess=False, # Apply preprocessing for QPU backends
debugging=False, # Verbose progress output
)
```
### Parameter guidance
**`num_reads`**
Controls the number of independent samples. More reads means better coverage of the solution space.
| Backend | Recommended range |
| ---------------- | ----------------- |
| GPU (production) | 1000–10000 |
| CPU | 500–5000 |
| QPU | 1–100 |
| LOCAL | 100–1000 |
**`annealing_time`**
Controls the ODE integration depth. Longer annealing gives the system more time to find lower-energy states.
| Backend | Recommended range |
| ---------------- | ----------------- |
| GPU (production) | 200–1000 |
| CPU | 100–500 |
| QPU | 10–1000 |
| LOCAL | 50–500 |
**`shots`**
For network backends (CPU/GPU/QPU), sets the minimum number of solutions to collect from workers before returning. Useful when you need multiple diverse solutions, not just the global optimum. Current recommended maximum: **5**.
**`qpu_max_coeff`** *(default: `9.0`, QPU only)*
Maximum allowed absolute value for any BQM coefficient when using a QPU backend. If any linear or quadratic coefficient exceeds this threshold, the sampler automatically scales the entire BQM down proportionally before submitting the job. Solutions are returned in the original variable space. Useful when your QUBO contains large penalty terms that exceed hardware bounds.
**`preprocess`**
Enables automatic scaling and normalization of QUBO coefficients. Recommended for QPU backends to stay within hardware bounds.
## Model-specific examples
### BQM
```python theme={null}
model = dynex.BQM(bqm)
sampler = dynex.DynexSampler(model, config=config)
sampleset = sampler.sample(num_reads=1000, annealing_time=200)
```
### CQM
```python theme={null}
model = dynex.CQM(cqm)
sampler = dynex.DynexSampler(model, config=config)
sampleset = sampler.sample(num_reads=500, annealing_time=100)
```
### DQM
```python theme={null}
model = dynex.DQM(dqm)
sampler = dynex.DynexSampler(model, config=config)
sampleset = sampler.sample(num_reads=500, annealing_time=100)
```
### GPU (production)
```python theme={null}
config = DynexConfig(compute_backend=ComputeBackend.GPU)
sampler = dynex.DynexSampler(model, config=config)
sampleset = sampler.sample(
num_reads=5000,
annealing_time=500,
shots=5,
)
```
### QPU with preprocessing
QPU backends require smaller parameter values due to hardware constraints.
```python theme={null}
from dynex import QPUModel
config = DynexConfig(
compute_backend=ComputeBackend.QPU,
qpu_model=QPUModel.APOLLO_RC1
)
sampler = dynex.DynexSampler(model, config=config)
sampleset = sampler.sample(
num_reads=50, # QPU: keep in range 1–100
annealing_time=200, # QPU: keep in range 10–1000
shots=1, # QPU: up to 5
qpu_max_coeff=9.0, # Auto-scale BQM if any coefficient exceeds this value
preprocess=True
)
```
## Working with results
The sampler returns a dimod `SampleSet`:
```python theme={null}
# Best solution by energy
best = sampleset.first
print(best.sample) # dict: {var: value, ...}
print(best.energy) # float: objective value
# Iterate all samples (sorted by energy)
for sample, energy in sampleset.data(['sample', 'energy']):
print(f"{sample} → {energy:.4f}")
# Check constraint satisfaction (CQM only)
for sample in sampleset.samples():
violations = cqm.violations(sample)
feasible = all(v == 0 for v in violations.values())
print(f"Feasible: {feasible}")
# Convert to pandas
df = sampleset.to_pandas_dataframe()
print(df.sort_values('energy').head(10))
# Get aggregate statistics
energies = [datum.energy for datum in sampleset.data(['energy'])]
print(f"Min energy: {min(energies):.4f}")
print(f"Mean energy: {sum(energies)/len(energies):.4f}")
```
## Advanced ODE parameters
For fine-grained control of the ODE integration, the following parameters can be set. These define upper bounds for automatic parameter tuning:
```python theme={null}
sampleset = sampler.sample(
num_reads=1000,
annealing_time=200,
alpha=0.1, # Upper bound for ODE alpha parameter
beta=0.1, # Upper bound for ODE beta parameter
gamma=0.5, # Upper bound for ODE gamma parameter
delta=0.5, # Upper bound for ODE delta parameter
epsilon=0.5, # Upper bound for ODE epsilon parameter
zeta=0.5, # Upper bound for ODE zeta parameter
minimum_stepsize=1e-6, # Minimum adaptive step size
)
```
See the [equations of motion](https://github.com/dynexcoin/website/blob/main/Dynex_ODE_equations.pdf) for the mathematical background.
## Block fee (spot compute)
For priority compute on the Dynex network, specify a block fee in nanoDNX:
```python theme={null}
sampleset = sampler.sample(
num_reads=1000,
annealing_time=200,
block_fee=1000000000, # 1 DNX in nanoDNX
)
```
Higher block fees prioritize your jobs on the network. If not specified, the current average network fee is used.
# DynexCircuit
Source: https://dynex.mintlify.app/api-reference/dynex-circuit
Execute quantum gate circuits on the Dynex platform
# DynexCircuit
`DynexCircuit` executes quantum gate circuits on the Dynex neuromorphic platform. Accepts PennyLane, Qiskit, Cirq, and OpenQASM circuits.
```python theme={null}
from dynex import DynexCircuit
```
## Constructor
```python theme={null}
DynexCircuit(config: DynexConfig)
```
Configuration object. For circuits, QPU backend is recommended.
## `execute()` method
```python theme={null}
result = dynex_circuit.execute(
circuit, # PennyLane function | Qiskit QuantumCircuit | QASM string
params: list, # Parameters passed to the circuit function
wires: int, # Number of qubits
method: str = 'measure', # Measurement type
shots: int = 1, # Minimum solutions from network (QPU: up to 5)
description: str = "", # Job description
debugging: bool = False, # Verbose output
num_reads: int = 100, # Parallel samples (QPU: 1–100)
integration_steps: int = 100, # ODE integration depth (QPU: 10–1000)
# ODE parameters: alpha, beta, gamma, delta, epsilon, zeta, minimum_stepsize
block_fee: int = None, # Priority fee in nanoDNX
)
```
### Parameters
The quantum circuit in one of the following formats:
* **PennyLane**: a Python function that applies gates and returns a measurement
* **Qiskit**: a `QuantumCircuit` object
* **OpenQASM**: a string containing QASM 2.0 instructions
* **Cirq**: a Cirq circuit object
Parameters passed to the circuit function. Use `[]` for circuits with no parameters.
Number of qubits the circuit operates on.
Measurement type:
| Value | Returns |
| ------------- | ----------------------------------------- |
| `"measure"` | Computational basis measurement samples |
| `"probs"` | Probability of each basis state per qubit |
| `"all"` | All solutions, one array per shot |
| `"sampleset"` | dimod `SampleSet` object |
Minimum number of solutions to collect from workers before returning. `shots > 1` collects multiple independent circuit runs.
Number of parallel ODE integrations. Higher values improve measurement statistics. For QPU backends, keep in the range 1–100.
ODE integration depth — the number of integration steps used in the neuromorphic circuit simulation. Higher values allow circuits to converge more reliably. For QPU backends, keep in the range 10–1000.
Maximum allowed absolute coefficient value for QPU backends. Coefficients exceeding this are auto-scaled. For circuit BQMs (QASM), scaling is handled by the Apollo API and this parameter is ignored.
Priority fee in nanoDNX (1 DNX = 10⁹ nanoDNX).
## Returns
Depends on `method`:
| method | Return type | Description |
| ------------- | ----------------- | -------------------------- |
| `"measure"` | `array` | Bit string measurement |
| `"probs"` | `array` | Probability for each qubit |
| `"all"` | `list[array]` | One array per shot |
| `"sampleset"` | `dimod.SampleSet` | Full sample set |
## Examples
### PennyLane circuit
```python theme={null}
import pennylane as qml
import numpy as np
from dynex import DynexConfig, ComputeBackend, DynexCircuit
def variational_circuit(params):
qml.RX(params[0], wires=0)
qml.RY(params[1], wires=1)
qml.CNOT(wires=[0, 1])
qml.RZ(params[2], wires=0)
return qml.state()
config = DynexConfig(
compute_backend=ComputeBackend.QPU,
qpu_model='apollo_rc1'
)
circuit = DynexCircuit(config=config)
result = circuit.execute(
variational_circuit,
params=[np.pi/4, np.pi/3, np.pi/6],
wires=2,
method='probs'
)
print("Probabilities:", result)
```
### Qiskit circuit
```python theme={null}
from qiskit import QuantumCircuit
from dynex import DynexConfig, ComputeBackend, DynexCircuit
qc = QuantumCircuit(3)
qc.h(0)
qc.cx(0, 1)
qc.cx(1, 2)
qc.ry(0.5, 2)
config = DynexConfig(compute_backend=ComputeBackend.QPU, qpu_model='apollo_rc1')
circuit = DynexCircuit(config=config)
result = circuit.execute(qc, params=[], wires=3, method='measure')
print("Measurement:", result)
```
### OpenQASM circuit
```python theme={null}
from dynex import DynexConfig, ComputeBackend, DynexCircuit
qasm = """
OPENQASM 2.0;
include "qelib1.inc";
qreg q[3];
h q[0];
cx q[0], q[1];
cx q[1], q[2];
"""
config = DynexConfig(compute_backend=ComputeBackend.QPU, qpu_model='apollo_rc1')
circuit = DynexCircuit(config=config)
result = circuit.execute(qasm, params=[], wires=3, method='all', shots=3)
for i, shot in enumerate(result):
print(f"Shot {i}: {shot}")
```
### Getting a SampleSet
```python theme={null}
sampleset = circuit.execute(
my_circuit, params=[], wires=4, method='sampleset', shots=3
)
print(sampleset.first.sample)
print(sampleset.first.energy)
df = sampleset.to_pandas_dataframe()
```
# DynexConfig
Source: https://dynex.mintlify.app/api-reference/dynex-config
Configuration handler for credentials, backend selection, and SDK behavior
# DynexConfig
Handles all SDK configuration: credentials, compute backend, gRPC endpoint, timeouts, and output formatting.
```python theme={null}
from dynex import DynexConfig, ComputeBackend, QPUModel
```
## Constructor
```python theme={null}
DynexConfig(
sdk_key: Optional[str] = None,
grpc_endpoint: Optional[str] = None,
solver_path: Optional[str] = None,
compute_backend: Union[ComputeBackend, str] = ComputeBackend.UNSPECIFIED,
qpu_model: Optional[Union[QPUModel, str]] = None,
use_notebook_output: bool = True,
default_timeout: float = 300.0,
default_description: str = "Dynex SDK Job",
retry_count: int = 5,
preserve_solutions: bool = False,
remove_local_solutions: bool = False,
debug_save_solutions: bool = False,
dotenv_path: Optional[str] = None,
)
```
## Parameters
SDK authentication key. If not provided, loaded from `DYNEX_SDK_KEY` environment variable or `.env` file.
gRPC server endpoint. Defaults to `"127.0.0.1:9090"`. Set via `DYNEX_GRPC_ENDPOINT` env var or provide directly.
Production: `"quantum-router-engine-grpc.hz.dynex.co:3000"`
Compute backend to use. Accepts enum value or string:
| Value | String | Description |
| ---------------------- | --------- | -------------------------------------------------- |
| `ComputeBackend.GPU` | `"gpu"` | **Dynex neuromorphic GPU chips — primary backend** |
| `ComputeBackend.QPU` | `"qpu"` | Specific QPU hardware model |
| `ComputeBackend.CPU` | `"cpu"` | CPU workers on the network |
| `ComputeBackend.LOCAL` | `"local"` | Local binary, no network required |
Required when `compute_backend=QPU`. Available models:
| Value | String |
| ----------------------- | ---------------- |
| `QPUModel.APOLLO_RC1` | `"apollo_rc1"` |
| `QPUModel.APOLLO_10000` | `"apollo_10000"` |
Enable Jupyter-friendly output formatting (progress bars, tables).
Job timeout in seconds. Applies to network backends.
Default job description shown in the Dynex job dashboard.
Number of retries for transient network failures.
If `True`, keep solution files on disk after sampling completes. Applies to `LOCAL` backend only — network backends store solutions in memory.
If `True`, automatically delete local solution files after reading. Applies to `LOCAL` backend only.
If `True`, write solution data to disk even when using a network backend (CPU, GPU, QPU). Files are saved to the `tmp/` directory alongside job files. Useful for debugging raw solver output without switching to `LOCAL` mode.
Custom path to `.env` file. If not provided, searches current directory and up to 3 parent directories.
Custom path to directory containing `dynexcore` binary (LOCAL mode only).
## Configuration priority
Parameters are resolved in this order (highest to lowest priority):
1. Constructor arguments
2. Environment variables (`DYNEX_SDK_KEY`, `DYNEX_GRPC_ENDPOINT`, etc.)
3. `.env` file values (if `python-dotenv` is installed)
4. Default values
## Examples
```python theme={null}
from dynex import DynexConfig, ComputeBackend, QPUModel
# GPU — Dynex neuromorphic chips, primary production backend
config = DynexConfig(compute_backend=ComputeBackend.GPU)
# QPU — specific hardware model
config = DynexConfig(
compute_backend=ComputeBackend.QPU,
qpu_model=QPUModel.APOLLO_RC1,
default_timeout=600.0,
default_description="Production portfolio optimization",
)
# CPU — lightweight network testing
config = DynexConfig(compute_backend=ComputeBackend.CPU)
# LOCAL — offline development, no credentials needed
config = DynexConfig(compute_backend=ComputeBackend.LOCAL)
# Inspect configuration
print(config.as_dict())
print(config.get_platform_prefix()) # "APOLLO-RC1" | "CPU" | "LOCAL" etc.
```
## `as_dict()` method
Returns all configuration parameters as a dictionary:
```python theme={null}
config.as_dict()
# {
# 'sdk_key': '...',
# 'grpc_endpoint': 'quantum-router-engine-grpc.hz.dynex.co:3000',
# 'mainnet': True,
# 'solver_path': None,
# 'retry_count': 5,
# 'compute_backend': 'qpu',
# 'qpu_model': 'apollo_rc1',
# 'use_notebook_output': True,
# 'default_timeout': 300.0,
# 'default_description': 'Dynex SDK Job',
# 'preserve_solutions': False,
# 'remove_local_solutions': False,
# 'debug_save_solutions': False,
# }
```
## Errors
| Exception | Cause |
| ------------------- | ------------------------------------------------------------------------------------ |
| `ValueError` | Invalid `compute_backend` or `qpu_model` string; missing `qpu_model` for QPU backend |
| `FileNotFoundError` | `dynexcore` binary not found in LOCAL mode |
| `PermissionError` | Cannot create `tmp/` directory |
# DynexSampler
Source: https://dynex.mintlify.app/api-reference/dynex-sampler
Submit annealing jobs and retrieve results from the Dynex platform
# DynexSampler
`DynexSampler` is the core interface for running quantum annealing computations on the Dynex platform. It accepts any model type (BQM, CQM, DQM), submits jobs via gRPC, and returns a dimod `SampleSet`.
```python theme={null}
from dynex import DynexSampler
```
## Constructor
```python theme={null}
DynexSampler(
model, # dynex.BQM | CQM | DQM
config: DynexConfig, # Backend and credentials
description: str = "", # Job description (shown in dashboard)
logging: bool = True, # Enable SDK logging output
)
```
### Parameters
The problem model to sample. Must be a Dynex model wrapper — not a raw dimod object.
Configuration object specifying the compute backend, credentials, and SDK settings.
Human-readable job description. Appears in the Dynex job dashboard and network explorer.
Whether to emit SDK log messages during sampling. Set to `False` for parallel workers or automated pipelines.
## `sample()` method
```python theme={null}
sampleset = sampler.sample(
num_reads: int,
annealing_time: int,
shots: int = 1,
preprocess: bool = False,
debugging: bool = False,
# Advanced ODE parameters:
alpha: float = None,
beta: float = None,
gamma: float = None,
delta: float = None,
epsilon: float = None,
zeta: float = None,
minimum_stepsize: float = None,
block_fee: int = None,
)
```
### Parameters
Number of independent parallel samples. Higher values give broader coverage of the solution space.
| Backend | Recommended |
| ------- | ----------- |
| GPU | 1000–10000 |
| CPU | 500–5000 |
| QPU | 1–100 |
| LOCAL | 100–1000 |
ODE integration depth (number of integration steps). Higher values allow the system more time to find lower-energy states.
| Backend | Recommended |
| ------- | ----------- |
| GPU | 200–1000 |
| CPU | 100–500 |
| QPU | 10–1000 |
| LOCAL | 50–500 |
For network backends, the minimum number of solutions to collect from workers before returning. Use `shots > 1` when you need multiple diverse solutions. Current recommended maximum: **5**.
Maximum allowed absolute value for BQM coefficients when using a QPU backend. If any linear or quadratic coefficient exceeds this threshold, the entire BQM is automatically scaled down proportionally so the maximum coefficient equals `qpu_max_coeff`. Solutions are returned in the original variable space. Has no effect on GPU/CPU/LOCAL backends or on circuit BQMs (QASM), where scaling is handled by the Apollo API.
Apply automatic preprocessing (coefficient scaling, normalization). Recommended for QPU backends to stay within hardware bounds.
Show verbose progress output including worker responses and integration metrics.
Upper bound for automatic alpha parameter tuning in ODE integration. Range: `[0.00000001, 100.0]`.
Upper bound for automatic beta parameter tuning. Range: `[0.00000001, 100.0]`.
Upper bound for automatic gamma parameter tuning. Range: `[0.0, 1.0]`.
Upper bound for automatic delta parameter tuning. Range: `[0.0, 1.0]`.
Upper bound for automatic epsilon parameter tuning. Range: `[0.0, 1.0]`.
Upper bound for automatic zeta parameter tuning. Range: `[0.0, 1.0]`.
Minimum adaptive ODE step size. Range: `[1e-16, 1.0]`. Smaller values increase precision but slow computation.
Priority fee in nanoDNX (1 DNX = 1,000,000,000 nanoDNX). Higher fees prioritize your job on the network. If not specified, the current average network fee is used.
## Returns
Returns a dimod [`SampleSet`](https://docs.ocean.dwavesys.com/en/stable/docs_dimod/reference/sampleset.html):
```python theme={null}
sampleset.first # Sample with lowest energy
sampleset.first.sample # dict: {variable: value}
sampleset.first.energy # float
sampleset.samples() # Iterator (sorted by energy)
sampleset.data(['sample', 'energy']) # Iterator over named fields
sampleset.to_pandas_dataframe() # pandas DataFrame
sampleset.record # numpy structured array
```
## Thread safety
`DynexSampler` is thread-safe and can be used from multiple threads or processes simultaneously. See [Parallel Sampling](/annealing/parallel) for examples.
## Full example
```python theme={null}
import dynex
import dimod
from dynex import DynexConfig, ComputeBackend, QPUModel
# Build problem
bqm = dimod.BinaryQuadraticModel(
{i: float(i % 3 - 1) for i in range(20)},
{(i, i+1): 0.5 for i in range(19)},
0.0,
'BINARY'
)
# Configure QPU
config = DynexConfig(
compute_backend=ComputeBackend.QPU,
qpu_model=QPUModel.APOLLO_RC1,
default_timeout=300.0
)
# Wrap and sample
model = dynex.BQM(bqm)
sampler = dynex.DynexSampler(
model,
config=config,
description="Production optimization run"
)
sampleset = sampler.sample(
num_reads=50, # QPU: keep in range 1–100
annealing_time=200, # QPU: keep in range 10–1000
shots=1, # QPU: up to 5
preprocess=True
)
# Analyze results
print(f"Best energy: {sampleset.first.energy:.4f}")
print(f"Best sample: {sampleset.first.sample}")
print(f"Total samples: {len(sampleset)}")
df = sampleset.to_pandas_dataframe()
print(df.sort_values('energy').head(5))
```
# API Reference
Source: https://dynex.mintlify.app/api-reference/introduction
Complete reference for all Dynex SDK classes and methods
# API Reference
The Dynex SDK exposes a small, focused set of classes. All public API is importable directly from the `dynex` package.
## Core classes
```python theme={null}
import dynex
from dynex import (
DynexConfig, # Configuration and credentials
DynexSampler, # Run annealing jobs
DynexCircuit, # Run gate circuits
BQM, # Binary Quadratic Model wrapper
CQM, # Constrained Quadratic Model wrapper
DQM, # Discrete Quadratic Model wrapper
ComputeBackend, # Backend enum (LOCAL, CPU, GPU, QPU)
QPUModel, # QPU hardware model enum
)
```
## Quick reference
| Class | Purpose |
| ---------------------------------------------- | ------------------------------------------ |
| [`DynexConfig`](/api-reference/dynex-config) | Credentials, backend selection, timeouts |
| [`DynexSampler`](/api-reference/dynex-sampler) | Submit annealing jobs and retrieve results |
| [`BQM`](/api-reference/models) | Wrap a dimod BinaryQuadraticModel |
| [`CQM`](/api-reference/models) | Wrap a dimod ConstrainedQuadraticModel |
| [`DQM`](/api-reference/models) | Wrap a dimod DiscreteQuadraticModel |
| [`DynexCircuit`](/api-reference/dynex-circuit) | Submit gate circuit jobs |
| `ComputeBackend` | Enum: `LOCAL`, `CPU`, `GPU`, `QPU` |
| `QPUModel` | Enum: `APOLLO_RC1`, `APOLLO_10000` |
## Minimal example
```python theme={null}
import dynex
import dimod
from dynex import DynexConfig, ComputeBackend
bqm = dimod.BinaryQuadraticModel({0: -1, 1: -1}, {(0, 1): 2}, 0.0, 'BINARY')
config = DynexConfig(compute_backend=ComputeBackend.GPU)
model = dynex.BQM(bqm)
sampler = dynex.DynexSampler(model, config=config)
sampleset = sampler.sample(num_reads=1000, annealing_time=200)
print(sampleset.first.sample, sampleset.first.energy)
```
## Return types
All samplers return a dimod [`SampleSet`](https://docs.ocean.dwavesys.com/en/stable/docs_dimod/reference/sampleset.html):
```python theme={null}
sampleset.first # Best sample (lowest energy)
sampleset.first.sample # dict: {variable: value}
sampleset.first.energy # float: objective value
sampleset.samples() # Iterator over all samples
sampleset.to_pandas_dataframe() # pandas DataFrame
```
# Model Classes
Source: https://dynex.mintlify.app/api-reference/models
BQM, CQM, DQM — Dynex model wrappers
# Model Classes
Dynex model classes wrap dimod model objects and pass configuration context to the sampler.
```python theme={null}
import dynex
model = dynex.BQM(bqm) # dimod.BinaryQuadraticModel
model = dynex.CQM(cqm) # dimod.ConstrainedQuadraticModel
model = dynex.DQM(dqm) # dimod.DiscreteQuadraticModel
```
***
## `dynex.BQM`
Wraps a dimod `BinaryQuadraticModel`.
```python theme={null}
dynex.BQM(bqm: dimod.BinaryQuadraticModel, config: DynexConfig = None)
```
A dimod BQM object. Variable types can be `'BINARY'` (0/1) or `'SPIN'` (-1/+1).
```python theme={null}
import dimod
import dynex
# BINARY variables (0 or 1)
bqm = dimod.BinaryQuadraticModel(
{'x': -1.0, 'y': -1.0},
{('x', 'y'): 2.0},
0.0,
'BINARY'
)
model = dynex.BQM(bqm)
# SPIN variables (-1 or +1) — Ising model
bqm_ising = dimod.BinaryQuadraticModel(
{0: -0.5, 1: 0.5},
{(0, 1): -1.0},
0.0,
'SPIN'
)
model_ising = dynex.BQM(bqm_ising)
# From QUBO dict
Q = {(0, 0): -1, (1, 1): -1, (0, 1): 2}
bqm_qubo = dimod.BinaryQuadraticModel.from_qubo(Q)
model_qubo = dynex.BQM(bqm_qubo)
```
***
## `dynex.CQM`
Wraps a dimod `ConstrainedQuadraticModel`. Constraints are encoded as first-class objects.
```python theme={null}
dynex.CQM(cqm: dimod.ConstrainedQuadraticModel)
```
```python theme={null}
import dimod
import dynex
cqm = dimod.ConstrainedQuadraticModel()
x, y, z = dimod.Binary('x'), dimod.Binary('y'), dimod.Binary('z')
# Maximize x + 2y + 3z subject to budget constraint
cqm.set_objective(-x - 2*y - 3*z)
cqm.add_constraint(x + y + z <= 2, label='budget')
cqm.add_constraint(x + z >= 1, label='minimum')
model = dynex.CQM(cqm)
```
***
## `dynex.DQM`
Wraps a dimod `DiscreteQuadraticModel`. Each variable can take one of multiple discrete values.
```python theme={null}
dynex.DQM(dqm: dimod.DiscreteQuadraticModel)
```
```python theme={null}
import dimod
import dynex
dqm = dimod.DiscreteQuadraticModel()
dqm.add_variable(3, label='color') # 3 possible values: 0, 1, 2
dqm.add_variable(4, label='size') # 4 possible values: 0, 1, 2, 3
# Biases
dqm.set_linear('color', [1.0, -1.0, 0.0])
dqm.set_linear('size', [0.0, 0.5, -1.0, 0.5])
# Interactions
dqm.set_quadratic('color', 'size', {(0, 0): 1.0, (1, 2): -0.5})
model = dynex.DQM(dqm)
```
***
## Model selection guide
```python theme={null}
def select_model(problem_type):
if problem_type == 'qubo':
# Natural binary optimization, no constraints
return dynex.BQM(dimod.BinaryQuadraticModel.from_qubo(Q))
elif problem_type == 'constrained':
# Hard constraints (budget, capacity, etc.)
cqm = dimod.ConstrainedQuadraticModel()
# ... build cqm ...
return dynex.CQM(cqm)
elif problem_type == 'multi_valued':
# Variables with >2 discrete states
dqm = dimod.DiscreteQuadraticModel()
# ... build dqm ...
return dynex.DQM(dqm)
```
# DynexCircuit
Source: https://dynex.mintlify.app/circuits/dynex-circuit
Execute PennyLane, Qiskit, and OpenQASM circuits on the Dynex platform
# DynexCircuit
`DynexCircuit` executes quantum gate circuits on the Dynex neuromorphic computing platform. It accepts circuits in PennyLane, Qiskit, Cirq, and OpenQASM formats.
## Installation
```bash theme={null}
# PennyLane circuits
pip install pennylane
# Qiskit circuits
pip install qiskit pennylane-qiskit
# OpenQASM circuits — no additional packages needed
```
## Imports
```python theme={null}
from dynex import DynexConfig, ComputeBackend, DynexCircuit
```
## Basic usage
```python theme={null}
import pennylane as qml
from dynex import DynexConfig, ComputeBackend, DynexCircuit
def my_circuit(params):
qml.PauliX(wires=0)
qml.Hadamard(wires=1)
qml.CNOT(wires=[0, 1])
return qml.state()
config = DynexConfig(
compute_backend=ComputeBackend.QPU,
qpu_model='apollo_rc1'
)
dynex_circuit = DynexCircuit(config=config)
result = dynex_circuit.execute(
my_circuit,
params=[],
wires=2,
method='measure'
)
print("Result:", result)
```
## `execute()` — method reference
```python theme={null}
result = dynex_circuit.execute(
circuit, # Circuit function or object
params, # List of circuit parameters
wires, # Number of qubits (int)
method='measure', # Measurement type (see below)
shots=1, # Minimum solutions from network (QPU: up to 5)
description="", # Job description
debugging=False, # Verbose output
num_reads=100, # Parallel samples (QPU: 1–100)
integration_steps=100, # ODE integration depth (QPU: 10–1000)
qpu_max_coeff=9.0, # Max absolute coefficient for QPU auto-scaling
# ... advanced ODE params (alpha, beta, gamma, delta, epsilon, zeta)
block_fee=None, # Priority fee in nanoDNX
)
```
For QPU backends, keep `num_reads` in the range 1–100, `integration_steps` in 10–1000, and `shots` up to 5. These are hardware limits on the current QPU models.
### `method` values
| Value | Returns |
| ------------- | ------------------------------------------------------------ |
| `"measure"` | Samples from a single measurement in the computational basis |
| `"probs"` | Probability of each computational basis state per qubit |
| `"all"` | All solutions as arrays, one per shot |
| `"sampleset"` | dimod `SampleSet` object |
## PennyLane circuits
```python theme={null}
import pennylane as qml
import numpy as np
from dynex import DynexConfig, ComputeBackend, DynexCircuit
def variational_circuit(params):
qml.RX(params[0], wires=0)
qml.RY(params[1], wires=1)
qml.CNOT(wires=[0, 1])
qml.RZ(params[2], wires=0)
return qml.state()
config = DynexConfig(
compute_backend=ComputeBackend.QPU,
qpu_model='apollo_rc1',
use_notebook_output=True
)
dynex_circuit = DynexCircuit(config=config)
params = [np.pi/4, np.pi/3, np.pi/6]
result = dynex_circuit.execute(variational_circuit, params, wires=2, method='probs')
print("Measurement probabilities:", result)
```
## Qiskit circuits
```python theme={null}
from qiskit import QuantumCircuit
from dynex import DynexConfig, ComputeBackend, DynexCircuit
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc.ry(0.5, 1)
config = DynexConfig(
compute_backend=ComputeBackend.QPU,
qpu_model='apollo_rc1'
)
dynex_circuit = DynexCircuit(config=config)
result = dynex_circuit.execute(qc, params=[], wires=2, method='measure')
print("Measurement:", result)
```
## OpenQASM circuits
OpenQASM circuits are provided as strings. No additional plugins required.
```python theme={null}
from dynex import DynexConfig, ComputeBackend, DynexCircuit
qasm_circuit = """
OPENQASM 2.0;
include "qelib1.inc";
qreg q[2];
h q[0];
cx q[0], q[1];
"""
config = DynexConfig(
compute_backend=ComputeBackend.QPU,
qpu_model='apollo_rc1'
)
dynex_circuit = DynexCircuit(config=config)
result = dynex_circuit.execute(qasm_circuit, params=[], wires=2, method='measure')
print("Measurement:", result)
```
## Getting probabilities
```python theme={null}
result = dynex_circuit.execute(
my_circuit, params, wires=3, method='probs'
)
# Returns probability array over 2^n basis states
for i, prob in enumerate(result):
if prob > 0.01:
print(f"|{i:0{3}b}⟩ : {prob:.4f}")
```
## Getting all solutions
```python theme={null}
result = dynex_circuit.execute(
my_circuit, params, wires=2, method='all', shots=3
)
# Returns list of solution arrays, one per shot
for i, solution in enumerate(result):
print(f"Shot {i}: {solution}")
```
## Using as dimod SampleSet
```python theme={null}
sampleset = dynex_circuit.execute(
my_circuit, params, wires=4, method='sampleset'
)
print(sampleset.first.sample)
print(sampleset.first.energy)
```
# Circuit Examples
Source: https://dynex.mintlify.app/circuits/examples
Bell state, Grover, Shor, QFT, and quantum transformer circuits on Dynex
# Circuit Examples
## Bell State (Entanglement)
Creates a maximally entangled 2-qubit Bell state.
```python theme={null}
import pennylane as qml
from dynex import DynexConfig, ComputeBackend, DynexCircuit
def bell_circuit(params):
qml.Hadamard(wires=0)
qml.CNOT(wires=[0, 1])
return qml.state()
config = DynexConfig(compute_backend=ComputeBackend.QPU, qpu_model='apollo_rc1')
circuit = DynexCircuit(config=config)
result = circuit.execute(
bell_circuit, params=[], wires=2, method='probs',
num_reads=50, integration_steps=200, shots=1
)
print("Probabilities:", result)
# Expected: ~0.5 for |00⟩ and |11⟩
```
## Simple 2-Qubit Circuit
RX → RY → CNOT → Hadamard sequence:
```python theme={null}
import pennylane as qml
import numpy as np
def simple_circuit(params):
qml.RX(np.pi, wires=0) # Flip qubit 0
qml.RY(np.pi, wires=1) # Flip qubit 1
qml.CNOT(wires=[0, 1]) # Entangle
qml.Hadamard(wires=0) # Superposition
return qml.state()
result = circuit.execute(simple_circuit, params=[], wires=2, method='measure')
```
Notebooks: [PennyLane](https://github.com/Dynex-Development/awesome-dynex/blob/main/quantum_circuits/circuit_example_pennylane.ipynb) · [OpenQASM](https://github.com/Dynex-Development/awesome-dynex/blob/main/quantum_circuits/circuit_example_openqasm.ipynb) · [Qiskit](https://github.com/Dynex-Development/awesome-dynex/blob/main/quantum_circuits/circuit_example_qiskit.ipynb)
## Medium Circuit (3 Qubits)
Demonstrates Hadamard, CNOT, RX, CRZ, T, Toffoli, SWAP sequence:
```python theme={null}
def medium_circuit(params):
qml.Hadamard(wires=0)
qml.CNOT(wires=[0, 1])
qml.RX(0.3, wires=1)
qml.CRZ(0.1, wires=[0, 1])
qml.T(wires=1)
qml.Toffoli(wires=[0, 1, 2])
qml.SWAP(wires=[1, 2])
return qml.state()
```
[Notebook](https://github.com/Dynex-Development/awesome-dynex/blob/main/quantum_circuits/circuit_example_medium.ipynb)
## 13-Qubit Full Adder
Implements quantum addition via QFT-based phase encoding:
```python theme={null}
import pennylane as qml
import numpy as np
def kfourier(value, wires):
for i, wire in enumerate(wires):
qml.PhaseShift(value * np.pi / (2**i), wires=wire)
def adder_circuit(params):
a, b = int(params[0]), int(params[1])
n_bits = 13
# Encode 'a' via basis embedding
qml.BasisEmbedding(a, wires=range(n_bits))
# QFT
qml.QFT(wires=range(n_bits))
# Add 'b' in Fourier domain
kfourier(b, range(n_bits))
# Inverse QFT
qml.adjoint(qml.QFT)(wires=range(n_bits))
return qml.state()
result = circuit.execute(
adder_circuit, params=[42, 13], wires=13, method='measure',
num_reads=50, integration_steps=200, shots=1
)
```
[Notebook](https://github.com/Dynex-Development/awesome-dynex/blob/main/quantum_circuits/circuit_example_nbit_adder.ipynb)
## Grover's Algorithm (Integer Factorization)
Uses quantum amplitude amplification to find prime factors:
```python theme={null}
def grover_factorization(params, n=15):
import pennylane as qml
import numpy as np
wires_p = [0, 1, 2]
wires_q = [3, 4, 5]
wires_solution = list(range(6, 6 + 2*len(wires_p)))
# Superposition over factor candidates
for wire in wires_p + wires_q:
qml.Hadamard(wires=wire)
# Multiply p * q into solution register (QFT-based)
# ... multiplication circuit ...
# Grover amplitude amplification
# ... FlipSign + Grover operator ...
return qml.probs(wires=wires_p + wires_q)
result = circuit.execute(
grover_factorization, params=[], wires=12, method='probs',
num_reads=50, integration_steps=500, shots=1
)
```
[Full notebook](https://github.com/Dynex-Development/awesome-dynex/blob/main/quantum_circuits/circuit_example_grover.ipynb)
## Shor's Algorithm
Period-finding circuit for integer factorization of N:
```python theme={null}
# Full implementation in notebook
# Factorizes N=35 with base a=12
```
The circuit uses:
1. Hadamard gates for superposition over estimate qubits
2. Controlled modular exponentiation unitaries
3. Inverse QFT to extract period information
4. Post-processing to derive prime factors
[Full notebook](https://github.com/Dynex-Development/awesome-dynex/blob/main/quantum_circuits/circuit_example_shor.ipynb)
## Quantum Self-Attention Transformer
Quantum analogue of the transformer attention mechanism for NLP:
The circuit:
1. Tokenizes sentences into word embeddings (Word2Vec, 8-dim)
2. Encodes embeddings via `BasisEmbedding`
3. Applies 3 rotation layers (RX, RY, RZ) with entanglement (CRZ, CNOT)
4. Applies QFT + Grover operator for amplitude amplification
5. Measures Z-basis expectation values → softmax → attention weights
6. Generates new sentence by combining weights with word embeddings
```python theme={null}
# See full implementation
# https://github.com/Dynex-Development/awesome-dynex/blob/main/quantum_circuits/circuit_example_quantum_transformer.ipynb
```
[Full notebook](https://github.com/Dynex-Development/awesome-dynex/blob/main/quantum_circuits/circuit_example_quantum_transformer.ipynb)
## All circuit notebooks
| Circuit | Qubits | Description |
| ---------------------------------------------------------------------------------------------------------------------------------------------- | ------ | ---------------------------------------- |
| [Simple PennyLane](https://github.com/Dynex-Development/awesome-dynex/blob/main/quantum_circuits/circuit_example_pennylane.ipynb) | 2 | RX, RY, CNOT, H |
| [Simple OpenQASM](https://github.com/Dynex-Development/awesome-dynex/blob/main/quantum_circuits/circuit_example_openqasm.ipynb) | 2 | Same in QASM format |
| [Simple Qiskit](https://github.com/Dynex-Development/awesome-dynex/blob/main/quantum_circuits/circuit_example_qiskit.ipynb) | 2 | Same in Qiskit |
| [Medium](https://github.com/Dynex-Development/awesome-dynex/blob/main/quantum_circuits/circuit_example_medium.ipynb) | 3 | H, CNOT, T, Toffoli, SWAP |
| [Complex 1](https://github.com/Dynex-Development/awesome-dynex/blob/main/quantum_circuits/circuit_example_complex_1.ipynb) | 4 | Full entanglement + controlled rotations |
| [Complex 2](https://github.com/Dynex-Development/awesome-dynex/blob/main/quantum_circuits/circuit_example_complex_2.ipynb) | 12 | Large-scale entanglement |
| [Full Adder](https://github.com/Dynex-Development/awesome-dynex/blob/main/quantum_circuits/circuit_example_nbit_adder.ipynb) | 13 | QFT-based addition |
| [Grover](https://github.com/Dynex-Development/awesome-dynex/blob/main/quantum_circuits/circuit_example_grover.ipynb) | 12 | Integer factorization |
| [Shor](https://github.com/Dynex-Development/awesome-dynex/blob/main/quantum_circuits/circuit_example_shor.ipynb) | 8 | Period finding, N=35 |
| [Quantum Transformer](https://github.com/Dynex-Development/awesome-dynex/blob/main/quantum_circuits/circuit_example_quantum_transformer.ipynb) | 8 | NLP self-attention |
# Quantum Gates
Source: https://dynex.mintlify.app/circuits/overview
Quantum gate reference for PennyLane, Qiskit, and OpenQASM on Dynex
# Quantum Gates on Dynex
Quantum gates are the building blocks of quantum circuits. Each gate performs a specific unitary operation on one or more qubits, altering their probability amplitudes and phases. Dynex supports all standard gates via PennyLane, Qiskit, and OpenQASM.
## Single-Qubit Gates
### Pauli-X (NOT gate)
Flips the qubit state: X|0⟩ = |1⟩, X|1⟩ = |0⟩.
| Framework | Syntax |
| --------- | --------------------- |
| PennyLane | `qml.PauliX(wires=0)` |
| OpenQASM | `x q[0];` |
| Qiskit | `qc.x(0)` |
### Pauli-Y
Phase flip then bit flip: Y|0⟩ = i|1⟩, Y|1⟩ = −i|0⟩.
| Framework | Syntax |
| --------- | --------------------- |
| PennyLane | `qml.PauliY(wires=0)` |
| OpenQASM | `y q[0];` |
| Qiskit | `qc.y(0)` |
### Pauli-Z
Phase flip: Z|0⟩ = |0⟩, Z|1⟩ = −|1⟩.
| Framework | Syntax |
| --------- | --------------------- |
| PennyLane | `qml.PauliZ(wires=0)` |
| OpenQASM | `z q[0];` |
| Qiskit | `qc.z(0)` |
### Hadamard (H)
Creates equal superposition: H|0⟩ = (|0⟩ + |1⟩)/√2.
| Framework | Syntax |
| --------- | ----------------------- |
| PennyLane | `qml.Hadamard(wires=0)` |
| OpenQASM | `h q[0];` |
| Qiskit | `qc.h(0)` |
### T Gate
Applies a π/4 phase shift. Non-Clifford gate essential for universal quantum computation.
| Framework | Syntax |
| --------- | ---------------- |
| PennyLane | `qml.T(wires=0)` |
| OpenQASM | `t q[0];` |
| Qiskit | `qc.t(0)` |
## Rotation Gates
### RX, RY, RZ
Single-axis rotations by angle `θ`.
| Gate | PennyLane | Qiskit |
| ---- | ------------------------ | ----------------- |
| RX | `qml.RX(theta, wires=0)` | `qc.rx(theta, 0)` |
| RY | `qml.RY(theta, wires=0)` | `qc.ry(theta, 0)` |
| RZ | `qml.RZ(theta, wires=0)` | `qc.rz(theta, 0)` |
## Two-Qubit Gates
### CNOT (CX)
Flips target qubit if control qubit is |1⟩.
| Framework | Syntax |
| --------- | ------------------------ |
| PennyLane | `qml.CNOT(wires=[0, 1])` |
| OpenQASM | `cx q[0], q[1];` |
| Qiskit | `qc.cx(0, 1)` |
### Controlled-Z (CZ)
Applies Z to target if control is |1⟩.
| Framework | Syntax |
| --------- | ---------------------- |
| PennyLane | `qml.CZ(wires=[0, 1])` |
| OpenQASM | `cz q[0], q[1];` |
| Qiskit | `qc.cz(0, 1)` |
### SWAP (Fredkin)
Exchanges the states of two qubits.
| Framework | Syntax |
| --------- | ------------------------ |
| PennyLane | `qml.SWAP(wires=[0, 1])` |
| OpenQASM | `swap q[0], q[1];` |
| Qiskit | `qc.swap(0, 1)` |
### Controlled Rotations (CRX, CRY, CRZ)
Apply rotation to target qubit if control is |1⟩.
| Gate | PennyLane | Qiskit |
| ---- | ------------------------------ | --------------------- |
| CRX | `qml.CRX(theta, wires=[0, 1])` | `qc.crx(theta, 0, 1)` |
| CRY | `qml.CRY(theta, wires=[0, 1])` | `qc.cry(theta, 0, 1)` |
| CRZ | `qml.CRZ(theta, wires=[0, 1])` | `qc.crz(theta, 0, 1)` |
### Controlled Phase Shift
Applies phase shift to target if control is |1⟩.
| Framework | Syntax |
| --------- | ----------------------------------------------- |
| PennyLane | `qml.ControlledPhaseShift(theta, wires=[0, 1])` |
| Qiskit | `qc.cp(theta, 0, 1)` |
## Three-Qubit Gates
### Toffoli (CCNOT)
Flips target if both control qubits are |1⟩.
| Framework | Syntax |
| --------- | ------------------------------ |
| PennyLane | `qml.Toffoli(wires=[0, 1, 2])` |
| OpenQASM | `ccx q[0], q[1], q[2];` |
| Qiskit | `qc.ccx(0, 1, 2)` |
## Advanced Operations
### Quantum Fourier Transform (QFT)
```python theme={null}
# PennyLane
def qft(wires):
qml.QFT(wires=wires)
# Qiskit
from qiskit.circuit.library import QFT
qc.append(QFT(num_qubits).decompose(), range(num_qubits))
```
### Adjoint (Dagger)
```python theme={null}
# PennyLane
qml.adjoint(qml.Hadamard)(wires=0)
# Qiskit
qc.h(0).inverse()
```
### Basis Embedding
Encodes classical binary data into quantum states:
```python theme={null}
# PennyLane
qml.BasisEmbedding(features, wires=[0, 1, 2])
```
### Controlled Unitary (CU)
```python theme={null}
# PennyLane
qml.ControlledQubitUnitary(U_matrix, control_wires=[0], wires=[1])
```
## Next: Running circuits on Dynex
See [DynexCircuit Class](/circuits/dynex-circuit) to learn how to execute these gates on the Dynex platform.
# Grover's Algorithm
Source: https://dynex.mintlify.app/examples/algorithms/grover
Integer factorization via quantum amplitude amplification on Dynex
# Grover's Algorithm on Dynex
[Grover's algorithm](https://en.wikipedia.org/wiki/Grover%27s_algorithm) provides a quadratic speedup for unstructured search problems. On Dynex, it is implemented as a quantum gate circuit using PennyLane and can be used for integer factorization, database search, and optimization.
## How it works
1. **Hadamard gates** create superposition over all candidate states in `wires_p` and `wires_q` (representing prime factor candidates)
2. **Multiplication function** uses the QFT and controlled phase rotations (Kfourier) to compute p × q, storing the result in `wires_solution`
3. **FlipSign operator** marks the target state (the correct factorization)
4. **Grover operator** performs amplitude amplification, iteratively increasing the probability of measuring the correct factors
5. The circuit returns **probabilities** of each factor combination
## Implementation
```python theme={null}
import pennylane as qml
import numpy as np
from dynex import DynexConfig, ComputeBackend, DynexCircuit
def kfourier(value, wires):
"""Apply phase rotations for QFT-based multiplication."""
for i, wire in enumerate(wires):
qml.PhaseShift(value * np.pi / (2**i), wires=wire)
def flip_sign(state, wires):
"""Mark the target state with a phase flip."""
for i, wire in enumerate(wires):
if not (state >> i & 1):
qml.PauliX(wires=wire)
qml.ctrl(qml.PauliZ, control=wires[:-1])(wires=wires[-1])
for i, wire in enumerate(wires):
if not (state >> i & 1):
qml.PauliX(wires=wire)
def grover_circuit(params):
n = int(params[0]) # Number to factorize
bits = int(np.ceil(np.log2(n + 1)))
wires_p = list(range(bits))
wires_q = list(range(bits, 2 * bits))
wires_solution = list(range(2 * bits, 2 * bits + 2 * bits))
# Step 1: Superposition over candidate factors
for wire in wires_p + wires_q:
qml.Hadamard(wires=wire)
# Step 2: QFT on solution register
qml.QFT(wires=wires_solution)
# Step 3: Grover iterations
iterations = int(np.floor(np.pi / 4 * np.sqrt(2**bits)))
for _ in range(iterations):
# Oracle: mark correct factorization
flip_sign(n, wires_solution)
# Diffusion: amplitude amplification
for wire in wires_p + wires_q:
qml.Hadamard(wires=wire)
flip_sign(0, wires_p + wires_q)
for wire in wires_p + wires_q:
qml.Hadamard(wires=wire)
return qml.probs(wires=wires_p + wires_q)
# Factorize n=15
config = DynexConfig(
compute_backend=ComputeBackend.QPU,
qpu_model='apollo_rc1'
)
circuit = DynexCircuit(config=config)
probs = circuit.execute(
grover_circuit,
params=[15],
wires=12,
method='probs'
)
# Find highest probability factors
best_idx = np.argmax(probs)
bits = 4
p = best_idx >> bits
q = best_idx & ((1 << bits) - 1)
print(f"Most likely factors of 15: {p} × {q} = {p*q}")
```
## Results
Grover's algorithm concentrates probability amplitude on the correct factor pairs. For N=15:
| Factor pair | Expected probability |
| ----------- | -------------------- |
| 3 × 5 | High (\~0.5) |
| 5 × 3 | High (\~0.5) |
| Others | Near zero |
## Full notebook
[circuit\_example\_grover.ipynb](https://github.com/Dynex-Development/awesome-dynex/blob/main/quantum_circuits/circuit_example_grover.ipynb)
# Optimization Algorithms
Source: https://dynex.mintlify.app/examples/algorithms/optimization
MaxCut, graph partitioning, job sequencing, and combinatorial problems on Dynex
# Optimization Algorithms
Dynex excels at NP-hard combinatorial optimization problems. All examples use the annealing interface (BQM/QUBO formulations).
## MaxCut
Partition graph vertices into two sets to maximize the number of edges between sets.
```python theme={null}
import dynex
import dimod
import networkx as nx
from dynex import DynexConfig, ComputeBackend
# Build a random graph
G = nx.gnp_random_graph(20, 0.4, seed=42)
# MaxCut QUBO: maximize sum of (1 - x_i*x_j) for each edge (i,j)
# Equivalent: minimize sum of x_i*x_j - constant
Q = {}
for i, j in G.edges():
Q[(i, i)] = Q.get((i, i), 0) - 1
Q[(j, j)] = Q.get((j, j), 0) - 1
Q[(i, j)] = Q.get((i, j), 0) + 2
bqm = dimod.BinaryQuadraticModel.from_qubo(Q)
model = dynex.BQM(bqm)
config = DynexConfig(compute_backend=ComputeBackend.GPU)
sampler = dynex.DynexSampler(model, config=config)
sampleset = sampler.sample(num_reads=1000, annealing_time=200)
best = sampleset.first.sample
partition_0 = [v for v, val in best.items() if val == 0]
partition_1 = [v for v, val in best.items() if val == 1]
cut_edges = [(u, v) for u, v in G.edges() if best[u] != best[v]]
print(f"Cut size: {len(cut_edges)}")
```
[G70 MaxCut benchmark notebook](https://github.com/Dynex-Development/awesome-dynex/blob/main/benchmarks/G70_dynex.ipynb)
## Number Partitioning
Divide a set of numbers into two subsets with equal (or near-equal) sums.
```python theme={null}
import dynex
import dimod
from dynex import DynexConfig, ComputeBackend
numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3]
n = len(numbers)
# QUBO: minimize (sum_i s_i * n_i)^2 where s_i in {-1, +1}
# Binary encoding: x_i = (s_i + 1) / 2 -> s_i = 2*x_i - 1
Q = {}
for i in range(n):
for j in range(n):
Q[(i, j)] = Q.get((i, j), 0) + numbers[i] * numbers[j]
bqm = dimod.BinaryQuadraticModel.from_qubo(Q)
model = dynex.BQM(bqm)
config = DynexConfig(compute_backend=ComputeBackend.GPU)
sampler = dynex.DynexSampler(model, config=config)
sampleset = sampler.sample(num_reads=500, annealing_time=100)
assignment = sampleset.first.sample
set_a = [numbers[i] for i, v in assignment.items() if v == 0]
set_b = [numbers[i] for i, v in assignment.items() if v == 1]
print(f"Set A: {set_a} (sum={sum(set_a)})")
print(f"Set B: {set_b} (sum={sum(set_b)})")
```
[Number partitioning notebook](https://github.com/Dynex-Development/awesome-dynex/blob/main/optimization/quantum_number_partitioning.ipynb)
## Vertex Cover
Find the minimum set of vertices that covers every edge in a graph.
```python theme={null}
import dynex, dimod, networkx as nx
from dynex import DynexConfig, ComputeBackend
G = nx.petersen_graph()
penalty = 10.0 # Constraint penalty weight
Q = {}
# Objective: minimize number of selected vertices
for v in G.nodes():
Q[(v, v)] = Q.get((v, v), 0) + 1
# Constraint: for each edge, at least one endpoint must be in cover
for u, v in G.edges():
Q[(u, u)] = Q.get((u, u), 0) - penalty
Q[(v, v)] = Q.get((v, v), 0) - penalty
Q[(u, v)] = Q.get((u, v), 0) + penalty
bqm = dimod.BinaryQuadraticModel.from_qubo(Q)
model = dynex.BQM(bqm)
config = DynexConfig(compute_backend=ComputeBackend.GPU)
sampler = dynex.DynexSampler(model, config=config)
sampleset = sampler.sample(num_reads=1000, annealing_time=200)
cover = [v for v, val in sampleset.first.sample.items() if val == 1]
print(f"Vertex cover: {cover} (size={len(cover)})")
```
[Vertex cover notebook](https://github.com/Dynex-Development/awesome-dynex/blob/main/optimization/quantum_vertex_cover.ipynb)
## All optimization notebooks
| Problem | Notebook |
| --------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- |
| MaxCut | [G70 benchmark](https://github.com/Dynex-Development/awesome-dynex/blob/main/benchmarks/G70_dynex.ipynb) |
| Number partitioning | [quantum\_number\_partitioning.ipynb](https://github.com/Dynex-Development/awesome-dynex/blob/main/optimization/quantum_number_partitioning.ipynb) |
| Vertex cover | [quantum\_vertex\_cover.ipynb](https://github.com/Dynex-Development/awesome-dynex/blob/main/optimization/quantum_vertex_cover.ipynb) |
| Graph partitioning | [quantum\_graph\_partitioning.ipynb](https://github.com/Dynex-Development/awesome-dynex/blob/main/optimization/quantum_graph_partitioning.ipynb) |
| Set cover | [quantum\_set\_cover.ipynb](https://github.com/Dynex-Development/awesome-dynex/blob/main/optimization/quantum_set_cover.ipynb) |
| Job sequencing | [quantum\_job\_sequencing.ipynb](https://github.com/Dynex-Development/awesome-dynex/blob/main/optimization/quantum_job_sequencing.ipynb) |
| k-Means clustering | [quantum\_kmeans\_clustering.ipynb](https://github.com/Dynex-Development/awesome-dynex/blob/main/optimization/quantum_kmeans_clustering.ipynb) |
| Binary ILP | [quantum\_BILP.ipynb](https://github.com/Dynex-Development/awesome-dynex/blob/main/optimization/quantum_BILP.ipynb) |
| Integer factorization | [example\_integer\_factorisation.ipynb](https://github.com/Dynex-Development/awesome-dynex/blob/main/misc/example_integer_factorisation.ipynb) |
| n-Queens | [QuantumnQueenProblem.ipynb](https://github.com/Dynex-Development/awesome-dynex/blob/main/advanced_applications/QuantumnQueenProblem.ipynb) |
| Sudoku | [QuantumSudoku.ipynb](https://github.com/Dynex-Development/awesome-dynex/blob/main/advanced_applications/QuantumSudoku.ipynb) |
| Protein folding | [QuantumProteinFolding.ipynb](https://github.com/Dynex-Development/awesome-dynex/blob/main/advanced_applications/QuantumProteinFolding.ipynb) |
| RNA folding | [example\_rna\_folding.ipynb](https://github.com/Dynex-Development/awesome-dynex/blob/main/misc/example_rna_folding.ipynb) |
| Multi-vehicle routing | [quantum\_multi\_vehicle\_routing](https://github.com/dynexcoin/quantum_multi_vehicle_routing) |
| Workforce scheduling | [quantum\_workforce\_scheduling](https://github.com/dynexcoin/quantum_workforce_scheduling) |
| Flow shop scheduling | [quantum\_flow\_scheduling](https://github.com/dynexcoin/quantum_flow_scheduling) |
# Shor's Algorithm
Source: https://dynex.mintlify.app/examples/algorithms/shor
Period-finding for efficient integer factorization on Dynex
# Shor's Algorithm on Dynex
[Shor's algorithm](https://en.wikipedia.org/wiki/Shor%27s_algorithm) factorizes integers exponentially faster than the best known classical algorithm. It reduces factorization to **period finding** using the quantum Fourier transform.
## How it works
1. **Quantum state preparation** — superposition via Hadamard gates on estimate qubits; target qubit initialized to |1⟩ via Pauli-X
2. **Controlled unitaries** — powers of modular exponentiation unitary U\_NA (from integers a and N) applied to target qubits, controlled by estimate qubits
3. **Inverse QFT** — extracts phase information related to the period r of f(x) = a^x mod N
4. **Measurement** — samples encode period information
5. **Post-processing** — continued fractions + GCD to extract prime factors from period r
## Example: Factorize N=35
```python theme={null}
import pennylane as qml
import numpy as np
from fractions import Fraction
from math import gcd
from dynex import DynexConfig, ComputeBackend, DynexCircuit
N = 35 # Number to factorize
a = 12 # Randomly chosen base (gcd(a, N) == 1)
def build_U_NA(a, N, wires):
"""Construct controlled modular exponentiation matrix."""
dim = 2 ** len(wires)
U = np.eye(dim, dtype=complex)
for x in range(dim):
y = pow(a, x, N)
U[x, x] = 0
U[y, x] = 1
return U
def shor_circuit(params):
n_estimate = 8 # Qubits for period estimation
n_target = 1
estimate_wires = list(range(n_estimate))
target_wires = [n_estimate]
# Initialize target qubit to |1⟩
qml.PauliX(wires=target_wires[0])
# Superposition on estimate qubits
for wire in estimate_wires:
qml.Hadamard(wires=wire)
# Controlled modular exponentiation
for i, wire in enumerate(estimate_wires):
power = 2 ** i
U = build_U_NA(pow(a, power, N), N, target_wires)
qml.ctrl(qml.QubitUnitary, control=wire)(U, wires=target_wires)
# Inverse QFT on estimate register
qml.adjoint(qml.QFT)(wires=estimate_wires)
return qml.sample(wires=estimate_wires)
config = DynexConfig(
compute_backend=ComputeBackend.QPU,
qpu_model='apollo_rc1'
)
circuit = DynexCircuit(config=config)
sample = circuit.execute(shor_circuit, params=[], wires=9, method='measure')
# Post-process: find period via continued fractions
measured = int(''.join(str(int(b)) for b in sample), 2)
phase = measured / (2 ** 8)
frac = Fraction(phase).limit_denominator(N)
r = frac.denominator
# Extract factors
if r % 2 == 0:
factor1 = gcd(pow(a, r//2) - 1, N)
factor2 = gcd(pow(a, r//2) + 1, N)
print(f"N={N} = {factor1} × {factor2}")
```
## Full notebook
[circuit\_example\_shor.ipynb](https://github.com/Dynex-Development/awesome-dynex/blob/main/quantum_circuits/circuit_example_shor.ipynb)
# BQM Usage Examples
Source: https://dynex.mintlify.app/examples/basic/bqm-usage
Working with Binary Quadratic Models in Dynex SDK
# BQM Usage Examples
Learn how to create and manipulate Binary Quadratic Models for quantum computing.
## Creating BQMs
### From Scratch
```python theme={null}
import dimod
# Method 1: Direct construction
bqm = dimod.BinaryQuadraticModel(
linear={0: 1.0, 1: -1.0, 2: 0.5},
quadratic={(0, 1): 0.5, (1, 2): -0.3},
offset=0.0,
vartype='BINARY'
)
```
### From QUBO Matrix
```python theme={null}
import numpy as np
# Create QUBO matrix
Q = np.array([
[1.0, 0.5, 0.0],
[0.0, -1.0, -0.3],
[0.0, 0.0, 0.5]
])
# Convert to BQM
bqm = dimod.BinaryQuadraticModel.from_qubo(Q)
```
## BQM Operations
### Scaling for QPU
```python theme={null}
import dynex
# Scale BQM coefficients for QPU compatibility
scaled_bqm, scale_factor = dynex.scale_bqm_to_range(bqm, max_abs_coeff=9.0)
print(f"Original max coefficient: {max(abs(c) for c in bqm.linear.values())}")
print(f"Scaled max coefficient: {max(abs(c) for c in scaled_bqm.linear.values())}")
print(f"Scale factor: {scale_factor}")
```
### BQM Analysis
```python theme={null}
# Analyze BQM properties
print(f"Number of variables: {len(bqm.variables)}")
print(f"Number of interactions: {len(bqm.quadratic)}")
print(f"Variable types: {bqm.vartype}")
print(f"Energy range: [{bqm.lower_bound}, {bqm.upper_bound}]")
```
## Sampling Different BQM Types
### SPIN vs BINARY
```python theme={null}
# BINARY variables (0, 1)
binary_bqm = dimod.BinaryQuadraticModel(
{0: 1, 1: -1}, {(0, 1): 2}, 0.0, 'BINARY'
)
# SPIN variables (-1, +1)
spin_bqm = dimod.BinaryQuadraticModel(
{0: 1, 1: -1}, {(0, 1): 2}, 0.0, 'SPIN'
)
# Sample both
for name, bqm in [("BINARY", binary_bqm), ("SPIN", spin_bqm)]:
model = dynex.BQM(bqm)
sampler = dynex.DynexSampler(model)
sampleset = sampler.sample(num_reads=10)
print(f"{name} result: {sampleset.first.sample}")
```
## Real-World Example: Max-Cut Problem
```python theme={null}
import networkx as nx
# Create a graph
G = nx.Graph()
G.add_edges_from([(0, 1), (1, 2), (2, 3), (3, 0), (0, 2)])
# Formulate as QUBO
Q = {}
for u, v in G.edges():
Q[(u, u)] = Q.get((u, u), 0) + 1
Q[(v, v)] = Q.get((v, v), 0) + 1
Q[(u, v)] = Q.get((u, v), 0) - 2
# Convert to BQM and solve
bqm = dimod.BinaryQuadraticModel.from_qubo(Q)
model = dynex.BQM(bqm)
sampler = dynex.DynexSampler(model)
sampleset = sampler.sample(num_reads=100)
# Interpret results
solution = sampleset.first.sample
partition_0 = [node for node, val in solution.items() if val == 0]
partition_1 = [node for node, val in solution.items() if val == 1]
print(f"Partition 0: {partition_0}")
print(f"Partition 1: {partition_1}")
print(f"Cut size: {-sampleset.first.energy}")
```
## Next Steps
* Explore [Machine Learning with QRBMs](/examples/ml/qrbm)
* Learn about [Optimization Problems](/examples/optimization/tsp)
* Check [API Reference](/api-reference/models/bqm)
# Simple BQM Sampling
Source: https://dynex.mintlify.app/examples/basic/simple-sampling
Basic example of sampling a Binary Quadratic Model
# Simple BQM Sampling
This example demonstrates the basic usage of Dynex SDK for sampling Binary Quadratic Models.
## Problem Setup
```python theme={null}
import dynex
import dimod
# Create a simple BQM
bqm = dimod.BinaryQuadraticModel(
{0: 1.0, 1: -1.0}, # Linear coefficients
{(0, 1): 0.5}, # Quadratic coefficients
0.0, # Offset
'BINARY'
)
```
## CPU Sampling
```python theme={null}
from dynex import ComputeBackend, DynexConfig
# Configure for CPU backend
config = DynexConfig(compute_backend=ComputeBackend.CPU)
# Create model and sampler
model = dynex.BQM(bqm)
sampler = dynex.DynexSampler(model, config=config)
# Sample the problem
sampleset = sampler.sample(num_reads=100)
# Print results
print(f"Best solution: {sampleset.first.sample}")
print(f"Best energy: {sampleset.first.energy}")
```
## QPU Sampling
```python theme={null}
from dynex import QPUModel
# Configure for QPU backend
config = DynexConfig(
compute_backend=ComputeBackend.QPU,
qpu_model=QPUModel.APOLLO_RC1
)
sampler = dynex.DynexSampler(model, config=config)
sampleset = sampler.sample(num_reads=10, annealing_time=200) # QPU: num_reads 1–100, annealing_time 10–1000
print(f"Quantum solution: {sampleset.first.sample}")
```
## Next Steps
* Try [BQM Usage Examples](/examples/basic/bqm-usage)
* Explore [Machine Learning Examples](/examples/ml/qrbm)
* Learn about [Configuration Options](/guides/configuration)
# Quantum Machine Learning
Source: https://dynex.mintlify.app/examples/ml/overview
QSVM, QPCA, QBM, QNN, and feature selection on Dynex
# Quantum Machine Learning
Dynex supports a range of quantum machine learning algorithms. Because neuromorphic and quantum computing share similar features, these algorithms run without the limitations of limited qubits, error correction requirements, or hardware availability.
## Supported algorithms
Quantum Support Vector Machine — classification with quantum kernel functions
Quantum (Restricted) Boltzmann Machine — generative models via quantum annealing
Drop-in PyTorch layers backed by Dynex computation
scikit-learn plugin for quantum-enhanced feature selection
## Algorithm Overview
### Quantum Support Vector Machine (QSVM)
QSVM uses a quantum kernel function for classification. It leverages quantum superposition and feature mapping to potentially provide computational advantages over classical SVM, especially on high-dimensional data.
* [QSVM notebook](https://github.com/Dynex-Development/awesome-dynex/blob/main/machine_learning/example_support_vector_machine.ipynb)
* [QSVM with PyTorch](https://github.com/Dynex-Development/awesome-dynex/blob/main/machine_learning/Example_SVM_pytorch.ipynb)
* Scientific background: Rounds & Goddard, "Optimal feature selection in credit scoring and classification using a quantum annealer" (2017)
### Quantum Principal Component Analysis (QPCA)
Quantum version of classical PCA using quantum linear algebra for dimensionality reduction. Can process high-dimensional feature spaces more efficiently than classical approaches.
### Quantum Neural Networks (QNN)
Quantum counterparts of classical neural networks. Leverage superposition and entanglement to process and manipulate data, learning complex patterns for classification and regression.
### Quantum Boltzmann Machines (QBM)
Quantum analogues of classical Boltzmann Machines. Use quantum annealing to sample from probability distributions and learn patterns in data for unsupervised learning.
* [QBM notebook](https://github.com/Dynex-Development/awesome-dynex/blob/main/machine_learning/example_quantum_boltzmann_machine_QBM.ipynb)
### Quantum K-Means Clustering
Quantum-inspired K-means using quantum algorithms to accelerate clustering. Explores multiple cluster assignments simultaneously via quantum parallelism.
* [k-Means notebook](https://github.com/Dynex-Development/awesome-dynex/blob/main/optimization/quantum_kmeans_clustering.ipynb)
### QBoost
Ensemble method inspired by Google & D-Wave's 2008 paper. Formulates binary classification as QUBO and uses quantum optimization to learn classifier weights that minimize training error.
* [QBoost implementation](https://github.com/Dynex-Development/awesome-dynex/blob/main/machine_learning/Dynex_Scikit-Learn_Plugin.ipynb)
## Quantum Natural Language Processing (QNLP)
End-to-end QNLP pipeline on Dynex: web data collection, model training, and real-time inference from a ChatGPT-style bot.
Video demo: quantum NLP model training and inference on the Dynex platform.
## Quantum Transformer (QTransform)
Quantum analogue of the transformer attention mechanism for NLP and generative tasks. Combines the self-attention mechanism with quantum computing to improve sequential data processing.
Video demo: quantum transformer implementation on Dynex for NLP tasks.
## Publications
Key scientific papers backing these implementations:
* Dixit et al. (2021). "Training Restricted Boltzmann Machines With a D-Wave Quantum Annealer." *Front. Phys.* 9:589626
* Manukian et al. (2020). "Mode-assisted unsupervised learning of restricted Boltzmann machines." *Communications Physics* 3:105
* Neumann (2024). "Advancements in Unsupervised Learning: Mode-Assisted QRBM Leveraging Neuromorphic Computing." *IJBIC* 3(1):91–103
* Rounds & Goddard (2017). "Optimal feature selection in credit scoring and classification using a quantum annealer"
* Bhatia & Phillipson (2021). "Performance Analysis of Support Vector Machine on the D-Wave Quantum Annealer." *ICCS 2021*
# Quantum RBM / QBM
Source: https://dynex.mintlify.app/examples/ml/qrbm
Quantum Restricted Boltzmann Machine via quantum annealing on Dynex
# Quantum Restricted Boltzmann Machine (QRBM)
The Quantum Restricted Boltzmann Machine uses quantum annealing on Dynex to sample from the RBM's probability distribution. During training, the quantum sampler replaces the classical Gibbs sampler, leveraging quantum tunneling to escape local minima and find better solutions.
## How it works
1. **Initialize** visible and hidden unit weights
2. **Positive phase** — clamp visible units to training data, compute hidden activations
3. **Negative phase** — use Dynex quantum annealing to sample from model distribution (replaces classical Gibbs sampling)
4. **Update weights** using contrastive divergence: `ΔW = lr * (⟨vh⟩_data - ⟨vh⟩_model)`
5. Repeat for all training batches
## Installation
```bash theme={null}
pip install dynex torch numpy
```
## PyTorch RBM with Dynex
```python theme={null}
import torch
import numpy as np
import dynex
import dimod
from dynex import DynexConfig, ComputeBackend
class DynexRBM:
def __init__(self, n_visible, n_hidden, config):
self.n_visible = n_visible
self.n_hidden = n_hidden
self.config = config
# Initialize weights and biases
self.W = torch.randn(n_visible, n_hidden) * 0.01
self.b_v = torch.zeros(n_visible)
self.b_h = torch.zeros(n_hidden)
def _build_rbm_qubo(self, v_data):
"""Build QUBO for joint sampling of visible and hidden units."""
Q = {}
batch_avg_v = v_data.mean(0).numpy()
# Hidden unit biases
for j in range(self.n_hidden):
bias = float(self.b_h[j])
for i in range(self.n_visible):
bias += float(self.W[i, j]) * batch_avg_v[i]
Q[(j, j)] = Q.get((j, j), 0) - bias
# Weight interactions (hidden-hidden via visible)
for j1 in range(self.n_hidden):
for j2 in range(j1+1, self.n_hidden):
interaction = sum(
float(self.W[i, j1]) * float(self.W[i, j2])
for i in range(self.n_visible)
)
if abs(interaction) > 1e-6:
Q[(j1, j2)] = Q.get((j1, j2), 0) + interaction
return Q
def sample_hidden(self, v_data, num_reads=1000, annealing_time=200):
"""Sample hidden units given visible data using Dynex."""
Q = self._build_rbm_qubo(v_data)
bqm = dimod.BinaryQuadraticModel.from_qubo(Q)
model = dynex.BQM(bqm)
sampler = dynex.DynexSampler(model, config=self.config, logging=False)
sampleset = sampler.sample(num_reads=num_reads, annealing_time=annealing_time)
h_sample = torch.zeros(self.n_hidden)
for j, val in sampleset.first.sample.items():
if j < self.n_hidden:
h_sample[j] = float(val)
return h_sample
def train_step(self, v_data, lr=0.01):
"""Single training step with contrastive divergence."""
# Positive phase: data statistics
h_prob_pos = torch.sigmoid(v_data @ self.W + self.b_h)
pos_grad = v_data.t() @ h_prob_pos / v_data.shape[0]
# Negative phase: model statistics via Dynex
h_neg = self.sample_hidden(v_data)
v_neg = torch.sigmoid(h_neg @ self.W.t() + self.b_v)
neg_grad = v_neg.unsqueeze(1) @ h_neg.unsqueeze(0)
# Update parameters
self.W += lr * (pos_grad - neg_grad)
self.b_h += lr * (h_prob_pos.mean(0) - h_neg)
self.b_v += lr * (v_data.mean(0) - v_neg)
# Train on MNIST-like data
config = DynexConfig(compute_backend=ComputeBackend.GPU)
rbm = DynexRBM(n_visible=784, n_hidden=128, config=config)
# Assume X_train is [n_samples, 784] binary tensor
# for batch in DataLoader(X_train, batch_size=32):
# rbm.train_step(batch)
```
## Mode-assisted QRBM (PyTorch)
The mode-assisted variant uses Dynex to find the mode (most probable state) of the hidden distribution rather than sampling:
```python theme={null}
# See full implementation in:
# examples/utils/HybridQRBM/
```
[Mode-assisted QRBM notebook](https://github.com/Dynex-Development/awesome-dynex/blob/main/machine_learning/example_pytorch.ipynb)
## Notebooks
| Notebook | Description |
| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------- |
| [Dynex-Full-QRBM.ipynb](https://github.com/Dynex-Development/awesome-dynex/blob/main/machine_learning/Dynex-Full-QRBM.ipynb) | 3-step QUBO RBM implementation |
| [example\_pytorch.ipynb](https://github.com/Dynex-Development/awesome-dynex/blob/main/machine_learning/example_pytorch.ipynb) | Mode-assisted QRBM with PyTorch |
| [example\_quantum\_boltzmann\_machine\_QBM.ipynb](https://github.com/Dynex-Development/awesome-dynex/blob/main/machine_learning/example_quantum_boltzmann_machine_QBM.ipynb) | Full QBM implementation |
| [Medium\_Image\_Classification.ipynb](https://github.com/Dynex-Development/awesome-dynex/blob/main/misc/Medium_Image_Classification.ipynb) | Image classification with Q-RBM |
## Scientific background
* Dixit et al. (2021). "Training Restricted Boltzmann Machines With a D-Wave Quantum Annealer." *Front. Phys.* 9:589626
* Manukian et al. (2020). "Mode-assisted unsupervised learning of restricted Boltzmann machines." *Communications Physics* 3:105
* Neumann (2024). "Advancements in Unsupervised Learning: Mode-Assisted QRBM." *IJBIC* 3(1):91–103
* Sleeman et al. (2020). "A Hybrid Quantum enabled RBM Advantage." *Defense + Commercial Sensing*
# Quantum SVM
Source: https://dynex.mintlify.app/examples/ml/qsvm
Quantum Support Vector Machine for classification on Dynex
# Quantum Support Vector Machine (QSVM)
QSVM formulates the feature selection step of SVM training as a QUBO problem, solved on the Dynex platform. This finds the optimal subset of features to maximize classification accuracy while minimizing model complexity.
## Installation
```bash theme={null}
pip install dynex scikit-learn numpy
```
## Using the Dynex scikit-learn Plugin
The `dynex_scikit_plugin` provides a drop-in scikit-learn transformer:
```python theme={null}
import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
# Load the dynex scikit plugin
import sys
sys.path.append('examples/utils')
from dynex_scikit_plugin import DynexClassifier
from dynex import DynexConfig, ComputeBackend
# Load dataset
X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Build pipeline: scaler -> quantum feature selection -> SVM
config = DynexConfig(compute_backend=ComputeBackend.GPU)
pipeline = Pipeline([
('scaler', StandardScaler()),
('qsvm', DynexClassifier(config=config, num_reads=1000, annealing_time=200)),
])
pipeline.fit(X_train, y_train)
accuracy = pipeline.score(X_test, y_test)
print(f"Test accuracy: {accuracy:.4f}")
```
## Manual QSVM formulation
```python theme={null}
import dynex
import dimod
import numpy as np
from sklearn.datasets import make_classification
from dynex import DynexConfig, ComputeBackend
# Generate dataset
X, y = make_classification(n_samples=100, n_features=10, random_state=42)
y = 2 * y - 1 # Convert to {-1, +1}
# Build QUBO for feature selection
# Objective: select features that maximize margin while penalizing count
n_features = X.shape[1]
lambda_reg = 0.1 # Regularization weight
# Compute kernel matrix
K = X @ X.T
Q = {}
# Linear terms: negative contribution to SVM objective
for i in range(n_features):
Q[(i, i)] = Q.get((i, i), 0) + lambda_reg
# Quadratic terms: correlations between features
for i in range(n_features):
for j in range(i+1, n_features):
correlation = np.abs(np.corrcoef(X[:, i], X[:, j])[0, 1])
if correlation > 0.1:
Q[(i, j)] = Q.get((i, j), 0) + correlation * lambda_reg
bqm = dimod.BinaryQuadraticModel.from_qubo(Q)
model = dynex.BQM(bqm)
config = DynexConfig(compute_backend=ComputeBackend.GPU)
sampler = dynex.DynexSampler(model, config=config)
sampleset = sampler.sample(num_reads=1000, annealing_time=200)
selected_features = [i for i, v in sampleset.first.sample.items() if v == 1]
print(f"Selected features: {selected_features}")
# Train classical SVM on selected features
from sklearn.svm import SVC
from sklearn.model_selection import cross_val_score
X_selected = X[:, selected_features]
svm = SVC(kernel='rbf')
scores = cross_val_score(svm, X_selected, y, cv=5)
print(f"Cross-validation accuracy: {scores.mean():.4f} ± {scores.std():.4f}")
```
## Notebooks
* [QSVM implementation](https://github.com/Dynex-Development/awesome-dynex/blob/main/machine_learning/example_support_vector_machine.ipynb)
* [QSVM with PyTorch](https://github.com/Dynex-Development/awesome-dynex/blob/main/machine_learning/Example_SVM_pytorch.ipynb)
* [Breast Cancer prediction with scikit-learn plugin](https://github.com/Dynex-Development/awesome-dynex/blob/main/machine_learning/Dynex_Scikit-Learn_Plugin.ipynb)
* [Feature selection — Titanic](https://github.com/Dynex-Development/awesome-dynex/blob/main/misc/example_feature_selection_titanic_survivals.ipynb)
# Neuromorphic Torch Layers
Source: https://dynex.mintlify.app/examples/ml/torch-layers
Drop-in PyTorch layers backed by Dynex quantum computation
# Neuromorphic Torch Layers
The Dynex Neuromorphic Torch Layer integrates Dynex quantum computation directly into PyTorch model architectures. It can be used as a drop-in replacement for any standard PyTorch layer, enabling:
* **Hybrid quantum-classical models** — combine classical neural network layers with quantum computation
* **Neuromorphic transfer learning** — fine-tune pre-trained models with quantum layers
* **Federated learning** — run quantum layers across distributed compute nodes
## Installation
```bash theme={null}
pip install dynex torch
```
## Basic usage
```python theme={null}
import torch
import torch.nn as nn
from dynex import DynexConfig, ComputeBackend
# Import the neuromorphic layer
import sys
sys.path.append('examples/utils')
from HybridQRBM.pytorchdnx import DynexTorchLayer
config = DynexConfig(compute_backend=ComputeBackend.GPU)
# Build a hybrid model: classical layers + Dynex quantum layer
class HybridModel(nn.Module):
def __init__(self):
super().__init__()
self.encoder = nn.Sequential(
nn.Linear(784, 256),
nn.ReLU(),
nn.Linear(256, 128),
)
self.quantum_layer = DynexTorchLayer(
n_visible=128,
n_hidden=64,
config=config,
num_reads=1000,
annealing_time=200
)
self.classifier = nn.Sequential(
nn.Linear(64, 32),
nn.ReLU(),
nn.Linear(32, 10),
)
def forward(self, x):
x = self.encoder(x)
x = self.quantum_layer(x) # Dynex quantum computation
x = self.classifier(x)
return x
model = HybridModel()
```
## Training a hybrid model
```python theme={null}
import torch
import torch.nn as nn
from torch.utils.data import DataLoader, TensorDataset
# Dummy data
X = torch.randn(1000, 784)
y = torch.randint(0, 10, (1000,))
dataset = TensorDataset(X, y)
loader = DataLoader(dataset, batch_size=32, shuffle=True)
model = HybridModel()
optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)
criterion = nn.CrossEntropyLoss()
for epoch in range(5):
total_loss = 0
for batch_X, batch_y in loader:
optimizer.zero_grad()
output = model(batch_X)
loss = criterion(output, batch_y)
loss.backward()
optimizer.step()
total_loss += loss.item()
print(f"Epoch {epoch+1}: loss={total_loss/len(loader):.4f}")
```
## Federated learning with parallel Dynex layers
```python theme={null}
import multiprocessing
from dynex import DynexConfig, ComputeBackend
def train_node(queue, node_id, local_data):
"""Train a model partition on a single federated node."""
config = DynexConfig(compute_backend=ComputeBackend.QPU, qpu_model='apollo_rc1')
# ... local training with quantum layer ...
queue.put((node_id, local_model_weights))
# Run N federated nodes in parallel
nodes = 4
queues = []
processes = []
for i in range(nodes):
q = multiprocessing.Queue()
queues.append(q)
p = multiprocessing.Process(target=train_node, args=(q, i, data_partition[i]))
processes.append(p)
p.start()
for p in processes:
p.join()
# Aggregate weights (federated averaging)
all_weights = [q.get() for q in queues]
```
## TensorFlow support
Neuromorphic layers are also available for TensorFlow:
* [QSVM TensorFlow](https://github.com/dynexcoin/QSVM_Tensorflow/blob/main/Example_SVM_Tensorflow.ipynb)
* [MA-QRBM TensorFlow](https://github.com/dynexcoin/QRBM_Tensorflow)
## Notebooks
| Notebook | Description |
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------ |
| [example\_neuromorphic\_torch\_layers.ipynb](https://github.com/Dynex-Development/awesome-dynex/blob/main/machine_learning/example_neuromorphic_torch_layers.ipynb) | QBM with PyTorch |
| [Example\_SVM\_pytorch.ipynb](https://github.com/Dynex-Development/awesome-dynex/blob/main/machine_learning/Example_SVM_pytorch.ipynb) | QSVM with PyTorch |
| [example\_pytorch.ipynb](https://github.com/Dynex-Development/awesome-dynex/blob/main/machine_learning/example_pytorch.ipynb) | Mode-assisted QRBM |
# Examples Overview
Source: https://dynex.mintlify.app/examples/overview
Practical examples across optimization, machine learning, algorithms, and circuits
# Examples
Practical examples demonstrating the Dynex SDK across different problem domains. From simple BQM sampling to production-grade quantum machine learning, these examples cover the full spectrum of what Dynex can compute.
## Prerequisites
```bash theme={null}
pip install dynex dimod numpy
```
For ML examples:
```bash theme={null}
pip install torch scikit-learn
```
For circuit examples:
```bash theme={null}
pip install pennylane qiskit pennylane-qiskit
```
## Basic Examples
Getting started with the fundamental SDK workflow:
Build and sample a Binary Quadratic Model on CPU and QPU
Constructing BQMs with dimod, PyQUBO, and named variables
## Algorithm Examples
Classic quantum algorithms implemented on the Dynex platform:
Integer factorization via quantum amplitude amplification
Period-finding for efficient integer factorization
MaxCut, graph partitioning, job sequencing, and more
## Machine Learning Examples
Quantum-enhanced ML algorithms with PyTorch and scikit-learn integration:
QSVM, QPCA, QNN, QBM, and feature selection
Quantum Support Vector Machine
Quantum Restricted Boltzmann Machine
Hybrid quantum-classical PyTorch models
## Industry Applications
Real-world applications across industries:
| Domain | Examples |
| --------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Finance | [Portfolio optimization](https://github.com/Dynex-Development/awesome-dynex/blob/main/optimization/Dynex_Portfolio_Optimisation.ipynb), [collaborative filtering](https://github.com/Dynex-Development/awesome-dynex/blob/main/misc/example_collaborative_filtering_CFQIRBM.ipynb) |
| Pharma / Health | [Protein folding](https://github.com/Dynex-Development/awesome-dynex/blob/main/advanced_applications/QuantumProteinFolding.ipynb), [RNA folding](https://github.com/Dynex-Development/awesome-dynex/blob/main/misc/example_rna_folding.ipynb), [molecule screening](https://github.com/Dynex-Development/awesome-dynex/blob/main/misc/molecule_screening.ipynb) |
| Automotive | [Traffic optimization](https://github.com/Dynex-Development/awesome-dynex/blob/main/optimization/TrafficOptimizationCQMBUG.ipynb), [EV charging placement](https://github.com/Dynex-Development/awesome-dynex/blob/main/misc/example_placement_of_charging_stations.ipynb), [CFD](https://github.com/dynexcoin/QCFD) |
| Logistics | [Aircraft loading](https://github.com/Dynex-Development/awesome-dynex/blob/main/optimization/aircraft-loading-optim.ipynb), [job sequencing](https://github.com/Dynex-Development/awesome-dynex/blob/main/optimization/quantum_job_sequencing.ipynb), [multi-vehicle routing](https://github.com/dynexcoin/quantum_multi_vehicle_routing) |
| Aerospace | [Satellite scheduling](https://github.com/Dynex-Development/awesome-dynex/blob/main/advanced_applications/QuantumSatellite.ipynb) |
| Computer Vision | [Image classification (Q-RBM)](https://github.com/Dynex-Development/awesome-dynex/blob/main/misc/Medium_Image_Classification.ipynb), [image super-resolution (Q-SISR)](https://github.com/dynexcoin/QSISR) |
## All notebooks
Browse the complete notebook collection on GitHub:
[github.com/Dynex-Development/awesome-dynex](https://github.com/Dynex-Development/awesome-dynex)
# Automotive & Aerospace
Source: https://dynex.mintlify.app/examples/use-cases/automotive-aerospace
Quantum computing applications in vehicle design, traffic optimization, and aerospace engineering
# Automotive & Aerospace
Quantum computing addresses engineering optimization challenges in aerodynamics, fleet management, and satellite systems — problems where the search space is too large for classical solvers.
## Computational Fluid Dynamics (Q-CFD)
Simulating fluid flow around vehicles is computationally intensive. Quantum CFD accelerates aerodynamics simulations, enabling engineers to rapidly analyze and optimize vehicle design for drag reduction and fuel efficiency.
Quantum-accelerated CFD for vehicle aerodynamics and turbulence modeling. Significant speedup over classical numerical methods.
**Scientific background:** Bharadwaj & Sreenivasan. *An Introduction to Algorithms in Quantum Computation of Fluid Dynamics.* STO Educational Notes, 2022.
## Traffic Optimization
Urban traffic flow optimization modeled as a constrained quadratic problem. Minimizes congestion and travel time across road networks by finding optimal signal timing and routing assignments.
CQM-based traffic optimization. Reduces average travel time and network congestion through quantum-optimized signal coordination.
## EV Charging Station Placement
Optimal placement of electric vehicle charging infrastructure using quantum annealing. Maximizes coverage and accessibility while minimizing installation costs under geographic and demand constraints.
User- and destination-based location model for EV charging stations, formulated as a QUBO.
**Scientific background:** Pagany et al. *Electric Charging Demand Location Model.* Sustainability, 2019, 11(8), 2301.
## Aircraft Loading Optimization
Optimal cargo and passenger load distribution for aircraft, ensuring weight balance constraints while maximizing capacity utilization. Based on the Airbus Quantum Computing Challenge.
Airbus QCC Problem n°5: quantum optimization of aircraft weight and balance under structural and safety constraints.
## Satellite Constellation Scheduling
Optimal scheduling of satellite observation tasks across a constellation, formulated as a weighted k-clique problem. Maximizes coverage and minimizes scheduling conflicts.
Heterogeneous quantum computing for satellite constellation optimization. Solves the weighted K-Clique problem for task scheduling.
**Scientific background:** Bass et al. *Heterogeneous Quantum Computing for Satellite Constellation Optimization.* Quantum Sci. Technol. 3, 024010 (2018).
# Finance
Source: https://dynex.mintlify.app/examples/use-cases/finance
Quantum computing applications in portfolio optimization, risk management, and financial services
# Financial Services
Quantum computing enables financial institutions to analyze large datasets, optimize asset allocations, and tackle combinatorial problems in risk and fraud management that are intractable classically.
## Portfolio Optimization
Modern portfolio theory requires searching an exponentially large space of asset combinations to find the allocation that maximizes return for a given level of risk. Quantum annealing formulates this as a QUBO problem and finds near-optimal allocations efficiently.
Markowitz mean-variance portfolio optimization on Dynex. Selects optimal asset weights under risk and cardinality constraints.
**Scientific background:** Sakuler et al. (2023). *A real world test of Portfolio Optimization with Quantum Annealing.* [DOI:10.21203/rs.3.rs-3959774/v1](https://doi.org/10.21203/rs.3.rs-3959774/v1)
## Collaborative Filtering
Quantum-enhanced recommendation systems and fraud detection via Collaborative Filtering using a Quantum Immune Restricted Boltzmann Machine (CFQIRBM). Models latent user-item interactions as a quantum probabilistic graphical model.
Quantum Immune RBM for collaborative filtering — applicable to fraud pattern detection and personalized recommendations.
# Logistics & Operations
Source: https://dynex.mintlify.app/examples/use-cases/logistics
Quantum computing applications in routing, scheduling, and supply chain optimization
# Logistics & Operations
Combinatorial optimization problems in logistics — routing, scheduling, and resource allocation — are a natural fit for quantum annealing. Dynex solves these problems at scale with competitive solution quality.
## Multi-Vehicle Routing
Quantum-optimized routing and scheduling for a fleet of vehicles. Minimizes total travel time and fuel consumption while satisfying delivery constraints across large networks.
Fleet routing optimization using quantum annealing. Handles capacity, time window, and precedence constraints for real-world logistics operations.
## Workforce Scheduling
Optimal shift assignment and task allocation for workforce management. Balances employee availability, skill requirements, and operational constraints to maximize efficiency.
Quantum-optimized workforce scheduling for dynamic staffing environments. Reduces scheduling conflicts and operational costs.
## Flow Shop Scheduling
Job shop and flow shop scheduling optimization — minimizing makespan across multiple machines and processing stages. Quantum annealing explores the scheduling space efficiently to find near-optimal job orderings.
Quantum optimization for JSS and FSS problems. Minimizes completion time across multi-machine production environments.
## Aircraft Loading
Optimal cargo distribution and weight balancing for aircraft. Ensures structural safety while maximizing payload capacity.
Airbus QCC Problem n°5: quantum optimization of load distribution under weight and balance constraints.
## Job Sequencing
Optimal sequencing of jobs to minimize total weighted completion time. Applicable to manufacturing, printing, and processing pipelines.
QUBO formulation for job sequencing with deadlines and weights. Finds optimal job orderings for single-machine and parallel-machine settings.
# Pharma & Health
Source: https://dynex.mintlify.app/examples/use-cases/pharma-health
Quantum computing applications in drug discovery, protein folding, and biomedical research
# Pharmaceutical & Healthcare
Quantum computing accelerates drug discovery and biomedical research by solving molecular optimization problems that are computationally infeasible classically — protein folding, RNA structure prediction, and molecular screening.
## Protein Folding
Predicting the three-dimensional structure of a protein from its amino acid sequence is one of biology's hardest problems. The folding path can be encoded as a QUBO and solved on Dynex to find low-energy conformations.
Lattice protein folding via quantum annealing. Finds minimal-energy conformations for peptide chains on a 2D/3D lattice.
**Scientific background:** Irbäck et al. (2022). *Folding lattice proteins with quantum annealing.*
## RNA Folding
RNA secondary structure prediction — finding the minimum free energy fold — maps naturally to a QUBO. This example folds the Tobacco Mild Green Mosaic Virus RNA sequence on Dynex.
Minimum free energy RNA folding of the TMGMV sequence. Based on Fox et al., PLoS Comput Biol (2022).
**Scientific background:** Fox DM et al. *RNA folding using quantum computers.* PLoS Comput Biol. 2022;18(4):e1010032.
## Molecule Screening
Virtual screening of phenol derivatives to identify candidates with desired physicochemical properties. Group contribution methods are combined with a QUBO formulation to efficiently explore large chemical spaces.
QUBO-based molecular screening using group contribution approaches. Identifies optimal phenol derivative candidates for industrial applications.
**Scientific background:** Cho et al. *Efficient Exploration of Phenol Derivatives Using QUBO Solvers.* Ind. Eng. Chem. Res. 2024, 63(10), 4248–4256.
## Enzyme Target Prediction
Quantum optimization applied to enzyme-target identification — a key step in drug discovery pipelines. Formulates the binding problem as a QUBO to identify enzyme targets efficiently.
QuTIE: Quantum optimization for Target Identification by Enzymes.
**Scientific background:** Ngo HM et al. *QuTIE: Quantum optimization for Target Identification by Enzymes.* Bioinformatics Advances, 2023.
## Breast Cancer Prediction
Quantum feature selection for breast cancer classification using the Dynex scikit-learn plugin. Formulates mutual information-based feature selection as a QUBO problem.
Quantum feature selection applied to the Wisconsin Breast Cancer Dataset using the Dynex scikit-learn transformer.
**Scientific background:** Bhatia & Phillipson. *Performance Analysis of SVM Implementations on the D-Wave Quantum Annealer.* ICCS 2021.
# Telecommunication
Source: https://dynex.mintlify.app/examples/use-cases/telecom
Quantum computing applications in network optimization and infrastructure planning
# Telecommunication
Quantum computing addresses network planning and infrastructure optimization challenges where classical solvers struggle with the combinatorial complexity of large deployments.
## WiFi Hotspot Positioning
Optimal placement of WiFi access points to maximize coverage area and signal quality while minimizing infrastructure costs. Formulated as a QUBO optimization problem over candidate locations.
QUBO/Ising formulation for access point placement. Maximizes network coverage under budget and interference constraints.
## EV Charging Infrastructure
Quantum-optimized placement of EV charging stations — applicable to telecom site selection and distributed infrastructure planning.
User- and destination-based location model, adaptable to distributed network infrastructure planning.
# Installation
Source: https://dynex.mintlify.app/installation
Install the Dynex SDK and configure your environment
## System Requirements
| Component | Minimum | Recommended |
| --------- | --------------------- | ----------- |
| Python | 3.11 | 3.11+ |
| RAM | 4 GB | 8 GB+ |
| Storage | 2 GB | 10 GB+ |
| OS | Linux, macOS, Windows | — |
## Install
[uv](https://docs.astral.sh/uv/) is a fast Python package manager. If you don't have it:
```bash theme={null}
curl -LsSf https://astral.sh/uv/install.sh | sh
```
Then:
```bash theme={null}
uv add dynex
```
Or in a new project:
```bash theme={null}
uv init my-project && cd my-project
uv add dynex
uv run python main.py
```
```bash theme={null}
pip install dynex
```
For development or latest features, install from source:
```bash theme={null}
git clone https://github.com/Dynex-Development/py-sdk.git
cd py-sdk
uv sync --group dev # or: pip install -e .
```
### With optional dependencies
```bash theme={null}
uv add dynex python-dotenv
uv add dynex pennylane
uv add dynex torch
```
```bash theme={null}
pip install dynex python-dotenv # .env file support
pip install dynex pennylane # gate circuits
pip install dynex torch # PyTorch neuromorphic layers
```
## Core dependencies
The SDK automatically installs:
* **grpcio** ≥ 1.60.0 — gRPC communication
* **protobuf** ≥ 4.25.0 — protocol buffer serialization
* **dimod** ≥ 0.12.0 — quadratic model framework
* **numpy** ≥ 1.24.0 — numerical computing
* **pydantic** ≥ 2.0.0 — data validation
## Configuration
### Environment variables
```bash theme={null}
export DYNEX_SDK_KEY="your_sdk_key"
export DYNEX_GRPC_ENDPOINT="quantum-router-engine-grpc.hz.dynex.co:3000"
```
### .env file (recommended)
Create `.env` in your project root and install `python-dotenv`:
```bash theme={null}
# .env
DYNEX_SDK_KEY=your_sdk_key
DYNEX_GRPC_ENDPOINT=quantum-router-engine-grpc.hz.dynex.co:3000
# Optional
DYNEX_COMPUTE_BACKEND=cpu
DYNEX_DEFAULT_TIMEOUT=300.0
```
```bash theme={null}
pip install python-dotenv
```
The SDK automatically discovers `.env` files in the current directory and up to 3 parent directories.
### Verify installation
```python theme={null}
import dynex
print(dynex.__version__)
from dynex import DynexConfig, ComputeBackend
import dimod
bqm = dimod.BinaryQuadraticModel({0: 1, 1: -1}, {(0, 1): 0.5}, 0.0, 'BINARY')
config = DynexConfig(compute_backend=ComputeBackend.LOCAL)
model = dynex.BQM(bqm)
sampler = dynex.DynexSampler(model, config=config)
sampleset = sampler.sample(num_reads=10)
print(f"Test passed. Best energy: {sampleset.first.energy}")
```
## Platform notes
No additional setup required. All features work out of the box.
Install Xcode command line tools if not present:
```bash theme={null}
xcode-select --install
```
Apple Silicon (M1/M2/M3) is fully supported.
* Install [Microsoft Visual C++ Build Tools](https://visualstudio.microsoft.com/visual-cpp-build-tools/) if compilation errors occur
* WSL (Windows Subsystem for Linux) recommended for production use
* PowerShell and Command Prompt both supported
## Docker
```dockerfile theme={null}
FROM python:3.11-slim
RUN pip install dynex python-dotenv
ENV DYNEX_SDK_KEY=${DYNEX_SDK_KEY}
ENV DYNEX_GRPC_ENDPOINT=${DYNEX_GRPC_ENDPOINT}
COPY . /app
WORKDIR /app
CMD ["python", "main.py"]
```
```bash theme={null}
docker build -t my-dynex-app .
docker run -e DYNEX_SDK_KEY=your_key -e DYNEX_GRPC_ENDPOINT=quantum-router-engine-grpc.hz.dynex.co:3000 my-dynex-app
```
## Jupyter notebooks
```bash theme={null}
pip install dynex jupyter # or: uv add dynex jupyter
jupyter notebook
```
Add this boilerplate at the top of your notebooks:
```python theme={null}
import dynex
from dynex import DynexConfig, ComputeBackend, QPUModel
import dimod
import numpy as np
config = DynexConfig(
compute_backend=ComputeBackend.GPU,
use_notebook_output=True
)
print(f"Dynex SDK {dynex.__version__} ready")
```
## Troubleshooting
```bash theme={null}
pip install grpcio
```
Check that you are using the correct Python environment. Try:
```bash theme={null}
pip uninstall dynex && pip install dynex
```
* Verify credentials: `DYNEX_SDK_KEY` and `DYNEX_GRPC_ENDPOINT`
* Check that port 443 is not blocked by a firewall
* Test connectivity: `grpcurl quantum-router-engine-grpc.hz.dynex.co:3000 list`
QPU backend requires an explicit model. Use:
```python theme={null}
config = DynexConfig(
compute_backend=ComputeBackend.QPU,
qpu_model='apollo_rc1'
)
```
LOCAL backend requires the `dynexcore` binary in a `testnet/` directory. Download it from the releases page or switch to `ComputeBackend.CPU`.
## Upgrading from legacy SDK
```bash theme={null}
pip uninstall dynex
pip install dynex
```
Notable changes from legacy SDK:
* Replace `mainnet=True/False` with explicit `DynexConfig(compute_backend=...)`
* Remove `v2=True` parameter from sampler calls
* Communication is now gRPC-based instead of REST
# Introduction
Source: https://dynex.mintlify.app/introduction
Dynex Quantum Platform: A cloud-based, qubit-agnostic platform
# Dynex SDK
The Dynex SDK provides a unified programming interface for expressing optimization, probabilistic, and quantum-inspired workloads. Users interact with the platform through high-level representations such as optimization problem formulations, probabilistic models, graph-based structures, and circuit-derived abstractions. The SDK handles compilation, transformation, and backend adaptation internally, enabling portability across supported execution resources.
Run your first quantum computation in under 5 minutes
Install the SDK and configure credentials
Solve QUBO, Ising, CQM, and DQM problems
Run PennyLane, Qiskit, and OpenQASM circuits
## What is Dynex?
Dynex provides a qubit-agnostic computing platform designed to unify diverse quantum and quantum-driven compute resources under a single execution and programming environment. The platform enables users to access heterogeneous compute modalities through a consistent workflow for optimization, simulation, and probabilistic workloads—without requiring direct exposure to device-specific implementations. The Dynex platform focuses on abstraction, orchestration, and interoperability, allowing end users to work at the problem level rather than the hardware level.
The platform excels at two complementary computing paradigms:
Solve QUBO, Ising, and constrained optimization problems with BQM, CQM, and DQM model types. Compatible with the dimod framework, PyQUBO, and other QUBO tools.
Run quantum gate circuits from PennyLane, Qiskit, Cirq, and OpenQASM directly on the Dynex platform. Run Grover's, Shor's, QFT and other algorithms without modification.
## How It Works
Define your problem as a BQM, CQM, or DQM model, or as a quantum gate circuit using PennyLane, Qiskit, or OpenQASM.
Select LOCAL for testing, CPU/GPU for testnet, or QPU for quantum hardware access via `DynexConfig`.
The SDK converts your problem into a neuromorphic circuit and submits it to the Dynex computing network.
Retrieve results as a dimod `SampleSet` and inspect samples, energies, and variable assignments.
## Unified Execution Environment
Dynex presents all supported compute backends as standardized execution resources within a common runtime environment. These resources include:
* proprietary Dynex compute systems,
* large-scale software-based emulation resources, and
* third-party quantum processing units operated by external providers.
A centralized orchestration layer manages workload submission, routing, execution coordination, and result handling. From the user’s perspective, workloads are expressed once and executed consistently, independent of the underlying compute modality.
## Hybrid and Heterogeneous Workflows
The platform is architected to enable hybrid computational workflows, allowing multiple computing paradigms to be combined seamlessly within the lifecycle of a single problem. Rather than binding a workload to a fixed execution model, the system supports flexible orchestration across heterogeneous compute substrates. As a result, different stages of a computation—such as preprocessing, probabilistic sampling, optimization, or refinement—can be executed on the hardware or simulation environment best suited to the specific task.
Depending on availability, suitability, and performance requirements, workloads can be dynamically mapped to different backend resources, including classical high-performance systems, quantum emulation environments, neuromorphic probabilistic processors, or emerging room-temperature quantum hardware. Backend selection mechanisms evaluate factors such as the mathematical structure of the problem, the required computational precision, latency or throughput constraints, and the current availability of resources within the platform.
Importantly, this orchestration layer is designed to remain transparent to the application developer. Developers interact with the platform through a unified programming interface and abstract problem formulations (e.g., QUBO, Ising, or probabilistic graphical models), while the platform handles the underlying execution strategy. This abstraction allows users to focus on modeling and algorithm design, while the system automatically determines the most effective execution pathway across the available heterogeneous computing infrastructure.
## Dynex Compute Systems
Dynex-operated compute systems are optimized for probabilistic and energy-based problem formulations commonly used in optimization, sampling, and inference. These systems are integrated into the Dynex platform as native execution resources and are accessed through the same APIs and tooling as other supported backends. From a platform architecture perspective, these systems can be understood as specialized accelerators for probabilistic and combinatorial computation, designed to complement rather than replace existing classical and quantum hardware infrastructures. Instead of operating as isolated computing paradigms, they form part of a heterogeneous compute stack in which different physical substrates are leveraged according to their strengths in solving optimization, sampling, and stochastic inference problems.
Within this framework, the available computational resources span several technological layers. At one end, high-performance quantum emulation systems implemented on CPU/GPU nodes enable the simulation of large-scale quantum circuits and quantum-inspired algorithms with substantial scalability. In parallel, quantum-driven neuromorphic computing systems based on analog CMOS technology (Apollo Series) provide energy-efficient hardware substrates for probabilistic computing, enabling massively parallel exploration of energy landscapes typical of Ising and QUBO formulations. At the hardware frontier, a proprietary room-temperature quantum computing system built on nitrogen-vacancy (NV) diamond spin qubits (Zeus series) introduces a genuine quantum spin system that operates without cryogenic infrastructure, opening a pathway toward hybrid architectures where classical, neuromorphic, and quantum spin-based devices coexist within a unified computational ecosystem.
## Supported Integrations
Native BQM, CQM, DQM model support
Quantum ML circuits on Dynex
IBM Qiskit circuits on Dynex
Neuromorphic Torch layers
Quantum feature selection plugin
Neuromorphic TF layers
Build QUBO/Ising from math expressions
Fujitsu Research — auto-convert Python functions to QUBO
Lamarr Institute — lightweight NumPy QUBO toolbox
## Resources
### Book
**Neuromorphic Computing for Computer Scientists** — a complete guide to neuromorphic computing on the Dynex platform. 249 pages, 2024. Available on [Amazon.com](https://www.amazon.com/s?k=Neuromorphic+Computing+for+Computer+Scientists+Dynex), [Amazon.co.uk](https://www.amazon.co.uk/s?k=Neuromorphic+Computing+for+Computer+Scientists+Dynex), and [Amazon.de](https://www.amazon.de/s?k=Neuromorphic+Computing+for+Computer+Scientists+Dynex).
### Benchmarks & Publications
* [Benchmarks](https://dynex.co/learn/benchmarks)
* [Scientific Publications](https://dynex.co/learn/scientific-publications)
* [Use Cases](https://dynex.co/learn/partnerships-customers)
### Medium Guides
Step-by-step articles covering real-world implementations on the Dynex platform:
* [Quantum Self-Attention Transformer on Dynex](https://medium.com/dynex)
* [13-bit Full Adder Quantum Circuit on Dynex](https://medium.com/dynex)
* [Grover's Algorithm on Dynex](https://medium.com/dynex)
* [Shor's Algorithm on Dynex](https://medium.com/dynex)
* [Stock Portfolio Optimisation with Quantum Algorithms on Dynex](https://medium.com/dynex)
* [Image Classification on the Dynex Neuromorphic Platform](https://medium.com/dynex)
* [IBM Qiskit 4-Qubit Full Adder Circuit on Dynex](https://medium.com/dynex)
* [Benchmarking the Dynex Neuromorphic Platform with the Q-Score](https://medium.com/dynex)
* [Enhancing MaxCut Solutions: Dynex's Benchmark on G70](https://medium.com/dynex)
# Algorithmic Emulation Resources
Source: https://dynex.mintlify.app/platform/algorithmic-emulation-resources
In addition to physical hardware, Dynex provides access to high-performance software-based emulation resources
In addition to physical hardware, Dynex provides access to high-performance software-based emulation resources designed to support large problem instances, development workflows, and reproducible experimentation.
These resources integrate seamlessly with the same SDK and runtime environment, allowing users to develop, test, and validate workloads before or alongside execution on specialized hardware.
* up to 1 million algorithmic qubits,
* deterministic reproducibility,
* flexible embedding,
* and compatibility with the same SDK used for Apollo and QPUs.
GPU qNodes are particularly suited for:
* large-scale sweeps,
* embedding validation,
* debugging of Hamiltonian structures,
* and scenarios where massive problem sizes exceed practical physical qubit counts.
[Benchmarks](https://dynex.co/learn/benchmarks)
# Dynex Compute Systems
Source: https://dynex.mintlify.app/platform/dynex-compute-systems
Dynex Compute Systems
Dynex-operated compute systems are optimized for probabilistic and energy-based problem formulations commonly used in optimization, sampling, and inference. These systems are integrated into the Dynex platform as native execution resources and are accessed through the same APIs and tooling as other supported backends.
From a platform architecture perspective, these systems can be understood as specialized accelerators for probabilistic and combinatorial computation, designed to complement rather than replace existing classical and quantum hardware infrastructures. Instead of operating as isolated computing paradigms, they form part of a heterogeneous compute stack in which different physical substrates are leveraged according to their strengths in solving optimization, sampling, and stochastic inference problems.
Within this framework, the available computational resources span several technological layers. At one end, high-performance quantum emulation systems implemented on CPU/GPU nodes enable the simulation of large-scale quantum circuits and quantum-inspired algorithms with substantial scalability. In parallel, quantum-driven neuromorphic computing systems based on analog CMOS technology (Apollo Series) provide energy-efficient hardware substrates for probabilistic computing, enabling massively parallel exploration of energy landscapes typical of Ising and QUBO formulations. At the hardware frontier, a proprietary room-temperature quantum computing system built on nitrogen-vacancy (NV) diamond spin qubits (Zeus series) introduces a genuine quantum spin system that operates without cryogenic infrastructure, opening a pathway toward hybrid architectures where classical, neuromorphic, and quantum spin-based devices coexist within a unified computational ecosystem.
* [Watch the Apollo video](https://youtu.be/k9xGL4IugDM)
* [Quantum-Driven Neuromorphic Computing for Million-Qubit-Scale Workloads (Academic Paper)](https://drive.google.com/file/d/1BZGTcfgKZ2v8Gars13K1DuubPQCvM04Q/view?usp=sharing)
* [More Scientific Publications](https://dynex.co/learn/scientific-publications)
# Integration of External Quantum Hardware
Source: https://dynex.mintlify.app/platform/external-quantum-hardware
Dynex supports interoperability with a range of external quantum computing providers
Dynex supports interoperability with a range of external quantum computing providers across different hardware paradigms, including gate-based systems, annealing systems, and analog quantum simulators.
* IBM (Eagle, others), Superconducting (gate model)
* IonQ (Aria, Forte), Trapped-ion (gate model)
* Rigetti (Ankaa series), Superconducting (gate model)
* D-Wave (Advantage / Advantage2), Quantum annealing
* QuEra (Aquila), Neutral-atom / Rydberg analog simulation
* IQM (Garnet, Emerald), Superconducting (gate model)
The platform abstracts differences in control interfaces, device topology, and execution semantics, enabling external quantum hardware to be used as complementary resources for experimentation, benchmarking, validation, or hybrid workflows.
# Overview
Source: https://dynex.mintlify.app/platform/overview
Dynex Quantum Platform: A cloud-based, qubit-agnostic platform
# Unified Execution Environment
Dynex presents all supported compute backends as standardized execution resources within a common runtime environment. These resources may include:
* proprietary Dynex compute systems,
* large-scale software-based emulation resources, and
* third-party quantum processing units operated by external providers.
A centralized orchestration layer manages workload submission, routing, execution coordination, and result handling. From the user’s perspective, workloads are expressed once and executed consistently, independent of the underlying compute modality.
# Hybrid and Heterogeneous Workflows
The platform is architected to enable hybrid computational workflows, allowing multiple computing paradigms to be combined seamlessly within the lifecycle of a single problem. Rather than binding a workload to a fixed execution model, the system supports flexible orchestration across heterogeneous compute substrates. As a result, different stages of a computation—such as preprocessing, probabilistic sampling, optimization, or refinement—can be executed on the hardware or simulation environment best suited to the specific task.
Depending on availability, suitability, and performance requirements, workloads can be dynamically mapped to different backend resources, including classical high-performance systems, quantum emulation environments, neuromorphic probabilistic processors, or emerging room-temperature quantum hardware. Backend selection mechanisms evaluate factors such as the mathematical structure of the problem, the required computational precision, latency or throughput constraints, and the current availability of resources within the platform.
Importantly, this orchestration layer is designed to remain transparent to the application developer. Developers interact with the platform through a unified programming interface and abstract problem formulations (e.g., QUBO, Ising, or probabilistic graphical models), while the platform handles the underlying execution strategy. This abstraction allows users to focus on modeling and algorithm design, while the system automatically determines the most effective execution pathway across the available heterogeneous computing infrastructure.
# Runtime and Deployment Model
Source: https://dynex.mintlify.app/platform/runtime-deployment-model
The Dynex runtime environment is designed for flexible, managed execution
# Managed Execution
The Dynex runtime environment is designed for flexible, managed execution. Compute resources may be provisioned dynamically, workloads may be rerouted as needed, and results may be returned incrementally or upon completion, depending on workload characteristics.
# Distributed and Federated Operation
Compute resources supported by Dynex may operate in Dynex-managed environments, partner facilities, or distributed deployments. The platform coordinates execution across these environments while maintaining a unified user experience.
# Workflow: Formulation and Sampling
Source: https://dynex.mintlify.app/platform/workflow
The standard Dynex SDK workflow from problem definition to result analysis
# Workflow: Formulation and Sampling
Every computation on Dynex follows the same pattern: define a model, configure a backend, sample, and analyze results.
## Full Example
```python theme={null}
import dynex
import dimod
from dynex import DynexConfig, ComputeBackend
# Step 1: Build the problem model
bqm = dimod.BinaryQuadraticModel(
{0: -1.0, 1: -1.0},
{(0, 1): 2.0},
0.0,
'BINARY'
)
# Step 2: Configure the compute backend (GPU = Dynex neuromorphic chips)
config = DynexConfig(compute_backend=ComputeBackend.GPU)
# Step 3: Wrap model and create sampler
model = dynex.BQM(bqm)
sampler = dynex.DynexSampler(model, config=config, description="My optimization job")
# Step 4: Sample
sampleset = sampler.sample(
num_reads=1000,
annealing_time=200,
shots=5,
)
# Step 5: Inspect results
best = sampleset.first
print(f"Best sample: {best.sample}")
print(f"Best energy: {best.energy}")
# Iterate over all samples
for sample, energy in sampleset.data(['sample', 'energy']):
print(f" {sample} → energy {energy:.4f}")
```
## Step 1: Choose a Model Type
Select the model class that best fits your problem:
| Model | Class | Use when |
| --------------------------- | ----------- | ------------------------------------------ |
| Binary Quadratic Model | `dynex.BQM` | Natural QUBO/Ising formulation |
| Constrained Quadratic Model | `dynex.CQM` | Constraints are central to the problem |
| Discrete Quadratic Model | `dynex.DQM` | Variables have more than 2 possible values |
See [Defining Models](/annealing/models) for detailed examples of each type.
## Step 2: Choose a Compute Backend
```python theme={null}
from dynex import DynexConfig, ComputeBackend, QPUModel
# GPU — Dynex neuromorphic chips, primary production backend
config = DynexConfig(compute_backend=ComputeBackend.GPU)
# QPU — specific quantum hardware model
config = DynexConfig(
compute_backend=ComputeBackend.QPU,
qpu_model=QPUModel.APOLLO_RC1
)
# CPU — lightweight network jobs and connectivity testing
config = DynexConfig(compute_backend=ComputeBackend.CPU)
# LOCAL — offline testing, no credentials required
config = DynexConfig(compute_backend=ComputeBackend.LOCAL)
```
Use `GPU` for all production workloads — it runs on Dynex's own neuromorphic chips distributed globally. Use `LOCAL` for offline development and unit tests.
## Step 3: Build Sampler
```python theme={null}
sampler = dynex.DynexSampler(
model,
config=config,
description="Optional job description",
logging=True
)
```
## Step 4: Run Sampling
```python theme={null}
sampleset = sampler.sample(
num_reads=1000, # Number of parallel reads
annealing_time=200, # Integration depth (ODE steps)
shots=5, # Minimum solutions from network
preprocess=False, # Enable preprocessing for QPU
)
```
**Parameter guidance:**
| Parameter | GPU (small/test) | GPU (production) | QPU |
| ---------------- | ---------------- | ---------------- | ------- |
| `num_reads` | 100–500 | 1000–10000 | 1–100 |
| `annealing_time` | 50–200 | 200–1000 | 10–1000 |
| `shots` | 1 | 1–5 | 1–5 |
QPU backends have tighter hardware constraints: `num_reads` must stay within 1–100, `annealing_time` within 10–1000, and `shots` up to 5.
## Step 5: Analyze Results
The sampler returns a dimod `SampleSet`:
```python theme={null}
# Best solution
best = sampleset.first
print(best.sample) # {0: 1, 1: 0, 2: 1, ...}
print(best.energy) # -3.14159
# All samples sorted by energy
for sample in sampleset.samples():
print(sample)
# As pandas DataFrame
df = sampleset.to_pandas_dataframe()
print(df.head())
# Number of occurrences
for sample, energy, num_occ in sampleset.data(['sample', 'energy', 'num_occurrences']):
print(f"Energy {energy:.3f} occurred {num_occ} times")
```
## Step 6: Iterate
Tune your model and parameters:
* **Better solutions** → increase `num_reads` and `annealing_time`
* **Faster results** → decrease `annealing_time`, use CPU instead of QPU
* **Constrained problems** → switch from BQM to CQM
* **Large-scale** → use QPU backend with `preprocess=True`
## Migrating from legacy SDK
| Legacy | Current |
| ------------------------------------ | --------------------------------------------------- |
| `sampler.sample(..., mainnet=True)` | `DynexConfig(compute_backend=ComputeBackend.CPU)` |
| `sampler.sample(..., mainnet=False)` | `DynexConfig(compute_backend=ComputeBackend.LOCAL)` |
| `sampler.sample(..., v2=True)` | Remove `v2=True` — no longer needed |
| REST-based communication | gRPC-based communication (automatic) |
# Quickstart
Source: https://dynex.mintlify.app/quickstart
Run your first quantum computation in under 5 minutes
## Prerequisites
* Python 3.11+
* A Dynex SDK key ([get one at dynexcoin.org](https://dynexcoin.org))
## Install
```bash theme={null}
pip install dynex
```
## Configure credentials
Set your SDK key as an environment variable, or create a `.env` file in your project root:
```bash theme={null}
# .env
DYNEX_SDK_KEY=your_sdk_key_here
DYNEX_GRPC_ENDPOINT=quantum-router-engine-grpc.hz.dynex.co:3000
```
Install `python-dotenv` to auto-load `.env` files: `pip install python-dotenv`
## Your first annealing job
The following example creates a simple Binary Quadratic Model and samples it on the Dynex neuromorphic GPU network:
```python theme={null}
import dynex
import dimod
from dynex import DynexConfig, ComputeBackend
# Build a simple BQM: minimize x0 + x1 with interaction penalty
bqm = dimod.BinaryQuadraticModel(
{0: -1.0, 1: -1.0},
{(0, 1): 2.0},
0.0,
'BINARY'
)
# Configure to use Dynex neuromorphic GPU chips
config = DynexConfig(compute_backend=ComputeBackend.GPU)
# Wrap model and create sampler
model = dynex.BQM(bqm)
sampler = dynex.DynexSampler(model, config=config, description="My first Dynex job")
# Sample
sampleset = sampler.sample(num_reads=1000, annealing_time=200)
# Inspect results
best = sampleset.first
print(f"Best sample: {best.sample}")
print(f"Best energy: {best.energy}")
```
`ComputeBackend.GPU` is the primary Dynex backend — your job runs on Dynex's own neuromorphic GPU chips distributed globally. For offline testing without credentials, use `ComputeBackend.LOCAL` with the local solver binary.
## Your first quantum circuit
Run a PennyLane circuit on Dynex using the `DynexCircuit` class:
```python theme={null}
import pennylane as qml
from dynex import DynexConfig, ComputeBackend, DynexCircuit
# Define a simple 2-qubit circuit
def bell_circuit(params):
qml.Hadamard(wires=0)
qml.CNOT(wires=[0, 1])
return qml.state()
# Configure QPU backend
config = DynexConfig(
compute_backend=ComputeBackend.QPU,
qpu_model='apollo_rc1'
)
dynex_circuit = DynexCircuit(config=config)
result = dynex_circuit.execute(
bell_circuit,
params=[],
wires=2,
method='measure'
)
print("Circuit result:", result)
```
## Next steps
Learn about BQM, CQM, and DQM models
Sampling parameters and backends explained
LOCAL, CPU, GPU, and QPU backends
Grover's, Shor's, QFT, and more