Download tasks/bibliometric_lab/environment/package_common.py from Tokenwave-AI/REE: direct link, hf CLI and curl.
- Browser
- Download file 10.3 kB
-
https://huggingface.co/datasets/Tokenwave-AI/REE/resolve/main/tasks/bibliometric_lab/environment/package_common.py
- Command line
-
hf download hf://datasets/Tokenwave-AI/REE/tasks/bibliometric_lab/environment/package_common.py
-
curl -L -o package_common.py https://huggingface.co/datasets/Tokenwave-AI/REE/resolve/main/tasks/bibliometric_lab/environment/package_common.py
10.3 kB
| """Values the grader and the self-check share, and the one function that calls the core's metric. | |
| Nothing about the sealed instances is in this file: their ids and answer paths are in | |
| `tests/sealed.json`, which only the grader's image holds. | |
| """ | |
| from __future__ import annotations | |
| import json | |
| import math | |
| import os | |
| import shlex | |
| import shutil | |
| import subprocess | |
| import tempfile | |
| import time | |
| from pathlib import Path | |
| # ---- the task's constants ---- | |
| PER_RUN_BUDGET_SEC = 120.0 # seconds per method run | |
| METRIC_COMMAND = 'python3 metric/metric.py --data {instance} --answers {answers} --output {output}' | |
| SCORE_FROM = 'stdout-first-line' | |
| SCOPE = 'instance' | |
| FLOOR = -1.0 | |
| DIRECTION = 'higher' | |
| AGGREGATE = 'mean' # mean or geometric | |
| GEOMETRIC_MIN = None # scores are clamped up to this before the geometric mean's log | |
| OUTPUTS = ('predictions.csv',) # the files the method writes | |
| METRIC_TIMEOUT_SEC = 122.0 # seconds the metric may take per instance | |
| PRACTICE_ID = 'v-25a8c06e04b9' | |
| PRACTICE_IDS = ('v-25a8c06e04b9', 'v-2a4d99d63188', 'v-e50596c00260') # flat /app/data when there is one | |
| # {answers} of each instance, relative to its answers root; empty when the layout declares none | |
| ANSWER_PATHS = {'v-25a8c06e04b9': '.', 'v-2a4d99d63188': '.', 'v-e50596c00260': '.'} | |
| # ---- end of the task's constants ---- | |
| def practice_dirs() -> list[tuple[str, Path, Path | None]]: | |
| """(id, inputs, answers root) for every practice instance, in the order of PRACTICE_IDS. | |
| One practice instance sits flat under /app/data; several sit in a subdirectory each, named by | |
| the instance id.""" | |
| root, answers = Path("/app/data"), Path("/app/data-answers") | |
| ids = globals().get("PRACTICE_IDS") or (PRACTICE_ID,) | |
| if len(ids) == 1: | |
| return [(ids[0], root, answers if answers.exists() else None)] | |
| return [(i, root / i, (answers / i) if (answers / i).exists() else None) for i in ids] | |
| CORE = Path(os.environ.get("CORE_DIR", "/app/core")) | |
| # Where the metric's programs are found. Root starts the metric after the method has run, and the method can | |
| # write to none of these directories. | |
| METRIC_PATH = '/usr/local/bin:/usr/local/sbin:/usr/sbin:/usr/bin:/sbin:/bin' | |
| STDOUT_KEPT = 2000 # characters of the metric's stdout kept in the record | |
| # The run time a metric that reads {elapsed} is given (a round scored by its time): the caller sets it from runner.LAST_RUN_SEC right before it scores that run's output, | |
| # and metric_call uses it once and clears it, so a call without it fails closed instead of reading | |
| # another instance's time. | |
| ELAPSED: float | None = None | |
| # The same for a metric that reads {elapsed_file} (scope "set"): {instance id: that run's seconds, as | |
| # ELAPSED carries them, or None for a run that never started}, one entry per instance of the call. | |
| # metric_call writes it to a fresh JSON file, names that file in the command, and clears it. | |
| ELAPSED_BY_ID: dict | None = None | |
| def aggregate(scores: list[float]) -> float: | |
| """The aggregate score, from the per-instance scores. The grader and the self-check share this, so | |
| a rehearsal aggregates exactly as grading does. AGGREGATE says which of the two below applies. | |
| `mean` is the plain arithmetic mean, in the metric's own units, and is the default. | |
| `geometric` is the **geometric mean**, `exp(mean(log(s)))`, in the metric's own units -- NOT the | |
| mean of the logs, which is its logarithm and lives on a different scale. On a cost metric it | |
| measures each instance's **relative** improvement, so an instance whose absolute cost is orders | |
| of magnitude larger than its neighbours' does not dominate the aggregate. Each score is first | |
| clamped up to GEOMETRIC_MIN, which keeps the log finite for a score of 0 or below.""" | |
| if not scores: | |
| raise ValueError("no per-instance scores to aggregate") | |
| if globals().get("AGGREGATE", "mean") != "geometric": | |
| return sum(scores) / len(scores) | |
| lo = GEOMETRIC_MIN | |
| return math.exp(sum(math.log(max(s, lo)) for s in scores) / len(scores)) | |
| def answers_for(root: Path, iid: str) -> Path | None: | |
| """{answers} for one instance: its answers under `root`, or None if the layout declares none.""" | |
| rel = ANSWER_PATHS.get(iid) | |
| return None if rel is None else Path(root) / rel | |
| def _fill(token: str, values: dict) -> str: | |
| for key, value in values.items(): | |
| token = token.replace("{" + key + "}", str(value)) | |
| return token | |
| def _read_score(stdout: str) -> float | None: | |
| """The score as SCORE_FROM says -- the first stdout line, or <key> of the last JSON-object line; | |
| None if it cannot be read.""" | |
| lines = stdout.splitlines() | |
| try: | |
| if SCORE_FROM == "stdout-first-line": | |
| value = float(lines[0].strip()) | |
| else: # "stdout-json:<key>": the last line that is a JSON object | |
| key = SCORE_FROM.split(":", 1)[1] | |
| value = None | |
| for line in reversed(lines): | |
| try: | |
| obj = json.loads(line) | |
| except ValueError: | |
| continue | |
| if isinstance(obj, dict): | |
| value = float(obj[key]) | |
| break | |
| except (IndexError, KeyError, TypeError, ValueError): | |
| return None | |
| if value is None or not math.isfinite(value): | |
| return None | |
| return value | |
| def whole_side_timeout(n: int) -> float: | |
| """What one call over a whole side of n instances may spend (scope "set"): n calls' worth.""" | |
| return max(1, n) * METRIC_TIMEOUT_SEC | |
| def metric_call(instance: Path, answers: Path | None, output: Path, timeout: float | None = None) -> dict: | |
| """Run the core's declared metric command once and read its score. | |
| The placeholders are filled with the given paths and a fresh {scratch}; the command runs in | |
| CORE with CORE_DIR set, under METRIC_TIMEOUT_SEC. Any failure gives the floor: | |
| status "metric_failed" (non-zero exit), "metric_timeout" or "unreadable_score". | |
| A call over a whole side passes `timeout`, whole_side_timeout of its size, instead. | |
| A command that reads {elapsed} is given ELAPSED, the run's measured seconds, and fails closed | |
| ("metric_failed") when the caller set none. | |
| A command that reads {elapsed_file} is given the path of a JSON file holding ELAPSED_BY_ID, and | |
| fails closed the same way. | |
| """ | |
| global ELAPSED | |
| global ELAPSED_BY_ID | |
| elapsed, ELAPSED = ELAPSED, None | |
| times, ELAPSED_BY_ID = ELAPSED_BY_ID, None | |
| if "{elapsed}" in METRIC_COMMAND and elapsed is None: | |
| return {"score": FLOOR, "status": "metric_failed", "exit": None, "metric_sec": 0.0, | |
| "stdout": "the metric reads {elapsed}, and this call was given no measured run time"} | |
| if "{elapsed_file}" in METRIC_COMMAND and times is None: | |
| return {"score": FLOOR, "status": "metric_failed", "exit": None, "metric_sec": 0.0, | |
| "stdout": "the metric reads {elapsed_file}, and this call was given no measured run times"} | |
| program = shutil.which(shlex.split(METRIC_COMMAND)[0], path=METRIC_PATH) | |
| if program is None: | |
| return {"score": FLOOR, "status": "metric_failed", "exit": None, "metric_sec": 0.0, | |
| "stdout": "the metric's program is not on METRIC_PATH"} | |
| scratch = Path(tempfile.mkdtemp(prefix="metric_scratch_")) | |
| values = {"instance": instance, "output": output, "scratch": scratch} | |
| if elapsed is not None: | |
| values["elapsed"] = f"{elapsed:.3f}" | |
| times_dir = None | |
| if "{elapsed_file}" in METRIC_COMMAND: | |
| times_dir = Path(tempfile.mkdtemp(prefix="metric_elapsed_")) | |
| values["elapsed_file"] = times_dir / "elapsed.json" | |
| values["elapsed_file"].write_text(json.dumps(times)) | |
| if answers is not None: | |
| values["answers"] = answers | |
| argv = [program] + [_fill(t, values) for t in shlex.split(METRIC_COMMAND)[1:]] | |
| env = dict(os.environ, PATH=METRIC_PATH, CORE_DIR=str(CORE), PYTHONDONTWRITEBYTECODE="1") | |
| t0 = time.time() | |
| try: | |
| p = subprocess.run(argv, cwd=str(CORE), env=env, capture_output=True, text=True, | |
| errors="replace", timeout=METRIC_TIMEOUT_SEC if timeout is None else timeout) | |
| except subprocess.TimeoutExpired: | |
| return {"score": FLOOR, "status": "metric_timeout", "exit": None, "stdout": "", | |
| "metric_sec": round(time.time() - t0, 3)} | |
| finally: | |
| shutil.rmtree(scratch, ignore_errors=True) | |
| if times_dir is not None: | |
| shutil.rmtree(times_dir, ignore_errors=True) | |
| rec = {"exit": p.returncode, "stdout": p.stdout[:STDOUT_KEPT], | |
| "metric_sec": round(time.time() - t0, 3)} | |
| if p.returncode != 0: | |
| return {"score": FLOOR, "status": "metric_failed", **rec} | |
| score = _read_score(p.stdout) | |
| if score is None: | |
| return {"score": FLOOR, "status": "unreadable_score", **rec} | |
| return {"score": score, "status": "ok", **rec} | |
| def write_outputs(texts: dict, out: Path) -> None: | |
| """The declared output files, as read by runner._read_output, into a fresh directory. | |
| The metric runs as root, so it never reads the method's own work directory: a leftover link | |
| there could lead it to another file. Only regular files the runner already read are | |
| written, and a file the method did not write stays absent. | |
| """ | |
| out.mkdir(mode=0o700, parents=True, exist_ok=False) | |
| for name in OUTPUTS: | |
| text = texts.get(name) | |
| if text is not None: | |
| path = out / name | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| path.write_bytes(text if isinstance(text, bytes) else text.encode("utf-8")) | |
| def score_outputs(texts: dict, instance: Path, answers: Path | None) -> dict: | |
| """Score one instance's outputs with the metric; the record metric_call returns.""" | |
| root = Path(tempfile.mkdtemp(prefix="metric_out_")) | |
| try: | |
| write_outputs(texts, root / "output") | |
| return metric_call(instance, answers, root / "output") | |
| finally: | |
| shutil.rmtree(root, ignore_errors=True) | |
| def better(a: float, b: float) -> bool: | |
| """True when score a is better than score b in the core's direction.""" | |
| return a > b if DIRECTION == "higher" else a < b | |