Skip to main content

exacta

Metrics and differentiable losses for 2D and 3D medical-image segmentation, on CPU and GPU. Exacta provides reusable implementations of Dice, HD95, surface distances, lesion scores, probability metrics and training objectives, with explicit mathematical conventions. Version 0.1.1 fixes a rare one-ulp error of the exact distance transform on adversarial inputs. Version 0.1.0 made NSD count distances equal to the tolerance as its definition intends, added reporting signatures that encode a score's full definition, and let Dice and Tversky losses reproduce segmentation_models_pytorch's treatment of absent classes. Version 0.0.1a6 added classification and regression APIs, instance-map evaluation, Betti errors and pooled overlap.

CPU operations use C++ kernels where implemented; CUDA paths use Triton or native PyTorch. Definitions are checked against independent references such as SciPy, MONAI, MedPy, DeepMind's surface-distance, MeshMetrics, SimpleITK, Panoptica and the BraTS 2023 evaluation code. Where conventions differ, parameters select the intended definition.

Published version: 0.1.1. Documentation · Source · Issues

Installation

Exacta requires Python 3.10+, PyTorch 2.4+ and NumPy 1.22+. Install PyTorch for your CPU or CUDA environment, then install Exacta:

python -m pip install exacta==0.1.1

Binary wheels target Linux x86-64 with glibc 2.28 or newer: Python 3.10 and 3.11 wheels, plus a Python 3.12 stable-ABI wheel for Python 3.12 and newer. Other platforms install from source and require a C++17 compiler and Python development headers; OpenMP is optional. SciPy is an optional dependency for Hungarian lesion matching.

For distributed CPU evaluation with Gloo, use PyTorch 2.8+ to avoid an older process-group teardown deadlock. Multi-GPU NCCL support remains experimental.

Quickstart

Train with logits and evaluate hard labels. This synthetic 3D example runs on the available CPU or CUDA device; it demonstrates the API, not model accuracy:

import torch
import exacta.functional as EF
from exacta.losses import DiceCELoss

rng = torch.Generator().manual_seed(7)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
logits = torch.randn((2, 3, 16, 24, 24), generator=rng).to(device).requires_grad_()
target = torch.zeros((2, 16, 24, 24), dtype=torch.long, device=device)
target[:, 3:8, 4:12, 5:13] = 1
target[:, 9:13, 12:20, 12:20] = 2

loss = DiceCELoss(include_background=False)(logits, target)
loss.backward()

prediction = logits.detach().argmax(dim=1)
scores = EF.evaluate(
    prediction, target, num_classes=3, include_background=False,
    spacing=(1.5, 0.8, 0.8),  # spatial-axis order, in mm
    metrics={"dice": {}, "hd95": {}, "nsd": {"tolerance": 1.0}},
)
print("Loss:", loss.item())
print("Dice per case/class:", scores["dice"])  # shape (2, 2)
print("HD95 in mm:", scores["hd95"])

For 2D images, use logits (B,C,H,W), integer targets (B,H,W) and two-axis spacing. For independent overlapping labels, supported losses use activation="sigmoid" and target_format="one-hot" with same-shaped binary targets. The 2D medical-segmentation guide includes binary, multiclass and multilabel examples.

Metrics

Stateless functions live in exacta.functional. Their stateful counterparts in exacta.metrics accumulate across batches and support distributed evaluation.

Category Metrics
Overlap Dice / voxel F1; IoU / Jaccard
Classification rates Sensitivity / recall; precision; specificity
Relative size Volume similarity; signed or absolute relative volume difference
Physical size Predicted/target 3D volume and error in mm³ or mL; 2D area and error in mm² or cm²
Boundaries Hausdorff distance with configurable percentile; HD95; ASSD; normalized surface Dice (NSD)
Centreline Hard-skeleton clDice
Probability quality Brier score; negative log-likelihood (NLL)
Calibration Expected calibration error (ECE); reliability diagrams
Voxel ranking Average precision (AP); AUROC; precision–recall and ROC curves, exact or approximately binned
Lesion matching Lesion TP/FP/FN, precision, recall, F1, segmentation quality and panoptic quality
Lesion segmentation Lesion-wise Dice and HD95; BraTS 2023 evaluation conventions
Confidence-ranked detection Lesion AP and FROC curves

Use exacta.lesions.evaluate for lesion matching and exacta.detection.LesionDetection for confidence-ranked detection. Connected-component labeling, largest-component selection and small-component removal are available in exacta.components.

functional.evaluate and MetricCollection share confusion counts and compatible surface distances when evaluating multiple metrics. For accumulation across validation batches:

from exacta.metrics import MetricCollection

