Skip to main content

Signed Common Meadow arithmetic for stable machine learning

Project description

ZeroProofML

Machine learning that handles division by zero gracefully

Pipeline Docs

Built on Signed Common Meadow (SCM) semantics for totalized arithmetic

What is ZeroProofML?

ZeroProofML is a PyTorch library that enables neural networks to learn functions with singularities—like 1/x near zero or gravitational potentials—without numerical instabilities or undefined behavior. Instead of treating division by zero as an error, we use Signed Common Meadow (SCM) semantics to provide a mathematically rigorous foundation for arithmetic operations that remain well-defined everywhere.

Key capabilities

  • Totalized arithmetic: Singular operations map to an absorptive bottom element , tracked by explicit masks (and optionally represented as NaN payloads at strict decode time)
  • Smooth training: Optional projective mode with ⟨N,D⟩ tuples and "ghost gradients" keeps optimization stable near singularities
  • Strict inference: Decode projective outputs with configurable thresholds (τ_infer, τ_train) and obtain bottom_mask / gap_mask for rejection or safe fallbacks
  • Orientation tracking: Weak-sign protocol provides direction/orientation information near singularities
  • PyTorch integration: Drop-in rational layers, SCM-aware losses, and JIT-compatible operations

When to use ZeroProofML

ZeroProofML excels in domains where singularities arise naturally:

  • Physics: Gravitational/electrostatic potentials (1/r), collision dynamics, quantum mechanics
  • Robotics: Inverse kinematics with joint limits, collision avoidance fields
  • Computer vision: Homogeneous coordinates, projective geometry, structure-from-motion
  • Scientific computing: Learning differential equations with singular solutions, rational approximations

Quick start

# install with a backend (PyPI)
pip install "zeroproofml[torch]"

# optional experimental plotting/logging utilities
pip install "zeroproofml[viz]"

# optional interactive training-log reports
pip install "zeroproofml[interactive]"

# from a repo checkout (development)
# pip install -e ".[dev,torch]"

The zeroproofml[viz] extra installs optional experimental reporting helpers (zeroproofml.utils.viz, TensorBoardLogger, and jsonl_to_dataframe) in addition to the stable JSONL logger. Trainer and evaluation metric JSONL records use the stable zeroproofml.metric_log schema with a canonical metrics payload plus flat metric keys for older readers. For dashboard/CSV/BI pipelines, zeroproofml.utils.logging also exposes experimental metric_log_records_to_wide_rows(...) and metric_log_records_to_long_rows(...) converters. The optional zeroproofml[interactive] extra installs Plotly so training-log report regeneration can also write an interactive <stem>_REPORT.html beside the Markdown summary and SVG.

zeroproofml is the canonical public namespace for package/docs/install references. The legacy zeroproof import path remains supported as a compatibility namespace, so existing integrations do not need an immediate rename. That compatibility commitment holds through the roadmap's next major milestone, the M4 core 1.0-or-stay-0.x decision, and no namespace deprecation warning is planned before then unless a concrete migration plan is published. Layering rule for new code: keep SCM implementation modules under zeroproof.*, expose them through zeroproofml.* for public imports/docs, and reserve zeroproofml.*-only modules for product-level surfaces that have no legacy counterpart (for example zeroproofml.benchmarks).

import torch
from torch.utils.data import DataLoader, TensorDataset

from zeroproofml.inference import InferenceConfig, SCMInferenceWrapper
from zeroproofml.layers.projective_rational import ProjectiveRRModelConfig, RRProjectiveRationalModel
from zeroproofml.losses.implicit import implicit_loss
from zeroproofml.training import SCMTrainer, TrainingConfig

# Toy example: learn a 1D rational function (targets may include inf/NaN for singular labels).
x = torch.linspace(-1.0, 1.0, 2048).unsqueeze(-1)
y = 1.0 / (x + 0.1)
train_loader = DataLoader(TensorDataset(x, y), batch_size=256, shuffle=True)

model = RRProjectiveRationalModel(
    ProjectiveRRModelConfig(input_dim=1, output_dim=1, numerator_degree=3, denominator_degree=2)
)
wrapped = SCMInferenceWrapper(model, config=InferenceConfig(tau_infer=1e-6, tau_train=1e-4))

def loss_fn(outputs, lifted_targets):
    P, Q = outputs
    Y_n, Y_d = lifted_targets
    return implicit_loss(P, Q, Y_n, Y_d)

optimizer = torch.optim.AdamW(model.parameters(), lr=1e-3)
trainer = SCMTrainer(
    model=model,
    optimizer=optimizer,
    loss_fn=loss_fn,
    train_loader=train_loader,
    config=TrainingConfig(max_epochs=20),
)
trainer.fit()

