Spaces:
Running
Running
Upload from GitHub Actions: Merge pull request #32 from datenlabor-bmz/eval-crash-safe-incremental-runs
Browse files- .github/workflows/nightly-evals.yml +22 -0
- .gitignore +2 -0
- evals/datasets_/util.py +6 -2
- evals/main.py +208 -57
- evals/models.py +44 -5
.github/workflows/nightly-evals.yml
CHANGED
|
@@ -4,6 +4,11 @@ on:
|
|
| 4 |
schedule:
|
| 5 |
- cron: '0 3 * * 1' # Weekly: Mondays 3am UTC
|
| 6 |
workflow_dispatch: # Allow manual triggering
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
|
| 8 |
jobs:
|
| 9 |
run-evals:
|
|
@@ -104,7 +109,24 @@ jobs:
|
|
| 104 |
# Per-model checkpointing makes this safe: completed models are
|
| 105 |
# published and skipped next run; a partial model resumes.
|
| 106 |
MAX_RUNTIME_SECONDS: 18000
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 107 |
run: |
|
|
|
|
|
|
|
|
|
|
| 108 |
# `huggingface-cli login` only warms a credential cache; all dataset
|
| 109 |
# load/save calls in the code pass token=HUGGINGFACE_ACCESS_TOKEN
|
| 110 |
# explicitly, so this is non-essential. HF's whoami endpoint
|
|
|
|
| 4 |
schedule:
|
| 5 |
- cron: '0 3 * * 1' # Weekly: Mondays 3am UTC
|
| 6 |
workflow_dispatch: # Allow manual triggering
|
| 7 |
+
inputs:
|
| 8 |
+
max_new_models:
|
| 9 |
+
description: 'Max not-yet-complete models to work on this run (0 = unlimited). Scheduled runs use 2.'
|
| 10 |
+
required: false
|
| 11 |
+
default: '2'
|
| 12 |
|
| 13 |
jobs:
|
| 14 |
run-evals:
|
|
|
|
| 109 |
# Per-model checkpointing makes this safe: completed models are
|
| 110 |
# published and skipped next run; a partial model resumes.
|
| 111 |
MAX_RUNTIME_SECONDS: 18000
|
| 112 |
+
# This workflow is for INCREMENTAL additions, "a new model landed,
|
| 113 |
+
# evaluate it", not for clearing a backlog. Onboarding many models in
|
| 114 |
+
# one CI run is the expensive/fragile path: every per-model checkpoint
|
| 115 |
+
# re-pushes the whole results-detailed log, `all_results` is held
|
| 116 |
+
# entirely in RAM on a 16GB runner, and a crash re-costs the in-flight
|
| 117 |
+
# model because CI has no sample-level joblib cache (that lives on
|
| 118 |
+
# local disk, and is deliberately NOT restored here).
|
| 119 |
+
# Backlogs belong on a local machine, or on a deliberate
|
| 120 |
+
# workflow_dispatch run with this input set to 0 (unlimited).
|
| 121 |
+
# Empty for `schedule` (no inputs context); the default is applied in
|
| 122 |
+
# the shell below, NOT with `${{ ... || '2' }}`. GitHub's expression
|
| 123 |
+
# truthiness can cast the string '0' to falsy, which would silently
|
| 124 |
+
# turn the "0 = unlimited" escape hatch back into 2.
|
| 125 |
+
MAX_NEW_MODELS_PER_RUN: ${{ github.event.inputs.max_new_models }}
|
| 126 |
run: |
|
| 127 |
+
# Default only when genuinely unset/empty (i.e. a scheduled run).
|
| 128 |
+
export MAX_NEW_MODELS_PER_RUN="${MAX_NEW_MODELS_PER_RUN:-2}"
|
| 129 |
+
echo "MAX_NEW_MODELS_PER_RUN=$MAX_NEW_MODELS_PER_RUN"
|
| 130 |
# `huggingface-cli login` only warms a credential cache; all dataset
|
| 131 |
# load/save calls in the code pass token=HUGGINGFACE_ACCESS_TOKEN
|
| 132 |
# explicitly, so this is non-essential. HF's whoami endpoint
|
.gitignore
CHANGED
|
@@ -4,6 +4,8 @@
|
|
| 4 |
results/results-detailed.json
|
| 5 |
results/*.csv
|
| 6 |
results/*.log
|
|
|
|
|
|
|
| 7 |
data/translations/
|
| 8 |
floresp-*
|
| 9 |
fleurs
|
|
|
|
| 4 |
results/results-detailed.json
|
| 5 |
results/*.csv
|
| 6 |
results/*.log
|
| 7 |
+
# DRY_RUN=1 output, partial-scale test snapshots, never published
|
| 8 |
+
results/dry-run/
|
| 9 |
data/translations/
|
| 10 |
floresp-*
|
| 11 |
fleurs
|
evals/datasets_/util.py
CHANGED
|
@@ -109,10 +109,14 @@ def save_local_only(df: pd.DataFrame, fname: str):
|
|
| 109 |
Used during partial-scale eval runs (smoke tests, local development) so
|
| 110 |
the public dataset isn't truncated by a filtered aggregate. The next
|
| 111 |
full-scale run will push the canonical version.
|
|
|
|
|
|
|
|
|
|
| 112 |
"""
|
| 113 |
df = df.drop(columns=["__index_level_0__"], errors="ignore")
|
| 114 |
-
Path("results").
|
| 115 |
-
|
|
|
|
| 116 |
|
| 117 |
|
| 118 |
def get_valid_task_languages(task_name: str) -> set:
|
|
|
|
| 109 |
Used during partial-scale eval runs (smoke tests, local development) so
|
| 110 |
the public dataset isn't truncated by a filtered aggregate. The next
|
| 111 |
full-scale run will push the canonical version.
|
| 112 |
+
|
| 113 |
+
`fname` may contain a subdirectory (e.g. "dry-run/results"), which DRY_RUN
|
| 114 |
+
uses to keep test output away from the tracked results/*.json files.
|
| 115 |
"""
|
| 116 |
df = df.drop(columns=["__index_level_0__"], errors="ignore")
|
| 117 |
+
out = Path("results") / f"{fname}.json"
|
| 118 |
+
out.parent.mkdir(parents=True, exist_ok=True)
|
| 119 |
+
df.to_json(out, orient="records", force_ascii=False, indent=2)
|
| 120 |
|
| 121 |
|
| 122 |
def get_valid_task_languages(task_name: str) -> set:
|
evals/main.py
CHANGED
|
@@ -38,12 +38,34 @@ n_models = int(environ.get("N_MODELS", 40))
|
|
| 38 |
# run resumes the rest (completed models are skipped). 0 = no limit (local runs).
|
| 39 |
max_runtime_seconds = int(environ.get("MAX_RUNTIME_SECONDS", 0))
|
| 40 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 41 |
# When n_languages or n_models is smaller than canonical, the filter in
|
| 42 |
# `results_agg` below would discard most rows and overwrite the public HF
|
| 43 |
# aggregate. Detect that and downgrade to local-only writes.
|
| 44 |
ALLOW_HF_PUSH_RESULTS = (
|
| 45 |
n_languages >= CANONICAL_N_LANGUAGES_FOR_PUSH
|
| 46 |
and n_models >= CANONICAL_N_MODELS_FOR_PUSH
|
|
|
|
| 47 |
)
|
| 48 |
|
| 49 |
def publishable_models(log_df, covered_models):
|
|
@@ -87,22 +109,36 @@ def checkpoint(log_df, covered_models, cohort_languages, note):
|
|
| 87 |
.agg({"score": "mean", "origin": "first"})
|
| 88 |
.reset_index()
|
| 89 |
)
|
| 90 |
-
|
| 91 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
# The aggregated tables are filtered by cohort_models × cohort_languages, so
|
| 93 |
# a partial-scale run would truncate the published view — push only from a
|
| 94 |
# full-scale run; otherwise local-only.
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
|
|
|
|
|
|
|
|
|
| 99 |
else:
|
| 100 |
-
|
| 101 |
-
save_local_only(models, "models")
|
| 102 |
-
save_local_only(languages, "languages")
|
| 103 |
print(f" ✓ checkpoint after {note}: {len(keep)} models published, "
|
| 104 |
-
f"{len(log_df)} detailed rows "
|
| 105 |
-
f"({'HF' if ALLOW_HF_PUSH_RESULTS else 'local-only'})")
|
| 106 |
return agg
|
| 107 |
|
| 108 |
|
|
@@ -128,13 +164,39 @@ async def evaluate():
|
|
| 128 |
|
| 129 |
# Load cached results and filter out completed combinations
|
| 130 |
old_results = load("results-detailed")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 131 |
if not old_results.empty:
|
| 132 |
# Only treat status==\"ok\" (or missing status) as completed.
|
| 133 |
if "status" in old_results.columns:
|
| 134 |
ok_mask = old_results["status"].isna() | (old_results["status"] == "ok")
|
| 135 |
-
completed_df = old_results.loc[ok_mask,
|
| 136 |
else:
|
| 137 |
-
completed_df = old_results[
|
| 138 |
completed = set(completed_df.apply(tuple, axis=1))
|
| 139 |
combis = combis[~combis.apply(lambda row: tuple(row) in completed, axis=1)]
|
| 140 |
|
|
@@ -158,21 +220,62 @@ async def evaluate():
|
|
| 158 |
columns=["task", "model", "bcp_47", "metric", "sentence_nr", "score", "origin", "status"]
|
| 159 |
)
|
| 160 |
dedup_keys = ["task", "model", "bcp_47", "metric", "sentence_nr"]
|
| 161 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 162 |
|
| 163 |
-
#
|
| 164 |
-
# Models already fully cached have no pending combis
|
|
|
|
| 165 |
pending_models = [m for m in models.iloc[:n_models]["id"].tolist()
|
| 166 |
if (combis["model"] == m).any()]
|
| 167 |
|
| 168 |
-
# A model is COVERAGE-COMPLETE
|
| 169 |
-
#
|
| 170 |
-
#
|
| 171 |
-
#
|
| 172 |
-
#
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 176 |
def over_budget():
|
| 177 |
return max_runtime_seconds and (time.time() - start_time) > max_runtime_seconds
|
| 178 |
|
|
@@ -185,7 +288,7 @@ async def evaluate():
|
|
| 185 |
for mi, model_id in enumerate(pending_models, 1):
|
| 186 |
# Don't START a new model once over budget — stop cleanly between models.
|
| 187 |
if over_budget():
|
| 188 |
-
print(
|
| 189 |
f"{len(pending_models) - mi + 1} model(s) deferred to next run.")
|
| 190 |
break
|
| 191 |
model_combis = combis[combis["model"] == model_id]
|
|
@@ -193,35 +296,82 @@ async def evaluate():
|
|
| 193 |
model_out = []
|
| 194 |
model_started = time.time()
|
| 195 |
attempted = 0
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 225 |
# Flag the model as slow if it took disproportionately long per sample
|
| 226 |
# this run (rate-limited). Needs a meaningful sample count to be reliable.
|
| 227 |
sec_per_sample = (time.time() - model_started) / max(attempted, 1)
|
|
@@ -238,7 +388,7 @@ async def evaluate():
|
|
| 238 |
subset=dedup_keys, keep="last"
|
| 239 |
)
|
| 240 |
if budget_hit:
|
| 241 |
-
print(
|
| 242 |
f"progress, {len(pending_models) - mi} model(s) deferred to next run.")
|
| 243 |
results_agg = checkpoint(all_results, covered, current_languages, f"budget stop @ {model_id}")
|
| 244 |
break
|
|
@@ -263,9 +413,10 @@ async def evaluate():
|
|
| 263 |
# auto-blocklisted after staying broken across runs — not after a single run
|
| 264 |
# where a provider may have rate-limited us. Non-fatal if it fails.
|
| 265 |
try:
|
| 266 |
-
update_blocklist_strikes(all_results, slow_models=slow_models
|
|
|
|
| 267 |
except Exception as e:
|
| 268 |
-
print(
|
| 269 |
|
| 270 |
elapsed = time.time() - start_time
|
| 271 |
print(f"Evaluation completed in {str(timedelta(seconds=int(elapsed)))}")
|
|
|
|
| 38 |
# run resumes the rest (completed models are skipped). 0 = no limit (local runs).
|
| 39 |
max_runtime_seconds = int(environ.get("MAX_RUNTIME_SECONDS", 0))
|
| 40 |
|
| 41 |
+
# Optional cap on how many NOT-YET-COMPLETE models a single run may work on.
|
| 42 |
+
# The weekly CI run is meant for incremental additions ("one new model landed,
|
| 43 |
+
# evaluate it"), not for chewing through a large backlog: every checkpoint
|
| 44 |
+
# re-pushes the whole results-detailed log, `all_results` is held entirely in
|
| 45 |
+
# RAM on a 16GB runner, and a crash re-costs the in-flight model (CI has no
|
| 46 |
+
# sample-level joblib cache, that's local-disk only). Large backfills belong on
|
| 47 |
+
# a local machine, or in a `workflow_dispatch` run with the cap explicitly
|
| 48 |
+
# raised. 0 = unlimited (the default, so local runs are unaffected).
|
| 49 |
+
max_new_models_per_run = int(environ.get("MAX_NEW_MODELS_PER_RUN", 0))
|
| 50 |
+
|
| 51 |
+
# Skip ALL HuggingFace pushes and write snapshots to results/dry-run/ instead.
|
| 52 |
+
# For exercising this file end-to-end (e.g. verifying the crash-path checkpoint)
|
| 53 |
+
# without a multi-hundred-MB upload per attempt. The separate directory matters:
|
| 54 |
+
# results/{results,models,languages}.json are tracked in git, so writing a
|
| 55 |
+
# partial-scale aggregate over them would dirty committed files on every test.
|
| 56 |
+
# This also suppresses the results-detailed push, which the
|
| 57 |
+
# ALLOW_HF_PUSH_RESULTS guard below deliberately does not.
|
| 58 |
+
# NOT for real runs: those must push, that is both how results get published
|
| 59 |
+
# and how the next run resumes.
|
| 60 |
+
DRY_RUN = environ.get("DRY_RUN", "").lower() in ("1", "true", "yes")
|
| 61 |
+
|
| 62 |
# When n_languages or n_models is smaller than canonical, the filter in
|
| 63 |
# `results_agg` below would discard most rows and overwrite the public HF
|
| 64 |
# aggregate. Detect that and downgrade to local-only writes.
|
| 65 |
ALLOW_HF_PUSH_RESULTS = (
|
| 66 |
n_languages >= CANONICAL_N_LANGUAGES_FOR_PUSH
|
| 67 |
and n_models >= CANONICAL_N_MODELS_FOR_PUSH
|
| 68 |
+
and not DRY_RUN
|
| 69 |
)
|
| 70 |
|
| 71 |
def publishable_models(log_df, covered_models):
|
|
|
|
| 109 |
.agg({"score": "mean", "origin": "first"})
|
| 110 |
.reset_index()
|
| 111 |
)
|
| 112 |
+
def write(df, fname, allow_hf):
|
| 113 |
+
# DRY_RUN wins over everything and writes under results/dry-run/, because
|
| 114 |
+
# results/{results,models,languages}.json are TRACKED IN GIT, writing a
|
| 115 |
+
# partial-scale aggregate over them would dirty committed files on every
|
| 116 |
+
# test run.
|
| 117 |
+
if DRY_RUN:
|
| 118 |
+
save_local_only(df, f"dry-run/{fname}")
|
| 119 |
+
elif allow_hf:
|
| 120 |
+
save(df, fname)
|
| 121 |
+
else:
|
| 122 |
+
save_local_only(df, fname)
|
| 123 |
+
|
| 124 |
+
# results-detailed is append-merged (immutable log); safe at any scale, so
|
| 125 |
+
# it pushes even from a partial-scale run. DRY_RUN is the only thing that
|
| 126 |
+
# suppresses it, for local verification of this file.
|
| 127 |
+
write(log_df, "results-detailed", allow_hf=True)
|
| 128 |
# The aggregated tables are filtered by cohort_models × cohort_languages, so
|
| 129 |
# a partial-scale run would truncate the published view — push only from a
|
| 130 |
# full-scale run; otherwise local-only.
|
| 131 |
+
write(agg, "results", allow_hf=ALLOW_HF_PUSH_RESULTS)
|
| 132 |
+
write(models, "models", allow_hf=ALLOW_HF_PUSH_RESULTS)
|
| 133 |
+
write(languages, "languages", allow_hf=ALLOW_HF_PUSH_RESULTS)
|
| 134 |
+
if DRY_RUN:
|
| 135 |
+
destination = "DRY_RUN: results/dry-run/ only, nothing pushed"
|
| 136 |
+
elif ALLOW_HF_PUSH_RESULTS:
|
| 137 |
+
destination = "HF"
|
| 138 |
else:
|
| 139 |
+
destination = "results-detailed → HF, aggregates local-only"
|
|
|
|
|
|
|
| 140 |
print(f" ✓ checkpoint after {note}: {len(keep)} models published, "
|
| 141 |
+
f"{len(log_df)} detailed rows ({destination})")
|
|
|
|
| 142 |
return agg
|
| 143 |
|
| 144 |
|
|
|
|
| 164 |
|
| 165 |
# Load cached results and filter out completed combinations
|
| 166 |
old_results = load("results-detailed")
|
| 167 |
+
|
| 168 |
+
# COVERAGE-COMPLETENESS is about what has been ATTEMPTED (any status), not
|
| 169 |
+
# what succeeded, matching `covered.add(model_id)` below, which fires once a
|
| 170 |
+
# model's matrix has been attempted regardless of pass/fail. Computed here
|
| 171 |
+
# against the FULL matrix, before the pending filter strips rows.
|
| 172 |
+
#
|
| 173 |
+
# Why it can't just be "has no pending combis": a failed combo is retried
|
| 174 |
+
# every run (only status=="ok" counts as done), so a model with a handful of
|
| 175 |
+
# permanently-failing combos would never be coverage-complete and would be
|
| 176 |
+
# dropped from the published aggregate, which `checkpoint()` rebuilds from
|
| 177 |
+
# `covered` each time. Uncapped that never showed, because every model was
|
| 178 |
+
# attempted every run. With MAX_NEW_MODELS_PER_RUN it would silently
|
| 179 |
+
# un-publish every model the run didn't reach.
|
| 180 |
+
key_cols = ["task", "model", "bcp_47", "sentence_nr"]
|
| 181 |
+
if not old_results.empty:
|
| 182 |
+
seen = old_results[key_cols].drop_duplicates()
|
| 183 |
+
seen["_attempted"] = True
|
| 184 |
+
merged = combis.merge(seen, on=key_cols, how="left")
|
| 185 |
+
unattempted_per_model = merged[merged["_attempted"].isna()].groupby("model").size()
|
| 186 |
+
else:
|
| 187 |
+
# No prior log: NOTHING has been attempted, so every model is short its
|
| 188 |
+
# entire matrix. Must not be an empty Series, `.get(m, 0)` would then
|
| 189 |
+
# report 0 unattempted for every model and mark the whole cohort
|
| 190 |
+
# coverage-complete, publishing models with no data at all.
|
| 191 |
+
unattempted_per_model = combis.groupby("model").size()
|
| 192 |
+
|
| 193 |
if not old_results.empty:
|
| 194 |
# Only treat status==\"ok\" (or missing status) as completed.
|
| 195 |
if "status" in old_results.columns:
|
| 196 |
ok_mask = old_results["status"].isna() | (old_results["status"] == "ok")
|
| 197 |
+
completed_df = old_results.loc[ok_mask, key_cols]
|
| 198 |
else:
|
| 199 |
+
completed_df = old_results[key_cols]
|
| 200 |
completed = set(completed_df.apply(tuple, axis=1))
|
| 201 |
combis = combis[~combis.apply(lambda row: tuple(row) in completed, axis=1)]
|
| 202 |
|
|
|
|
| 220 |
columns=["task", "model", "bcp_47", "metric", "sentence_nr", "score", "origin", "status"]
|
| 221 |
)
|
| 222 |
dedup_keys = ["task", "model", "bcp_47", "metric", "sentence_nr"]
|
| 223 |
+
# Also the crash/budget salvage granularity: progress is preserved to the
|
| 224 |
+
# last COMPLETED batch boundary, so smaller batches lose less on an
|
| 225 |
+
# interruption (at the cost of more frequent Python-side bookkeeping).
|
| 226 |
+
# Overridable mainly so the salvage path can be exercised in a small
|
| 227 |
+
# local DRY_RUN without issuing 2000 real calls.
|
| 228 |
+
batch_size = int(environ.get("BATCH_SIZE", 2000))
|
| 229 |
|
| 230 |
+
# One entry per model with outstanding work, so each checkpoint boundary is a
|
| 231 |
+
# fully-computed model. Models already fully cached have no pending combis
|
| 232 |
+
# and are skipped. (Re-ordered just below, see the sort.)
|
| 233 |
pending_models = [m for m in models.iloc[:n_models]["id"].tolist()
|
| 234 |
if (combis["model"] == m).any()]
|
| 235 |
|
| 236 |
+
# A model is COVERAGE-COMPLETE once every combo in its matrix has been
|
| 237 |
+
# ATTEMPTED, in this run or any earlier one. Only these may be published,
|
| 238 |
+
# which is what stops a model with a handful of evaluated languages from
|
| 239 |
+
# showing an inflated mean and jumping the leaderboard. Models that failed
|
| 240 |
+
# some combos stay covered (and published); their retries are still queued in
|
| 241 |
+
# pending_models, so a model can legitimately be in BOTH sets.
|
| 242 |
+
covered = {m for m in current_models if int(unattempted_per_model.get(m, 0)) == 0}
|
| 243 |
+
print(f"{len(covered)} models coverage-complete (publishable); "
|
| 244 |
+
f"{len(pending_models)} with outstanding work this run")
|
| 245 |
+
|
| 246 |
+
# Ordering matters once MAX_NEW_MODELS_PER_RUN truncates this list.
|
| 247 |
+
# 1. Brand-new models (nothing in the log yet) go FIRST, onboarding them
|
| 248 |
+
# is the entire point of an incremental run.
|
| 249 |
+
# 2. Then partially-done models, closest-to-complete first, so a model left
|
| 250 |
+
# half-evaluated by a crash or budget stop is finished (and becomes
|
| 251 |
+
# publishable) before another is started.
|
| 252 |
+
# Sorting purely by pending-count would invert this: a new model has the
|
| 253 |
+
# WHOLE matrix pending, so it would sort last and be starved behind older
|
| 254 |
+
# models whose errored combos stay pending forever (only status=="ok"
|
| 255 |
+
# counts as done, so failures are re-attempted every run).
|
| 256 |
+
seen_models = set(old_results["model"].unique()) if not old_results.empty else set()
|
| 257 |
+
pending_counts = combis["model"].value_counts()
|
| 258 |
+
pending_models.sort(key=lambda m: (m in seen_models, pending_counts.get(m, 0)))
|
| 259 |
+
|
| 260 |
+
# Truncate to the cap. What keeps this safe is that `covered` is derived from
|
| 261 |
+
# `unattempted_per_model` (the full matrix vs the log) and NOT from
|
| 262 |
+
# `pending_models`, so deferring a model cannot reclassify it as
|
| 263 |
+
# coverage-complete. Keep it that way: the earlier
|
| 264 |
+
# `covered = current_models - set(pending_models)` would have published every
|
| 265 |
+
# deferred model on sparse or zero data, the inflation bug the coverage gate
|
| 266 |
+
# exists to prevent.
|
| 267 |
+
deferred_models = set()
|
| 268 |
+
if max_new_models_per_run and len(pending_models) > max_new_models_per_run:
|
| 269 |
+
deferred_models = set(pending_models[max_new_models_per_run:])
|
| 270 |
+
pending_models = pending_models[:max_new_models_per_run]
|
| 271 |
+
# NB: this module does `from rich import print`, which parses "[tag]" as
|
| 272 |
+
# markup and silently eats it. Escape as "\[" so the prefix survives;
|
| 273 |
+
# these are the lines you grep for in a CI log.
|
| 274 |
+
print(rf"\[cap] MAX_NEW_MODELS_PER_RUN={max_new_models_per_run}: running "
|
| 275 |
+
f"{len(pending_models)} model(s) this run, {len(deferred_models)} "
|
| 276 |
+
f"deferred to a later run. Raise the cap (or run locally) to "
|
| 277 |
+
f"clear a backlog faster.")
|
| 278 |
+
|
| 279 |
def over_budget():
|
| 280 |
return max_runtime_seconds and (time.time() - start_time) > max_runtime_seconds
|
| 281 |
|
|
|
|
| 288 |
for mi, model_id in enumerate(pending_models, 1):
|
| 289 |
# Don't START a new model once over budget — stop cleanly between models.
|
| 290 |
if over_budget():
|
| 291 |
+
print(rf"\[budget] {max_runtime_seconds}s reached before {model_id}; "
|
| 292 |
f"{len(pending_models) - mi + 1} model(s) deferred to next run.")
|
| 293 |
break
|
| 294 |
model_combis = combis[combis["model"] == model_id]
|
|
|
|
| 296 |
model_out = []
|
| 297 |
model_started = time.time()
|
| 298 |
attempted = 0
|
| 299 |
+
try:
|
| 300 |
+
for i in tqdm(range(0, len(model_combis), batch_size),
|
| 301 |
+
colour="blue", desc=model_id):
|
| 302 |
+
batch = model_combis.iloc[i:i + batch_size]
|
| 303 |
+
attempted += len(batch)
|
| 304 |
+
rows = [(t, m, b, s) for _, (t, m, b, s) in batch.iterrows()]
|
| 305 |
+
# A single combo that throws (e.g. a flaky HF dataset download) must
|
| 306 |
+
# NOT crash a multi-hour run. tqdm_asyncio.gather has no
|
| 307 |
+
# return_exceptions, so wrap each task: catch non-fatal errors and
|
| 308 |
+
# return them as a value; the combo is then skipped (stays pending,
|
| 309 |
+
# re-attempted next run) without counting toward the model's
|
| 310 |
+
# blocklist strikes. FatalAPIError (account-level) still propagates.
|
| 311 |
+
async def _safe(t, m, b, s):
|
| 312 |
+
try:
|
| 313 |
+
return await tasks[t](m, b, s)
|
| 314 |
+
except (FatalAPIError, KeyboardInterrupt, asyncio.CancelledError):
|
| 315 |
+
# Control-flow signals, not task failures. KeyboardInterrupt
|
| 316 |
+
# is raised inside whatever coroutine is running when the
|
| 317 |
+
# signal lands, so a plain BaseException catch swallows it
|
| 318 |
+
# and Ctrl-C just marks combos "skipped" while the run
|
| 319 |
+
# carries on. Re-raise so the run actually aborts and the
|
| 320 |
+
# salvage handler below can checkpoint completed batches.
|
| 321 |
+
raise
|
| 322 |
+
except BaseException as e: # noqa: BLE001 - intentional catch-all
|
| 323 |
+
return e
|
| 324 |
+
batch_res = await tqdm_asyncio.gather(*[_safe(t, m, b, s) for (t, m, b, s) in rows])
|
| 325 |
+
for (t, m, b, s), res in zip(rows, batch_res):
|
| 326 |
+
if isinstance(res, BaseException):
|
| 327 |
+
print(f" ! {t}/{m}/{b}#{s} skipped: {type(res).__name__}: {str(res)[:120]}")
|
| 328 |
+
else:
|
| 329 |
+
model_out.extend(res)
|
| 330 |
+
# Budget can be hit MID-model (a rate-limited model can take >>1h).
|
| 331 |
+
# Stop at this batch boundary so we never blow past the 6h hard cap.
|
| 332 |
+
if over_budget():
|
| 333 |
+
budget_hit = True
|
| 334 |
+
break
|
| 335 |
+
except BaseException as crash:
|
| 336 |
+
# Salvage work that has ALREADY BEEN PAID FOR before unwinding.
|
| 337 |
+
# `model_out` is only folded into `all_results` after this loop, so
|
| 338 |
+
# without this handler a FatalAPIError (exhausted key), an OOM, or a
|
| 339 |
+
# local Ctrl-C silently discards every COMPLETED BATCH for this
|
| 340 |
+
# model. That is exactly what cost the 2026-06-15 run ~4.5h of
|
| 341 |
+
# already-billed results.
|
| 342 |
+
#
|
| 343 |
+
# Granularity is the batch, not the sample: `model_out.extend()`
|
| 344 |
+
# only runs once a batch's gather() returns, so an interrupted batch
|
| 345 |
+
# contributes nothing. That's the right trade, the thing that kills
|
| 346 |
+
# a batch is FatalAPIError, which fails every in-flight call in it
|
| 347 |
+
# anyway, but it means a model is salvaged to the last completed
|
| 348 |
+
# batch boundary, not to the last completed sample.
|
| 349 |
+
#
|
| 350 |
+
# BaseException on purpose: also covers KeyboardInterrupt and
|
| 351 |
+
# asyncio.CancelledError. It does NOT cover SIGKILL/SIGTERM from the
|
| 352 |
+
# runner, MAX_RUNTIME_SECONDS is what keeps us clear of that.
|
| 353 |
+
#
|
| 354 |
+
# model_id is deliberately NOT added to `covered` here. A brand-new
|
| 355 |
+
# model therefore stays unpublished until some run attempts its full
|
| 356 |
+
# matrix, which is the sparse-coverage guard. A model already covered
|
| 357 |
+
# by earlier runs stays published, correctly: its aggregate is built
|
| 358 |
+
# from a complete attempt, and this run only added more ok rows.
|
| 359 |
+
#
|
| 360 |
+
# "\\[" so rich's markup parser doesn't eat the "[crash]" prefix.
|
| 361 |
+
print(f"\n\\[crash] {type(crash).__name__} during {model_id}; "
|
| 362 |
+
f"saving {len(model_out)} completed rows so the next run can "
|
| 363 |
+
f"resume (do not interrupt again)...")
|
| 364 |
+
try:
|
| 365 |
+
if model_out:
|
| 366 |
+
all_results = pd.concat(
|
| 367 |
+
[all_results, pd.DataFrame(model_out)]
|
| 368 |
+
).drop_duplicates(subset=dedup_keys, keep="last")
|
| 369 |
+
checkpoint(all_results, covered, current_languages,
|
| 370 |
+
f"crash during {model_id}")
|
| 371 |
+
except Exception as save_err:
|
| 372 |
+
# Never let a failing salvage mask the original failure.
|
| 373 |
+
print(rf"\[crash] could not save partial progress: {save_err}")
|
| 374 |
+
raise
|
| 375 |
# Flag the model as slow if it took disproportionately long per sample
|
| 376 |
# this run (rate-limited). Needs a meaningful sample count to be reliable.
|
| 377 |
sec_per_sample = (time.time() - model_started) / max(attempted, 1)
|
|
|
|
| 388 |
subset=dedup_keys, keep="last"
|
| 389 |
)
|
| 390 |
if budget_hit:
|
| 391 |
+
print(rf"\[budget] {max_runtime_seconds}s reached mid-{model_id}; saved partial "
|
| 392 |
f"progress, {len(pending_models) - mi} model(s) deferred to next run.")
|
| 393 |
results_agg = checkpoint(all_results, covered, current_languages, f"budget stop @ {model_id}")
|
| 394 |
break
|
|
|
|
| 413 |
# auto-blocklisted after staying broken across runs — not after a single run
|
| 414 |
# where a provider may have rate-limited us. Non-fatal if it fails.
|
| 415 |
try:
|
| 416 |
+
update_blocklist_strikes(all_results, slow_models=slow_models,
|
| 417 |
+
not_attempted=deferred_models, dry_run=DRY_RUN)
|
| 418 |
except Exception as e:
|
| 419 |
+
print(rf"\[main] could not update blocklist strikes: {e}")
|
| 420 |
|
| 421 |
elapsed = time.time() - start_time
|
| 422 |
print(f"Evaluation completed in {str(timedelta(seconds=int(elapsed)))}")
|
evals/models.py
CHANGED
|
@@ -10,7 +10,12 @@ from dotenv import load_dotenv
|
|
| 10 |
from google.cloud import translate_v2 as translate
|
| 11 |
from huggingface_hub import AsyncInferenceClient, HfApi
|
| 12 |
from joblib.memory import Memory
|
| 13 |
-
from openai import
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
from requests import HTTPError, get
|
| 15 |
|
| 16 |
# for development purposes, all languages will be evaluated on the fast models
|
|
@@ -422,6 +427,12 @@ class FatalAPIError(RuntimeError):
|
|
| 422 |
"""
|
| 423 |
|
| 424 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 425 |
_FATAL_ERROR_MARKERS = (
|
| 426 |
"key limit exceeded",
|
| 427 |
"insufficient credits",
|
|
@@ -449,6 +460,18 @@ async def complete(**kwargs) -> str | None:
|
|
| 449 |
if "filtered" in e.message:
|
| 450 |
return None
|
| 451 |
raise e
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 452 |
except Exception as e:
|
| 453 |
msg = str(e).lower()
|
| 454 |
if any(marker in msg for marker in _FATAL_ERROR_MARKERS):
|
|
@@ -645,7 +668,8 @@ def load_auto_blocklist(date: date) -> list[str]:
|
|
| 645 |
)
|
| 646 |
|
| 647 |
|
| 648 |
-
def update_blocklist_strikes(detailed=None, slow_models=None
|
|
|
|
| 649 |
"""Recompute consecutive-bad-run strikes and persist them to HF. Called once
|
| 650 |
per eval run (from main.py) after results are merged. A model currently past
|
| 651 |
the failure threshold gets +1 strike; a model that has recovered (or never
|
|
@@ -655,10 +679,18 @@ def update_blocklist_strikes(detailed=None, slow_models=None) -> pd.DataFrame:
|
|
| 655 |
The 2-run grace (one free re-attempt) only applies when retrying is cheap.
|
| 656 |
A failing model that is ALSO egregiously bad (>=80%) or SLOW (in
|
| 657 |
`slow_models`, measured this run) is excluded after a single run — we don't
|
| 658 |
-
spend more time/money re-attempting an expensive failure.
|
| 659 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 660 |
|
| 661 |
slow_models = slow_models or set()
|
|
|
|
| 662 |
health = compute_model_health(detailed)
|
| 663 |
cols = ["model", "strikes", "failed_pct"]
|
| 664 |
if health.empty:
|
|
@@ -679,6 +711,10 @@ def update_blocklist_strikes(detailed=None, slow_models=None) -> pd.DataFrame:
|
|
| 679 |
fail_map = dict(zip(bad["model"], bad["failed_pct"]))
|
| 680 |
|
| 681 |
def _strikes_for(model, fail_pct):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 682 |
# No grace if the failure is egregious OR slow-and-expensive-to-retry;
|
| 683 |
# otherwise increment so a fast, moderately-failing model gets one free
|
| 684 |
# re-attempt before exclusion.
|
|
@@ -699,7 +735,10 @@ def update_blocklist_strikes(detailed=None, slow_models=None) -> pd.DataFrame:
|
|
| 699 |
],
|
| 700 |
columns=cols,
|
| 701 |
)
|
| 702 |
-
|
|
|
|
|
|
|
|
|
|
| 703 |
blocked = sorted(
|
| 704 |
strikes_df[strikes_df["strikes"] >= AUTO_BLOCKLIST_MIN_RUNS]["model"].tolist()
|
| 705 |
)
|
|
|
|
| 10 |
from google.cloud import translate_v2 as translate
|
| 11 |
from huggingface_hub import AsyncInferenceClient, HfApi
|
| 12 |
from joblib.memory import Memory
|
| 13 |
+
from openai import (
|
| 14 |
+
AsyncOpenAI,
|
| 15 |
+
AuthenticationError,
|
| 16 |
+
BadRequestError,
|
| 17 |
+
PermissionDeniedError,
|
| 18 |
+
)
|
| 19 |
from requests import HTTPError, get
|
| 20 |
|
| 21 |
# for development purposes, all languages will be evaluated on the fast models
|
|
|
|
| 427 |
"""
|
| 428 |
|
| 429 |
|
| 430 |
+
# Account-level by TYPE, regardless of message: 401 (bad/revoked/mistyped key)
|
| 431 |
+
# and 403 (key lacks permission, or spend policy denies the request). Note
|
| 432 |
+
# RateLimitError (429) is deliberately absent, that one is transient and
|
| 433 |
+
# per-request, not account-level.
|
| 434 |
+
_FATAL_ERROR_TYPES = (AuthenticationError, PermissionDeniedError)
|
| 435 |
+
|
| 436 |
_FATAL_ERROR_MARKERS = (
|
| 437 |
"key limit exceeded",
|
| 438 |
"insufficient credits",
|
|
|
|
| 460 |
if "filtered" in e.message:
|
| 461 |
return None
|
| 462 |
raise e
|
| 463 |
+
except _FATAL_ERROR_TYPES as e:
|
| 464 |
+
# Credential/permission failures are account-level by definition and
|
| 465 |
+
# apply to every subsequent call. Matched BY TYPE because the string
|
| 466 |
+
# markers below do not catch them: a revoked or mistyped key returns
|
| 467 |
+
# 401 "User not found.", which contains none of the markers, so the
|
| 468 |
+
# run would otherwise grind through the whole matrix logging every
|
| 469 |
+
# combo as an error, flooding results-detailed and poisoning the
|
| 470 |
+
# auto-blocklist, which is exactly what this guard exists to stop.
|
| 471 |
+
raise FatalAPIError(
|
| 472 |
+
f"OpenRouter account-level failure ({type(e).__name__}): {e}. "
|
| 473 |
+
"Aborting run before results-detailed is polluted."
|
| 474 |
+
) from e
|
| 475 |
except Exception as e:
|
| 476 |
msg = str(e).lower()
|
| 477 |
if any(marker in msg for marker in _FATAL_ERROR_MARKERS):
|
|
|
|
| 668 |
)
|
| 669 |
|
| 670 |
|
| 671 |
+
def update_blocklist_strikes(detailed=None, slow_models=None,
|
| 672 |
+
not_attempted=None, dry_run=False) -> pd.DataFrame:
|
| 673 |
"""Recompute consecutive-bad-run strikes and persist them to HF. Called once
|
| 674 |
per eval run (from main.py) after results are merged. A model currently past
|
| 675 |
the failure threshold gets +1 strike; a model that has recovered (or never
|
|
|
|
| 679 |
The 2-run grace (one free re-attempt) only applies when retrying is cheap.
|
| 680 |
A failing model that is ALSO egregiously bad (>=80%) or SLOW (in
|
| 681 |
`slow_models`, measured this run) is excluded after a single run — we don't
|
| 682 |
+
spend more time/money re-attempting an expensive failure.
|
| 683 |
+
|
| 684 |
+
`not_attempted` are models this run never got to, deferred by
|
| 685 |
+
MAX_NEW_MODELS_PER_RUN. Strikes are computed from the CUMULATIVE log, so
|
| 686 |
+
without this they would keep accruing +1 per run on a stale record and be
|
| 687 |
+
auto-blocklisted after AUTO_BLOCKLIST_MIN_RUNS runs without ever getting the
|
| 688 |
+
re-attempt the grace period is supposed to buy them. Their prior count is
|
| 689 |
+
held steady instead."""
|
| 690 |
+
from datasets_.util import load, save, save_local_only
|
| 691 |
|
| 692 |
slow_models = slow_models or set()
|
| 693 |
+
not_attempted = not_attempted or set()
|
| 694 |
health = compute_model_health(detailed)
|
| 695 |
cols = ["model", "strikes", "failed_pct"]
|
| 696 |
if health.empty:
|
|
|
|
| 711 |
fail_map = dict(zip(bad["model"], bad["failed_pct"]))
|
| 712 |
|
| 713 |
def _strikes_for(model, fail_pct):
|
| 714 |
+
# Deferred by the per-run cap, it never ran, so it can't have earned a
|
| 715 |
+
# strike. Hold the prior count so the record persists without advancing.
|
| 716 |
+
if model in not_attempted:
|
| 717 |
+
return int(prior_map.get(model, 0))
|
| 718 |
# No grace if the failure is egregious OR slow-and-expensive-to-retry;
|
| 719 |
# otherwise increment so a fast, moderately-failing model gets one free
|
| 720 |
# re-attempt before exclusion.
|
|
|
|
| 735 |
],
|
| 736 |
columns=cols,
|
| 737 |
)
|
| 738 |
+
if dry_run:
|
| 739 |
+
save_local_only(strikes_df, "dry-run/model-health-strikes")
|
| 740 |
+
else:
|
| 741 |
+
save(strikes_df, "model-health-strikes")
|
| 742 |
blocked = sorted(
|
| 743 |
strikes_df[strikes_df["strikes"] >= AUTO_BLOCKLIST_MIN_RUNS]["model"].tolist()
|
| 744 |
)
|