benchmark 包 API 参考

benchmark 是纯 Python 包(唯一要求的环境依赖是各模拟器 wheel 与 matplotlib),入口为 python -m benchmark。模块按数据流组织:IR → 注册表 → 线路/噪声生成 → 后端适配 → 运行器 → 图表/报告。

套件的使用方法(CLI 参数、测量的维度、线程模式分类)见 基准测试套件; 方法论细节见 Benchmark 套件;最新一轮的测量结果与图表见 Benchmark 详情。

线路中间表示

Backend-agnostic circuit intermediate representation.

Every benchmark circuit is compiled to a flat list of Op before it reaches a simulator adapter. Adapters translate this IR into their native gate set, so adding a new simulator or a new circuit family never touches the other side.

Gate names (angles in radians):

h, x, y, z, s, sdg, t, tdg                # 1-qubit, no parameters
rx, ry, rz                                 # 1-qubit, 1 parameter
cx, cz, swap                               # 2-qubit, no parameters

Noise channel names (inline, applied at their position in the op list):

depol1   (q, p)                 1-qubit depolarizing
depol2   (q1, q2, p)            2-qubit depolarizing
adamp    (q, gamma)             amplitude damping
bitflip  (q, p)                 bit flip
class benchmark.ir.Op(name: 'str', qubits: 'tuple[int, ...]', params: 'tuple[float, ...]' = ())[源代码]

基类:object

class benchmark.ir.Circuit(name: str, n_qubits: int, ops: tuple[Op, ...], seed: int | None = None)[源代码]

基类:object

A flat op list plus metadata. Channels (if any) are inline.

class benchmark.ir.NoisePreset(name: str, kind: str = 'none', p1: float = 0.0, p2: float = 0.0, gamma: float = 0.0)[源代码]

基类:object

A noise configuration attached after every gate of matching arity.

kind == "depolarizing": depol1(p1) after every 1q gate, depol2(p2) after every 2q gate. kind == "amplitude_damping": adamp(gamma) after every 1q gate. kind == "bitflip": bitflip(p1) after every 1q gate.

benchmark.ir.apply_noise(circuit: Circuit, preset: NoisePreset) → Circuit[源代码]

Return a copy of circuit with inline channels inserted per preset.

注册表

Registry of extension points: circuit families, noise presets, backends.

Adding a new circuit family = decorate a builder with @register_circuit. Adding a noise preset = @register_noise. Adding a simulator = subclass BenchmarkBackend and put the module in benchmark/backends/; importing benchmark.backends registers it automatically.

线路族

Circuit families used by the benchmark.

Each builder returns a Circuit built from the shared IR, so every backend executes an identical gate sequence. depth scales the gate count of the parametric families (ghz/qft ignore it).

benchmark.circuits.ghz(n_qubits: int, depth: int = 1, seed: int = 0) → Circuit[源代码]

H on q0 then a CNOT chain: the classic fixed-overhead entangler.

benchmark.circuits.qft(n_qubits: int, depth: int = 1, seed: int = 0) → Circuit[源代码]

Quantum Fourier transform, ~n^2 CRz decomposed to 2 CX each + swaps.

benchmark.circuits.random_layered(n_qubits: int, depth: int = 4, seed: int = 0) → Circuit[源代码]

Layered random circuit: per layer random rx/ry/rz on every qubit followed by a CNOT ring. Scales with depth.

benchmark.circuits.qaoa(n_qubits: int, depth: int = 3, seed: int = 0) → Circuit[源代码]

QAOA-style ansatz on a ring: uniform-H, then per layer ZZ(θ_i) on ring edges (CX-RZ-CX) + RX(θ) on every qubit.

噪声预设

Noise presets. Applied by ir.apply_noise as inline channel ops.

矩阵预设

Benchmark matrices.

A preset is a list of Group slices; the runner expands each group into concrete cases (backend x circuit x qubits x threads ...), dropping combinations a backend cannot run (unavailable package, qubit cap, channel support). Add a new group or preset here to extend the matrix — nothing else needs to change.

