ZeroProofML v0.7.0a1 API Reference

This page collects the public Python API for the signed common meadow (SCM) implementation described in this documentation set. v0.7.0a1 is a breaking semantic alpha; legacy v0.6 notes remain inline where they explain explicit compatibility behavior. See the migration guide and semantic limitations.

For the exact-vs-finite numerical scope, including which overflows are masked and which paths are refused, see 01_scm_foundations.md.

Stability map (stable vs experimental)

The table below is the stability contract for this documentation set. Anything not listed here should be treated as experimental/internal and may change without notice. The table uses the canonical zeroproofml.* import paths; matching zeroproof.* compatibility imports have the same support level unless noted otherwise. Namespace layering rule for future additions: implement maintained modules under zeroproofml.* and add explicit zeroproof.* compatibility wrappers only for historically public paths. The zeroproof compatibility namespace is part of this stability contract; it is deprecated, remains available through 0.8.x, and may be removed no earlier than 1.0.0 after the documented migration window.

Module Symbols Stability Notes
zeroproofml.scm.value SCMValue, scm_real, scm_complex, scm_assert_exact_real, scm_assert_exact_complex, scm_bottom Stable Legacy/exact-assertion SCM value contract; non-finite construction raises ValueError, finite-input non-finite arithmetic raises OverflowError, and bottom stores None
zeroproofml.scm.ops scm_add, scm_sub, scm_mul, scm_div, scm_inv, scm_neg, scm_pow, scm_log, scm_exp, scm_sqrt, scm_sin, scm_cos, scm_tan, plus tested *_numpy, *_torch, and *_jax variants Stable Scalar SCM helpers plus backend shims; mask_x / mask_y are keyword-only. Vector shims combine incoming masks, domain failures, and post-operation non-finite results into the returned mask, zero masked payloads, promote NumPy integer reciprocal to floating output, and keep masked Torch gradients finite on hazardous paths. Positional mask forms raise TypeError.
zeroproofml.scm.fracterm Fracterm, Polynomial, SimplificationMode, StrictPreservingTarget Stable Symbolic/common-meadow helpers exercised by property tests and flattening docs; Fracterm.strict_preserving_target declares the pure strict (P, Q) target, nonzero domain_assumptions are caller contracts for local simplification, and field-rational cancellation requires explicit unsafe simplification_mode="field_rational"
zeroproofml.scm._eager_oracle evaluate_fru_expression, FloatingCoefficientRefusal Stable (v0.6.1 strict refusal) Operational FRU evaluator; defaults to compatibility mode and emits RuntimeWarning for floating coefficients / assignments. Proof / certificate / checker callers must pass strict=True, which refuses those inputs with FloatingCoefficientRefusal(ValueError). Not a proof / exact-symbolic oracle unless strict mode succeeds
zeroproofml.scm.sign sign4, weak_sign, HystereticOrientationTracker, WeakSignState Stable typed core sign4(value) is the pure real SCM projection. weak_sign is a deprecated compatibility adapter for the historical merged sign/orientation/phase behavior. The named tracker owns history-aware engineering hysteresis.
zeroproofml.autodiff.policies GradientPolicy, gradient_policy, register_policy, apply_policy, apply_policy_vector Stable Policy routing for gradients near ⊥
zeroproofml.autodiff.graph SCMNode, add, sub, mul, div, stop_gradient Experimental Low-level graph scaffolding kept primarily for docs/examples/tests
zeroproofml.autodiff.projective GaugePolicy, ProjectiveNormalize, ProjectiveSample, encode, decode, renormalize, projectively_equal Legacy compatibility Historical local-gauge tuple utilities. Raw |Q| thresholds are gauge-dependent and are not the canonical v0.7 decision boundary; new code uses zeroproofml.projective.normalize_projective and a serialized typed decode policy.
zeroproofml.training lift_targets, lift_semantic_targets, SemanticTargets, lift_targets_torch, lift_targets_jax, lift_targets_numpy, AdaptiveSampler, AdaptiveSamplerConfig, sampling_weights, singularity_prob, perturbed_threshold, TrainingConfig, ResumeProfile, SCMTrainer, UnsafeCheckpointLoadUnavailable, load_checkpoint_mapping, LinearRamp, LossWeightsCurriculum Stable Training, named resume, fail-closed checkpoint, sampling, and curriculum entry points
zeroproofml.layers AngularProjectiveHead, SCMRationalLayer, SCMNorm, SCMSoftmax Stable Core layers used throughout examples/benchmarks
zeroproofml.layers.fru FractermRationalUnit, FRUExpression, FRUConstant, FRUVariable, FRURational, FRUAdd, FRUMul, FRUDiv, FlattenedFRU, UnflattenedFRUAudit, FRUDenominatorSource, DomainAssumption, FRUResourceRefusal, FLATTEN_MAX_WORK, FLATTEN_MAX_TERM_PRODUCT Experimental Small symbolic FRU AST for local P/Q flattening, simplification, experimental structural-validity metadata, and audit-only domain assumptions or unflattened bound-refusal records. Since v0.6.1 FRUExpression.flatten() runs a memoized DAG walk to bound pre-expansion work (FLATTEN_MAX_WORK = 100_000, per-term FLATTEN_MAX_TERM_PRODUCT = 10_000) and raises FRUResourceRefusal(RuntimeError) before expansion; max_flatten_work / max_term_product keyword arguments raise the budget explicitly. Public structural-validity fields/accessors such as FlattenedFRU.denominator_provenance, FlattenedFRU.strict_validity_sources, and FlattenedFRU.validity_factors are experimental and orthogonal to the stable fault/semantic mask split
zeroproofml.layers.projective_rational ProjectiveRationalMultiHead, ProjectiveRRModelConfig, RRProjectiveRationalModel Stable Projective rational builders used by the README and inference/training integration tests
zeroproofml.inference typed_strict_inference, typed_strict_inference_tensor, StrictDecodePolicy, plus deprecated strict_inference* and SCMInferenceWrapper adapters v0.7 typed alpha Typed results and canonical gauge policy are the semantic source of truth. The merged-mask functions preserve v0.6 behavior only for migration, emit DeprecationWarning, and must not be used for new claim-bearing decisions. Deployment bundle surfaces remain separately versioned.
zeroproofml.benchmarks BenchmarkConfig, BenchmarkArtifacts, BenchmarkRun, BenchmarkComparison, BenchmarkBaselineComparison, run_benchmark, run_dose_benchmark, run_rf_benchmark, run_ik_benchmark, load_benchmark_run, compare_benchmark_runs, validate_run_dir Stable Top-level benchmark runner plus run loading/comparison and run-directory validation; direct zeroproofml.benchmarks.domains.* imports stay outside this stable contract
zeroproofml.losses LossConfig, implicit_loss, implicit_loss_jax, margin_loss, sign_consistency_loss, coverage, rejection_loss, soft_coverage_loss, SCMTrainingLoss Stable Core SCM loss stack. Since v0.6.1 scalar loss knobs are validated as finite and within documented domains, masked sign/margin losses use safe selection before reductions, and broadcastable separation masks are expanded before indexing
zeroproofml.metrics tau_infer_sweep_from_q_abs, tau_infer_sweep_report, write_tau_infer_sweep Stable Strict-gating evaluation helpers; RR-specific pole metrics remain example-level/internal for now
zeroproofml.reference_robotics_trajectory_eval ReferenceRoboticsTrajectoryAction, ReferenceRoboticsTrajectoryStepRequest, evaluate_reference_robotics_trajectory_policy, make_reference_robotics_dls_policy Experimental Closed-loop RR trajectory evaluation over the synthetic near-singularity dataset; intended for rollout/control-loop studies rather than the stable SCM core
zeroproofml.downstream_pipeline DownstreamPipelineReferenceSample, DownstreamPipelineSample, DownstreamPipelineStage, DownstreamPipelineSimulator, build_downstream_pipeline_simulator, compare_downstream_pipeline_strategies, simulate_downstream_pipeline, write_downstream_pipeline_visualization_pack Experimental Downstream composability simulator with configurable stage boundaries, built-in baseline comparisons over 1-step / 3-step / 5-step variants, and per-stage visualization artifacts
zeroproofml.utils from_ieee, to_ieee Stable IEEE-754 bridge helpers
zeroproofml.utils.logging JsonlLogger, read_jsonl Stable core TensorBoardLogger and jsonl_to_dataframe are experimental reporting conveniences; zeroproof.utils.logging remains a compatibility import
zeroproofml.utils.viz plot_mask_rates, plot_denominator_hist, plot_tau_infer_sweep, plot_tau_train_sweep, plot_2d_mask_map, plot_3d_mask_map, plot_workspace_rate_heatmaps, plot_route_to_solver_overlay, plot_fallback_route_timeline, plot_monitoring_batch_summary, plot_confusion_matrix, plot_categorical_reliability, plot_detj_stratified_metrics, plot_safety_accuracy_pareto, plot_eval_log Experimental Lightweight plotting primitives stay under the canonical zeroproofml.utils.viz path and are grouped under training, strict_inference, benchmarks, and domains submodules; higher-level report generators should live in a separate report layer if they become maintained APIs; zeroproof.utils.viz remains a compatibility import

