Spaces:
Running
Running
Upload from GitHub Actions: Merge pull request #32 from datenlabor-bmz/eval-crash-safe-incremental-runs
Browse filesFiles changed (5)
3 unmodified lines45678994 unmodified lines1041051061071081091103 unmodified linesschedule:- cron: '0 3 * * 1' # Weekly: Mondays 3am UTCworkflow_dispatch: # Allow manual triggeringjobs:run-evals:94 unmodified lines# Per-model checkpointing makes this safe: completed models are# published and skipped next run; a partial model resumes.MAX_RUNTIME_SECONDS: 18000run: |# `huggingface-cli login` only warms a credential cache; all dataset# load/save calls in the code pass token=HUGGINGFACE_ACCESS_TOKEN# explicitly, so this is non-essential. HF's whoami endpoint3 unmodified lines456789101112131494 unmodified lines1091101111121131141151161171181191201211221231241251261271281291301311323 unmodified linesschedule:- cron: '0 3 * * 1' # Weekly: Mondays 3am UTCworkflow_dispatch: # Allow manual triggeringinputs:max_new_models:description: 'Max not-yet-complete models to work on this run (0 = unlimited). Scheduled runs use 2.'required: falsedefault: '2'jobs:run-evals:94 unmodified lines# Per-model checkpointing makes this safe: completed models are# published and skipped next run; a partial model resumes.MAX_RUNTIME_SECONDS: 18000# This workflow is for INCREMENTAL additions, "a new model landed,# evaluate it", not for clearing a backlog. Onboarding many models in# one CI run is the expensive/fragile path: every per-model checkpoint# re-pushes the whole results-detailed log, `all_results` is held# entirely in RAM on a 16GB runner, and a crash re-costs the in-flight# model because CI has no sample-level joblib cache (that lives on# local disk, and is deliberately NOT restored here).# Backlogs belong on a local machine, or on a deliberate# workflow_dispatch run with this input set to 0 (unlimited).# Empty for `schedule` (no inputs context); the default is applied in# the shell below, NOT with `${{ ... || '2' }}`. GitHub's expression# truthiness can cast the string '0' to falsy, which would silently# turn the "0 = unlimited" escape hatch back into 2.MAX_NEW_MODELS_PER_RUN: ${{ github.event.inputs.max_new_models }}run: |# Default only when genuinely unset/empty (i.e. a scheduled run).export MAX_NEW_MODELS_PER_RUN="${MAX_NEW_MODELS_PER_RUN:-2}"echo "MAX_NEW_MODELS_PER_RUN=$MAX_NEW_MODELS_PER_RUN"# `huggingface-cli login` only warms a credential cache; all dataset# load/save calls in the code pass token=HUGGINGFACE_ACCESS_TOKEN# explicitly, so this is non-essential. HF's whoami endpoint
3 unmodified lines4567893 unmodified linesresults/results-detailed.jsonresults/*.csvresults/*.logdata/translations/floresp-*fleurs3 unmodified lines45678910113 unmodified linesresults/results-detailed.jsonresults/*.csvresults/*.log# DRY_RUN=1 output, partial-scale test snapshots, never publishedresults/dry-run/data/translations/floresp-*fleurs
108 unmodified lines109110111112113114115116117118108 unmodified linesUsed during partial-scale eval runs (smoke tests, local development) sothe public dataset isn't truncated by a filtered aggregate. The nextfull-scale run will push the canonical version."""df = df.drop(columns=["__index_level_0__"], errors="ignore")Path("results").mkdir(exist_ok=True)df.to_json(f"results/{fname}.json", orient="records", force_ascii=False, indent=2)def get_valid_task_languages(task_name: str) -> set:108 unmodified lines109110111112113114115116117118119120121122108 unmodified linesUsed during partial-scale eval runs (smoke tests, local development) sothe public dataset isn't truncated by a filtered aggregate. The nextfull-scale run will push the canonical version.`fname` may contain a subdirectory (e.g. "dry-run/results"), which DRY_RUNuses to keep test output away from the tracked results/*.json files."""df = df.drop(columns=["__index_level_0__"], errors="ignore")out = Path("results") / f"{fname}.json"out.parent.mkdir(parents=True, exist_ok=True)df.to_json(out, orient="records", force_ascii=False, indent=2)def get_valid_task_languages(task_name: str) -> set:
37 unmodified lines38394041424344454647484937 unmodified lines8788899091929394959697989910010110210310410510610710819 unmodified lines12812913013113213313413513613713813914017 unmodified lines1581591601611621631641651661671681691701711721731741751761771786 unmodified lines1851861871881891901911 unmodified line19319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622710 unmodified lines23823924024124224324418 unmodified lines26326426526626726826927027137 unmodified lines# run resumes the rest (completed models are skipped). 0 = no limit (local runs).max_runtime_seconds = int(environ.get("MAX_RUNTIME_SECONDS", 0))# When n_languages or n_models is smaller than canonical, the filter in# `results_agg` below would discard most rows and overwrite the public HF# aggregate. Detect that and downgrade to local-only writes.ALLOW_HF_PUSH_RESULTS = (n_languages >= CANONICAL_N_LANGUAGES_FOR_PUSHand n_models >= CANONICAL_N_MODELS_FOR_PUSH)def publishable_models(log_df, covered_models):37 unmodified lines.agg({"score": "mean", "origin": "first"}).reset_index())# results-detailed is append-merged (immutable log); safe at any scale.save(log_df, "results-detailed")# The aggregated tables are filtered by cohort_models × cohort_languages, so# a partial-scale run would truncate the published view — push only from a# full-scale run; otherwise local-only.if ALLOW_HF_PUSH_RESULTS:save(agg, "results")save(models, "models")save(languages, "languages")else:save_local_only(agg, "results")save_local_only(models, "models")save_local_only(languages, "languages")print(f" ✓ checkpoint after {note}: {len(keep)} models published, "f"{len(log_df)} detailed rows "f"({'HF' if ALLOW_HF_PUSH_RESULTS else 'local-only'})")return agg19 unmodified lines# Load cached results and filter out completed combinationsold_results = load("results-detailed")if not old_results.empty:# Only treat status==\"ok\" (or missing status) as completed.if "status" in old_results.columns:ok_mask = old_results["status"].isna() | (old_results["status"] == "ok")completed_df = old_results.loc[ok_mask, ["task", "model", "bcp_47", "sentence_nr"]]else:completed_df = old_results[["task", "model", "bcp_47", "sentence_nr"]]completed = set(completed_df.apply(tuple, axis=1))combis = combis[~combis.apply(lambda row: tuple(row) in completed, axis=1)]17 unmodified linescolumns=["task", "model", "bcp_47", "metric", "sentence_nr", "score", "origin", "status"])dedup_keys = ["task", "model", "bcp_47", "metric", "sentence_nr"]batch_size = 2000# Cohort order, so each checkpoint boundary is a fully-computed model.# Models already fully cached have no pending combis and are skipped.pending_models = [m for m in models.iloc[:n_models]["id"].tolist()if (combis["model"] == m).any()]# A model is COVERAGE-COMPLETE iff it has zero pending combis: either it was# already fully evaluated before this run (not in pending_models), or this# run finishes its full matrix below. Only coverage-complete models may be# published — this is what stops a model with a handful of evaluated# languages from showing an inflated mean and jumping the leaderboard.covered = current_models - set(pending_models)print(f"{len(covered)} models already fully covered; "f"{len(pending_models)} pending this run")def over_budget():return max_runtime_seconds and (time.time() - start_time) > max_runtime_seconds6 unmodified linesfor mi, model_id in enumerate(pending_models, 1):# Don't START a new model once over budget — stop cleanly between models.if over_budget():print(f"[budget] {max_runtime_seconds}s reached before {model_id}; "f"{len(pending_models) - mi + 1} model(s) deferred to next run.")breakmodel_combis = combis[combis["model"] == model_id]1 unmodified linemodel_out = []model_started = time.time()attempted = 0for i in tqdm(range(0, len(model_combis), batch_size),colour="blue", desc=model_id):batch = model_combis.iloc[i:i + batch_size]attempted += len(batch)rows = [(t, m, b, s) for _, (t, m, b, s) in batch.iterrows()]# A single combo that throws (e.g. a flaky HF dataset download) must# NOT crash a multi-hour run. tqdm_asyncio.gather has no# return_exceptions, so wrap each task: catch non-fatal errors and# return them as a value; the combo is then skipped (stays pending,# re-attempted next run) without counting toward the model's# blocklist strikes. FatalAPIError (account-level) still propagates.async def _safe(t, m, b, s):try:return await tasks[t](m, b, s)except FatalAPIError:raiseexcept BaseException as e: # noqa: BLE001 - intentional catch-allreturn ebatch_res = await tqdm_asyncio.gather(*[_safe(t, m, b, s) for (t, m, b, s) in rows])for (t, m, b, s), res in zip(rows, batch_res):if isinstance(res, BaseException):print(f" ! {t}/{m}/{b}#{s} skipped: {type(res).__name__}: {str(res)[:120]}")else:model_out.extend(res)# Budget can be hit MID-model (a rate-limited model can take >>1h).# Stop at this batch boundary so we never blow past the 6h hard cap.if over_budget():budget_hit = Truebreak# Flag the model as slow if it took disproportionately long per sample# this run (rate-limited). Needs a meaningful sample count to be reliable.sec_per_sample = (time.time() - model_started) / max(attempted, 1)10 unmodified linessubset=dedup_keys, keep="last")if budget_hit:print(f"[budget] {max_runtime_seconds}s reached mid-{model_id}; saved partial "f"progress, {len(pending_models) - mi} model(s) deferred to next run.")results_agg = checkpoint(all_results, covered, current_languages, f"budget stop @ {model_id}")break18 unmodified lines# auto-blocklisted after staying broken across runs — not after a single run# where a provider may have rate-limited us. Non-fatal if it fails.try:update_blocklist_strikes(all_results, slow_models=slow_models)except Exception as e:print(f"[main] could not update blocklist strikes: {e}")elapsed = time.time() - start_timeprint(f"Evaluation completed in {str(timedelta(seconds=int(elapsed)))}")37 unmodified lines3839404142434445464748495051525354555657585960616263646566676869707137 unmodified lines10911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314419 unmodified lines16416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120217 unmodified lines2202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802816 unmodified lines2882892902912922932941 unmodified line29629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637710 unmodified lines38838939039139239339418 unmodified lines41341441541641741841942042142237 unmodified lines# run resumes the rest (completed models are skipped). 0 = no limit (local runs).max_runtime_seconds = int(environ.get("MAX_RUNTIME_SECONDS", 0))# Optional cap on how many NOT-YET-COMPLETE models a single run may work on.# The weekly CI run is meant for incremental additions ("one new model landed,# evaluate it"), not for chewing through a large backlog: every checkpoint# re-pushes the whole results-detailed log, `all_results` is held entirely in# RAM on a 16GB runner, and a crash re-costs the in-flight model (CI has no# sample-level joblib cache, that's local-disk only). Large backfills belong on# a local machine, or in a `workflow_dispatch` run with the cap explicitly# raised. 0 = unlimited (the default, so local runs are unaffected).max_new_models_per_run = int(environ.get("MAX_NEW_MODELS_PER_RUN", 0))# Skip ALL HuggingFace pushes and write snapshots to results/dry-run/ instead.# For exercising this file end-to-end (e.g. verifying the crash-path checkpoint)# without a multi-hundred-MB upload per attempt. The separate directory matters:# results/{results,models,languages}.json are tracked in git, so writing a# partial-scale aggregate over them would dirty committed files on every test.# This also suppresses the results-detailed push, which the# ALLOW_HF_PUSH_RESULTS guard below deliberately does not.# NOT for real runs: those must push, that is both how results get published# and how the next run resumes.DRY_RUN = environ.get("DRY_RUN", "").lower() in ("1", "true", "yes")# When n_languages or n_models is smaller than canonical, the filter in# `results_agg` below would discard most rows and overwrite the public HF# aggregate. Detect that and downgrade to local-only writes.ALLOW_HF_PUSH_RESULTS = (n_languages >= CANONICAL_N_LANGUAGES_FOR_PUSHand n_models >= CANONICAL_N_MODELS_FOR_PUSHand not DRY_RUN)def publishable_models(log_df, covered_models):37 unmodified lines.agg({"score": "mean", "origin": "first"}).reset_index())def write(df, fname, allow_hf):# DRY_RUN wins over everything and writes under results/dry-run/, because# results/{results,models,languages}.json are TRACKED IN GIT, writing a# partial-scale aggregate over them would dirty committed files on every# test run.if DRY_RUN:save_local_only(df, f"dry-run/{fname}")elif allow_hf:save(df, fname)else:save_local_only(df, fname)# results-detailed is append-merged (immutable log); safe at any scale, so# it pushes even from a partial-scale run. DRY_RUN is the only thing that# suppresses it, for local verification of this file.write(log_df, "results-detailed", allow_hf=True)# The aggregated tables are filtered by cohort_models × cohort_languages, so# a partial-scale run would truncate the published view — push only from a# full-scale run; otherwise local-only.write(agg, "results", allow_hf=ALLOW_HF_PUSH_RESULTS)write(models, "models", allow_hf=ALLOW_HF_PUSH_RESULTS)write(languages, "languages", allow_hf=ALLOW_HF_PUSH_RESULTS)if DRY_RUN:destination = "DRY_RUN: results/dry-run/ only, nothing pushed"elif ALLOW_HF_PUSH_RESULTS:destination = "HF"else:destination = "results-detailed → HF, aggregates local-only"print(f" ✓ checkpoint after {note}: {len(keep)} models published, "f"{len(log_df)} detailed rows ({destination})")return agg19 unmodified lines# Load cached results and filter out completed combinationsold_results = load("results-detailed")# COVERAGE-COMPLETENESS is about what has been ATTEMPTED (any status), not# what succeeded, matching `covered.add(model_id)` below, which fires once a# model's matrix has been attempted regardless of pass/fail. Computed here# against the FULL matrix, before the pending filter strips rows.## Why it can't just be "has no pending combis": a failed combo is retried# every run (only status=="ok" counts as done), so a model with a handful of# permanently-failing combos would never be coverage-complete and would be# dropped from the published aggregate, which `checkpoint()` rebuilds from# `covered` each time. Uncapped that never showed, because every model was# attempted every run. With MAX_NEW_MODELS_PER_RUN it would silently# un-publish every model the run didn't reach.key_cols = ["task", "model", "bcp_47", "sentence_nr"]if not old_results.empty:seen = old_results[key_cols].drop_duplicates()seen["_attempted"] = Truemerged = combis.merge(seen, on=key_cols, how="left")unattempted_per_model = merged[merged["_attempted"].isna()].groupby("model").size()else:# No prior log: NOTHING has been attempted, so every model is short its# entire matrix. Must not be an empty Series, `.get(m, 0)` would then# report 0 unattempted for every model and mark the whole cohort# coverage-complete, publishing models with no data at all.unattempted_per_model = combis.groupby("model").size()if not old_results.empty:# Only treat status==\"ok\" (or missing status) as completed.if "status" in old_results.columns:ok_mask = old_results["status"].isna() | (old_results["status"] == "ok")completed_df = old_results.loc[ok_mask, key_cols]else:completed_df = old_results[key_cols]completed = set(completed_df.apply(tuple, axis=1))combis = combis[~combis.apply(lambda row: tuple(row) in completed, axis=1)]17 unmodified linescolumns=["task", "model", "bcp_47", "metric", "sentence_nr", "score", "origin", "status"])dedup_keys = ["task", "model", "bcp_47", "metric", "sentence_nr"]# Also the crash/budget salvage granularity: progress is preserved to the# last COMPLETED batch boundary, so smaller batches lose less on an# interruption (at the cost of more frequent Python-side bookkeeping).# Overridable mainly so the salvage path can be exercised in a small# local DRY_RUN without issuing 2000 real calls.batch_size = int(environ.get("BATCH_SIZE", 2000))# One entry per model with outstanding work, so each checkpoint boundary is a# fully-computed model. Models already fully cached have no pending combis# and are skipped. (Re-ordered just below, see the sort.)pending_models = [m for m in models.iloc[:n_models]["id"].tolist()if (combis["model"] == m).any()]# A model is COVERAGE-COMPLETE once every combo in its matrix has been# ATTEMPTED, in this run or any earlier one. Only these may be published,# which is what stops a model with a handful of evaluated languages from# showing an inflated mean and jumping the leaderboard. Models that failed# some combos stay covered (and published); their retries are still queued in# pending_models, so a model can legitimately be in BOTH sets.covered = {m for m in current_models if int(unattempted_per_model.get(m, 0)) == 0}print(f"{len(covered)} models coverage-complete (publishable); "f"{len(pending_models)} with outstanding work this run")# Ordering matters once MAX_NEW_MODELS_PER_RUN truncates this list.# 1. Brand-new models (nothing in the log yet) go FIRST, onboarding them# is the entire point of an incremental run.# 2. Then partially-done models, closest-to-complete first, so a model left# half-evaluated by a crash or budget stop is finished (and becomes# publishable) before another is started.# Sorting purely by pending-count would invert this: a new model has the# WHOLE matrix pending, so it would sort last and be starved behind older# models whose errored combos stay pending forever (only status=="ok"# counts as done, so failures are re-attempted every run).seen_models = set(old_results["model"].unique()) if not old_results.empty else set()pending_counts = combis["model"].value_counts()pending_models.sort(key=lambda m: (m in seen_models, pending_counts.get(m, 0)))# Truncate to the cap. What keeps this safe is that `covered` is derived from# `unattempted_per_model` (the full matrix vs the log) and NOT from# `pending_models`, so deferring a model cannot reclassify it as# coverage-complete. Keep it that way: the earlier# `covered = current_models - set(pending_models)` would have published every# deferred model on sparse or zero data, the inflation bug the coverage gate# exists to prevent.deferred_models = set()if max_new_models_per_run and len(pending_models) > max_new_models_per_run:deferred_models = set(pending_models[max_new_models_per_run:])pending_models = pending_models[:max_new_models_per_run]# NB: this module does `from rich import print`, which parses "[tag]" as# markup and silently eats it. Escape as "\[" so the prefix survives;# these are the lines you grep for in a CI log.print(rf"\[cap] MAX_NEW_MODELS_PER_RUN={max_new_models_per_run}: running "f"{len(pending_models)} model(s) this run, {len(deferred_models)} "f"deferred to a later run. Raise the cap (or run locally) to "f"clear a backlog faster.")def over_budget():return max_runtime_seconds and (time.time() - start_time) > max_runtime_seconds6 unmodified linesfor mi, model_id in enumerate(pending_models, 1):# Don't START a new model once over budget — stop cleanly between models.if over_budget():print(rf"\[budget] {max_runtime_seconds}s reached before {model_id}; "f"{len(pending_models) - mi + 1} model(s) deferred to next run.")breakmodel_combis = combis[combis["model"] == model_id]1 unmodified linemodel_out = []model_started = time.time()attempted = 0try:for i in tqdm(range(0, len(model_combis), batch_size),colour="blue", desc=model_id):batch = model_combis.iloc[i:i + batch_size]attempted += len(batch)rows = [(t, m, b, s) for _, (t, m, b, s) in batch.iterrows()]# A single combo that throws (e.g. a flaky HF dataset download) must# NOT crash a multi-hour run. tqdm_asyncio.gather has no# return_exceptions, so wrap each task: catch non-fatal errors and# return them as a value; the combo is then skipped (stays pending,# re-attempted next run) without counting toward the model's# blocklist strikes. FatalAPIError (account-level) still propagates.async def _safe(t, m, b, s):try:return await tasks[t](m, b, s)except (FatalAPIError, KeyboardInterrupt, asyncio.CancelledError):# Control-flow signals, not task failures. KeyboardInterrupt# is raised inside whatever coroutine is running when the# signal lands, so a plain BaseException catch swallows it# and Ctrl-C just marks combos "skipped" while the run# carries on. Re-raise so the run actually aborts and the# salvage handler below can checkpoint completed batches.raiseexcept BaseException as e: # noqa: BLE001 - intentional catch-allreturn ebatch_res = await tqdm_asyncio.gather(*[_safe(t, m, b, s) for (t, m, b, s) in rows])for (t, m, b, s), res in zip(rows, batch_res):if isinstance(res, BaseException):print(f" ! {t}/{m}/{b}#{s} skipped: {type(res).__name__}: {str(res)[:120]}")else:model_out.extend(res)# Budget can be hit MID-model (a rate-limited model can take >>1h).# Stop at this batch boundary so we never blow past the 6h hard cap.if over_budget():budget_hit = Truebreakexcept BaseException as crash:# Salvage work that has ALREADY BEEN PAID FOR before unwinding.# `model_out` is only folded into `all_results` after this loop, so# without this handler a FatalAPIError (exhausted key), an OOM, or a# local Ctrl-C silently discards every COMPLETED BATCH for this# model. That is exactly what cost the 2026-06-15 run ~4.5h of# already-billed results.## Granularity is the batch, not the sample: `model_out.extend()`# only runs once a batch's gather() returns, so an interrupted batch# contributes nothing. That's the right trade, the thing that kills# a batch is FatalAPIError, which fails every in-flight call in it# anyway, but it means a model is salvaged to the last completed# batch boundary, not to the last completed sample.## BaseException on purpose: also covers KeyboardInterrupt and# asyncio.CancelledError. It does NOT cover SIGKILL/SIGTERM from the# runner, MAX_RUNTIME_SECONDS is what keeps us clear of that.## model_id is deliberately NOT added to `covered` here. A brand-new# model therefore stays unpublished until some run attempts its full# matrix, which is the sparse-coverage guard. A model already covered# by earlier runs stays published, correctly: its aggregate is built# from a complete attempt, and this run only added more ok rows.## "\\[" so rich's markup parser doesn't eat the "[crash]" prefix.print(f"\n\\[crash] {type(crash).__name__} during {model_id}; "f"saving {len(model_out)} completed rows so the next run can "f"resume (do not interrupt again)...")try:if model_out:all_results = pd.concat([all_results, pd.DataFrame(model_out)]).drop_duplicates(subset=dedup_keys, keep="last")checkpoint(all_results, covered, current_languages,f"crash during {model_id}")except Exception as save_err:# Never let a failing salvage mask the original failure.print(rf"\[crash] could not save partial progress: {save_err}")raise# Flag the model as slow if it took disproportionately long per sample# this run (rate-limited). Needs a meaningful sample count to be reliable.sec_per_sample = (time.time() - model_started) / max(attempted, 1)10 unmodified linessubset=dedup_keys, keep="last")if budget_hit:print(rf"\[budget] {max_runtime_seconds}s reached mid-{model_id}; saved partial "f"progress, {len(pending_models) - mi} model(s) deferred to next run.")results_agg = checkpoint(all_results, covered, current_languages, f"budget stop @ {model_id}")break18 unmodified lines# auto-blocklisted after staying broken across runs — not after a single run# where a provider may have rate-limited us. Non-fatal if it fails.try:update_blocklist_strikes(all_results, slow_models=slow_models,not_attempted=deferred_models, dry_run=DRY_RUN)except Exception as e:print(rf"\[main] could not update blocklist strikes: {e}")elapsed = time.time() - start_timeprint(f"Evaluation completed in {str(timedelta(seconds=int(elapsed)))}")
9 unmodified lines10111213141516405 unmodified lines42242342442542642721 unmodified lines449450451452453454190 unmodified lines6456466476486496506513 unmodified lines65565665765865966066166266366414 unmodified lines67968068168268368414 unmodified lines6997007017027037047059 unmodified linesfrom google.cloud import translate_v2 as translatefrom huggingface_hub import AsyncInferenceClient, HfApifrom joblib.memory import Memoryfrom openai import AsyncOpenAI, BadRequestErrorfrom requests import HTTPError, get# for development purposes, all languages will be evaluated on the fast models405 unmodified lines"""_FATAL_ERROR_MARKERS = ("key limit exceeded","insufficient credits",21 unmodified linesif "filtered" in e.message:return Noneraise eexcept Exception as e:msg = str(e).lower()if any(marker in msg for marker in _FATAL_ERROR_MARKERS):190 unmodified lines)def update_blocklist_strikes(detailed=None, slow_models=None) -> pd.DataFrame:"""Recompute consecutive-bad-run strikes and persist them to HF. Called onceper eval run (from main.py) after results are merged. A model currently pastthe failure threshold gets +1 strike; a model that has recovered (or never3 unmodified linesThe 2-run grace (one free re-attempt) only applies when retrying is cheap.A failing model that is ALSO egregiously bad (>=80%) or SLOW (in`slow_models`, measured this run) is excluded after a single run — we don'tspend more time/money re-attempting an expensive failure."""from datasets_.util import load, saveslow_models = slow_models or set()health = compute_model_health(detailed)cols = ["model", "strikes", "failed_pct"]if health.empty:14 unmodified linesfail_map = dict(zip(bad["model"], bad["failed_pct"]))def _strikes_for(model, fail_pct):# No grace if the failure is egregious OR slow-and-expensive-to-retry;# otherwise increment so a fast, moderately-failing model gets one free# re-attempt before exclusion.14 unmodified lines],columns=cols,)save(strikes_df, "model-health-strikes")blocked = sorted(strikes_df[strikes_df["strikes"] >= AUTO_BLOCKLIST_MIN_RUNS]["model"].tolist())9 unmodified lines101112131415161718192021405 unmodified lines42742842943043143243343443543643743821 unmodified lines460461462463464465466467468469470471472473474475476477190 unmodified lines6686696706716726736746753 unmodified lines67968068168268368468568668768868969069169269369469569614 unmodified lines71171271371471571671771871972014 unmodified lines7357367377387397407417427437449 unmodified linesfrom google.cloud import translate_v2 as translatefrom huggingface_hub import AsyncInferenceClient, HfApifrom joblib.memory import Memoryfrom openai import (AsyncOpenAI,AuthenticationError,BadRequestError,PermissionDeniedError,)from requests import HTTPError, get# for development purposes, all languages will be evaluated on the fast models405 unmodified lines"""# Account-level by TYPE, regardless of message: 401 (bad/revoked/mistyped key)# and 403 (key lacks permission, or spend policy denies the request). Note# RateLimitError (429) is deliberately absent, that one is transient and# per-request, not account-level._FATAL_ERROR_TYPES = (AuthenticationError, PermissionDeniedError)_FATAL_ERROR_MARKERS = ("key limit exceeded","insufficient credits",21 unmodified linesif "filtered" in e.message:return Noneraise eexcept _FATAL_ERROR_TYPES as e:# Credential/permission failures are account-level by definition and# apply to every subsequent call. Matched BY TYPE because the string# markers below do not catch them: a revoked or mistyped key returns# 401 "User not found.", which contains none of the markers, so the# run would otherwise grind through the whole matrix logging every# combo as an error, flooding results-detailed and poisoning the# auto-blocklist, which is exactly what this guard exists to stop.raise FatalAPIError(f"OpenRouter account-level failure ({type(e).__name__}): {e}. ""Aborting run before results-detailed is polluted.") from eexcept Exception as e:msg = str(e).lower()if any(marker in msg for marker in _FATAL_ERROR_MARKERS):190 unmodified lines)def update_blocklist_strikes(detailed=None, slow_models=None,not_attempted=None, dry_run=False) -> pd.DataFrame:"""Recompute consecutive-bad-run strikes and persist them to HF. Called onceper eval run (from main.py) after results are merged. A model currently pastthe failure threshold gets +1 strike; a model that has recovered (or never3 unmodified linesThe 2-run grace (one free re-attempt) only applies when retrying is cheap.A failing model that is ALSO egregiously bad (>=80%) or SLOW (in`slow_models`, measured this run) is excluded after a single run — we don'tspend more time/money re-attempting an expensive failure.`not_attempted` are models this run never got to, deferred byMAX_NEW_MODELS_PER_RUN. Strikes are computed from the CUMULATIVE log, sowithout this they would keep accruing +1 per run on a stale record and beauto-blocklisted after AUTO_BLOCKLIST_MIN_RUNS runs without ever getting there-attempt the grace period is supposed to buy them. Their prior count isheld steady instead."""from datasets_.util import load, save, save_local_onlyslow_models = slow_models or set()not_attempted = not_attempted or set()health = compute_model_health(detailed)cols = ["model", "strikes", "failed_pct"]if health.empty:14 unmodified linesfail_map = dict(zip(bad["model"], bad["failed_pct"]))def _strikes_for(model, fail_pct):# Deferred by the per-run cap, it never ran, so it can't have earned a# strike. Hold the prior count so the record persists without advancing.if model in not_attempted:return int(prior_map.get(model, 0))# No grace if the failure is egregious OR slow-and-expensive-to-retry;# otherwise increment so a fast, moderately-failing model gets one free# re-attempt before exclusion.14 unmodified lines],columns=cols,)if dry_run:save_local_only(strikes_df, "dry-run/model-health-strikes")else:save(strikes_df, "model-health-strikes")blocked = sorted(strikes_df[strikes_df["strikes"] >= AUTO_BLOCKLIST_MIN_RUNS]["model"].tolist())
.github/workflows/nightly-evals.yml+22
.gitignore+2
evals/datasets_/util.py+6-2
evals/main.py+208-57
evals/models.py+44-5