class benchmark.presets.Group(name: str, backends: tuple[str, ...], circuits: tuple[str, ...] = ('ghz',), qubits: tuple[int, ...] = (4, 8), depth: int = 1, noise: str = 'none', shots: int = 0, threads: tuple[int, ...] = (1,), repeats: int = 3, timeout_s: int = 300)[源代码]

基类:object

One slice of a benchmark matrix.

A group fixes every dimension except the ones it varies: it names the backends (or the all_sv / all_dm wildcards), the circuit families, the qubit sweep, the noise preset, whether shots are sampled, and the thread tiers. expand_groups turns each group into concrete case dicts and drops combinations a backend cannot run.

后端适配器

基类契约(线程机制、能力声明、支持性检查):

Backend adapter contract.

A backend wraps one simulator and executes Circuit instances (gate list + optional inline channels).

Thread baselines

threads_mode says how the threads dimension of the matrix is applied:

  • "env" the runner exports OMP/BLAS thread limits in the worker

    subprocess before import (qulacs, lightning, quimb, cirq, qutip).

  • "option" the backend takes a thread-count option at construction

    (aer, qsimcirq, qibo, uniqc — kernel threads via the global set_num_threads / set_parallel_enabled API).

  • "batch" the kernel runs single-threaded, so "multi-thread" means

    running independent trajectory shots in parallel worker processes and measuring sampling throughput (uniqc statevector batch baseline).

  • "none" the simulator is single-threaded with no knob.

Readout contract: run returns {"p_q0_1": float} — the probability of measuring qubit 0 in state 1 (exact for shots == 0, empirical otherwise). Comparing a single scalar keeps timing free of output-format differences.

class benchmark.backends.base.BenchmarkBackend(threads: int = 1)[源代码]

基类:ABC

classmethod availability() → tuple[bool, str][源代码]

(available, reason) — checks that import_name is importable.

set_threads(n: int) → None[源代码]

Hook for threads_mode == "option" backends (no-op default).

supports(circuit: Circuit, shots: int) → str | None[源代码]

Return a skip reason, or None when this backend can run the case.

abstractmethod run(circuit: Circuit, shots: int, seed: int) → dict[源代码]

Execute the circuit; return at least {"p_q0_1": float}.

数值辅助:

Small numeric helpers shared by backend adapters.

numpy is imported inside the functions on purpose: importing the backend registry (benchmark.backends) must not require numpy or any comparison simulator — list / selftest / probe need to run on machines where only uniqc_cpp is installed. Every adapter that calls these helpers is running its simulator at that point, which brings numpy with it.

benchmark.backends.util.prob_q0_1_from_statevector(vec, q0_is_lsb: bool = True) → float[源代码]

P(measure qubit 0 -> 1) from a flat statevector of length 2^n.

q0_is_lsb says whether qubit 0 is the least-significant bit of the flat amplitude index (the usual little-endian convention).

benchmark.backends.util.prob_q0_1_from_diag(mat, q0_is_lsb: bool = True) → float[源代码]

P(q0 -> 1) from a density-matrix diag; ordering flag as above.

具体适配器(每个文件顶部 docstring 说明该后端的线程模式与特殊处理):

uniqc_cpp StatevectorSimulator adapters.

UniqcStatevector is an option-mode backend: the threads tier is applied via the simulator's global multithreading API (uniqc_cpp.set_num_threads + set_parallel_enabled), so exact probabilities and trajectory shots both run in a single process with a parallel gate kernel. UniqcStatevectorBatch keeps the historical batch baseline: trajectories run single-threaded in parallel worker processes (multiprocessing) and measure sampling throughput. Noise channels are stochastic on the statevector (quantum-trajectory Monte Carlo), one trajectory per shot.

class benchmark.backends.uniqc_sv.UniqcStatevector(threads: int = 1)[源代码]

基类:BenchmarkBackend

set_threads(n: int) → None[源代码]

Apply the threads tier to the simulator's global kernel threads.

run(circuit: Circuit, shots: int, seed: int) → dict[源代码]

