Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- tasks/activeprune-al-unlabeled-pool-pruning/environment/Dockerfile +47 -0
- tasks/activeprune-al-unlabeled-pool-pruning/environment/app/harness/al_loop.py +102 -0
- tasks/activeprune-al-unlabeled-pool-pruning/environment/app/harness/prune_worker.py +104 -0
- tasks/activeprune-al-unlabeled-pool-pruning/environment/app/harness/runner.py +94 -0
- tasks/activeprune-al-unlabeled-pool-pruning/environment/app/harness/worker_client.py +169 -0
- tasks/activeprune-al-unlabeled-pool-pruning/environment/app/run_dev.py +119 -0
- tasks/activeprune-al-unlabeled-pool-pruning/environment/requirements.txt +5 -0
- tasks/activeprune-al-unlabeled-pool-pruning/hints/hint.md +1 -0
- tasks/activeprune-al-unlabeled-pool-pruning/tests/Dockerfile +35 -0
- tasks/activeprune-al-unlabeled-pool-pruning/tests/al_loop.py +102 -0
- tasks/activeprune-al-unlabeled-pool-pruning/tests/compute_reward.py +18 -0
- tasks/activeprune-al-unlabeled-pool-pruning/tests/grader_core.py +170 -0
- tasks/activeprune-al-unlabeled-pool-pruning/tests/intermediate.sh +23 -0
- tasks/activeprune-al-unlabeled-pool-pruning/tests/prune_worker.py +109 -0
- tasks/activeprune-al-unlabeled-pool-pruning/tests/requirements-verifier.txt +2 -0
- tasks/activeprune-al-unlabeled-pool-pruning/tests/requirements.txt +5 -0
- tasks/activeprune-al-unlabeled-pool-pruning/tests/runner.py +94 -0
- tasks/activeprune-al-unlabeled-pool-pruning/tests/test.sh +23 -0
- tasks/activeprune-al-unlabeled-pool-pruning/tests/test_state.py +67 -0
- tasks/activeprune-al-unlabeled-pool-pruning/tests/worker_client.py +169 -0
- tasks/budgeted-imputation-mcar50/environment/Dockerfile +41 -0
- tasks/budgeted-imputation-mcar50/environment/requirements.txt +5 -0
- tasks/budgeted-imputation-mcar50/hints/hint.md +1 -0
- tasks/budgeted-imputation-mcar50/tests/Dockerfile +35 -0
- tasks/budgeted-imputation-mcar50/tests/cellrunner.py +24 -0
- tasks/budgeted-imputation-mcar50/tests/cellspec.py +91 -0
- tasks/budgeted-imputation-mcar50/tests/compute_reward.py +21 -0
- tasks/budgeted-imputation-mcar50/tests/grader_core.py +101 -0
- tasks/budgeted-imputation-mcar50/tests/intermediate.sh +53 -0
- tasks/budgeted-imputation-mcar50/tests/requirements-verifier.txt +2 -0
- tasks/budgeted-imputation-mcar50/tests/requirements.txt +5 -0
- tasks/budgeted-imputation-mcar50/tests/test.sh +24 -0
- tasks/budgeted-imputation-mcar50/tests/test_state.py +381 -0
- tasks/carps-star-discrepancy-subset-select/environment/app/data/examples/manifest.json +54 -0
- tasks/carps-star-discrepancy-subset-select/environment/requirements.txt +2 -0
- tasks/carps-star-discrepancy-subset-select/hints/hint.md +1 -0
- tasks/carps-star-discrepancy-subset-select/tests/Dockerfile +40 -0
- tasks/carps-star-discrepancy-subset-select/tests/compute_reward.py +17 -0
- tasks/carps-star-discrepancy-subset-select/tests/grader_core.py +77 -0
- tasks/carps-star-discrepancy-subset-select/tests/hidden_data/final/manifest.json +109 -0
- tasks/carps-star-discrepancy-subset-select/tests/hidden_data/intermediate/manifest.json +109 -0
- tasks/carps-star-discrepancy-subset-select/tests/intermediate.sh +20 -0
- tasks/carps-star-discrepancy-subset-select/tests/requirements-verifier.txt +2 -0
- tasks/carps-star-discrepancy-subset-select/tests/requirements.txt +2 -0
- tasks/carps-star-discrepancy-subset-select/tests/runner.py +68 -0
- tasks/carps-star-discrepancy-subset-select/tests/test.sh +20 -0
- tasks/carps-star-discrepancy-subset-select/tests/test_state.py +312 -0
- tasks/cpu-decoder-graph-executor/environment/Dockerfile +42 -0
- tasks/cpu-decoder-graph-executor/environment/app/bench.py +54 -0
- tasks/cpu-decoder-graph-executor/environment/app/graph_spec.py +110 -0
tasks/activeprune-al-unlabeled-pool-pruning/environment/Dockerfile
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM --platform=linux/amd64 public.ecr.aws/docker/library/python:3.13-slim-bookworm@sha256:01f42367a0a94ad4bc17111776fd66e3500c1d87c15bbd6055b7371d39c124fb
|
| 2 |
+
|
| 3 |
+
RUN set -eu; \
|
| 4 |
+
if [ ! -s /etc/ssl/certs/ca-certificates.crt ]; then \
|
| 5 |
+
apt-get update && apt-get install -y --no-install-recommends ca-certificates=20230311+deb12u1; \
|
| 6 |
+
fi; \
|
| 7 |
+
rm -f /tmp/hz-prereq.list; \
|
| 8 |
+
echo 'deb [signed-by=/usr/share/keyrings/debian-archive-keyring.gpg] https://snapshot.debian.org/archive/debian/20260801T000000Z bookworm main' >> /tmp/hz-prereq.list; \
|
| 9 |
+
echo 'deb [signed-by=/usr/share/keyrings/debian-archive-keyring.gpg] https://snapshot.debian.org/archive/debian-security/20260801T000000Z bookworm-security main' >> /tmp/hz-prereq.list; \
|
| 10 |
+
apt-get -o Dir::Etc::sourcelist=/tmp/hz-prereq.list -o Dir::Etc::sourceparts=/dev/null -o Acquire::Check-Valid-Until=false update; \
|
| 11 |
+
apt-get -o Dir::Etc::sourcelist=/tmp/hz-prereq.list -o Dir::Etc::sourceparts=/dev/null -o Acquire::Check-Valid-Until=false install -y --no-install-recommends tmux=3.3a-3 asciinema=2.2.0-1; \
|
| 12 |
+
rm -f /tmp/hz-prereq.list; rm -rf /var/lib/apt/lists/*
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
ENTRYPOINT []
|
| 16 |
+
ENV DEBIAN_FRONTEND=noninteractive \
|
| 17 |
+
PYTHONHASHSEED=0 \
|
| 18 |
+
PIP_NO_CACHE_DIR=1 \
|
| 19 |
+
PIP_DISABLE_PIP_VERSION_CHECK=1 \
|
| 20 |
+
OMP_NUM_THREADS=1 \
|
| 21 |
+
OPENBLAS_NUM_THREADS=1 \
|
| 22 |
+
MKL_NUM_THREADS=1
|
| 23 |
+
|
| 24 |
+
RUN apt-get update \
|
| 25 |
+
&& apt-get install -y --no-install-recommends \
|
| 26 |
+
git=1:2.39.5-0+deb12u3 \
|
| 27 |
+
&& rm -rf /var/lib/apt/lists/* \
|
| 28 |
+
&& git config --system user.email "agent@localhost" \
|
| 29 |
+
&& git config --system user.name "autoresearch agent"
|
| 30 |
+
|
| 31 |
+
RUN useradd --create-home --uid 1001 agent
|
| 32 |
+
|
| 33 |
+
COPY ./requirements.txt /tmp/requirements.txt
|
| 34 |
+
RUN /usr/local/bin/python3 -m pip install --no-cache-dir -r /tmp/requirements.txt \
|
| 35 |
+
&& rm /tmp/requirements.txt
|
| 36 |
+
|
| 37 |
+
WORKDIR /app
|
| 38 |
+
COPY ./app /app
|
| 39 |
+
|
| 40 |
+
RUN mkdir -p /app/output \
|
| 41 |
+
&& chown -R agent:agent /app \
|
| 42 |
+
&& find /app -exec touch -d @1700000000 {} +
|
| 43 |
+
|
| 44 |
+
ENV HF_HUB_OFFLINE=1
|
| 45 |
+
ENV TRANSFORMERS_OFFLINE=1
|
| 46 |
+
|
| 47 |
+
USER agent
|
tasks/activeprune-al-unlabeled-pool-pruning/environment/app/harness/al_loop.py
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
from sklearn.linear_model import LogisticRegression
|
| 5 |
+
from sklearn.metrics import f1_score
|
| 6 |
+
|
| 7 |
+
POOL_SIZE = 12_500
|
| 8 |
+
KEEP = 3_125
|
| 9 |
+
LABEL_BUDGET = 125
|
| 10 |
+
N_ITERATIONS = 5
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class InvalidSelection(ValueError):
|
| 14 |
+
"""The pruner returned something the protocol does not allow."""
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class _ConstantModel:
|
| 18 |
+
"""Fallback for a labelled set that contains a single class."""
|
| 19 |
+
|
| 20 |
+
def __init__(self, label, classes):
|
| 21 |
+
self.label = int(label)
|
| 22 |
+
self.classes_ = np.asarray(classes)
|
| 23 |
+
|
| 24 |
+
def predict(self, X):
|
| 25 |
+
return np.full(len(X), self.label, dtype=np.int64)
|
| 26 |
+
|
| 27 |
+
def predict_proba(self, X):
|
| 28 |
+
p = np.zeros((len(X), len(self.classes_)), dtype=np.float64)
|
| 29 |
+
p[:, int(np.searchsorted(self.classes_, self.label))] = 1.0
|
| 30 |
+
return p
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def fit_model(X, y):
|
| 34 |
+
y = np.asarray(y, dtype=np.int64)
|
| 35 |
+
if len(np.unique(y)) < 2:
|
| 36 |
+
return _ConstantModel(y[0], np.unique(y))
|
| 37 |
+
clf = LogisticRegression(C=1.0, max_iter=1000, solver="lbfgs", random_state=0)
|
| 38 |
+
clf.fit(X, y)
|
| 39 |
+
return clf
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def macro_f1(y_true, y_pred):
|
| 43 |
+
"""Macro-averaged F1, in percent."""
|
| 44 |
+
return 100.0 * f1_score(y_true, y_pred, average="macro", zero_division=0)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def validate_selection(selection, available_set, keep):
|
| 48 |
+
"""Normalise and check one pruner return value. Raises InvalidSelection."""
|
| 49 |
+
if isinstance(selection, np.ndarray):
|
| 50 |
+
if selection.ndim != 1 or not np.issubdtype(selection.dtype, np.integer):
|
| 51 |
+
raise InvalidSelection("numpy return must be a 1-D integer array")
|
| 52 |
+
items = selection.tolist()
|
| 53 |
+
elif isinstance(selection, (list, tuple)):
|
| 54 |
+
items = list(selection)
|
| 55 |
+
else:
|
| 56 |
+
raise InvalidSelection(f"return type {type(selection).__name__} is not accepted")
|
| 57 |
+
out = []
|
| 58 |
+
for value in items:
|
| 59 |
+
if isinstance(value, bool) or not isinstance(value, (int, np.integer)):
|
| 60 |
+
raise InvalidSelection("selection contains a non-integer element")
|
| 61 |
+
out.append(int(value))
|
| 62 |
+
if not 1 <= len(out) <= keep:
|
| 63 |
+
raise InvalidSelection(f"selection length {len(out)} outside [1, {keep}]")
|
| 64 |
+
if len(set(out)) != len(out):
|
| 65 |
+
raise InvalidSelection("selection contains duplicate indices")
|
| 66 |
+
if not available_set.issuperset(out):
|
| 67 |
+
raise InvalidSelection("selection contains an index that is not available")
|
| 68 |
+
return np.asarray(out, dtype=np.int64)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def run_al(pool_labels, pool_X, eval_y, eval_X, seed, call_prune,
|
| 72 |
+
keep=KEEP, budget=LABEL_BUDGET, iterations=N_ITERATIONS):
|
| 73 |
+
"""Run one seeded end-to-end AL loop. `call_prune` takes
|
| 74 |
+
(available, labeled_indices, labeled_labels, keep, iteration, rng_seed) and returns the
|
| 75 |
+
retained pool indices. Returns the per-iteration macro-F1 list."""
|
| 76 |
+
n = len(pool_labels)
|
| 77 |
+
rng = np.random.default_rng(seed)
|
| 78 |
+
labeled: list[int] = []
|
| 79 |
+
model = None
|
| 80 |
+
curve = []
|
| 81 |
+
|
| 82 |
+
for iteration in range(iterations):
|
| 83 |
+
labeled_set = set(labeled)
|
| 84 |
+
available = [i for i in range(n) if i not in labeled_set]
|
| 85 |
+
selection = call_prune(available, list(labeled),
|
| 86 |
+
[int(pool_labels[i]) for i in labeled],
|
| 87 |
+
keep, iteration, int(seed))
|
| 88 |
+
sel = np.sort(validate_selection(selection, set(available), keep))
|
| 89 |
+
|
| 90 |
+
take = min(budget, len(sel))
|
| 91 |
+
if model is None:
|
| 92 |
+
newly = sel[rng.permutation(len(sel))[:take]]
|
| 93 |
+
else:
|
| 94 |
+
confidence = model.predict_proba(pool_X[sel]).max(axis=1)
|
| 95 |
+
order = np.lexsort((sel, confidence))
|
| 96 |
+
newly = sel[order[:take]]
|
| 97 |
+
|
| 98 |
+
labeled.extend(int(i) for i in newly)
|
| 99 |
+
model = fit_model(pool_X[labeled], pool_labels[labeled])
|
| 100 |
+
curve.append(macro_f1(eval_y, model.predict(eval_X)))
|
| 101 |
+
|
| 102 |
+
return curve
|
tasks/activeprune-al-unlabeled-pool-pruning/environment/app/harness/prune_worker.py
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import importlib.util
|
| 4 |
+
import json
|
| 5 |
+
import os
|
| 6 |
+
import sys
|
| 7 |
+
import traceback
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def _private_channel():
|
| 11 |
+
"""Move the protocol onto duplicated descriptors, then point fd 0/1 at /dev/null and
|
| 12 |
+
stderr so submitted code cannot read from or write into the channel."""
|
| 13 |
+
read_fd = os.dup(0)
|
| 14 |
+
write_fd = os.dup(1)
|
| 15 |
+
devnull = os.open(os.devnull, os.O_RDONLY)
|
| 16 |
+
os.dup2(devnull, 0)
|
| 17 |
+
os.close(devnull)
|
| 18 |
+
os.dup2(2, 1)
|
| 19 |
+
sys.stdin = open(os.devnull, "r")
|
| 20 |
+
sys.stdout = sys.stderr
|
| 21 |
+
return os.fdopen(read_fd, "r", encoding="utf-8"), \
|
| 22 |
+
os.fdopen(write_fd, "w", encoding="utf-8")
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def main():
|
| 26 |
+
module_dir, entry_module, pool_path = sys.argv[1:4]
|
| 27 |
+
channel_in, channel_out = _private_channel()
|
| 28 |
+
|
| 29 |
+
def emit(payload):
|
| 30 |
+
channel_out.write(json.dumps(payload) + "\n")
|
| 31 |
+
channel_out.flush()
|
| 32 |
+
|
| 33 |
+
try:
|
| 34 |
+
with open(pool_path, "r", encoding="utf-8") as fh:
|
| 35 |
+
pool_texts = json.load(fh)
|
| 36 |
+
sys.path.insert(0, module_dir)
|
| 37 |
+
spec = importlib.util.spec_from_file_location(
|
| 38 |
+
entry_module, os.path.join(module_dir, entry_module + ".py"))
|
| 39 |
+
if spec is None or spec.loader is None:
|
| 40 |
+
raise ImportError(f"cannot load {entry_module}.py from {module_dir}")
|
| 41 |
+
module = importlib.util.module_from_spec(spec)
|
| 42 |
+
sys.modules[entry_module] = module
|
| 43 |
+
spec.loader.exec_module(module)
|
| 44 |
+
prune = getattr(module, "prune")
|
| 45 |
+
if not callable(prune):
|
| 46 |
+
raise TypeError("prune is not callable")
|
| 47 |
+
except BaseException:
|
| 48 |
+
emit({"status": "startup_error", "detail": traceback.format_exc(limit=8)})
|
| 49 |
+
return 0
|
| 50 |
+
|
| 51 |
+
emit({"status": "ready"})
|
| 52 |
+
|
| 53 |
+
for line in channel_in:
|
| 54 |
+
line = line.strip()
|
| 55 |
+
if not line:
|
| 56 |
+
continue
|
| 57 |
+
request = json.loads(line)
|
| 58 |
+
if request.get("op") == "stop":
|
| 59 |
+
return 0
|
| 60 |
+
try:
|
| 61 |
+
result = prune(pool_texts,
|
| 62 |
+
request["available"],
|
| 63 |
+
request["labeled_indices"],
|
| 64 |
+
request["labeled_labels"],
|
| 65 |
+
request["keep"],
|
| 66 |
+
request["iteration"],
|
| 67 |
+
request["rng_seed"])
|
| 68 |
+
emit({"status": "ok", "selection": _as_int_list(result)})
|
| 69 |
+
except BaseException:
|
| 70 |
+
emit({"status": "call_error", "detail": traceback.format_exc(limit=8)})
|
| 71 |
+
return 0
|
| 72 |
+
return 0
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def _as_int_list(result):
|
| 76 |
+
"""Serialise the return value while preserving enough type information for the harness
|
| 77 |
+
to reject a wrong type. Anything unrecognised is passed through as its type name."""
|
| 78 |
+
if isinstance(result, (list, tuple)):
|
| 79 |
+
items = list(result)
|
| 80 |
+
else:
|
| 81 |
+
shape = getattr(result, "shape", None)
|
| 82 |
+
dtype = getattr(result, "dtype", None)
|
| 83 |
+
if shape is None or dtype is None:
|
| 84 |
+
return {"bad_type": type(result).__name__}
|
| 85 |
+
if len(shape) != 1 or dtype.kind not in "iu":
|
| 86 |
+
return {"bad_type": f"array(ndim={len(shape)}, dtype={dtype})"}
|
| 87 |
+
items = result.tolist()
|
| 88 |
+
out = []
|
| 89 |
+
for value in items:
|
| 90 |
+
if isinstance(value, bool):
|
| 91 |
+
return {"bad_type": "element bool"}
|
| 92 |
+
if not isinstance(value, int):
|
| 93 |
+
try:
|
| 94 |
+
as_int = value.__index__()
|
| 95 |
+
except Exception:
|
| 96 |
+
return {"bad_type": f"element {type(value).__name__}"}
|
| 97 |
+
out.append(as_int)
|
| 98 |
+
else:
|
| 99 |
+
out.append(value)
|
| 100 |
+
return out
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
if __name__ == "__main__":
|
| 104 |
+
sys.exit(main())
|
tasks/activeprune-al-unlabeled-pool-pruning/environment/app/harness/runner.py
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
import os
|
| 5 |
+
import pwd
|
| 6 |
+
import shutil
|
| 7 |
+
import sys
|
| 8 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
|
| 11 |
+
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
| 12 |
+
|
| 13 |
+
import al_loop
|
| 14 |
+
from worker_client import CALL_BUDGET_SEC, IMPORT_BUDGET_SEC, PruneWorker, PrunerFailure
|
| 15 |
+
|
| 16 |
+
MAX_CONCURRENT_RUNS = 6
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def stage_pool_texts(texts, path):
|
| 20 |
+
"""Write the pool text list where a worker can read it (texts only: no labels)."""
|
| 21 |
+
tmp = str(path) + ".tmp"
|
| 22 |
+
with open(tmp, "w", encoding="utf-8") as fh:
|
| 23 |
+
json.dump(list(texts), fh, ensure_ascii=False)
|
| 24 |
+
os.replace(tmp, path)
|
| 25 |
+
os.chmod(path, 0o644)
|
| 26 |
+
return str(path)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def make_readonly(tree):
|
| 30 |
+
"""Strip every write bit from a staged tree. The scoring harness hands the pruner a
|
| 31 |
+
read-only copy of the deliverable so no seeded run can leave anything on disk for the next
|
| 32 |
+
one; the development runner does the same, so a solution that needs to write at run time
|
| 33 |
+
fails locally rather than at grade time."""
|
| 34 |
+
os.chmod(tree, 0o555)
|
| 35 |
+
for base, dirs, files in os.walk(tree):
|
| 36 |
+
for name in dirs:
|
| 37 |
+
os.chmod(os.path.join(base, name), 0o555)
|
| 38 |
+
for name in files:
|
| 39 |
+
os.chmod(os.path.join(base, name), 0o444)
|
| 40 |
+
return tree
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def _make_scratch(root, name, as_user):
|
| 44 |
+
path = os.path.join(root, name)
|
| 45 |
+
shutil.rmtree(path, ignore_errors=True)
|
| 46 |
+
os.makedirs(path, exist_ok=True)
|
| 47 |
+
if as_user:
|
| 48 |
+
entry = pwd.getpwnam(as_user)
|
| 49 |
+
os.lchown(path, entry.pw_uid, entry.pw_gid)
|
| 50 |
+
os.chmod(path, 0o700)
|
| 51 |
+
return path
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def execute_runs(specs, *, python_exe, worker_script, module_dir, entry_module, scratch_root,
|
| 55 |
+
as_user=None, launch_prefix=None, new_session=os.setsid,
|
| 56 |
+
max_workers=MAX_CONCURRENT_RUNS,
|
| 57 |
+
call_budget=CALL_BUDGET_SEC, import_budget=IMPORT_BUDGET_SEC,
|
| 58 |
+
stderr_root=None):
|
| 59 |
+
"""specs: iterable of dicts with keys draw, seed, pool_labels, pool_X, eval_y, eval_X,
|
| 60 |
+
pool_texts_path. Returns one result dict per spec, in the input order."""
|
| 61 |
+
os.makedirs(scratch_root, exist_ok=True)
|
| 62 |
+
|
| 63 |
+
def one(index_spec):
|
| 64 |
+
index, spec = index_spec
|
| 65 |
+
tag = f"run_{spec['draw']}_{spec['seed']}"
|
| 66 |
+
scratch = _make_scratch(scratch_root, tag, as_user)
|
| 67 |
+
stderr_path = os.path.join(stderr_root, tag + ".err") if stderr_root else None
|
| 68 |
+
worker = PruneWorker(python_exe, worker_script, module_dir, entry_module,
|
| 69 |
+
spec["pool_texts_path"], scratch, launch_prefix=launch_prefix,
|
| 70 |
+
new_session=new_session, stderr_path=stderr_path,
|
| 71 |
+
call_budget=call_budget,
|
| 72 |
+
import_budget=import_budget)
|
| 73 |
+
result = {"index": index, "draw": spec["draw"], "seed": spec["seed"],
|
| 74 |
+
"curve": None, "final": None, "timings": [], "error": None}
|
| 75 |
+
try:
|
| 76 |
+
worker.start()
|
| 77 |
+
curve = al_loop.run_al(spec["pool_labels"], spec["pool_X"], spec["eval_y"],
|
| 78 |
+
spec["eval_X"], spec["seed"], worker.call)
|
| 79 |
+
result["curve"] = [float(v) for v in curve]
|
| 80 |
+
result["final"] = float(curve[-1])
|
| 81 |
+
except (PrunerFailure, al_loop.InvalidSelection) as exc:
|
| 82 |
+
result["error"] = f"{type(exc).__name__}: {exc}"
|
| 83 |
+
except Exception as exc:
|
| 84 |
+
result["error"] = f"harness error: {type(exc).__name__}: {exc}"
|
| 85 |
+
finally:
|
| 86 |
+
result["timings"] = [round(t, 3) for t in worker.timings]
|
| 87 |
+
worker.close()
|
| 88 |
+
shutil.rmtree(scratch, ignore_errors=True)
|
| 89 |
+
return result
|
| 90 |
+
|
| 91 |
+
with ThreadPoolExecutor(max_workers=max_workers) as pool:
|
| 92 |
+
results = list(pool.map(one, list(enumerate(specs))))
|
| 93 |
+
results.sort(key=lambda r: r["index"])
|
| 94 |
+
return results
|
tasks/activeprune-al-unlabeled-pool-pruning/environment/app/harness/worker_client.py
ADDED
|
@@ -0,0 +1,169 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
import os
|
| 5 |
+
import selectors
|
| 6 |
+
import signal
|
| 7 |
+
import subprocess
|
| 8 |
+
import time
|
| 9 |
+
|
| 10 |
+
IMPORT_BUDGET_SEC = 60.0
|
| 11 |
+
CALL_BUDGET_SEC = 20.0
|
| 12 |
+
ADDRESS_SPACE_LIMIT = 4 * 1024 ** 3
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class PrunerFailure(RuntimeError):
|
| 16 |
+
"""The submitted pruner crashed, timed out, or broke the protocol."""
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class PruneWorker:
|
| 20 |
+
def __init__(self, python_exe, worker_script, module_dir, entry_module, pool_texts_path,
|
| 21 |
+
scratch_dir, launch_prefix=None, new_session=os.setsid,
|
| 22 |
+
stderr_path=None, call_budget=CALL_BUDGET_SEC,
|
| 23 |
+
import_budget=IMPORT_BUDGET_SEC,
|
| 24 |
+
address_space_limit=ADDRESS_SPACE_LIMIT):
|
| 25 |
+
self.python_exe = python_exe
|
| 26 |
+
self.worker_script = worker_script
|
| 27 |
+
self.module_dir = module_dir
|
| 28 |
+
self.entry_module = entry_module
|
| 29 |
+
self.pool_texts_path = pool_texts_path
|
| 30 |
+
self.scratch_dir = scratch_dir
|
| 31 |
+
self.launch_prefix = list(launch_prefix) if launch_prefix else []
|
| 32 |
+
self.new_session = new_session
|
| 33 |
+
self.stderr_path = stderr_path
|
| 34 |
+
self.call_budget = call_budget
|
| 35 |
+
self.import_budget = import_budget
|
| 36 |
+
self.address_space_limit = address_space_limit
|
| 37 |
+
self.proc = None
|
| 38 |
+
self._selector = None
|
| 39 |
+
self._stderr = None
|
| 40 |
+
self.timings = []
|
| 41 |
+
|
| 42 |
+
def _argv(self):
|
| 43 |
+
return self.launch_prefix + [self.python_exe, self.worker_script, self.module_dir,
|
| 44 |
+
self.entry_module, self.pool_texts_path]
|
| 45 |
+
|
| 46 |
+
def _child_setup(self):
|
| 47 |
+
limit = self.address_space_limit
|
| 48 |
+
new_session = self.new_session
|
| 49 |
+
|
| 50 |
+
def apply():
|
| 51 |
+
new_session()
|
| 52 |
+
import resource
|
| 53 |
+
resource.setrlimit(resource.RLIMIT_AS, (limit, limit))
|
| 54 |
+
resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
|
| 55 |
+
return apply
|
| 56 |
+
|
| 57 |
+
def start(self):
|
| 58 |
+
env = {
|
| 59 |
+
"PATH": "/usr/local/bin:/usr/bin:/bin",
|
| 60 |
+
"HOME": self.scratch_dir,
|
| 61 |
+
"TMPDIR": self.scratch_dir,
|
| 62 |
+
"PYTHONHASHSEED": "0",
|
| 63 |
+
"PYTHONDONTWRITEBYTECODE": "1",
|
| 64 |
+
"OMP_NUM_THREADS": "1",
|
| 65 |
+
"OPENBLAS_NUM_THREADS": "1",
|
| 66 |
+
"MKL_NUM_THREADS": "1",
|
| 67 |
+
"NUMEXPR_NUM_THREADS": "1",
|
| 68 |
+
"VECLIB_MAXIMUM_THREADS": "1",
|
| 69 |
+
}
|
| 70 |
+
self._stderr = open(self.stderr_path, "ab") if self.stderr_path \
|
| 71 |
+
else open(os.devnull, "wb")
|
| 72 |
+
self.proc = subprocess.Popen(
|
| 73 |
+
self._argv(), stdin=subprocess.PIPE, stdout=subprocess.PIPE,
|
| 74 |
+
stderr=self._stderr, cwd=self.scratch_dir, env=env, text=True,
|
| 75 |
+
bufsize=1, preexec_fn=self._child_setup())
|
| 76 |
+
self._selector = selectors.DefaultSelector()
|
| 77 |
+
self._selector.register(self.proc.stdout, selectors.EVENT_READ)
|
| 78 |
+
hello = self._read(self.import_budget, "module import")
|
| 79 |
+
if hello.get("status") != "ready":
|
| 80 |
+
detail = hello.get("detail", hello)
|
| 81 |
+
self.kill()
|
| 82 |
+
raise PrunerFailure(f"module did not import: {detail}")
|
| 83 |
+
|
| 84 |
+
def kill(self):
|
| 85 |
+
if self.proc is None:
|
| 86 |
+
return
|
| 87 |
+
try:
|
| 88 |
+
os.killpg(self.proc.pid, signal.SIGKILL)
|
| 89 |
+
except (ProcessLookupError, PermissionError):
|
| 90 |
+
try:
|
| 91 |
+
self.proc.kill()
|
| 92 |
+
except ProcessLookupError:
|
| 93 |
+
pass
|
| 94 |
+
try:
|
| 95 |
+
self.proc.wait(timeout=15)
|
| 96 |
+
except subprocess.TimeoutExpired:
|
| 97 |
+
pass
|
| 98 |
+
if self._selector is not None:
|
| 99 |
+
self._selector.close()
|
| 100 |
+
self._selector = None
|
| 101 |
+
if self._stderr is not None:
|
| 102 |
+
self._stderr.close()
|
| 103 |
+
self._stderr = None
|
| 104 |
+
self.proc = None
|
| 105 |
+
|
| 106 |
+
def close(self):
|
| 107 |
+
if self.proc is None:
|
| 108 |
+
return
|
| 109 |
+
try:
|
| 110 |
+
self.proc.stdin.write(json.dumps({"op": "stop"}) + "\n")
|
| 111 |
+
self.proc.stdin.flush()
|
| 112 |
+
self.proc.wait(timeout=10)
|
| 113 |
+
except Exception:
|
| 114 |
+
pass
|
| 115 |
+
self.kill()
|
| 116 |
+
|
| 117 |
+
def _read(self, budget, what):
|
| 118 |
+
deadline = time.monotonic() + budget
|
| 119 |
+
while True:
|
| 120 |
+
remaining = deadline - time.monotonic()
|
| 121 |
+
if remaining <= 0:
|
| 122 |
+
self.kill()
|
| 123 |
+
raise PrunerFailure(f"{what} exceeded its {budget:g}s budget")
|
| 124 |
+
if not self._selector.select(timeout=min(remaining, 1.0)):
|
| 125 |
+
if self.proc.poll() is not None:
|
| 126 |
+
self.kill()
|
| 127 |
+
raise PrunerFailure(f"{what}: process exited without replying")
|
| 128 |
+
continue
|
| 129 |
+
line = self.proc.stdout.readline()
|
| 130 |
+
if line == "":
|
| 131 |
+
self.kill()
|
| 132 |
+
raise PrunerFailure(f"{what}: channel closed without a reply")
|
| 133 |
+
line = line.strip()
|
| 134 |
+
if not line:
|
| 135 |
+
continue
|
| 136 |
+
try:
|
| 137 |
+
return json.loads(line)
|
| 138 |
+
except json.JSONDecodeError as exc:
|
| 139 |
+
self.kill()
|
| 140 |
+
raise PrunerFailure(f"{what}: unparseable reply ({exc})") from None
|
| 141 |
+
|
| 142 |
+
def call(self, available, labeled_indices, labeled_labels, keep, iteration, rng_seed):
|
| 143 |
+
if self.proc is None:
|
| 144 |
+
raise PrunerFailure("worker is not running")
|
| 145 |
+
request = {"op": "prune", "available": list(map(int, available)),
|
| 146 |
+
"labeled_indices": list(map(int, labeled_indices)),
|
| 147 |
+
"labeled_labels": list(map(int, labeled_labels)),
|
| 148 |
+
"keep": int(keep), "iteration": int(iteration),
|
| 149 |
+
"rng_seed": int(rng_seed)}
|
| 150 |
+
started = time.monotonic()
|
| 151 |
+
try:
|
| 152 |
+
self.proc.stdin.write(json.dumps(request) + "\n")
|
| 153 |
+
self.proc.stdin.flush()
|
| 154 |
+
except (BrokenPipeError, ValueError) as exc:
|
| 155 |
+
self.kill()
|
| 156 |
+
raise PrunerFailure(f"pruner is gone before iteration {iteration}: {exc}") from None
|
| 157 |
+
reply = self._read(self.call_budget, f"prune call at iteration {iteration}")
|
| 158 |
+
self.timings.append(time.monotonic() - started)
|
| 159 |
+
if reply.get("status") != "ok":
|
| 160 |
+
detail = reply.get("detail", reply)
|
| 161 |
+
self.kill()
|
| 162 |
+
raise PrunerFailure(f"pruner raised at iteration {iteration}: {detail}")
|
| 163 |
+
selection = reply.get("selection")
|
| 164 |
+
if isinstance(selection, dict):
|
| 165 |
+
self.kill()
|
| 166 |
+
raise PrunerFailure(
|
| 167 |
+
f"pruner returned an unusable type at iteration {iteration}: "
|
| 168 |
+
f"{selection.get('bad_type')}")
|
| 169 |
+
return selection
|
tasks/activeprune-al-unlabeled-pool-pruning/environment/app/run_dev.py
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
import gzip
|
| 5 |
+
import json
|
| 6 |
+
import os
|
| 7 |
+
import shutil
|
| 8 |
+
import statistics
|
| 9 |
+
import sys
|
| 10 |
+
import tempfile
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
|
| 13 |
+
import numpy as np
|
| 14 |
+
|
| 15 |
+
HARNESS = Path(__file__).resolve().parent / "harness"
|
| 16 |
+
sys.path.insert(0, str(HARNESS))
|
| 17 |
+
|
| 18 |
+
import runner
|
| 19 |
+
from worker_client import CALL_BUDGET_SEC, IMPORT_BUDGET_SEC
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def read_texts(path):
|
| 23 |
+
with gzip.open(path, "rt", encoding="utf-8") as fh:
|
| 24 |
+
return [json.loads(line)["text"] for line in fh]
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def parse_seeds(spec):
|
| 28 |
+
out = []
|
| 29 |
+
for part in spec.split(","):
|
| 30 |
+
part = part.strip()
|
| 31 |
+
if "-" in part:
|
| 32 |
+
lo, hi = part.split("-")
|
| 33 |
+
out.extend(range(int(lo), int(hi) + 1))
|
| 34 |
+
else:
|
| 35 |
+
out.append(int(part))
|
| 36 |
+
return out
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def main():
|
| 40 |
+
ap = argparse.ArgumentParser()
|
| 41 |
+
ap.add_argument("--draws", default="a,b,c")
|
| 42 |
+
ap.add_argument("--seeds", default="0-5")
|
| 43 |
+
ap.add_argument("--module-dir", default="/app/output")
|
| 44 |
+
ap.add_argument("--entry", default="prune")
|
| 45 |
+
ap.add_argument("--workers", type=int, default=runner.MAX_CONCURRENT_RUNS)
|
| 46 |
+
ap.add_argument("--data", default=str(Path(__file__).resolve().parent / "data"))
|
| 47 |
+
ap.add_argument("--json", default=None, help="also write the summary as JSON here")
|
| 48 |
+
args = ap.parse_args()
|
| 49 |
+
|
| 50 |
+
DATA = Path(args.data)
|
| 51 |
+
draws = [d.strip() for d in args.draws.split(",") if d.strip()]
|
| 52 |
+
seeds = parse_seeds(args.seeds)
|
| 53 |
+
eval_y = np.load(DATA / "dev_eval_y.npy")
|
| 54 |
+
|
| 55 |
+
scratch = tempfile.mkdtemp(prefix="dev_run_")
|
| 56 |
+
specs = []
|
| 57 |
+
for draw in draws:
|
| 58 |
+
texts = read_texts(DATA / f"pool_{draw}.jsonl.gz")
|
| 59 |
+
pool_texts_path = runner.stage_pool_texts(texts, Path(scratch) / f"pool_{draw}.json")
|
| 60 |
+
pool_labels = np.load(DATA / f"pool_{draw}_y.npy")
|
| 61 |
+
pool_X = np.load(DATA / f"pool_{draw}_X.npy")
|
| 62 |
+
eval_X = np.load(DATA / f"eval_{draw}_X.npy")
|
| 63 |
+
for seed in seeds:
|
| 64 |
+
specs.append({"draw": draw, "seed": seed, "pool_labels": pool_labels,
|
| 65 |
+
"pool_X": pool_X, "eval_y": eval_y, "eval_X": eval_X,
|
| 66 |
+
"pool_texts_path": pool_texts_path})
|
| 67 |
+
|
| 68 |
+
print(f"{len(specs)} runs: draws={draws} seeds={seeds} "
|
| 69 |
+
f"import_budget={IMPORT_BUDGET_SEC:g}s call_budget={CALL_BUDGET_SEC:g}s")
|
| 70 |
+
err_root = Path(scratch) / "err"
|
| 71 |
+
err_root.mkdir(exist_ok=True)
|
| 72 |
+
staged = Path(scratch) / "deliverable"
|
| 73 |
+
shutil.copytree(args.module_dir, staged, symlinks=True)
|
| 74 |
+
runner.make_readonly(staged)
|
| 75 |
+
results = runner.execute_runs(
|
| 76 |
+
specs, python_exe=sys.executable, worker_script=str(HARNESS / "prune_worker.py"),
|
| 77 |
+
module_dir=str(staged), entry_module=args.entry, scratch_root=scratch,
|
| 78 |
+
as_user=None, new_session=os.setsid, max_workers=args.workers,
|
| 79 |
+
stderr_root=str(err_root))
|
| 80 |
+
|
| 81 |
+
failed = [r for r in results if r["error"]]
|
| 82 |
+
for r in failed[:5]:
|
| 83 |
+
print(f" FAILED draw={r['draw']} seed={r['seed']}: {r['error']}")
|
| 84 |
+
if failed:
|
| 85 |
+
print(f"{len(failed)}/{len(results)} runs failed -- a submission with any failing run "
|
| 86 |
+
f"is invalid. Worker stderr: {scratch}/err")
|
| 87 |
+
if args.json:
|
| 88 |
+
Path(args.json).write_text(json.dumps(
|
| 89 |
+
{"ok": False, "failed": len(failed), "first_error": failed[0]["error"]}))
|
| 90 |
+
return 1
|
| 91 |
+
|
| 92 |
+
per_draw = {}
|
| 93 |
+
for r in results:
|
| 94 |
+
per_draw.setdefault(r["draw"], []).append(r["final"])
|
| 95 |
+
print()
|
| 96 |
+
for draw in draws:
|
| 97 |
+
vals = per_draw[draw]
|
| 98 |
+
sd = statistics.stdev(vals) if len(vals) > 1 else 0.0
|
| 99 |
+
print(f"draw {draw}: final macro-F1 mean {statistics.fmean(vals):8.4f} "
|
| 100 |
+
f"sd {sd:6.4f} n {len(vals)}")
|
| 101 |
+
allv = [r["final"] for r in results]
|
| 102 |
+
print(f"OVERALL mean final macro-F1: {statistics.fmean(allv):.4f} (n={len(allv)})")
|
| 103 |
+
curve = np.mean(np.array([r["curve"] for r in results]), axis=0)
|
| 104 |
+
print("mean per-iteration macro-F1: " + " ".join(f"{v:.3f}" for v in curve))
|
| 105 |
+
slowest = max(max(r["timings"]) for r in results)
|
| 106 |
+
print(f"slowest prune call: {slowest:.2f}s of the {CALL_BUDGET_SEC:g}s budget")
|
| 107 |
+
if args.json:
|
| 108 |
+
Path(args.json).write_text(json.dumps(
|
| 109 |
+
{"ok": True, "overall_mean": statistics.fmean(allv),
|
| 110 |
+
"per_draw_mean": {d: statistics.fmean(v) for d, v in per_draw.items()},
|
| 111 |
+
"per_draw_sd": {d: (statistics.stdev(v) if len(v) > 1 else 0.0)
|
| 112 |
+
for d, v in per_draw.items()},
|
| 113 |
+
"per_iteration_mean": [float(v) for v in curve],
|
| 114 |
+
"slowest_call_sec": slowest, "n_runs": len(allv)}, indent=2))
|
| 115 |
+
return 0
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
if __name__ == "__main__":
|
| 119 |
+
sys.exit(main())
|
tasks/activeprune-al-unlabeled-pool-pruning/environment/requirements.txt
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
numpy==2.5.2
|
| 2 |
+
scipy==1.18.0
|
| 3 |
+
scikit-learn==1.9.0
|
| 4 |
+
joblib==1.5.3
|
| 5 |
+
threadpoolctl==3.6.0
|
tasks/activeprune-al-unlabeled-pool-pruning/hints/hint.md
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
Most of the score is pool hygiene: train an in-domain detector offline, ship it inside the submission, and prune to documents that match the evaluation set's style rather than refining the acquisition rule. Use it to return a class-balanced high-confidence set in round zero, where no model exists yet, then widen in later rounds and exclude the most ambiguous documents so labels are not spent on noise. Load the artifact at import, not inside the call, which has its own time limit.
|
tasks/activeprune-al-unlabeled-pool-pruning/tests/Dockerfile
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM --platform=linux/amd64 public.ecr.aws/docker/library/python:3.13-slim-bookworm@sha256:01f42367a0a94ad4bc17111776fd66e3500c1d87c15bbd6055b7371d39c124fb
|
| 2 |
+
|
| 3 |
+
ENTRYPOINT []
|
| 4 |
+
ENV PYTHONPATH=
|
| 5 |
+
ENV PYTHONSAFEPATH=1
|
| 6 |
+
ENV DEBIAN_FRONTEND=noninteractive \
|
| 7 |
+
PYTHONHASHSEED=0 \
|
| 8 |
+
PIP_NO_CACHE_DIR=1 \
|
| 9 |
+
PIP_DISABLE_PIP_VERSION_CHECK=1 \
|
| 10 |
+
OMP_NUM_THREADS=1 \
|
| 11 |
+
OPENBLAS_NUM_THREADS=1 \
|
| 12 |
+
MKL_NUM_THREADS=1
|
| 13 |
+
|
| 14 |
+
RUN useradd --create-home --uid 1001 agent
|
| 15 |
+
|
| 16 |
+
COPY ./requirements.txt /tmp/requirements.txt
|
| 17 |
+
COPY ./requirements-verifier.txt /tmp/requirements-verifier.txt
|
| 18 |
+
RUN /usr/local/bin/python3 -m pip install --no-cache-dir \
|
| 19 |
+
-r /tmp/requirements.txt -r /tmp/requirements-verifier.txt \
|
| 20 |
+
&& rm /tmp/requirements.txt /tmp/requirements-verifier.txt
|
| 21 |
+
|
| 22 |
+
RUN mkdir -p /app/output /logs/verifier /grade_stage \
|
| 23 |
+
&& chmod 755 /tmp /var/tmp /dev/shm /home/agent
|
| 24 |
+
|
| 25 |
+
COPY . /tests
|
| 26 |
+
|
| 27 |
+
RUN chown -R root:root /tests \
|
| 28 |
+
&& chmod 700 /tests/hidden_data /tests/hidden_data/intermediate /tests/hidden_data/final \
|
| 29 |
+
&& chmod +x /tests/test.sh /tests/intermediate.sh \
|
| 30 |
+
&& find /tests -exec touch -d @1700000000 {} +
|
| 31 |
+
|
| 32 |
+
WORKDIR /tests
|
| 33 |
+
|
| 34 |
+
ENV HF_HUB_OFFLINE=1
|
| 35 |
+
ENV TRANSFORMERS_OFFLINE=1
|
tasks/activeprune-al-unlabeled-pool-pruning/tests/al_loop.py
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
from sklearn.linear_model import LogisticRegression
|
| 5 |
+
from sklearn.metrics import f1_score
|
| 6 |
+
|
| 7 |
+
POOL_SIZE = 12_500
|
| 8 |
+
KEEP = 3_125
|
| 9 |
+
LABEL_BUDGET = 125
|
| 10 |
+
N_ITERATIONS = 5
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class InvalidSelection(ValueError):
|
| 14 |
+
"""The pruner returned something the protocol does not allow."""
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class _ConstantModel:
|
| 18 |
+
"""Fallback for a labelled set that contains a single class."""
|
| 19 |
+
|
| 20 |
+
def __init__(self, label, classes):
|
| 21 |
+
self.label = int(label)
|
| 22 |
+
self.classes_ = np.asarray(classes)
|
| 23 |
+
|
| 24 |
+
def predict(self, X):
|
| 25 |
+
return np.full(len(X), self.label, dtype=np.int64)
|
| 26 |
+
|
| 27 |
+
def predict_proba(self, X):
|
| 28 |
+
p = np.zeros((len(X), len(self.classes_)), dtype=np.float64)
|
| 29 |
+
p[:, int(np.searchsorted(self.classes_, self.label))] = 1.0
|
| 30 |
+
return p
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def fit_model(X, y):
|
| 34 |
+
y = np.asarray(y, dtype=np.int64)
|
| 35 |
+
if len(np.unique(y)) < 2:
|
| 36 |
+
return _ConstantModel(y[0], np.unique(y))
|
| 37 |
+
clf = LogisticRegression(C=1.0, max_iter=1000, solver="lbfgs", random_state=0)
|
| 38 |
+
clf.fit(X, y)
|
| 39 |
+
return clf
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def macro_f1(y_true, y_pred):
|
| 43 |
+
"""Macro-averaged F1, in percent."""
|
| 44 |
+
return 100.0 * f1_score(y_true, y_pred, average="macro", zero_division=0)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def validate_selection(selection, available_set, keep):
|
| 48 |
+
"""Normalise and check one pruner return value. Raises InvalidSelection."""
|
| 49 |
+
if isinstance(selection, np.ndarray):
|
| 50 |
+
if selection.ndim != 1 or not np.issubdtype(selection.dtype, np.integer):
|
| 51 |
+
raise InvalidSelection("numpy return must be a 1-D integer array")
|
| 52 |
+
items = selection.tolist()
|
| 53 |
+
elif isinstance(selection, (list, tuple)):
|
| 54 |
+
items = list(selection)
|
| 55 |
+
else:
|
| 56 |
+
raise InvalidSelection(f"return type {type(selection).__name__} is not accepted")
|
| 57 |
+
out = []
|
| 58 |
+
for value in items:
|
| 59 |
+
if isinstance(value, bool) or not isinstance(value, (int, np.integer)):
|
| 60 |
+
raise InvalidSelection("selection contains a non-integer element")
|
| 61 |
+
out.append(int(value))
|
| 62 |
+
if not 1 <= len(out) <= keep:
|
| 63 |
+
raise InvalidSelection(f"selection length {len(out)} outside [1, {keep}]")
|
| 64 |
+
if len(set(out)) != len(out):
|
| 65 |
+
raise InvalidSelection("selection contains duplicate indices")
|
| 66 |
+
if not available_set.issuperset(out):
|
| 67 |
+
raise InvalidSelection("selection contains an index that is not available")
|
| 68 |
+
return np.asarray(out, dtype=np.int64)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def run_al(pool_labels, pool_X, eval_y, eval_X, seed, call_prune,
|
| 72 |
+
keep=KEEP, budget=LABEL_BUDGET, iterations=N_ITERATIONS):
|
| 73 |
+
"""Run one seeded end-to-end AL loop. `call_prune` takes
|
| 74 |
+
(available, labeled_indices, labeled_labels, keep, iteration, rng_seed) and returns the
|
| 75 |
+
retained pool indices. Returns the per-iteration macro-F1 list."""
|
| 76 |
+
n = len(pool_labels)
|
| 77 |
+
rng = np.random.default_rng(seed)
|
| 78 |
+
labeled: list[int] = []
|
| 79 |
+
model = None
|
| 80 |
+
curve = []
|
| 81 |
+
|
| 82 |
+
for iteration in range(iterations):
|
| 83 |
+
labeled_set = set(labeled)
|
| 84 |
+
available = [i for i in range(n) if i not in labeled_set]
|
| 85 |
+
selection = call_prune(available, list(labeled),
|
| 86 |
+
[int(pool_labels[i]) for i in labeled],
|
| 87 |
+
keep, iteration, int(seed))
|
| 88 |
+
sel = np.sort(validate_selection(selection, set(available), keep))
|
| 89 |
+
|
| 90 |
+
take = min(budget, len(sel))
|
| 91 |
+
if model is None:
|
| 92 |
+
newly = sel[rng.permutation(len(sel))[:take]]
|
| 93 |
+
else:
|
| 94 |
+
confidence = model.predict_proba(pool_X[sel]).max(axis=1)
|
| 95 |
+
order = np.lexsort((sel, confidence))
|
| 96 |
+
newly = sel[order[:take]]
|
| 97 |
+
|
| 98 |
+
labeled.extend(int(i) for i in newly)
|
| 99 |
+
model = fit_model(pool_X[labeled], pool_labels[labeled])
|
| 100 |
+
curve.append(macro_f1(eval_y, model.predict(eval_X)))
|
| 101 |
+
|
| 102 |
+
return curve
|
tasks/activeprune-al-unlabeled-pool-pruning/tests/compute_reward.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import math
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
|
| 5 |
+
REWARD_PATH = Path("/logs/verifier/reward.txt")
|
| 6 |
+
|
| 7 |
+
try:
|
| 8 |
+
REWARD_PATH.parent.mkdir(parents=True, exist_ok=True)
|
| 9 |
+
value = float(json.loads(Path("/logs/verifier/metric.json").read_text())["reward"])
|
| 10 |
+
if not math.isfinite(value):
|
| 11 |
+
raise ValueError("non-finite reward")
|
| 12 |
+
reward = f"{min(1.0, max(0.0, value)):.12g}"
|
| 13 |
+
REWARD_PATH.write_text(reward + "\n")
|
| 14 |
+
print(f"reward={reward}")
|
| 15 |
+
except Exception as exc:
|
| 16 |
+
REWARD_PATH.parent.mkdir(parents=True, exist_ok=True)
|
| 17 |
+
REWARD_PATH.write_text("0\n")
|
| 18 |
+
print(f"reward=0 (fallback: {exc})")
|
tasks/activeprune-al-unlabeled-pool-pruning/tests/grader_core.py
ADDED
|
@@ -0,0 +1,170 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import gzip
|
| 4 |
+
import json
|
| 5 |
+
import math
|
| 6 |
+
import os
|
| 7 |
+
import pwd
|
| 8 |
+
import shutil
|
| 9 |
+
import statistics
|
| 10 |
+
import sys
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
|
| 13 |
+
import numpy as np
|
| 14 |
+
|
| 15 |
+
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
| 16 |
+
|
| 17 |
+
import runner
|
| 18 |
+
from worker_client import CALL_BUDGET_SEC, IMPORT_BUDGET_SEC
|
| 19 |
+
|
| 20 |
+
TESTS_DIR = Path(__file__).resolve().parent
|
| 21 |
+
HIDDEN = TESTS_DIR / "hidden_data"
|
| 22 |
+
PYTHON = sys.executable
|
| 23 |
+
DELIVERABLE_DIR = Path("/app/output")
|
| 24 |
+
ENTRY_MODULE = "prune"
|
| 25 |
+
STAGE_ROOT = Path("/grade_stage")
|
| 26 |
+
CANDIDATE_USER = "agent"
|
| 27 |
+
|
| 28 |
+
DRAWS = ("s0", "s1")
|
| 29 |
+
SEEDS = tuple(range(12))
|
| 30 |
+
|
| 31 |
+
M0 = 77.9
|
| 32 |
+
BASELINE_SCORE = 93.11
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class SubmissionInvalid(Exception):
|
| 36 |
+
"""The submission cannot be scored: it is missing, unsafe, crashed, or out of budget."""
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def scan_for_links(root: Path):
|
| 40 |
+
"""Reject every symlink and every hard-linked file anywhere under the submitted tree,
|
| 41 |
+
BEFORE anything is copied. A submitted directory symlink would otherwise be recursed
|
| 42 |
+
into by the copy and materialise verifier-owned files where the score is computed from."""
|
| 43 |
+
offences = []
|
| 44 |
+
stack = [root]
|
| 45 |
+
while stack:
|
| 46 |
+
current = stack.pop()
|
| 47 |
+
with os.scandir(current) as entries:
|
| 48 |
+
for entry in entries:
|
| 49 |
+
info = os.lstat(entry.path)
|
| 50 |
+
rel = os.path.relpath(entry.path, root)
|
| 51 |
+
if os.path.islink(entry.path):
|
| 52 |
+
offences.append(f"symlink: {rel}")
|
| 53 |
+
continue
|
| 54 |
+
if os.path.isdir(entry.path):
|
| 55 |
+
stack.append(Path(entry.path))
|
| 56 |
+
continue
|
| 57 |
+
if info.st_nlink != 1:
|
| 58 |
+
offences.append(f"hard link (st_nlink={info.st_nlink}): {rel}")
|
| 59 |
+
return offences
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def stage_deliverable(source: Path, dest: Path):
|
| 63 |
+
if not source.is_dir():
|
| 64 |
+
raise SubmissionInvalid(f"no deliverable directory at {source}")
|
| 65 |
+
entry = source / (ENTRY_MODULE + ".py")
|
| 66 |
+
if not entry.is_file() or entry.stat().st_size == 0:
|
| 67 |
+
raise SubmissionInvalid(f"missing or empty entry point {entry}")
|
| 68 |
+
offences = scan_for_links(source)
|
| 69 |
+
if offences:
|
| 70 |
+
raise SubmissionInvalid("submitted tree contains links: " + "; ".join(offences[:5]))
|
| 71 |
+
shutil.rmtree(dest, ignore_errors=True)
|
| 72 |
+
shutil.copytree(source, dest, symlinks=True)
|
| 73 |
+
os.lchown(dest, 0, 0)
|
| 74 |
+
for base, dirs, files in os.walk(dest):
|
| 75 |
+
for name in dirs + files:
|
| 76 |
+
os.lchown(os.path.join(base, name), 0, 0)
|
| 77 |
+
return runner.make_readonly(dest)
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def load_pool_texts(draw):
|
| 81 |
+
with gzip.open(HIDDEN / "pools" / f"pool_{draw}.jsonl.gz", "rt", encoding="utf-8") as fh:
|
| 82 |
+
return [json.loads(line)["text"] for line in fh]
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def build_specs(phase, stage_root, seeds=SEEDS):
|
| 86 |
+
eval_y = np.load(HIDDEN / phase / "eval_y.npy")
|
| 87 |
+
specs = []
|
| 88 |
+
for draw in DRAWS:
|
| 89 |
+
pool_texts_path = runner.stage_pool_texts(
|
| 90 |
+
load_pool_texts(draw), Path(stage_root) / f"pool_{draw}.json")
|
| 91 |
+
pool_labels = np.load(HIDDEN / "pools" / f"pool_{draw}_y.npy")
|
| 92 |
+
pool_X = np.load(HIDDEN / "pools" / f"pool_{draw}_X.npy")
|
| 93 |
+
eval_X = np.load(HIDDEN / phase / f"eval_{draw}_X.npy")
|
| 94 |
+
for seed in seeds:
|
| 95 |
+
specs.append({"draw": draw, "seed": seed, "pool_labels": pool_labels,
|
| 96 |
+
"pool_X": pool_X, "eval_y": eval_y, "eval_X": eval_X,
|
| 97 |
+
"pool_texts_path": pool_texts_path})
|
| 98 |
+
return specs
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def graded_reward(metric, valid):
|
| 102 |
+
"""rational_squash: 0 at the strongest trivial baseline, 0.5 at the baseline score,
|
| 103 |
+
strictly increasing above it, asymptotic to 1, never negative."""
|
| 104 |
+
if not valid or metric is None or not math.isfinite(metric):
|
| 105 |
+
return 0.0
|
| 106 |
+
x_ref = BASELINE_SCORE - M0
|
| 107 |
+
assert x_ref > 0, "malformed task: the baseline score does not beat the trivial baseline"
|
| 108 |
+
u = max(0.0, metric - M0) / x_ref
|
| 109 |
+
return u / (1.0 + u)
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def grade(phase, launch_prefix, new_session=os.setsid, call_timeout=CALL_BUDGET_SEC,
|
| 113 |
+
import_timeout=IMPORT_BUDGET_SEC, deliverable=DELIVERABLE_DIR,
|
| 114 |
+
stage_root=STAGE_ROOT, seeds=SEEDS):
|
| 115 |
+
"""Run the sealed panel and return the record written to /logs/verifier/metric.json."""
|
| 116 |
+
record = {"phase": phase, "valid": False, "metric": None, "reward": 0.0,
|
| 117 |
+
"n_runs": len(DRAWS) * len(seeds), "detail": "", "per_iteration_mean": None,
|
| 118 |
+
"run_sd": None, "run_min": None, "run_max": None, "slowest_call_sec": None}
|
| 119 |
+
|
| 120 |
+
stage_root = Path(stage_root)
|
| 121 |
+
stage_root.mkdir(parents=True, exist_ok=True)
|
| 122 |
+
os.chmod(stage_root, 0o755)
|
| 123 |
+
scratch_root = stage_root / "scratch"
|
| 124 |
+
err_root = stage_root / "worker_stderr"
|
| 125 |
+
err_root.mkdir(parents=True, exist_ok=True)
|
| 126 |
+
module_dir = stage_root / "deliverable"
|
| 127 |
+
|
| 128 |
+
worker_script = stage_root / "prune_worker.py"
|
| 129 |
+
shutil.copyfile(TESTS_DIR / "prune_worker.py", worker_script)
|
| 130 |
+
os.chown(worker_script, 0, 0)
|
| 131 |
+
os.chmod(worker_script, 0o644)
|
| 132 |
+
|
| 133 |
+
try:
|
| 134 |
+
stage_deliverable(Path(deliverable), module_dir)
|
| 135 |
+
specs = build_specs(phase, stage_root, seeds)
|
| 136 |
+
results = runner.execute_runs(
|
| 137 |
+
specs, python_exe=PYTHON,
|
| 138 |
+
worker_script=str(worker_script),
|
| 139 |
+
module_dir=str(module_dir), entry_module=ENTRY_MODULE,
|
| 140 |
+
scratch_root=str(scratch_root), as_user=CANDIDATE_USER,
|
| 141 |
+
launch_prefix=launch_prefix, new_session=new_session, call_budget=call_timeout,
|
| 142 |
+
import_budget=import_timeout, stderr_root=str(err_root))
|
| 143 |
+
except SubmissionInvalid as exc:
|
| 144 |
+
record["detail"] = str(exc)
|
| 145 |
+
return record
|
| 146 |
+
|
| 147 |
+
failures = [r for r in results if r["error"]]
|
| 148 |
+
timings = [t for r in results for t in r["timings"]]
|
| 149 |
+
record["slowest_call_sec"] = round(max(timings), 3) if timings else None
|
| 150 |
+
if failures:
|
| 151 |
+
record["detail"] = (f"{len(failures)}/{len(results)} runs failed; first: "
|
| 152 |
+
f"{failures[0]['error'][:800]}")
|
| 153 |
+
return record
|
| 154 |
+
|
| 155 |
+
finals = [r["final"] for r in results]
|
| 156 |
+
per_draw = {}
|
| 157 |
+
for r in results:
|
| 158 |
+
per_draw.setdefault(r["draw"], []).append(r["final"])
|
| 159 |
+
record["per_draw_mean"] = {d: statistics.fmean(v) for d, v in per_draw.items()}
|
| 160 |
+
record["per_run_final"] = [round(v, 6) for v in finals]
|
| 161 |
+
record["valid"] = True
|
| 162 |
+
record["metric"] = statistics.fmean(finals)
|
| 163 |
+
record["run_sd"] = statistics.stdev(finals)
|
| 164 |
+
record["run_min"] = min(finals)
|
| 165 |
+
record["run_max"] = max(finals)
|
| 166 |
+
record["per_iteration_mean"] = [round(float(v), 4) for v in
|
| 167 |
+
np.mean(np.array([r["curve"] for r in results]), axis=0)]
|
| 168 |
+
record["reward"] = graded_reward(record["metric"], True)
|
| 169 |
+
record["detail"] = "all runs completed"
|
| 170 |
+
return record
|
tasks/activeprune-al-unlabeled-pool-pruning/tests/intermediate.sh
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
set -u
|
| 3 |
+
|
| 4 |
+
mkdir -p /logs/verifier
|
| 5 |
+
chown root:root /logs/verifier 2>/dev/null || true
|
| 6 |
+
chmod 755 /logs/verifier 2>/dev/null || true
|
| 7 |
+
rm -f /logs/verifier/reward.txt /logs/verifier/ctrf.json /logs/verifier/metric.json
|
| 8 |
+
|
| 9 |
+
trap 'if [ ! -s /logs/verifier/reward.txt ]; then printf "0\n" > /logs/verifier/reward.txt; fi' EXIT
|
| 10 |
+
|
| 11 |
+
chmod -R go-rwx /tests
|
| 12 |
+
|
| 13 |
+
export GRADE_SPLIT=intermediate
|
| 14 |
+
export OMP_NUM_THREADS=1
|
| 15 |
+
export OPENBLAS_NUM_THREADS=1
|
| 16 |
+
export MKL_NUM_THREADS=1
|
| 17 |
+
export PYTHONHASHSEED=0
|
| 18 |
+
|
| 19 |
+
cd /tests
|
| 20 |
+
/usr/local/bin/python3 -m pytest --ctrf /logs/verifier/ctrf.json /tests/test_state.py -rA
|
| 21 |
+
/usr/local/bin/python3 /tests/compute_reward.py
|
| 22 |
+
|
| 23 |
+
exit 0
|
tasks/activeprune-al-unlabeled-pool-pruning/tests/prune_worker.py
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import importlib.util
|
| 4 |
+
import json
|
| 5 |
+
import os
|
| 6 |
+
import random
|
| 7 |
+
import sys
|
| 8 |
+
import traceback
|
| 9 |
+
|
| 10 |
+
import numpy as np
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def _private_channel():
|
| 14 |
+
"""Move the protocol onto duplicated descriptors, then point fd 0/1 at /dev/null and
|
| 15 |
+
stderr so submitted code cannot read from or write into the channel."""
|
| 16 |
+
read_fd = os.dup(0)
|
| 17 |
+
write_fd = os.dup(1)
|
| 18 |
+
devnull = os.open(os.devnull, os.O_RDONLY)
|
| 19 |
+
os.dup2(devnull, 0)
|
| 20 |
+
os.close(devnull)
|
| 21 |
+
os.dup2(2, 1)
|
| 22 |
+
sys.stdin = open(os.devnull, "r")
|
| 23 |
+
sys.stdout = sys.stderr
|
| 24 |
+
return os.fdopen(read_fd, "r", encoding="utf-8"), \
|
| 25 |
+
os.fdopen(write_fd, "w", encoding="utf-8")
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def main():
|
| 29 |
+
module_dir, entry_module, pool_path = sys.argv[1:4]
|
| 30 |
+
channel_in, channel_out = _private_channel()
|
| 31 |
+
|
| 32 |
+
def emit(payload):
|
| 33 |
+
channel_out.write(json.dumps(payload) + "\n")
|
| 34 |
+
channel_out.flush()
|
| 35 |
+
|
| 36 |
+
try:
|
| 37 |
+
with open(pool_path, "r", encoding="utf-8") as fh:
|
| 38 |
+
pool_texts = json.load(fh)
|
| 39 |
+
sys.path.insert(0, module_dir)
|
| 40 |
+
spec = importlib.util.spec_from_file_location(
|
| 41 |
+
entry_module, os.path.join(module_dir, entry_module + ".py"))
|
| 42 |
+
if spec is None or spec.loader is None:
|
| 43 |
+
raise ImportError(f"cannot load {entry_module}.py from {module_dir}")
|
| 44 |
+
random.seed(0)
|
| 45 |
+
np.random.seed(0)
|
| 46 |
+
module = importlib.util.module_from_spec(spec)
|
| 47 |
+
sys.modules[entry_module] = module
|
| 48 |
+
spec.loader.exec_module(module)
|
| 49 |
+
prune = getattr(module, "prune")
|
| 50 |
+
if not callable(prune):
|
| 51 |
+
raise TypeError("prune is not callable")
|
| 52 |
+
except BaseException:
|
| 53 |
+
emit({"status": "startup_error", "detail": traceback.format_exc(limit=8)})
|
| 54 |
+
return 0
|
| 55 |
+
|
| 56 |
+
emit({"status": "ready"})
|
| 57 |
+
|
| 58 |
+
for line in channel_in:
|
| 59 |
+
line = line.strip()
|
| 60 |
+
if not line:
|
| 61 |
+
continue
|
| 62 |
+
request = json.loads(line)
|
| 63 |
+
if request.get("op") == "stop":
|
| 64 |
+
return 0
|
| 65 |
+
try:
|
| 66 |
+
result = prune(pool_texts,
|
| 67 |
+
request["available"],
|
| 68 |
+
request["labeled_indices"],
|
| 69 |
+
request["labeled_labels"],
|
| 70 |
+
request["keep"],
|
| 71 |
+
request["iteration"],
|
| 72 |
+
request["rng_seed"])
|
| 73 |
+
emit({"status": "ok", "selection": _as_int_list(result)})
|
| 74 |
+
except BaseException:
|
| 75 |
+
emit({"status": "call_error", "detail": traceback.format_exc(limit=8)})
|
| 76 |
+
return 0
|
| 77 |
+
return 0
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def _as_int_list(result):
|
| 81 |
+
"""Serialise the return value while preserving enough type information for the harness
|
| 82 |
+
to reject a wrong type. Anything unrecognised is passed through as its type name."""
|
| 83 |
+
if isinstance(result, (list, tuple)):
|
| 84 |
+
items = list(result)
|
| 85 |
+
else:
|
| 86 |
+
shape = getattr(result, "shape", None)
|
| 87 |
+
dtype = getattr(result, "dtype", None)
|
| 88 |
+
if shape is None or dtype is None:
|
| 89 |
+
return {"bad_type": type(result).__name__}
|
| 90 |
+
if len(shape) != 1 or dtype.kind not in "iu":
|
| 91 |
+
return {"bad_type": f"array(ndim={len(shape)}, dtype={dtype})"}
|
| 92 |
+
items = result.tolist()
|
| 93 |
+
out = []
|
| 94 |
+
for value in items:
|
| 95 |
+
if isinstance(value, bool):
|
| 96 |
+
return {"bad_type": "element bool"}
|
| 97 |
+
if not isinstance(value, int):
|
| 98 |
+
try:
|
| 99 |
+
as_int = value.__index__()
|
| 100 |
+
except Exception:
|
| 101 |
+
return {"bad_type": f"element {type(value).__name__}"}
|
| 102 |
+
out.append(as_int)
|
| 103 |
+
else:
|
| 104 |
+
out.append(value)
|
| 105 |
+
return out
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
if __name__ == "__main__":
|
| 109 |
+
sys.exit(main())
|
tasks/activeprune-al-unlabeled-pool-pruning/tests/requirements-verifier.txt
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
pytest==8.3.5
|
| 2 |
+
pytest-json-ctrf==0.3.5
|
tasks/activeprune-al-unlabeled-pool-pruning/tests/requirements.txt
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
numpy==2.5.2
|
| 2 |
+
scipy==1.18.0
|
| 3 |
+
scikit-learn==1.9.0
|
| 4 |
+
joblib==1.5.3
|
| 5 |
+
threadpoolctl==3.6.0
|
tasks/activeprune-al-unlabeled-pool-pruning/tests/runner.py
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
import os
|
| 5 |
+
import pwd
|
| 6 |
+
import shutil
|
| 7 |
+
import sys
|
| 8 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
|
| 11 |
+
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
| 12 |
+
|
| 13 |
+
import al_loop
|
| 14 |
+
from worker_client import CALL_BUDGET_SEC, IMPORT_BUDGET_SEC, PruneWorker, PrunerFailure
|
| 15 |
+
|
| 16 |
+
MAX_CONCURRENT_RUNS = 6
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def stage_pool_texts(texts, path):
|
| 20 |
+
"""Write the pool text list where a worker can read it (texts only: no labels)."""
|
| 21 |
+
tmp = str(path) + ".tmp"
|
| 22 |
+
with open(tmp, "w", encoding="utf-8") as fh:
|
| 23 |
+
json.dump(list(texts), fh, ensure_ascii=False)
|
| 24 |
+
os.replace(tmp, path)
|
| 25 |
+
os.chmod(path, 0o644)
|
| 26 |
+
return str(path)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def make_readonly(tree):
|
| 30 |
+
"""Strip every write bit from a staged tree. The scoring harness hands the pruner a
|
| 31 |
+
read-only copy of the deliverable so no seeded run can leave anything on disk for the next
|
| 32 |
+
one; the development runner does the same, so a solution that needs to write at run time
|
| 33 |
+
fails locally rather than at grade time."""
|
| 34 |
+
os.chmod(tree, 0o555)
|
| 35 |
+
for base, dirs, files in os.walk(tree):
|
| 36 |
+
for name in dirs:
|
| 37 |
+
os.chmod(os.path.join(base, name), 0o555)
|
| 38 |
+
for name in files:
|
| 39 |
+
os.chmod(os.path.join(base, name), 0o444)
|
| 40 |
+
return tree
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def _make_scratch(root, name, as_user):
|
| 44 |
+
path = os.path.join(root, name)
|
| 45 |
+
shutil.rmtree(path, ignore_errors=True)
|
| 46 |
+
os.makedirs(path, exist_ok=True)
|
| 47 |
+
if as_user:
|
| 48 |
+
entry = pwd.getpwnam(as_user)
|
| 49 |
+
os.lchown(path, entry.pw_uid, entry.pw_gid)
|
| 50 |
+
os.chmod(path, 0o700)
|
| 51 |
+
return path
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def execute_runs(specs, *, python_exe, worker_script, module_dir, entry_module, scratch_root,
|
| 55 |
+
as_user=None, launch_prefix=None, new_session=os.setsid,
|
| 56 |
+
max_workers=MAX_CONCURRENT_RUNS,
|
| 57 |
+
call_budget=CALL_BUDGET_SEC, import_budget=IMPORT_BUDGET_SEC,
|
| 58 |
+
stderr_root=None):
|
| 59 |
+
"""specs: iterable of dicts with keys draw, seed, pool_labels, pool_X, eval_y, eval_X,
|
| 60 |
+
pool_texts_path. Returns one result dict per spec, in the input order."""
|
| 61 |
+
os.makedirs(scratch_root, exist_ok=True)
|
| 62 |
+
|
| 63 |
+
def one(index_spec):
|
| 64 |
+
index, spec = index_spec
|
| 65 |
+
tag = f"run_{spec['draw']}_{spec['seed']}"
|
| 66 |
+
scratch = _make_scratch(scratch_root, tag, as_user)
|
| 67 |
+
stderr_path = os.path.join(stderr_root, tag + ".err") if stderr_root else None
|
| 68 |
+
worker = PruneWorker(python_exe, worker_script, module_dir, entry_module,
|
| 69 |
+
spec["pool_texts_path"], scratch, launch_prefix=launch_prefix,
|
| 70 |
+
new_session=new_session, stderr_path=stderr_path,
|
| 71 |
+
call_budget=call_budget,
|
| 72 |
+
import_budget=import_budget)
|
| 73 |
+
result = {"index": index, "draw": spec["draw"], "seed": spec["seed"],
|
| 74 |
+
"curve": None, "final": None, "timings": [], "error": None}
|
| 75 |
+
try:
|
| 76 |
+
worker.start()
|
| 77 |
+
curve = al_loop.run_al(spec["pool_labels"], spec["pool_X"], spec["eval_y"],
|
| 78 |
+
spec["eval_X"], spec["seed"], worker.call)
|
| 79 |
+
result["curve"] = [float(v) for v in curve]
|
| 80 |
+
result["final"] = float(curve[-1])
|
| 81 |
+
except (PrunerFailure, al_loop.InvalidSelection) as exc:
|
| 82 |
+
result["error"] = f"{type(exc).__name__}: {exc}"
|
| 83 |
+
except Exception as exc:
|
| 84 |
+
result["error"] = f"harness error: {type(exc).__name__}: {exc}"
|
| 85 |
+
finally:
|
| 86 |
+
result["timings"] = [round(t, 3) for t in worker.timings]
|
| 87 |
+
worker.close()
|
| 88 |
+
shutil.rmtree(scratch, ignore_errors=True)
|
| 89 |
+
return result
|
| 90 |
+
|
| 91 |
+
with ThreadPoolExecutor(max_workers=max_workers) as pool:
|
| 92 |
+
results = list(pool.map(one, list(enumerate(specs))))
|
| 93 |
+
results.sort(key=lambda r: r["index"])
|
| 94 |
+
return results
|
tasks/activeprune-al-unlabeled-pool-pruning/tests/test.sh
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
set -u
|
| 3 |
+
|
| 4 |
+
mkdir -p /logs/verifier
|
| 5 |
+
chown root:root /logs/verifier 2>/dev/null || true
|
| 6 |
+
chmod 755 /logs/verifier 2>/dev/null || true
|
| 7 |
+
rm -f /logs/verifier/reward.txt /logs/verifier/ctrf.json /logs/verifier/metric.json
|
| 8 |
+
|
| 9 |
+
trap 'if [ ! -s /logs/verifier/reward.txt ]; then printf "0\n" > /logs/verifier/reward.txt; fi' EXIT
|
| 10 |
+
|
| 11 |
+
chmod -R go-rwx /tests
|
| 12 |
+
|
| 13 |
+
export GRADE_SPLIT=final
|
| 14 |
+
export OMP_NUM_THREADS=1
|
| 15 |
+
export OPENBLAS_NUM_THREADS=1
|
| 16 |
+
export MKL_NUM_THREADS=1
|
| 17 |
+
export PYTHONHASHSEED=0
|
| 18 |
+
|
| 19 |
+
cd /tests
|
| 20 |
+
/usr/local/bin/python3 -m pytest --ctrf /logs/verifier/ctrf.json /tests/test_state.py -rA
|
| 21 |
+
/usr/local/bin/python3 /tests/compute_reward.py
|
| 22 |
+
|
| 23 |
+
exit 0
|
tasks/activeprune-al-unlabeled-pool-pruning/tests/test_state.py
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
import math
|
| 5 |
+
import os
|
| 6 |
+
import sys
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
|
| 9 |
+
import pytest
|
| 10 |
+
|
| 11 |
+
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
| 12 |
+
|
| 13 |
+
import grader_core
|
| 14 |
+
|
| 15 |
+
PHASE = os.environ.get("GRADE_SPLIT", "final")
|
| 16 |
+
METRIC_PATH = Path("/logs/verifier/metric.json")
|
| 17 |
+
|
| 18 |
+
LAUNCH_PREFIX = ["/sbin/runuser", "-u", grader_core.CANDIDATE_USER, "--"]
|
| 19 |
+
NEW_SESSION = os.setsid
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
@pytest.fixture(scope="session")
|
| 23 |
+
def result():
|
| 24 |
+
record = grader_core.grade(phase=PHASE, launch_prefix=LAUNCH_PREFIX,
|
| 25 |
+
new_session=NEW_SESSION,
|
| 26 |
+
call_timeout=grader_core.CALL_BUDGET_SEC,
|
| 27 |
+
import_timeout=grader_core.IMPORT_BUDGET_SEC)
|
| 28 |
+
METRIC_PATH.parent.mkdir(parents=True, exist_ok=True)
|
| 29 |
+
METRIC_PATH.write_text(json.dumps(record, indent=2, sort_keys=True))
|
| 30 |
+
print(f"phase : {record['phase']}")
|
| 31 |
+
print(f"runs in panel : {record['n_runs']}")
|
| 32 |
+
print(f"submission valid : {record['valid']}")
|
| 33 |
+
print(f"detail : {record['detail']}")
|
| 34 |
+
if record["valid"]:
|
| 35 |
+
print(f"mean final macro-F1 : {record['metric']:.4f}")
|
| 36 |
+
print(f"across-run sd : {record['run_sd']:.4f}")
|
| 37 |
+
print(f"run min / max : {record['run_min']:.4f} / {record['run_max']:.4f}")
|
| 38 |
+
print("mean macro-F1 by AL iteration: "
|
| 39 |
+
+ " ".join(f"{v:.3f}" for v in record["per_iteration_mean"]))
|
| 40 |
+
print(f"slowest prune call : {record['slowest_call_sec']}s of "
|
| 41 |
+
f"{grader_core.CALL_BUDGET_SEC:g}s")
|
| 42 |
+
return record
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def test_deliverable_is_stageable(result):
|
| 46 |
+
"""The deliverable directory exists, holds a non-empty prune.py, and contains no symlink
|
| 47 |
+
or hard link -- a submitted link would let the staging copy reach outside the tree."""
|
| 48 |
+
assert result["detail"] != "", "grade produced no detail string"
|
| 49 |
+
assert "contains links" not in result["detail"], result["detail"]
|
| 50 |
+
assert "missing or empty entry point" not in result["detail"], result["detail"]
|
| 51 |
+
assert "no deliverable directory" not in result["detail"], result["detail"]
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def test_every_seeded_run_completed(result):
|
| 55 |
+
"""Every run in the sealed panel imported the module, answered all five prune calls
|
| 56 |
+
inside the per-call budget, and returned a selection the protocol accepts."""
|
| 57 |
+
assert result["valid"], result["detail"]
|
| 58 |
+
assert result["slowest_call_sec"] <= grader_core.CALL_BUDGET_SEC
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def test_metric_is_recorded(result):
|
| 62 |
+
"""The recorded metric is a finite macro-F1 in percent, and the reward derived from it is
|
| 63 |
+
inside [0, 1]."""
|
| 64 |
+
assert METRIC_PATH.is_file()
|
| 65 |
+
assert result["metric"] is not None and math.isfinite(result["metric"])
|
| 66 |
+
assert 0.0 <= result["metric"] <= 100.0
|
| 67 |
+
assert 0.0 <= result["reward"] <= 1.0
|
tasks/activeprune-al-unlabeled-pool-pruning/tests/worker_client.py
ADDED
|
@@ -0,0 +1,169 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
import os
|
| 5 |
+
import selectors
|
| 6 |
+
import signal
|
| 7 |
+
import subprocess
|
| 8 |
+
import time
|
| 9 |
+
|
| 10 |
+
IMPORT_BUDGET_SEC = 60.0
|
| 11 |
+
CALL_BUDGET_SEC = 20.0
|
| 12 |
+
ADDRESS_SPACE_LIMIT = 4 * 1024 ** 3
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class PrunerFailure(RuntimeError):
|
| 16 |
+
"""The submitted pruner crashed, timed out, or broke the protocol."""
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class PruneWorker:
|
| 20 |
+
def __init__(self, python_exe, worker_script, module_dir, entry_module, pool_texts_path,
|
| 21 |
+
scratch_dir, launch_prefix=None, new_session=os.setsid,
|
| 22 |
+
stderr_path=None, call_budget=CALL_BUDGET_SEC,
|
| 23 |
+
import_budget=IMPORT_BUDGET_SEC,
|
| 24 |
+
address_space_limit=ADDRESS_SPACE_LIMIT):
|
| 25 |
+
self.python_exe = python_exe
|
| 26 |
+
self.worker_script = worker_script
|
| 27 |
+
self.module_dir = module_dir
|
| 28 |
+
self.entry_module = entry_module
|
| 29 |
+
self.pool_texts_path = pool_texts_path
|
| 30 |
+
self.scratch_dir = scratch_dir
|
| 31 |
+
self.launch_prefix = list(launch_prefix) if launch_prefix else []
|
| 32 |
+
self.new_session = new_session
|
| 33 |
+
self.stderr_path = stderr_path
|
| 34 |
+
self.call_budget = call_budget
|
| 35 |
+
self.import_budget = import_budget
|
| 36 |
+
self.address_space_limit = address_space_limit
|
| 37 |
+
self.proc = None
|
| 38 |
+
self._selector = None
|
| 39 |
+
self._stderr = None
|
| 40 |
+
self.timings = []
|
| 41 |
+
|
| 42 |
+
def _argv(self):
|
| 43 |
+
return self.launch_prefix + [self.python_exe, self.worker_script, self.module_dir,
|
| 44 |
+
self.entry_module, self.pool_texts_path]
|
| 45 |
+
|
| 46 |
+
def _child_setup(self):
|
| 47 |
+
limit = self.address_space_limit
|
| 48 |
+
new_session = self.new_session
|
| 49 |
+
|
| 50 |
+
def apply():
|
| 51 |
+
new_session()
|
| 52 |
+
import resource
|
| 53 |
+
resource.setrlimit(resource.RLIMIT_AS, (limit, limit))
|
| 54 |
+
resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
|
| 55 |
+
return apply
|
| 56 |
+
|
| 57 |
+
def start(self):
|
| 58 |
+
env = {
|
| 59 |
+
"PATH": "/usr/local/bin:/usr/bin:/bin",
|
| 60 |
+
"HOME": self.scratch_dir,
|
| 61 |
+
"TMPDIR": self.scratch_dir,
|
| 62 |
+
"PYTHONHASHSEED": "0",
|
| 63 |
+
"PYTHONDONTWRITEBYTECODE": "1",
|
| 64 |
+
"OMP_NUM_THREADS": "1",
|
| 65 |
+
"OPENBLAS_NUM_THREADS": "1",
|
| 66 |
+
"MKL_NUM_THREADS": "1",
|
| 67 |
+
"NUMEXPR_NUM_THREADS": "1",
|
| 68 |
+
"VECLIB_MAXIMUM_THREADS": "1",
|
| 69 |
+
}
|
| 70 |
+
self._stderr = open(self.stderr_path, "ab") if self.stderr_path \
|
| 71 |
+
else open(os.devnull, "wb")
|
| 72 |
+
self.proc = subprocess.Popen(
|
| 73 |
+
self._argv(), stdin=subprocess.PIPE, stdout=subprocess.PIPE,
|
| 74 |
+
stderr=self._stderr, cwd=self.scratch_dir, env=env, text=True,
|
| 75 |
+
bufsize=1, preexec_fn=self._child_setup())
|
| 76 |
+
self._selector = selectors.DefaultSelector()
|
| 77 |
+
self._selector.register(self.proc.stdout, selectors.EVENT_READ)
|
| 78 |
+
hello = self._read(self.import_budget, "module import")
|
| 79 |
+
if hello.get("status") != "ready":
|
| 80 |
+
detail = hello.get("detail", hello)
|
| 81 |
+
self.kill()
|
| 82 |
+
raise PrunerFailure(f"module did not import: {detail}")
|
| 83 |
+
|
| 84 |
+
def kill(self):
|
| 85 |
+
if self.proc is None:
|
| 86 |
+
return
|
| 87 |
+
try:
|
| 88 |
+
os.killpg(self.proc.pid, signal.SIGKILL)
|
| 89 |
+
except (ProcessLookupError, PermissionError):
|
| 90 |
+
try:
|
| 91 |
+
self.proc.kill()
|
| 92 |
+
except ProcessLookupError:
|
| 93 |
+
pass
|
| 94 |
+
try:
|
| 95 |
+
self.proc.wait(timeout=15)
|
| 96 |
+
except subprocess.TimeoutExpired:
|
| 97 |
+
pass
|
| 98 |
+
if self._selector is not None:
|
| 99 |
+
self._selector.close()
|
| 100 |
+
self._selector = None
|
| 101 |
+
if self._stderr is not None:
|
| 102 |
+
self._stderr.close()
|
| 103 |
+
self._stderr = None
|
| 104 |
+
self.proc = None
|
| 105 |
+
|
| 106 |
+
def close(self):
|
| 107 |
+
if self.proc is None:
|
| 108 |
+
return
|
| 109 |
+
try:
|
| 110 |
+
self.proc.stdin.write(json.dumps({"op": "stop"}) + "\n")
|
| 111 |
+
self.proc.stdin.flush()
|
| 112 |
+
self.proc.wait(timeout=10)
|
| 113 |
+
except Exception:
|
| 114 |
+
pass
|
| 115 |
+
self.kill()
|
| 116 |
+
|
| 117 |
+
def _read(self, budget, what):
|
| 118 |
+
deadline = time.monotonic() + budget
|
| 119 |
+
while True:
|
| 120 |
+
remaining = deadline - time.monotonic()
|
| 121 |
+
if remaining <= 0:
|
| 122 |
+
self.kill()
|
| 123 |
+
raise PrunerFailure(f"{what} exceeded its {budget:g}s budget")
|
| 124 |
+
if not self._selector.select(timeout=min(remaining, 1.0)):
|
| 125 |
+
if self.proc.poll() is not None:
|
| 126 |
+
self.kill()
|
| 127 |
+
raise PrunerFailure(f"{what}: process exited without replying")
|
| 128 |
+
continue
|
| 129 |
+
line = self.proc.stdout.readline()
|
| 130 |
+
if line == "":
|
| 131 |
+
self.kill()
|
| 132 |
+
raise PrunerFailure(f"{what}: channel closed without a reply")
|
| 133 |
+
line = line.strip()
|
| 134 |
+
if not line:
|
| 135 |
+
continue
|
| 136 |
+
try:
|
| 137 |
+
return json.loads(line)
|
| 138 |
+
except json.JSONDecodeError as exc:
|
| 139 |
+
self.kill()
|
| 140 |
+
raise PrunerFailure(f"{what}: unparseable reply ({exc})") from None
|
| 141 |
+
|
| 142 |
+
def call(self, available, labeled_indices, labeled_labels, keep, iteration, rng_seed):
|
| 143 |
+
if self.proc is None:
|
| 144 |
+
raise PrunerFailure("worker is not running")
|
| 145 |
+
request = {"op": "prune", "available": list(map(int, available)),
|
| 146 |
+
"labeled_indices": list(map(int, labeled_indices)),
|
| 147 |
+
"labeled_labels": list(map(int, labeled_labels)),
|
| 148 |
+
"keep": int(keep), "iteration": int(iteration),
|
| 149 |
+
"rng_seed": int(rng_seed)}
|
| 150 |
+
started = time.monotonic()
|
| 151 |
+
try:
|
| 152 |
+
self.proc.stdin.write(json.dumps(request) + "\n")
|
| 153 |
+
self.proc.stdin.flush()
|
| 154 |
+
except (BrokenPipeError, ValueError) as exc:
|
| 155 |
+
self.kill()
|
| 156 |
+
raise PrunerFailure(f"pruner is gone before iteration {iteration}: {exc}") from None
|
| 157 |
+
reply = self._read(self.call_budget, f"prune call at iteration {iteration}")
|
| 158 |
+
self.timings.append(time.monotonic() - started)
|
| 159 |
+
if reply.get("status") != "ok":
|
| 160 |
+
detail = reply.get("detail", reply)
|
| 161 |
+
self.kill()
|
| 162 |
+
raise PrunerFailure(f"pruner raised at iteration {iteration}: {detail}")
|
| 163 |
+
selection = reply.get("selection")
|
| 164 |
+
if isinstance(selection, dict):
|
| 165 |
+
self.kill()
|
| 166 |
+
raise PrunerFailure(
|
| 167 |
+
f"pruner returned an unusable type at iteration {iteration}: "
|
| 168 |
+
f"{selection.get('bad_type')}")
|
| 169 |
+
return selection
|
tasks/budgeted-imputation-mcar50/environment/Dockerfile
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM --platform=linux/amd64 public.ecr.aws/docker/library/python:3.13-slim-bookworm@sha256:01f42367a0a94ad4bc17111776fd66e3500c1d87c15bbd6055b7371d39c124fb
|
| 2 |
+
|
| 3 |
+
RUN set -eu; \
|
| 4 |
+
if [ ! -s /etc/ssl/certs/ca-certificates.crt ]; then \
|
| 5 |
+
apt-get update && apt-get install -y --no-install-recommends ca-certificates=20230311+deb12u1; \
|
| 6 |
+
fi; \
|
| 7 |
+
rm -f /tmp/hz-prereq.list; \
|
| 8 |
+
echo 'deb [signed-by=/usr/share/keyrings/debian-archive-keyring.gpg] https://snapshot.debian.org/archive/debian/20260801T000000Z bookworm main' >> /tmp/hz-prereq.list; \
|
| 9 |
+
echo 'deb [signed-by=/usr/share/keyrings/debian-archive-keyring.gpg] https://snapshot.debian.org/archive/debian-security/20260801T000000Z bookworm-security main' >> /tmp/hz-prereq.list; \
|
| 10 |
+
apt-get -o Dir::Etc::sourcelist=/tmp/hz-prereq.list -o Dir::Etc::sourceparts=/dev/null -o Acquire::Check-Valid-Until=false update; \
|
| 11 |
+
apt-get -o Dir::Etc::sourcelist=/tmp/hz-prereq.list -o Dir::Etc::sourceparts=/dev/null -o Acquire::Check-Valid-Until=false install -y --no-install-recommends tmux=3.3a-3 asciinema=2.2.0-1 git=1:2.39.5-0+deb12u3; \
|
| 12 |
+
rm -f /tmp/hz-prereq.list; rm -rf /var/lib/apt/lists/*
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
ENTRYPOINT []
|
| 16 |
+
ENV DEBIAN_FRONTEND=noninteractive \
|
| 17 |
+
PYTHONHASHSEED=0 \
|
| 18 |
+
PIP_NO_CACHE_DIR=1 \
|
| 19 |
+
PIP_DISABLE_PIP_VERSION_CHECK=1 \
|
| 20 |
+
OMP_NUM_THREADS=1
|
| 21 |
+
|
| 22 |
+
RUN git config --system user.email "agent@localhost" \
|
| 23 |
+
&& git config --system user.name "autoresearch agent"
|
| 24 |
+
|
| 25 |
+
RUN useradd --create-home --uid 1001 agent
|
| 26 |
+
|
| 27 |
+
COPY ./requirements.txt /tmp/requirements.txt
|
| 28 |
+
RUN /usr/local/bin/python3 -m pip install --no-cache-dir -r /tmp/requirements.txt \
|
| 29 |
+
&& rm /tmp/requirements.txt
|
| 30 |
+
|
| 31 |
+
WORKDIR /app
|
| 32 |
+
COPY ./app /app
|
| 33 |
+
|
| 34 |
+
RUN mkdir -p /app/output \
|
| 35 |
+
&& chown -R agent:agent /app \
|
| 36 |
+
&& find /app -exec touch -d @1700000000 {} +
|
| 37 |
+
|
| 38 |
+
ENV HF_HUB_OFFLINE=1
|
| 39 |
+
ENV TRANSFORMERS_OFFLINE=1
|
| 40 |
+
|
| 41 |
+
USER agent
|
tasks/budgeted-imputation-mcar50/environment/requirements.txt
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
numpy==2.5.2
|
| 2 |
+
scipy==1.18.0
|
| 3 |
+
scikit-learn==1.9.0
|
| 4 |
+
joblib==1.5.3
|
| 5 |
+
threadpoolctl==3.6.0
|
tasks/budgeted-imputation-mcar50/hints/hint.md
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
Fit a joint-Gaussian conditional mean on the train and eval rows stacked together, then a per-column gradient-boosted model on its residuals, blended per feature with weights estimated on held-out entries. Build the blend's calibration rows so the target never leaked through an already-imputed predictor. The hidden panel is wider than the dev panel, so profile a synthetic worst-case at maximum dimension, and put a deadline guard with a column-mean fallback on every path.
|
tasks/budgeted-imputation-mcar50/tests/Dockerfile
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM --platform=linux/amd64 public.ecr.aws/docker/library/python:3.13-slim-bookworm@sha256:01f42367a0a94ad4bc17111776fd66e3500c1d87c15bbd6055b7371d39c124fb
|
| 2 |
+
|
| 3 |
+
ENTRYPOINT []
|
| 4 |
+
ENV PYTHONPATH=
|
| 5 |
+
ENV PYTHONSAFEPATH=1
|
| 6 |
+
ENV DEBIAN_FRONTEND=noninteractive \
|
| 7 |
+
PYTHONHASHSEED=0 \
|
| 8 |
+
PIP_NO_CACHE_DIR=1 \
|
| 9 |
+
PIP_DISABLE_PIP_VERSION_CHECK=1 \
|
| 10 |
+
OMP_NUM_THREADS=1 \
|
| 11 |
+
MKL_NUM_THREADS=1 \
|
| 12 |
+
OPENBLAS_NUM_THREADS=1
|
| 13 |
+
|
| 14 |
+
RUN useradd --create-home --uid 1001 agent
|
| 15 |
+
|
| 16 |
+
COPY ./requirements.txt /tmp/requirements.txt
|
| 17 |
+
COPY ./requirements-verifier.txt /tmp/requirements-verifier.txt
|
| 18 |
+
RUN /usr/local/bin/python3 -m pip install --no-cache-dir \
|
| 19 |
+
-r /tmp/requirements.txt -r /tmp/requirements-verifier.txt \
|
| 20 |
+
&& rm /tmp/requirements.txt /tmp/requirements-verifier.txt
|
| 21 |
+
|
| 22 |
+
RUN mkdir -p /app/output /logs/verifier /opt/grade
|
| 23 |
+
|
| 24 |
+
COPY . /tests
|
| 25 |
+
|
| 26 |
+
RUN chown -R root:root /tests \
|
| 27 |
+
&& chmod 700 /tests \
|
| 28 |
+
&& chmod 700 /tests/hidden_data /tests/hidden_data/intermediate /tests/hidden_data/final \
|
| 29 |
+
&& chmod +x /tests/test.sh /tests/intermediate.sh \
|
| 30 |
+
&& find /tests -exec touch -d @1700000000 {} +
|
| 31 |
+
|
| 32 |
+
WORKDIR /tests
|
| 33 |
+
|
| 34 |
+
ENV HF_HUB_OFFLINE=1
|
| 35 |
+
ENV TRANSFORMERS_OFFLINE=1
|
tasks/budgeted-imputation-mcar50/tests/cellrunner.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sys
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def main() -> int:
|
| 7 |
+
in_path, out_path, module_dir = sys.argv[1], sys.argv[2], sys.argv[3]
|
| 8 |
+
|
| 9 |
+
with np.load(in_path, allow_pickle=False) as data:
|
| 10 |
+
X_train = np.ascontiguousarray(data["X_train"], dtype=np.float64)
|
| 11 |
+
X_eval = np.ascontiguousarray(data["X_eval"], dtype=np.float64)
|
| 12 |
+
seed = int(data["seed"][0])
|
| 13 |
+
|
| 14 |
+
sys.path.insert(0, module_dir)
|
| 15 |
+
import impute
|
| 16 |
+
|
| 17 |
+
result = impute.impute(X_train, X_eval, seed)
|
| 18 |
+
|
| 19 |
+
np.save(out_path, np.asarray(result), allow_pickle=False)
|
| 20 |
+
return 0
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
if __name__ == "__main__":
|
| 24 |
+
sys.exit(main())
|
tasks/budgeted-imputation-mcar50/tests/cellspec.py
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
from sklearn.preprocessing import QuantileTransformer
|
| 5 |
+
|
| 6 |
+
MISSING_RATE = 0.50
|
| 7 |
+
|
| 8 |
+
QT_N_QUANTILES = 1000
|
| 9 |
+
QT_SUBSAMPLE = 100_000
|
| 10 |
+
QT_RANDOM_STATE = 0
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def build_cell(X, seed, n_train, n_eval):
|
| 14 |
+
"""Build one cell from the raw feature matrix `X` (float64, no missing values).
|
| 15 |
+
|
| 16 |
+
Rows are permuted with `seed` and then *partitioned*: the first `n_train` rows of the
|
| 17 |
+
permutation become the training rows and the next `n_eval` become the evaluation rows,
|
| 18 |
+
so the two are disjoint by construction. Independent MCAR masks at MISSING_RATE are
|
| 19 |
+
drawn for each matrix from the same generator. A QuantileTransformer with a normal
|
| 20 |
+
output distribution is fitted on the *incomplete* training matrix and applied to both.
|
| 21 |
+
|
| 22 |
+
Returns (X_train, X_eval, X_eval_true, mask_eval):
|
| 23 |
+
X_train (n_train, d) float64, gaussianized, np.nan at masked entries
|
| 24 |
+
X_eval (n_eval, d) float64, gaussianized, np.nan at masked entries
|
| 25 |
+
X_eval_true (n_eval, d) float64, gaussianized, complete -- the ground truth
|
| 26 |
+
mask_eval (n_eval, d) bool, True where X_eval is missing
|
| 27 |
+
"""
|
| 28 |
+
X = np.asarray(X, dtype=np.float64)
|
| 29 |
+
n_rows = X.shape[0]
|
| 30 |
+
if n_train + n_eval > n_rows:
|
| 31 |
+
raise ValueError(f"cell needs {n_train + n_eval} rows, matrix has {n_rows}")
|
| 32 |
+
|
| 33 |
+
rng = np.random.default_rng(seed)
|
| 34 |
+
perm = rng.permutation(n_rows)
|
| 35 |
+
rows_train = perm[:n_train]
|
| 36 |
+
rows_eval = perm[n_train : n_train + n_eval]
|
| 37 |
+
|
| 38 |
+
raw_train = X[rows_train]
|
| 39 |
+
raw_eval = X[rows_eval]
|
| 40 |
+
|
| 41 |
+
mask_train = rng.random(raw_train.shape) < MISSING_RATE
|
| 42 |
+
mask_eval = rng.random(raw_eval.shape) < MISSING_RATE
|
| 43 |
+
|
| 44 |
+
incomplete_train = raw_train.copy()
|
| 45 |
+
incomplete_train[mask_train] = np.nan
|
| 46 |
+
|
| 47 |
+
qt = QuantileTransformer(
|
| 48 |
+
output_distribution="normal",
|
| 49 |
+
n_quantiles=min(QT_N_QUANTILES, n_train),
|
| 50 |
+
subsample=QT_SUBSAMPLE,
|
| 51 |
+
random_state=QT_RANDOM_STATE,
|
| 52 |
+
copy=True,
|
| 53 |
+
)
|
| 54 |
+
qt.fit(incomplete_train)
|
| 55 |
+
|
| 56 |
+
X_train = np.ascontiguousarray(qt.transform(incomplete_train), dtype=np.float64)
|
| 57 |
+
X_eval_true = np.ascontiguousarray(qt.transform(raw_eval), dtype=np.float64)
|
| 58 |
+
X_eval = X_eval_true.copy()
|
| 59 |
+
X_eval[mask_eval] = np.nan
|
| 60 |
+
|
| 61 |
+
return X_train, X_eval, X_eval_true, mask_eval
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def imputation_r2(X_pred, X_true, mask):
|
| 65 |
+
"""Per-feature R^2 over masked entries, averaged unweighted over features.
|
| 66 |
+
|
| 67 |
+
For feature j, over the entries where `mask` is True:
|
| 68 |
+
R2_j = 1 - sum((true - pred)^2) / sum((true - mean(true))^2)
|
| 69 |
+
Features with fewer than two masked entries, or with a degenerate ground-truth
|
| 70 |
+
variance over those entries, are skipped. Returns the mean of the kept features.
|
| 71 |
+
"""
|
| 72 |
+
X_pred = np.asarray(X_pred, dtype=np.float64)
|
| 73 |
+
X_true = np.asarray(X_true, dtype=np.float64)
|
| 74 |
+
mask = np.asarray(mask, dtype=bool)
|
| 75 |
+
|
| 76 |
+
scores = []
|
| 77 |
+
for j in range(X_true.shape[1]):
|
| 78 |
+
sel = mask[:, j]
|
| 79 |
+
if int(sel.sum()) < 2:
|
| 80 |
+
continue
|
| 81 |
+
truth = X_true[sel, j]
|
| 82 |
+
pred = X_pred[sel, j]
|
| 83 |
+
ss_tot = float(np.sum((truth - truth.mean()) ** 2))
|
| 84 |
+
if not np.isfinite(ss_tot) or ss_tot <= 1e-12:
|
| 85 |
+
continue
|
| 86 |
+
ss_res = float(np.sum((truth - pred) ** 2))
|
| 87 |
+
scores.append(1.0 - ss_res / ss_tot)
|
| 88 |
+
|
| 89 |
+
if not scores:
|
| 90 |
+
raise ValueError("no scorable feature in this cell")
|
| 91 |
+
return float(np.mean(scores))
|
tasks/budgeted-imputation-mcar50/tests/compute_reward.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import math
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
|
| 5 |
+
REWARD_PATH = Path("/logs/verifier/reward.txt")
|
| 6 |
+
|
| 7 |
+
try:
|
| 8 |
+
REWARD_PATH.parent.mkdir(parents=True, exist_ok=True)
|
| 9 |
+
value = float(json.loads(Path("/logs/verifier/metric.json").read_text())["reward"])
|
| 10 |
+
if not math.isfinite(value):
|
| 11 |
+
raise ValueError("non-finite reward")
|
| 12 |
+
reward = f"{min(1.0, max(0.0, value)):.12g}"
|
| 13 |
+
REWARD_PATH.write_text(reward + "\n")
|
| 14 |
+
print(f"reward={reward}")
|
| 15 |
+
except Exception as exc:
|
| 16 |
+
try:
|
| 17 |
+
REWARD_PATH.parent.mkdir(parents=True, exist_ok=True)
|
| 18 |
+
except Exception:
|
| 19 |
+
pass
|
| 20 |
+
REWARD_PATH.write_text("0\n")
|
| 21 |
+
print(f"reward=0 (fallback: {exc})")
|
tasks/budgeted-imputation-mcar50/tests/grader_core.py
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
import os
|
| 5 |
+
import sys
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
|
| 8 |
+
import numpy as np
|
| 9 |
+
|
| 10 |
+
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
| 11 |
+
|
| 12 |
+
import cellspec
|
| 13 |
+
|
| 14 |
+
HIDDEN_ROOT = Path("/tests/hidden_data")
|
| 15 |
+
|
| 16 |
+
DELIVERABLE_DIR = Path("/app/output")
|
| 17 |
+
ENTRY_POINT = DELIVERABLE_DIR / "impute.py"
|
| 18 |
+
ENTRY_FUNCTION = "impute"
|
| 19 |
+
CELL_BUDGET_SEC = 30.0
|
| 20 |
+
MAX_DELIVERABLE_FILES = 2000
|
| 21 |
+
MAX_DELIVERABLE_BYTES = 512 * 1024 * 1024
|
| 22 |
+
|
| 23 |
+
M0 = 0.00
|
| 24 |
+
BASELINE_SCORE = 0.30
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def graded_reward(metric: float) -> float:
|
| 28 |
+
"""rational_squash: 0 at the trivial baseline, 0.5 at the baseline score, no cutoff."""
|
| 29 |
+
x_ref = BASELINE_SCORE - M0
|
| 30 |
+
assert x_ref > 0, "malformed task: the baseline score does not beat the trivial baseline"
|
| 31 |
+
if not np.isfinite(metric):
|
| 32 |
+
return 0.0
|
| 33 |
+
u = max(0.0, float(metric) - M0) / x_ref
|
| 34 |
+
return u / (1.0 + u)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def load_manifest(half: str) -> dict:
|
| 38 |
+
with open(HIDDEN_ROOT / half / "manifest.json") as fh:
|
| 39 |
+
return json.load(fh)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def iter_cells(half: str):
|
| 43 |
+
"""Yield (cell_key, X_raw, seed, n_train, n_eval) for every graded cell of `half`."""
|
| 44 |
+
manifest = load_manifest(half)
|
| 45 |
+
for entry in manifest["datasets"]:
|
| 46 |
+
with np.load(HIDDEN_ROOT / half / entry["file"], allow_pickle=False) as data:
|
| 47 |
+
X = np.ascontiguousarray(data["X"], dtype=np.float64)
|
| 48 |
+
for k, seed in enumerate(entry["seeds"]):
|
| 49 |
+
yield (f"{entry['id']}:{k}", X, int(seed), entry["n_train"], entry["n_eval"])
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def score_submission(X_pred_raw, X_eval_true, mask_eval):
|
| 53 |
+
"""Validate an untrusted returned array, then score it. Returns (score, reason).
|
| 54 |
+
|
| 55 |
+
`score` is None when the array violates the contract. The reasons are deliberately
|
| 56 |
+
coarse: they are aggregated into the public grader's stdout, and a reason carrying the
|
| 57 |
+
expected shape would hand the agent the dimensions of a sealed dataset.
|
| 58 |
+
"""
|
| 59 |
+
arr = X_pred_raw
|
| 60 |
+
if not isinstance(arr, np.ndarray):
|
| 61 |
+
return None, "not_an_array"
|
| 62 |
+
if arr.dtype.kind != "f":
|
| 63 |
+
return None, "wrong_dtype"
|
| 64 |
+
if arr.shape != X_eval_true.shape:
|
| 65 |
+
return None, "wrong_shape"
|
| 66 |
+
arr = np.ascontiguousarray(arr, dtype=np.float64)
|
| 67 |
+
if not np.all(np.isfinite(arr)):
|
| 68 |
+
return None, "non_finite"
|
| 69 |
+
return cellspec.imputation_r2(arr, X_eval_true, mask_eval), "ok"
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def aggregate(cell_scores):
|
| 73 |
+
"""Unweighted mean over cells. An invalid cell contributes 0.0."""
|
| 74 |
+
if not cell_scores:
|
| 75 |
+
return 0.0
|
| 76 |
+
return float(np.mean([0.0 if s is None else float(s) for s in cell_scores]))
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def deliverable_files(root: Path):
|
| 80 |
+
"""Every regular, non-symlink file under `root`, deepest-first order irrelevant.
|
| 81 |
+
|
| 82 |
+
Symlinks are neither followed nor copied at any depth: a submitted
|
| 83 |
+
`weights.npy -> /tests/hidden_data/f1.npz` must never materialise anywhere the
|
| 84 |
+
grader or the candidate process can read it.
|
| 85 |
+
"""
|
| 86 |
+
kept, skipped_links = [], []
|
| 87 |
+
for dirpath, dirnames, filenames in os.walk(root, followlinks=False):
|
| 88 |
+
dirnames.sort()
|
| 89 |
+
for name in list(dirnames):
|
| 90 |
+
if os.path.islink(os.path.join(dirpath, name)):
|
| 91 |
+
dirnames.remove(name)
|
| 92 |
+
skipped_links.append(os.path.join(dirpath, name))
|
| 93 |
+
for name in sorted(filenames):
|
| 94 |
+
full = os.path.join(dirpath, name)
|
| 95 |
+
if os.path.islink(full):
|
| 96 |
+
skipped_links.append(full)
|
| 97 |
+
continue
|
| 98 |
+
if not os.path.isfile(full):
|
| 99 |
+
continue
|
| 100 |
+
kept.append(full)
|
| 101 |
+
return kept, skipped_links
|
tasks/budgeted-imputation-mcar50/tests/intermediate.sh
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
set -u
|
| 3 |
+
|
| 4 |
+
PY=/usr/local/bin/python3
|
| 5 |
+
|
| 6 |
+
mkdir -p /logs/verifier
|
| 7 |
+
chown root:root /logs/verifier 2>/dev/null || true
|
| 8 |
+
chmod 755 /logs/verifier 2>/dev/null || true
|
| 9 |
+
rm -f /logs/verifier/reward.txt /logs/verifier/ctrf.json /logs/verifier/metric.json
|
| 10 |
+
|
| 11 |
+
trap 'if [ ! -s /logs/verifier/reward.txt ]; then echo 0 > /logs/verifier/reward.txt; fi' EXIT
|
| 12 |
+
|
| 13 |
+
chmod -R go-rwx /tests
|
| 14 |
+
|
| 15 |
+
export GRADE_SPLIT=intermediate
|
| 16 |
+
export OMP_NUM_THREADS=1
|
| 17 |
+
export MKL_NUM_THREADS=1
|
| 18 |
+
export OPENBLAS_NUM_THREADS=1
|
| 19 |
+
|
| 20 |
+
cd /tests
|
| 21 |
+
"$PY" -m pytest --ctrf /logs/verifier/ctrf.json /tests/test_state.py -rA \
|
| 22 |
+
> /logs/verifier/pytest_intermediate.log 2>&1
|
| 23 |
+
"$PY" /tests/compute_reward.py > /logs/verifier/compute_reward.log 2>&1
|
| 24 |
+
|
| 25 |
+
"$PY" - <<'PY'
|
| 26 |
+
import json
|
| 27 |
+
from pathlib import Path
|
| 28 |
+
|
| 29 |
+
try:
|
| 30 |
+
rec = json.loads(Path("/logs/verifier/metric.json").read_text())
|
| 31 |
+
except Exception:
|
| 32 |
+
rec = {}
|
| 33 |
+
try:
|
| 34 |
+
score = float(Path("/logs/verifier/reward.txt").read_text().strip())
|
| 35 |
+
except Exception:
|
| 36 |
+
score = 0.0
|
| 37 |
+
|
| 38 |
+
total = int(rec.get("cells_total", 0))
|
| 39 |
+
invalid = int(rec.get("cells_invalid", total))
|
| 40 |
+
reasons = rec.get("invalid_reasons", {}) or {}
|
| 41 |
+
note = rec.get("note", "") or ""
|
| 42 |
+
|
| 43 |
+
print("evaluation cells: %d" % total)
|
| 44 |
+
print("cells scored: %d" % (total - invalid))
|
| 45 |
+
print("cells scored as zero: %d" % invalid)
|
| 46 |
+
if reasons:
|
| 47 |
+
print("zeroed because: " + ", ".join(f"{k}={v}" for k, v in sorted(reasons.items())))
|
| 48 |
+
if note:
|
| 49 |
+
print("note: %s" % note)
|
| 50 |
+
print("score: %.6f" % score)
|
| 51 |
+
PY
|
| 52 |
+
|
| 53 |
+
exit 0
|
tasks/budgeted-imputation-mcar50/tests/requirements-verifier.txt
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
pytest==8.3.5
|
| 2 |
+
pytest-json-ctrf==0.3.5
|
tasks/budgeted-imputation-mcar50/tests/requirements.txt
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
numpy==2.5.2
|
| 2 |
+
scipy==1.18.0
|
| 3 |
+
scikit-learn==1.9.0
|
| 4 |
+
joblib==1.5.3
|
| 5 |
+
threadpoolctl==3.6.0
|
tasks/budgeted-imputation-mcar50/tests/test.sh
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
set -u
|
| 3 |
+
|
| 4 |
+
PY=/usr/local/bin/python3
|
| 5 |
+
|
| 6 |
+
mkdir -p /logs/verifier
|
| 7 |
+
chown root:root /logs/verifier 2>/dev/null || true
|
| 8 |
+
chmod 755 /logs/verifier 2>/dev/null || true
|
| 9 |
+
rm -f /logs/verifier/reward.txt /logs/verifier/ctrf.json /logs/verifier/metric.json
|
| 10 |
+
|
| 11 |
+
trap 'if [ ! -s /logs/verifier/reward.txt ]; then echo 0 > /logs/verifier/reward.txt; fi' EXIT
|
| 12 |
+
|
| 13 |
+
chmod -R go-rwx /tests
|
| 14 |
+
|
| 15 |
+
export GRADE_SPLIT=final
|
| 16 |
+
export OMP_NUM_THREADS=1
|
| 17 |
+
export MKL_NUM_THREADS=1
|
| 18 |
+
export OPENBLAS_NUM_THREADS=1
|
| 19 |
+
|
| 20 |
+
cd /tests
|
| 21 |
+
"$PY" -m pytest --ctrf /logs/verifier/ctrf.json /tests/test_state.py -rA
|
| 22 |
+
"$PY" /tests/compute_reward.py
|
| 23 |
+
|
| 24 |
+
exit 0
|
tasks/budgeted-imputation-mcar50/tests/test_state.py
ADDED
|
@@ -0,0 +1,381 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
import os
|
| 5 |
+
import pwd
|
| 6 |
+
import shutil
|
| 7 |
+
import signal
|
| 8 |
+
import subprocess
|
| 9 |
+
import sys
|
| 10 |
+
import time
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
|
| 13 |
+
import numpy as np
|
| 14 |
+
import pytest
|
| 15 |
+
|
| 16 |
+
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
| 17 |
+
|
| 18 |
+
import grader_core as gc
|
| 19 |
+
|
| 20 |
+
PY = "/usr/local/bin/python3"
|
| 21 |
+
AGENT_UID = 1001
|
| 22 |
+
try:
|
| 23 |
+
AGENT_GID = pwd.getpwuid(AGENT_UID).pw_gid
|
| 24 |
+
except KeyError:
|
| 25 |
+
AGENT_GID = 1001
|
| 26 |
+
GRADE_ROOT = Path("/opt/grade")
|
| 27 |
+
METRIC_PATH = Path("/logs/verifier/metric.json")
|
| 28 |
+
|
| 29 |
+
CELL_BUDGET_SEC = gc.CELL_BUDGET_SEC
|
| 30 |
+
|
| 31 |
+
SCRUB_DIRS = ("/tmp", "/var/tmp", "/dev/shm", "/home/agent")
|
| 32 |
+
|
| 33 |
+
CHILD_ENV = {
|
| 34 |
+
"PATH": "/usr/local/bin:/usr/bin:/bin",
|
| 35 |
+
"LC_ALL": "C",
|
| 36 |
+
"PYTHONHASHSEED": "0",
|
| 37 |
+
"PYTHONSAFEPATH": "1",
|
| 38 |
+
"PYTHONDONTWRITEBYTECODE": "1",
|
| 39 |
+
"OMP_NUM_THREADS": "1",
|
| 40 |
+
"OPENBLAS_NUM_THREADS": "1",
|
| 41 |
+
"MKL_NUM_THREADS": "1",
|
| 42 |
+
"NUMEXPR_NUM_THREADS": "1",
|
| 43 |
+
"VECLIB_MAXIMUM_THREADS": "1",
|
| 44 |
+
}
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def _tool(name: str, fallback: str) -> str:
|
| 50 |
+
return shutil.which(name) or fallback
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
RUNUSER = _tool("runuser", "/usr/sbin/runuser")
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def _chown_tree(path: Path, uid: int, gid: int) -> None:
|
| 57 |
+
os.chown(path, uid, gid)
|
| 58 |
+
for dirpath, dirnames, filenames in os.walk(path):
|
| 59 |
+
dirnames.sort()
|
| 60 |
+
for name in sorted(dirnames + filenames):
|
| 61 |
+
os.chown(os.path.join(dirpath, name), uid, gid)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def _drop_privilege_works() -> bool:
|
| 65 |
+
"""Probe the privilege-drop mechanism before grading anything.
|
| 66 |
+
|
| 67 |
+
The agent cannot reach or influence this probe; its result is recorded in
|
| 68 |
+
metric.json so an infra failure is distinguishable from a bad submission.
|
| 69 |
+
"""
|
| 70 |
+
if os.geteuid() != 0:
|
| 71 |
+
return False
|
| 72 |
+
try:
|
| 73 |
+
probe = subprocess.run(
|
| 74 |
+
[RUNUSER, "-u", "agent", "--", PY, "-c", "import os;print(os.getuid())"],
|
| 75 |
+
capture_output=True,
|
| 76 |
+
text=True,
|
| 77 |
+
timeout=120,
|
| 78 |
+
env=dict(CHILD_ENV),
|
| 79 |
+
start_new_session=True,
|
| 80 |
+
)
|
| 81 |
+
except Exception:
|
| 82 |
+
return False
|
| 83 |
+
return probe.returncode == 0 and probe.stdout.strip() == str(AGENT_UID)
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def _launch(argv, cwd, env, budget, log_dir: Path, drop_privilege: bool):
|
| 87 |
+
"""Run argv in a session of its own; SIGKILL the whole group at `budget` seconds.
|
| 88 |
+
|
| 89 |
+
start_new_session=True is setsid(2): the child leads a new session and process group,
|
| 90 |
+
so os.killpg reaches anything it forked. Output goes to files rather than pipes so
|
| 91 |
+
that a grandchild holding a pipe open cannot make the grader itself hang.
|
| 92 |
+
|
| 93 |
+
`drop_privilege` uses Popen's own setuid/setgid, which is the fallback when runuser is
|
| 94 |
+
unusable. Candidate code is never executed as root on any path.
|
| 95 |
+
"""
|
| 96 |
+
out_path = log_dir / "stdout.txt"
|
| 97 |
+
err_path = log_dir / "stderr.txt"
|
| 98 |
+
extra = {"user": AGENT_UID, "group": AGENT_GID} if drop_privilege else {}
|
| 99 |
+
started = time.monotonic()
|
| 100 |
+
with open(out_path, "w") as out_fh, open(err_path, "w") as err_fh:
|
| 101 |
+
proc = subprocess.Popen(
|
| 102 |
+
argv,
|
| 103 |
+
cwd=str(cwd),
|
| 104 |
+
env=env,
|
| 105 |
+
stdout=out_fh,
|
| 106 |
+
stderr=err_fh,
|
| 107 |
+
start_new_session=True,
|
| 108 |
+
**extra,
|
| 109 |
+
)
|
| 110 |
+
try:
|
| 111 |
+
proc.wait(timeout=budget)
|
| 112 |
+
timed_out = False
|
| 113 |
+
except subprocess.TimeoutExpired:
|
| 114 |
+
timed_out = True
|
| 115 |
+
try:
|
| 116 |
+
os.killpg(os.getpgid(proc.pid), signal.SIGKILL)
|
| 117 |
+
except Exception:
|
| 118 |
+
proc.kill()
|
| 119 |
+
try:
|
| 120 |
+
proc.wait(timeout=60)
|
| 121 |
+
except subprocess.TimeoutExpired:
|
| 122 |
+
pass
|
| 123 |
+
elapsed = time.monotonic() - started
|
| 124 |
+
try:
|
| 125 |
+
os.killpg(os.getpgid(proc.pid), signal.SIGKILL)
|
| 126 |
+
except Exception:
|
| 127 |
+
pass
|
| 128 |
+
try:
|
| 129 |
+
stderr_tail = err_path.read_text(errors="replace")[-800:]
|
| 130 |
+
except Exception:
|
| 131 |
+
stderr_tail = ""
|
| 132 |
+
return {
|
| 133 |
+
"returncode": proc.returncode,
|
| 134 |
+
"stderr": stderr_tail,
|
| 135 |
+
"timed_out": timed_out,
|
| 136 |
+
"elapsed": elapsed,
|
| 137 |
+
}
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def _stage_deliverable() -> dict:
|
| 141 |
+
"""Copy /app/output into a root-owned tree, pruning symlinks at every depth."""
|
| 142 |
+
staged = GRADE_ROOT / "deliverable"
|
| 143 |
+
if staged.exists():
|
| 144 |
+
shutil.rmtree(staged)
|
| 145 |
+
staged.mkdir(parents=True)
|
| 146 |
+
|
| 147 |
+
info = {"present": False, "entry_bytes": 0, "files": 0, "pruned_symlinks": 0}
|
| 148 |
+
src = gc.DELIVERABLE_DIR
|
| 149 |
+
if not src.is_dir():
|
| 150 |
+
return info
|
| 151 |
+
|
| 152 |
+
files, links = gc.deliverable_files(src)
|
| 153 |
+
info["pruned_symlinks"] = len(links)
|
| 154 |
+
entry_src = str(src / gc.ENTRY_POINT.name)
|
| 155 |
+
files.sort(key=lambda p: (p != entry_src, p))
|
| 156 |
+
if len(files) > gc.MAX_DELIVERABLE_FILES:
|
| 157 |
+
files = files[: gc.MAX_DELIVERABLE_FILES]
|
| 158 |
+
|
| 159 |
+
total = 0
|
| 160 |
+
for full in files:
|
| 161 |
+
rel = os.path.relpath(full, src)
|
| 162 |
+
size = os.path.getsize(full)
|
| 163 |
+
if total + size > gc.MAX_DELIVERABLE_BYTES:
|
| 164 |
+
break
|
| 165 |
+
dest = staged / rel
|
| 166 |
+
dest.parent.mkdir(parents=True, exist_ok=True)
|
| 167 |
+
shutil.copyfile(full, dest, follow_symlinks=False)
|
| 168 |
+
os.chmod(dest, 0o644)
|
| 169 |
+
total += size
|
| 170 |
+
info["files"] += 1
|
| 171 |
+
|
| 172 |
+
entry = staged / gc.ENTRY_POINT.name
|
| 173 |
+
if entry.is_file():
|
| 174 |
+
info["entry_bytes"] = entry.stat().st_size
|
| 175 |
+
info["present"] = info["entry_bytes"] > 0
|
| 176 |
+
_chown_tree(staged, 0, 0)
|
| 177 |
+
os.chmod(staged, 0o755)
|
| 178 |
+
return info
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
def _snapshot_writable() -> dict:
|
| 182 |
+
"""Record what is in the shared writable directories before any candidate runs."""
|
| 183 |
+
seen = {}
|
| 184 |
+
for d in SCRUB_DIRS:
|
| 185 |
+
try:
|
| 186 |
+
seen[d] = set(sorted(os.listdir(d)))
|
| 187 |
+
except OSError:
|
| 188 |
+
seen[d] = set()
|
| 189 |
+
return seen
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def _scrub_writable(seen: dict) -> None:
|
| 193 |
+
"""Remove everything a cell left behind in the shared writable directories."""
|
| 194 |
+
for d, before in seen.items():
|
| 195 |
+
try:
|
| 196 |
+
entries = sorted(os.listdir(d))
|
| 197 |
+
except OSError:
|
| 198 |
+
continue
|
| 199 |
+
for name in entries:
|
| 200 |
+
if name in before:
|
| 201 |
+
continue
|
| 202 |
+
full = os.path.join(d, name)
|
| 203 |
+
try:
|
| 204 |
+
if os.path.islink(full) or os.path.isfile(full):
|
| 205 |
+
os.unlink(full)
|
| 206 |
+
else:
|
| 207 |
+
shutil.rmtree(full, ignore_errors=True)
|
| 208 |
+
except OSError:
|
| 209 |
+
pass
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
def _prepare_runner() -> Path:
|
| 213 |
+
runner_dir = GRADE_ROOT / "runner"
|
| 214 |
+
runner_dir.mkdir(parents=True, exist_ok=True)
|
| 215 |
+
dest = runner_dir / "cellrunner.py"
|
| 216 |
+
shutil.copyfile("/tests/cellrunner.py", dest)
|
| 217 |
+
os.chmod(runner_dir, 0o755)
|
| 218 |
+
os.chmod(dest, 0o644)
|
| 219 |
+
return dest
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
def _run_cell(runner: Path, staged: Path, index: int, X_train, X_eval, seed):
|
| 223 |
+
cell_dir = GRADE_ROOT / "cells" / f"c{index:03d}"
|
| 224 |
+
if cell_dir.exists():
|
| 225 |
+
shutil.rmtree(cell_dir)
|
| 226 |
+
work = cell_dir / "work"
|
| 227 |
+
work.mkdir(parents=True)
|
| 228 |
+
os.chmod(cell_dir, 0o755)
|
| 229 |
+
|
| 230 |
+
in_path = cell_dir / "in.npz"
|
| 231 |
+
np.savez(in_path, X_train=X_train, X_eval=X_eval, seed=np.array([seed], dtype=np.int64))
|
| 232 |
+
os.chmod(in_path, 0o644)
|
| 233 |
+
|
| 234 |
+
out_path = work / "out.npy"
|
| 235 |
+
os.chown(work, AGENT_UID, AGENT_GID)
|
| 236 |
+
os.chmod(work, 0o700)
|
| 237 |
+
|
| 238 |
+
env = dict(CHILD_ENV)
|
| 239 |
+
env["TMPDIR"] = str(work)
|
| 240 |
+
env["HOME"] = str(work)
|
| 241 |
+
call = [PY, str(runner), str(in_path), str(out_path), str(staged)]
|
| 242 |
+
argv = [RUNUSER, "-u", "agent", "--"] + call if RUNUSER_OK else call
|
| 243 |
+
|
| 244 |
+
res = _launch(argv, work, env, CELL_BUDGET_SEC, cell_dir, drop_privilege=not RUNUSER_OK)
|
| 245 |
+
|
| 246 |
+
returned = None
|
| 247 |
+
if not res["timed_out"] and res["returncode"] == 0 and out_path.is_file():
|
| 248 |
+
try:
|
| 249 |
+
returned = np.load(out_path, allow_pickle=False)
|
| 250 |
+
except Exception:
|
| 251 |
+
returned = None
|
| 252 |
+
shutil.rmtree(cell_dir, ignore_errors=True)
|
| 253 |
+
return returned, res
|
| 254 |
+
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
RUNUSER_OK = False
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
def _grade() -> dict:
|
| 262 |
+
global RUNUSER_OK
|
| 263 |
+
half = os.environ.get("GRADE_SPLIT", "final")
|
| 264 |
+
record = {
|
| 265 |
+
"half": half,
|
| 266 |
+
"cell_budget_sec": CELL_BUDGET_SEC,
|
| 267 |
+
"privilege_drop": "unknown",
|
| 268 |
+
"cells_total": 0,
|
| 269 |
+
"cells_valid": 0,
|
| 270 |
+
"cells_invalid": 0,
|
| 271 |
+
"invalid_reasons": {},
|
| 272 |
+
"metric": 0.0,
|
| 273 |
+
"reward": 0.0,
|
| 274 |
+
"valid": False,
|
| 275 |
+
"note": "",
|
| 276 |
+
}
|
| 277 |
+
|
| 278 |
+
GRADE_ROOT.mkdir(parents=True, exist_ok=True)
|
| 279 |
+
os.chmod(GRADE_ROOT, 0o755)
|
| 280 |
+
|
| 281 |
+
RUNUSER_OK = _drop_privilege_works()
|
| 282 |
+
record["privilege_drop"] = "runuser:agent" if RUNUSER_OK else "popen-setuid:agent"
|
| 283 |
+
|
| 284 |
+
staged_info = _stage_deliverable()
|
| 285 |
+
record["deliverable"] = staged_info
|
| 286 |
+
|
| 287 |
+
cells = list(gc.iter_cells(half))
|
| 288 |
+
record["cells_total"] = len(cells)
|
| 289 |
+
|
| 290 |
+
if not staged_info["present"]:
|
| 291 |
+
record["note"] = "missing_or_empty_entry_point"
|
| 292 |
+
record["cells_invalid"] = len(cells)
|
| 293 |
+
record["invalid_reasons"] = {"missing_entry_point": len(cells)}
|
| 294 |
+
return record
|
| 295 |
+
|
| 296 |
+
runner = _prepare_runner()
|
| 297 |
+
staged = GRADE_ROOT / "deliverable"
|
| 298 |
+
|
| 299 |
+
writable_before = _snapshot_writable()
|
| 300 |
+
scores, reasons, elapsed, per_cell = [], {}, [], {}
|
| 301 |
+
for index, (key, X, seed, n_train, n_eval) in enumerate(cells):
|
| 302 |
+
X_train, X_eval, X_eval_true, mask_eval = gc.cellspec.build_cell(X, seed, n_train, n_eval)
|
| 303 |
+
returned, res = _run_cell(runner, staged, index, X_train, X_eval, seed)
|
| 304 |
+
_scrub_writable(writable_before)
|
| 305 |
+
elapsed.append(round(res["elapsed"], 3))
|
| 306 |
+
|
| 307 |
+
if res["timed_out"]:
|
| 308 |
+
score, reason = None, "timeout"
|
| 309 |
+
elif res["returncode"] != 0:
|
| 310 |
+
score, reason = None, "nonzero_exit"
|
| 311 |
+
elif returned is None:
|
| 312 |
+
score, reason = None, "no_or_unreadable_output"
|
| 313 |
+
else:
|
| 314 |
+
score, reason = gc.score_submission(returned, X_eval_true, mask_eval)
|
| 315 |
+
|
| 316 |
+
scores.append(score)
|
| 317 |
+
per_cell[key] = None if score is None else round(float(score), 6)
|
| 318 |
+
if score is None:
|
| 319 |
+
reasons[reason] = reasons.get(reason, 0) + 1
|
| 320 |
+
del X_train, X_eval, X_eval_true, mask_eval, returned
|
| 321 |
+
|
| 322 |
+
record["cells_valid"] = sum(1 for s in scores if s is not None)
|
| 323 |
+
record["cells_invalid"] = sum(1 for s in scores if s is None)
|
| 324 |
+
record["invalid_reasons"] = reasons
|
| 325 |
+
record["metric"] = gc.aggregate(scores)
|
| 326 |
+
record["reward"] = gc.graded_reward(record["metric"])
|
| 327 |
+
record["valid"] = record["cells_valid"] > 0
|
| 328 |
+
record["cell_elapsed_sec"] = elapsed
|
| 329 |
+
record["cell_scores"] = per_cell
|
| 330 |
+
if not record["valid"]:
|
| 331 |
+
record["reward"] = 0.0
|
| 332 |
+
return record
|
| 333 |
+
|
| 334 |
+
|
| 335 |
+
def _write(record: dict) -> None:
|
| 336 |
+
METRIC_PATH.parent.mkdir(parents=True, exist_ok=True)
|
| 337 |
+
with open(METRIC_PATH, "w") as fh:
|
| 338 |
+
json.dump(record, fh, indent=2, sort_keys=True)
|
| 339 |
+
fh.write("\n")
|
| 340 |
+
|
| 341 |
+
|
| 342 |
+
@pytest.fixture(scope="module")
|
| 343 |
+
def result():
|
| 344 |
+
try:
|
| 345 |
+
record = _grade()
|
| 346 |
+
except Exception as exc:
|
| 347 |
+
record = {"valid": False, "reward": 0.0, "metric": 0.0, "note": f"grader_error: {exc!r}"}
|
| 348 |
+
_write(record)
|
| 349 |
+
raise
|
| 350 |
+
_write(record)
|
| 351 |
+
return record
|
| 352 |
+
|
| 353 |
+
|
| 354 |
+
def test_deliverable_present(result):
|
| 355 |
+
"""The submitted entry point exists at the declared path and is non-empty."""
|
| 356 |
+
assert result["deliverable"]["present"], (
|
| 357 |
+
f"no usable {gc.ENTRY_POINT}: {result.get('note')}"
|
| 358 |
+
)
|
| 359 |
+
|
| 360 |
+
|
| 361 |
+
def test_no_symlinks_submitted(result):
|
| 362 |
+
"""Symbolic links under the deliverable directory are pruned, never followed."""
|
| 363 |
+
assert result["deliverable"]["pruned_symlinks"] == 0, (
|
| 364 |
+
"symbolic links under /app/output were skipped; they are not copied to the verifier"
|
| 365 |
+
)
|
| 366 |
+
|
| 367 |
+
|
| 368 |
+
def test_every_cell_ran(result):
|
| 369 |
+
"""Every graded cell returned a finite, correctly shaped array inside its budget."""
|
| 370 |
+
assert result["cells_total"] > 0
|
| 371 |
+
assert result["cells_invalid"] == 0, (
|
| 372 |
+
f"{result['cells_invalid']}/{result['cells_total']} cells scored 0: "
|
| 373 |
+
f"{result['invalid_reasons']}"
|
| 374 |
+
)
|
| 375 |
+
|
| 376 |
+
|
| 377 |
+
def test_metric_recorded(result):
|
| 378 |
+
"""The panel metric and the mapped reward were computed and recorded."""
|
| 379 |
+
assert METRIC_PATH.is_file()
|
| 380 |
+
assert np.isfinite(result["metric"])
|
| 381 |
+
assert 0.0 <= result["reward"] <= 1.0
|
tasks/carps-star-discrepancy-subset-select/environment/app/data/examples/manifest.json
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"instances": [
|
| 3 |
+
{
|
| 4 |
+
"id": "cloud_00",
|
| 5 |
+
"file": "cloud_00.npy",
|
| 6 |
+
"n": 2436,
|
| 7 |
+
"k": 30
|
| 8 |
+
},
|
| 9 |
+
{
|
| 10 |
+
"id": "cloud_01",
|
| 11 |
+
"file": "cloud_01.npy",
|
| 12 |
+
"n": 3217,
|
| 13 |
+
"k": 65
|
| 14 |
+
},
|
| 15 |
+
{
|
| 16 |
+
"id": "cloud_02",
|
| 17 |
+
"file": "cloud_02.npy",
|
| 18 |
+
"n": 1149,
|
| 19 |
+
"k": 30
|
| 20 |
+
},
|
| 21 |
+
{
|
| 22 |
+
"id": "cloud_03",
|
| 23 |
+
"file": "cloud_03.npy",
|
| 24 |
+
"n": 1374,
|
| 25 |
+
"k": 30
|
| 26 |
+
},
|
| 27 |
+
{
|
| 28 |
+
"id": "cloud_04",
|
| 29 |
+
"file": "cloud_04.npy",
|
| 30 |
+
"n": 3621,
|
| 31 |
+
"k": 50
|
| 32 |
+
},
|
| 33 |
+
{
|
| 34 |
+
"id": "cloud_05",
|
| 35 |
+
"file": "cloud_05.npy",
|
| 36 |
+
"n": 872,
|
| 37 |
+
"k": 65
|
| 38 |
+
},
|
| 39 |
+
{
|
| 40 |
+
"id": "cloud_06",
|
| 41 |
+
"file": "cloud_06.npy",
|
| 42 |
+
"n": 2457,
|
| 43 |
+
"k": 50
|
| 44 |
+
},
|
| 45 |
+
{
|
| 46 |
+
"id": "cloud_07",
|
| 47 |
+
"file": "cloud_07.npy",
|
| 48 |
+
"n": 2990,
|
| 49 |
+
"k": 65
|
| 50 |
+
}
|
| 51 |
+
],
|
| 52 |
+
"dim": 3,
|
| 53 |
+
"note": "Example clouds. The graded panel is drawn the same way."
|
| 54 |
+
}
|
tasks/carps-star-discrepancy-subset-select/environment/requirements.txt
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
numpy==2.5.2
|
| 2 |
+
scipy==1.18.0
|
tasks/carps-star-discrepancy-subset-select/hints/hint.md
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
Build an exact evaluator on the grid of the points' own coordinates, then initialise from a cheap closed-form L2 descent - recomputing only the swapped point's kernel column - and refine against the current critical boxes. Spend the budget on many restarts with a patience rule rather than one deep search; weighted variants of the L2 objective give complementary basins. Decide deliberately how to treat points on a boundary coordinate: blanket filtering them looks safe and hurts on skewed clouds.
|
tasks/carps-star-discrepancy-subset-select/tests/Dockerfile
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM --platform=linux/amd64 public.ecr.aws/docker/library/python:3.13-slim-bookworm@sha256:01f42367a0a94ad4bc17111776fd66e3500c1d87c15bbd6055b7371d39c124fb
|
| 2 |
+
|
| 3 |
+
ENTRYPOINT []
|
| 4 |
+
ENV PYTHONPATH=
|
| 5 |
+
ENV PYTHONSAFEPATH=1
|
| 6 |
+
ENV DEBIAN_FRONTEND=noninteractive \
|
| 7 |
+
PYTHONHASHSEED=0 \
|
| 8 |
+
PIP_NO_CACHE_DIR=1 \
|
| 9 |
+
PIP_DISABLE_PIP_VERSION_CHECK=1 \
|
| 10 |
+
OMP_NUM_THREADS=1 \
|
| 11 |
+
MKL_NUM_THREADS=1 \
|
| 12 |
+
OPENBLAS_NUM_THREADS=1
|
| 13 |
+
|
| 14 |
+
RUN useradd --create-home --uid 1001 agent
|
| 15 |
+
|
| 16 |
+
COPY ./requirements.txt /tmp/requirements.txt
|
| 17 |
+
COPY ./requirements-verifier.txt /tmp/requirements-verifier.txt
|
| 18 |
+
RUN /usr/local/bin/python3 -m pip install --no-cache-dir \
|
| 19 |
+
-r /tmp/requirements.txt -r /tmp/requirements-verifier.txt \
|
| 20 |
+
&& rm /tmp/requirements.txt /tmp/requirements-verifier.txt
|
| 21 |
+
|
| 22 |
+
RUN mkdir -p /app/output /logs/verifier
|
| 23 |
+
|
| 24 |
+
COPY . /tests
|
| 25 |
+
|
| 26 |
+
RUN chown -R root:root /tests \
|
| 27 |
+
&& chmod 700 /tests \
|
| 28 |
+
&& chmod 700 /tests/hidden_data /tests/hidden_data/intermediate /tests/hidden_data/final \
|
| 29 |
+
&& chmod +x /tests/test.sh /tests/intermediate.sh \
|
| 30 |
+
&& mkdir -p /opt/verifier /opt/candidate \
|
| 31 |
+
&& cp /tests/runner.py /opt/verifier/runner.py \
|
| 32 |
+
&& chown root:root /opt/verifier /opt/verifier/runner.py \
|
| 33 |
+
&& chmod 755 /opt/verifier \
|
| 34 |
+
&& chmod 644 /opt/verifier/runner.py \
|
| 35 |
+
&& find /tests /opt/verifier -exec touch -d @1700000000 {} +
|
| 36 |
+
|
| 37 |
+
WORKDIR /tests
|
| 38 |
+
|
| 39 |
+
ENV HF_HUB_OFFLINE=1
|
| 40 |
+
ENV TRANSFORMERS_OFFLINE=1
|
tasks/carps-star-discrepancy-subset-select/tests/compute_reward.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import math
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
|
| 5 |
+
REWARD_PATH = Path("/logs/verifier/reward.txt")
|
| 6 |
+
|
| 7 |
+
try:
|
| 8 |
+
REWARD_PATH.parent.mkdir(parents=True, exist_ok=True)
|
| 9 |
+
value = float(json.loads(Path("/logs/verifier/metric.json").read_text())["reward"])
|
| 10 |
+
if not math.isfinite(value):
|
| 11 |
+
raise ValueError("non-finite reward")
|
| 12 |
+
reward = f"{min(1.0, max(0.0, value)):.12g}"
|
| 13 |
+
REWARD_PATH.write_text(reward + "\n")
|
| 14 |
+
print(f"reward={reward}")
|
| 15 |
+
except Exception as exc:
|
| 16 |
+
REWARD_PATH.write_text("0\n")
|
| 17 |
+
print(f"reward=0 (fallback: {exc})")
|
tasks/carps-star-discrepancy-subset-select/tests/grader_core.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
|
| 3 |
+
DIM = 3
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def star_discrepancy_3d(pts: np.ndarray) -> float:
|
| 7 |
+
"""Exact L_inf star discrepancy of a point set in [0,1]^3."""
|
| 8 |
+
pts = np.ascontiguousarray(np.asarray(pts, dtype=np.float64))
|
| 9 |
+
if pts.ndim != 2 or pts.shape[1] != DIM or pts.shape[0] == 0:
|
| 10 |
+
raise ValueError("expected a non-empty (k, 3) array")
|
| 11 |
+
if not np.isfinite(pts).all() or pts.min() < 0.0 or pts.max() > 1.0:
|
| 12 |
+
raise ValueError("points must lie in [0,1]^3")
|
| 13 |
+
k = pts.shape[0]
|
| 14 |
+
|
| 15 |
+
grids, idx = [], []
|
| 16 |
+
for d in range(DIM):
|
| 17 |
+
g = np.unique(np.concatenate([pts[:, d], np.array([1.0])]))
|
| 18 |
+
grids.append(g)
|
| 19 |
+
idx.append(np.searchsorted(g, pts[:, d]))
|
| 20 |
+
|
| 21 |
+
shape = tuple(len(g) for g in grids)
|
| 22 |
+
hist = np.zeros(shape, dtype=np.int64)
|
| 23 |
+
np.add.at(hist, (idx[0], idx[1], idx[2]), 1)
|
| 24 |
+
closed = hist.cumsum(0).cumsum(1).cumsum(2)
|
| 25 |
+
op = np.zeros(shape, dtype=np.int64)
|
| 26 |
+
op[1:, 1:, 1:] = closed[:-1, :-1, :-1]
|
| 27 |
+
|
| 28 |
+
vol = grids[0][:, None, None] * grids[1][None, :, None] * grids[2][None, None, :]
|
| 29 |
+
over = closed / k - vol
|
| 30 |
+
under = vol - op / k
|
| 31 |
+
return float(max(over.max(), under.max()))
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def baseline_indices(seed: int, n: int, k: int) -> np.ndarray:
|
| 35 |
+
"""The trivial baseline: a uniformly random k-subset, ignoring the coordinates."""
|
| 36 |
+
return np.random.default_rng(int(seed)).choice(int(n), int(k), replace=False)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def validate_indices(raw, n: int, k: int) -> np.ndarray:
|
| 40 |
+
"""Turn an untrusted decoded JSON value into k distinct indices, or raise.
|
| 41 |
+
|
| 42 |
+
Accepts a flat sequence of k integral values (ints, or floats that are exactly
|
| 43 |
+
integral). Anything else - wrong length, duplicates, out-of-range, non-integral,
|
| 44 |
+
booleans, nested structures - is rejected.
|
| 45 |
+
"""
|
| 46 |
+
if not isinstance(raw, list):
|
| 47 |
+
raise ValueError(f"result is {type(raw).__name__}, expected a sequence")
|
| 48 |
+
if len(raw) != k:
|
| 49 |
+
raise ValueError(f"returned {len(raw)} indices, expected exactly {k}")
|
| 50 |
+
out = np.empty(k, dtype=np.int64)
|
| 51 |
+
for i, v in enumerate(raw):
|
| 52 |
+
if isinstance(v, bool) or not isinstance(v, (int, float)):
|
| 53 |
+
raise ValueError(f"index {i} is {type(v).__name__}, expected an integer")
|
| 54 |
+
if isinstance(v, float):
|
| 55 |
+
if not np.isfinite(v) or float(v) != int(v):
|
| 56 |
+
raise ValueError(f"index {i} = {v!r} is not integral")
|
| 57 |
+
v = int(v)
|
| 58 |
+
if v < 0 or v >= n:
|
| 59 |
+
raise ValueError(f"index {i} = {v} is outside [0, {n})")
|
| 60 |
+
out[i] = v
|
| 61 |
+
if len(np.unique(out)) != k:
|
| 62 |
+
raise ValueError("returned indices are not distinct")
|
| 63 |
+
return out
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def graded_reward(metric: float, m0: float) -> float:
|
| 67 |
+
"""single_anchor_ratio, lower-is-better: rho = m0 / m, V = max(0, 1 - 1/rho).
|
| 68 |
+
|
| 69 |
+
m0 is the panel mean of the trivial random-subset baseline, recomputed from the
|
| 70 |
+
sealed instances at grade time. A submission at or worse than the baseline scores
|
| 71 |
+
exactly 0; there is no cutoff above it. Neither anchor nor this arithmetic appears
|
| 72 |
+
in instruction.md.
|
| 73 |
+
"""
|
| 74 |
+
if not np.isfinite(metric) or not np.isfinite(m0) or m0 <= 0.0 or metric <= 0.0:
|
| 75 |
+
return 0.0
|
| 76 |
+
value = 1.0 - (float(metric) / float(m0))
|
| 77 |
+
return float(value) if value > 1e-9 else 0.0
|
tasks/carps-star-discrepancy-subset-select/tests/hidden_data/final/manifest.json
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"instances": [
|
| 3 |
+
{
|
| 4 |
+
"iid": "s1000100",
|
| 5 |
+
"file": "cloud_00.npy",
|
| 6 |
+
"n": 1725,
|
| 7 |
+
"k": 50,
|
| 8 |
+
"baseline_seed": 1000100
|
| 9 |
+
},
|
| 10 |
+
{
|
| 11 |
+
"iid": "s1000101",
|
| 12 |
+
"file": "cloud_01.npy",
|
| 13 |
+
"n": 1199,
|
| 14 |
+
"k": 50,
|
| 15 |
+
"baseline_seed": 1000101
|
| 16 |
+
},
|
| 17 |
+
{
|
| 18 |
+
"iid": "s1000102",
|
| 19 |
+
"file": "cloud_02.npy",
|
| 20 |
+
"n": 1153,
|
| 21 |
+
"k": 50,
|
| 22 |
+
"baseline_seed": 1000102
|
| 23 |
+
},
|
| 24 |
+
{
|
| 25 |
+
"iid": "s1000103",
|
| 26 |
+
"file": "cloud_03.npy",
|
| 27 |
+
"n": 3874,
|
| 28 |
+
"k": 50,
|
| 29 |
+
"baseline_seed": 1000103
|
| 30 |
+
},
|
| 31 |
+
{
|
| 32 |
+
"iid": "s1000104",
|
| 33 |
+
"file": "cloud_04.npy",
|
| 34 |
+
"n": 3979,
|
| 35 |
+
"k": 50,
|
| 36 |
+
"baseline_seed": 1000104
|
| 37 |
+
},
|
| 38 |
+
{
|
| 39 |
+
"iid": "s1000105",
|
| 40 |
+
"file": "cloud_05.npy",
|
| 41 |
+
"n": 2770,
|
| 42 |
+
"k": 30,
|
| 43 |
+
"baseline_seed": 1000105
|
| 44 |
+
},
|
| 45 |
+
{
|
| 46 |
+
"iid": "s1000106",
|
| 47 |
+
"file": "cloud_06.npy",
|
| 48 |
+
"n": 2995,
|
| 49 |
+
"k": 30,
|
| 50 |
+
"baseline_seed": 1000106
|
| 51 |
+
},
|
| 52 |
+
{
|
| 53 |
+
"iid": "s1000107",
|
| 54 |
+
"file": "cloud_07.npy",
|
| 55 |
+
"n": 2243,
|
| 56 |
+
"k": 50,
|
| 57 |
+
"baseline_seed": 1000107
|
| 58 |
+
},
|
| 59 |
+
{
|
| 60 |
+
"iid": "s1000108",
|
| 61 |
+
"file": "cloud_08.npy",
|
| 62 |
+
"n": 1266,
|
| 63 |
+
"k": 65,
|
| 64 |
+
"baseline_seed": 1000108
|
| 65 |
+
},
|
| 66 |
+
{
|
| 67 |
+
"iid": "s1000109",
|
| 68 |
+
"file": "cloud_09.npy",
|
| 69 |
+
"n": 2751,
|
| 70 |
+
"k": 50,
|
| 71 |
+
"baseline_seed": 1000109
|
| 72 |
+
},
|
| 73 |
+
{
|
| 74 |
+
"iid": "s1000110",
|
| 75 |
+
"file": "cloud_10.npy",
|
| 76 |
+
"n": 3006,
|
| 77 |
+
"k": 30,
|
| 78 |
+
"baseline_seed": 1000110
|
| 79 |
+
},
|
| 80 |
+
{
|
| 81 |
+
"iid": "s1000111",
|
| 82 |
+
"file": "cloud_11.npy",
|
| 83 |
+
"n": 2799,
|
| 84 |
+
"k": 50,
|
| 85 |
+
"baseline_seed": 1000111
|
| 86 |
+
},
|
| 87 |
+
{
|
| 88 |
+
"iid": "s1000112",
|
| 89 |
+
"file": "cloud_12.npy",
|
| 90 |
+
"n": 3234,
|
| 91 |
+
"k": 65,
|
| 92 |
+
"baseline_seed": 1000112
|
| 93 |
+
},
|
| 94 |
+
{
|
| 95 |
+
"iid": "s1000113",
|
| 96 |
+
"file": "cloud_13.npy",
|
| 97 |
+
"n": 2242,
|
| 98 |
+
"k": 50,
|
| 99 |
+
"baseline_seed": 1000113
|
| 100 |
+
},
|
| 101 |
+
{
|
| 102 |
+
"iid": "s1000114",
|
| 103 |
+
"file": "cloud_14.npy",
|
| 104 |
+
"n": 2890,
|
| 105 |
+
"k": 65,
|
| 106 |
+
"baseline_seed": 1000114
|
| 107 |
+
}
|
| 108 |
+
]
|
| 109 |
+
}
|
tasks/carps-star-discrepancy-subset-select/tests/hidden_data/intermediate/manifest.json
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"instances": [
|
| 3 |
+
{
|
| 4 |
+
"iid": "s1000000",
|
| 5 |
+
"file": "cloud_00.npy",
|
| 6 |
+
"n": 3213,
|
| 7 |
+
"k": 30,
|
| 8 |
+
"baseline_seed": 1000000
|
| 9 |
+
},
|
| 10 |
+
{
|
| 11 |
+
"iid": "s1000001",
|
| 12 |
+
"file": "cloud_01.npy",
|
| 13 |
+
"n": 3016,
|
| 14 |
+
"k": 65,
|
| 15 |
+
"baseline_seed": 1000001
|
| 16 |
+
},
|
| 17 |
+
{
|
| 18 |
+
"iid": "s1000002",
|
| 19 |
+
"file": "cloud_02.npy",
|
| 20 |
+
"n": 866,
|
| 21 |
+
"k": 65,
|
| 22 |
+
"baseline_seed": 1000002
|
| 23 |
+
},
|
| 24 |
+
{
|
| 25 |
+
"iid": "s1000003",
|
| 26 |
+
"file": "cloud_03.npy",
|
| 27 |
+
"n": 1247,
|
| 28 |
+
"k": 50,
|
| 29 |
+
"baseline_seed": 1000003
|
| 30 |
+
},
|
| 31 |
+
{
|
| 32 |
+
"iid": "s1000004",
|
| 33 |
+
"file": "cloud_04.npy",
|
| 34 |
+
"n": 1100,
|
| 35 |
+
"k": 30,
|
| 36 |
+
"baseline_seed": 1000004
|
| 37 |
+
},
|
| 38 |
+
{
|
| 39 |
+
"iid": "s1000005",
|
| 40 |
+
"file": "cloud_05.npy",
|
| 41 |
+
"n": 2395,
|
| 42 |
+
"k": 50,
|
| 43 |
+
"baseline_seed": 1000005
|
| 44 |
+
},
|
| 45 |
+
{
|
| 46 |
+
"iid": "s1000006",
|
| 47 |
+
"file": "cloud_06.npy",
|
| 48 |
+
"n": 2111,
|
| 49 |
+
"k": 65,
|
| 50 |
+
"baseline_seed": 1000006
|
| 51 |
+
},
|
| 52 |
+
{
|
| 53 |
+
"iid": "s1000007",
|
| 54 |
+
"file": "cloud_07.npy",
|
| 55 |
+
"n": 1220,
|
| 56 |
+
"k": 65,
|
| 57 |
+
"baseline_seed": 1000007
|
| 58 |
+
},
|
| 59 |
+
{
|
| 60 |
+
"iid": "s1000008",
|
| 61 |
+
"file": "cloud_08.npy",
|
| 62 |
+
"n": 1042,
|
| 63 |
+
"k": 65,
|
| 64 |
+
"baseline_seed": 1000008
|
| 65 |
+
},
|
| 66 |
+
{
|
| 67 |
+
"iid": "s1000009",
|
| 68 |
+
"file": "cloud_09.npy",
|
| 69 |
+
"n": 3730,
|
| 70 |
+
"k": 50,
|
| 71 |
+
"baseline_seed": 1000009
|
| 72 |
+
},
|
| 73 |
+
{
|
| 74 |
+
"iid": "s1000010",
|
| 75 |
+
"file": "cloud_10.npy",
|
| 76 |
+
"n": 3310,
|
| 77 |
+
"k": 50,
|
| 78 |
+
"baseline_seed": 1000010
|
| 79 |
+
},
|
| 80 |
+
{
|
| 81 |
+
"iid": "s1000011",
|
| 82 |
+
"file": "cloud_11.npy",
|
| 83 |
+
"n": 3577,
|
| 84 |
+
"k": 50,
|
| 85 |
+
"baseline_seed": 1000011
|
| 86 |
+
},
|
| 87 |
+
{
|
| 88 |
+
"iid": "s1000012",
|
| 89 |
+
"file": "cloud_12.npy",
|
| 90 |
+
"n": 2472,
|
| 91 |
+
"k": 65,
|
| 92 |
+
"baseline_seed": 1000012
|
| 93 |
+
},
|
| 94 |
+
{
|
| 95 |
+
"iid": "s1000013",
|
| 96 |
+
"file": "cloud_13.npy",
|
| 97 |
+
"n": 2098,
|
| 98 |
+
"k": 50,
|
| 99 |
+
"baseline_seed": 1000013
|
| 100 |
+
},
|
| 101 |
+
{
|
| 102 |
+
"iid": "s1000014",
|
| 103 |
+
"file": "cloud_14.npy",
|
| 104 |
+
"n": 3847,
|
| 105 |
+
"k": 65,
|
| 106 |
+
"baseline_seed": 1000014
|
| 107 |
+
}
|
| 108 |
+
]
|
| 109 |
+
}
|
tasks/carps-star-discrepancy-subset-select/tests/intermediate.sh
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
set -u
|
| 3 |
+
|
| 4 |
+
mkdir -p /logs/verifier
|
| 5 |
+
chown root:root /logs/verifier 2>/dev/null || true
|
| 6 |
+
chmod 755 /logs/verifier 2>/dev/null || true
|
| 7 |
+
rm -f /logs/verifier/reward.txt /logs/verifier/ctrf.json /logs/verifier/metric.json
|
| 8 |
+
|
| 9 |
+
trap '[ -s /logs/verifier/reward.txt ] || echo 0 > /logs/verifier/reward.txt' EXIT
|
| 10 |
+
|
| 11 |
+
chmod -R go-rwx /tests
|
| 12 |
+
|
| 13 |
+
cd /tests
|
| 14 |
+
export GRADE_SPLIT=intermediate
|
| 15 |
+
GRADE_VERBOSE=0 \
|
| 16 |
+
/usr/local/bin/python3 -m pytest --ctrf /logs/verifier/ctrf.json /tests/test_state.py -rA
|
| 17 |
+
|
| 18 |
+
/usr/local/bin/python3 /tests/compute_reward.py
|
| 19 |
+
|
| 20 |
+
exit 0
|
tasks/carps-star-discrepancy-subset-select/tests/requirements-verifier.txt
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
pytest==8.3.5
|
| 2 |
+
pytest-json-ctrf==0.3.5
|
tasks/carps-star-discrepancy-subset-select/tests/requirements.txt
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
numpy==2.5.2
|
| 2 |
+
scipy==1.18.0
|
tasks/carps-star-discrepancy-subset-select/tests/runner.py
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import os
|
| 3 |
+
import sys
|
| 4 |
+
import time
|
| 5 |
+
|
| 6 |
+
import numpy as np
|
| 7 |
+
|
| 8 |
+
_dump = json.dump
|
| 9 |
+
_exit = os._exit
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def encode(obj):
|
| 13 |
+
"""Best-effort, lossless-for-integers JSON encoding of an untrusted return value."""
|
| 14 |
+
if obj is None or isinstance(obj, (bool, int, float, str)):
|
| 15 |
+
return obj
|
| 16 |
+
if isinstance(obj, np.integer):
|
| 17 |
+
return int(obj)
|
| 18 |
+
if isinstance(obj, np.floating):
|
| 19 |
+
return float(obj)
|
| 20 |
+
if isinstance(obj, np.ndarray):
|
| 21 |
+
return [encode(x) for x in obj.tolist()]
|
| 22 |
+
if isinstance(obj, (list, tuple, set, frozenset)):
|
| 23 |
+
return [encode(x) for x in obj]
|
| 24 |
+
try:
|
| 25 |
+
return [encode(x) for x in list(obj)]
|
| 26 |
+
except Exception:
|
| 27 |
+
return {"__unencodable__": type(obj).__name__}
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def main() -> None:
|
| 31 |
+
work, candidate = sys.argv[1], sys.argv[2]
|
| 32 |
+
out_path = os.path.join(work, "result.json")
|
| 33 |
+
payload = {"ok": False, "error": "runner did not complete"}
|
| 34 |
+
try:
|
| 35 |
+
with open(os.path.join(work, "args.json"), "r") as fh:
|
| 36 |
+
args = json.load(fh)
|
| 37 |
+
points = np.ascontiguousarray(np.load(os.path.join(work, "points.npy")), dtype=np.float64)
|
| 38 |
+
|
| 39 |
+
entry = os.path.join(candidate, "select_subset.py")
|
| 40 |
+
import importlib.util
|
| 41 |
+
|
| 42 |
+
spec = importlib.util.spec_from_file_location("candidate_select_subset", entry)
|
| 43 |
+
if spec is None or spec.loader is None:
|
| 44 |
+
raise ImportError(f"cannot load {entry}")
|
| 45 |
+
module = importlib.util.module_from_spec(spec)
|
| 46 |
+
sys.path.insert(0, candidate)
|
| 47 |
+
spec.loader.exec_module(module)
|
| 48 |
+
fn = getattr(module, "select")
|
| 49 |
+
|
| 50 |
+
t0 = time.monotonic()
|
| 51 |
+
returned = fn(points, int(args["k"]), int(args["seed"]), float(args["time_budget_s"]))
|
| 52 |
+
call_s = time.monotonic() - t0
|
| 53 |
+
payload = {"ok": True, "call_s": call_s, "result": encode(returned)}
|
| 54 |
+
except BaseException as exc:
|
| 55 |
+
payload = {"ok": False, "error": f"{type(exc).__name__}: {exc}"[:400]}
|
| 56 |
+
|
| 57 |
+
try:
|
| 58 |
+
with open(out_path, "w") as fh:
|
| 59 |
+
_dump(payload, fh)
|
| 60 |
+
fh.flush()
|
| 61 |
+
os.fsync(fh.fileno())
|
| 62 |
+
except BaseException:
|
| 63 |
+
_exit(3)
|
| 64 |
+
_exit(0)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
if __name__ == "__main__":
|
| 68 |
+
main()
|
tasks/carps-star-discrepancy-subset-select/tests/test.sh
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
set -u
|
| 3 |
+
|
| 4 |
+
mkdir -p /logs/verifier
|
| 5 |
+
chown root:root /logs/verifier 2>/dev/null || true
|
| 6 |
+
chmod 755 /logs/verifier 2>/dev/null || true
|
| 7 |
+
rm -f /logs/verifier/reward.txt /logs/verifier/ctrf.json /logs/verifier/metric.json
|
| 8 |
+
|
| 9 |
+
trap '[ -s /logs/verifier/reward.txt ] || echo 0 > /logs/verifier/reward.txt' EXIT
|
| 10 |
+
|
| 11 |
+
chmod -R go-rwx /tests
|
| 12 |
+
|
| 13 |
+
cd /tests
|
| 14 |
+
export GRADE_SPLIT=final
|
| 15 |
+
GRADE_VERBOSE=1 \
|
| 16 |
+
/usr/local/bin/python3 -m pytest --ctrf /logs/verifier/ctrf.json /tests/test_state.py -rA
|
| 17 |
+
|
| 18 |
+
/usr/local/bin/python3 /tests/compute_reward.py
|
| 19 |
+
|
| 20 |
+
exit 0
|
tasks/carps-star-discrepancy-subset-select/tests/test_state.py
ADDED
|
@@ -0,0 +1,312 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import os
|
| 3 |
+
import shutil
|
| 4 |
+
import signal
|
| 5 |
+
import subprocess
|
| 6 |
+
import sys
|
| 7 |
+
import tempfile
|
| 8 |
+
import time
|
| 9 |
+
from collections import defaultdict
|
| 10 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
|
| 13 |
+
import numpy as np
|
| 14 |
+
import pytest
|
| 15 |
+
|
| 16 |
+
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
| 17 |
+
import grader_core
|
| 18 |
+
|
| 19 |
+
PY = "/usr/local/bin/python3"
|
| 20 |
+
RUNNER = "/opt/verifier/runner.py"
|
| 21 |
+
RUNUSER = shutil.which("runuser") or "/usr/sbin/runuser"
|
| 22 |
+
TASKSET = shutil.which("taskset") or "/usr/bin/taskset"
|
| 23 |
+
ARTIFACT_DIR = Path("/app/output")
|
| 24 |
+
CANDIDATE_DIR = Path("/opt/candidate")
|
| 25 |
+
ENTRY_NAME = "select_subset.py"
|
| 26 |
+
HIDDEN_ROOT = Path("/tests/hidden_data")
|
| 27 |
+
METRIC_PATH = Path("/logs/verifier/metric.json")
|
| 28 |
+
|
| 29 |
+
TIME_BUDGET_S = 10.0
|
| 30 |
+
KILL_GRACE_S = 5.0
|
| 31 |
+
AGENT_SEEDS = (0, 1, 2)
|
| 32 |
+
AGENT_UID, AGENT_GID = 1001, 1001
|
| 33 |
+
|
| 34 |
+
SPLIT = os.environ.get("GRADE_SPLIT", "final")
|
| 35 |
+
VERBOSE = os.environ.get("GRADE_VERBOSE", "0") == "1"
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def _harden_shared_paths() -> None:
|
| 39 |
+
"""Remove every agent-writable path that could survive from one graded run to the
|
| 40 |
+
next. Each call gets a fresh scratch directory and nothing else, so a submission
|
| 41 |
+
cannot pool budget across instances or replay cached work into a later run."""
|
| 42 |
+
for path in ("/tmp", "/var/tmp", "/dev/shm"):
|
| 43 |
+
try:
|
| 44 |
+
os.chmod(path, 0o755)
|
| 45 |
+
except OSError:
|
| 46 |
+
pass
|
| 47 |
+
for path in ("/home/agent", str(ARTIFACT_DIR)):
|
| 48 |
+
try:
|
| 49 |
+
os.chmod(path, 0o555)
|
| 50 |
+
except OSError:
|
| 51 |
+
pass
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def _has_link(root: Path) -> str:
|
| 55 |
+
"""Reject a submitted tree containing symlinks or hard links, at any depth."""
|
| 56 |
+
for dirpath, dirnames, filenames in os.walk(root, followlinks=False):
|
| 57 |
+
for name in dirnames + filenames:
|
| 58 |
+
p = Path(dirpath) / name
|
| 59 |
+
st = p.lstat()
|
| 60 |
+
if os.path.islink(p):
|
| 61 |
+
return f"symlink {p}"
|
| 62 |
+
if not os.path.isdir(p) and st.st_nlink > 1:
|
| 63 |
+
return f"hard link {p}"
|
| 64 |
+
return ""
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def stage_candidate() -> dict:
|
| 68 |
+
"""Copy the submitted deliverable to a root-owned directory, links refused."""
|
| 69 |
+
info = {"found": False, "note": ""}
|
| 70 |
+
if not ARTIFACT_DIR.is_dir():
|
| 71 |
+
info["note"] = f"{ARTIFACT_DIR} is missing"
|
| 72 |
+
return info
|
| 73 |
+
link = _has_link(ARTIFACT_DIR)
|
| 74 |
+
if link:
|
| 75 |
+
info["note"] = f"submitted tree contains a {link}; refused"
|
| 76 |
+
return info
|
| 77 |
+
CANDIDATE_DIR.mkdir(parents=True, exist_ok=True)
|
| 78 |
+
for child in CANDIDATE_DIR.iterdir():
|
| 79 |
+
if child.is_dir() and not child.is_symlink():
|
| 80 |
+
shutil.rmtree(child)
|
| 81 |
+
else:
|
| 82 |
+
child.unlink()
|
| 83 |
+
shutil.copytree(ARTIFACT_DIR, CANDIDATE_DIR, symlinks=True, dirs_exist_ok=True)
|
| 84 |
+
os.chown(CANDIDATE_DIR, 0, 0)
|
| 85 |
+
os.chmod(CANDIDATE_DIR, 0o755)
|
| 86 |
+
for dirpath, dirnames, filenames in os.walk(CANDIDATE_DIR):
|
| 87 |
+
for name in dirnames + filenames:
|
| 88 |
+
p = Path(dirpath) / name
|
| 89 |
+
if os.path.islink(p):
|
| 90 |
+
continue
|
| 91 |
+
os.chown(p, 0, 0)
|
| 92 |
+
os.chmod(p, 0o755 if p.is_dir() else 0o644)
|
| 93 |
+
entry = CANDIDATE_DIR / ENTRY_NAME
|
| 94 |
+
if not entry.is_file():
|
| 95 |
+
info["note"] = f"{ARTIFACT_DIR / ENTRY_NAME} is missing"
|
| 96 |
+
return info
|
| 97 |
+
info["found"] = True
|
| 98 |
+
return info
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def _child_env(work: Path) -> dict:
|
| 102 |
+
return {
|
| 103 |
+
"PATH": "/usr/local/bin:/usr/bin:/bin",
|
| 104 |
+
"HOME": str(work),
|
| 105 |
+
"TMPDIR": str(work),
|
| 106 |
+
"PYTHONHASHSEED": "0",
|
| 107 |
+
"PYTHONSAFEPATH": "1",
|
| 108 |
+
"PYTHONDONTWRITEBYTECODE": "1",
|
| 109 |
+
"OMP_NUM_THREADS": "1",
|
| 110 |
+
"MKL_NUM_THREADS": "1",
|
| 111 |
+
"OPENBLAS_NUM_THREADS": "1",
|
| 112 |
+
"NUMEXPR_NUM_THREADS": "1",
|
| 113 |
+
}
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def _read_result(path: Path):
|
| 117 |
+
"""Read the runner's output without following a symlink planted in its place."""
|
| 118 |
+
fd = os.open(str(path), os.O_RDONLY | os.O_NOFOLLOW)
|
| 119 |
+
with os.fdopen(fd, "r") as fh:
|
| 120 |
+
return json.load(fh)
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def run_one(points: np.ndarray, k: int, seed: int, cpu: int) -> dict:
|
| 124 |
+
"""Execute the candidate once, as uid 1001, on one CPU, under a hard deadline."""
|
| 125 |
+
work = Path(tempfile.mkdtemp(prefix="grade_"))
|
| 126 |
+
try:
|
| 127 |
+
np.save(work / "points.npy", points)
|
| 128 |
+
(work / "args.json").write_text(
|
| 129 |
+
json.dumps({"k": int(k), "seed": int(seed), "time_budget_s": TIME_BUDGET_S})
|
| 130 |
+
)
|
| 131 |
+
for p in (work, work / "points.npy", work / "args.json"):
|
| 132 |
+
os.chmod(p, 0o755 if p.is_dir() else 0o644)
|
| 133 |
+
os.chown(work, AGENT_UID, AGENT_GID)
|
| 134 |
+
|
| 135 |
+
cmd = [
|
| 136 |
+
TASKSET, "-c", str(cpu),
|
| 137 |
+
RUNUSER, "-u", "agent", "--",
|
| 138 |
+
PY, RUNNER, str(work), str(CANDIDATE_DIR),
|
| 139 |
+
]
|
| 140 |
+
hard = TIME_BUDGET_S + KILL_GRACE_S
|
| 141 |
+
t0 = time.monotonic()
|
| 142 |
+
proc = subprocess.Popen(
|
| 143 |
+
cmd,
|
| 144 |
+
stdout=subprocess.DEVNULL,
|
| 145 |
+
stderr=subprocess.PIPE,
|
| 146 |
+
env=_child_env(work),
|
| 147 |
+
cwd=str(work),
|
| 148 |
+
start_new_session=True,
|
| 149 |
+
)
|
| 150 |
+
killed = False
|
| 151 |
+
try:
|
| 152 |
+
_, err = proc.communicate(timeout=hard)
|
| 153 |
+
except subprocess.TimeoutExpired:
|
| 154 |
+
killed = True
|
| 155 |
+
try:
|
| 156 |
+
os.killpg(os.getpgid(proc.pid), signal.SIGKILL)
|
| 157 |
+
except OSError:
|
| 158 |
+
pass
|
| 159 |
+
try:
|
| 160 |
+
_, err = proc.communicate(timeout=15)
|
| 161 |
+
except subprocess.TimeoutExpired:
|
| 162 |
+
err = b""
|
| 163 |
+
wall = time.monotonic() - t0
|
| 164 |
+
|
| 165 |
+
if killed:
|
| 166 |
+
return {"valid": False, "error": "exceeded the deadline", "wall_s": wall}
|
| 167 |
+
try:
|
| 168 |
+
payload = _read_result(work / "result.json")
|
| 169 |
+
except Exception as exc:
|
| 170 |
+
tail = (err or b"").decode("utf-8", "replace").strip().splitlines()[-1:]
|
| 171 |
+
reason = tail[0][:200] if tail else f"{type(exc).__name__}"
|
| 172 |
+
return {"valid": False, "error": f"no usable result ({reason})", "wall_s": wall}
|
| 173 |
+
if not isinstance(payload, dict) or not payload.get("ok"):
|
| 174 |
+
reason = str(payload.get("error", "unknown"))[:200] if isinstance(payload, dict) else "malformed"
|
| 175 |
+
return {"valid": False, "error": reason, "wall_s": wall}
|
| 176 |
+
try:
|
| 177 |
+
idx = grader_core.validate_indices(payload.get("result"), points.shape[0], k)
|
| 178 |
+
except ValueError as exc:
|
| 179 |
+
return {"valid": False, "error": str(exc)[:200], "wall_s": wall}
|
| 180 |
+
try:
|
| 181 |
+
call_s = float(payload.get("call_s"))
|
| 182 |
+
except (TypeError, ValueError):
|
| 183 |
+
call_s = float("nan")
|
| 184 |
+
return {"valid": True, "indices": idx, "wall_s": wall, "call_s": call_s}
|
| 185 |
+
finally:
|
| 186 |
+
shutil.rmtree(work, ignore_errors=True)
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
def grade() -> dict:
|
| 190 |
+
out = {
|
| 191 |
+
"split": SPLIT,
|
| 192 |
+
"metric": None,
|
| 193 |
+
"m0": None,
|
| 194 |
+
"reward": 0.0,
|
| 195 |
+
"valid_runs": 0,
|
| 196 |
+
"total_runs": 0,
|
| 197 |
+
"candidate_found": False,
|
| 198 |
+
"time_budget_s": TIME_BUDGET_S,
|
| 199 |
+
"kill_grace_s": KILL_GRACE_S,
|
| 200 |
+
"agent_seeds": list(AGENT_SEEDS),
|
| 201 |
+
"errors": [],
|
| 202 |
+
}
|
| 203 |
+
try:
|
| 204 |
+
_harden_shared_paths()
|
| 205 |
+
manifest = json.loads((HIDDEN_ROOT / SPLIT / "manifest.json").read_text())
|
| 206 |
+
instances = []
|
| 207 |
+
for entry in manifest["instances"]:
|
| 208 |
+
pts = np.load(HIDDEN_ROOT / SPLIT / entry["file"])
|
| 209 |
+
instances.append({**entry, "points": np.ascontiguousarray(pts, dtype=np.float64)})
|
| 210 |
+
|
| 211 |
+
baseline = {}
|
| 212 |
+
for inst in instances:
|
| 213 |
+
bidx = grader_core.baseline_indices(inst["baseline_seed"], inst["n"], inst["k"])
|
| 214 |
+
baseline[inst["iid"]] = grader_core.star_discrepancy_3d(inst["points"][bidx])
|
| 215 |
+
|
| 216 |
+
info = stage_candidate()
|
| 217 |
+
out["candidate_found"] = info["found"]
|
| 218 |
+
if info["note"]:
|
| 219 |
+
out["errors"].append(info["note"])
|
| 220 |
+
|
| 221 |
+
jobs = [(inst, seed) for seed in AGENT_SEEDS for inst in instances]
|
| 222 |
+
out["total_runs"] = len(jobs)
|
| 223 |
+
m0 = float(np.mean([baseline[inst["iid"]] for inst, _ in jobs]))
|
| 224 |
+
out["m0"] = m0
|
| 225 |
+
cpus = sorted(os.sched_getaffinity(0))
|
| 226 |
+
workers = max(1, min(8, len(cpus)))
|
| 227 |
+
results = [None] * len(jobs)
|
| 228 |
+
|
| 229 |
+
if info["found"]:
|
| 230 |
+
def task(job_index):
|
| 231 |
+
inst, seed = jobs[job_index]
|
| 232 |
+
cpu = cpus[job_index % workers]
|
| 233 |
+
return job_index, run_one(inst["points"], inst["k"], seed, cpu)
|
| 234 |
+
|
| 235 |
+
with ThreadPoolExecutor(max_workers=workers) as pool:
|
| 236 |
+
for job_index, res in pool.map(task, range(len(jobs))):
|
| 237 |
+
results[job_index] = res
|
| 238 |
+
else:
|
| 239 |
+
results = [{"valid": False, "error": info["note"] or "no deliverable"}] * len(jobs)
|
| 240 |
+
|
| 241 |
+
per_run, per_k, errors, walls = [], defaultdict(list), defaultdict(int), []
|
| 242 |
+
for (inst, seed), res in zip(jobs, results):
|
| 243 |
+
if res and "wall_s" in res:
|
| 244 |
+
walls.append(res["wall_s"])
|
| 245 |
+
if res and res.get("valid"):
|
| 246 |
+
value = grader_core.star_discrepancy_3d(inst["points"][res["indices"]])
|
| 247 |
+
out["valid_runs"] += 1
|
| 248 |
+
else:
|
| 249 |
+
value = baseline[inst["iid"]]
|
| 250 |
+
errors[(res or {}).get("error", "unknown")] += 1
|
| 251 |
+
per_run.append(value)
|
| 252 |
+
per_k[inst["k"]].append(value)
|
| 253 |
+
if VERBOSE:
|
| 254 |
+
print(f" {inst['iid']} k={inst['k']} seed={seed} d*={value:.4f} "
|
| 255 |
+
f"valid={bool(res and res.get('valid'))}")
|
| 256 |
+
|
| 257 |
+
if VERBOSE:
|
| 258 |
+
out["per_run"] = [
|
| 259 |
+
{"iid": inst["iid"], "k": inst["k"], "seed": seed, "d": value,
|
| 260 |
+
"baseline_d": baseline[inst["iid"]]}
|
| 261 |
+
for (inst, seed), value in zip(jobs, per_run)
|
| 262 |
+
]
|
| 263 |
+
out["metric"] = float(np.mean(per_run))
|
| 264 |
+
out["per_k_mean"] = {str(k): float(np.mean(v)) for k, v in sorted(per_k.items())}
|
| 265 |
+
if walls:
|
| 266 |
+
out["wall_s"] = {"max": float(np.max(walls)), "mean": float(np.mean(walls))}
|
| 267 |
+
out["reward"] = grader_core.graded_reward(out["metric"], m0)
|
| 268 |
+
out["errors"].extend(f"{n}x {msg}" for msg, n in sorted(errors.items(), key=lambda kv: -kv[1])[:5])
|
| 269 |
+
except Exception as exc:
|
| 270 |
+
out["errors"].append(f"grader error: {type(exc).__name__}: {exc}"[:300])
|
| 271 |
+
finally:
|
| 272 |
+
METRIC_PATH.parent.mkdir(parents=True, exist_ok=True)
|
| 273 |
+
METRIC_PATH.write_text(json.dumps(out, indent=2, sort_keys=True) + "\n")
|
| 274 |
+
return out
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
@pytest.fixture(scope="session")
|
| 278 |
+
def outcome():
|
| 279 |
+
result = grade()
|
| 280 |
+
print(f"\nsplit: {result['split']}")
|
| 281 |
+
print(f"runs: {result['valid_runs']}/{result['total_runs']} valid "
|
| 282 |
+
f"({len(result['agent_seeds'])} seeds per instance, "
|
| 283 |
+
f"{result['time_budget_s']:.1f}s budget per call)")
|
| 284 |
+
if result["metric"] is not None:
|
| 285 |
+
print(f"mean exact L_inf star discrepancy: {result['metric']:.6f}")
|
| 286 |
+
for k, v in result.get("per_k_mean", {}).items():
|
| 287 |
+
print(f" k={k}: {v:.6f}")
|
| 288 |
+
print(f"score: {result['reward']:.6f}")
|
| 289 |
+
for msg in result["errors"]:
|
| 290 |
+
print(f"note: {msg}")
|
| 291 |
+
return result
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
def test_deliverable_present(outcome):
|
| 295 |
+
"""/app/output/select_subset.py exists and was stageable (no links in the tree)."""
|
| 296 |
+
assert outcome["candidate_found"], outcome["errors"]
|
| 297 |
+
|
| 298 |
+
|
| 299 |
+
def test_all_runs_valid(outcome):
|
| 300 |
+
"""Every graded call returned k distinct in-range indices inside its deadline."""
|
| 301 |
+
assert outcome["valid_runs"] == outcome["total_runs"], outcome["errors"]
|
| 302 |
+
|
| 303 |
+
|
| 304 |
+
def test_metric_computed(outcome):
|
| 305 |
+
"""A finite panel metric and a reward in [0,1] were produced."""
|
| 306 |
+
assert outcome["metric"] is not None and np.isfinite(outcome["metric"])
|
| 307 |
+
assert 0.0 <= outcome["reward"] <= 1.0
|
| 308 |
+
|
| 309 |
+
|
| 310 |
+
def test_beats_trivial_baseline(outcome):
|
| 311 |
+
"""The submitted selector is strictly better than an unguided random subset."""
|
| 312 |
+
assert outcome["metric"] < outcome["m0"], (outcome["metric"], outcome["m0"])
|
tasks/cpu-decoder-graph-executor/environment/Dockerfile
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM --platform=linux/amd64 public.ecr.aws/docker/library/python:3.13-slim-bookworm@sha256:01f42367a0a94ad4bc17111776fd66e3500c1d87c15bbd6055b7371d39c124fb
|
| 2 |
+
|
| 3 |
+
RUN set -eu; \
|
| 4 |
+
if [ ! -s /etc/ssl/certs/ca-certificates.crt ]; then \
|
| 5 |
+
apt-get update && apt-get install -y --no-install-recommends ca-certificates=20230311+deb12u1; \
|
| 6 |
+
fi; \
|
| 7 |
+
rm -f /tmp/hz-prereq.list; \
|
| 8 |
+
echo 'deb [signed-by=/usr/share/keyrings/debian-archive-keyring.gpg] https://snapshot.debian.org/archive/debian/20260801T000000Z bookworm main' >> /tmp/hz-prereq.list; \
|
| 9 |
+
echo 'deb [signed-by=/usr/share/keyrings/debian-archive-keyring.gpg] https://snapshot.debian.org/archive/debian-security/20260801T000000Z bookworm-security main' >> /tmp/hz-prereq.list; \
|
| 10 |
+
apt-get -o Dir::Etc::sourcelist=/tmp/hz-prereq.list -o Dir::Etc::sourceparts=/dev/null -o Acquire::Check-Valid-Until=false update; \
|
| 11 |
+
apt-get -o Dir::Etc::sourcelist=/tmp/hz-prereq.list -o Dir::Etc::sourceparts=/dev/null -o Acquire::Check-Valid-Until=false install -y --no-install-recommends tmux=3.3a-3 asciinema=2.2.0-1 git=1:2.39.5-0+deb12u3; \
|
| 12 |
+
rm -f /tmp/hz-prereq.list; rm -rf /var/lib/apt/lists/*
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
ENTRYPOINT []
|
| 16 |
+
ENV DEBIAN_FRONTEND=noninteractive \
|
| 17 |
+
PYTHONHASHSEED=0 \
|
| 18 |
+
PIP_NO_CACHE_DIR=1 \
|
| 19 |
+
PIP_DISABLE_PIP_VERSION_CHECK=1 \
|
| 20 |
+
OMP_NUM_THREADS=1
|
| 21 |
+
|
| 22 |
+
RUN git config --system user.email "agent@localhost" \
|
| 23 |
+
&& git config --system user.name "autoresearch agent"
|
| 24 |
+
|
| 25 |
+
RUN useradd --create-home --uid 1001 agent
|
| 26 |
+
|
| 27 |
+
COPY ./requirements.txt /tmp/requirements.txt
|
| 28 |
+
RUN /usr/local/bin/python3 -m pip install --no-cache-dir -r /tmp/requirements.txt \
|
| 29 |
+
&& rm /tmp/requirements.txt
|
| 30 |
+
|
| 31 |
+
WORKDIR /app
|
| 32 |
+
COPY ./app /app
|
| 33 |
+
|
| 34 |
+
RUN mkdir -p /app/output \
|
| 35 |
+
&& chown -R agent:agent /app \
|
| 36 |
+
&& chmod +x /app/bench.py \
|
| 37 |
+
&& find /app -exec touch -d @1700000000 {} +
|
| 38 |
+
|
| 39 |
+
ENV HF_HUB_OFFLINE=1
|
| 40 |
+
ENV TRANSFORMERS_OFFLINE=1
|
| 41 |
+
|
| 42 |
+
USER agent
|
tasks/cpu-decoder-graph-executor/environment/app/bench.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
import argparse
|
| 3 |
+
import os
|
| 4 |
+
import shutil
|
| 5 |
+
import sys
|
| 6 |
+
import tempfile
|
| 7 |
+
|
| 8 |
+
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
| 9 |
+
import harness
|
| 10 |
+
|
| 11 |
+
HERE = os.path.dirname(os.path.abspath(__file__))
|
| 12 |
+
PUBLIC_SEEDS = list(range(16))
|
| 13 |
+
CORE = ("worker.py", "graph_spec.py", "reference_executor.py")
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def main():
|
| 17 |
+
ap = argparse.ArgumentParser()
|
| 18 |
+
ap.add_argument("--dir", default="/app/output", help="directory holding executor.py")
|
| 19 |
+
ap.add_argument("--seeds", default=",".join(str(s) for s in PUBLIC_SEEDS))
|
| 20 |
+
ap.add_argument("--json", default=None, help="also write the full record here")
|
| 21 |
+
args = ap.parse_args()
|
| 22 |
+
|
| 23 |
+
seeds = [int(s) for s in args.seeds.split(",") if s.strip()]
|
| 24 |
+
run = tempfile.mkdtemp(prefix="bench_")
|
| 25 |
+
try:
|
| 26 |
+
for f in CORE:
|
| 27 |
+
shutil.copy2(os.path.join(HERE, f), os.path.join(run, f))
|
| 28 |
+
shutil.copytree(args.dir, os.path.join(run, "submission"))
|
| 29 |
+
rec = harness.measure(seeds, run, python=sys.executable)
|
| 30 |
+
finally:
|
| 31 |
+
shutil.rmtree(run, ignore_errors=True)
|
| 32 |
+
|
| 33 |
+
print("%5s %5s %6s %6s %11s %11s %8s %10s %10s"
|
| 34 |
+
% ("seed", "T", "d", "L", "ref best ms", "sub best ms", "ratio",
|
| 35 |
+
"max abs", "rel fro"))
|
| 36 |
+
for r in rec["per_instance"]:
|
| 37 |
+
print("%5d %5d %6d %6d %11.2f %11.2f %8.3f %10.2e %10.2e%s"
|
| 38 |
+
% (r["seed"], r["shape"]["T"], r["shape"]["d_model"],
|
| 39 |
+
r["shape"]["n_layers"], r["ref_best_s"] * 1e3, r["sub_best_s"] * 1e3,
|
| 40 |
+
r["ratio"], r["max_abs_err"], r["rel_fro_err"],
|
| 41 |
+
"" if r["equivalent"] else " NOT EQUIVALENT"))
|
| 42 |
+
if rec["failure"]:
|
| 43 |
+
print("\nFAILED: %s" % rec["failure"])
|
| 44 |
+
if rec["stderr_tail"]:
|
| 45 |
+
print(rec["stderr_tail"])
|
| 46 |
+
print("\ninstances %d, equivalent %d, geometric-mean speedup %.4f"
|
| 47 |
+
% (rec["n_instances"], rec["n_equivalent"], rec["metric"]))
|
| 48 |
+
if args.json:
|
| 49 |
+
harness.dump(rec, args.json)
|
| 50 |
+
return 0
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
if __name__ == "__main__":
|
| 54 |
+
sys.exit(main())
|
tasks/cpu-decoder-graph-executor/environment/app/graph_spec.py
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
|
| 3 |
+
D_MODEL_CHOICES = (192, 256, 384)
|
| 4 |
+
FF_RATIO_CHOICES = (2.6875, 4.0)
|
| 5 |
+
N_LAYER_CHOICES = (16, 32)
|
| 6 |
+
N_HEAD_CHOICES = (4, 8)
|
| 7 |
+
KV_DIV_CHOICES = (1, 2, 4)
|
| 8 |
+
T_CHOICES = (1, 1, 1, 8, 8, 32)
|
| 9 |
+
|
| 10 |
+
RMS_EPS = 1e-5
|
| 11 |
+
ROPE_THETA = 10000.0
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def sample_spec(seed):
|
| 15 |
+
"""Return the graph_spec dict for `seed`."""
|
| 16 |
+
rng = np.random.default_rng(seed)
|
| 17 |
+
d_model = int(rng.choice(D_MODEL_CHOICES))
|
| 18 |
+
ratio = float(rng.choice(FF_RATIO_CHOICES))
|
| 19 |
+
d_ff = int(round(d_model * ratio / 32.0)) * 32
|
| 20 |
+
n_layers = int(rng.choice(N_LAYER_CHOICES))
|
| 21 |
+
n_heads = int(rng.choice(N_HEAD_CHOICES))
|
| 22 |
+
head_dim = d_model // n_heads
|
| 23 |
+
n_kv_heads = n_heads // int(rng.choice(KV_DIV_CHOICES))
|
| 24 |
+
T = int(rng.choice(T_CHOICES))
|
| 25 |
+
|
| 26 |
+
layers = []
|
| 27 |
+
for li in range(n_layers):
|
| 28 |
+
p = "blk.%d." % li
|
| 29 |
+
layers.append([
|
| 30 |
+
{"op": "rmsnorm", "out": "n1", "inputs": ["h"], "weight": p + "attn_norm"},
|
| 31 |
+
{"op": "matmul", "out": "q", "inputs": ["n1"], "weight": p + "attn_q"},
|
| 32 |
+
{"op": "matmul", "out": "k", "inputs": ["n1"], "weight": p + "attn_k"},
|
| 33 |
+
{"op": "matmul", "out": "v", "inputs": ["n1"], "weight": p + "attn_v"},
|
| 34 |
+
{"op": "attention", "out": "att", "inputs": ["q", "k", "v"], "weight": None},
|
| 35 |
+
{"op": "matmul", "out": "ao", "inputs": ["att"], "weight": p + "attn_out"},
|
| 36 |
+
{"op": "add", "out": "h", "inputs": ["h", "ao"], "weight": None},
|
| 37 |
+
{"op": "rmsnorm", "out": "n2", "inputs": ["h"], "weight": p + "ffn_norm"},
|
| 38 |
+
{"op": "matmul", "out": "g", "inputs": ["n2"], "weight": p + "ffn_gate"},
|
| 39 |
+
{"op": "matmul", "out": "u", "inputs": ["n2"], "weight": p + "ffn_up"},
|
| 40 |
+
{"op": "swiglu", "out": "f", "inputs": ["g", "u"], "weight": None},
|
| 41 |
+
{"op": "matmul", "out": "fo", "inputs": ["f"], "weight": p + "ffn_down"},
|
| 42 |
+
{"op": "add", "out": "h", "inputs": ["h", "fo"], "weight": None},
|
| 43 |
+
])
|
| 44 |
+
|
| 45 |
+
return {
|
| 46 |
+
"seed": int(seed),
|
| 47 |
+
"n_layers": n_layers,
|
| 48 |
+
"d_model": d_model,
|
| 49 |
+
"d_ff": d_ff,
|
| 50 |
+
"n_heads": n_heads,
|
| 51 |
+
"n_kv_heads": n_kv_heads,
|
| 52 |
+
"head_dim": head_dim,
|
| 53 |
+
"T": T,
|
| 54 |
+
"rms_eps": RMS_EPS,
|
| 55 |
+
"layers": layers,
|
| 56 |
+
"final": {"op": "rmsnorm", "out": "h", "inputs": ["h"], "weight": "output_norm"},
|
| 57 |
+
}
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def _normal(rng, shape, scale):
|
| 61 |
+
return (rng.standard_normal(shape, dtype=np.float32) * np.float32(scale))
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def build_weights(spec):
|
| 65 |
+
"""Return the tensor dict for `spec`. All arrays are C-contiguous float32."""
|
| 66 |
+
rng = np.random.default_rng(spec["seed"] + 1_000_003)
|
| 67 |
+
d = spec["d_model"]
|
| 68 |
+
d_ff = spec["d_ff"]
|
| 69 |
+
hd = spec["head_dim"]
|
| 70 |
+
n_q = spec["n_heads"] * hd
|
| 71 |
+
n_kv = spec["n_kv_heads"] * hd
|
| 72 |
+
T = spec["T"]
|
| 73 |
+
|
| 74 |
+
w = {}
|
| 75 |
+
for li in range(spec["n_layers"]):
|
| 76 |
+
p = "blk.%d." % li
|
| 77 |
+
w[p + "attn_norm"] = np.ascontiguousarray(1.0 + 0.02 * _normal(rng, (d,), 1.0))
|
| 78 |
+
w[p + "attn_q"] = np.ascontiguousarray(_normal(rng, (d, n_q), d ** -0.5))
|
| 79 |
+
w[p + "attn_k"] = np.ascontiguousarray(_normal(rng, (d, n_kv), d ** -0.5))
|
| 80 |
+
w[p + "attn_v"] = np.ascontiguousarray(_normal(rng, (d, n_kv), d ** -0.5))
|
| 81 |
+
w[p + "attn_out"] = np.ascontiguousarray(_normal(rng, (n_q, d), n_q ** -0.5))
|
| 82 |
+
w[p + "ffn_norm"] = np.ascontiguousarray(1.0 + 0.02 * _normal(rng, (d,), 1.0))
|
| 83 |
+
w[p + "ffn_gate"] = np.ascontiguousarray(_normal(rng, (d, d_ff), d ** -0.5))
|
| 84 |
+
w[p + "ffn_up"] = np.ascontiguousarray(_normal(rng, (d, d_ff), d ** -0.5))
|
| 85 |
+
w[p + "ffn_down"] = np.ascontiguousarray(_normal(rng, (d_ff, d), d_ff ** -0.5))
|
| 86 |
+
w["output_norm"] = np.ascontiguousarray(1.0 + 0.02 * _normal(rng, (d,), 1.0))
|
| 87 |
+
|
| 88 |
+
half = hd // 2
|
| 89 |
+
inv = (ROPE_THETA ** (-np.arange(half, dtype=np.float64) / half))
|
| 90 |
+
ang = np.arange(T, dtype=np.float64)[:, None] * inv[None, :]
|
| 91 |
+
w["rope_cos"] = np.ascontiguousarray(np.cos(ang).astype(np.float32))
|
| 92 |
+
w["rope_sin"] = np.ascontiguousarray(np.sin(ang).astype(np.float32))
|
| 93 |
+
|
| 94 |
+
mask = np.zeros((T, T), dtype=np.float32)
|
| 95 |
+
mask[np.triu_indices(T, k=1)] = -np.inf
|
| 96 |
+
w["attn_mask"] = np.ascontiguousarray(mask)
|
| 97 |
+
return w
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def build_inputs(spec, n):
|
| 101 |
+
"""Return `n` distinct input activations of shape (T, d_model), float32.
|
| 102 |
+
|
| 103 |
+
Drawn from fresh OS entropy, never from the instance seed: the same list is fed
|
| 104 |
+
to both executors within a run, but no executor can precompute the output for an
|
| 105 |
+
input it has not yet been sent.
|
| 106 |
+
"""
|
| 107 |
+
rng = np.random.default_rng()
|
| 108 |
+
T, d = spec["T"], spec["d_model"]
|
| 109 |
+
return [np.ascontiguousarray(rng.standard_normal((T, d), dtype=np.float32))
|
| 110 |
+
for _ in range(n)]
|