pyhighlights 0.7.0__tar.gz → 0.7.2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (99) hide show
  1. {pyhighlights-0.7.0 → pyhighlights-0.7.2}/PKG-INFO +1 -1
  2. pyhighlights-0.7.2/pyhighlights/__init__.py +1 -0
  3. {pyhighlights-0.7.0 → pyhighlights-0.7.2}/pyhighlights/components/analyzers.py +44 -4
  4. pyhighlights-0.7.2/pyhighlights/components/callbacks.py +185 -0
  5. {pyhighlights-0.7.0 → pyhighlights-0.7.2}/pyhighlights/components/models/spp/base.py +10 -0
  6. {pyhighlights-0.7.0 → pyhighlights-0.7.2}/pyhighlights/components/models/spp/grat.py +12 -0
  7. {pyhighlights-0.7.0 → pyhighlights-0.7.2}/pyhighlights/components/tasks.py +72 -16
  8. {pyhighlights-0.7.0 → pyhighlights-0.7.2}/pyhighlights/configurations/base.py +41 -6
  9. {pyhighlights-0.7.0 → pyhighlights-0.7.2}/pyhighlights/configurations/benchmarks.py +5 -0
  10. pyhighlights-0.7.2/pyhighlights/configurations/callbacks.py +104 -0
  11. {pyhighlights-0.7.0 → pyhighlights-0.7.2}/pyhighlights/configurations/grat.py +4 -17
  12. {pyhighlights-0.7.0 → pyhighlights-0.7.2}/pyhighlights/configurations/keys.py +9 -0
  13. pyhighlights-0.7.2/pyhighlights/configurations/mcd.py +47 -0
  14. {pyhighlights-0.7.0 → pyhighlights-0.7.2}/pyhighlights/configurations/metrics.py +11 -3
  15. {pyhighlights-0.7.0 → pyhighlights-0.7.2}/pyhighlights/configurations/mgr.py +8 -30
  16. {pyhighlights-0.7.0 → pyhighlights-0.7.2}/pyhighlights/configurations/mrd.py +5 -25
  17. {pyhighlights-0.7.0 → pyhighlights-0.7.2}/pyhighlights/configurations/tasks.py +15 -2
  18. {pyhighlights-0.7.0 → pyhighlights-0.7.2}/pyhighlights/utility/manifest.py +29 -1
  19. {pyhighlights-0.7.0 → pyhighlights-0.7.2}/pyhighlights/utility/metrics.py +15 -4
  20. {pyhighlights-0.7.0 → pyhighlights-0.7.2}/pyhighlights.egg-info/PKG-INFO +1 -1
  21. {pyhighlights-0.7.0 → pyhighlights-0.7.2}/pyhighlights.egg-info/SOURCES.txt +3 -0
  22. {pyhighlights-0.7.0 → pyhighlights-0.7.2}/pyhighlights_benchmarks/genspp2025/configurations/common.py +42 -4
  23. {pyhighlights-0.7.0 → pyhighlights-0.7.2}/pyhighlights_benchmarks/genspp2025/configurations/keys.py +5 -0
  24. {pyhighlights-0.7.0 → pyhighlights-0.7.2}/tests/test_benchmarks.py +54 -6
  25. pyhighlights-0.7.2/tests/test_callbacks.py +255 -0
  26. {pyhighlights-0.7.0 → pyhighlights-0.7.2}/tests/test_configurations.py +46 -0
  27. {pyhighlights-0.7.0 → pyhighlights-0.7.2}/tests/test_genspp2025.py +8 -1
  28. {pyhighlights-0.7.0 → pyhighlights-0.7.2}/tests/test_manifest.py +45 -6
  29. {pyhighlights-0.7.0 → pyhighlights-0.7.2}/tests/test_metrics.py +33 -1
  30. {pyhighlights-0.7.0 → pyhighlights-0.7.2}/tests/test_optimizers.py +8 -5
  31. {pyhighlights-0.7.0 → pyhighlights-0.7.2}/tests/test_tasks.py +44 -2
  32. pyhighlights-0.7.0/pyhighlights/__init__.py +0 -1
  33. pyhighlights-0.7.0/pyhighlights/configurations/mcd.py +0 -74
  34. {pyhighlights-0.7.0 → pyhighlights-0.7.2}/LICENSE +0 -0
  35. {pyhighlights-0.7.0 → pyhighlights-0.7.2}/README.md +0 -0
  36. {pyhighlights-0.7.0 → pyhighlights-0.7.2}/pyhighlights/components/__init__.py +0 -0
  37. {pyhighlights-0.7.0 → pyhighlights-0.7.2}/pyhighlights/components/benchmarks.py +0 -0
  38. {pyhighlights-0.7.0 → pyhighlights-0.7.2}/pyhighlights/components/data.py +0 -0
  39. {pyhighlights-0.7.0 → pyhighlights-0.7.2}/pyhighlights/components/faithfulness.py +0 -0
  40. {pyhighlights-0.7.0 → pyhighlights-0.7.2}/pyhighlights/components/leakage.py +0 -0
  41. {pyhighlights-0.7.0 → pyhighlights-0.7.2}/pyhighlights/components/loaders.py +0 -0
  42. {pyhighlights-0.7.0 → pyhighlights-0.7.2}/pyhighlights/components/models/__init__.py +0 -0
  43. {pyhighlights-0.7.0 → pyhighlights-0.7.2}/pyhighlights/components/models/base.py +0 -0
  44. {pyhighlights-0.7.0 → pyhighlights-0.7.2}/pyhighlights/components/models/data.py +0 -0
  45. {pyhighlights-0.7.0 → pyhighlights-0.7.2}/pyhighlights/components/models/spp/__init__.py +0 -0
  46. {pyhighlights-0.7.0 → pyhighlights-0.7.2}/pyhighlights/components/models/spp/dar.py +0 -0
  47. {pyhighlights-0.7.0 → pyhighlights-0.7.2}/pyhighlights/components/models/spp/data.py +0 -0
  48. {pyhighlights-0.7.0 → pyhighlights-0.7.2}/pyhighlights/components/models/spp/dr.py +0 -0
  49. {pyhighlights-0.7.0 → pyhighlights-0.7.2}/pyhighlights/components/models/spp/fr.py +0 -0
  50. {pyhighlights-0.7.0 → pyhighlights-0.7.2}/pyhighlights/components/models/spp/genspp.py +0 -0
  51. {pyhighlights-0.7.0 → pyhighlights-0.7.2}/pyhighlights/components/models/spp/implementations.py +0 -0
  52. {pyhighlights-0.7.0 → pyhighlights-0.7.2}/pyhighlights/components/models/spp/mcd.py +0 -0
  53. {pyhighlights-0.7.0 → pyhighlights-0.7.2}/pyhighlights/components/models/spp/mgr.py +0 -0
  54. {pyhighlights-0.7.0 → pyhighlights-0.7.2}/pyhighlights/components/models/spp/mrd.py +0 -0
  55. {pyhighlights-0.7.0 → pyhighlights-0.7.2}/pyhighlights/components/preprocessors.py +0 -0
  56. {pyhighlights-0.7.0 → pyhighlights-0.7.2}/pyhighlights/configurations/__init__.py +0 -0
  57. {pyhighlights-0.7.0 → pyhighlights-0.7.2}/pyhighlights/configurations/backbones.py +0 -0
  58. {pyhighlights-0.7.0 → pyhighlights-0.7.2}/pyhighlights/configurations/dar.py +0 -0
  59. {pyhighlights-0.7.0 → pyhighlights-0.7.2}/pyhighlights/configurations/datasets.py +0 -0
  60. {pyhighlights-0.7.0 → pyhighlights-0.7.2}/pyhighlights/configurations/dr.py +0 -0
  61. {pyhighlights-0.7.0 → pyhighlights-0.7.2}/pyhighlights/configurations/fr.py +0 -0
  62. {pyhighlights-0.7.0 → pyhighlights-0.7.2}/pyhighlights/configurations/genspp.py +0 -0
  63. {pyhighlights-0.7.0 → pyhighlights-0.7.2}/pyhighlights/configurations/losses.py +0 -0
  64. {pyhighlights-0.7.0 → pyhighlights-0.7.2}/pyhighlights/configurations/optimizers.py +0 -0
  65. {pyhighlights-0.7.0 → pyhighlights-0.7.2}/pyhighlights/configurations/preprocessors.py +0 -0
  66. {pyhighlights-0.7.0 → pyhighlights-0.7.2}/pyhighlights/utility/__init__.py +0 -0
  67. {pyhighlights-0.7.0 → pyhighlights-0.7.2}/pyhighlights/utility/embeddings.py +0 -0
  68. {pyhighlights-0.7.0 → pyhighlights-0.7.2}/pyhighlights/utility/io.py +0 -0
  69. {pyhighlights-0.7.0 → pyhighlights-0.7.2}/pyhighlights/utility/losses.py +0 -0
  70. {pyhighlights-0.7.0 → pyhighlights-0.7.2}/pyhighlights/utility/statistics.py +0 -0
  71. {pyhighlights-0.7.0 → pyhighlights-0.7.2}/pyhighlights.egg-info/dependency_links.txt +0 -0
  72. {pyhighlights-0.7.0 → pyhighlights-0.7.2}/pyhighlights.egg-info/requires.txt +0 -0
  73. {pyhighlights-0.7.0 → pyhighlights-0.7.2}/pyhighlights.egg-info/top_level.txt +0 -0
  74. {pyhighlights-0.7.0 → pyhighlights-0.7.2}/pyhighlights_benchmarks/__init__.py +0 -0
  75. {pyhighlights-0.7.0 → pyhighlights-0.7.2}/pyhighlights_benchmarks/genspp2025/__init__.py +0 -0
  76. {pyhighlights-0.7.0 → pyhighlights-0.7.2}/pyhighlights_benchmarks/genspp2025/configurations/__init__.py +0 -0
  77. {pyhighlights-0.7.0 → pyhighlights-0.7.2}/pyhighlights_benchmarks/genspp2025/configurations/hatexplain.py +0 -0
  78. {pyhighlights-0.7.0 → pyhighlights-0.7.2}/pyhighlights_benchmarks/genspp2025/configurations/toy.py +0 -0
  79. {pyhighlights-0.7.0 → pyhighlights-0.7.2}/pyhighlights_benchmarks/genspp2025/corpora.py +0 -0
  80. {pyhighlights-0.7.0 → pyhighlights-0.7.2}/pyproject.toml +0 -0
  81. {pyhighlights-0.7.0 → pyhighlights-0.7.2}/setup.cfg +0 -0
  82. {pyhighlights-0.7.0 → pyhighlights-0.7.2}/tests/test_dar.py +0 -0
  83. {pyhighlights-0.7.0 → pyhighlights-0.7.2}/tests/test_data.py +0 -0
  84. {pyhighlights-0.7.0 → pyhighlights-0.7.2}/tests/test_documentation.py +0 -0
  85. {pyhighlights-0.7.0 → pyhighlights-0.7.2}/tests/test_dr.py +0 -0
  86. {pyhighlights-0.7.0 → pyhighlights-0.7.2}/tests/test_embeddings.py +0 -0
  87. {pyhighlights-0.7.0 → pyhighlights-0.7.2}/tests/test_faithfulness.py +0 -0
  88. {pyhighlights-0.7.0 → pyhighlights-0.7.2}/tests/test_fr.py +0 -0
  89. {pyhighlights-0.7.0 → pyhighlights-0.7.2}/tests/test_genspp.py +0 -0
  90. {pyhighlights-0.7.0 → pyhighlights-0.7.2}/tests/test_grat.py +0 -0
  91. {pyhighlights-0.7.0 → pyhighlights-0.7.2}/tests/test_imports.py +0 -0
  92. {pyhighlights-0.7.0 → pyhighlights-0.7.2}/tests/test_io.py +0 -0
  93. {pyhighlights-0.7.0 → pyhighlights-0.7.2}/tests/test_leakage.py +0 -0
  94. {pyhighlights-0.7.0 → pyhighlights-0.7.2}/tests/test_loaders.py +0 -0
  95. {pyhighlights-0.7.0 → pyhighlights-0.7.2}/tests/test_losses.py +0 -0
  96. {pyhighlights-0.7.0 → pyhighlights-0.7.2}/tests/test_mrd.py +0 -0
  97. {pyhighlights-0.7.0 → pyhighlights-0.7.2}/tests/test_preprocessors.py +0 -0
  98. {pyhighlights-0.7.0 → pyhighlights-0.7.2}/tests/test_statistics.py +0 -0
  99. {pyhighlights-0.7.0 → pyhighlights-0.7.2}/tests/test_transformer_configurations.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pyhighlights
