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 wheremask=Trueare finite zero placeholders. Complex vectorpowaccepts real exponents only; complex exponents are refused in v0.6.1. - All functions accept
SCMValueor 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 ofapply_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 forwardSCMValue, autodiff metadata, and anis_bottomflag 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, andangular_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⊥whenD = 0.renormalize(numerator, denominator, gamma=1e-9, stop_gradient=None): detached renormalisation used in projective training (auto-detects Torch/JAX tensors and appliesdetach/stop_gradientto 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 plusNaN/Infbottoms; stable for compatibility, but not the preferred audit path.zeroproofml.training.targets.lift_semantic_targets: lift numeric targets plus explicitSemanticTargetLabelenum values (FINITE,BOTTOM,CENSORED_BELOW,CENSORED_ABOVE,EXACT_DOMAIN_INVALID,OBSERVATION_DOMAIN_INVALID,MISSING, orFAULT) intoSemanticTargetswith 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 forAdaptiveSampler.zeroproofml.training.sampler.singularity_probandsampling_weights: tested helper functions for adaptive sampling decisions.singularity_probconsumes finite canonical denominator scores in[0,1]; its historicalq_valuesparameter name does not authorize raw-gauge denominators.zeroproofml.training.gap.perturbed_threshold: lightweight training-time gap helper.zeroproofml.training.trainer.TrainingConfig: config container forSCMTrainer(early-stop thresholds, AMP toggle, optional validation loader, logging hook, gradient-policy override,tau_infer,projective_coordinate_axis, and the explicitallow_bottom_unreachableescape hatch).projective_coordinate_axis="model"uses the model declaration, an integer selects a shared-denominator tuple axis, andNoneselects elementwise pairs. Every numeric field is validated at construction:gradient_accumulation_steps >= 1,max_epochs >= 1,coverage_patience >= 1,coverage_threshold ∈ [0, 1], andlearning_rateis finite and strictly positive. Boolean flags are not coerced, loss weights are copied and must be finite/nonnegative, and thresholds usevalidate_tau_infer/validate_tau_train.zeroproofml.training.trainer.SCMTrainer: training loop integrating projective decoding, coverage tracking, gradient policies, and schema-v4 resume.TrainingConfig.resume_profileselects a named CPU/basic, CPU/shuffled-single-worker, CUDA/single-device, or unqualified contract.load_model_stateandload_checkpointare untrusted loaders requiring PyTorch 2.10.0+ and never fall back fromweights_only=True;load_trusted_checkpointwarns and is only for trusted producers. Resume identity covers model/optimizer/scheduler/loss/data-order configuration; only amax_epochsextension is permitted drift. See the complete capability matrix.SCMTrainerchecksinf/NaNbottom labels against projective heads that exposebottom_capability(tau_infer)and raises when the denominator construction cannot enter|Q| < tau_infer. Setallow_bottom_unreachable=Trueonly when those labels are intentional noise or outside the current task.lift_targets_torch,lift_targets_jax, andlift_targets_numpy: backend-specific target lifting helpers.- Optional curricula:
LinearRampandLossWeightsCurriculumfor per-epoch loss-weight schedules (passed into loss functions that acceptloss_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.1SCMRationalLayer.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-float64inputs) adds a promoted-float64pre-division overflow bound so the division node's local Jacobian never enters the autograd graph on singular or overflowing samples.singular_epsilonis validated as finite and non-negative at construction. Projective normalization, training/autograd, and typed strict decoding are real-valued; complex coordinates raiseTypeErrorrather than losing their imaginary component.SCMNormuses safe selection before masked reductions and validatesepsas finite and non-negative. The output payload at bottom indices is a documented placeholder (0.0for rational layers,NaNfor current normalization masks);bottom_maskis authoritative.zeroproofml.layers.fru(experimental): typed symbolic FRU helpers (FRUExpression,FRURational,FlattenedFRU,FractermRationalUnit) for flattening small composed rational heads into a checkedP/Qpair with structural validity provenance and audit-onlydomain_assumptions.FractermRationalUnit.flatten_expression(..., preserve_unflattened=True)returnsUnflattenedFRUAuditinstead 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_modeis explicitlyaudit_only, so the record stores the originalFRUExpressiontree 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_provenanceandFlattenedFRU.validity_factorsare experimental structural-validity fields/accessors.FlattenedFRU.denominator_provenanceis preserved for compatibility,FlattenedFRU.strict_validity_sourcesis the experimental structural-validity source field for factors not already enforced by the reduced payload denominator, andFlattenedFRU.validity_factorsis 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_assumptionsrecords the declared nonzero facts tied to cancelled symbolic factors for audit/export consumers.FlattenedFRU.strict_preserving_targetdeclares 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 unsafesimplification_mode="field_rational"; declared nonzero assumptions are caller contracts, not runtime guards.zeroproofml.layers.projective_rational:ProjectiveRationalMultiHead,ProjectiveRRModelConfig, andRRProjectiveRationalModelare 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_inferregion.
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 hashcoordinate_axis; use-1for a last-axis numerator tuple with one shared denominator andNonefor elementwise pairs.InferenceConfig: inference thresholds (tau_infer, optionaltau_trainfor gap diagnostics) plus legacy provenance metadata controls (provenance, deprecatedprovenance_fault_threshold, andprovenance_representation). Since v0.6.1tau_infermust be finite and strictly positive;tau_train(when set) must be finite, strictly positive, and>= tau_infer. Illegal values raiseValueErrorat construction. Eager strict decoders also reject a positivetau_inferthat narrows to0.0in the backend denominator dtype, using the real component dtype for complex denominators. Prefernumerical_hazard_thresholdfor monitor-only finite-denominator hazard metadata; the deprecatedprovenance_fault_thresholdconstructor/metadata name is an alias. Both accept onlyNoneor finite nonnegative real values, normalize through the alias, and are revalidated on bundle load. Neither setting contributes tobottom_mask,fault_mask, orsemantic_bottom_mask.strict_inference(...),strict_inference_numpy(...), andstrict_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 insemantic_bottom_maskare compatibility encodings, not exact-bottom evidence. Calls emitDeprecationWarning.decode_strict_censored_3way(...): semantic/censored strict decoder returning a tuple-compatibleSemanticDecodeResult(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 aswrapper((inputs, validity_denominator)): the second tensor is an external validity denominatorQ_validused for additional bottom/gap mask gating, not a boolean mask, while the model-returnedQremains 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 underinference_output_schema; the oldexperimental_inference_output_schemakey is a deprecated loading alias.- Bundle utilities:
validate_bundle(bundle_dir)checksmodel.onnx+metadata.jsonconsistency.load_onnx_runtime_bundle(bundle_dir, providers=..., provider_options=..., session_options=...)validates the bundle, opensmodel.onnxwithonnxruntime, and returns anONNXRuntimeBundle. Schema-v3 bundles require the recordedCPUExecutionProviderorder 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 adjacentinference_summary.jsonruntime/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.jsonsidecar 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.StrictInferenceMonitorandstrict_inference_rates(...)help monitor bottom/gap/acceptance rates, optionally split bottoms into fault vs semantic rates when provenance diagnostics are supplied, optionally expose monitor-onlynumerical_hazard_ratefrom a supplied finite-hazard mask, can export monitor state plus per-update histograms and per-batch summaries throughStrictInferenceMonitor.export_state(...), and can emit structured trigger/drift records through an optionalevent_logger.- Fallback helpers:
reject_on_bottom,reject_on_gap,safe_sentinel,route_to_analytic_solver.route_to_analytic_solver(...)can also emit structuredfallback-routingevents with provenance tags when anevent_loggeris provided. - Export helpers:
script_moduleremains 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 amodel.onnx+metadata.jsonbundle. The default schema-v3 export wraps a raw(P, Q)model with typed decoding, emits the fixedResultTensorABI, and embeds the complete decoder policy under its semantic-identity hash. Passbundle_schema_version=2explicitly 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, andsoft_coverage_lossimplement the objectives described in04_loss_functions.md;sign_consistency_lossis a singular-orientation auxiliary loss, not a generic finite-regression loss, hardrejection_loss(is_bottom, ...)is detached metric-style penalty accounting, andsoft_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_lossvalidategamma,margin_lossvalidatestau_train,scm_separation_lossesvalidatestau_bot <= tau_finite, andLossConfigvalidates all scalar weights / thresholds. Masked sign and margin losses use safe selection before reduction so maskedNaNsamples cannot contaminate selected samples. implicit_loss(..., detach_scale=False)andimplicit_loss_jax(..., detach_scale=False)keep the implicit-loss scale attached by default; passdetach_scale=Trueto 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. Passnumerator=Pfor canonical-gauge scores; the Q-only form is retained as a v0.6 raw-coordinate compatibility helper.SCMTrainingLosscombines the individual terms with configurable weights (λ_margin,λ_sign,λ_rej) and computes its margin from the canonical(P,Q)score. Passcoordinate_axisfor a shared-denominator tuple.- When
sign_consistency_lossis called withoutmask_singular, orSCMTrainingLossreceiveslambda_sign > 0withoutmask_singular, sign supervision is restricted to targets withabs(Y_d) <= epsilon_sing; passmask_singularexplicitly 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(...), andrun_ik_benchmark(...)are the per-domain benchmark APIs used by the CLI.BenchmarkConfigandrun_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-levelzeroproofml.benchmarkspackage 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 tozeroproofml.layersorzeroproofml.lossesin this release. - Legacy wrapper files under
scripts/andexamples/robotics/rr_ik_dataset.pystill delegate to these APIs, but now emitDeprecationWarningat runtime so migration is visible in code as well as docs. BenchmarkConfig.resume/python -m zeroproofml.benchmarks ... --resumecontinue interrupted long-profile benchmark runs from the sameout_rootwhile preserving per-attempt provenance history. Paper-exact experiments remain frozen to thev0.4.3artifact.BenchmarkConfig.skip_complete_seeds/--skip-complete-seedsreuse an existingout_rootand run only missing canonical seed artifacts;BenchmarkConfig.force_rerun/--force-rerunrerun the requested seeds in an existingout_root.BenchmarkConfig.html_report/python -m zeroproofml.benchmarks ... --html-reportadd an optionalRUN_REPORT.html; every completed run always writesRUN_REPORT.md.zeroproofml.report.generate_benchmark_report(...),generate_bundle_report(...), andgenerate_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 writefigures/dose_figure_pack/whenaggregated/dose_diagnostics.jsonis present. Benchmark reports can also write optional embedded HTML with--html-report, and training-log reports add an interactive<stem>_REPORT.htmlwhen Plotly is installed viazeroproofml[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 aBenchmarkRunobject 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 loadedBenchmarkRunobjects 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_2dremain 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, currentdet(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 includefault/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 fornan_to_num, missing-flag drops, clipping, default fills, JSON/CSV round-trips, andaggregate_meanreductions.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(...), andrender_downstream_pipeline_corruption_sensitivity_svg(...): generate notebook-free SVG diagnostics for stage handoffs, failure propagation, and downstream corruption sensitivity.write_downstream_pipeline_visualization_pack(...): writescomposability_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(...), andwrite_downstream_pipeline_report(...): turn a simulation result or strategy comparison into composability artifacts, withwrite_downstream_pipeline_report(...)now also saving a machine-readableDOWNSTREAM_PIPELINE_REPORT.jsonsidecar 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, plusread_metric_log_runs(...)/aggregate_metric_logs(...)for multi-seed and multi-run JSONL summaries. The legacyzeroproof.utils.loggingpath 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"andschema_version=1;metric_log_record(...)creates the canonicalmetricspayload 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 canonicalzeroproofml.utils.vizpath and are grouped undertraining,strict_inference,benchmarks, anddomainssubmodules;plot_denominator_histaccepts 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.vizremains a compatibility import.