# Strict inference (decoded uses NaN for ⊥ payloads; masks are authoritative).
wrapped.eval()
decoded, bottom_mask, gap_mask = wrapped(x)

See examples/README.md for the maintained-vs-archival map of the example tree, then docs/ (start at docs/index.md) for end-to-end demos and recommended patterns. The maintained tutorial path through the strongest examples lives in docs/39_examples_tutorials.md, and the full examples label map lives in docs/38_examples_inventory.md. The end-to-end deployment workflow examples live under examples/deployment/README.md. For the opt-in provenance diagnostics, see docs/23_experimental_provenance_guide.md.

How it works

ZeroProofML implements a two-phase training paradigm:

  1. Training mode (smooth/projective): Networks learn rational functions as projective tuples ⟨N,D⟩ with detached normalization, allowing smooth gradients even when denominators approach zero
  2. Inference mode (strict SCM): Outputs are decoded with configurable thresholds; small denominators trigger and are surfaced via bottom_mask / gap_mask (decoded payloads use NaN for )

This approach combines the stability of smooth optimization with the rigor of totalized arithmetic, enabling reliable deployment in safety-critical domains.

Architecture

zeroproof/
├── scm/          # SCM values + totalized ops (⊥ semantics)
├── autodiff/     # Gradient policies + projective helpers
├── layers/       # PyTorch SCM layers (rational heads, normalization)
├── losses/       # SCM-aware losses (fit/margin/sign/rejection)
├── training/     # Trainer loop + target lifting utilities
├── inference/    # Export & deployment helpers
├── metrics/      # Pole & singularity metrics
└── utils/        # IEEE↔SCM bridge, visualization

Docs hub: docs/index.md | Getting started: docs/00_getting_started.md | Theory: docs/theory/00_overview.md | API: docs/08_api_reference.md Published docs track the latest main branch at the site root.

Development

Install development dependencies and run tests:

pip install -e ".[dev,torch]"
pytest -m "scm and not benchmark" tests -v

Run linting and type checking:

ruff check zeroproof tests
mypy --strict zeroproof
python scripts/ci/check_version_sync.py

Generate the release-compliance artifacts from a built wheel:

python -m build
python scripts/ci/generate_sbom.py --project-name zeroproofml dist/*.whl
python scripts/ci/generate_license_report.py --project-name zeroproofml --all-extras dist/*.whl

Live vulnerability scanning is intentionally kept out of the tag-triggered release:pypi lane because advisory-database lookups are time-varying and network-dependent. The separate scheduled/manual security:vulnerability-audit job runs:

python -m pip install -U pip-audit
python -m pip_audit -r requirements.txt -r requirements-int.txt --strict

Reproduce the SCM-suite coverage report that GitLab publishes:

pytest -m "scm and not benchmark" tests -q --cov=zeroproof --cov-report=term --cov-report=xml

This publishes a GitLab Cobertura artifact for inspection only; CI does not apply a coverage fail-under gate, and the README does not display this partial SCM-suite coverage as a project-level quality badge.

Run scientific claim benchmarks / reproduction flows:

make reproduce-paper
# or run a single replay command:
make reproduce-dose
make reproduce-rf
make reproduce-ik
make reproduce-reference-robotics

Run performance microbenchmarks separately:

python perf/run_benchmarks.py --suite all --output benchmark_results
python perf/parity_runner.py --output benchmark_results

GitLab merge request CI keeps the scientific claim benchmark harness in smoke mode; the 10-seed paper-mode claim-benchmark:* jobs are reserved for scheduled runs and manual default-branch jobs. The benchmark_results/ JSON artifacts belong to the performance microbenchmark suite, not the DOSE/RF/IK claim-benchmark runs. The same scheduled/manual claim-benchmark CI lane also runs a curated nightly ONNX export compatibility matrix across pinned Torch/ONNX/onnxruntime stacks, exercising tests/inference/test_export_bundle.py plus tests/inference/test_export_compatibility.py. Legacy wrapper entrypoints such as scripts/run_paper_suite_dose.py, scripts/rf/run_rf_suite.py, scripts/rf/generate_paper_figures.py, scripts/rf/plot_pole_migration.py, and examples/robotics/rr_ik_dataset.py still run for compatibility, but they now emit DeprecationWarning; prefer python -m zeroproofml.benchmarks ... or the importable zeroproofml.benchmarks.domains.* modules.

Interrupted paper-mode benchmark runs can be resumed in-place with python -m zeroproofml.benchmarks <domain> --mode paper --out-root <run_dir> --resume; the harness preserves the original attempt metadata in resume_state.json and records the full attempt history in provenance.json. For explicit artifact reuse, pass --skip-complete-seeds to fill only missing canonical seed results, or --force-rerun to rerun the requested seeds in an existing --out-root. Every completed run also writes a root-level RUN_REPORT.md; pass --html-report to add a browser-friendly RUN_REPORT.html alongside it. To regenerate the report from an existing benchmark artifact directory, run python -m zeroproofml.report benchmark <run_dir> --html-report; add --baseline-run-dir <previous_run_dir> to rebuild paired baseline stats from another run directory. Regenerated benchmark reports use artifact-relative paths and refresh aggregated/summary.md from aggregated/summary.json, so copied run directories produce the same report content. Report regeneration also includes a fault-vs-semantic bottom breakdown when fault_rate / semantic_bottom_rate provenance metrics are present, and writes SVG figure artifacts: benchmark runs get figures/metric_summary.svg, deployment bundles get VALIDATION_REPORT.summary.svg, and JSONL training logs get an adjacent <stem>_REPORT_metrics.svg. DOSE benchmark reports with saved diagnostics also get figures/dose_figure_pack/ for threshold sweeps, macro-F1/finite-MAE trade-offs, censor-direction confusion, assay-limit edge cases, and operating-point bottom provenance when available. IK benchmark reports also get figures/robotics_figure_pack/ for workspace heatmaps, |det(J)| error/fallback plots, analytic-fallback route maps, and fallback timelines. The same report entry point also accepts deployment bundles and JSONL training logs: python -m zeroproofml.report bundle <bundle_dir> writes VALIDATION_REPORT.md, and python -m zeroproofml.report training-log runs/scm_train_metrics.jsonl writes an adjacent Markdown log summary plus its metric SVG. When Plotly is available through zeroproofml[interactive], training-log report regeneration also writes <stem>_REPORT.html with interactive metric traces. For direct plotting, zeroproofml.utils.viz includes experimental 2D/3D mask-map helpers plus workspace heatmaps, route-to-solver overlays, fallback-route timelines, and per-batch monitoring summaries.

The make reproduce-* targets replay the frozen commands in artifacts/paper_2026/commands.json. Override REPRO_ROOT to write into a fresh directory when rerunning a bundle. The same artifact manifest now records pinned CPU/GPU container recipes under artifacts/paper_2026/manifest.json; build them with the Dockerfiles in artifacts/paper_2026/containers/ and mount the repo at /workspace when replaying inside a container. See REPRODUCIBILITY.md for the shortest supported rerun path and the exact files that define the paper replay contract. The published paper artifact DOI is 10.5281/zenodo.18944465.

Acknowledgements

The theoretical foundation of this library builds on the pioneering work of Jan A. Bergstra and John V. Tucker on meadows and common meadows—algebraic structures that totalize the field of rational numbers by making division a total operation. Their formalization of division by zero as an absorptive element provides the mathematical rigor underlying our approach.

License

MIT License. See LICENSE for details.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

zeroproofml-0.5.1.tar.gz (653.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

zeroproofml-0.5.1-py3-none-any.whl (298.7 kB view details)

Uploaded Python 3

File details

Details for the file zeroproofml-0.5.1.tar.gz.

File metadata

  • Download URL: zeroproofml-0.5.1.tar.gz
  • Upload date:
  • Size: 653.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.13

File hashes

Hashes for zeroproofml-0.5.1.tar.gz
Algorithm Hash digest
SHA256 b132c988a41284c9f5d94c185680ddefb9bec2a249e743873ff970059f128803
MD5 ff90503463948d4eae718e66668d9f27
BLAKE2b-256 12f338fd463e443509e6548fb6acb8286688a552ca988931f82ded16e40bcd12

See more details on using hashes here.

File details

Details for the file zeroproofml-0.5.1-py3-none-any.whl.

File metadata

  • Download URL: zeroproofml-0.5.1-py3-none-any.whl
  • Upload date:
  • Size: 298.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.13

File hashes

Hashes for zeroproofml-0.5.1-py3-none-any.whl
Algorithm Hash digest
SHA256 2cbd75cde2a67aed3e01795f472ba43e2b7ec9887ccf28947028c92d91bf212d
MD5 2d5f4a49e87eb126ed8c5f596074ade2
BLAKE2b-256 21d01cdc3033170d79661118c4cd9e4788037f65e0115fc756690ebf2b8a40aa

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page