From b48970c8ed321a022d8a77228b4034679df44885 Mon Sep 17 00:00:00 2001 From: Daniel Primosch Date: Fri, 23 Oct 2026 12:45:29 -0700 Subject: [PATCH] Add efficiency-at-fixed-purity validation metric and optional best-efficiency checkpoint New option checkpoint_eff_at_purity (purity target, 0 = off). When set, the validation epoch logs validation_eff_at_purity (overall, per topology and balanced) plus validation_purity / validation_efficiency at the detection cut, and train.py adds a ModelCheckpoint on validation_eff_at_purity next to the existing top-3 on validation_average_jet_accuracy. --- spanet/dataset/eff_at_purity.py | 107 ++++++++++++++++++ .../jet_reconstruction_validation.py | 57 ++++++++++ spanet/options.py | 5 + spanet/train.py | 9 ++ tests/test_eff_at_purity.py | 100 ++++++++++++++++ 5 files changed, 278 insertions(+) create mode 100644 spanet/dataset/eff_at_purity.py create mode 100644 tests/test_eff_at_purity.py diff --git a/spanet/dataset/eff_at_purity.py b/spanet/dataset/eff_at_purity.py new file mode 100644 index 0000000..f6329f0 --- /dev/null +++ b/spanet/dataset/eff_at_purity.py @@ -0,0 +1,107 @@ +"""Efficiency at a fixed purity: the validation metric behind the optional +best-efficiency checkpoint (Options.checkpoint_eff_at_purity). + +A candidate is a predicted particle whose detection score passes the SPANet +detection cut. Candidates are ranked by that score; the operating point is +the loosest cut whose purity (correct / selected) still reaches the target, +and the metric is the efficiency (correct / truth particles) at that cut. +NaN when no cut reaches the target. +""" +import re +from typing import List, Sequence, Tuple + +import numpy as np + +DETECTION_CUT = 0.5 + +_SLOT_SUFFIX = re.compile(r"t\d+$") + + +def topology_name(particle: str) -> str: + """FRt1 -> FR, SRqqt2 -> SRqq; names without a slot suffix are unchanged.""" + return _SLOT_SUFFIX.sub("", particle) or particle + + +def efficiency_at_purity(scores: np.ndarray, correct: np.ndarray, num_truth: int, purity: float) -> float: + if num_truth == 0 or len(scores) == 0: + return np.nan + + order = np.argsort(-scores, kind="stable") + found = np.cumsum(correct[order]) + selected = np.arange(1, len(order) + 1) + + reached = found / selected >= purity + if not reached.any(): + return np.nan + + return found[reached].max() / num_truth + + +def candidate_table( + jet_predictions: Sequence[np.ndarray], + particle_scores: np.ndarray, + stacked_targets: Sequence[np.ndarray], + stacked_masks: np.ndarray, + permutation_group: np.ndarray, + detection_cut: float = DETECTION_CUT, +) -> Tuple[np.ndarray, np.ndarray]: + """Per-target (correct, candidate) boolean tables of shape (num_targets, batch_size). + + As in compute_metrics, each event is scored under the event permutation that + maximises its number of correct targets. A target is correct when every + predicted daughter matches the permuted truth and that truth is present. + """ + num_targets, batch_size = stacked_masks.shape + correct = np.zeros((num_targets, batch_size), dtype=bool) + best_count = np.full(batch_size, -1) + + for permutation in permutation_group: + hit = np.stack([ + np.all(jet_predictions[i] == stacked_targets[p], axis=1) & stacked_masks[p] + for i, p in enumerate(permutation) + ]) + count = hit.sum(0) + better = count > best_count + correct[:, better] = hit[:, better] + best_count[better] = count[better] + + candidate = particle_scores >= detection_cut + return correct, candidate + + +def summarize( + scores: np.ndarray, + correct: np.ndarray, + slot: np.ndarray, + num_truth: np.ndarray, + slot_topologies: Sequence[str], + purity: float, +) -> dict: + """Metrics over one validation epoch's candidates. + + scores, correct, slot: one entry per candidate (slot = target index). + num_truth: truth particles per target slot. + """ + slot_topologies = np.asarray(slot_topologies) + metrics = { + "validation_purity": correct.mean() if len(correct) else np.nan, + "validation_efficiency": correct.sum() / num_truth.sum() if num_truth.sum() else np.nan, + "validation_eff_at_purity": efficiency_at_purity(scores, correct, num_truth.sum(), purity), + } + + per_topology = [] + for topology in dict.fromkeys(slot_topologies): + in_topology = slot_topologies[slot] == topology + value = efficiency_at_purity( + scores[in_topology], correct[in_topology], + num_truth[slot_topologies == topology].sum(), purity, + ) + metrics[f"validation_eff_at_purity/{topology}"] = value + per_topology.append(value) + + with np.errstate(all="ignore"): + metrics["validation_balanced_eff_at_purity"] = ( + np.nanmean(per_topology) if not np.all(np.isnan(per_topology)) else np.nan + ) + + return metrics diff --git a/spanet/network/jet_reconstruction/jet_reconstruction_validation.py b/spanet/network/jet_reconstruction/jet_reconstruction_validation.py index 0fe3a21..45e96ff 100644 --- a/spanet/network/jet_reconstruction/jet_reconstruction_validation.py +++ b/spanet/network/jet_reconstruction/jet_reconstruction_validation.py @@ -9,6 +9,7 @@ from sklearn import metrics as sk_metrics from spanet.options import Options from spanet.dataset.evaluator import SymmetricEvaluator +from spanet.dataset.eff_at_purity import candidate_table, summarize, topology_name from spanet.network.jet_reconstruction.jet_reconstruction_network import JetReconstructionNetwork @@ -21,6 +22,59 @@ class JetReconstructionValidation(JetReconstructionNetwork): self.particle_weights_tensor_np = self.particle_weights_tensor.cpu().detach().numpy() # self.validation_step_metrics_outputs = [] + self.eff_at_purity_target = options.checkpoint_eff_at_purity + if self.eff_at_purity_target > 0: + self.slot_topologies = [topology_name(name) for name in self.event_info.event_particles.names] + self.reset_eff_at_purity_buffers() + + def reset_eff_at_purity_buffers(self): + self.eff_scores, self.eff_correct, self.eff_slot = [], [], [] + self.eff_num_truth = np.zeros(len(self.slot_topologies), dtype=np.int64) + + def accumulate_eff_at_purity(self, jet_predictions, particle_scores, stacked_targets, stacked_masks): + correct, candidate = candidate_table( + jet_predictions, particle_scores, stacked_targets, stacked_masks, + self.event_permutation_tensor.cpu().numpy(), + ) + slot = np.broadcast_to(np.arange(candidate.shape[0])[:, np.newaxis], candidate.shape) + + self.eff_scores.append(particle_scores[candidate]) + self.eff_correct.append(correct[candidate]) + self.eff_slot.append(slot[candidate]) + self.eff_num_truth += stacked_masks.sum(1) + + def log_eff_at_purity(self): + if self.eff_at_purity_target <= 0: + return + + scores = np.concatenate(self.eff_scores) if self.eff_scores else np.zeros(0) + correct = np.concatenate(self.eff_correct) if self.eff_correct else np.zeros(0, dtype=bool) + slot = np.concatenate(self.eff_slot) if self.eff_slot else np.zeros(0, dtype=np.int64) + num_truth = self.eff_num_truth + self.reset_eff_at_purity_buffers() + + if self.trainer.world_size > 1: + parts = [None] * self.trainer.world_size + torch.distributed.all_gather_object(parts, (scores, correct, slot, num_truth)) + scores = np.concatenate([part[0] for part in parts]) + correct = np.concatenate([part[1] for part in parts]) + slot = np.concatenate([part[2] for part in parts]) + num_truth = sum(part[3] for part in parts) + + metrics = summarize(scores, correct, slot, num_truth, self.slot_topologies, self.eff_at_purity_target) + + # The monitored key is logged even when NaN: ModelCheckpoint needs it + # every epoch and treats NaN as the worst value. + for name, value in metrics.items(): + if name == "validation_eff_at_purity" or not np.isnan(value): + self.log(name, float(value), sync_dist=True) + + def on_validation_epoch_end(self): + self.log_eff_at_purity() + + def on_test_epoch_end(self): + self.log_eff_at_purity() + @property def particle_metrics(self) -> Dict[str, Callable[[np.ndarray, np.ndarray], float]]: return { @@ -157,6 +211,9 @@ class JetReconstructionValidation(JetReconstructionNetwork): metrics.update(self.compute_metrics(jet_predictions, particle_scores, stacked_targets, stacked_masks, stacked_weights)) + if self.eff_at_purity_target > 0: + self.accumulate_eff_at_purity(jet_predictions, particle_scores, stacked_targets, stacked_masks) + for key in regressions: delta = regressions[key] - regression_targets[key] diff --git a/spanet/options.py b/spanet/options.py index cf3f697..2337cd0 100644 --- a/spanet/options.py +++ b/spanet/options.py @@ -251,6 +251,11 @@ class Options(Namespace): # 1.0 = full validation, 0.2 = 20% of validation batches. Default 1.0. self.limit_val_batches: float = 1.0 + # Purity target for the efficiency-at-fixed-purity validation metric + # (validation_eff_at_purity). 0 disables the metric and the extra + # best-efficiency checkpoint it drives. + self.checkpoint_eff_at_purity: float = 0.0 + # Training batch size. self.batch_size: int = 4096 diff --git a/spanet/train.py b/spanet/train.py index a746d8e..c920407 100644 --- a/spanet/train.py +++ b/spanet/train.py @@ -155,6 +155,15 @@ def main( RichModelSummary(max_depth=1) if _RICH_AVAILABLE else ModelSummary(max_depth=1) ] + if options.checkpoint_eff_at_purity > 0: + callbacks.append(ModelCheckpoint( + verbose=options.verbose_output, + filename='{epoch}-{step}-{validation_eff_at_purity:.3f}', + monitor='validation_eff_at_purity', + save_top_k=1, + mode='max' + )) + epochs = options.epochs profiler = None if profile: diff --git a/tests/test_eff_at_purity.py b/tests/test_eff_at_purity.py new file mode 100644 index 0000000..a6f1f10 --- /dev/null +++ b/tests/test_eff_at_purity.py @@ -0,0 +1,100 @@ +"""Efficiency-at-fixed-purity metric (spanet/dataset/eff_at_purity.py).""" +import numpy as np +import pytest + +from spanet.dataset.eff_at_purity import candidate_table, efficiency_at_purity, summarize, topology_name + + +def test_topology_name_strips_slot_suffix(): + assert topology_name("FRt1") == "FR" + assert topology_name("SRqqt2") == "SRqq" + assert topology_name("FBt1") == "FB" + assert topology_name("bh1") == "bh1" + assert topology_name("t1") == "t1" + + +def test_overall_purity_above_target_gives_plain_efficiency(): + scores = np.array([0.9, 0.8, 0.7, 0.6]) + correct = np.array([True, True, False, False]) + assert efficiency_at_purity(scores, correct, num_truth=4, purity=0.5) == pytest.approx(0.5) + + +def test_tightening_the_cut_recovers_the_purity_target(): + scores = np.array([0.9, 0.8, 0.7, 0.6]) + correct = np.array([True, False, False, False]) + # cuts keeping 1..4 candidates have purity 1, .5, .33, .25: deepest at .5 keeps 2 + assert efficiency_at_purity(scores, correct, num_truth=4, purity=0.5) == pytest.approx(0.25) + assert efficiency_at_purity(scores, correct, num_truth=4, purity=0.6) == pytest.approx(0.25) + + +def test_ranking_is_by_score_not_input_order(): + scores = np.array([0.6, 0.9]) + correct = np.array([False, True]) + assert efficiency_at_purity(scores, correct, num_truth=2, purity=1.0) == pytest.approx(0.5) + + +def test_unreachable_purity_and_empty_inputs_are_nan(): + scores = np.array([0.9, 0.8]) + assert np.isnan(efficiency_at_purity(scores, np.array([False, False]), num_truth=2, purity=0.5)) + assert np.isnan(efficiency_at_purity(np.zeros(0), np.zeros(0, dtype=bool), num_truth=2, purity=0.5)) + assert np.isnan(efficiency_at_purity(scores, np.array([True, True]), num_truth=0, purity=0.5)) + + +def _two_slot_batch(): + """Two FR slots, event permutation group {identity, swap}, two events. + + Event 0: truth only in slot 0, prediction slot 0 matches it. + Event 1: truth only in slot 1, prediction slot 0 matches it (needs the swap). + """ + jet_predictions = [ + np.array([[0, 1, 2], [3, 4, 5]]), + np.array([[3, 4, 5], [0, 1, 2]]), + ] + stacked_targets = np.empty(2, dtype=object) + stacked_targets[0] = np.array([[0, 1, 2], [-1, -1, -1]]) + stacked_targets[1] = np.array([[-1, -1, -1], [3, 4, 5]]) + stacked_masks = np.array([[True, False], [False, True]]) + permutation_group = np.array([[0, 1], [1, 0]]) + return jet_predictions, stacked_targets, stacked_masks, permutation_group + + +def test_candidate_table_picks_the_best_event_permutation(): + jet_predictions, stacked_targets, stacked_masks, permutation_group = _two_slot_batch() + particle_scores = np.array([[0.9, 0.7], [0.4, 0.8]]) + + correct, candidate = candidate_table( + jet_predictions, particle_scores, stacked_targets, stacked_masks, permutation_group + ) + + assert correct.tolist() == [[True, True], [False, False]] + assert candidate.tolist() == [[True, True], [False, True]] + + +def test_summarize_reports_overall_per_topology_and_balanced(): + scores = np.array([0.9, 0.8, 0.7, 0.6]) + correct = np.array([True, False, True, False]) + slot = np.array([0, 0, 2, 3]) + num_truth = np.array([2, 0, 1, 1]) + topologies = ["FR", "FR", "SRqq", "SRqq"] + + metrics = summarize(scores, correct, slot, num_truth, topologies, purity=0.5) + + assert metrics["validation_purity"] == pytest.approx(0.5) + assert metrics["validation_efficiency"] == pytest.approx(0.5) + assert metrics["validation_eff_at_purity"] == pytest.approx(0.5) + assert metrics["validation_eff_at_purity/FR"] == pytest.approx(0.5) + assert metrics["validation_eff_at_purity/SRqq"] == pytest.approx(0.5) + assert metrics["validation_balanced_eff_at_purity"] == pytest.approx(0.5) + + +def test_summarize_balanced_ignores_unreachable_topologies(): + scores = np.array([0.9, 0.8]) + correct = np.array([True, False]) + slot = np.array([0, 1]) + num_truth = np.array([1, 1]) + + metrics = summarize(scores, correct, slot, num_truth, ["FR", "FB"], purity=0.5) + + assert metrics["validation_eff_at_purity/FR"] == pytest.approx(1.0) + assert np.isnan(metrics["validation_eff_at_purity/FB"]) + assert metrics["validation_balanced_eff_at_purity"] == pytest.approx(1.0) -- 2.43.7