Metadata-Version: 2.4
Name: zeroproofml
Version: 0.6.0
Summary: Signed Common Meadow arithmetic for stable machine learning
Author-email: Zsolt Döme <dome@zeroproofml.com>
License-Expression: MIT
Project-URL: Homepage, https://zeroproofml.com
Project-URL: Repository, https://gitlab.com/domezsolt/zeroproofml
Project-URL: Documentation, https://zeroproofml-9aafa4.gitlab.io/
Project-URL: Issues, https://gitlab.com/domezsolt/zeroproofml/-/issues
Keywords: signed-common-meadow,scm,machine-learning,numerical-stability,autodiff,robustness
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Science/Research
Classifier: Programming Language :: Python
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Provides-Extra: torch
Requires-Dist: torch>=1.12; (platform_system != "Darwin" or platform_machine != "arm64") and extra == "torch"
Provides-Extra: jax
Requires-Dist: jax>=0.4.14; extra == "jax"
Requires-Dist: jaxlib>=0.4.14; (platform_machine != "arm64" or platform_system != "Darwin") and extra == "jax"
Provides-Extra: dev
Requires-Dist: numpy>=1.23; extra == "dev"
Requires-Dist: pytest>=7.4; extra == "dev"
Requires-Dist: pytest-cov>=4.1; extra == "dev"
Requires-Dist: hypothesis>=6.88; extra == "dev"
Requires-Dist: black>=23.7; extra == "dev"
Requires-Dist: ruff>=0.4.0; extra == "dev"
Requires-Dist: isort>=5.12; extra == "dev"
Requires-Dist: mypy>=1.4; extra == "dev"
Requires-Dist: pre-commit>=3.3; extra == "dev"
Provides-Extra: viz
Requires-Dist: matplotlib>=3.7; extra == "viz"
Requires-Dist: tensorboard>=2.8; extra == "viz"
Requires-Dist: Pillow>=9.3; extra == "viz"
Requires-Dist: pandas>=2.0; extra == "viz"
Provides-Extra: interactive
Requires-Dist: plotly>=5.22; extra == "interactive"
Provides-Extra: all
Requires-Dist: torch>=1.12; (platform_system != "Darwin" or platform_machine != "arm64") and extra == "all"
Requires-Dist: jax>=0.4.14; extra == "all"
Requires-Dist: jaxlib>=0.4.14; (platform_machine != "arm64" or platform_system != "Darwin") and extra == "all"
Dynamic: license-file

# ZeroProofML

<div align="center">

**Machine learning that handles division by zero gracefully**

[![Pipeline](https://gitlab.com/domezsolt/zeroproofml/badges/main/pipeline.svg)](https://gitlab.com/domezsolt/zeroproofml/-/pipelines)
[![Docs](https://img.shields.io/badge/docs-latest-blue)](https://zeroproofml-9aafa4.gitlab.io/)

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

</div>

## 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

```bash
# 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`](docs/33_namespace_guide.md):
implementation stays under `zeroproof.*`, new public examples should prefer
`zeroproofml.*`, and each example should use one namespace family consistently.

```python
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`](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`](docs/39_examples_tutorials.md), and the full
examples label map lives in
[`docs/38_examples_inventory.md`](docs/38_examples_inventory.md).
The end-to-end deployment workflow examples live under
[`examples/deployment/README.md`](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:

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

Run the larger eager-SCM oracle property-test profile locally with:

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

Run linting and type checking:

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

Generate the release-compliance artifacts from a built wheel:

```bash
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:

```bash
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:

```bash
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:

```bash
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:

```bash
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](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.