The examples/robotics/rrr_ik_* and ik6r_* scripts are intentionally absent from this table: they remain example-level workflows rather than first-class experimental integrations until they gain a maintained zeroproofml.* surface plus the same artifact-contract and CI expectations used for supported robotics entry points.

SCM Core (zeroproofml.scm)

zeroproofml.scm.value

  • SCMValue: immutable value container carrying either a numeric payload or the absorptive bottom .
  • scm_real(x: float) -> SCMValue: construct a finite SCM value from a real number.
  • scm_complex(z: complex) -> SCMValue: construct a finite SCM value from a complex number.
  • scm_assert_exact_real(x) / scm_assert_exact_complex(z): explicit spellings for legacy exact-literal assertions. A zero asserted through this API is an exact denominator zero; raw zero in the evidence-bearing typed API is only machine evidence.
  • scm_bottom() -> SCMValue: return the absorptive bottom element.

zeroproofml.scm.ops

  • Arithmetic helpers mirror common meadow semantics: scm_add, scm_sub, scm_mul, scm_div, scm_inv, scm_neg, scm_pow.
  • Transcendental helpers respect the bottom element: scm_log, scm_exp, scm_sqrt, scm_sin, scm_cos, scm_tan.
  • Vectorized helpers return (payload, mask). In v0.6.1 the mask is the authoritative bottom status for incoming masks, zero/inverse-zero division, unsupported real domains, and finite IEEE overflow/non-finite backend results. Payload entries where mask=True are finite zero placeholders. Complex vector pow accepts real exponents only; complex exponents are refused in v0.6.1.
  • All functions accept SCMValue or plain Python scalars for ergonomic use in notebooks and examples.

