QuAIRKit Guide
When To Use
Use this skill when a task involves:
- writing or reviewing QuAIRKit code
- reproducing or adapting examples from the official QuAIRKit tutorials
- explaining QuAIRKit APIs for states, circuits, training, plotting, or LOCC
- creating tutorial-like demos for the paper appendix
- integrating a
StateOperatorbackend
First Principles
- Treat the QuAIRKit installed package source as the source of truth.
- Prefer
Circuitas the default user-facing interface. - Use
databasefor construction andqinfofor analysis. - Use
losswrappers for training-oriented code. - When an insertion rule is ambiguous, verify it in code instead of guessing.
Installation
Runtime Install
- Recommended environment: Python 3.10 and PyTorch 2.11.x.
- On supported wheel platforms, use
pip install quairkit. - Release wheels are acceptable if their PyTorch compatibility matches the environment.
Source Install
- Use source install when modifying QuAIRKit itself or when no compatible wheel exists.
- Requirements: active Python environment, PyTorch >= 2.4, and a C++17 toolchain.
- Standard editable install:
pip install -e . --no-build-isolation
- Better IDE compatibility:
pip install -e . --config-settings editable_mode=strict --no-build-isolation
- For VSCode/Pylance,
python.analysis.extraPathsmay still be useful after editable install.
Optional Plotting Dependencies
Circuit.plot()requirespdflatex.- Recommended TeX distribution: TeX Live or MacTeX.
- On macOS, install
popplerif PDF page-count errors appear.
Default Imports
import time
import numpy as np
import torch
import quairkit as qkit
from quairkit import Circuit, State, Hamiltonian, to_state
from quairkit.database import *
from quairkit.loss import *
from quairkit.qinfo import *
Use narrower imports in final user-facing code when that improves readability.
Default Global Setup
- Use
qkit.set_dtype("complex128")when numerical stability matters. - Use
qkit.set_device("cpu")orqkit.set_device("cuda")with PyTorch-style device strings. - Use
qkit.set_seed(seed)when reproducibility matters. - Backend choice, dtype, device, and seed are global settings.
Core Mental Model
Circuitis the main user entry point.Layeris a reusable subcircuit template and is anOperatorList.Stateis the top-level alias users normally see.StateSimulatoris for tensor-level simulation and state inspection.StateOperatoris for execution-style backends such as cloud or shot-based providers.databasebuilds matrices, channels, states, bases, and random data.qinfois the analysis toolbox.lossprovides training-friendly wrappers.OneWayLOCCNetis the only application-level wrapper covered by this skill.
Routing
States, Hamiltonians, to_state, backend switching, or cloud backends
Read api-core.md.
Circuit creation, gates, channels, oracles, measurement, plotting, or QASM2
Read api-circuit.md.
Template layers, encodings, or custom subcircuits
Read api-ansatz.md.
Matrix/state generators, random data, or quantum-information utilities
Read api-database-qinfo.md.
Loss wrappers or OneWayLOCCNet
Read api-loss-application.md.
Training loops, PyTorch integration, hybrid models, or NumPy/Torch interop
Read api-torch.md.
Common workload patterns and tutorial-like reconstruction
Read tutorials-checklist.md.
Default Working Patterns
Writing A New Example
- Decide whether the task is about state preparation, circuit construction, analysis, training, plotting, or backend integration.
- Pick the right API family instead of mixing abstractions randomly.
- Prefer
Circuitplusdatabasefactories for concise examples. - Keep batch shape and
system_dimsemantics explicit. - If plotting or cloud execution is involved, mention external dependencies.
Reproducing A Tutorial
- Use tutorials-checklist.md to identify the target capability and APIs.
- Rebuild the workflow from APIs and patterns, not by copying tutorial cells.
- Preserve the same conceptual pipeline, but simplify constants or logging if the user does not need an exact replica.
- If the tutorial depends on randomness, seed it or state clearly that output is stochastic.
- If the tutorial depends on third-party infrastructure, provide a simulator fallback when possible.
Writing Training Code
- Separate the training objective from the validation metric.
- Prefer numerically stable losses even if the final success metric is different.
- Use the standard loop in api-torch.md.
- For simple VQE-like tasks, the validation metric can be omitted; otherwise keep it.
Non-Negotiable API Conventions
- For trainable built-in layers in
quairkit.ansatz.layer, batched parameters use[batch_size, total_param_num]. Circuit.append(layer)keeps the layer as a child module;Circuit.extend(layer)flattens the layer into its internal operators.- For operator insertion,
int,List[int], andList[List[int]]can mean different things depending on arity. Check api-circuit.md before writing examples. - Build circuits with
Circuit.*; usedatabase.*when you need matrices, channels, or named states outside a circuit. - Do not import from
quairkit.operatorin ordinary user code. Names such asRX,CNOT,Oracle,Collapse, andOneWayLOCCare low-level operator classes, not the default user interface. database.rx(...)returns a matrix (torch.Tensorornumpy.ndarray), not a callable gate object.- Conceptually, state tensors follow
(batch, prob_1, ..., prob_K, state_rows, state_cols). See api-core.md before reshaping or indexing leading dimensions. qinfois more analysis-oriented;lossis more training-oriented.Circuit.measureis structurally different fromloss.Measure.- Only qubit circuits can be exported to OpenQASM 2.0.
- Do not document or recommend
PQCombNetin this skill. - Do not create a separate backend-integration skill; backend integration belongs in the core/backend notes.
Plotting And Paper Integration
Circuit.to_latex()returns Quantikz code.Circuit.plot()depends onpdflatex.- For arXiv, include the Quantikz support file if the archive does not provide it.
- If users only need a publication figure, exporting code and compiling in Overleaf is a valid fallback.
Backend Integration Guardrails
StateOperatorbackends are for shots, execution, and operator-history workflows.- They do not support direct numeric state construction from matrices or state vectors.
- For backend examples, only promise
measureandexpec_valunless the provider explicitly supports more. - Use
SimpleStateOperatoras a lightweight local stand-in when demonstrating interface design.
What To Avoid
- Do not invent undocumented batch rules.
- Do not assume tutorial prose is newer than the source.
- Do not paste large tutorial code blocks when a smaller runnable example is enough.
- Do not mix qubit-only and qudit-aware assumptions silently.
- Do not use Windows-style paths inside the skill files.
Common Pitfalls
Circuit.rx(...),database.rx(...), andquairkit.operator.RX(...)live at three different abstraction levels. Use the first for circuit building, the second for matrices, and avoid the third in ordinary examples.- Not every leading state dimension is an independent training batch. Later leading dimensions can be probability branches created by
measure,locc, orquasi. - Passing a plain
torch.Tensorasparamdoes not register a module parameter. Useparam=Noneor an explicittorch.nn.Parameterwhen the parameter must appear inmodel.parameters(). Circuit.measurechanges circuit structure;loss.Measureconsumes an already prepared state.StateOperatorbackends cannot be initialized from numeric matrices or state vectors.
Deliverable Style
- Keep examples short and runnable.
- Prefer current APIs over deprecated wrappers.
- Use English only.
- If something is uncertain, say it needs verification instead of guessing.
Additional Resources
- State and backend details: api-core.md
- Circuit and plotting details: api-circuit.md
- Layers and encodings: api-ansatz.md
- Data generation and analysis tools: api-database-qinfo.md
- Training and PyTorch usage: api-torch.md
- Tutorial coverage targets: tutorials-checklist.md
Source: QuAIR/QuAIRKit — distributed by TomeVault.