Execute the circuit; return at least {"p_q0_1": float}.

class benchmark.backends.uniqc_sv.UniqcStatevectorBatch(threads: int = 1)[源代码]

基类:BenchmarkBackend

run(circuit: Circuit, shots: int, seed: int) → dict[源代码]

Execute the circuit; return at least {"p_q0_1": float}.

uniqc_cpp DensityOperatorSimulator adapter (deterministic noise, <= 10q).

option thread mode: the threads tier is applied via the simulator's global multithreading API (uniqc_cpp.set_num_threads + set_parallel_enabled) — the density-matrix row loops parallelize with the statevector kernels.

class benchmark.backends.uniqc_dm.UniqcDensity(threads: int = 1)[源代码]

基类:BenchmarkBackend

set_threads(n: int) → None[源代码]

Apply the threads tier to the simulator's global kernel threads.

run(circuit: Circuit, shots: int, seed: int) → dict[源代码]

Execute the circuit; return at least {"p_q0_1": float}.

Qiskit Aer adapters (statevector / density_matrix methods).

Noise channels are appended inline as QuantumError instructions, mirroring the IR semantics one-to-one (Aer samples a trajectory per op on the statevector method, applies the superoperator on density_matrix).

benchmark.backends.aer.build_qiskit_circuit(circuit: Circuit, n_clbits: int = 0)[源代码]

Compile IR to a QuantumCircuit; channels become QuantumError instructions in place, and n_clbits reserves a classical register for the counts readout in shots mode.

class benchmark.backends.aer.AerStatevector(threads: int = 1)[源代码]

基类:_AerBase

class benchmark.backends.aer.AerDensity(threads: int = 1)[源代码]

基类:_AerBase

Cirq adapters (pure-NumPy Simulator / DensityMatrixSimulator).

Cirq amplitude indexing is big-endian w.r.t. qubit_order: the first qubit in the order is the most significant bit, so qubit 0 lives on the last axis. Phase gates S/T are exact; noise channels are only supported on the density backend (inline Cirq noise ops).

benchmark.backends.cirq_sim.build_cirq_circuit(circuit: Circuit, with_channels: bool, phase_via_rz: bool = False)[源代码]

Compile IR to a cirq.Circuit plus its qubit order.

with_channels inlines the noise channel ops (density backend only). phase_via_rz swaps S/T-family gates for phase-equivalent Rz so backends without S†/T† instructions (qsim) can still run the circuit identically up to global phase.

class benchmark.backends.cirq_sim.CirqStatevector(threads: int = 1)[源代码]

基类:BenchmarkBackend

run(circuit: Circuit, shots: int, seed: int) → dict[源代码]

Execute the circuit; return at least {"p_q0_1": float}.

class benchmark.backends.cirq_sim.CirqDensity(threads: int = 1)[源代码]

基类:BenchmarkBackend

run(circuit: Circuit, shots: int, seed: int) → dict[源代码]

Execute the circuit; return at least {"p_q0_1": float}.

Google qsim adapter via qsimcirq (C++ kernel, OpenMP threads).

class benchmark.backends.qsimcirq_sim.QsimCirq(threads: int = 1)[源代码]

基类:BenchmarkBackend

run(circuit: Circuit, shots: int, seed: int) → dict[源代码]

Execute the circuit; return at least {"p_q0_1": float}.

Qulacs adapters (QuantumState / DensityMatrix; OpenMP via env vars).

Qulacs has no Python-level thread API; the runner pins OMP_NUM_THREADS in the worker environment before import (threads_mode == "env"). Gates are recorded on a qulacs.QuantumCircuit once per run and applied with update_quantum_state; the built-in qulacs noise gates realize the inline channels on the density matrix. Empirically qubit 0 is the most significant bit of the flat amplitude index.

class benchmark.backends.qulacs_sim.QulacsStatevector(threads: int = 1)[源代码]

基类:_QulacsBase

class benchmark.backends.qulacs_sim.QulacsDensity(threads: int = 1)[源代码]