Autodiff (zeroproofml.autodiff)

Gradient policies (zeroproofml.autodiff.policies)

  • GradientPolicy: enum of gradient handling strategies (CLAMP, PROJECT, REJECT, PASSTHROUGH).
  • gradient_policy(policy: GradientPolicy): validated context-local override of the active policy; asyncio children inherit the value at task creation and new threads start without an override.
  • Policy selection precedence is explicit argument, context override, registered layer default, then CLAMP.
  • register_policy(layer: str, policy: GradientPolicy): register normalized layer-specific defaults through a synchronized registry.
  • policy_registry_snapshot() / restore_policy_registry(snapshot): obtain an immutable policy-default snapshot or atomically restore a validated snapshot.
  • GradientPolicyConfig: serialize and load stable gradient-policy enum values.
  • apply_policy(gradient: float, is_bottom: bool, policy: GradientPolicy | None = None) -> float: transform a gradient according to the active policy.
  • apply_policy_vector(...): vectorised version of apply_policy.

Computation graph (zeroproofml.autodiff.graph) (experimental)

  • Experimental: this low-level graph scaffolding is kept primarily for docs/examples/tests and may change without notice.
  • SCMNode: lightweight computation node carrying a forward SCMValue, autodiff metadata, and an is_bottom flag for policy routing.
  • Constructors: SCMNode.constant(value), SCMNode.stop_gradient(node).
  • Primitives: add, sub, mul, div, each propagating bottom semantics.
  • Utilities: backward(upstream=1.0, policy=None), trace(depth=0).
  • Functional helpers mirror the methods: add, sub, mul, div, stop_gradient.

Projective tuples (zeroproofml.autodiff.projective)

  • GaugePolicy: enum of projective magnitude conventions (canonical_denominator, unit_l2_projective, and angular_unit_circle).
  • ProjectiveNormalize(policy=GaugePolicy.CANONICAL_DENOMINATOR, gamma=0.0): callable helper for applying an explicit gauge convention to (N, D) before downstream thresholding or monitoring. The default preserves exported denominator magnitudes; the unit policies normalize by the projective L2 norm and leave (0, 0) unchanged for explicit caller routing.
  • ProjectiveSample: dataclass representing a homogeneous tuple (N, D).
  • encode(value: SCMValue) -> ProjectiveSample: lift an SCM value to projective coordinates (finite → (x, 1), bottom → (1, 0)).
  • decode(sample: ProjectiveSample) -> SCMValue: map a projective tuple back to SCM, emitting when D = 0.
  • renormalize(numerator, denominator, gamma=1e-9, stop_gradient=None): detached renormalisation used in projective training (auto-detects Torch/JAX tensors and applies detach/stop_gradient to the norm).
  • projectively_equal(a, b, atol=1e-8) -> bool: compare projective tuples up to scaling.