3
- Version: 0.7.0
3
+ Version: 0.7.2
4
4
  Summary: A simple library implementing Select-Then-Predict (SPP) models.
5
5
  Author-email: Federico Ruggeri <federico.ruggeri6@unibo.it>
6
6
  License-Expression: MIT
@@ -0,0 +1 @@
1
+ __version__ = "0.7.2"
@@ -25,6 +25,7 @@ from cinnamon.registry import RegistrationKey, Registry
25
25
 
26
26
  from pyhighlights.components.loaders import HighlightLoader
27
27
  from pyhighlights.components.preprocessors import Preprocessor
28
+ from pyhighlights.utility.manifest import registration_key
28
29
 
29
30
  #: The predictions one seed left behind. A glob rather than a name: a run
30
31
  #: stores one file per seed, and every analyzer here reads all of them.
@@ -306,22 +307,57 @@ class PredictionAnalyzer(Analyzer):
306
307
  directory: str | Path | None = None,
307
308
  pattern: str = PREDICTIONS,
308
309
  split: str = "test",
310
+ latest: bool = True,
309
311
  ):
310
312
  super().__init__(directory)
311
313
  self.pattern = pattern
312
314
  self.split = split
315
+ self.latest = latest
316
+
317
+ def runs(self) -> List[Path]:
318
+ """The run directories to read, newest per task when ``latest``.
319
+
320
+ A task keeps every run it has ever done, one timestamped directory
321
+ each, so without this a re-run or a requeued job reads as extra
322
+ samples: duplicate rows here, and duplicate files out of
323
+ :class:`LabelStudioExporter`, which a reviewer would then annotate
324
+ twice.
325
+
326
+ Grouped by the name the run's manifest reports rather than by its
327
+ directory, for the reason :meth:`MetricsAnalyzer.reports` groups that
328
+ way: the stamp is a path component, and a task that has been renamed or
329
+ moved is still the task its own record says it is.
330
+ """
331
+ candidates = sorted(
332
+ {path.parent for path in self.directory.rglob(self.pattern)}
333
+ )
334
+ if not self.latest:
335
+ return candidates
336
+ found: Dict[str, Path] = {}
337
+ for run in candidates:
338
+ manifest = run / "manifest.json"
339
+ name = run.parent.name
340
+ if manifest.exists():
341
+ settings = json.loads(manifest.read_text()).get("settings", {})
342
+ name = settings.get("name", name)
343
+ # `candidates` is sorted and a stamp sorts chronologically, so the
344
+ # last one written wins.
345
+ found[name] = run
346
+ return sorted(found.values())
313
347
 