metrics = MetricCollection(
    metrics={"dice": {}, "hd95": {}}, num_classes=3, include_background=False,
)
metrics.update(prediction, target, spacing=(1.5, 0.8, 0.8))
result = metrics.compute()["dice"]
print(result.per_case, result.per_class, result.mean)
metrics.reset()

Functional APIs accept PyTorch, NumPy, CuPy and JAX arrays and return the prediction's array type. Stateful APIs use PyTorch. See Metrics and Lesion evaluation for arguments, formulas and matching protocols.

Training losses

Losses are PyTorch modules in exacta.losses. Choose the objective and target representation explicitly; different loss definitions produce different gradients.

Category Classes
Overlap DiceLoss, GeneralizedDiceLoss, TverskyLoss, FocalTverskyLoss
Class-confusion costs GeneralizedWassersteinDiceLoss
Voxel classification FocalLoss, TopKCELoss
Combined objectives DiceCELoss, DiceFocalLoss, GeneralizedDiceCELoss, DiceTopKCELoss
IoU surrogates LovaszSoftmaxLoss, LovaszHingeLoss
Boundary objectives BoundaryLoss, HausdorffDTLoss
Soft centreline objective SoftClDiceLoss

DeepSupervisionLoss combines a loss across explicitly paired prediction/target resolutions. zero_absent=True on Dice and Tversky losses gives zero loss to classes absent from the target, as segmentation_models_pytorch does; by default, as in MONAI, an empty target still penalizes predicted probability. DiceLoss(squared_pred=True) uses a squared denominator; Dice–CE, Dice–focal and Dice–top-k CE support the same option. Generalized Dice supports inverse-square, inverse-volume and uniform class weights. Standard cross-entropy and binary cross-entropy remain available in PyTorch.

Wasserstein Dice accepts integer labels and a symmetric, nonnegative class-cost matrix with zero diagonal and a positive maximum. The matrix is normalized by that maximum. Default weighting requires maximal background/foreground costs; weighting_mode="GDL" uses inverse observed class counts. These costs describe label confusion, not spatial distance.

HausdorffDTLoss is a distance-transform training surrogate, not HD95. Soft-clDice uses a finite-iteration soft skeleton and differs from the hard clDice evaluation metric. Geometry and topology objectives require complete target geometry; combine them with regional supervision where appropriate. See Losses for equations, smoothing, reductions, target formats and derivative support.

Instances, topology and pooled overlap

Version 0.0.1a6 added the following segmentation APIs.

API Purpose
aggregate="pooled" in Dice, IoU, FBeta, Sensitivity, Precision, Specificity and MetricCollection Dataset-pooled counts: global Dice, per-class IoU and mIoU (mmsegmentation convention)
functional.fbeta, metrics.FBeta F-beta per case and class; beta=1 is Dice
functional.confusion_counts Per-case TP/FP/FN/TN for custom definitions and pooling
exacta.instances Instance label maps with touching instances: PQ/SQ/F1, AJI, AJI+, Cell Tracking Challenge SEG, Data Science Bowl 2018 score; per-case or pooled accumulation
functional.betti_numbers, betti_error, metrics.BettiError Betti numbers (components, holes/tunnels, cavities) and Betti errors in 2D/3D
skeletonize(method=...), cldice(method=...) Zhang thinning in C++; 2D clDice now uses it by default, as the clDice authors do (method="lee" reproduces 0.0.1a5)
losses.SkeletonRecallLoss, skeleton_recall_target Skeleton Recall for thin tubular structures, with the authors' tubed skeleton targets
soft_label=True in Dice, Tversky, generalized Dice and their CE/focal combinations Dice semimetric statistics: minimal at the soft target, identical for hard labels
import torch
from exacta import instances
from exacta.metrics import IoU

pred_instances = torch.tensor([[[1, 1, 0, 2, 2], [1, 1, 0, 2, 2]]])
true_instances = torch.tensor([[[3, 3, 0, 4, 4], [3, 3, 0, 0, 4]]])
scores = instances.evaluate(pred_instances, true_instances)  # IoU > 0.5 matching
print(scores.pq, scores.aji, scores.seg)

miou = IoU(num_classes=3, aggregate="pooled")
miou.update(torch.tensor([[[0, 1], [2, 2]]]), torch.tensor([[[0, 1], [2, 1]]]))
print(miou.compute().per_class, miou.compute().mean)

Pooled scores weight every voxel equally and differ from case means. Instance matching above 0.5 IoU is unique; lower thresholds and AJI follow documented reference procedures. See Metrics, Instance evaluation, Losses and Advanced segmentation for definitions, empty-input behavior and references.

Classification and regression

These APIs evaluate samples across a dataset, with separate namespaces from the per-image segmentation metrics.

