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 and direction-head side channels provide orientation near singularities without treating IEEE infinities as decoded scalar values
  • 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). For import guidance, see docs/33_namespace_guide.md: implementation stays under zeroproof.*, new public examples should prefer zeroproofml.*, and each example should use one namespace family consistently.

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 (legacy/simple targets may use inf/NaN).
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, tau_infer=1e-6),
)
trainer.fit()

# For audited target streams, SCMTrainer accepts explicit semantic labels:
# DataLoader samples can be (inputs, values, "finite"/"censored_below"/"fault"/...)
# Loss functions that accept `semantic_targets` receive masks and bottom-kind codes.

# Strict inference (non-finite P/Q and optional validity factors fail closed; masks are authoritative).
wrapped.eval()
result = wrapped(x)
decoded, bottom_mask, gap_mask = result  # backward-compatible tuple unpacking
fault_mask = result.fault_mask
semantic_bottom_mask = result.semantic_bottom_mask
bottom_provenance = result.bottom_provenance

When targets include singular labels (inf/NaN), SCMTrainer checks projective heads that expose bottom_capability(tau_infer) and raises if the denominator construction cannot enter the strict |Q| < tau_infer bottom region. Sentinel-based lift_targets(...) remains a legacy/simple convenience path for demos and compatibility, but it collapses semantic bottoms, censored labels, missing values, and faults into non-finite payloads. New code that needs an auditable fault/semantic split should call lift_semantic_targets(...) with explicit labels (finite, bottom, censored_below, censored_above, domain_invalid, missing, or fault) instead of encoding those distinctions with sentinels.

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 strict mask and provenance contract, see docs/34_masks_and_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; non-finite projective payloads and optional guarded-FRU validity factors fail closed into bottom_mask and fault_mask, semantic threshold bottoms land in semantic_bottom_mask, and gap_mask tracks the train-infer boundary region (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 the larger eager-SCM oracle property-test profile locally with:

ZEROPROOFML_SCM_ORACLE_PROFILE=nightly pytest tests/scm/test_oracle_vs_flattened.py -q

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. For paper-exact reproduction, pin to zeroproofml==0.4.3 or the matching release tag v0.4.3; the v0.6.x line should not reinterpret paper-era bundles under newer strict-inference schemas.

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.6.0.tar.gz (731.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.6.0-py3-none-any.whl (322.9 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: zeroproofml-0.6.0.tar.gz
  • Upload date:
  • Size: 731.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.6.0.tar.gz
Algorithm Hash digest
SHA256 cfef75a836230d5921b166eab9c13c56979d3dbf414e6655ab7299ecb42397d9
MD5 c7d3e7a4f07e2c9fe5d24ea3746aeee2
BLAKE2b-256 ddb63fd83b85181368183e77b74be0eb14ac2ad5447f71e125aa1234ccad1476

See more details on using hashes here.

File details

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

File metadata

  • Download URL: zeroproofml-0.6.0-py3-none-any.whl
  • Upload date:
  • Size: 322.9 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.6.0-py3-none-any.whl
Algorithm Hash digest
SHA256 686eeb776bce23abe2f729ac535e6748a0f9e6d5b7d6a0f05ad98a934dbbc3c0
MD5 d93fc5b160f2430b4d2dd48d720a8aa4
BLAKE2b-256 8eea5ce9fcfc57454c1874248facdd0a07dba00285fdc00a300be6e979db752e

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