314
348
  def corpus(self, run: Path) -> Dict[int, pd.Series]:
315
349
  """The split these predictions were made on, keyed by sample id."""
316
350
  settings = json.loads((run / "manifest.json").read_text())["settings"]
317
351
  splits = Registry.from_key(
318
- RegistrationKey.parse(registration_key=settings["loader"]["key"]),
352
+ RegistrationKey.parse(
353
+ registration_key=registration_key(settings["loader"])
354
+ ),
319
355
  expected_type=HighlightLoader,
320
356
  ).load()
321
357
  preprocessor = settings.get("preprocessor")
322
358
  if preprocessor is not None:
323
359
  splits = Registry.from_key(
324
- RegistrationKey.parse(registration_key=preprocessor["key"]),
360
+ RegistrationKey.parse(registration_key=registration_key(preprocessor)),
325
361
  expected_type=Preprocessor,
326
362
  ).process(splits)
327
363
  frame = splits[self.split]
@@ -339,7 +375,8 @@ class PredictionAnalyzer(Analyzer):
339
375
  # trained on the same split, and loading it again per file is the whole
340
376
  # cost of the analysis repeated.
341
377
  corpora: Dict[Path, Dict[int, Any]] = {}
342
- for path in sorted(self.directory.rglob(self.pattern)):
378
+ files = [path for run in self.runs() for path in sorted(run.glob(self.pattern))]
379
+ for path in files:
343
380
  rows: List[Dict[str, Any]] = []