基类:_QulacsBase

PennyLane lightning.qubit adapter (C++/OpenMP kernel via OMP env).

benchmark.backends.lightning_sim.build_pl_tape(circuit: Circuit)[源代码]

Compile IR gates (channels unsupported) to a PennyLane QuantumScript measuring probs(wires=0).

class benchmark.backends.lightning_sim.PennyLaneLightning(threads: int = 1)[源代码]

基类:BenchmarkBackend

run(circuit: Circuit, shots: int, seed: int) → dict[源代码]

Execute the circuit; return at least {"p_q0_1": float}.

Qibo adapter (qibojit numba backend, qibo.set_threads).

benchmark.backends.qibo_sim.build_qibo_circuit(circuit: Circuit)[源代码]

Compile IR gates (channels unsupported) to a qibo.models.Circuit.

class benchmark.backends.qibo_sim.QiboSimulator(threads: int = 1)[源代码]

基类:BenchmarkBackend

set_threads(n: int) → None[源代码]

Hook for threads_mode == "option" backends (no-op default).

run(circuit: Circuit, shots: int, seed: int) → dict[源代码]

Execute the circuit; return at least {"p_q0_1": float}.

Quimb adapter (dense statevector via quimb.tensor.Circuit).

class benchmark.backends.quimb_sim.QuimbSimulator(threads: int = 1)[源代码]

基类:BenchmarkBackend

run(circuit: Circuit, shots: int, seed: int) → dict[源代码]

Execute the circuit; return at least {"p_q0_1": float}.

QuTiP adapter (qutip-qip CircuitSimulator, sequential sparse application).

QuTiP is a general open-system framework, not a circuit-simulator speed daemon; it is included as a scientific-computing reference point. Phase gates use exact PHASEGATE instructions.

class benchmark.backends.qutip_sim.QuTiPSimulator(threads: int = 1)[源代码]

基类:BenchmarkBackend

run(circuit: Circuit, shots: int, seed: int) → dict[源代码]

Execute the circuit; return at least {"p_q0_1": float}.

Amazon Braket local simulator adapter (pure NumPy/SciPy reference speed).

benchmark.backends.braket_sim.build_braket_circuit(circuit: Circuit)[源代码]

Compile IR gates (channels unsupported) to a Braket Circuit with a state_vector() result type for exact amplitude readout.

class benchmark.backends.braket_sim.BraketLocalSimulator(threads: int = 1)[源代码]

基类:BenchmarkBackend

run(circuit: Circuit, shots: int, seed: int) → dict[源代码]

Execute the circuit; return at least {"p_q0_1": float}.

PyQrack adapter (Qrack hybrid stabilizer/statevector engine).

Kept for reuse on machines where the native Qrack shared library (libqrack_pinvoke.so under /usr/lib/qrack) is installed; the availability probe skips it automatically otherwise. API mapping follows the PyQrack examples (adjoint phase gates via adjoint_s/adjoint_t).

class benchmark.backends.pyqrack_sim.PyQrack(threads: int = 1)[源代码]

基类:BenchmarkBackend

run(circuit: Circuit, shots: int, seed: int) → dict[源代码]

Execute the circuit; return at least {"p_q0_1": float}.

运行器与 worker

Matrix expansion + sequential case scheduling into worker subprocesses.

benchmark.runner.probe_backends(backend_names: list[str]) → dict[str, dict][源代码]

Import-probe each backend in a subprocess.

Returns {name: {"available", "version", "reason"}}; the version is best-effort (module __version__ or installed distribution metadata).

benchmark.runner.selftest_backends(backend_names: list[str]) → dict[str, dict][源代码]

Run the known-answer check (worker --selftest) per backend.

benchmark.runner.expand_groups(groups: list[Group]) → list[dict][源代码]

Expand preset groups into concrete case dicts (no availability filter).

benchmark.runner.collect_env_meta(preset_name: str, probes: dict, selftests: dict) → dict[源代码]

Snapshot of the run environment (CPU, memory, python, per-backend versions and selftest status) stored alongside the results.