Training helpers (zeroproofml.training)

  • zeroproofml.training.targets.lift_targets: legacy/simple sentinel lifting for finite values plus NaN/Inf bottoms; stable for compatibility, but not the preferred audit path.
  • zeroproofml.training.targets.lift_semantic_targets: lift numeric targets plus explicit SemanticTargetLabel enum values (FINITE, BOTTOM, CENSORED_BELOW, CENSORED_ABOVE, EXACT_DOMAIN_INVALID, OBSERVATION_DOMAIN_INVALID, MISSING, or FAULT) into SemanticTargets with projective coordinates, finite/bottom masks, orientation labels, and semantic-vs-fault bottom-kind codes. Raw strings are rejected.
  • zeroproofml.training.sampler.AdaptiveSampler: wraps PyTorch dataloaders with singularity-aware sampling weights.
  • zeroproofml.training.sampler.AdaptiveSamplerConfig: sampler config for AdaptiveSampler.
  • zeroproofml.training.sampler.singularity_prob and sampling_weights: tested helper functions for adaptive sampling decisions. singularity_prob consumes finite canonical denominator scores in [0,1]; its historical q_values parameter name does not authorize raw-gauge denominators.
  • zeroproofml.training.gap.perturbed_threshold: lightweight training-time gap helper.
  • zeroproofml.training.trainer.TrainingConfig: config container for SCMTrainer (early-stop thresholds, AMP toggle, optional validation loader, logging hook, gradient-policy override, tau_infer, projective_coordinate_axis, and the explicit allow_bottom_unreachable escape hatch). projective_coordinate_axis="model" uses the model declaration, an integer selects a shared-denominator tuple axis, and None selects elementwise pairs. Every numeric field is validated at construction: gradient_accumulation_steps >= 1, max_epochs >= 1, coverage_patience >= 1, coverage_threshold ∈ [0, 1], and learning_rate is finite and strictly positive. Boolean flags are not coerced, loss weights are copied and must be finite/nonnegative, and thresholds use validate_tau_infer / validate_tau_train.
  • zeroproofml.training.trainer.SCMTrainer: training loop integrating projective decoding, coverage tracking, gradient policies, and schema-v4 resume. TrainingConfig.resume_profile selects a named CPU/basic, CPU/shuffled-single-worker, CUDA/single-device, or unqualified contract. load_model_state and load_checkpoint are untrusted loaders requiring PyTorch 2.10.0+ and never fall back from weights_only=True; load_trusted_checkpoint warns and is only for trusted producers. Resume identity covers model/optimizer/scheduler/loss/data-order configuration; only a max_epochs extension is permitted drift. See the complete capability matrix.
  • SCMTrainer checks inf/NaN bottom labels against projective heads that expose bottom_capability(tau_infer) and raises when the denominator construction cannot enter |Q| < tau_infer. Set allow_bottom_unreachable=True only when those labels are intentional noise or outside the current task.
  • lift_targets_torch, lift_targets_jax, and lift_targets_numpy: backend-specific target lifting helpers.
  • Optional curricula:
  • LinearRamp and LossWeightsCurriculum for per-epoch loss-weight schedules (passed into loss functions that accept loss_weights).

Layers (zeroproofml.layers)

  • AngularProjectiveHead: unit-circle projective output head (P=cosθ, Q=sinθ) for stable strict gating. bottom_capability(tau_infer) reports whether strict bottom emission is reachable by construction.
  • SCMRationalLayer, SCMNorm, SCMSoftmax: SCM-aware PyTorch layers. Since v0.6.1 SCMRationalLayer.forward(...) classifies non-finite inputs and overflowed basis features before multiplying by trainable parameters, classifies non-finite numerator / denominator values before division, substitutes safe operands at every flagged index, and (for sub-float64 inputs) adds a promoted-float64 pre-division overflow bound so the division node's local Jacobian never enters the autograd graph on singular or overflowing samples. singular_epsilon is validated as finite and non-negative at construction. Projective normalization, training/autograd, and typed strict decoding are real-valued; complex coordinates raise TypeError rather than losing their imaginary component. SCMNorm uses safe selection before masked reductions and validates eps as finite and non-negative. The output payload at bottom indices is a documented placeholder (0.0 for rational layers, NaN for current normalization masks); bottom_mask is authoritative.
  • zeroproofml.layers.fru (experimental): typed symbolic FRU helpers (FRUExpression, FRURational, FlattenedFRU, FractermRationalUnit) for flattening small composed rational heads into a checked P/Q pair with structural validity provenance and audit-only domain_assumptions. FractermRationalUnit.flatten_expression(..., preserve_unflattened=True) returns UnflattenedFRUAudit instead of raising when strict flattening succeeds algebraically but exceeds the configured local FRU depth or degree budget; it still runs strict flattening and bound checks first, is not a pre-flatten shortcut, and does not preserve artifacts that fail only after an explicit non-strict flattening mode. UnflattenedFRUAudit.preservation_mode is explicitly audit_only, so the record stores the original FRUExpression tree plus refusal metadata and is not a runtime eager-evaluation fallback. Any future runtime fallback must be a separate opt-in that uses eager SCM semantics and documents the slower path. FlattenedFRU.denominator_provenance and FlattenedFRU.validity_factors are experimental structural-validity fields/accessors. FlattenedFRU.denominator_provenance is preserved for compatibility, FlattenedFRU.strict_validity_sources is the experimental structural-validity source field for factors not already enforced by the reduced payload denominator, and FlattenedFRU.validity_factors is the derived factor-only accessor. FlattenedFRU.structural_validity_output_schema(...) reserves deterministic value, fault-mask, and semantic-mask output names for a future consumer-requested structural-provenance promotion without making those outputs stable today. FlattenedFRU.cancellation_domain_assumptions records the declared nonzero facts tied to cancelled symbolic factors for audit/export consumers. FlattenedFRU.strict_preserving_target declares the guarded strict FRU target, where reduced payloads rely on load-bearing validity factors. The structural provenance trace is orthogonal to the stable strict-inference fault/semantic mask split and has no promotion gate. If a future consumer requests promotion, define a new structural-provenance gate at that time rather than pre-committing thresholds now. Guarded strict FRU evaluation still treats its validity factors as required internal checks for reduced payloads. Field-rational simplification requires explicit unsafe simplification_mode="field_rational"; declared nonzero assumptions are caller contracts, not runtime guards.
  • zeroproofml.layers.projective_rational: ProjectiveRationalMultiHead, ProjectiveRRModelConfig, and RRProjectiveRationalModel are the supported projective-rational building blocks used by the README quickstart and integration tests. ProjectiveRationalMultiHead.bottom_capability(tau_infer) reports "unreachable_by_construction" when configured denominator floors, including anchored softplus floors, cannot enter the strict |Q| < tau_infer region.