344
381
  run = path.parent
345
382
  if run not in corpora:
@@ -508,13 +545,16 @@ class LabelStudioExporter(PredictionAnalyzer):
508
545
  directory: str | Path | None = None,
509
546
  pattern: str = PREDICTIONS,
510
547
  split: str = "test",
548
+ latest: bool = True,
511
549
  model_version: str = "pyhighlights",
512
550
  labels: Sequence[str] = ("highlight",),
513
551
  only: int | None = None,
514
552
  column: str = "label",
515
553
  stem: str = "label-studio",
516
554
  ):
517
- super().__init__(directory=directory, pattern=pattern, split=split)
555
+ super().__init__(
556
+ directory=directory, pattern=pattern, split=split, latest=latest
557
+ )
518
558
  self.model_version = model_version
519
559
  self.labels = list(labels)
520
560
  self.only = only
@@ -0,0 +1,185 @@
1
+ """Callbacks a run is monitored by, and the criterion that selects its epoch.
2
+
3
+ Early stopping and checkpointing used to be built inside
4
+ :class:`~pyhighlights.components.tasks.SPPTask` from one ``monitor`` string and
5
+ one ``patience``, with ``mode="min"`` written into both. That is three
6
+ decisions a study cannot make: it cannot maximise a metric, cannot monitor
7
+ anything but a single logged quantity, and cannot say that a model spends its
8
+ first epochs pretraining something the monitor knows nothing about. They are
9
+ registered components here, so a study configures them the way it configures
10
+ its losses and its metrics.
11
+
12
+ **One quantity decides both.** The callback that stops a run and the callback
13
+ that keeps an epoch have to agree, or a run reports a model its own stopping
14
+ rule did not choose: stop when two quantities are exhausted and the restored
15
+ epoch is whichever one the checkpoint happened to monitor.
16
+ :class:`GeneralizationLossScore` exists so that a study combining two
17
+ quantities still monitors one.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ from typing import Any, Mapping
23
+
24
+ import lightning as L
25
+ import torch as th
26
+ from lightning.pytorch.callbacks import Callback, EarlyStopping, ModelCheckpoint
27
+
28
+ __all__ = [
29
+ "GeneralizationLossScore",
30
+ "MonitoredScore",
31
+ "WarmupEarlyStopping",
32
+ "WarmupModelCheckpoint",
33
+ "warmup_epochs",
34
+ ]
35
+
36
+
37
+ def warmup_epochs(module: L.LightningModule) -> int:
38
+ """Training epochs before the monitored model starts learning.
39
+
40
+ A model that pretrains a component over the first epochs of the training
41
+ loop is not improving the thing a monitor watches, so a patience counted
42
+ from epoch zero can exhaust before the model has taken a single step.
43
+ G-RAT is that case -- it gates its optimizer on
44
+ ``current_epoch >= pretrain_epochs`` -- and two of five seeds of the legal
45
+ study's frozen arm stopped inside that window.
46
+
47
+ The number comes from the model rather than from the task's configuration,
48
+ because a task repeating it is a second place for it to be wrong. A model
49
+ that pretrains outside the training loop, as DAR does in
50
+ ``on_train_start``, costs no epochs and needs nothing here.
51
+ """
52
+ return int(getattr(module, "warmup_epochs", 0) or 0)
53
+
54
+
55
+ class MonitoredScore(Callback):
56
+ """A callback that writes the quantity a run is monitored by.
57
+
58
+ Marked as a class rather than recognised by name, so that
59
+ :meth:`~pyhighlights.components.tasks.SPPTask.build_callbacks` can order
60
+ every criterion before the callbacks that read one.
61
+ """
62
+
63
+
64
+ class GeneralizationLossScore(MonitoredScore):
65
+ """One monitored quantity out of a metric and a one-sided loss penalty.
66
+
67
+ Maximises ``quality`` while charging for validation loss that has risen
68
+ above its own best:
69
+
70
+ .. math::
71
+
72
+ score = quality - \\lambda \\cdot \\max(0, loss / loss_{opt} - 1)
73
+
74
+ The penalty is Prechelt's **generalization loss** (Prechelt, 1998, *Early
75
+ Stopping -- But When?*), with ``loss_opt`` the lowest validation loss seen
76
+ so far. A *ratio* rather than a difference, and that matters: a weighted
77
+ cross entropy at a class weight of 105 is unbounded while an F1 is not, so
78
+ a difference would make ``coefficient`` a guess about scale. A relative
79
+ regression is dimensionless, and the coefficient means one thing -- how
80
+ much ``quality`` an epoch forfeits per unit of relative loss regression.
81
+
82
+ Measured over the legal study's frozen arm, monitoring the rare class's F1
83
+ alone accepted a 26 to 31% relative loss regression, and monitoring the
84
+ loss alone gave up three to four points of that F1 at a regression under
85
+ 1%. The coefficient is what chooses between those, and it belongs to an
86
+ architecture rather than to the library: a coefficient of 0 monitors
87
+ ``quality`` alone and a large one monitors the loss alone, so both of the
88
+ criteria it replaces are special cases of it.
89
+ """
90
+
91
+ def __init__(
92
+ self,
93
+ quality: str = "val_f1",
94
+ loss: str = "val_loss",
95
+ coefficient: float = 2.0,
96
+ name: str = "val_score",
97
+ ):
98
+ super().__init__()
99
+ if coefficient < 0:
100
+ raise ValueError("coefficient must be non-negative")
101
+ self.quality = quality
102
+ self.loss = loss
103
+ self.coefficient = coefficient
104
+ self.name = name
105
+ self.best_loss: float | None = None
106
+
107
+ def state_dict(self) -> Mapping[str, Any]:
108
+ # `loss_opt` is the whole memory of the criterion: a resumed run that
109
+ # forgot it would charge nothing for a regression it had already seen.
110
+ return {"best_loss": self.best_loss}
111
+
112
+ def load_state_dict(self, state_dict: Mapping[str, Any]) -> None:
113
+ self.best_loss = state_dict.get("best_loss")
114
+
115
+ def on_validation_end(
116
+ self, trainer: L.Trainer, pl_module: L.LightningModule
117
+ ) -> None:
118
+ """Logged here, not in ``on_validation_epoch_end``.
119
+
120
+ Lightning runs a callback's ``on_validation_epoch_end`` *before* the
121
+ module's, so the metrics this reads are not logged yet at that point
122
+ and the criterion would silently write nothing -- leaving early
123
+ stopping to fail on a quantity that never appeared. ``on_validation_end``
124
+ runs after the module has logged, and before ``EarlyStopping``'s own
125
+ check on the same hook, provided this callback comes first in the
126
+ list. :meth:`~pyhighlights.components.tasks.SPPTask.build_callbacks`
127
+ puts it there rather than trusting the order it was given.
128
+ """
129
+ logged = trainer.callback_metrics
130
+ if self.quality not in logged or self.loss not in logged:
131
+ # Sanity checking runs a validation epoch before training, and a
132
+ # split that logs neither is not this criterion's business.
133
+ return
134
+ quality = float(logged[self.quality])
135
+ loss = float(logged[self.loss])
136
+
137
+ if trainer.sanity_checking:
138
+ return
139
+ if trainer.current_epoch < warmup_epochs(pl_module):
140
+ # A pretraining epoch's loss is a different model's loss, so it
141
+ # cannot set the floor the rest of the run is charged against.
142
+ return
143
+
144
+ if self.best_loss is None or loss < self.best_loss:
145
+ self.best_loss = loss
146
+ regression = max(0.0, loss / max(self.best_loss, 1e-12) - 1.0)
147
+ score = quality - self.coefficient * regression
148
+
149
+ # `self.log` is refused on this hook, so the value is put where the
150
+ # callbacks that read it look -- `trainer.callback_metrics` is what
151
+ # both `EarlyStopping` and `ModelCheckpoint` consult -- and handed to
152
+ # the logger separately so that it also lands in `metrics.csv` and a
153
+ # learning curve can be drawn from it afterwards.
154
+ trainer.callback_metrics[self.name] = th.tensor(score)
155
+ if trainer.logger is not None:
156
+ trainer.logger.log_metrics({self.name: score}, step=trainer.current_epoch)
157
+
158
+
159
+ class WarmupEarlyStopping(EarlyStopping):
160
+ """Early stopping that starts counting when the model starts learning.
161
+
162
+ Patience is about epochs the monitored model failed to improve on, and an
163
+ epoch it did not train in is not one of those.
164
+ """
165
+
166
+ def _run_early_stopping_check(self, trainer: L.Trainer) -> None:
167
+ if trainer.current_epoch < warmup_epochs(trainer.lightning_module):
168
+ return
169
+ super()._run_early_stopping_check(trainer)
170
+
171
+
172
+ class WarmupModelCheckpoint(ModelCheckpoint):
173
+ """Checkpointing that ignores the epochs before the model trains.
174
+
175
+ Without this the best epoch of a pretraining phase is a candidate for the
176
+ epoch a run is scored on, and it holds a rationalizer that has taken no
177
+ gradient step at all.
178
+ """
179
+
180
+ def _save_topk_checkpoint(
181
+ self, trainer: L.Trainer, monitor_candidates: dict
182
+ ) -> None:
183
+ if trainer.current_epoch < warmup_epochs(trainer.lightning_module):
184
+ return
185
+ super()._save_topk_checkpoint(trainer, monitor_candidates)
@@ -70,6 +70,16 @@ class SPPFirstAggregator(SPPAggregator):
70
70
 
71
71
 
72
72
  class SPP(Model[SPPOutput]):
73
+ #: Training epochs this model spends before the monitored model learns.
74
+ #:
75
+ #: Zero for every architecture whose first optimizer step happens in the
76
+ #: first epoch. G-RAT overrides it: it gates the rationalizer on
77
+ #: ``current_epoch >= pretrain_epochs``, so its early epochs train a guider
78
+ #: and leave the thing a monitor watches untouched. Read by the monitoring
79
+ #: callbacks, which is why it lives on the model -- a task repeating the
80
+ #: number is a second place for it to disagree.
81
+ warmup_epochs: int = 0
82
+
73
83
  def __init__(
74
84
  self,
75
85
  selector_backbones: Union[
@@ -137,6 +137,18 @@ class GRAT(SPP):
137
137
  self.register_buffer("_model_steps", th.zeros((), dtype=th.long))
138
138
  self.automatic_optimization = False
139
139
 
140
+ @property
141
+ def warmup_epochs(self) -> int:
142
+ """The guider's pretraining, which the rationalizer sits out.
143
+
144
+ ``training_step`` gates the model's optimizer on
145
+ ``current_epoch >= pretrain_epochs``, so until then the monitored
146
+ quantities describe a model that has taken no step. Monitoring from
147
+ epoch zero stopped two of five seeds of the legal study's frozen arm
148
+ inside this window.
149
+ """
150
+ return int(self.pretrain_epochs)
151
+
140
152
  @property
141
153
  def guide_factor(self) -> float:
142
154
  completed_decay_steps = max(self._model_steps.item() - 1, 0)
@@ -28,10 +28,11 @@ import pandas as pd
28
28
  import torch as th
29
29
  from cinnamon.registry import RegistrationKey, Registry
30
30
  from lightning.pytorch import seed_everything
31
- from lightning.pytorch.callbacks import EarlyStopping, ModelCheckpoint
31
+ from lightning.pytorch.callbacks import Callback, ModelCheckpoint
32
32
  from torch.utils.data import DataLoader
33
33
 
34
34
  from pyhighlights.components import faithfulness
35
+ from pyhighlights.components.callbacks import MonitoredScore
35
36
  from pyhighlights.components.data import (
36
37
  HighlightCollator,
37
38
  HighlightDataset,
@@ -203,8 +204,7 @@ class SPPTask(Task):
203
204
  add_special_tokens: bool = True,
204
205
  embeddings: str | Path | None = None,
205
206
  pretrained_tokens_only: bool = True,
206
- monitor: str = "val_loss",
207
- patience: int = 5,
207
+ callbacks: List[RegistrationKey[Callback]] | None = None,
208
208
  store_predictions: bool = False,
209
209
  keep_checkpoints: bool = True,
210
210
  save_weights_only: bool = False,
@@ -239,8 +239,7 @@ class SPPTask(Task):
239
239
  "a task embeds its tokens either with a pretrained model card "
240
240
  "or with a vector file, not both"
241
241
  )
242
- self.monitor = monitor
243
- self.patience = patience
242
+ self.callbacks = list(callbacks) if callbacks is not None else None
244
243
  self.store_predictions = store_predictions
245
244
  # A checkpoint holds the whole model. On a transformer grid that is
246
245
  # hundreds of gigabytes of files nothing downstream reads: the task
@@ -318,6 +317,58 @@ class SPPTask(Task):
318
317
  for name, frame in splits.items()
319
318
  }
320
319
 
320
+ def build_callbacks(self, checkpoints: Path) -> List[Callback]:
321
+ """What monitors this run, built from the keys the task was given.
322
+
323
+ A checkpoint callback is told where to write and whether to store
324
+ weights only, because those are the task's business rather than the
325
+ study's -- the run deletes them again once it has scored the epoch
326
+ they hold.
327
+
328
+ Nothing is monitored when no keys are given, and the run is scored on
329
+ the weights it ended on. The registered configuration names the pair
330
+ the task used to build for itself -- early stopping and checkpointing
331
+ on ``val_loss`` -- rather than this class naming it, so that which
332
+ callbacks are the default is a decision of the configuration layer and
333
+ is stated once.
334
+ """
335
+ built: List[Callback] = []
336
+ for key in self.callbacks or []:
337
+ callback = Registry.from_key(key, expected_type=Callback)
338
+ if isinstance(callback, ModelCheckpoint):
339
+ callback.dirpath = str(checkpoints)
340
+ callback.save_weights_only = self.save_weights_only
341
+ built.append(callback)
342
+ # Everything that monitors has to monitor the same thing. Early
343
+ # stopping decides when a run ends and the checkpoint decides which
344
+ # epoch it is scored on, so two quantities mean the reported model is
345
+ # not the one the stopping rule chose -- and nothing downstream says
346
+ # so, because `results.json` records the scores and not the argument
347
+ # behind them. Refused here rather than left to a reader of a table.
348
+ monitored = {
349
+ (callback.monitor, callback.mode)
350
+ for callback in built
351
+ if getattr(callback, "monitor", None) is not None
352
+ and getattr(callback, "mode", None) is not None
353
+ }
354
+ if len(monitored) > 1:
355
+ raise ValueError(
356
+ "callbacks monitoring different quantities: "
357
+ + ", ".join(
358
+ f"{monitor} ({mode})" for monitor, mode in sorted(monitored)
359
+ )
360
+ + ". Early stopping ends the run and the checkpoint chooses "
361
+ "the epoch it is scored on, so they have to agree; combine "
362
+ "two quantities with a MonitoredScore instead."
363
+ )
364
+
365
+ # A criterion that writes the monitored quantity has to run before the
366
+ # callbacks that read it: they share the `on_validation_end` hook and
367
+ # Lightning calls them in order. Sorted here rather than documented as
368
+ # a rule about list order, which is the kind of rule a study gets
369
+ # wrong once and then cannot see.
370
+ return sorted(built, key=lambda item: not isinstance(item, MonitoredScore))
371
+
321
372
  def build_model(self) -> Model:
322
373
  # Passed only when asked for, so an unsupervised run builds exactly the
323
374
  # model its key describes.
@@ -367,18 +418,13 @@ class SPPTask(Task):
367
418
 
368
419
  checkpoints = self.directory / f"seed={seed}"
369
420
  checkpoints.mkdir(parents=True, exist_ok=True)
370
- checkpoint = ModelCheckpoint(
371
- monitor=self.monitor,
372
- mode="min",
373
- dirpath=checkpoints,
374
- save_weights_only=self.save_weights_only,
421
+ built = self.build_callbacks(checkpoints)
422
+ checkpoint = next(
423
+ (item for item in built if isinstance(item, ModelCheckpoint)), None
375
424
  )
376
425
  trainer = L.Trainer(
377
426
  **{"default_root_dir": checkpoints, **self.trainer_args},
378
- callbacks=[
379
- EarlyStopping(monitor=self.monitor, mode="min", patience=self.patience),
380
- checkpoint,
381
- ],
427
+ callbacks=built,
382
428
  )
383
429
  trainer.fit(
384
430
  model,
@@ -389,7 +435,17 @@ class SPPTask(Task):
389
435
  # The last epoch is not the best one: early stopping stops after
390
436
  # `patience` worse epochs, so scoring the weights still in memory
391
437
  # reports a model nobody would have kept.
392
- if not checkpoint.best_model_path:
438
+ if checkpoint is None:
439
+ # No checkpoint callback was configured, so there is no best epoch
440
+ # to go back to and the run is scored on the weights it ended on.
441
+ # A deliberate configuration rather than an accident, so it is not
442
+ # a warning.
443
+ logger.info(
444
+ "%s: no checkpoint callback, so seed %s is scored on its last epoch",
445
+ self.name,
446
+ seed,
447
+ )
448
+ elif not checkpoint.best_model_path:
393
449
  # Nothing was ever checkpointed: `monitor` names a metric no split
394
450
  # logs. Scoring the weights training happened to end on is not the
395
451
  # same experiment, so say which metric is missing.
@@ -397,7 +453,7 @@ class SPPTask(Task):
397
453
  "%s: nothing monitored %s, so seed %s is scored on its last "
398
454
  "epoch rather than its best one",
399
455
  self.name,
400
- self.monitor,
456
+ checkpoint.monitor,
401
457
  seed,
402
458
  )
403
459
  else:
@@ -3,7 +3,12 @@
3
3
  Nothing here registers: every model would otherwise inherit a registration it
4
4
  never asked for. The fields each model overrides -- the backbones, the losses,
5
5
  the optimizer -- are named once here and pinned per model in ``fr``, ``mgr``,
6
- ``mcd``, ``grat`` and ``genspp``.
6
+ ``mcd``, ``mrd``, ``dr``, ``dar``, ``grat`` and ``genspp``.
7
+
8
+ Three bases rather than one, because the architectures disagree about what a
9
+ loss is: :class:`SPPModelConfig` scores a flat list,
10
+ :class:`PhasedSPPModelConfig` scores three lists tied to training phases, and
11
+ :class:`SPPShapeConfig` is what the two share.
7
12
  """
