Spaces:
Running on CPU Upgrade
Running on CPU Upgrade
File size: 15,958 Bytes
b78ff28 49442cb b78ff28 49442cb b78ff28 49442cb b78ff28 49442cb b78ff28 49442cb b78ff28 49442cb b78ff28 49442cb b78ff28 49442cb b78ff28 49442cb b78ff28 49442cb b78ff28 49442cb b78ff28 49442cb b78ff28 49442cb b78ff28 49442cb b78ff28 49442cb b78ff28 49442cb b78ff28 49442cb 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 | """The Submit tab: validate, score and record one submission bundle.
Because PLUG is not blinded, everything happens inside the request β the bundle
is validated, scored against the held-back labels, stored, and added to the
leaderboard before the participant's status box updates. There is no queue and
nothing to wait for, so the response can show the participant their own
{n} metrics and their PLUG Score immediately.
The order of operations matters. The bundle is validated *before* anything is
uploaded, so a malformed submission costs the participant nothing and does not
start their cooldown; the bundle and metadata are stored before the leaderboard
is touched, so a failure part-way through leaves a recoverable record rather
than a leaderboard row with no submission behind it.
"""
import re
from datetime import datetime, timedelta
from pathlib import Path
import gradio as gr
import pandas as pd
from loguru import logger
from config import (
BENCHMARK_COUNT,
BOOTSTRAP_SAMPLES,
BUNDLE_TREE_MD,
CURRENT_PHASE,
DATASET_DOWNLOAD_LINK,
HOURS_BETWEEN_SUBMISSIONS,
REQUIRE_COMPLETE_BUNDLE,
SUBMISSION_SCHEMAS_MD,
TUTORIAL_LINK,
)
from models import Submission
from plug_challenge import BENCHMARKS, aggregate, scoring, store
from plug_challenge.benchmarks import TRACK_DESCRIPTIONS, TRACK_LABELS, TRACKS
from plug_challenge.validation import validate_bundle
from utils import (
BANNED_USERNAMES,
safeify_username,
validate_hf_username,
validate_model_details,
)
EMAIL_RE = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")
_TRACKS_MD = "\n".join(
f"- **{TRACK_LABELS[track]}** β {TRACK_DESCRIPTIONS[track]}" for track in TRACKS
)
_INTRO_MD = f"""New to the challenge? The [PLUG baselines]({TUTORIAL_LINK}) walk through
loading each benchmark and producing predictions. The [challenge dataset]({DATASET_DOWNLOAD_LINK})
holds the row ids and Lo-Hi splits; the labels come from each benchmark's original source.
Every submission enters one of two leaderboards:
{_TRACKS_MD}
A submission is **one `.zip`** containing one file per benchmark
({BENCHMARK_COUNT} files{", all required" if REQUIRE_COMPLETE_BUNDLE else ""}):
{BUNDLE_TREE_MD}
Build the skeleton for your track and check it before uploading:
```bash
pip install "plug-challenge @ git+https://huggingface.co/spaces/PrismScienceOrg/PLUG-challenge"
plug-challenge template ./my_submission --track supervised # every file, ids in place
# ...fill in the prediction columns...
cd my_submission && zip ../plug_submission.zip *.csv && cd ..
plug-challenge validate plug_submission.zip --track supervised # the checks this Space runs
```
<details>
<summary><b>Per-file column reference</b></summary>
{SUBMISSION_SCHEMAS_MD}
</details>
"""
def render_submission_tab(phase: int) -> None:
"""Render the Submit tab for the current challenge phase.
Parameters
----------
phase : int
``config.CURRENT_PHASE``: 0 pre-challenge, 1 open, 2 closed.
"""
if phase == 0:
gr.Markdown(
"# Submission portal (coming soon)\n\n"
"The portal opens when the challenge begins. Please check back then."
)
return
if phase >= 2:
gr.Markdown(
"# Submission portal (closed)\n\n"
"Submissions are closed β thank you for taking part. The final standings are "
"on the **Leaderboard** tab."
)
return
gr.Markdown("# Submit your predictions")
gr.Markdown(_INTRO_MD)
with gr.Row():
with gr.Column(scale=1):
gr.Markdown("### Leaderboard identity")
track_input = gr.Radio(
choices=[(TRACK_LABELS[track], track) for track in TRACKS],
value="supervised",
label="Track *",
info="Which leaderboard this submission enters.",
)
username_input = gr.Textbox(
label="Hugging Face username *",
placeholder="your-hf-username",
info="Required. Used to track submissions and to rate-limit them.",
)
user_alias = gr.Textbox(
label="Alias (display name for the leaderboard; anonymous by default)",
placeholder="Leakage-Free Learners",
)
anon_checkbox = gr.Checkbox(
label="Submit anonymously (show the alias instead of my username)",
value=True,
)
proprietary_checkbox = gr.Checkbox(
label="I used proprietary (not publicly available) training data",
value=False,
info="Displayed publicly on the leaderboard.",
)
open_code_checkbox = gr.Checkbox(
label="My code is open-source and publicly available",
value=False,
info="Link it as your method report.",
)
model_tag = gr.Textbox(
label="Method report link *",
placeholder="https://...",
info="Required. A report, preprint or repository describing how the "
"predictions were made; shown on the leaderboard. Must start with "
"'https://' and be reachable.",
)
with gr.Column(scale=1):
gr.Markdown("### Contact & publication *(optional, private)*")
participant_name = gr.Textbox(label="Full name", placeholder="Jane Smith")
discord_username = gr.Textbox(label="Discord / contact handle")
email = gr.Textbox(label="Email", placeholder="jane@example.com")
affiliation = gr.Textbox(label="Affiliation", placeholder="University / company")
with gr.Column(scale=1):
gr.Markdown("### Bundle")
file_input = gr.File(label="plug_submission.zip *", file_types=[".zip"])
gr.Markdown(
f"One submission per account per track every "
f"**{HOURS_BETWEEN_SUBMISSIONS} hours**. Only your latest submission to "
"each track is ranked."
)
submit_btn = gr.Button("Validate, score and submit", variant="primary", size="lg")
submit_msg = gr.Markdown(visible=False)
submit_btn.click(
fn=submit_bundle,
inputs=[
username_input,
track_input,
user_alias,
anon_checkbox,
participant_name,
discord_username,
email,
affiliation,
model_tag,
proprietary_checkbox,
open_code_checkbox,
file_input,
],
outputs=[submit_msg],
)
def _error(message: str) -> dict:
"""Format a failure for the status box."""
return gr.update(value=f"### β Submission not accepted\n\n{message}", visible=True)
def _format_cooldown(last_submission: datetime, track: str) -> str:
"""Explain how long is left before this account may submit to a track again."""
next_allowed = last_submission + timedelta(hours=HOURS_BETWEEN_SUBMISSIONS)
remaining = max(0, int((next_allowed - store.now()).total_seconds()))
hours, rest = divmod(remaining, 3600)
minutes, seconds = divmod(rest, 60)
return (
f"You submitted to the {TRACK_LABELS[track].lower()} track on "
f"{last_submission.strftime('%Y-%m-%d %H:%M UTC')}. Please wait "
f"**{hours:02d}:{minutes:02d}:{seconds:02d}** before submitting to it again."
)
def _score_table_md(scores: dict[str, dict[str, float]]) -> str:
"""Render one submission's own scores as a markdown table."""
rows = [
"| Benchmark | Metric | Value | Over chance |",
"| :--- | :--- | ---: | ---: |",
]
for spec in BENCHMARKS:
if spec.name not in scores:
rows.append(f"| {spec.label} | {spec.primary.label} | *not scored* | |")
continue
value = scores[spec.name].get(f"{spec.primary.key}_mean")
if value is None or pd.isna(value):
rows.append(f"| {spec.label} | {spec.primary.label} | β | β |")
continue
normalised = aggregate.normalise(value, spec.primary)
rows.append(
f"| {spec.label} | {spec.primary.label} | {value:.4f} | {normalised:.4f} |"
)
return "\n".join(rows)
def submit_bundle(
username: str,
track: str,
user_alias: str,
anonymous: bool,
participant_name: str,
discord_username: str,
email: str,
affiliation: str,
model_tag: str,
used_proprietary_data: bool,
open_source_code: bool,
file_input: str | None,
) -> dict:
"""Handle one submission from the Submit tab.
Parameters
----------
username : str
Hugging Face username. Checked against Hugging Face to confirm the
account exists β a typo check, not an identity proof.
track : str
``supervised`` or ``unsupervised``: which rows are scored and which
leaderboard the submission enters.
user_alias : str
Display alias, required when submitting anonymously.
anonymous : bool
Show the alias instead of the username on the leaderboard.
participant_name : str
Real name (private).
discord_username : str
Contact handle (private).
email : str
Contact email (private).
affiliation : str
Institutional affiliation (private).
model_tag : str
Method report link. Required, and validated for reachability.
used_proprietary_data : bool
Whether non-public training data was used.
open_source_code : bool
Whether the method's code is public.
file_input : str | None
Path to the uploaded bundle.
Returns
-------
dict
A ``gr.update`` carrying the outcome: either the rejection reasons, or
the submission's own per-benchmark scores and PLUG Score.
"""
if CURRENT_PHASE != 1:
return _error("The submission portal is not open.")
handle = (username or "").strip()
if not handle:
return _error("A Hugging Face username is required.")
if not validate_hf_username(handle):
logger.warning("Unknown Hugging Face username: {!r}", handle)
return _error(f"Hugging Face account `{handle}` could not be found β check for typos.")
banned_reason = BANNED_USERNAMES.get(handle.lower())
if banned_reason:
logger.warning("Blocked submission from banned username {!r}", handle)
return _error(
f"Account `{handle}` is blocked. Reason: {banned_reason}. "
"Contact the organisers if you believe this is a mistake."
)
if track not in TRACKS:
return _error("Choose a track: supervised or unsupervised.")
if anonymous and not (user_alias or "").strip():
return _error(
"An alias is required when submitting anonymously β either provide one or "
"untick *Submit anonymously*."
)
if email and email.strip() and not EMAIL_RE.match(email.strip()):
return _error("That does not look like a valid email address.")
model_status = validate_model_details(model_tag)
if model_status == "Not submitted":
return _error(
"A method report link is required: a report, preprint or repository "
"describing how the predictions were made."
)
if model_status == "Invalid link":
return _error(
"Could not open the method report link. Check the URL β it must start "
"with `https://` and be publicly reachable."
)
if file_input is None:
return _error("Please upload your submission bundle.")
bundle_path = Path(file_input)
if not store.configured():
logger.error("HF_TOKEN is not set on the Space β cannot accept submissions.")
return _error(
"Submission storage is not configured on this Space. Please report this to "
"the organisers."
)
safe_username = safeify_username(handle)
last_submission = store.last_submission_at(safe_username, track)
if (
last_submission is not None
and (store.now() - last_submission).total_seconds() < HOURS_BETWEEN_SUBMISSIONS * 3600
):
return _error(_format_cooldown(last_submission, track))
# --- validate before anything is stored ---
truth = store.available_ground_truth(track)
if not truth:
return _error(
"No ground truth is staged for this challenge yet, so nothing can be scored. "
"Please report this to the organisers."
)
result = validate_bundle(
bundle_path,
expected_ids=store.expected_ids(truth),
require_complete=REQUIRE_COMPLETE_BUNDLE,
)
if not result.ok:
return _error(
"Your bundle did not pass validation. Nothing was stored and your "
f"submission cooldown has not started.\n\n{result.report()}\n\n"
"Run `plug-challenge validate` locally to iterate without uploading."
)
# --- score ---
try:
scores = scoring.score_bundle(
result.frames, truth, BENCHMARKS, bootstrap_samples=BOOTSTRAP_SAMPLES
)
except Exception as exc:
logger.exception("Scoring failed for {}: {}", handle, exc)
return _error(
"Your bundle validated but scoring failed unexpectedly. Please report this "
"to the organisers β nothing was stored."
)
submission = Submission(
username=handle,
track=track,
user_alias=(user_alias or "").strip(),
anonymous=anonymous,
participant_name=(participant_name or "").strip(),
discord_username=(discord_username or "").strip(),
email=(email or "").strip(),
affiliation=(affiliation or "").strip(),
model_report_link=model_status,
used_proprietary_data=used_proprietary_data,
open_source_code=open_source_code,
filename=bundle_path.name,
)
# --- store: bundle and metadata first, then the derived leaderboard row ---
try:
submission.bundle_path = store.upload_submission(
safe_username=submission.safe_username,
submission_id=submission.submission_id,
bundle_path=bundle_path,
metadata=submission.model_dump(),
)
entry = {
**submission.public_fields(),
"plug_score": aggregate.plug_score(scores),
**aggregate.flatten(scores),
}
store.save_scores(submission.safe_username, submission.submission_id, entry)
store.append_leaderboard_entry(entry)
except Exception as exc:
logger.exception("Storing submission {} failed: {}", submission.submission_id, exc)
return _error(
"Your bundle scored, but storing it failed, so it is not on the leaderboard. "
f"Please report this to the organisers with submission id "
f"`{submission.submission_id}`."
)
logger.info(
"Accepted submission {} from {} β PLUG Score {:.4f}",
submission.submission_id,
submission.display_name,
entry["plug_score"],
)
caveat = (
f"\n\n**Note:** {result.report()}\n" if result.warnings else ""
)
return gr.update(
value=(
f"### β
Submission accepted{caveat}\n\n"
f"Recorded for **{submission.display_name}** β it will appear on the "
f"{TRACK_LABELS[track].lower()} leaderboard within a minute.\n\n"
f"**PLUG Score: {entry['plug_score']:.4f}**\n\n"
f"{_score_table_md(scores)}\n\n"
f"Submission id `{submission.submission_id}`. You may submit to this track "
f"again in {HOURS_BETWEEN_SUBMISSIONS} hours; only your latest submission to "
"each track is ranked."
),
visible=True,
)
|