Inference (zeroproofml.inference)

  • typed_strict_inference(...) / typed_strict_inference_tensor(...): canonical v0.7 scalar and tensor decoders. They normalize with the declared canonical gauge and preserve exact bottom, machine zero, threshold rejection, ambiguity, representation faults, and numerical faults on separate axes. Tensor policies hash coordinate_axis; use -1 for a last-axis numerator tuple with one shared denominator and None for elementwise pairs.
  • InferenceConfig: inference thresholds (tau_infer, optional tau_train for gap diagnostics) plus legacy provenance metadata controls (provenance, deprecated provenance_fault_threshold, and provenance_representation). Since v0.6.1 tau_infer must be finite and strictly positive; tau_train (when set) must be finite, strictly positive, and >= tau_infer. Illegal values raise ValueError at construction. Eager strict decoders also reject a positive tau_infer that narrows to 0.0 in the backend denominator dtype, using the real component dtype for complex denominators. Prefer numerical_hazard_threshold for monitor-only finite-denominator hazard metadata; the deprecated provenance_fault_threshold constructor/metadata name is an alias. Both accept only None or finite nonnegative real values, normalize through the alias, and are revalidated on bundle load. Neither setting contributes to bottom_mask, fault_mask, or semantic_bottom_mask.
  • strict_inference(...), strict_inference_numpy(...), and strict_inference_jax(...): deprecated v0.6 compatibility projections. Results unpack as (decoded, bottom_mask, gap_mask) and retain the historical raw-|Q| threshold and merged-mask vocabulary. Machine zero and threshold rejection appearing in semantic_bottom_mask are compatibility encodings, not exact-bottom evidence. Calls emit DeprecationWarning.
  • decode_strict_censored_3way(...): semantic/censored strict decoder returning a tuple-compatible SemanticDecodeResult(decoded, bottom_mask, class_id).
  • strict_inference_numpy(...) / strict_inference_jax(...): backend-specific decode helpers used when callers want an explicit NumPy or JAX entry point.
  • SCMInferenceWrapper: wraps a (P, Q)-outputting model and applies strict decoding in eval mode; eager Python results expose the stable mask provenance attributes while retaining the three-field tuple unpacking path. The eager tuple override is documented as wrapper((inputs, validity_denominator)): the second tensor is an external validity denominator Q_valid used for additional bottom/gap mask gating, not a boolean mask, while the model-returned Q remains the value denominator for decoding and bottom detection.
  • get_inference_output_schema(...): returns the promoted schema-v2 descriptor for stable provenance-bearing bundle outputs.
  • get_experimental_inference_output_schema(...): returns the legacy versioned schema descriptor used by recorded pre-promotion provenance sidecars. New schema-v2 bundle metadata writes the promoted descriptor under inference_output_schema; the old experimental_inference_output_schema key is a deprecated loading alias.
  • Bundle utilities:
  • validate_bundle(bundle_dir) checks model.onnx + metadata.json consistency.
  • load_onnx_runtime_bundle(bundle_dir, providers=..., provider_options=..., session_options=...) validates the bundle, opens model.onnx with onnxruntime, and returns an ONNXRuntimeBundle. Schema-v3 bundles require the recorded CPUExecutionProvider order and provider options and refuse unrecorded session options; schema-v2 outputs retain the legacy tuple-compatible provenance view.
  • run_bundle_reference_smoke_test(bundle_dir, model, smoke_inputs, ...) runs a small in-process parity check. For schema v3 it applies the embedded decoder policy to the raw (P, Q) model and compares every typed status field plus payload; recorded legacy schemas keep their merged-mask check.
  • generate_validation_report(bundle_dir, benchmark_dir=..., output_path=..., runtime_summary_path=..., calibration_report_path=...) writes a lightweight Markdown report, includes provenance schema / fault-vs-semantic rate breakdowns when those diagnostics are available, automatically picks up adjacent inference_summary.json runtime/fallback stats plus parent benchmark summaries and DOSE operating-point calibration provenance when those sidecars are present (or via the explicit path overrides), and saves a concise *.summary.json sidecar when you persist the report to disk.
  • Patterns and operations:
  • decode_strict_censored_3way(...) implements a strict-gate + optional finite orientation side-channel / direction-head decode for 3-way censoring tasks and can optionally consume provenance diagnostics to reserve the direction head for semantic bottoms while keeping fault-like bottoms out of implicit IEEE-infinity sign routing.
  • StrictInferenceMonitor and strict_inference_rates(...) help monitor bottom/gap/acceptance rates, optionally split bottoms into fault vs semantic rates when provenance diagnostics are supplied, optionally expose monitor-only numerical_hazard_rate from a supplied finite-hazard mask, can export monitor state plus per-update histograms and per-batch summaries through StrictInferenceMonitor.export_state(...), and can emit structured trigger/drift records through an optional event_logger.
  • Fallback helpers: reject_on_bottom, reject_on_gap, safe_sentinel, route_to_analytic_solver. route_to_analytic_solver(...) can also emit structured fallback-routing events with provenance tags when an event_logger is provided.
  • Export helpers:
  • script_module remains a legacy TorchScript compatibility helper, and ONNX is the preferred deployment path.
  • script_module(model) for legacy TorchScript compatibility only.
  • export_onnx_model(model, example_inputs, output_path, ...) for ONNX; this is the preferred deployment/export path.
  • export_bundle(model, example_inputs, out_dir, decode_policy=..., ...) for a model.onnx + metadata.json bundle. The default schema-v3 export wraps a raw (P, Q) model with typed decoding, emits the fixed ResultTensor ABI, and embeds the complete decoder policy under its semantic-identity hash. Pass bundle_schema_version=2 explicitly only for the deprecated merged-mask compatibility contract.