benchmark.runner.run_matrix(preset_name: str, out_path: str, selected_backends: list[str] | None = None, limit: int | None = None, resume: bool = False) → dict[源代码]

Execute a preset matrix and persist a results document.

Flow: probe availability -> selftest every reachable backend (failures are excluded) -> expand cases -> run each in a worker subprocess, updating out_path after every case so an interrupted run can be resumed with resume=True (completed cases are reused, failures re-run). Returns the final {"meta", "dropped", "results"} dict.

Single-case worker. Runs in its own process (spawned by the runner) so that thread-pinning environment variables take effect before any simulator import, and so a crash/timeout cannot poison the timing of other cases.

Usage:

python -m benchmark.worker --case-json '{"backend": ...}' [--selftest] python -m benchmark.worker --probe aer_sv

Emits exactly one JSON line on stdout.

benchmark.worker.run_case(case: dict) → None[源代码]

Execute one benchmark case and emit its JSON record.

Builds the circuit from the registry, applies the noise preset, checks support, runs one warm-up + case["repeats"] timed repeats of backend.run (seed varies per repeat), then reports the raw times, the readout scalar and peak RSS. Emits {"status": "skip", ...} when the backend cannot run this case.

benchmark.worker.main() → None[源代码]

Entry point for python -m benchmark.worker (see module docstring).

图表与报告

Chart rendering from a results JSON (matplotlib only, no pandas).

Each figure is an independent function so new chart types can be added without touching the dispatcher: implement fig_xxx(data, out_dir) and register it in PLOTTERS.

matplotlib (and numpy) are imported lazily inside the figure functions so that python -m benchmark list / selftest / run work on machines without them — only plot needs the plotting stack.

benchmark.plotting.fig_ideal_runtime(data: dict, out_dir: str) → tuple[str, str][源代码]

Runtime vs qubit count for ideal statevector simulation (per circuit).

benchmark.plotting.fig_thread_speedup(data: dict, out_dir: str) → tuple[str, str][源代码]

Single-thread vs multi-thread speedup per backend (largest common size).

benchmark.plotting.fig_noise_runtime(data: dict, out_dir: str) → tuple[str, str][源代码]

Noise (density-matrix) runtime vs qubits per noise preset.

benchmark.plotting.fig_sampling_throughput(data: dict, out_dir: str) → tuple[str, str][源代码]

Shot-sampling throughput (shots/s) for trajectory Monte-Carlo runs.

benchmark.plotting.plot_all(results_path: str, out_dir: str) → list[tuple[str, str]][源代码]

Render every registered figure from a results JSON.

Returns [(figure_name, output_path)] for the figures that produced output; figures whose data slice is empty are skipped silently.

Markdown report generation from a results JSON.

write_report produces the detailed docs/benchmark/report.md; write_readme_summary produces the compact docs/benchmark/README_summary.md.

benchmark.report.write_readme_summary(data: dict, doc_path: str) → str[源代码]

Compact summary tables included by the README benchmark section.

命令行入口

Command-line interface: python -m benchmark <subcommand> ...

benchmark.cli.cmd_list(args: Namespace) → None[源代码]

Print registered backends (with availability), circuits, noise and presets.

benchmark.cli.cmd_selftest(args: Namespace) → None[源代码]

Run the known-answer check for the requested (or all) backends.

Applies the same availability filter as run: backends whose simulator package is not installed are reported as missing (reason) and skipped, so a partial environment still exits 0. Only a reachable backend that fails the known-answer check (or an unknown name given via --backends) is an error.

benchmark.cli.cmd_run(args: Namespace) → None[源代码]

Execute a preset matrix (see runner.run_matrix).

benchmark.cli.cmd_plot(args: Namespace) → None[源代码]

Render every registered figure from a results JSON.

benchmark.cli.cmd_report(args: Namespace) → None[源代码]

Generate docs/benchmark/report.md and the README summary.

benchmark.cli.build_parser() → ArgumentParser[源代码]

Argument parser for python -m benchmark <command>.

参见