8
13
 
9
14
  from typing import List
@@ -31,8 +36,16 @@ from pyhighlights.utility.losses import Loss
31
36
  from pyhighlights.utility.metrics import BoundMetric
32
37
 
33
38
 
34
- class SPPModelConfig(Configuration):
35
- """One selector feeding one predictor, the shape every SPP model starts from."""
39
+ class SPPShapeConfig(Configuration):
40
+ """The parts every SPP model has, without saying what it optimises.
41
+
42
+ Split from :class:`SPPModelConfig` because not every architecture has a
43
+ flat ``losses`` list: MCD and MRD score their criteria per training phase
44
+ and take three lists instead. Restating the other eleven fields to get rid
45
+ of one is what cost PR #48 -- ``encoder_lr`` was added here and reached
46
+ neither -- so the shape lives in one place and each model says only what
47
+ differs.
48
+ """
36
49
 
37
50
  name: str = Param("spp")
38
51
  selector_backbones: RegistrationKey[SPPBackbone] = Param(GRU_BACKBONE)
@@ -55,10 +68,32 @@ class SPPModelConfig(Configuration):
55
68
  #: Set it when a pretrained encoder *is* being fine-tuned: one rate cannot
56
69
  #: serve both a transformer and a selector initialized from scratch.
57
70
  encoder_lr: float | None = Param(None, gt=0.0)