Losses (zeroproofml.losses)

  • LossConfig: grouped hyperparameters for the combined training loss.
  • implicit_loss, implicit_loss_jax, margin_loss, sign_consistency_loss, coverage, rejection_loss, and soft_coverage_loss implement the objectives described in 04_loss_functions.md; sign_consistency_loss is a singular-orientation auxiliary loss, not a generic finite-regression loss, hard rejection_loss(is_bottom, ...) is detached metric-style penalty accounting, and soft_coverage_loss(P, Q, tau, temperature, target) is the canonical-gauge, scale-invariant differentiable under-coverage surrogate with invalid-cell gradient isolation.
  • Since v0.6.1 implicit_loss / sign_consistency_loss validate gamma, margin_loss validates tau_train, scm_separation_losses validates tau_bot <= tau_finite, and LossConfig validates all scalar weights / thresholds. Masked sign and margin losses use safe selection before reduction so masked NaN samples cannot contaminate selected samples.
  • implicit_loss(..., detach_scale=False) and implicit_loss_jax(..., detach_scale=False) keep the implicit-loss scale attached by default; pass detach_scale=True to opt into the legacy detached-scale shrink heuristic.
  • margin_loss(..., reduction="population" | "conditional") defaults to the population-style masked batch mean; conditional reduction averages over finite targets only. Pass numerator=P for canonical-gauge scores; the Q-only form is retained as a v0.6 raw-coordinate compatibility helper.
  • SCMTrainingLoss combines the individual terms with configurable weights (λ_margin, λ_sign, λ_rej) and computes its margin from the canonical (P,Q) score. Pass coordinate_axis for a shared-denominator tuple.
  • When sign_consistency_loss is called without mask_singular, or SCMTrainingLoss receives lambda_sign > 0 without mask_singular, sign supervision is restricted to targets with abs(Y_d) <= epsilon_sing; pass mask_singular explicitly to supervise finite orientations or another signed task domain.
  • DOSE-specific direction-head losses, samplers, and mixed finite-MSE/censoring recipes remain benchmark-only; use the generic losses above plus curricula instead of depending on DOSE follow-up scripts as public APIs.

