Repository navigation
Development and Contribution Guide
Set up a source development environment, find the owning module, run meaningful checks, and submit a focused contribution for review.
Scope: Concrete commands and policies are checked against FlagQuantum v0.3.1, commit 5714b569cfc94e212b6d175eb7c87e1f36d8cf9d, on October 20, 2026. An isolated macOS ARM64 checkout was built editable using Python 3.12.14 and an existing compatible PyTorch 2.13.0 runtime. Verification passed 41 existing focused tests, the illustrative regression test below, and architecture/dependency/ownership checks. Hook installation and tier plans were inspected; the complete pre-push gate, full CI matrix, Linux/Windows builds, and accelerator/provider checks were not all executed for this page. A macOS editable native-loader issue required the process-scoped diagnostic described below.
For a new contribution, start from the current upstream main and follow the instructions in that checkout. The pinned release provides a reproducible reference; its detailed checks may differ from a newer branch.
| Document | What it governs |
|---|---|
CONTRIBUTING.md |
Contributor setup, hooks, pull requests, and commit conventions. |
AGENTS.md and applicable directory instructions |
Ownership, engineering boundaries, compatibility, and verification policy. |
docs/development/PYTHON_ENGINEERING_STANDARD.md |
Readability, types, behavioral tests, error/resource ownership, and documentation. |
ARCHITECTURE.md and domain READMEs |
Where implementation belongs and how the domain is used/tested. |
docs/development/TESTING.md |
Test markers, local tiers, optional dependencies, and hardware evidence. |
docs/development/PUBLIC_API_PROTECTION.md |
Protected API/schema changes and the proposal/review process. |
.pre-commit-config.yaml and .github/workflows/ci.yml
|
Executable commit hooks and CI checks. |
Repository contributions use English, including comments, docstrings, errors, tests, examples, and documentation, subject only to the narrowly documented workshop localization exception. Keep the repository's engineering rules authoritative; this Wiki does not replace them.
Report ordinary bugs with a minimal reproducer, versions, expected/observed behavior, and traceback. Search existing issues first. Report a security vulnerability through SECURITY.md, rather than posting exploit details or credentials in a public issue.
git clone --branch v0.3.1 --depth 1 https://github.com/flagos-ai/FlagQuantum.git FlagQuantum-dev-reference
cd FlagQuantum-dev-reference
git rev-parse HEADExpected revision:
5714b569cfc94e212b6d175eb7c87e1f36d8cf9d
A tag checkout can be detached; it is suitable for reproducing these examples. Some provenance and push checks need history and refs that a depth-1 tag clone does not contain. Use a normal full-history contribution clone for that workflow; a shallow clone's missing history must not be reported as successful evidence validation.
Fork the project on GitHub, then replace YOUR_GITHUB_USER and the example branch name:
git clone https://github.com/YOUR_GITHUB_USER/FlagQuantum.git FlagQuantum-contrib
cd FlagQuantum-contrib
git remote add upstream https://github.com/flagos-ai/FlagQuantum.git
git fetch upstream main
git switch -c fix/your-change upstream/main
git status --shortExpected outcomes: the branch is created from upstream main, and a new clean checkout prints no short-status entries. These are workflow commands; no user fork, branch push, or PR was created while validating this page.
Ordinary work uses a short-lived branch and pull request. The coordinated multi-team branches/worktree names in policy files are reserved for that optional mode; follow INTEGRATION_WORKFLOW.md for ordinary contributions. Keep one writer per worktree and preserve unrelated changes in existing checkouts.
Use Python 3.12 for the shortest path matching the quality lane. The release supports Python 3.10–3.12. Core runtime PyTorch is >=2.10,<2.15; the contributor/quality setup explicitly selects 2.13.x.
Editable installation compiles package-local C++ operators. Install a working platform C++ toolchain compatible with PyTorch and the checkout's setup.py: a suitable Linux compiler/build environment, Apple's command-line developer tools, or the supported Windows C++ build environment. The release build specifies C++17 flags and can link OpenMP according to the installed PyTorch runtime. A prebuilt end-user wheel does not remove source-development toolchain requirements.
From the checkout root:
python3.12 -m venv .venv
source .venv/bin/activate
python -m pip install --upgrade pip setuptools wheelOn Linux with upstream CPU PyTorch:
python -m pip install "torch>=2.13,<2.14" --index-url https://download.pytorch.org/whl/cpu
python -m pip install --no-build-isolation -e ".[dev]"On macOS Apple Silicon, install the compatible upstream wheel from the default index:
python -m pip install "torch>=2.13,<2.14"
python -m pip install --no-build-isolation -e ".[dev]"py -3.12 -m venv .venv
.\.venv\Scripts\Activate.ps1
python -m pip install --upgrade pip setuptools wheel
python -m pip install "torch>=2.13,<2.14" --index-url https://download.pytorch.org/whl/cpu
python -m pip install --no-build-isolation -e ".[dev]"Use the venv's Python directly if activation is unavailable. For accelerator development, install the matching supported runtime first using Accelerator Setup; retain vendor-managed PyTorch where required.
The important build order is PyTorch first, editable build second. --no-build-isolation deliberately reuses the compatible installed runtime. The isolated wheel-build requirements in pyproject.toml target an older Stable ABI build lane and are a separate packaging concern. Do not silently replace a vendor runtime or infer compatibility outside the declared range.
The dev extra supplies pytest, coverage/xdist, Ruff, Black, mypy, build tooling, pre-commit, and YAML support. It does not install every optional simulator, SDK, compiler plugin, or accelerator. Add the documented extra only for the surface you are testing, for example:
python -m pip install --no-build-isolation -e ".[dev,qiskit]"Optional extras have their own Python/version markers. Read pyproject.toml and the selected test lane before assuming an integration is present.
python -c "import flagquantum as fq, torch; print('FlagQuantum:', fq.__version__); print('PyTorch:', torch.__version__); print('Imported package:', fq.__file__)"Reference output shape:
FlagQuantum: 0.3.1
PyTorch: 2.13.0
Imported package: <your checkout>/flagquantum/__init__.py
The path should identify the intended editable checkout. A different installed copy, local module shadow, stale binary, or changed working directory can make tests exercise unexpected code. For a standard pip environment, also run python -m pip check; a healthy dependency set reports No broken requirements found. The verification environment here reused an existing compatible runtime rather than recreating every dependency from fresh pip downloads.
| Path | Owns |
|---|---|
flagquantum/__init__.py, _api.py, circuit.py
|
Reviewed public facade and circuit-facing composition. Package-root files are a closed set, not a place for new domain implementations. |
flagquantum/core/ |
Vendor-neutral IR, schemas, parameters, and shared semantics. |
flagquantum/compiler/ |
Program transformations, target legalization, routing, and emission. |
flagquantum/runtime/ |
Planning, execution lifecycle, coordination, results, and runtime evidence. |
flagquantum/simulation/ |
Numerical state evolution and differentiation methods. |
flagquantum/compute/, remote/
|
Directly controlled resources versus external task systems. |
flagquantum/ecosystem/ |
Optional framework adapters; external objects stop at that boundary. |
flagquantum/noise/, lindblad/, qec/, twin/
|
Noise descriptions and the corresponding domain workflows. |
flagquantum/observables/, deployment/, services/, algorithms/
|
Output semantics, sealed deployment artifacts, and application composition. |
flagquantum/benchmarking/ |
Maintained reproducible measurement runners. |
tests/, contracts/
|
Behavioral checks, conformance, and versioned contracts. |
docs/, examples/, notebooks/
|
Product/developer documentation and executable learning workflows. |
tools/, .github/
|
Repository automation and CI, outside runtime dependencies. |
benchmarks/ |
Research/comparison scripts, manifests, raw evidence, and reports. |
Read the relevant domain README before editing. Compiler transforms a program; Runtime organizes execution; Simulation computes numerical results. Keep optional vendor/provider types out of Core and avoid new dependencies or parallel configuration/contract systems without a concrete reviewed need.
Identify ownership using team-ownership.toml. For example, this existing simulation/test path pair is accepted:
python tools/check_team_scope.py --team simulation --files flagquantum/simulation/statevector/operations.py tests/smoke/test_smoke_baseline.pyObserved output:
team ownership policy passed
Use the actual team and changed paths for your contribution. Protected integration surfaces—such as public contracts, architecture policy, CI/tooling, and dependency manifests—require their separately coordinated change process. Ordinary work should usually stay within one primary domain.
All commands in this section run from the checkout root with the development environment active.
python -m pytest tests/smoke/test_smoke_baseline.py -qRelevant summary observed at the pinned revision:
3 passed in 0.67s
This covers imports, a minimal Bell circuit, and parameter autograd. Durations vary; three selected tests passing does not certify the whole repository.
A focused native/gradient check used for this guide is:
python -m pytest tests/test_native_circuit.py::test_native_bell_state tests/test_gradient_api.py -qObserved summary:
38 passed in 1.35s
These tests passed on the local CPU environment. Some Python simulation paths can work even when a native extension fails to load, so ordinary smoke success is not proof that a specific native optimized kernel was exercised.
For illustration, save as tests/smoke/test_ry_regression.py on your contribution branch:
"""Check the analytic RY expectation and its parameter gradient."""
import pytest
import torch
import flagquantum as fq
pytestmark = pytest.mark.smoke
def test_ry_expectation_and_autograd() -> None:
"""RY(theta) gives <Z> = cos(theta) and derivative -sin(theta)."""
theta = torch.tensor(0.3, requires_grad=True)
options = fq.ExecutionOptions(mode="statevector", backend="pytorch", device="cpu")
result = fq.run(
fq.Circuit(1).ry(0, theta),
outputs=fq.expectation(fq.Z(0)),
options=options,
)
value = result.expectation().sum()
torch.testing.assert_close(value, torch.cos(theta.detach()), atol=1e-6, rtol=0.0)
value.backward()
assert theta.grad is not None
torch.testing.assert_close(
theta.grad, -torch.sin(theta.detach()), atol=1e-6, rtol=0.0
)Run:
python -m pytest tests/smoke/test_ry_regression.py -qExpected result: 1 passed, with elapsed time depending on the host. This exact test was executed and passed during page validation. It checks <Z>=cos(theta) and the independent derivative -sin(theta), rather than merely checking that a function exists.
Adapt the pattern to the actual regression. Avoid adding a duplicate test solely to increase a count. Include boundary/refusal behavior and relevant user scenarios; use contract snapshots for protected serialization only under the applicable API process. Add the appropriate marker so a real CI lane selects the test. An empty selection or an all-skipped selection is not evidence for the intended behavior.
Inspect tier definitions without running them:
python tools/ci_tier.py --list
python tools/ci_tier.py pr-default --dry-runThe dry-run output includes this shape:
+ <active Python executable> -m pytest -m smoke or unit -q
It prints a command plan, not a test result. For direct shell execution, quote marker expressions as shown below.
| Change / purpose | Actual execution command | Boundary |
|---|---|---|
| Every ordinary change's baseline | python tools/ci_tier.py pr-default |
Seeded smoke/unit health, not whole CI or hardware readiness. |
| Local API/runtime/planner/compiler changes | python tools/ci_tier.py pr-runtime |
Local integration, not multi-process transport. |
| Distributed metadata/planning, benchmark contracts, or release-gate logic | python tools/ci_tier.py pr-distributed |
CPU distributed semantics plus contract checks, not real multi-GPU scalability. |
| Accelerator-backed changes | python tools/ci_tier.py gpu-scheduled |
Requires actual configured hardware and dependencies. |
| Multi-node transport/workloads | python tools/ci_tier.py multinode-scheduled |
Requires the documented configured hosts, storage/network, and launch workflow. |
| Release validation | python tools/ci_tier.py release |
Broad release/audit workflow; successful local tests alone do not replace it. |
Direct marker commands remain useful for focused work:
python -m pytest -m "smoke or unit" -q
python -m pytest -m "integration" -q
python -m pytest -m "benchmark_contract or release_gate" -qThese broader tiers are instructions for contributors, not checks claimed to have all passed during this page's validation. Required checks depend on the change; run the smallest meaningful set first, then the required wider tiers. Keep the selected count, failures, skips, and environment in the result report.
For coverage, use the lane's configured command and report the measured scope. The engineering standard targets meaningful coverage above 95%, including branches; a percentage alone is not proof of correctness. Do not suppress failures, weaken assertions, or reclassify unsupported behavior just to make the gate green.
Optional integration tests need their specific extras. Hardware tests require a matching runner/device; CPU fallback, a fake provider, or distributed CPU semantics cannot substitute for actual accelerator/QPU evidence. See Reproducibility and Benchmarks before making performance or scalability claims.
Install hooks in the activated development environment:
pre-commit installFor a checkout without a conflicting hooks configuration, expected output is:
pre-commit installed at .git/hooks/pre-commit
pre-commit installed at .git/hooks/pre-push
The versioned configuration installs both hook types. Many hooks use tools from the active environment; keep that environment active when committing/pushing. Initial hook execution can need network access to initialize its pinned external hook environment.
Run commit-stage hooks explicitly when needed:
pre-commit run --all-files --hook-stage pre-commit --show-diff-on-failureThe hooks cover whitespace/syntax, English content, architecture/hygiene, generated operator/runtime/docs contracts, documentation links, public API checks, Ruff, Black, and strict typing. Some hooks can modify files; review the diff and rerun rather than treating a formatting failure as a completed check.
Representative CI quality commands are:
ruff check flagquantum tests tools
black --check flagquantum tests tools
mypy --strict --python-version 3.12 --ignore-missing-imports flagquantum
python tools/check_architecture.py
python tools/check_dependency_policy.py
python tools/check_team_scope.py --validateObserved output from the three structural checks:
architecture boundaries passed
dependency policy passed
team ownership policy passed
Ruff/Black were also checked on the illustrative regression test. The complete repository-wide lint/type command set above is not claimed to have been executed for this page. Follow the exact CI/hook configuration for the remaining contracts and tooling type checks; the short list is not a replacement for them.
python tools/pre_push.py --dry-run
python tools/pre_push.pyThe first prints the gate; the second actually executes it. In this release the plan contains 46 stages, including commit-stage hooks, strict types, domain contracts, evidence/ownership checks, and CPU-safe test tiers. The dry-run can still finish with the text FlagQuantum pre-push gate passed. That line after --dry-run means only that planning completed, not that the checks ran or passed.
The local push gate does not reproduce clean Python/version matrices, package installation across operating systems, supply-chain checks, or accelerator jobs. Required GitHub checks remain authoritative, and protected branches must not merge until their required checks pass.
- Use precise parameter/return annotations, focused functions, and the existing domain records. Validate external input before coercion; preserve actionable errors and explicit resource cleanup.
- Keep optional dependencies isolated and lazily imported. A new production dependency needs a documented requirement, ownership, license/supply-chain review, replacement interface, and exit plan.
- Use public
fq.*workflows in user examples. Public workflow docstrings need a shortest supported executable example; docstring examples must not require credentials, paid submissions, or unavailable hardware. - Preserve protected exports, signatures/defaults, result fields, enums, exceptions, and serialized schemas. A protected change requires explicit authorization and an approved API-change proposal, compatibility/migration analysis, and the required conformance checks. Do not edit snapshots merely to silence a failure.
- Update implementation documentation and the authoritative capability/limitation records when a support boundary changes. Regenerate derived documents through their owning tools instead of creating conflicting manual copies.
- Keep measured raw evidence intact. State actual execution semantics, accuracy, fallback, and claim limits; a plan or passing mock test does not establish hardware behavior.
A bug fix within an existing contract should stay small and explain its changed behavior. A new public contract or cross-domain change should follow the reviewed contract process before parallel implementations depend on it.
After implementing and testing the focused change:
git diff --check
git diff --stat
git status --short
git add path/to/changed-file.py path/to/relevant-test.py
git commit -m "Fix the specific behavior"
git push -u origin fix/your-changeReplace the paths and branch with the actual contribution. Review generated changes before staging; include only the intended files. git diff --check prints nothing on success. Commit/push commands trigger the installed gates; inspect their actual exit status and logs. The commands above are a workflow template, not mutations performed on a contributor's repository for this page.
Open a pull request to flagos-ai/FlagQuantum, base main. A useful PR description explains:
- The concrete problem and the resulting behavior, with a small before/after example when helpful.
- The implementation/domain scope and any compatibility or numerical tradeoff.
- Exact checks run, their results, and checks requiring a different environment.
- Updated documentation, examples, issue links, and required API proposal/evidence references.
Use imperative present-tense commit subjects, keep the first line at most 72 characters, and put issue/PR references after the subject. Follow any current PR template. Reviewers should be able to assess the final change without reading a chat transcript.
Address review feedback with focused commits and rerun the checks affected by the changes. A failed or missing required CI check is not approval. Merge through the repository's review/protection policy; the local hook's success does not authorize bypassing it.
| Problem | Action |
|---|---|
| Build cannot import Torch | Install the compatible runtime first in the active environment, then use the documented --no-build-isolation editable command. |
| A compiler/header/toolchain error occurs | Check the platform toolchain, Python architecture, selected PyTorch build, and first failing compiler/linker diagnostic. Rebuilding a source extension is different from installing a wheel. |
| Tests import the wrong checkout | Inspect fq.__file__, sys.executable, editable metadata, current directory, and stale build outputs. |
Hook install says core.hooksPath is set |
Inspect git config --show-origin --get core.hooksPath and integrate with the existing hook policy. Do not blindly unset shared/global configuration. |
The push gate cannot resolve origin/main or evidence history |
Use a properly fetched contribution checkout with the expected refs/history; the reference tag's shallow clone is insufficient for some checks. |
| A marker selects nothing or only skips | Check the actual marker, dependencies, and hardware lane; report the missing validation rather than calling it passed. |
| Generated contract checks fail | Inspect the owning source and generation tool; a protected API/schema change needs its process, not an arbitrary baseline update. |
| A GPU/provider test passes with a fake or CPU path | Report that scope accurately and obtain the required hardware evidence separately. |
The editable build tested here compiled successfully, but the native extension initially failed to load @rpath/libomp.dylib from the source-tree layout. The Python smoke/gradient tests still passed, illustrating why they cannot certify native-kernel availability.
For this specific loader error, the following process-scoped diagnostic uses the installed Torch library directory without changing global linker configuration:
import os
import subprocess
import sys
from pathlib import Path
import torch
library_dir = str(Path(torch.__file__).parent / "lib")
environment = os.environ.copy()
environment["DYLD_LIBRARY_PATH"] = os.pathsep.join(
item
for item in (library_dir, environment.get("DYLD_LIBRARY_PATH", ""))
if item
)
subprocess.run(
[
sys.executable,
"-c",
"from flagquantum.simulation.native_cpu import adjoint; "
"assert adjoint.native_cpu_adjoint_available(), repr(adjoint._EXTENSION_ERROR); "
"print('Native CPU adjoint available: True')",
],
env=environment,
check=True,
timeout=30,
)Save as a temporary diagnostic script and run it with the same development interpreter. Observed output:
Native CPU adjoint available: True
This is a contributor diagnostic for the observed macOS source-layout issue, not a cross-platform packaging fix or a claim that a standard editable environment loads every native kernel. Retain the original loader traceback, verify actual native availability, and use the appropriate build/packaging workflow when fixing it. The installed end-user wheel and other operating systems require their own checks.
Technical sources below are pinned to v0.3.1. Use the corresponding files on your contribution branch for current requirements:
- Contribution guide · Repository operating rules
- Python engineering standard
- Architecture map · Ownership policy
- Testing manual · Tier runner
- Integration workflow · Public API protection
- Build/dependency declarations · Native extension build
- Hook configuration · Pre-push runner · CI workflow
- Security reporting
- Installation and Compatibility · Reproducibility and Benchmarks · Troubleshooting and FAQ
- Installation and Compatibility
- Quick Start
- Install and Run
- Qubit Ordering and Result Conventions
- Runnable Examples
- Building and Simulating Circuits
- Training Parameterized Circuits
- Hybrid Classical-Quantum Models
- Core Concepts
- From Papers and Equations to FlagQuantum Code
- Reproducing Molecular Hydrogen VQE
- Fundamentals
- Tutorials
- Choosing a Simulation Method
- Accelerator Setup
- Distributed Simulation and Training
- Execution
- Circuit Compilation and Interoperability
- Noise and Open-System Simulation
- Quantum Error Correction Experiments
- Cloud and Quantum Hardware Execution
- QPU Digital Twins
- Advanced Topics
- Support and Contribution
All 21 guides are linked in the navigation sections. The Wiki Directory lists published guides and current repository resources.
- Troubleshooting and FAQ
- Reproducibility and Benchmarks
- Development and Contribution Guide
- Documentation Guide
Documentation, capability, and contribution links in this section follow current main; the guides above target 0.3.1.