FlagQuantum Examples
September 20, 2026 · View on GitHub
Runnable, copy-ready workflows for building and training quantum AI programs with the current FlagQuantum API.
Examples driven by the root-level fq alias use:
import flagquantum as fqas the public entry point;fq.Circuit(n_qubits=...)for circuit construction;- PyTorch for parameters, gradients, and optimizers;
- explicit runtime and distribution semantics when making performance claims.
These examples do not use that alias:
algorithms/—pca.py,kmedians.py,quantum_kernel.py,feature_selection.py,qarm.pyandsvd.py, which import the unit they demonstrate from the subpackage surface becauseflagquantum.algorithms.<unit>carries no root-levelfq.name.docs/guides/ALGORITHMS.mdis the per-unit reference they follow, and the place each unit's advantage premise is recorded in full.extensions/reference_extensions.pyandextensions/reference_compiler_extension.py— they import the extension and ecosystem APIs, and the second also importsCircuitIRfrom the root rather than through the alias.remote/jiuding_submit.py— it imports its client.single_machine_quantum_ai/common.py— a shared helper for the examples beside it, which imports no FlagQuantum at all.
For exact support levels, consult the capability catalog.
Three local basics
Start with three small programs that use only the stable fq.* API:
python -m examples.local.simulate
python -m examples.local.measure
python -m examples.local.train
They cover local statevector simulation, exact and sampled measurements, and PyTorch-native training without credentials, remote resources, or optional backends. See the annotated local guide before moving to configurable research examples.
First CPU execution
Start with the complete local execution path:
python -m examples.cpu_statevector
The example builds a Bell-state circuit, creates an inspectable execution plan, runs that exact plan on the PyTorch CPU statevector engine, and checks the double-precision result against its analytical state. It disables backend fallback so a successful run proves the reported CPU path was actually used.
To inspect target-independent compiler optimization separately:
python -m examples.compiler_optimize
This example removes redundant gates, verifies that optimization reaches a
fixed point, and compares the optimized program with the original numerical
result. It uses compiler.optimize; target-aware lowering and routing belong to
compiler.compile.
Compile non-local gates for a concrete hardware topology with:
python -m examples.target_aware_compilation
The example targets a five-qubit line, checks every emitted two-qubit operation against that connectivity, verifies logical-wire restoration, and executes the compiled IR against the original result.
Start in one minute
From an editable development installation:
python examples/quick_start.py --mode sv --steps 40
This trains a hybrid model with a torch.nn.Linear encoder and an fq.Module
quantum layer in one PyTorch optimizer loop. The example uses an analytical
target, so it reports correctness as well as training loss.
Switch the simulation representation without rewriting the model:
python examples/quick_start.py --mode mps --steps 40
python examples/quick_start.py --mode tn --steps 40
Statevector is the recommended first run. MPS and tensor-network support boundaries are listed in the capability catalog.
Choose a workflow
| Goal | Recommended entry | Scope |
|---|---|---|
| Learn circuits, measurements, gradients, and QML | Tutorials | Guided notebooks |
| Run one quantum algorithm unit end to end | Algorithm examples and the algorithms guide | Demonstration-scale units, subpackage surface |
| Verify the local CPU or one-GPU path | Single-machine quantum AI | Supported local workflows |
| Train a local statevector VQE | 01_vqe_statevector.py | Exact differentiable simulation |
| Train with MPS | 03_mps_training.py | Low-entanglement systems |
| Use a JAX kernel through PyTorch | 04_jax_kernel_torch_layer.py | Optional accelerator path |
| Inspect sharded statevector ownership | Distributed statevector | One logical statevector across ranks |
| Inspect rank-owned MPS execution | Distributed MPS | Development evidence |
| Train and package a circuit | train_parameterized_circuit_then_deploy.py | Deployment bridge |
| Build an extension | extensions/reference_extensions.py | Experimental API |
Larger application and research examples are intentionally not presented as minimal getting-started paths.
Run on remote resources
After completing the local examples, use the provider-specific golden paths:
python examples/remote/quafu_bell.py
python examples/remote/jiuding_workspace_bell.py
The Quafu path compiles and validates a circuit before submitting it to a QPU.
The Jiuding path reuses a running workspace for low-latency remote compute.
Both require provider credentials and configured remote resources.
Use --list-workspaces first when the account can see more than one Jiuding
workspace; a single visible workspace is selected automatically.
Plan before execution
Use the runtime planner when you need to inspect representation choice, gradient support, or blockers before running:
import flagquantum as fq
circuit = (
fq.Circuit(n_qubits=4)
.h(0)
.cx(0, 1)
.rzz(1, 2, theta=0.2)
)
plan = circuit.runtime_plan(prefer_jax=True, require_gradients=True)
print(plan.summary())
A plan is an explanation of intended execution, not benchmark evidence.
Performance and scalability statements must use runtime-generated records and
report their distribution_semantics.
Recommended smoke runs
These small commands are suitable for checking a development environment:
python examples/single_machine_quantum_ai/00_local_fast_path_check.py
python examples/single_machine_quantum_ai/01_vqe_statevector.py \
--backend torch --steps 2 --n-qubits 3
python examples/single_machine_quantum_ai/02_quantum_classifier.py --steps 2
python examples/single_machine_quantum_ai/03_mps_training.py \
--steps 2 --n-qubits 4 --max-bond 8
Optional JAX check:
python examples/single_machine_quantum_ai/04_jax_kernel_torch_layer.py \
--steps 1 --bench-iters 1
The curated single-machine examples do not initialize distributed backends and make no distributed scalability claim.
Example quality contract
A curated example must:
- state the task, runtime mode, and maturity boundary;
- expose practical arguments for problem size, steps, and device;
- run end to end from a documented installation;
- report a correctness metric or an explicit reference value;
- identify local, replicated, sliced, or sharded execution accurately;
- use stable public API unless explicitly labeled experimental.
Shared helpers belong next to the examples that use them. Example-only convenience code must not become a framework abstraction without a separate API review.