Benchmarks (zeroproofml.benchmarks)

  • run_dose_benchmark(...), run_rf_benchmark(...), and run_ik_benchmark(...) are the per-domain benchmark APIs used by the CLI.
  • BenchmarkConfig and run_benchmark(...) remain available when tooling wants to assemble the domain/config pair programmatically.
  • Direct zeroproofml.benchmarks.domains.* imports remain importable for tests/tooling, but the stable contract stays at the top-level zeroproofml.benchmarks package and CLI.
  • DOSE-specific direction-head and loss follow-ups are benchmark-only evidence paths, including python -m zeroproofml.benchmarks dose --mode frozen-dirhead; no DOSE-only head/loss is promoted to zeroproofml.layers or zeroproofml.losses in this release.
  • Legacy wrapper files under scripts/ and examples/robotics/rr_ik_dataset.py still delegate to these APIs, but now emit DeprecationWarning at runtime so migration is visible in code as well as docs.
  • BenchmarkConfig.resume / python -m zeroproofml.benchmarks ... --resume continue interrupted long-profile benchmark runs from the same out_root while preserving per-attempt provenance history. Paper-exact experiments remain frozen to the v0.4.3 artifact.
  • BenchmarkConfig.skip_complete_seeds / --skip-complete-seeds reuse an existing out_root and run only missing canonical seed artifacts; BenchmarkConfig.force_rerun / --force-rerun rerun the requested seeds in an existing out_root.
  • BenchmarkConfig.html_report / python -m zeroproofml.benchmarks ... --html-report add an optional RUN_REPORT.html; every completed run always writes RUN_REPORT.md.
  • zeroproofml.report.generate_benchmark_report(...), generate_bundle_report(...), and generate_training_log_report(...) regenerate Markdown reports from stored artifacts and write standard SVG summary figures; benchmark reports write metric means, per-seed distributions, and baseline-delta plots when paired stats are present, and DOSE benchmark reports also write figures/dose_figure_pack/ when aggregated/dose_diagnostics.json is present. Benchmark reports can also write optional embedded HTML with --html-report, and training-log reports add an interactive <stem>_REPORT.html when Plotly is installed via zeroproofml[interactive]. Regenerated benchmark and training-log reports use artifact-relative source labels so copied artifact directories reproduce the same report content.
  • load_benchmark_run(run_dir) validates and loads a completed scientific benchmark run directory into a BenchmarkRun object containing the manifest, provenance, summary, and paired stats payloads.
  • compare_benchmark_runs(target, baselines) compares one run with one or more baseline run directories or loaded BenchmarkRun objects and returns per-baseline paired statistics plus common model/metric metadata.
  • validate_run_dir(run_dir) checks a completed run directory for the required artifacts, validates the manifest / provenance / summary / paired-stats JSON schemas, and verifies recorded artifact hashes against the files on disk.

Metrics (zeroproofml.metrics)

  • tau_infer_sweep_from_q_abs(...): compute FN/FP/bottom-rate curves from cached |Q| values without re-running full inference.
  • tau_infer_sweep_report(curves, title=...): render a compact Markdown report for those curves.
  • write_tau_infer_sweep(out_dir, curves, provenance=...): write the JSON + Markdown pair used by deployment/benchmark reporting.
  • RR-specific pole metrics under zeroproofml.metrics.pole_2d remain example-level helpers and are not part of the stable contract yet.

RR trajectory evaluation (zeroproofml.reference_robotics_trajectory_eval) (experimental)

  • ReferenceRoboticsTrajectoryStepRequest: closed-loop per-step request object containing the current RR state, current det(J) diagnostics, target waypoint, derived workspace command, and the dataset's reference DLS action.
  • ReferenceRoboticsTrajectoryAction: policy response container with (dtheta1, dtheta2) plus optional fallback markers so evaluations can report fallback frequency by trajectory bin and, when fallback labels include fault / semantic, provenance-aware splits.
  • make_reference_robotics_dls_policy(...): build a DLS baseline policy that can replay the synthetic RR trajectory dataset under the same damping law used by the dataset generator.
  • evaluate_reference_robotics_trajectory_policy(dataset, policy, ...): replay a policy over the stratified RR trajectory dataset and summarize aggregate plus per-start-bin tracking error, reference-error gap, joint-step magnitude, fallback rate, per-step fallback-rate traces, joint-limit violations, chattering events, and policy latency/budget violations.