58
- losses: List[RegistrationKey[Loss]] = Param(
59
- [CLASSIFICATION_LOSS, SPARSITY_LOSS, CONTIGUITY_LOSS]
60
- )
61
71
  optimizer: RegistrationKey[th.optim.Optimizer] = Param(ADAM)
62
72
  train_metrics: List[RegistrationKey[BoundMetric]] | None = Param(None)
63
73
  val_metrics: List[RegistrationKey[BoundMetric]] | None = Param(None)
64
74
  test_metrics: List[RegistrationKey[BoundMetric]] | None = Param(None)
75
+
76
+
77
+ class SPPModelConfig(SPPShapeConfig):
78
+ """An SPP model scoring one flat list of criteria."""
79
+
80
+ losses: List[RegistrationKey[Loss]] = Param(
81
+ [CLASSIFICATION_LOSS, SPARSITY_LOSS, CONTIGUITY_LOSS]
82
+ )
83
+
84
+
85
+ class PhasedSPPModelConfig(SPPShapeConfig):
86
+ """An SPP model whose criteria belong to a training phase.
87
+
88
+ MCD and MRD are the same shape and differ only in which criteria go in
89
+ which list, so the lists are declared once. Both refuse
90
+ ``supervise_highlights`` for the same reason: a supervision loss appended
91
+ to a flat list would be dropped before the first batch, and the phase it
92
+ belongs to has to be named.
93
+ """
94
+
95
+ rationale_losses: List[RegistrationKey[Loss]] = Param(
96
+ [SPARSITY_LOSS, CONTIGUITY_LOSS]
97
+ )
98
+ predictor_losses: List[RegistrationKey[Loss]] = Param([])
99
+ generator_losses: List[RegistrationKey[Loss]] = Param([])
@@ -85,6 +85,11 @@ class PredictionAnalyzerConfig(Configuration):
85
85
  directory: str | None = Param(None)
