diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5dbfdfa..cbedd9d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -37,6 +37,21 @@ jobs: - run: python -m pip install torch --index-url https://download.pytorch.org/whl/cpu - run: python -m pip install . pytest - run: python -m pytest -q tests/test_contraction_compiler.py tests/test_distributed_compute.py + hybrid-quant-compiler: + runs-on: ubuntu-latest + timeout-minutes: 12 + env: + OMP_NUM_THREADS: '1' + MKL_NUM_THREADS: '1' + OPENBLAS_NUM_THREADS: '1' + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5 + with: + python-version: '3.12' + - run: python -m pip install torch --index-url https://download.pytorch.org/whl/cpu + - run: python -m pip install ".[jax,qiskit,dev]" + - run: python -m pytest -q tests/test_native_geometry.py tests/test_transport_geometry.py tests/test_classical_predicates.py tests/test_compilation_portability.py tests/test_package_layout.py public-types: runs-on: ubuntu-latest steps: @@ -109,7 +124,7 @@ jobs: - run: python -m pip install "torch==2.2.2" --index-url https://download.pytorch.org/whl/cpu - run: python -m pip install "numpy==1.26.4" "jax==0.4.30" "jaxlib==0.4.30" "optax==0.2.3" "chex==0.1.87" - run: python -m pip install ".[dev]" - - run: python -m pytest -q tests/test_compilation_portability.py tests/test_native_fusion.py tests/test_execution_hotpaths.py tests/test_package_layout.py tests/test_compute_kernel.py tests/test_reliability.py tests/test_entry_contracts.py tests/test_prepared_workflows.py tests/test_register_programs.py tests/test_accelerators.py tests/test_native_gpu.py tests/test_native_constant_cache.py + - run: python -m pytest -q tests/test_compilation_portability.py tests/test_native_geometry.py tests/test_transport_geometry.py tests/test_native_fusion.py tests/test_execution_hotpaths.py tests/test_package_layout.py tests/test_compute_kernel.py tests/test_reliability.py tests/test_entry_contracts.py tests/test_prepared_workflows.py tests/test_register_programs.py tests/test_accelerators.py tests/test_native_gpu.py tests/test_native_constant_cache.py compiled-transforms: runs-on: ubuntu-latest steps: @@ -119,7 +134,7 @@ jobs: python-version: '3.11' - run: python -m pip install "torch==2.4.1" --index-url https://download.pytorch.org/whl/cpu - run: python -m pip install "numpy==1.26.4" . pytest - - run: python -m pytest -q tests/test_compilation_portability.py tests/test_native_fusion.py tests/test_activation_checkpointing.py tests/test_execution_hotpaths.py tests/test_package_layout.py + - run: python -m pytest -q tests/test_compilation_portability.py tests/test_native_geometry.py tests/test_transport_geometry.py tests/test_native_fusion.py tests/test_activation_checkpointing.py tests/test_execution_hotpaths.py tests/test_package_layout.py portable-install: strategy: fail-fast: false @@ -138,6 +153,13 @@ jobs: with: python-version: ${{ matrix.python }} - run: python -m pip install ".[all,dev]" --report install-report.json + - name: Configure macOS OpenMP for TorchInductor + if: runner.os == 'macOS' + run: | + brew install libomp + omp_prefix=$(brew --prefix libomp) + test -f "$omp_prefix/include/omp.h" + echo "OMP_PREFIX=$omp_prefix" >> "$GITHUB_ENV" - name: Activate the Windows C++ toolchain for TorchInductor if: runner.os == 'Windows' shell: pwsh @@ -152,8 +174,8 @@ jobs: } - run: python -m pip check - run: python -m openqml doctor --extra all --check-imports --sizes --output environment-report.json - - run: python -m pytest -q tests/test_compilation_portability.py tests/test_native_fusion.py - - run: python -m pytest -q tests/test_compute_kernel.py tests/test_reliability.py tests/test_entry_contracts.py tests/test_prepared_workflows.py tests/test_register_programs.py tests/test_accelerators.py tests/test_native_gpu.py tests/test_precision_regressions.py tests/test_audit_regressions.py tests/test_switch_lowering.py tests/test_risk_budget.py tests/test_tensor_streaming.py tests/test_model_checkpoint.py tests/test_model_selection.py tests/test_walk_forward.py tests/test_conversion_sweeps.py tests/test_finance_execution.py tests/test_simple_api.py tests/test_adaptive_amplitude.py tests/test_amplitude.py tests/test_finance.py tests/test_frontier_models.py tests/test_algorithmic_execution.py tests/test_network_operators.py tests/test_architecture.py tests/test_deep_learning.py tests/test_cost_scheduling.py tests/test_calibration.py tests/test_distributed_compute.py tests/test_multiscale_execution.py tests/test_gradient_accumulation.py tests/test_program_compilation.py tests/test_distributed_training.py tests/test_compute_contractions.py tests/test_contraction_compiler.py tests/test_runtime.py tests/test_hybrid_training.py tests/test_sparse_scaling.py tests/test_research_methods.py tests/test_public_api.py tests/test_package_scope.py tests/test_package_layout.py tests/test_execution_hotpaths.py tests/test_mitigation.py tests/test_model_streaming.py tests/test_backends.py tests/test_providers.py tests/test_shared_readouts.py tests/test_conversion_plan.py tests/test_resource_audit.py tests/test_source_boundaries.py tests/test_resource_profiles.py tests/test_environment_report.py tests/test_scientific_scale.py tests/test_semantic_compiler.py tests/test_adaptive_execution.py + - run: python -m pytest -q tests/test_compilation_portability.py tests/test_native_fusion.py tests/test_register_programs.py tests/test_native_geometry.py tests/test_transport_geometry.py tests/test_classical_predicates.py + - run: python -m pytest -q tests/test_compute_kernel.py tests/test_reliability.py tests/test_entry_contracts.py tests/test_prepared_workflows.py tests/test_accelerators.py tests/test_native_gpu.py tests/test_precision_regressions.py tests/test_audit_regressions.py tests/test_switch_lowering.py tests/test_risk_budget.py tests/test_tensor_streaming.py tests/test_model_checkpoint.py tests/test_model_selection.py tests/test_walk_forward.py tests/test_conversion_sweeps.py tests/test_finance_execution.py tests/test_simple_api.py tests/test_adaptive_amplitude.py tests/test_amplitude.py tests/test_finance.py tests/test_frontier_models.py tests/test_algorithmic_execution.py tests/test_network_operators.py tests/test_architecture.py tests/test_deep_learning.py tests/test_cost_scheduling.py tests/test_calibration.py tests/test_distributed_compute.py tests/test_multiscale_execution.py tests/test_gradient_accumulation.py tests/test_program_compilation.py tests/test_distributed_training.py tests/test_compute_contractions.py tests/test_contraction_compiler.py tests/test_runtime.py tests/test_hybrid_training.py tests/test_sparse_scaling.py tests/test_research_methods.py tests/test_public_api.py tests/test_package_scope.py tests/test_package_layout.py tests/test_execution_hotpaths.py tests/test_mitigation.py tests/test_model_streaming.py tests/test_backends.py tests/test_providers.py tests/test_shared_readouts.py tests/test_conversion_plan.py tests/test_resource_audit.py tests/test_source_boundaries.py tests/test_resource_profiles.py tests/test_environment_report.py tests/test_scientific_scale.py tests/test_semantic_compiler.py tests/test_adaptive_execution.py - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 if: always() with: diff --git a/.github/workflows/gpu-integration.yml b/.github/workflows/gpu-integration.yml index c75543f..e2f942a 100644 --- a/.github/workflows/gpu-integration.yml +++ b/.github/workflows/gpu-integration.yml @@ -41,6 +41,8 @@ jobs: OPENQML_REQUIRE_CUDA: '1' OPENQML_HARDWARE_REPORT_DIR: ${{ runner.temp }}/openqml-hardware run: python -m pytest -q tests/test_distributed_compute.py -k physical_multi_gpu + - name: Verify resident native quantum geometry + run: python -m pytest -q tests/test_native_geometry.py -k physical_cuda - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 if: always() with: diff --git a/README.md b/README.md index c8943f3..46990cb 100644 --- a/README.md +++ b/README.md @@ -8,14 +8,26 @@ Build and train hybrid neural networks with PyTorch, JAX or Flax. Use `Model.fit` and `predict` for supervised tasks, or compose convolution, attention, graph, recurrent and generative architectures with native layers. Validation loss, early stopping and portable checkpoints keep model selection and continued training in the same workflow. [Explore hybrid AI](https://github.com/OpenQML-org/OpenQML/blob/main/docs/models.md). +Native quantum metric products and certified natural-gradient solves retain +PyTorch/JAX tensors and device placement. An optional geometry-first spectral +step balances circuit parameter blocks after preconditioning. + ## Quantum–classical hybrid quantitative research Train scenario distributions, allocate constrained portfolios and project decisions onto explicit CVaR budgets with a funded cash position. Low-rank factor solves and native PyTorch/JAX derivatives connect financial objectives to hybrid models. Purged walk-forward refits and self-financing accounting preserve chronological evaluation, execution delays, fees and market impact. [Explore quantitative research](https://github.com/OpenQML-org/OpenQML/blob/main/docs/finance.md). +Learn contextual Wasserstein radii and anisotropic transport metrics alongside +quantum scenario probabilities. Factor-space implicit derivatives connect the +robust risk bound and funded cash allocation to the predictive model. + ## Cross-framework quantum programming Connect Qiskit, Cirq, PennyLane and OpenQASM through a shared circuit representation. Compile grouped switch cases, finite loops and atomic classical guards; reuse shared definitions and symbolic expressions. Prepare conversions once, stream parameter sweeps and verify their semantics against round-trip or native execution. [Explore interoperability](https://github.com/OpenQML-org/OpenQML/blob/main/docs/interoperability.md). +Typed Qiskit logical, bitwise and unsigned comparison predicates lower to bounded +shared decision graphs. Their branch selection completes before either payload +executes, including payloads that overwrite a measured predicate input. + Simulate physical noise with amplitude/phase damping, depolarization and custom Kraus channels. Correct independent readout errors or extrapolate measured noise scales with explicit conditioning and sampling-overhead limits. Caller-initialized Qiskit V2 primitives connect real hardware; see [execution limits and mitigation](https://github.com/OpenQML-org/OpenQML/blob/main/docs/runtime.md#physical-noise-and-error-mitigation). ## Install diff --git a/docs/api.md b/docs/api.md index 15929a9..bf397a4 100644 --- a/docs/api.md +++ b/docs/api.md @@ -41,6 +41,11 @@ Checked `compile_compute` boundaries retain typed numerical failures. Raw native JIT calls retain framework error behavior and may expose the internal NaN/error status used by training checks. See [compute contracts](compute.md#numerical-contracts). +`QuantumMetricPlan.native_matvec`, `native_natural_gradient` and `spectral_step` +operate on native Torch/JAX parameter vectors. Their result types are +`NativeMetricResult` and `SpectralStepResult`. See [native quantum geometry](native-geometry.md) +for the metric convention, spectral block order, residual certificates and scope. + ## Circuit conversion ```python diff --git a/docs/compute.md b/docs/compute.md index 7eac852..2b0b2be 100644 --- a/docs/compute.md +++ b/docs/compute.md @@ -88,6 +88,17 @@ do not provide Inductor kernel fusion or CUDA Graph replay. `environment_report()["cxx_compiler"]` reports executable discovery only; it does not certify a working compiler, SDK, linker or accelerator. +On macOS, generated CPU kernels also need OpenMP headers and libraries. +Install `libomp` and set `OMP_PREFIX` to its installation prefix, for example +the path printed by `brew --prefix libomp`. An observed missing `omp.h` raises +an actionable `ResourceError`; other C++ compilation failures retain their +native exceptions. Portable macOS CI installs and configures this prerequisite. + +On legacy Dynamo, resolve lazy module/function references before constructing +a compiled callback, for example `norm = oq.finance.transport_dual_norm`. +Use that reference in the callback so first-use namespace discovery stays +outside the graph capture. + Compilation has an initial cost, and small circuits can remain faster eagerly. TorchInductor can delegate unsupported complex operators to native kernels. Fusion benefit depends on locality, gate mix and reuse. These mechanisms do not diff --git a/docs/finance.md b/docs/finance.md index 39c3dbe..627fbf3 100644 --- a/docs/finance.md +++ b/docs/finance.md @@ -229,6 +229,53 @@ rejects unresolved financing rather than returning weights outside the budget. ## Differentiable decision risk budgets +`WassersteinMetric(diagonal, factors=None)` defines the anisotropic ground norm +`||delta||_M`, where `M = diag(diagonal) + factors.T @ factors`. The diagonal +must be strictly positive; factors have shape `[...,rank,assets]`. Both may be +native trainable model outputs. `transport_dual_norm(w, metric)` computes +`sqrt(w.T @ M^-1 @ w)` through a certified, implicitly differentiated factor +solve. No asset covariance matrix or inverse is constructed. + +Pass `transport_metric=metric` to `wasserstein_cvar` or +`risk_budget_projection`. The robust margin becomes +`radius * transport_dual_norm(w, metric) / (1-confidence)`. Native radii can +vary by context and retain their gradients. The funded cash-ray projection +remains maximal because the anisotropic norm is positively homogeneous. +Metrics, radii, scenarios, probabilities and weights support broadcast batch +axes; financial tensors must use one framework and device. + +```python +import torch +import openqml as oq + +metric = oq.finance.WassersteinMetric( + diagonal=torch.tensor([0.7, 1.2], requires_grad=True), + factors=torch.tensor([[0.2, -0.3]], requires_grad=True), +) +decision = oq.finance.risk_budget_projection( + [0.4, 0.5], + [[-0.12, -0.03], [0.04, -0.08], [0.1, 0.02]], + confidence=0.5, + budget=0.015, + radius=torch.tensor(0.01, requires_grad=True), + transport_metric=metric, +) +``` + +This connects quantum Born scenario probabilities to contextual robust +decisions without detaching the metric or radius. A positive parameterization +such as `softplus(raw_diagonal)+floor` enforces the metric domain. Radius and +metric scale are confounded: constrain their scale or calibrate them jointly +within the training fold. The W1 dual margin is an unbounded-support bound; +restricted return supports can make it conservative. Learned radii do not +provide distribution-shift coverage without separate statistical calibration. + +[Learning Predictive Ambiguity Sets (July 2026)](https://arxiv.org/abs/2607.09820) +motivates contextual radii and anisotropic metrics. Its anisotropic metric was +not empirically evaluated in that paper, and its portfolio results do not +establish returns for this library. This implementation extends the existing +specialized W1/CVaR cash-ray layer; it does not reproduce the full LPAS pipeline. + `risk_budget_projection` takes a long-only proposal whose asset weights sum to at most one, a joint scenario table, optional Born probabilities, a CVaR budget and a nonnegative Wasserstein radius. It returns `RiskBudgetResult` with @@ -245,7 +292,8 @@ print(decision.weights, decision.cash, decision.robust_cvar) ``` For proposal `w`, scenario returns `R` and deterministic cash return `r_c`, -define `D = CVaR(r_c*sum(w) - R@w) + radius*||w||2/(1-confidence)`. +define `D = CVaR(r_c*sum(w) - R@w) + radius*dual_norm(w)/(1-confidence)`. +The dual norm is Euclidean unless `transport_metric` is supplied. The implementation selects `scale=1` when `D <= budget+r_c`, otherwise `scale=(budget+r_c)/D`. Positive homogeneity and cash translation make this the largest feasible scale on the proposal's ray toward cash. The budget must admit @@ -466,7 +514,7 @@ reduction or quasi-Monte-Carlo execution. Robust Optimization](https://arxiv.org/abs/2607.09820) (July 2026): motivates contextual scenario masses and learned ambiguity radii. OpenQML's cash-ray layer uses an isotropic W1/L2 margin with a closed-form funded risk - projection; trainable anisotropic metrics require a separate risk model. + projection; trainable anisotropic metrics use the factor transport model above. - [Constant-Depth Quantum Barrier Option Pricing via a Static Bivariate Oracle Framework](https://arxiv.org/abs/2610.27929) (October 2026): static path compression under GBM. OpenQML uses terminal-price conditioning, exact discrete payoff rotations and explicit state-loading costs for continuous monitoring. diff --git a/docs/interoperability.md b/docs/interoperability.md index f060519..f88863b 100644 --- a/docs/interoperability.md +++ b/docs/interoperability.md @@ -71,6 +71,37 @@ symbolic parameter identity, global phase, wire mappings and operation budgets; subsequent calls import the current source object afresh. Numerical bindings and target objects remain independent across exported artifacts. +## Typed classical predicates + +The Qiskit IR route additionally accepts pure `Bool`/`Uint` expressions over +declared classical bits/registers: `logic_not`, `logic_and`, `logic_or`, +`bit_not`, `bit_and`, `bit_or`, `bit_xor`, equality/inequality and all unsigned +ordered comparisons. Bool/Uint casts implement nonzero truth conversion, +unsigned truncation and zero extension. Standalone mutable variables, signed +arithmetic, stores, timing and other unsupported expression operations retain +explicit diagnostics or require the existing native program route. + +A bit-vector compiler lowers these predicates into reduced ordered binary +decision diagrams, reusing canonical nodes and cached Boolean operations. +Portable IR emits immutable equality decisions with shared branch bodies. +The predicate is fully evaluated before its selected body executes, including +when the body overwrites a measurement bit used by the predicate. No scratch +classical bits or truth-table enumeration are introduced. The emitted equality +subset remains compatible with OpenQASM and Cirq export/reimport paths. + +`max_operations` bounds expression/bit-vector work, BDD construction and the +expanded decision/payload cost; `max_depth` bounds expression, guard and payload +nesting. Variable order follows declared bit indices. Some Boolean functions +have large decision or expanded output representations and are rejected at the +budget boundary. This is an expanded representable subset, not universal host +Python or general classical-program translation. + +The supported source nodes follow [Qiskit's typed classical-expression API](https://quantum.cloud.ibm.com/docs/en/api/qiskit/circuit_classical). +Recent work on [structured quantum programs (September 2026)](https://arxiv.org/abs/2609.16171) +motivates retaining classical structure. The existing native program route +continues to retain supported dynamic loops instead of flattening their runtime +iterations; this addition handles bounded pure predicates in the portable IR. + ## Prepare once, bind many ```python diff --git a/docs/native-geometry.md b/docs/native-geometry.md new file mode 100644 index 0000000..8df6e55 --- /dev/null +++ b/docs/native-geometry.md @@ -0,0 +1,87 @@ +# Native quantum geometry + +`QuantumMetricPlan` now supports resident PyTorch/JAX metric products, damped +natural-gradient solves and an optional spectral step. Use the parameter order +declared by the plan. Native bindings may be scalars or share one visible +sample axis. A real floating vector selects a common coordinate displacement. +`sample_weights` optionally defines a normalized nonnegative empirical metric; +otherwise samples contribute their uniform mean. Inputs are staged once per +solve, and batched state evolution avoids a Python circuit call per example. + +| Method | Result | +| --- | --- | +| `native_matvec(bindings, vector, backend="torch")` | Exact real Fubini–Study metric times a vector | +| `native_natural_gradient(bindings, gradient, backend="torch", ...)` | Native direction and a true damped-system residual certificate | +| `spectral_step(bindings, gradient, block_shapes=..., ...)` | Bounded spectral-natural displacement and the original CG certificate | + +The metric is `G = Re(J* (I - |psi>