Downstream pipeline simulator (zeroproofml.downstream_pipeline) (experimental)

  • DownstreamPipelineSample: lightweight carrier for decoded scalar/vector payloads plus a reject flag and optional provenance label.
  • DownstreamPipelineReferenceSample: strategy-agnostic reference payload used to encode the built-in scalar-only, abstention/uncertainty, strict-SCM, and strict-SCM-plus-direction-head comparison baselines.
  • DownstreamPipelineStage: configurable downstream boundary that can drop the reject flag, provenance side channel, and optional direction-label side channel before an optional sample transform runs, with built-in bad-downstream toggles for nan_to_num, missing-flag drops, clipping, default fills, JSON/CSV round-trips, and aggregate_mean reductions.
  • build_downstream_pipeline_simulator(...): builds the default 1-step, 3-step, or 5-step variants used for composability experiments, threads shared bad-downstream toggle settings into the default stages, or validates a caller-supplied stage list against one of those variant lengths.
  • compare_downstream_pipeline_strategies(...): replay the same configured pipeline across the built-in scalar-only baseline, abstention/uncertainty baseline, strict SCM, and strict SCM + direction head encodings, returning one simulation result per strategy.
  • simulate_downstream_pipeline(samples, config) / DownstreamPipelineSimulator.simulate(...): replay samples through the configured stage chain and summarize per-stage finite-payload rates, reject-flag fidelity, propagated reject/censor/singularity fidelity, downstream decision accuracy, a payload/flag consistency calibration proxy under corruption, provenance survival (including per-label fault-vs-semantic fidelity when available), direction-label fidelity, and unsafe finite accepts when reject-flag carriers are lost.
  • build_downstream_pipeline_stage_summary_rows(...), write_downstream_pipeline_stage_summaries(...): flatten a simulation or strategy comparison into per-stage JSON/CSV summaries for transition analysis.
  • render_downstream_pipeline_transition_diagram_svg(...), render_downstream_pipeline_failure_propagation_svg(...), and render_downstream_pipeline_corruption_sensitivity_svg(...): generate notebook-free SVG diagnostics for stage handoffs, failure propagation, and downstream corruption sensitivity.
  • write_downstream_pipeline_visualization_pack(...): writes composability_figure_pack/ with stage-summary JSON/CSV, transition diagrams, failure-propagation diagrams, corruption-sensitivity curves, README, and manifest.
  • render_downstream_pipeline_report_markdown(...), render_downstream_pipeline_report_html(...), and write_downstream_pipeline_report(...): turn a simulation result or strategy comparison into composability artifacts, with write_downstream_pipeline_report(...) now also saving a machine-readable DOWNSTREAM_PIPELINE_REPORT.json sidecar containing per-stage sample snapshots for later analysis and optionally writing the visualization pack.

How to read this page

The functions above intentionally mirror the conceptual contract: train on smooth, infer on strict. Use the docstrings in each module for parameter details and examples; this page is a signpost for the available surfaces.

Utilities (zeroproofml.utils)

  • Prefer the stable JSONL path (JsonlLogger, read_jsonl) in release-facing integrations; the reporting conveniences below remain experimental.
  • IEEE bridge: from_ieee, to_ieee
  • zeroproofml.utils.logging: stable core = JsonlLogger, read_jsonl; experimental reporting conveniences = TensorBoardLogger, jsonl_to_dataframe, plus read_metric_log_runs(...) / aggregate_metric_logs(...) for multi-seed and multi-run JSONL summaries. The legacy zeroproof.utils.logging path remains supported as a compatibility import.
  • The same logging module also exposes experimental metric_log_records_to_wide_rows(...) / metric_log_records_to_long_rows(...) converters so dashboards and downstream tooling can flatten versioned metric logs without reimplementing schema parsing.
  • JSONL trainer/eval metric records use schema_name="zeroproofml.metric_log" and schema_version=1; metric_log_record(...) creates the canonical metrics payload while preserving flat top-level metric keys for older readers.
  • zeroproofml.utils.viz: experimental lightweight plotting primitives (plot_mask_rates, plot_denominator_hist, plot_tau_infer_sweep, plot_tau_train_sweep, plot_2d_mask_map, plot_3d_mask_map, plot_workspace_rate_heatmaps, plot_route_to_solver_overlay, plot_fallback_route_timeline, plot_monitoring_batch_summary, plot_confusion_matrix, plot_categorical_reliability, plot_detj_stratified_metrics, plot_safety_accuracy_pareto, plot_eval_log). Lightweight plotting primitives stay under the canonical zeroproofml.utils.viz path and are grouped under training, strict_inference, benchmarks, and domains submodules; plot_denominator_hist accepts optional provenance masks or enum labels to color finite/fault/semantic denominator samples; higher-level report generators should live in a separate report layer if they become maintained APIs; zeroproof.utils.viz remains a compatibility import.