Spaces:
Running on CPU Upgrade
Running on CPU Upgrade
File size: 15,991 Bytes
b78ff28 49442cb b78ff28 580f4e5 b78ff28 580f4e5 b78ff28 49442cb b78ff28 49442cb b78ff28 49442cb b78ff28 49442cb b78ff28 49442cb b78ff28 49442cb b78ff28 49442cb b78ff28 49442cb b78ff28 49442cb b78ff28 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 | """Submission bundle validation.
A PLUG submission is a single ``.zip`` carrying one file per benchmark. This
module is the one place that decides whether such a bundle is scorable, and it
runs in three places against the same rules: in the Space before a submission is
accepted, in ``plug_challenge.cli`` so participants can check a bundle locally
before uploading, and in the tests.
Every check produces a ``SubmissionError`` naming the benchmark it belongs to, so
the Space can show a participant every problem in their bundle at once instead of
one per upload attempt.
"""
import zipfile
from dataclasses import dataclass, field
from pathlib import Path
import numpy as np
import pandas as pd
from loguru import logger
from .benchmarks import BENCHMARK_NAMES, BENCHMARKS, ID_COLUMN, BenchmarkSpec
# Reject a prediction column whose standard deviation is below this, for the
# benchmarks scored by a rank statistic: a constant column makes Spearman and
# AUROC undefined, and near-constant columns with a dither of noise are the usual
# way that gets smuggled past an equality check. Fmax is exempt β see
# BenchmarkSpec.needs_varying_predictions.
MIN_PREDICTION_STD = 1e-9
# Entries a zip archive may carry that are not submission files. macOS's
# Archive Utility adds both.
_IGNORED_ZIP_PREFIXES = ("__MACOSX/", ".")
@dataclass(frozen=True)
class SubmissionError:
"""A single reason a bundle cannot be scored.
Attributes
----------
benchmark : str
Which benchmark the problem is in, or ``"bundle"`` for a problem with
the archive itself.
message : str
Participant-facing description, specific enough to act on without
needing the scorer's source.
"""
benchmark: str
message: str
def __str__(self) -> str:
"""Render as ``benchmark: message`` for display on the Space."""
return f"{self.benchmark}: {self.message}"
@dataclass
class ValidationResult:
"""The outcome of validating one bundle.
Attributes
----------
errors : list[SubmissionError]
Problems that make the bundle unscorable. Empty means it is scorable.
warnings : list[SubmissionError]
Problems worth telling the participant about that do not block scoring β
today, only a benchmark left out of a bundle when the challenge accepts
partial ones.
frames : dict[str, pd.DataFrame]
Per-benchmark parsed predictions, populated only for the benchmarks that
validated cleanly β so a caller can score a partial bundle when the
challenge allows it.
"""
errors: list[SubmissionError] = field(default_factory=list)
warnings: list[SubmissionError] = field(default_factory=list)
frames: dict[str, pd.DataFrame] = field(default_factory=dict)
@property
def ok(self) -> bool:
"""True when the bundle can be scored (warnings do not count)."""
return not self.errors
def add(self, benchmark: str, message: str) -> None:
"""Record a blocking problem."""
self.errors.append(SubmissionError(benchmark=benchmark, message=message))
def warn(self, benchmark: str, message: str) -> None:
"""Record a non-blocking problem."""
self.warnings.append(SubmissionError(benchmark=benchmark, message=message))
def report(self, limit: int = 12) -> str:
"""Format the errors as a participant-facing message.
Parameters
----------
limit : int
Maximum number of errors to list before summarising the remainder,
so a badly wrong bundle does not produce an unreadable wall of text.
Returns
-------
str
One bullet per error.
"""
problems = self.errors or self.warnings
if not problems:
return "Bundle is valid."
lines = [f"- {problem}" for problem in problems[:limit]]
if len(problems) > limit:
lines.append(f"- ...and {len(problems) - limit} more.")
return "\n".join(lines)
def read_table(path: Path) -> pd.DataFrame:
"""Read a submission file, accepting either CSV or Parquet.
Parameters
----------
path : Path
Path to a ``.csv`` or ``.parquet`` file.
Returns
-------
pd.DataFrame
The parsed table.
Raises
------
ValueError
If the suffix is neither ``.csv`` nor ``.parquet``.
"""
suffix = path.suffix.lower()
if suffix == ".parquet":
return pd.read_parquet(path)
if suffix == ".csv":
return pd.read_csv(path)
raise ValueError(f"Expected a .csv or .parquet file, got {path.name!r}")
def bundle_members(bundle_path: Path) -> dict[str, str]:
"""Map each benchmark name to its entry in the bundle.
Matching is on the file's basename with its extension dropped, so a bundle
zipped from a directory (``plug_submission/megascale.csv``) works as well as
one zipped from loose files, and either ``.csv`` or ``.parquet`` is accepted
per benchmark.
Parameters
----------
bundle_path : Path
The uploaded ``.zip``.
Returns
-------
dict[str, str]
Benchmark name -> zip entry name, for the benchmarks present.
"""
found: dict[str, str] = {}
with zipfile.ZipFile(bundle_path) as archive:
for entry in archive.namelist():
if entry.endswith("/") or any(
part.startswith(_IGNORED_ZIP_PREFIXES) for part in entry.split("/")
):
continue
stem = Path(entry).stem
suffix = Path(entry).suffix.lower()
if stem in BENCHMARK_NAMES and suffix in (".csv", ".parquet"):
# A bundle listing the same benchmark twice (e.g. both a .csv and a
# .parquet) is ambiguous rather than harmless β keep the first and
# let validate_bundle report the duplicate.
found.setdefault(stem, entry)
return found
def validate_bundle(
bundle_path: Path,
expected_ids: dict[str, set[str]],
require_complete: bool = True,
) -> ValidationResult:
"""Validate a submission bundle end to end.
Parameters
----------
bundle_path : Path
The uploaded ``.zip``.
expected_ids : dict[str, set[str]]
Benchmark name -> the set of ``datapoint_id`` values the submission's
track covers (the Lo-Hi test rows, or every row), taken from the ground
truth or the public manifest. A benchmark missing from this map is
treated as not currently scorable and is skipped with an error.
require_complete : bool
When True (the challenge default), a bundle missing any benchmark is
rejected. When False, missing benchmarks are recorded as errors but the
benchmarks that are present still parse into ``frames``.
Returns
-------
ValidationResult
Errors found, and the parsed frames for the benchmarks that passed.
"""
result = ValidationResult()
if not bundle_path.exists():
result.add("bundle", f"File not found: {bundle_path}")
return result
if bundle_path.suffix.lower() != ".zip":
result.add(
"bundle",
f"Submissions must be a single .zip archive, got {bundle_path.suffix!r}.",
)
return result
try:
members = bundle_members(bundle_path)
except zipfile.BadZipFile as exc:
result.add("bundle", f"Could not read the zip archive β {exc}")
return result
if not members:
result.add(
"bundle",
"The archive holds none of the benchmark files. Expected one file per "
"benchmark, named <benchmark>.csv or <benchmark>.parquet.",
)
return result
missing = [name for name in BENCHMARK_NAMES if name not in members]
if missing:
message = (
f"Missing {len(missing)} of {len(BENCHMARK_NAMES)} benchmark files: "
f"{', '.join(missing)}. Expected one file per benchmark, named "
f"<benchmark>.csv or <benchmark>.parquet."
)
if require_complete:
result.add("bundle", message)
return result
# Partial bundles are allowed here, so an absent benchmark is something to
# report rather than a reason to refuse: the rest still scores, and each
# absent benchmark counts as chance in the PLUG Score.
result.warn("bundle", message)
with zipfile.ZipFile(bundle_path) as archive:
for spec in BENCHMARKS:
entry = members.get(spec.name)
if entry is None:
continue
if spec.name not in expected_ids:
result.add(
spec.name,
"This benchmark is not open for scoring yet β remove it from the "
"bundle or check the challenge status.",
)
continue
frame = _read_member(archive, entry, spec, result)
if frame is None:
continue
before = len(result.errors)
_validate_frame(frame, spec, expected_ids[spec.name], result)
if len(result.errors) == before:
result.frames[spec.name] = frame
logger.info(
"Validated bundle {}: {} benchmark(s) parsed, {} error(s), {} warning(s).",
bundle_path.name,
len(result.frames),
len(result.errors),
len(result.warnings),
)
return result
def _read_member(
archive: zipfile.ZipFile, entry: str, spec: BenchmarkSpec, result: ValidationResult
) -> pd.DataFrame | None:
"""Read one benchmark's file out of the bundle, recording a parse failure.
``datapoint_id`` is always read as a string: most ids are bare row numbers
(``"1234"``), which a CSV reader would otherwise parse as integers that no
longer join against the ground truth.
"""
try:
with archive.open(entry) as handle:
if entry.lower().endswith(".parquet"):
frame = pd.read_parquet(handle)
else:
frame = pd.read_csv(handle, dtype={ID_COLUMN: str})
except Exception as exc:
result.add(spec.name, f"Could not read {entry!r} β {exc}")
return None
if ID_COLUMN in frame.columns:
frame[ID_COLUMN] = frame[ID_COLUMN].astype(str)
return frame
def _validate_frame(
frame: pd.DataFrame,
spec: BenchmarkSpec,
expected: set[str],
result: ValidationResult,
) -> None:
"""Apply every schema and value check for one benchmark."""
absent = [column for column in spec.required_columns if column not in frame.columns]
if absent:
result.add(
spec.name,
f"Missing required column(s): {', '.join(absent)}. Expected "
f"{', '.join(spec.required_columns)} (column names are case-sensitive).",
)
return
if frame.empty:
result.add(spec.name, "File has no rows.")
return
ids = frame[ID_COLUMN].astype(str)
if spec.long_form:
_validate_long_form(frame, ids, spec, expected, result)
else:
_validate_row_per_datapoint(ids, spec, expected, result)
for column in spec.pred_columns:
_validate_predictions(frame[column], column, spec, result)
def _validate_row_per_datapoint(
ids: pd.Series, spec: BenchmarkSpec, expected: set[str], result: ValidationResult
) -> None:
"""Require exactly one row per scored datapoint, no duplicates, nothing extra."""
duplicated = ids[ids.duplicated()].unique()
if duplicated.size:
result.add(
spec.name,
f"{duplicated.size} duplicated {ID_COLUMN} value(s), e.g. "
f"{', '.join(map(str, duplicated[:3]))}. Exactly one row per "
f"{spec.unit} is expected.",
)
submitted = set(ids)
if submitted == expected:
return
absent, unknown = expected - submitted, submitted - expected
if absent:
result.add(
spec.name,
f"{len(absent)} of {len(expected)} {spec.unit}s in this track have no prediction, "
f"e.g. {', '.join(sorted(absent)[:3])}.",
)
if unknown:
result.add(
spec.name,
f"{len(unknown)} {ID_COLUMN} value(s) are not scored in this track, e.g. "
f"{', '.join(sorted(unknown)[:3])}. Submit predictions for this track's "
f"rows of the benchmark's manifest and nothing else.",
)
def _validate_long_form(
frame: pd.DataFrame,
ids: pd.Series,
spec: BenchmarkSpec,
expected: set[str],
result: ValidationResult,
) -> None:
"""Validate a variable-length submission (cafa5): a set of (id, term) pairs.
Unlike a row-per-datapoint benchmark, declining to predict a target is
allowed here β that is what Fmax's coverage term measures β so a missing id
is not an error. Predicting a target outside the track still is.
"""
unknown = set(ids) - expected
if unknown:
result.add(
spec.name,
f"{len(unknown)} {ID_COLUMN} value(s) are not scored in this track, e.g. "
f"{', '.join(sorted(unknown)[:3])}.",
)
for column in spec.extra_columns:
blank = frame[column].isna() | (frame[column].astype(str).str.strip() == "")
if blank.any():
result.add(spec.name, f"{int(blank.sum())} row(s) have an empty {column!r}.")
for column, allowed in spec.allowed_values.items():
bad = ~frame[column].astype(str).str.strip().str.lower().isin(allowed)
if bad.any():
result.add(
spec.name,
f"{int(bad.sum())} row(s) have an unrecognised {column!r}; expected "
f"one of {', '.join(allowed)}.",
)
pair_columns = [ID_COLUMN, *spec.extra_columns]
duplicated = frame.duplicated(subset=pair_columns)
if duplicated.any():
result.add(
spec.name,
f"{int(duplicated.sum())} duplicated ({', '.join(pair_columns)}) pair(s). "
"Predict each term at most once per protein.",
)
covered = len(set(ids) & expected)
if covered == 0:
result.add(
spec.name,
f"No row refers to a {spec.unit} in this track; nothing could be scored.",
)
def _validate_predictions(
column: pd.Series, name: str, spec: BenchmarkSpec, result: ValidationResult
) -> None:
"""Check one prediction column is numeric, finite, in range, and not constant."""
values = pd.to_numeric(column, errors="coerce")
non_numeric = values.isna() & column.notna()
if non_numeric.any():
result.add(
spec.name,
f"Column {name!r} has {int(non_numeric.sum())} non-numeric value(s).",
)
return
if values.isna().any():
result.add(
spec.name,
f"Column {name!r} has {int(values.isna().sum())} missing value(s); every "
"prediction is required.",
)
return
finite = np.isfinite(values.to_numpy(dtype=float))
if not finite.all():
result.add(
spec.name,
f"Column {name!r} has {int((~finite).sum())} infinite value(s).",
)
return
if spec.score_range is not None:
low, high = spec.score_range
outside = (values < low) | (values > high)
if outside.any():
result.add(
spec.name,
f"Column {name!r} has {int(outside.sum())} value(s) outside "
f"[{low}, {high}].",
)
if spec.needs_varying_predictions and float(values.std()) < MIN_PREDICTION_STD:
result.add(
spec.name,
f"Column {name!r} is constant (or all but constant). This benchmark's "
"metrics are rank statistics, so a constant column cannot be scored β "
"please submit real model outputs.",
)
|