evalsuite-python 1.3.5__py3-none-any.whl → 1.4.0__py3-none-any.whl
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.
- evalsuite/__init__.py +16 -0
- evalsuite/_update.py +40 -10
- evalsuite/agreement.py +2 -1
- evalsuite/bayes.py +3 -2
- evalsuite/cache.py +258 -0
- evalsuite/cards.py +1 -1
- evalsuite/cli/main.py +37 -0
- evalsuite/core/registry.py +4 -0
- evalsuite/core/validation.py +21 -1
- evalsuite/llm_benchmarks.py +8 -1
- evalsuite/llmsys/longcontext.py +4 -3
- evalsuite/llmsys/multilingual.py +2 -1
- evalsuite/llmsys/robustness.py +4 -6
- evalsuite/llmsys/safety.py +2 -1
- evalsuite/monitor.py +5 -4
- evalsuite/multilabel.py +4 -0
- evalsuite/recalibration.py +4 -3
- evalsuite/stats/compare.py +10 -3
- evalsuite/stats/effect.py +5 -5
- evalsuite/stats/hypothesis.py +3 -3
- evalsuite/stats/intervals.py +2 -2
- evalsuite/stats/planning.py +9 -2
- evalsuite/survival.py +2 -1
- evalsuite/text/factuality.py +4 -3
- evalsuite/text/generation.py +2 -1
- evalsuite/text/judge.py +3 -2
- evalsuite/text/qa.py +2 -0
- evalsuite/text/rag.py +2 -1
- evalsuite/text/semantic.py +3 -2
- evalsuite/text/structured.py +3 -1
- evalsuite/version.py +1 -1
- evalsuite/vision/detection.py +3 -2
- {evalsuite_python-1.3.5.dist-info → evalsuite_python-1.4.0.dist-info}/METADATA +20 -3
- {evalsuite_python-1.3.5.dist-info → evalsuite_python-1.4.0.dist-info}/RECORD +38 -37
- {evalsuite_python-1.3.5.dist-info → evalsuite_python-1.4.0.dist-info}/WHEEL +0 -0
- {evalsuite_python-1.3.5.dist-info → evalsuite_python-1.4.0.dist-info}/entry_points.txt +0 -0
- {evalsuite_python-1.3.5.dist-info → evalsuite_python-1.4.0.dist-info}/licenses/LICENSE +0 -0
- {evalsuite_python-1.3.5.dist-info → evalsuite_python-1.4.0.dist-info}/licenses/LICENSE-APACHE +0 -0
evalsuite/__init__.py
CHANGED
|
@@ -46,6 +46,12 @@ if TYPE_CHECKING: # static analysers and IDEs see the full eager API
|
|
|
46
46
|
bayes_compare,
|
|
47
47
|
bayes_correlated_ttest,
|
|
48
48
|
)
|
|
49
|
+
from .cache import (
|
|
50
|
+
CacheInfo,
|
|
51
|
+
cache_dir,
|
|
52
|
+
cache_info,
|
|
53
|
+
clear_cache,
|
|
54
|
+
)
|
|
49
55
|
from .calibration import (
|
|
50
56
|
CalibrationReport,
|
|
51
57
|
calibration_intercept,
|
|
@@ -384,6 +390,12 @@ _EXPORTS: dict[str, tuple[str, ...]] = {
|
|
|
384
390
|
"Calibrator",
|
|
385
391
|
"recalibrate",
|
|
386
392
|
),
|
|
393
|
+
".cache": (
|
|
394
|
+
"CacheInfo",
|
|
395
|
+
"cache_dir",
|
|
396
|
+
"cache_info",
|
|
397
|
+
"clear_cache",
|
|
398
|
+
),
|
|
387
399
|
".fairness": (
|
|
388
400
|
"FairnessReport",
|
|
389
401
|
"fairness_report",
|
|
@@ -674,6 +686,7 @@ __all__ = [
|
|
|
674
686
|
"BENCHMARKS",
|
|
675
687
|
"BayesComparison",
|
|
676
688
|
"BlandAltman",
|
|
689
|
+
"CacheInfo",
|
|
677
690
|
"CalibrationReport",
|
|
678
691
|
"Calibrator",
|
|
679
692
|
"ClassificationReport",
|
|
@@ -745,6 +758,8 @@ __all__ = [
|
|
|
745
758
|
"bradley_terry",
|
|
746
759
|
"brier_score",
|
|
747
760
|
"brier_score_survival",
|
|
761
|
+
"cache_dir",
|
|
762
|
+
"cache_info",
|
|
748
763
|
"calibration",
|
|
749
764
|
"calibration_curve",
|
|
750
765
|
"calibration_intercept",
|
|
@@ -760,6 +775,7 @@ __all__ = [
|
|
|
760
775
|
"claim_verification_accuracy",
|
|
761
776
|
"classification",
|
|
762
777
|
"classification_report",
|
|
778
|
+
"clear_cache",
|
|
763
779
|
"cliffs_delta",
|
|
764
780
|
"clinical",
|
|
765
781
|
"code_complexity",
|
evalsuite/_update.py
CHANGED
|
@@ -68,13 +68,20 @@ def _installed() -> str:
|
|
|
68
68
|
return __version__
|
|
69
69
|
|
|
70
70
|
|
|
71
|
+
def _cache_root() -> Path:
|
|
72
|
+
"""EvalSuite's cache folder (documented in :mod:`evalsuite.cache`); kept here so importing stays light."""
|
|
73
|
+
env = os.environ.get("EVALSUITE_CACHE")
|
|
74
|
+
if env:
|
|
75
|
+
return Path(env).expanduser()
|
|
76
|
+
if os.environ.get("XDG_CACHE_HOME"):
|
|
77
|
+
return Path(os.environ["XDG_CACHE_HOME"]) / "evalsuite"
|
|
78
|
+
if sys.platform == "win32" and os.environ.get("LOCALAPPDATA"):
|
|
79
|
+
return Path(os.environ["LOCALAPPDATA"]) / "evalsuite"
|
|
80
|
+
return Path.home() / ".cache" / "evalsuite"
|
|
81
|
+
|
|
82
|
+
|
|
71
83
|
def _cache_file() -> Path:
|
|
72
|
-
|
|
73
|
-
os.path.join(os.environ.get("LOCALAPPDATA", ""), "evalsuite")
|
|
74
|
-
if sys.platform == "win32" and os.environ.get("LOCALAPPDATA")
|
|
75
|
-
else os.path.join(os.path.expanduser("~"), ".cache")
|
|
76
|
-
)
|
|
77
|
-
return Path(base) / "evalsuite" / "update-check.json"
|
|
84
|
+
return _cache_root() / "update-check.json"
|
|
78
85
|
|
|
79
86
|
|
|
80
87
|
def _read_cache() -> dict[str, Any]:
|
|
@@ -87,9 +94,10 @@ def _read_cache() -> dict[str, Any]:
|
|
|
87
94
|
|
|
88
95
|
def _write_cache(data: dict[str, Any]) -> None:
|
|
89
96
|
try:
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
97
|
+
from .cache import cache_dir
|
|
98
|
+
|
|
99
|
+
cache_dir(create=True)
|
|
100
|
+
_cache_file().write_text(json.dumps(data))
|
|
93
101
|
except OSError:
|
|
94
102
|
pass
|
|
95
103
|
|
|
@@ -148,8 +156,30 @@ def _background_refresh() -> None:
|
|
|
148
156
|
_write_cache(data)
|
|
149
157
|
|
|
150
158
|
|
|
159
|
+
def _clean_in_background() -> None:
|
|
160
|
+
"""Start the automatic cache clearing (evalsuite.cache) in a background thread when it is due (daily)."""
|
|
161
|
+
try:
|
|
162
|
+
root = _cache_root()
|
|
163
|
+
stamp = root / ".last-clean"
|
|
164
|
+
if not (root / ".evalsuite-cache").is_file():
|
|
165
|
+
return
|
|
166
|
+
if stamp.exists() and time.time() - stamp.stat().st_mtime < DAY:
|
|
167
|
+
return
|
|
168
|
+
except OSError:
|
|
169
|
+
return
|
|
170
|
+
|
|
171
|
+
def run() -> None:
|
|
172
|
+
from .cache import auto_clean
|
|
173
|
+
|
|
174
|
+
auto_clean()
|
|
175
|
+
|
|
176
|
+
threading.Thread(target=run, name="evalsuite-cache-clean", daemon=True).start()
|
|
177
|
+
|
|
178
|
+
|
|
151
179
|
def notify_on_import() -> None:
|
|
152
|
-
"""Print the cached notice (at most once a day) and refresh the cache in the background when stale
|
|
180
|
+
"""Print the cached notice (at most once a day) and refresh the cache in the background when stale; also
|
|
181
|
+
start the daily automatic cache clearing when due."""
|
|
182
|
+
_clean_in_background()
|
|
153
183
|
if _disabled():
|
|
154
184
|
return
|
|
155
185
|
data = _read_cache()
|
evalsuite/agreement.py
CHANGED
|
@@ -21,6 +21,7 @@ from typing import Any, Optional
|
|
|
21
21
|
import numpy as np
|
|
22
22
|
|
|
23
23
|
from .core.exceptions import InputValidationError
|
|
24
|
+
from .core.validation import numeric
|
|
24
25
|
|
|
25
26
|
__all__ = ["ICCResult", "ICCForm", "BlandAltman", "icc", "bland_altman", "lins_ccc"]
|
|
26
27
|
|
|
@@ -136,7 +137,7 @@ def _table(ratings: Any, subjects: Any, raters: Any) -> np.ndarray:
|
|
|
136
137
|
return x
|
|
137
138
|
if subjects is None or raters is None:
|
|
138
139
|
raise InputValidationError("Long format needs both subjects= and raters=.")
|
|
139
|
-
vals =
|
|
140
|
+
vals = numeric(ratings, "ratings").ravel()
|
|
140
141
|
s = np.asarray(subjects).ravel()
|
|
141
142
|
r = np.asarray(raters).ravel()
|
|
142
143
|
if not (vals.size == s.size == r.size):
|
evalsuite/bayes.py
CHANGED
|
@@ -23,6 +23,7 @@ from typing import Any, Callable, Optional, Union
|
|
|
23
23
|
import numpy as np
|
|
24
24
|
|
|
25
25
|
from .core.exceptions import EvalSuiteError, InputValidationError
|
|
26
|
+
from .core.validation import numeric
|
|
26
27
|
|
|
27
28
|
__all__ = ["BayesComparison", "bayes_compare", "bayes_correlated_ttest"]
|
|
28
29
|
|
|
@@ -277,8 +278,8 @@ def bayes_correlated_ttest(
|
|
|
277
278
|
Student t with n − 1 degrees of freedom; probabilities are exact and the draws only feed ``samples``."""
|
|
278
279
|
from scipy import stats
|
|
279
280
|
|
|
280
|
-
sa =
|
|
281
|
-
sb =
|
|
281
|
+
sa = numeric(scores_a, "scores_a").ravel()
|
|
282
|
+
sb = numeric(scores_b, "scores_b").ravel()
|
|
282
283
|
if sa.size != sb.size:
|
|
283
284
|
raise InputValidationError(f"Both models need a score per fold; got {sa.size} and {sb.size}.")
|
|
284
285
|
if sa.size < 2 or not (np.all(np.isfinite(sa)) and np.all(np.isfinite(sb))):
|
evalsuite/cache.py
ADDED
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
"""EvalSuite's cache folder: where downloaded benchmark data and the update-check record live.
|
|
2
|
+
|
|
3
|
+
>>> import evalsuite as es
|
|
4
|
+
>>> es.cache_info() # location, size, entries
|
|
5
|
+
>>> es.clear_cache(older_than="30d") # or clear_cache() for everything
|
|
6
|
+
|
|
7
|
+
The folder is ``$EVALSUITE_CACHE`` if set, else ``$XDG_CACHE_HOME/evalsuite``, ``%LOCALAPPDATA%\\evalsuite`` on
|
|
8
|
+
Windows, or ``~/.cache/evalsuite``. From the command line: ``evalsuite cache info`` and ``evalsuite cache clear``.
|
|
9
|
+
|
|
10
|
+
Automatic clearing: at most once a day, in the background after import, entries not used for
|
|
11
|
+
``EVALSUITE_CACHE_MAX_AGE`` (default 90 days) are removed, then the least recently used entries until the cache is
|
|
12
|
+
below ``EVALSUITE_CACHE_MAX_SIZE`` (default 2 GB). Set ``EVALSUITE_CACHE_AUTO_CLEAN=0`` to turn it off. Only
|
|
13
|
+
folders EvalSuite created (they carry a marker file) are ever touched, and only whole entries (one data set
|
|
14
|
+
download, one record) are removed, never part of one.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import contextlib
|
|
20
|
+
import os
|
|
21
|
+
import re
|
|
22
|
+
import shutil
|
|
23
|
+
import time
|
|
24
|
+
from dataclasses import dataclass
|
|
25
|
+
from pathlib import Path
|
|
26
|
+
from typing import Any, Optional, Union
|
|
27
|
+
|
|
28
|
+
from .core.exceptions import InputValidationError
|
|
29
|
+
|
|
30
|
+
__all__ = ["CacheInfo", "cache_dir", "cache_info", "clear_cache"]
|
|
31
|
+
|
|
32
|
+
MARKER = ".evalsuite-cache"
|
|
33
|
+
_STAMP = ".last-clean"
|
|
34
|
+
_KEEP = {MARKER, _STAMP}
|
|
35
|
+
_DEFAULT_MAX_AGE = 90 * 86400.0
|
|
36
|
+
_DEFAULT_MAX_SIZE = 2 * 1024**3
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def cache_dir(*, create: bool = False) -> Path:
|
|
40
|
+
"""The cache folder (see the module docstring); ``create=True`` makes it, with its marker file."""
|
|
41
|
+
from ._update import _cache_root
|
|
42
|
+
|
|
43
|
+
path = _cache_root()
|
|
44
|
+
if create:
|
|
45
|
+
path.mkdir(parents=True, exist_ok=True)
|
|
46
|
+
marker = path / MARKER
|
|
47
|
+
if not marker.exists():
|
|
48
|
+
marker.write_text("Created by EvalSuite. Everything in this folder can be deleted safely.\n")
|
|
49
|
+
return path
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _parse_age(value: Union[str, float, int, None]) -> Optional[float]:
|
|
53
|
+
"""Seconds from 3600, "30d", "12h", "45m", "90s", "2w" (None stays None)."""
|
|
54
|
+
if value is None:
|
|
55
|
+
return None
|
|
56
|
+
if isinstance(value, (int, float)):
|
|
57
|
+
if value < 0:
|
|
58
|
+
raise InputValidationError("Ages must be non-negative.")
|
|
59
|
+
return float(value)
|
|
60
|
+
m = re.fullmatch(r"\s*(\d+(?:\.\d+)?)\s*([smhdw]?)\s*", str(value).lower())
|
|
61
|
+
if not m:
|
|
62
|
+
raise InputValidationError(f"Cannot read the age {value!r}; use e.g. '30d', '12h', '2w' or seconds.")
|
|
63
|
+
unit = {"": 1, "s": 1, "m": 60, "h": 3600, "d": 86400, "w": 7 * 86400}[m.group(2)]
|
|
64
|
+
return float(m.group(1)) * unit
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _parse_size(value: Union[str, int, None]) -> Optional[int]:
|
|
68
|
+
"""Bytes from 1048576, "500MB", "2GB", "1.5G" (None stays None)."""
|
|
69
|
+
if value is None:
|
|
70
|
+
return None
|
|
71
|
+
if isinstance(value, int):
|
|
72
|
+
return value
|
|
73
|
+
m = re.fullmatch(r"\s*(\d+(?:\.\d+)?)\s*([kmgt]?)i?b?\s*", str(value).lower())
|
|
74
|
+
if not m:
|
|
75
|
+
raise InputValidationError(f"Cannot read the size {value!r}; use e.g. '500MB' or '2GB'.")
|
|
76
|
+
return int(float(m.group(1)) * 1024 ** "_kmgt".index(m.group(2) or "_"))
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _entries(root: Path) -> list[tuple[Path, int, float]]:
|
|
80
|
+
"""Whole entries — a top-level file, or one item inside a top-level folder (one data set download) — with
|
|
81
|
+
their size and last use (newest access or modification time of anything in them)."""
|
|
82
|
+
out: list[tuple[Path, int, float]] = []
|
|
83
|
+
if not root.is_dir():
|
|
84
|
+
return out
|
|
85
|
+
for top in root.iterdir():
|
|
86
|
+
if top.name in _KEEP or top.name.startswith(".trash-"):
|
|
87
|
+
continue
|
|
88
|
+
units = list(top.iterdir()) if top.is_dir() and not top.is_symlink() else [top]
|
|
89
|
+
for unit in units:
|
|
90
|
+
size, last = 0, 0.0
|
|
91
|
+
files = [unit] if not unit.is_dir() or unit.is_symlink() else [p for p in unit.rglob("*")]
|
|
92
|
+
for f in files:
|
|
93
|
+
if f.is_dir() and not f.is_symlink():
|
|
94
|
+
continue # listing a folder updates its access time, so only files say when it was used
|
|
95
|
+
try:
|
|
96
|
+
st = f.lstat()
|
|
97
|
+
except OSError:
|
|
98
|
+
continue
|
|
99
|
+
size += st.st_size
|
|
100
|
+
last = max(last, st.st_atime, st.st_mtime)
|
|
101
|
+
if last == 0.0:
|
|
102
|
+
with contextlib.suppress(OSError):
|
|
103
|
+
last = unit.lstat().st_mtime
|
|
104
|
+
out.append((unit, size, last))
|
|
105
|
+
return out
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
@dataclass(frozen=True)
|
|
109
|
+
class CacheInfo:
|
|
110
|
+
"""What the cache holds."""
|
|
111
|
+
|
|
112
|
+
path: str
|
|
113
|
+
exists: bool
|
|
114
|
+
size_bytes: int
|
|
115
|
+
entries: tuple[dict[str, Any], ...]
|
|
116
|
+
auto_clean: bool
|
|
117
|
+
max_age_days: float
|
|
118
|
+
max_size_bytes: int
|
|
119
|
+
|
|
120
|
+
def summary(self) -> str:
|
|
121
|
+
if not self.exists:
|
|
122
|
+
return f"EvalSuite cache: {self.path} (empty; nothing downloaded yet)"
|
|
123
|
+
lines = [
|
|
124
|
+
f"EvalSuite cache: {self.path}",
|
|
125
|
+
f" {_human(self.size_bytes)} in {len(self.entries)} entr{'y' if len(self.entries) == 1 else 'ies'}",
|
|
126
|
+
" Automatic clearing: "
|
|
127
|
+
+ (
|
|
128
|
+
f"on (unused for {self.max_age_days:g} days, or beyond {_human(self.max_size_bytes)})"
|
|
129
|
+
if self.auto_clean
|
|
130
|
+
else "off"
|
|
131
|
+
),
|
|
132
|
+
]
|
|
133
|
+
for e in sorted(self.entries, key=lambda e: -e["size_bytes"])[:15]:
|
|
134
|
+
lines.append(f" {_human(e['size_bytes']):>9} {e['days_unused']:6.1f} days unused {e['name']}")
|
|
135
|
+
return "\n".join(lines)
|
|
136
|
+
|
|
137
|
+
def __repr__(self) -> str:
|
|
138
|
+
return self.summary()
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def _human(n: float) -> str:
|
|
142
|
+
for unit in ("B", "KB", "MB", "GB"):
|
|
143
|
+
if n < 1024 or unit == "GB":
|
|
144
|
+
return f"{n:.0f} {unit}" if unit == "B" else f"{n:.1f} {unit}"
|
|
145
|
+
n /= 1024
|
|
146
|
+
return f"{n:.1f} GB" # pragma: no cover
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _settings() -> tuple[bool, float, int]:
|
|
150
|
+
auto = os.environ.get("EVALSUITE_CACHE_AUTO_CLEAN", "1").strip().lower() not in ("0", "false", "no", "off")
|
|
151
|
+
try:
|
|
152
|
+
age = _parse_age(os.environ.get("EVALSUITE_CACHE_MAX_AGE")) or _DEFAULT_MAX_AGE
|
|
153
|
+
size = _parse_size(os.environ.get("EVALSUITE_CACHE_MAX_SIZE")) or _DEFAULT_MAX_SIZE
|
|
154
|
+
except InputValidationError:
|
|
155
|
+
age, size = _DEFAULT_MAX_AGE, _DEFAULT_MAX_SIZE
|
|
156
|
+
return auto, age, size
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def cache_info() -> CacheInfo:
|
|
160
|
+
"""Location, size and entries of the cache, and the automatic-clearing settings."""
|
|
161
|
+
root = cache_dir()
|
|
162
|
+
auto, age, size = _settings()
|
|
163
|
+
now = time.time()
|
|
164
|
+
entries: tuple[dict[str, Any], ...] = tuple(
|
|
165
|
+
{"name": p.relative_to(root).as_posix(), "size_bytes": s, "days_unused": max(0.0, (now - last) / 86400)}
|
|
166
|
+
for p, s, last in _entries(root)
|
|
167
|
+
)
|
|
168
|
+
return CacheInfo(
|
|
169
|
+
str(root), root.is_dir(), sum(int(e["size_bytes"]) for e in entries), entries, auto, age / 86400, size
|
|
170
|
+
)
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def _remove(path: Path, root: Path) -> None:
|
|
174
|
+
"""Delete one entry: rename it into the cache's trash first (atomic), so an interrupted deletion never leaves
|
|
175
|
+
half an entry where a reader would find it; the trash is emptied now and on later runs."""
|
|
176
|
+
import uuid
|
|
177
|
+
|
|
178
|
+
trash = root / f".trash-{uuid.uuid4().hex}"
|
|
179
|
+
try:
|
|
180
|
+
path.rename(trash)
|
|
181
|
+
except OSError:
|
|
182
|
+
trash = path
|
|
183
|
+
if trash.is_dir() and not trash.is_symlink():
|
|
184
|
+
shutil.rmtree(trash, ignore_errors=True)
|
|
185
|
+
else:
|
|
186
|
+
with contextlib.suppress(OSError):
|
|
187
|
+
trash.unlink()
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def _owned(root: Path) -> bool:
|
|
191
|
+
return (root / MARKER).is_file()
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def clear_cache(
|
|
195
|
+
*,
|
|
196
|
+
older_than: Union[str, float, None] = None,
|
|
197
|
+
max_size: Union[str, int, None] = None,
|
|
198
|
+
dry_run: bool = False,
|
|
199
|
+
) -> dict[str, Any]:
|
|
200
|
+
"""Delete cache entries: everything, or those unused for ``older_than`` (e.g. ``"30d"``), then the least
|
|
201
|
+
recently used until the cache is below ``max_size`` (e.g. ``"1GB"``). Returns what was (or with
|
|
202
|
+
``dry_run=True`` would be) removed. Only a folder EvalSuite created is touched."""
|
|
203
|
+
root = cache_dir()
|
|
204
|
+
if not root.is_dir():
|
|
205
|
+
return {"path": str(root), "removed": [], "freed_bytes": 0, "dry_run": dry_run}
|
|
206
|
+
if not _owned(root):
|
|
207
|
+
raise InputValidationError(
|
|
208
|
+
f"{root} was not created by EvalSuite (no {MARKER} file); refusing to delete anything in it."
|
|
209
|
+
)
|
|
210
|
+
age = _parse_age(older_than)
|
|
211
|
+
limit = _parse_size(max_size)
|
|
212
|
+
now = time.time()
|
|
213
|
+
entries = sorted(_entries(root), key=lambda e: e[2]) # least recently used first
|
|
214
|
+
doomed: list[tuple[Path, int]] = []
|
|
215
|
+
if age is None and limit is None:
|
|
216
|
+
doomed = [(p, s) for p, s, _ in entries]
|
|
217
|
+
else:
|
|
218
|
+
keep = []
|
|
219
|
+
for p, s, last in entries:
|
|
220
|
+
(doomed.append((p, s)) if age is not None and now - last > age else keep.append((p, s)))
|
|
221
|
+
if limit is not None:
|
|
222
|
+
total = sum(s for _, s in keep)
|
|
223
|
+
for p, s in keep:
|
|
224
|
+
if total <= limit:
|
|
225
|
+
break
|
|
226
|
+
doomed.append((p, s))
|
|
227
|
+
total -= s
|
|
228
|
+
if not dry_run:
|
|
229
|
+
for p, _ in doomed:
|
|
230
|
+
_remove(p, root)
|
|
231
|
+
for leftover in root.glob(".trash-*"): # from an interrupted earlier run
|
|
232
|
+
_remove(leftover, root)
|
|
233
|
+
for top in root.iterdir(): # drop section folders left empty
|
|
234
|
+
if top.is_dir() and top.name not in _KEEP and not top.name.startswith(".") and not any(top.iterdir()):
|
|
235
|
+
top.rmdir()
|
|
236
|
+
return {
|
|
237
|
+
"path": str(root),
|
|
238
|
+
"removed": [p.relative_to(root).as_posix() for p, _ in doomed],
|
|
239
|
+
"freed_bytes": sum(s for _, s in doomed),
|
|
240
|
+
"dry_run": dry_run,
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def auto_clean(*, force: bool = False) -> Optional[dict[str, Any]]:
|
|
245
|
+
"""The automatic clearing (see the module docstring): runs at most once a day unless ``force``; never
|
|
246
|
+
raises."""
|
|
247
|
+
try:
|
|
248
|
+
auto, age, size = _settings()
|
|
249
|
+
root = cache_dir()
|
|
250
|
+
if not (auto or force) or not root.is_dir() or not _owned(root):
|
|
251
|
+
return None
|
|
252
|
+
stamp = root / _STAMP
|
|
253
|
+
if not force and stamp.exists() and time.time() - stamp.stat().st_mtime < 86400:
|
|
254
|
+
return None
|
|
255
|
+
stamp.write_text(str(time.time()))
|
|
256
|
+
return clear_cache(older_than=age, max_size=size)
|
|
257
|
+
except Exception:
|
|
258
|
+
return None
|
evalsuite/cards.py
CHANGED
|
@@ -228,7 +228,7 @@ class ReportCard:
|
|
|
228
228
|
def to_docx(self, path: str, *, digits: int = 3) -> None:
|
|
229
229
|
"""Write a Word document with the paragraph, the table and (model card) the narrative sections."""
|
|
230
230
|
try:
|
|
231
|
-
import docx # type: ignore[import-not-found]
|
|
231
|
+
import docx # type: ignore[import-not-found, unused-ignore]
|
|
232
232
|
except ImportError as exc:
|
|
233
233
|
raise OptionalDependencyError("python-docx", "docx", "ReportCard.to_docx") from exc
|
|
234
234
|
doc = docx.Document()
|
evalsuite/cli/main.py
CHANGED
|
@@ -461,6 +461,33 @@ def cmd_upgrade(args: argparse.Namespace) -> int:
|
|
|
461
461
|
return upgrade()
|
|
462
462
|
|
|
463
463
|
|
|
464
|
+
def cmd_cache(args: argparse.Namespace) -> int:
|
|
465
|
+
from ..cache import _human, cache_info, clear_cache
|
|
466
|
+
|
|
467
|
+
if args.action == "info":
|
|
468
|
+
print(cache_info().summary())
|
|
469
|
+
return 0
|
|
470
|
+
everything = args.older_than is None and args.max_size is None
|
|
471
|
+
if everything and not (args.yes or args.dry_run):
|
|
472
|
+
info = cache_info()
|
|
473
|
+
if not info.entries:
|
|
474
|
+
print(f"The cache is already empty ({info.path}).")
|
|
475
|
+
return 0
|
|
476
|
+
answer = input(
|
|
477
|
+
f"Delete all {len(info.entries)} cache entries ({_human(info.size_bytes)}) in {info.path}? [y/N] "
|
|
478
|
+
)
|
|
479
|
+
if answer.strip().lower() not in ("y", "yes"):
|
|
480
|
+
print("Nothing deleted.")
|
|
481
|
+
return 1
|
|
482
|
+
out = clear_cache(older_than=args.older_than, max_size=args.max_size, dry_run=args.dry_run)
|
|
483
|
+
verb = "Would free" if args.dry_run else "Freed"
|
|
484
|
+
k = len(out["removed"])
|
|
485
|
+
print(f"{verb} {_human(out['freed_bytes'])} ({k} entr{'y' if k == 1 else 'ies'}) in {out['path']}.")
|
|
486
|
+
for name in out["removed"][:20]:
|
|
487
|
+
print(f" {name}")
|
|
488
|
+
return 0
|
|
489
|
+
|
|
490
|
+
|
|
464
491
|
def cmd_version(args: argparse.Namespace) -> int:
|
|
465
492
|
from .._update import check_for_update
|
|
466
493
|
|
|
@@ -672,6 +699,16 @@ def build_parser() -> argparse.ArgumentParser:
|
|
|
672
699
|
p.add_argument("--force", action="store_true", help="run pip even if this is already the latest release")
|
|
673
700
|
p.set_defaults(func=cmd_upgrade)
|
|
674
701
|
|
|
702
|
+
p = sub.add_parser(
|
|
703
|
+
"cache", help="show or clear EvalSuite's cache of downloaded data (cleared automatically too)"
|
|
704
|
+
)
|
|
705
|
+
p.add_argument("action", choices=["info", "clear"], help="info: location and size; clear: delete entries")
|
|
706
|
+
p.add_argument("--older-than", help="clear only entries unused for this long, e.g. 30d, 12h, 2w")
|
|
707
|
+
p.add_argument("--max-size", help="clear least recently used entries until the cache is below this, e.g. 1GB")
|
|
708
|
+
p.add_argument("--dry-run", action="store_true", help="list what would be deleted without deleting it")
|
|
709
|
+
p.add_argument("-y", "--yes", action="store_true", help="do not ask before clearing everything")
|
|
710
|
+
p.set_defaults(func=cmd_cache)
|
|
711
|
+
|
|
675
712
|
p = sub.add_parser("version", help="show the installed version (--check: compare with PyPI)")
|
|
676
713
|
p.add_argument("--check", action="store_true", help="also look up the latest release on PyPI")
|
|
677
714
|
p.set_defaults(func=cmd_version)
|
evalsuite/core/registry.py
CHANGED
|
@@ -99,6 +99,10 @@ def register(
|
|
|
99
99
|
|
|
100
100
|
def list_metrics(category: Optional[str] = None) -> list[str]:
|
|
101
101
|
"""Sorted metric ids, optionally filtered by category (``"classification"``, ``"regression"``)."""
|
|
102
|
+
if category is not None and not isinstance(category, str):
|
|
103
|
+
from .exceptions import InputValidationError
|
|
104
|
+
|
|
105
|
+
raise InputValidationError(f"category must be a name such as 'classification'; got {category!r}.")
|
|
102
106
|
_load_all()
|
|
103
107
|
return sorted(k for k, v in _REGISTRY.items() if category is None or v.category == category)
|
|
104
108
|
|
evalsuite/core/validation.py
CHANGED
|
@@ -29,6 +29,24 @@ __all__ = [
|
|
|
29
29
|
TargetType = Literal["binary", "multiclass", "multilabel", "continuous"]
|
|
30
30
|
|
|
31
31
|
|
|
32
|
+
def numeric(x: Any, name: str) -> NDArray[Any]:
|
|
33
|
+
"""``np.asarray(x, dtype=float64)`` with an :class:`InputValidationError` naming ``name`` when ``x`` holds
|
|
34
|
+
values that are not numbers (strings, None, objects)."""
|
|
35
|
+
try:
|
|
36
|
+
return np.asarray(x, dtype=np.float64)
|
|
37
|
+
except (TypeError, ValueError):
|
|
38
|
+
sample = next((v for v in np.asarray(x, dtype=object).ravel() if not _is_number(v)), None)
|
|
39
|
+
raise InputValidationError(f"{name} must contain numbers; found {sample!r}.") from None
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _is_number(v: Any) -> bool:
|
|
43
|
+
try:
|
|
44
|
+
float(v)
|
|
45
|
+
except (TypeError, ValueError):
|
|
46
|
+
return False
|
|
47
|
+
return True
|
|
48
|
+
|
|
49
|
+
|
|
32
50
|
def to_numpy(x: ArrayLike, name: str, *, allow_2d: bool = False) -> NDArray[Any]:
|
|
33
51
|
"""Convert array-likes (lists, NumPy arrays, pandas objects) to a NumPy array without copying
|
|
34
52
|
when possible. Raises :class:`InputValidationError` for None, scalars, empty input or bad shapes."""
|
|
@@ -118,6 +136,8 @@ def _has_fraction(y: NDArray[Any]) -> bool:
|
|
|
118
136
|
"""Whether any value is non-integral. Real-valued targets almost always show it in the first few values,
|
|
119
137
|
so a short leading chunk is checked before the whole array."""
|
|
120
138
|
flat = y.ravel()
|
|
139
|
+
if flat.dtype.kind == "f" and not np.all(np.isfinite(flat)):
|
|
140
|
+
return True # NaN / infinity: not integer labels (finiteness is checked and reported elsewhere)
|
|
121
141
|
head = flat[:1024]
|
|
122
142
|
if not np.all(np.mod(head, 1) == 0):
|
|
123
143
|
return True
|
|
@@ -188,7 +208,7 @@ def validate_probabilities(
|
|
|
188
208
|
) -> FloatArray:
|
|
189
209
|
"""Probabilities in [0, 1]. For multiclass (2-D), one column per class and rows summing to 1.
|
|
190
210
|
Multilabel probabilities are independent per label (``rows_sum_to_one=False``)."""
|
|
191
|
-
p = to_numpy(y_prob, name, allow_2d=True)
|
|
211
|
+
p = numeric(to_numpy(y_prob, name, allow_2d=True), name)
|
|
192
212
|
check_finite(p, name)
|
|
193
213
|
if p.shape[0] != n:
|
|
194
214
|
raise InputValidationError(
|
evalsuite/llm_benchmarks.py
CHANGED
|
@@ -42,6 +42,8 @@ class BenchmarkSpec:
|
|
|
42
42
|
|
|
43
43
|
def format_multiple_choice(question: str, choices: list[str], *, instruction: Optional[str] = None) -> str:
|
|
44
44
|
"""A standard multiple-choice prompt: the question, lettered options and "Answer:"."""
|
|
45
|
+
if not isinstance(question, str) or isinstance(choices, str):
|
|
46
|
+
raise InputValidationError("format_multiple_choice takes a question string and a list of option strings.")
|
|
45
47
|
if len(choices) > 26:
|
|
46
48
|
raise InputValidationError("At most 26 options are supported.")
|
|
47
49
|
lines = [question.strip(), ""]
|
|
@@ -178,12 +180,17 @@ def load_benchmark(
|
|
|
178
180
|
"""Items of a benchmark as records with ``id``, ``prompt``, ``reference`` (and ``choices`` / ``category``
|
|
179
181
|
where they exist), ready to prompt a model and to pass as ``references`` to :func:`evalsuite.leaderboard`.
|
|
180
182
|
Downloads from the Hugging Face Hub with the optional ``datasets`` package
|
|
181
|
-
(``pip install "evalsuite-python[benchmarks]"``)
|
|
183
|
+
(``pip install "evalsuite-python[benchmarks]"``) into EvalSuite's cache (``evalsuite cache info``), unless
|
|
184
|
+
``cache_dir`` is given."""
|
|
182
185
|
s = spec(name)
|
|
183
186
|
try:
|
|
184
187
|
import datasets # type: ignore[import-not-found]
|
|
185
188
|
except ImportError as exc:
|
|
186
189
|
raise OptionalDependencyError("datasets", "benchmarks", "load_benchmark") from exc
|
|
190
|
+
if cache_dir is None:
|
|
191
|
+
from .cache import cache_dir as _cache_dir
|
|
192
|
+
|
|
193
|
+
cache_dir = str(_cache_dir(create=True) / "datasets")
|
|
187
194
|
ds = datasets.load_dataset(s.hf_path, s.hf_config, split=split or s.split, cache_dir=cache_dir)
|
|
188
195
|
out = []
|
|
189
196
|
for i, row in enumerate(ds):
|
evalsuite/llmsys/longcontext.py
CHANGED
|
@@ -15,6 +15,7 @@ import numpy as np
|
|
|
15
15
|
from ..core.exceptions import InputValidationError
|
|
16
16
|
from ..core.registry import register
|
|
17
17
|
from ..core.result import MetricResult
|
|
18
|
+
from ..core.validation import numeric
|
|
18
19
|
from ._common import bools, floats, group_agreement, lists_of, ragged_numbers, rate, same_length, seq
|
|
19
20
|
|
|
20
21
|
__all__ = [
|
|
@@ -124,7 +125,7 @@ def retrieval_accuracy_by_length(correct: Any, context_lengths: Any, *, threshol
|
|
|
124
125
|
)
|
|
125
126
|
def needle_in_haystack(correct: Any, context_lengths: Any, depths: Any) -> MetricResult:
|
|
126
127
|
"""``depths``: where the needle was placed, as a fraction of the context in [0, 1]."""
|
|
127
|
-
c = floats(
|
|
128
|
+
c = floats(numeric(seq(correct, "correct"), "correct"), "correct", lo=0, hi=1)
|
|
128
129
|
L = floats(context_lengths, "context_lengths", lo=0)
|
|
129
130
|
d = floats(depths, "depths", lo=0, hi=1)
|
|
130
131
|
same_length(("correct", c), ("context_lengths", L), ("depths", d))
|
|
@@ -163,7 +164,7 @@ def needle_in_haystack(correct: Any, context_lengths: Any, depths: Any) -> Metri
|
|
|
163
164
|
)
|
|
164
165
|
def position_accuracy(correct: Any, positions: Any, *, n_bins: int = 5) -> MetricResult:
|
|
165
166
|
"""``positions``: relative position of the relevant passage in [0, 1] (0 = start)."""
|
|
166
|
-
c = floats(
|
|
167
|
+
c = floats(numeric(seq(correct, "correct"), "correct"), "correct", lo=0, hi=1)
|
|
167
168
|
p = floats(positions, "positions", lo=0, hi=1)
|
|
168
169
|
same_length(("correct", c), ("positions", p))
|
|
169
170
|
if isinstance(n_bins, bool) or not isinstance(n_bins, int) or n_bins < 2:
|
|
@@ -191,7 +192,7 @@ def position_accuracy(correct: Any, positions: Any, *, n_bins: int = 5) -> Metri
|
|
|
191
192
|
higher_is_better=False,
|
|
192
193
|
)
|
|
193
194
|
def lost_in_the_middle(correct: Any, positions: Any, *, edge: float = 0.2) -> MetricResult:
|
|
194
|
-
c = floats(
|
|
195
|
+
c = floats(numeric(seq(correct, "correct"), "correct"), "correct", lo=0, hi=1)
|
|
195
196
|
p = floats(positions, "positions", lo=0, hi=1)
|
|
196
197
|
same_length(("correct", c), ("positions", p))
|
|
197
198
|
if not 0 < edge < 0.5:
|
evalsuite/llmsys/multilingual.py
CHANGED
|
@@ -17,6 +17,7 @@ import numpy as np
|
|
|
17
17
|
from ..core.exceptions import InputValidationError
|
|
18
18
|
from ..core.registry import register
|
|
19
19
|
from ..core.result import MetricResult
|
|
20
|
+
from ..core.validation import numeric
|
|
20
21
|
from ._common import bools, by_group, floats, group_agreement, rate, same_length, seq
|
|
21
22
|
|
|
22
23
|
__all__ = [
|
|
@@ -106,7 +107,7 @@ def language_id_accuracy(true_languages: Any, predicted_languages: Any) -> Metri
|
|
|
106
107
|
|
|
107
108
|
|
|
108
109
|
def _unit(x: Any, name: str) -> np.ndarray:
|
|
109
|
-
a =
|
|
110
|
+
a = numeric(x, "x")
|
|
110
111
|
if a.ndim != 2 or a.shape[0] < 2:
|
|
111
112
|
raise InputValidationError(f"{name} must be a 2-D array with at least two rows (one per sentence).")
|
|
112
113
|
if not np.all(np.isfinite(a)):
|
evalsuite/llmsys/robustness.py
CHANGED
|
@@ -19,6 +19,7 @@ import numpy as np
|
|
|
19
19
|
from ..core.exceptions import InputValidationError
|
|
20
20
|
from ..core.registry import register
|
|
21
21
|
from ..core.result import MetricResult
|
|
22
|
+
from ..core.validation import numeric
|
|
22
23
|
from ._common import bools, floats, group_agreement, lists_of, rate, same_length, seq
|
|
23
24
|
|
|
24
25
|
__all__ = [
|
|
@@ -448,12 +449,9 @@ def prompt_sensitivity(correct_by_template: Any) -> MetricResult:
|
|
|
448
449
|
under every template; or a 2-D array (templates × examples)."""
|
|
449
450
|
if isinstance(correct_by_template, Mapping):
|
|
450
451
|
names = [str(k) for k in correct_by_template]
|
|
451
|
-
mat = [
|
|
452
|
-
floats(np.asarray(v, dtype=float), f"correct_by_template[{k!r}]")
|
|
453
|
-
for k, v in correct_by_template.items()
|
|
454
|
-
]
|
|
452
|
+
mat = [floats(numeric(v, "v"), f"correct_by_template[{k!r}]") for k, v in correct_by_template.items()]
|
|
455
453
|
else:
|
|
456
|
-
arr =
|
|
454
|
+
arr = numeric(correct_by_template, "correct_by_template")
|
|
457
455
|
if arr.ndim != 2:
|
|
458
456
|
raise InputValidationError(
|
|
459
457
|
"correct_by_template must be a mapping or a 2-D array (templates × examples)."
|
|
@@ -495,7 +493,7 @@ def prompt_sensitivity(correct_by_template: Any) -> MetricResult:
|
|
|
495
493
|
higher_is_better=True,
|
|
496
494
|
)
|
|
497
495
|
def truncation_sensitivity(correct: Any, context_lengths: Any) -> MetricResult:
|
|
498
|
-
c = floats(
|
|
496
|
+
c = floats(numeric(seq(correct, "correct"), "correct"), "correct")
|
|
499
497
|
lens = floats(context_lengths, "context_lengths", lo=1)
|
|
500
498
|
same_length(("correct", c), ("context_lengths", lens))
|
|
501
499
|
levels = np.unique(lens)
|
evalsuite/llmsys/safety.py
CHANGED
|
@@ -19,6 +19,7 @@ from .._native import core
|
|
|
19
19
|
from ..core.exceptions import InputValidationError
|
|
20
20
|
from ..core.registry import register
|
|
21
21
|
from ..core.result import MetricResult
|
|
22
|
+
from ..core.validation import numeric
|
|
22
23
|
from ._common import bools, by_group, floats, lists_of, ragged_numbers, rate, same_length, seq, wilson
|
|
23
24
|
|
|
24
25
|
__all__ = [
|
|
@@ -298,7 +299,7 @@ def stereotype_preference(
|
|
|
298
299
|
|
|
299
300
|
|
|
300
301
|
def _unit(x: Any, name: str) -> np.ndarray:
|
|
301
|
-
a =
|
|
302
|
+
a = numeric(x, "x")
|
|
302
303
|
if a.ndim != 2 or a.shape[0] < 1:
|
|
303
304
|
raise InputValidationError(f"{name} must be a 2-D array (one embedding per row).")
|
|
304
305
|
if not np.all(np.isfinite(a)):
|