86
86
  pattern: str = Param(PREDICTIONS)
87
87
  split: str = Param("test")
88
+ #: The newest run of each task, as
89
+ #: :class:`~pyhighlights.configurations.benchmarks.MetricsAnalyzerConfig`
90
+ #: does. ``False`` reads every run a task has ever done, which is a report
91
+ #: about the history rather than about the model.
92
+ latest: bool = Param(True)
88
93
 
89
94
 
90
95
  @register_class(
@@ -0,0 +1,104 @@
1
+ """What monitors a run, as configurations rather than as task parameters.
2
+
3
+ Two sets are registered. The ``loss`` pair reproduces what the task used to
4
+ build for itself -- early stopping and checkpointing on ``val_loss``,
5
+ minimised -- so a study that wants the old behaviour names it rather than
6
+ inheriting it silently. The ``score`` pair monitors
7
+ :class:`~pyhighlights.components.callbacks.GeneralizationLossScore`'s
8
+ combination and maximises it.
9
+
10
+ **Both callbacks of a pair monitor the same quantity**, and that is the point
11
+ of pairing them: the epoch that stops a run has to be the epoch the run is
12
+ scored on. A study is free to mix them, and gets a run whose reported model is
13
+ not the one its stopping rule chose.
14
+ """
15
+
16
+ from cinnamon.configuration import Configuration, Param
17
+ from cinnamon.registry import register_class
18
+
19
+ from pyhighlights.configurations.keys import NAMESPACE
20
+
21
+ EARLY_STOPPING = "pyhighlights.components.callbacks.WarmupEarlyStopping"
22
+ CHECKPOINT = "pyhighlights.components.callbacks.WarmupModelCheckpoint"
23
+
24
+
25
+ @register_class(
26
+ name="callback",
27
+ tags={"score", "generalization_loss"},
28
+ namespace=NAMESPACE,
29
+ component="pyhighlights.components.callbacks.GeneralizationLossScore",
30
+ )
31
+ class GeneralizationLossScoreConfig(Configuration):
32
+ """A metric, charged for validation loss risen above its own best."""
33
+
34
+ quality: str = Param("val_f1")
35
+ loss: str = Param("val_loss")
36
+ #: How much ``quality`` an epoch forfeits per unit of relative loss
37
+ #: regression. Per architecture rather than per library: the loss curves
38
+ #: differ, and 0 monitors the metric alone while a large value monitors
39
+ #: the loss alone, so both are special cases of this.
40
+ coefficient: float = Param(2.0, ge=0.0)
41
+ name: str = Param("val_score")
42
+
43
+
44
+ @register_class(
45
+ name="callback",
46
+ tags={"early_stopping", "loss"},
47
+ namespace=NAMESPACE,
48
+ component=EARLY_STOPPING,
49
+ )
50
+ class LossEarlyStoppingConfig(Configuration):
51
+ """Stop when the validation loss stops falling."""
52
+
53
+ monitor: str = Param("val_loss")
54
+ mode: str = Param("min")
55
+ patience: int = Param(5, ge=0)
56
+
57
+
58
+ @register_class(
59
+ name="callback",
60
+ tags={"checkpoint", "loss"},
61
+ namespace=NAMESPACE,
62
+ component=CHECKPOINT,
63
+ )
64
+ class LossCheckpointConfig(Configuration):
65
+ """Keep the epoch with the lowest validation loss."""
66
+
67
+ monitor: str = Param("val_loss")
68
+ mode: str = Param("min")
69
+
70
+
71
+ @register_class(
72
+ name="callback",
73
+ tags={"early_stopping", "score"},
74
+ namespace=NAMESPACE,
75
+ component=EARLY_STOPPING,
76
+ )
77
+ class ScoreEarlyStoppingConfig(Configuration):
78
+ """Stop when the combined score stops rising."""
79
+
80
+ monitor: str = Param("val_score")
81
+ mode: str = Param("max")
82
+ patience: int = Param(5, ge=0)
83
+
84
+
85
+ @register_class(
86
+ name="callback",
87
+ tags={"checkpoint", "score"},
88
+ namespace=NAMESPACE,
89
+ component=CHECKPOINT,
90
+ )
91
+ class ScoreCheckpointConfig(Configuration):
92
+ """Keep the epoch with the highest combined score."""
93
+
94
+ monitor: str = Param("val_score")
95
+ mode: str = Param("max")
96
+
97
+
98
+ __all__ = [
99
+ "GeneralizationLossScoreConfig",
100
+ "LossCheckpointConfig",
101
+ "LossEarlyStoppingConfig",
102
+ "ScoreCheckpointConfig",
103
+ "ScoreEarlyStoppingConfig",
104
+ ]