feat(fermion): measure native one-body density tensors (#1179)
Adds experimental native fermionic one-body density measurement and one-body energy reconstruction. Previously users could express density monomials individually but lacked a reusable ordered measurement and tensor assembly path. The new concrete Algorithms module returns Hermitian observables for gamma[p,q] = <a†p aq> and assembles ordinary complex PyTorch tensors from their real expectations.
Algorithms owns both operations; callers keep executing through
fq.run. There is no new runtime, RDM class, dependency, root export or protected contract change. OpenFermion and Cirq are scientific references only and are not imported. The scope was committed before implementation indocs/development/FERMION_ONE_BODY_DENSITY.md.User workflow
python -m examples.algorithms.fermion_one_body_density --encoding parity python -m examples.algorithms.fermion_one_body_density --encoding bravyi_kitaevBoth use explicitly matched two-mode coherent one-particle preparations and the same native measurement/tensor consumer. Expected particle number:
1.0000000000; reconstructed energy:0.4520082847; circuit-angle gradient:-0.5016897975; direct-energy residual: below1e-12. Omitting--encodingselects JW. Normal execution uses X/RY/CX/S gates without dense reference state loading or diagonalization.Verification
CI correction: the original head omitted the new density module from the existing executable-docstring entry list. Both failed Linux checks reported
test_every_module_with_examples_is_covered. Commit184a07264adds the realone_body_density_observablesentry to that list; no assertion or production behavior is changed. The full docstring gate and density unit/integration tests pass locally together (47 tests). Ruff, Black and Algorithms ownership pass. On corrected head184a072641faffd10eeeca52a9e974492fed6906, both previously failed Linux jobs now pass:cpu-core-3-12-tests(8m25s) andcoverage-shard (138, 2)(4m47s). Both native-fermion Python lanes also pass. Latest exact-head snapshot: 217 successful checks, 3 conditional skips, 19 still running, no failures. The full CI run is not yet complete.
- 47 density unit/integration and selected example checks pass on macOS CPU: independent occupation-bit action, vacuum/determinant/complex/correlated states, JW/parity/BK replacement, particle number, spectral bounds, complex orbital rotations via independent two-particle minors, direct energy comparison, analytic/finite-difference gradients and optimizer update.
- Another 71 existing encoding/algebra/dependency-isolation/public-API candidate regressions pass.
- Fresh subprocesses run all three encodings while OpenFermion, Cirq, external science SDK imports and eigensolvers are blocked.
- Strict module typing, Ruff, Black, architecture boundaries, Algorithms path ownership, protected API baseline, generated-document consistency, repository language, whitespace and local Markdown links pass.
- The required full
python tools/ci_tier.py pr-defaultrun reached approximately 56% before its 600-second budget expired (exit 124). It is not a pass. Three QFT Hadamard/phase-fusion count assertions intests/team/simulation/test_controlled_phase_graph.pyfail with 44 applications versus expected 28. A focused run produces the identical three failures and eleven passes both on this head and in a separate clean detached checkout of baselineb58fc8a01d9395972042abd1aaa507c9769b73da; the baseline checkout was removed after comparison. No simulation source or assertion is changed by this PR. Linux coverage is left to CI.- Optional coverage instrumentation exited 245 before test output, also with plugin auto-loading disabled. No coverage percentage is claimed; ordinary focused pytest runs pass as recorded above.
Reproduce focused checks:
python -m pytest tests/unit/fermion/test_density.py tests/integration/test_fermion_one_body_density.py tests/test_algorithm_examples.py -k 'density or covered_and_indexed' -q python -m pytest tests/unit/fermion/test_encoding.py tests/unit/test_observables_fermion.py tests/integration/test_native_fermion_isolation.py tests/unit/test_public_api_candidate.py -qLimits and review boundary
single_device_fast_path, exact local CPU expectations; full-register matched encodings supplied by the caller. The assembler validates count, real singleton CPU tensors, dtype agreement and finiteness, and preserves autograd. Same-width state encoding/order cannot be inferred from unlabelled values. Hermiticity is imposed by the measurement design; no physical/noise projection occurs. Float32/complex64 assembly is accepted without a precision-equivalence claim.Observable/output count is O(n²); encoded strings add width-dependent cost and statevector memory remains exponential. Dense occupation references and unitary completions exist only in tests up to four modes. No 2-RDM, molecular two-body energy reconstruction, sampling, hardware, accelerator or distributed support is claimed. Experimental capability registration remains a separate Integration follow-up after scientific acceptance.
Review subtraction: reuse existing FermionOperator, encoders, Observable, native expectations and PyTorch tensors; keep execution outside the science module and leave stable exports unchanged.
版权所有:中国计算机学会技术支持:开源发展技术委员会
京ICP备13000930号-9
京公网安备 11010802047560号
Quantum computing, built for learning.
A PyTorch-first framework for differentiable quantum computing and quantum AI.
Qubit ordering · Quick start · Documentation · Wiki · Examples
Turn quantum circuits into trainable models. FlagQuantum brings PyTorch learning, multiple simulation representations, and hardware execution into one workflow. Its long-term goal is a continuous path from local scientific exploration to distributed training, device modeling, and fault-tolerant quantum computing research.
Support is specific to each backend and workload. Local training and selected distributed paths have correctness evidence. See the validation scope for what has been tested and what remains a research goal.
Qubit ordering: qubit 0 is the most-significant bit
By default, a circuit starts in
|00...0>, with amplitude1at statevector index0and0everywhere else. For example, applyingXto qubit0of|000>produces|100>at index4; applying it to qubit2produces|001>at index1. This matches the tensor-product notation|q0> ⊗ |q1> ⊗ ... ⊗ |q(n-1)>, keeping equations, matrices, and qubit lists in the same left-to-right order.0is the MSBqubit_orderis the MSB[q0, q1, ...][0, 1, ...]0is the LSB0is the LSB0on the left0as the MSBEndianness affects statevector, matrix, and bitstring indexing, not the
(control, target)order of gate arguments. Convert representations at framework boundaries instead of reversing gate arguments. Cloud services commonly expose measurement results rather than raw statevectors, so the service rows describe the order visible at FlagQuantum’s result boundary.Install and train your first quantum model
Requires Python 3.10–3.12. Choose the command for your computer.
macOS (Apple Silicon):
This release publishes macOS wheels for Apple Silicon only; Intel macOS is not a supported binary installation target.
Linux or Windows, CPU only:
FlagQuantum’s compiled extension uses PyTorch’s Stable ABI and is tested with PyTorch 2.10.x through 2.14.x in compatibility CI. New CPU/CUDA environments should use the recommended 2.13.x or 2.14.x runtime above. The first CPU install downloads about 200 MB of PyTorch. On a clean GitHub Ubuntu runner it took about 16 seconds; slower networks will take longer.
NVIDIA GPU: Select a PyTorch 2.13.x or 2.14.x CUDA command from the PyTorch installer, then run:
Installing from source? Follow the short setup in CONTRIBUTING.md.
Native accelerator support: FlagQuantum runs directly on the following vendor-provided PyTorch runtimes.
Keep the vendor runtime installed, then run
python -m pip install flagquantum. The core requirement acceptstorch>=2.10,<2.15, including local version labels such as2.10.0+metax3.8.1.0; do not replace a managed runtime with an upstream CPU/CUDA wheel. Avoid--upgrade/--upgrade-strategy eagerwhen retaining a managed runtime. Theinvertibleextra still requires PyTorch 2.13.x and is not a vendor-runtime installation shortcut.Huawei Ascend 910C support through Torch-FL: Native complex64/complex128 statevector, MPS, tensor-network and density-matrix execution, autograd and hybrid training, noise, TEBD, native dynamics and QEC predecoder training have hardware validation. Sharded statevector/MPS/TN training, two-host communication and checkpoint restart are also covered. Install the fixed source configuration in the 910C guide; previously published wheels alone do not contain the required fixes.
Quantum state, gradients and optimizer updates remain on
flagos. The acceptance record states the measured functions and topology. This is hardware development support; production, performance and capacity certification remain outside the claim. Optional third-party runtimes retain their own hardware requirements.To build a CPU or GPU environment with QSteed and optional JAX, follow the container guide.
Build a two-qubit circuit and learn its rotation angle by minimizing ⟨Z₀⟩.
fq.Moduleexposes the quantum model to PyTorch;outputsselects what to measure after training.For a complete classical–quantum model, follow the hybrid training example. The published wheel contains the
flagquantumpackage only, soexamples/comes from a clone of this repository:git clone https://github.com/flagos-ai/FlagQuantum.gitand run the examples from that working copy.Same circuit. Different execution targets.
The experimental adapters can evaluate the same observable on a Jiuding QuantumAI Cloud GPU workspace or Quafu quantum hardware. Configure the Jiuding QuantumAI Cloud workspace and credentials or the Quafu token before running the corresponding call.
The Jiuding QuantumAI Cloud call above needs
JIUDING_WORKSPACEset to the running workspace name when it is invoked from outside that workspace; inside the workspace the name is discovered automatically. See repeated low-latency workspace execution.Direct Quafu submission is available in the 0.3 release line. Install
flagquantum==0.3.0for this path. With the older 0.2.0 release, use the documented local QSteed compilation path instead: passcompiler="qsteed"after installing the separate FlagQuantum Compiler QSteed plugin, as described in optional local compiler plugin. Thequafuextra does not install that plugin.Jiuding QuantumAI Cloud computes a simulated expectation; Quafu estimates it from hardware measurements. The training example runs on your local machine; these calls evaluate the trained circuit remotely. Live provider access is required and is not certified by the local or A800 checks.
Go further
Connect simulation with device observations. Use QPU digital twins to compare calibration-based model predictions with measured counts. See the experiment guide for task binding and the scope of hardware validation.
Toward fault-tolerant quantum computing. Start with a local QEC memory experiment connecting syndrome extraction, decoding, and correction. Logical operations and hardware feedback are longer-term research goals.
Quantum AI tutorials · Distributed statevector · Distributed MPS · ARCHITECTURE.md
Documentation and Wiki
Start with the Wiki home or browse the Wiki Directory for the full learning path. Find a guide by topic:
The Wiki guides currently target FlagQuantum 0.3.1 and state their verification scope. For versioned API contracts, executable examples, and support boundaries, use the repository documentation, examples, and capability catalog matching your installed release;
maincan describe newer development.Citing FlagQuantum
If you use FlagQuantum in work you publish, cite the software through
CITATION.cff. GitHub renders it under Cite this repository in APA and BibTeX, andcffconvertproduces other formats from the same file, so a citation does not have to be assembled by hand.Cite the version you ran rather than
main: a result is reproducible against the release it was measured on. The file records 0.3.1; adjust the version and date if you ran an earlier release.Support varies by execution path. See the capability catalog for maturity and limitations.
Benchmarks and validated results
Contributing · Apache License 2.0