Namespace Metrics or losses
functional.classification Accuracy, top-k accuracy, confusion matrices, precision, recall, specificity, F1/F-beta, balanced accuracy, MCC, Cohen kappa, Brier, NLL, ECE, AP and AUROC
functional.regression MAE, MSE, RMSE, R², explained variance, Pearson and concordance correlation
metrics.classification ClassificationMetrics for pooled counts; ClassificationRanking for pooled AP/AUROC and PR/ROC curves
metrics.regression RegressionMetrics for pooled weighted errors and centered moments
losses.classification Native PyTorch CrossEntropyLoss, BCEWithLogitsLoss, BCELoss, NLLLoss, KLDivLoss
losses.regression QuantileLoss, LogCoshLoss; native PyTorch L1Loss, MSELoss, HuberLoss, SmoothL1Loss, GaussianNLLLoss, PoissonNLLLoss

Classification explicitly selects binary, multiclass or multilabel targets. Regression accepts (N,) or (N,D) arrays. Masks and sample weights are available for hard-decision classification and regression metrics; probability metrics currently accept masks but not sample weights. Stateful metrics pool sufficient statistics before computing scores. They do not average batch F1, R² or RMSE. CPU regression uses fused C++ statistics; CUDA regression uses native PyTorch. Standard losses are direct PyTorch exports.

import torch
from exacta.functional import classification as C, regression as R
from exacta.metrics.regression import RegressionMetrics

labels = torch.tensor([0, 1, 2, 1])
class_target = torch.tensor([0, 2, 2, 1])
print(C.evaluate(labels, class_target, task="multiclass", num_classes=3))

regression_pred = torch.tensor([1., 2., 4., 5.])
regression_target = torch.tensor([1., 3., 5., 4.])
print(R.evaluate(regression_pred, regression_target))
regression_metrics = RegressionMetrics(metrics=("mae", "rmse", "r2"))
regression_metrics.update(regression_pred[:2], regression_target[:2])
regression_metrics.update(regression_pred[2:], regression_target[2:])
print(regression_metrics.compute())

Undefined classification rates default to NaN; zero_division=0 or 1 is explicit. Regression R² preserves undefined constant-target cases unless force_finite=True. See classification and regression for formulas, averaging, empty-input behavior and examples.

Partial annotations and probability channels

Overlap, area and volume metrics accept shared boolean voxel masks and index-target ignore_index. Excluded voxels contribute to none of TP, FP, FN or TN:

partial_target = target.clone()
partial_target[:, :2] = -1
observed_dice = EF.dice(
    prediction, partial_target, num_classes=3, include_background=False, ignore_index=-1,
)

Surface and hard-clDice metrics require complete segmentations: removing voxels would change boundaries or topology. Loss masking follows each objective's documented rules.

Brier, NLL, ECE, reliability diagrams and voxel rankings support multilabel=True for independent probability channels with same-shaped binary targets. Logit inputs then use independent sigmoids. Shared or per-label masks and explicit macro/micro reductions are available where documented.

Reporting signatures

A metric's name does not fix its value. exacta.conventions.signature writes every convention behind a score, with defaults filled in, and the Exacta version, in one string to report next to the number; parse_signature reads it back into options that recompute the same score:

from exacta.conventions import parse_signature, signature

text = signature("hd95", combine="pooled")
# 'hd95[both_empty=nan;combine=pooled;one_empty=inf;surface=voxels]@exacta-0.1.1'
name, options, version = parse_signature(text)
again = EF.evaluate(prediction, target, metrics={name: options}, num_classes=3,
                    include_background=False, spacing=(1.5, 0.8, 0.8))

MetricCollection.signatures() returns the signatures of a collection, including whether scores are averaged over cases or pooled.

Mathematical conventions

Specify the definition as part of your evaluation protocol. Empty inputs, aggregation and surface representations can change reported values even for identical segmentations.

Choice Default and options
Hard labels Index maps with num_classes, or binary channels with input_format="one-hot"; overlapping channels are allowed.
Background Channel/class zero is included unless include_background=False.
Spacing Spatial-axis order of the array; physical area/volume inputs use millimetres.
Surfaces Boundary voxel centres by default; surface="surfels" uses physical length/area weights, and "mesh" uses contour/triangle geometry.
HD95 Maximum of the two directed 95th percentiles; combine="pooled" instead pools distances before the percentile.
ASSD Pooled surface-element mean; combine="mean" averages the two directed means.
Empty masks Dice/IoU return NaN when both are empty; distance metrics default to infinity when exactly one is empty, except NSD, which returns zero. Parameters make these policies explicit.
NSD ties A distance counts as within the tolerance when d <= tolerance * (1 + tie_rtol), default tie_rtol=1e-6, so distances equal to the tolerance in exact arithmetic count despite rounding; tie_rtol=0 compares strictly in float64, as SciPy-based tools do.
Case aggregation Stateful per-case metrics skip NaNs, average cases per class, then average class means.
Pooled evaluation Calibration pools voxel bins; VoxelRanking pools voxel rankings; overlap metrics with aggregate="pooled" pool confusion counts. Case averages and pooled scores are different quantities.
AP Non-interpolated sum of recall increments times precision, not trapezoidal PR area. No-positive AP and single-outcome AUROC are NaN.

For distributed evaluation, every rank must participate in compute(), including ranks with no local cases. Avoid samplers that duplicate cases through padding. See Conventions for full definitions, reference-library variants and empty-input behavior.

Performance

Backend choice depends on shape, class count, dtype and hardware. Supported metric passes use C++/OpenMP on CPU and Triton on CUDA. Training losses use native PyTorch and, for supported objectives, fused Triton forward/backward. torch.compile can improve native PyTorch paths; measure complete forward/backward cost and account for compilation startup.

Mesh distances and hard skeletonization run on CPU, including transfers for CUDA inputs. Lesion matching uses CPU lesion tables. The CPU extension is independent of the PyTorch binary version. See Performance for measured workloads, memory behavior and backend limitations.

License

Apache License 2.0; see the license, notices and third-party licenses.

Metadata

Release files for exacta 0.1.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for exacta 0.1.1
File Size Uploaded Provenance Actions
exacta-0.1.1.tar.gz 177.0 kB With provenance Details for exacta-0.1.1.tar.gz

Built distributions (wheels)

Table of built distributions (wheels) for exacta 0.1.1
File Interpreter ABI Platform Actions
exacta-0.1.1-cp312-abi3-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl CPython 3.12 abi3 Linux glibc 2.28+ x86-64, Linux glibc 2.27+ x86-64 Details for exacta-0.1.1-cp312-abi3-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl
exacta-0.1.1-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl CPython 3.11 CPython 3.11 Linux glibc 2.28+ x86-64, Linux glibc 2.27+ x86-64 Details for exacta-0.1.1-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl
exacta-0.1.1-cp310-cp310-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl CPython 3.10 CPython 3.10 Linux glibc 2.28+ x86-64, Linux glibc 2.27+ x86-64 Details for exacta-0.1.1-cp310-cp310-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl

Total release size: 1.5 MB

Release files / exacta-0.1.1.tar.gz

Download URL exacta-0.1.1.tar.gz
Size 177.0 kB
Tags Source
SHA-256 checksum
How to use checksums
400402376d666fa926950e3d6bd3a698decf268b37995d74556dbdd7d168585c
BLAKE2b-256 checksum
How to use checksums
14674708497868553dfa01a202448e227147cccb64ea71e73715ccf47a2e4a64
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 26, 2026.

Transparency log

Release files / exacta-0.1.1-cp312-abi3-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl

Download URL exacta-0.1.1-cp312-abi3-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl
Size 443.7 kB
Tags CPython 3.12 Linux glibc 2.27+ x86-64 Linux glibc 2.28+ x86-64 abi3
SHA-256 checksum
How to use checksums
80e71288271c5ada3c3002f42c2b0788dd3dcf721445c9f683c7602cd42525a8
BLAKE2b-256 checksum
How to use checksums
9639c88fa257934257af301a4593f37c6bd909ac8b0e2d593113822f833b053e
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 26, 2026.

Transparency log

Release files / exacta-0.1.1-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl

Download URL exacta-0.1.1-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl
Size 447.6 kB
Tags CPython 3.11 Linux glibc 2.27+ x86-64 Linux glibc 2.28+ x86-64
SHA-256 checksum
How to use checksums
a9adc9e12b81b716af19a3bfbc2635c4049e714353cfb8b3b3b9cd9d0caeb117
BLAKE2b-256 checksum
How to use checksums
04384398a0257ca2b577784e4e78f0bf294c24386dcca508f6d474f04832bd8b
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 26, 2026.

Transparency log

Release files / exacta-0.1.1-cp310-cp310-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl

Download URL exacta-0.1.1-cp310-cp310-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl
Size 447.9 kB
Tags CPython 3.10 Linux glibc 2.27+ x86-64 Linux glibc 2.28+ x86-64
SHA-256 checksum
How to use checksums
2c391f6ecbab960479ed050e95f1b118c19336716310bb84861b432bf84cffb8
BLAKE2b-256 checksum
How to use checksums
979a682c798354600dcf3315373a90e324e855ed67ed331cbfaefddedbd9e839
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 26, 2026.

Transparency log

Security for exacta 0.1.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

All 4 files in this release have been uploaded with provenance metadata.

Select from 4 files

Attestation for exacta-0.1.1.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 26, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page