diff --git a/README.md b/README.md index 176132b..14818f7 100644 --- a/README.md +++ b/README.md @@ -338,6 +338,7 @@ produced and auto-detects the shape. First-class adapters today: - **Ragas** result export (one RAG pipeline per run - pass two files to compare) - **OpenAI Evals** (`openai/evals`) `.jsonl` log (one model per run - pass two files to compare) - **HELM** per-instance results (`per_instance_stats.json`) (one model per run - pass two files to compare) +- **Lighteval** (Hugging Face) JSON per-sample details export (convert Parquet first; one model per run - pass two files to compare) - **MLflow evaluate** `eval_results_table` export (one model per run - pass two files to compare) - **lm-eval** (`lm-evaluation-harness`) sample logs (`.jsonl`) - **Nested JSON** - `{"models": [...], "examples": [{"id", "scores": {...}}]}` diff --git a/docs/adapters.md b/docs/adapters.md index 26c6349..033a0c0 100644 --- a/docs/adapters.md +++ b/docs/adapters.md @@ -116,6 +116,42 @@ The most valuable fixture is one derived from a genuine export of the tool. If y have a real sample file, base the test on it - that is how we make sure the adapter matches reality and not an assumption. +## Lighteval (Hugging Face) + +Supports JSON representations of Lighteval per-sample details, with tolerance +for optional fields. Each record has: + +- a document (`doc` or `__doc__`): `query`, `choices`, `gold_index`, and usually + `id` / `task_name` +- a metric dict (`metric` or `__metric__`): sample-level metric names to scores +- a model response (`model_response` or `__model_response__`, optional): + generations / logprobs + +Both the column names observed in recent official reference Parquet exports +(`doc` / `metric` / `model_response`) and the underscore-prefixed names in the +current public Hugging Face documentation (`__doc__` / `__metric__` / +`__model_response__`) are accepted. Native Parquet files are not read directly; +convert them to this JSON shape first. + +Normalization rules for this adapter: + +- Invalid, null, or unparseable metric values are ignored (not raised). +- Standard-error fields such as `*_stderr` are ignored. +- Valid metrics preserve input order when fanning out into a suite. +- Conflicting aliases (for example unequal `doc` and `__doc__`) are treated as + malformed and skipped. +- `skipped_rows` counts skipped input rows, not individual metric fields. + +Example IDs are preserved as `task_name:id` when `task_name` is present. +Multiple metrics fan out into a suite; the single-audit path prefers common +correctness metrics such as `acc` / `exact_match` / `em`. + +**Limitation:** the aggregate `results_{timestamp}.json` file +(`config_general`, `results`, `config_tasks`, …) contains only task-level +summaries. EvalTrust detects that shape and raises a clear error rather than +fabricating per-example rows. Convert details Parquet to the JSON detail shape +above (or export a details list) before auditing. + ## Single-model tools If a tool evaluates one model per run, you don't need anything special: parse it diff --git a/docs/input-formats.md b/docs/input-formats.md index 083198b..5bdba3b 100644 --- a/docs/input-formats.md +++ b/docs/input-formats.md @@ -163,6 +163,39 @@ path picks a correctness metric (`exact_match`, `quasi_exact_match`, ...). HELM's bookkeeping stats (`num_trials`, `num_prompt_tokens`, `finish_reason_*`, ...) are dropped so a suite audit only holds real quality metrics. +### Lighteval (Hugging Face) + +EvalTrust accepts JSON representations of Lighteval per-sample details (a list +of records, or a task-keyed dict of those lists). Each record has a document +(`doc` or `__doc__`, with `query` / `choices` / `gold_index`, and usually `id` / +`task_name`), a metric dict (`metric` or `__metric__`), and optionally a model +response (`model_response` or `__model_response__`). Both the names observed in +recent official reference Parquet exports and the underscore-prefixed names in +the current public Hugging Face documentation are supported. Native Parquet is +not read; convert `details_*.parquet` to this JSON shape first. Detection is +structural, never by filename. + +Normalization rules for this adapter: + +- Invalid, null, or unparseable metric values are ignored (not raised). +- Standard-error fields such as `*_stderr` are ignored. +- Valid metrics preserve input order when fanning out into a suite. +- Conflicting aliases (for example unequal `doc` and `__doc__`) are treated as + malformed and skipped. +- `skipped_rows` counts skipped input rows, not individual metric fields. + +A Lighteval run covers one model, so compare two details exports: + +```bash +evaltrust audit lighteval_details_a.json lighteval_details_b.json +``` + +**Limitation:** the aggregate `results_{timestamp}.json` +(`config_general` / `results` / `config_tasks`) has only task-level summaries. +EvalTrust detects that shape and raises a clear error rather than inventing +per-example rows. Convert `details_*.parquet` to the JSON detail shape above +before auditing. + ### Nested JSON A structured object with a list of examples, each carrying per-model scores: @@ -311,8 +344,8 @@ without a `metric` column is treated as a single metric, exactly as before. See ## Single-model tools (two-file comparison) Some tools - DeepEval, Langfuse, LangSmith, Ragas, OpenEvals, Inspect, HELM, -OpenAI Evals - evaluate one model per run, so a single export contains only one -model. Run each model, then pass both files: +Lighteval, MLflow evaluate, OpenAI Evals - evaluate one model per run, so a +single export contains only one model. Run each model, then pass both files: ```bash evaltrust audit gpt4_run.json claude_run.json diff --git a/src/evaltrust/adapters/lighteval.py b/src/evaltrust/adapters/lighteval.py new file mode 100644 index 0000000..49f4953 --- /dev/null +++ b/src/evaltrust/adapters/lighteval.py @@ -0,0 +1,335 @@ +"""Hugging Face Lighteval details adapter. + +Reads Lighteval's per-sample ``Detail`` records. Each row carries a document, +a metric dict of sample-level scores, and optionally a model response. JSON +exports of ``--save-details`` output use either the column names observed in +recent official reference Parquet files (``doc``, ``metric``, +``model_response``) or the underscore-prefixed names in the current public +Hugging Face documentation (``__doc__``, ``__metric__``, +``__model_response__``). Both exact aliases are accepted. + +Lighteval's aggregate ``results_{timestamp}.json`` (``config_general``, +``results``, ``config_tasks``, …) holds task-level summaries only. It is +recognised so ingestion can fail with a specific error rather than falling +through to a generic adapter, but it cannot be mapped to per-example canonical +rows. +""" + +from __future__ import annotations + +from collections import OrderedDict +from dataclasses import dataclass + +from ..core.schema import EvalData +from .common import Record, coerce_score, records_to_suite + +# Top-level keys on the aggregate results file (EvaluationTracker.save_results). +_AGGREGATE_KEYS = frozenset( + {"config_general", "results", "versions", "config_tasks", "summary_tasks", "summary_general"} +) + +# Keys that are never per-sample detail task lists when flattening a dict export. +_NON_DETAIL_KEYS = _AGGREGATE_KEYS | {"details", "summary_general"} + +# Exact field-name aliases: recent official Parquet columns, and the current +# public documentation's underscore-prefixed names. No other variants. +_DOC_KEYS = ("doc", "__doc__") +_METRIC_KEYS = ("metric", "__metric__") +_MODEL_RESPONSE_KEYS = ("model_response", "__model_response__") + +# Preferred metric for the single-audit path, in priority order. +_PRIMARY_METRICS = ( + "acc", + "exact_match", + "em", + "qem", + "pass@1", + "maj@1", +) + +_DEFAULT_MODEL = "model" + + +@dataclass(frozen=True) +class _DetailFields: + """Alias-resolved fields from one Lighteval detail row.""" + + doc: dict + metric: dict + model_response: dict | None = None + + +def _is_aggregate_results(raw: dict) -> bool: + """Return True when *raw* looks like Lighteval's aggregate results.json.""" + if not isinstance(raw, dict): + return False + cg = raw.get("config_general") + if not isinstance(cg, dict): + return False + # lighteval_sha is the strongest structural marker for this format. + if "lighteval_sha" not in cg: + return False + results = raw.get("results") + config_tasks = raw.get("config_tasks") + return isinstance(results, dict) and isinstance(config_tasks, dict) + + +def _resolve_aliased_field(entry: dict, keys: tuple[str, ...]): + """Return the value for an exact alias pair, or raise on conflict. + + If both aliases are present and equal, either value is returned. If both + are present but differ, raise ``ValueError`` so the row is not silently + accepted. If neither is present, return ``None``. + """ + present = [(key, entry[key]) for key in keys if key in entry] + if not present: + return None + if len(present) == 1: + return present[0][1] + (_, left), (_, right) = present[0], present[1] + if left == right: + return left + raise ValueError( + f"conflicting Lighteval detail fields {keys[0]!r} and {keys[1]!r}" + ) + + +def _extract_detail_fields(entry: dict) -> _DetailFields | None: + """Resolve doc/metric/(optional) model_response via exact aliases. + + Returns ``None`` when required fields are absent or not dicts (not a detail + row). Raises ``ValueError`` when both aliases of a field are present and + conflict — callers treat that as a malformed row. + """ + if not isinstance(entry, dict): + return None + doc = _resolve_aliased_field(entry, _DOC_KEYS) + metric = _resolve_aliased_field(entry, _METRIC_KEYS) + if not isinstance(doc, dict) or not isinstance(metric, dict): + return None + model_response = _resolve_aliased_field(entry, _MODEL_RESPONSE_KEYS) + if model_response is not None and not isinstance(model_response, dict): + # Present but not a mapping: treat as absent optional field rather + # than rejecting a otherwise-valid scored row. + model_response = None + return _DetailFields(doc=doc, metric=metric, model_response=model_response) + + +def _looks_like_detail(entry: dict) -> bool: + """Return True when *entry* matches a Lighteval Detail dict.""" + try: + fields = _extract_detail_fields(entry) + except ValueError: + # Conflicting aliases are still structurally Lighteval-shaped; detect + # so parse can skip with a counted malformed row rather than falling + # through to Generic. + return _has_any_detail_alias(entry) + if fields is None: + return False + # Doc fingerprint: query + choices + gold_index (see requests.Doc). + if not all(k in fields.doc for k in ("query", "choices", "gold_index")): + return False + # At least one numeric metric score must be present for detection parity + # with parse(). + return any(_metric_score(fields.metric, name) is not None for name in fields.metric) + + +def _has_any_detail_alias(entry: dict) -> bool: + """True when *entry* carries both a doc-shaped and metric-shaped alias pair. + + Used only so a conflicting-alias row is still claimed by this adapter + (and then skipped) instead of being mis-routed. + """ + if not isinstance(entry, dict): + return False + has_doc = any(k in entry and isinstance(entry[k], dict) for k in _DOC_KEYS) + has_metric = any(k in entry and isinstance(entry[k], dict) for k in _METRIC_KEYS) + if not (has_doc and has_metric): + return False + # Prefer a real doc fingerprint when available so bare {"doc": {}, ...} + # does not claim unrelated JSON. + for key in _DOC_KEYS: + doc = entry.get(key) + if isinstance(doc, dict) and all( + k in doc for k in ("query", "choices", "gold_index") + ): + return True + return False + + +def _metric_score(metric: dict, name: str) -> float | None: + if name.endswith("_stderr"): + return None + raw = metric.get(name) + if raw is None: + return None + try: + return coerce_score(raw) + except (ValueError, TypeError): + return None + + +def _example_id(doc: dict, task_hint: str | None = None) -> str | None: + doc_id = doc.get("id") + if doc_id is None: + return None + task = doc.get("task_name") or task_hint + ex_id = str(doc_id) + if isinstance(task, str) and task: + return f"{task}:{ex_id}" + return ex_id + + +def _model_name(raw) -> str: + if isinstance(raw, dict): + cg = raw.get("config_general") + if isinstance(cg, dict): + name = cg.get("model_name") + if isinstance(name, str) and name.strip(): + return name.strip() + mc = cg.get("model_config") + if isinstance(mc, dict): + name = mc.get("model_name") + if isinstance(name, str) and name.strip(): + return name.strip() + return _DEFAULT_MODEL + + +def _detail_rows(raw) -> list[tuple[dict, str | None]] | None: + """Return ``(detail_dict, task_hint)`` pairs extracted from supported shapes.""" + if isinstance(raw, list): + if not raw: + return None + if not any( + isinstance(row, dict) and _looks_like_detail(row) for row in raw + ): + return None + return [(row, None) for row in raw if isinstance(row, dict)] + + if not isinstance(raw, dict): + return None + + details = raw.get("details") + if isinstance(details, list) and details: + if any( + isinstance(row, dict) and _looks_like_detail(row) for row in details + ): + return [(row, None) for row in details if isinstance(row, dict)] + + rows: list[tuple[dict, str | None]] = [] + for key, value in raw.items(): + if key in _NON_DETAIL_KEYS: + continue + if not isinstance(value, list) or not value: + continue + if not any( + isinstance(row, dict) and _looks_like_detail(row) for row in value + ): + continue + task_hint = str(key) if "|" in str(key) or ":" in str(key) else None + for row in value: + if isinstance(row, dict): + rows.append((row, task_hint)) + + return rows or None + + +def _parse_to_records( + raw, + model: str, +) -> tuple[list[Record], int]: + pairs = _detail_rows(raw) + if pairs is None: + raise ValueError("Not a Lighteval per-sample details export") + + records: list[Record] = [] + skipped = 0 + + for entry, task_hint in pairs: + try: + fields = _extract_detail_fields(entry) + except ValueError: + # Conflicting aliases: skip and count, do not pick a side. + skipped += 1 + continue + if fields is None: + skipped += 1 + continue + # Revalidate the detail fingerprint on every row: detection of one + # valid row must not accept later mappings that lack query/choices/ + # gold_index. + if not all(k in fields.doc for k in ("query", "choices", "gold_index")): + skipped += 1 + continue + + ex_id = _example_id(fields.doc, task_hint) + if ex_id is None: + skipped += 1 + continue + + row_had_record = False + for name in fields.metric: + score = _metric_score(fields.metric, name) + if score is None: + # Ignore *_stderr, null, and unparseable metric values; they + # do not count toward skipped_rows. + continue + records.append(Record(ex_id, model, score, metric=str(name))) + row_had_record = True + + if not row_had_record: + skipped += 1 + + return records, skipped + + +def _pick_primary_metric(suite: "OrderedDict[str, EvalData]") -> str | None: + keys = suite.keys() + for preferred in _PRIMARY_METRICS: + if preferred in keys: + return preferred + return next(iter(keys), None) + + +class LightevalAdapter: + source_format = "lighteval" + + def detect(self, raw) -> bool: + if _is_aggregate_results(raw): + return True + pairs = _detail_rows(raw) + return pairs is not None and len(pairs) > 0 + + def _to_suite(self, raw) -> "OrderedDict[str, EvalData]": + if _is_aggregate_results(raw): + raise ValueError( + "Lighteval results.json contains only aggregate task metrics " + "(config_general, results, config_tasks, …). EvalTrust needs " + "per-example scores. Re-run with --save-details and point " + "evaltrust at a JSON details export (a list of " + "{doc|__doc__, metric|__metric__, model_response|__model_response__} " + "rows, or a task-grouped dict), or convert details_*.parquet " + "to that shape." + ) + + model = _model_name(raw) + records, skipped = _parse_to_records(raw, model) + if not records: + raise ValueError( + "No parsable per-sample metrics found in the Lighteval details " + "export. Expected objects with a doc/__doc__ (query, choices, " + "gold_index, id) and a metric/__metric__ dict of numeric scores." + ) + return records_to_suite( + records, self.source_format, {"skipped_rows": skipped} + ) + + def parse(self, raw) -> EvalData: + suite = self._to_suite(raw) + primary = _pick_primary_metric(suite) + if primary is not None and primary in suite: + return suite[primary] + return next(iter(suite.values())) + + def parse_suite(self, raw) -> "OrderedDict[str, EvalData]": + return self._to_suite(raw) diff --git a/src/evaltrust/adapters/registry.py b/src/evaltrust/adapters/registry.py index 24b4f78..e695f02 100644 --- a/src/evaltrust/adapters/registry.py +++ b/src/evaltrust/adapters/registry.py @@ -16,6 +16,7 @@ from .inspect_ai import InspectAdapter from .langfuse import LangfuseAdapter from .langsmith import LangSmithAdapter +from .lighteval import LightevalAdapter from .mlflow_evaluate import MlflowEvaluateAdapter from .openevals import OpenEvalsAdapter from .promptfoo import PromptfooAdapter @@ -46,6 +47,7 @@ class UnknownFormatError(ValueError): RagasAdapter(), HelmAdapter(), MlflowEvaluateAdapter(), + LightevalAdapter(), NativeNestedAdapter(), GenericRecordsAdapter(), ] @@ -58,7 +60,8 @@ def detect_adapter(raw) -> Adapter: raise UnknownFormatError( "Could not recognise this evaluation format. EvalTrust looked for " "promptfoo results, a DeepEval test-results export, Langfuse scores, " - "a HELM per_instance_stats.json, a nested {\"examples\": [...]} " - "structure, or a list of records with model/score fields. Provide " + "a HELM per_instance_stats.json, a Lighteval per-sample details " + "export, a nested {\"examples\": [...]} structure, or a list of " + "records with model/score fields. Provide " "per-example scores in one of those shapes, or a CSV." ) diff --git a/tests/fixtures/lighteval_PROVENANCE.md b/tests/fixtures/lighteval_PROVENANCE.md new file mode 100644 index 0000000..cabb695 --- /dev/null +++ b/tests/fixtures/lighteval_PROVENANCE.md @@ -0,0 +1,58 @@ +# Lighteval fixture provenance + +## `lighteval_details_agieval_aqua_rat.json` + +**Source:** Official Hugging Face Lighteval repository reference details +(`huggingface/lighteval`). + +- Upstream Git commit (immutable): + `31433cc9e19d60635e9f62f271d5f3a8f2ed2696` +- Repository-relative path: + `tests/reference_details/SmolLM2-1.7B-Instruct-transformers/details_agieval:aqua-rat|0_2025-11-05T14-43-47.148527.parquet` +- Immutable GitHub blob URL: + https://github.com/huggingface/lighteval/blob/31433cc9e19d60635e9f62f271d5f3a8f2ed2696/tests/reference_details/SmolLM2-1.7B-Instruct-transformers/details_agieval:aqua-rat%7C0_2025-11-05T14-43-47.148527.parquet +- Direct download (Git LFS / media CDN, same commit + path): + https://media.githubusercontent.com/media/huggingface/lighteval/31433cc9e19d60635e9f62f271d5f3a8f2ed2696/tests/reference_details/SmolLM2-1.7B-Instruct-transformers/details_agieval%3Aaqua-rat%7C0_2025-11-05T14-43-47.148527.parquet +- SHA-256 of the **original Parquet artifact** used for conversion: + `ef968329bee498b3387ec8df3677ca9bbac72e90599efbe7f78db23f4227b2f6` +- Timestamp in filename: `2025-11-05T14-43-47.148527` +- Model evaluated: `HuggingFaceTB/SmolLM2-1.7B-Instruct` +- Task: `agieval:aqua-rat|0` +- Lighteval commit referenced by the matching aggregate results file: + `config_general.lighteval_sha` = `01bd59882e01ab82971e6ab07c7c39c69ab8664b` + (evaluation-runtime SHA from the results JSON; distinct from the upstream + repository commit that stores this reference Parquet) + +**Column names in this recent official reference artifact:** `doc`, `metric`, +`model_response` (verified by reading the Parquet schema). This is the shape +preserved in the fixture. + +**Current public documentation shape:** the Hugging Face Lighteval docs +describe per-sample detail columns as `__doc__`, `__metric__`, and +`__model_response__`. The adapter accepts those exact aliases as well; they are +covered by focused inline tests rather than this authentic fixture. + +**Reduction / sanitization (EvalTrust JSON fixture, not the Parquet digest):** + +- Converted from the Parquet above to JSON (EvalTrust JSON adapters; no runtime + Parquet dependency). +- Kept the first 3 of 10 authentic samples. +- Truncated `model_response.input_tokens` / `output_tokens` for size only; + `doc`, `metric`, and remaining `model_response` fields are unchanged. +- No credentials, local paths, or tokens were present. +- The SHA-256 above fingerprints the **original Parquet file**. The reduced + JSON in this repository is a derived fixture and has a different digest. + +Redistribution: these are public Lighteval test fixtures (MIT License, +Hugging Face Team). + +## `lighteval_results_aggregate.json` + +**Source:** Official Lighteval reference scores +`tests/reference_scores/SmolLM2-1.7B-Instruct-results-accelerate.json`. + +**Reduction:** Kept the authentic top-level shape (`config_general`, `results`, +`versions`, `config_tasks`, `summary_tasks`, `summary_general`) but retained only +two task entries plus the `all` aggregate. Used as a negative fixture: this +shape is detected as Lighteval but rejected on parse because it has no +per-example scores. diff --git a/tests/fixtures/lighteval_details_agieval_aqua_rat.json b/tests/fixtures/lighteval_details_agieval_aqua_rat.json new file mode 100644 index 0000000..3eb967d --- /dev/null +++ b/tests/fixtures/lighteval_details_agieval_aqua_rat.json @@ -0,0 +1,341 @@ +[ + { + "doc": { + "choices": [ + " (A)20%", + " (B)30%", + " (C)40%", + " (D)50%", + " (E)60%" + ], + "fewshot_samples": [], + "fewshot_sorting_class": null, + "generation_grammar": null, + "generation_size": 1, + "gold_index": [ + 1 + ], + "id": "44", + "images": null, + "instruction": null, + "num_samples": 1, + "original_query": null, + "query": "Q: At Daifu university, 24% of all students are members of both a chess club and a swim team. If 20% of members of the swim team are not members of the chess club, what percentage of all Daifu students are members of the swim team? Answer Choices: (A)20% (B)30% (C)40% (D)50% (E)60%\nA: Among A through E, the answer is", + "sampling_methods": [ + "LOGPROBS" + ], + "specific": null, + "stop_sequences": [], + "task_name": "agieval:aqua-rat|0", + "unconditioned_query": null, + "use_logits": true + }, + "metric": { + "acc": 0 + }, + "model_response": { + "argmax_logits_eq_gold": [ + false, + false, + false, + false, + false + ], + "input": null, + "input_tokens": [ + 1, + 9690, + 198, + 2683, + 359, + 253, + 5356, + 5646, + 11173, + 3365, + 3511, + 308, + 34519, + 28, + 7018 + ], + "logits": null, + "logprobs": [ + -14.3203125, + -13.65625, + -14.46875, + -11.703125, + -12.0234375 + ], + "output_tokens": [ + [ + 198, + 365, + 49, + 25, + 34 + ], + [ + 198, + 365, + 50, + 25, + 35 + ], + [ + 198, + 365, + 51, + 25, + 36 + ], + [ + 198, + 365, + 52, + 25, + 37 + ], + [ + 198, + 365, + 53, + 25, + 38 + ] + ], + "padded_tokens_count": 0, + "reasonings": [], + "text": [], + "text_post_processed": [], + "truncated_tokens_count": 0, + "unconditioned_logprobs": null + } + }, + { + "doc": { + "choices": [ + " (A)15", + " (B)24", + " (C)25", + " (D)40", + " (E)52" + ], + "fewshot_samples": [], + "fewshot_sorting_class": null, + "generation_grammar": null, + "generation_size": 1, + "gold_index": [ + 3 + ], + "id": "9", + "images": null, + "instruction": null, + "num_samples": 1, + "original_query": null, + "query": "Q: A sales person gets a 10% commission on each sale he makes. How many sales of $250 each must he make in order to reach a salary of at least $1000? Answer Choices: (A)15 (B)24 (C)25 (D)40 (E)52\nA: Among A through E, the answer is", + "sampling_methods": [ + "LOGPROBS" + ], + "specific": null, + "stop_sequences": [], + "task_name": "agieval:aqua-rat|0", + "unconditioned_query": null, + "use_logits": true + }, + "metric": { + "acc": 0 + }, + "model_response": { + "argmax_logits_eq_gold": [ + false, + false, + false, + false, + false + ], + "input": null, + "input_tokens": [ + 1, + 9690, + 198, + 2683, + 359, + 253, + 5356, + 5646, + 11173, + 3365, + 3511, + 308, + 34519, + 28, + 7018 + ], + "logits": null, + "logprobs": [ + -14.2578125, + -13.703125, + -13.6328125, + -13.1640625, + -11.9296875 + ], + "output_tokens": [ + [ + 198, + 365, + 49, + 25, + 33 + ], + [ + 198, + 365, + 50, + 25, + 34 + ], + [ + 198, + 365, + 51, + 25, + 34 + ], + [ + 198, + 365, + 52, + 25, + 36 + ], + [ + 198, + 365, + 53, + 25, + 37 + ] + ], + "padded_tokens_count": 0, + "reasonings": [], + "text": [], + "text_post_processed": [], + "truncated_tokens_count": 0, + "unconditioned_logprobs": null + } + }, + { + "doc": { + "choices": [ + " (A)520", + " (B)720", + " (C)920", + " (D)None", + " (E)Cannot be determined" + ], + "fewshot_samples": [], + "fewshot_sorting_class": null, + "generation_grammar": null, + "generation_size": 1, + "gold_index": [ + 1 + ], + "id": "73", + "images": null, + "instruction": null, + "num_samples": 1, + "original_query": null, + "query": "Q: Suppose you want to arrange your English, Hindi, Mathematics, History, Geography and Science books on a shelf. In how many ways can you do it ? Answer Choices: (A)520 (B)720 (C)920 (D)None (E)Cannot be determined\nA: Among A through E, the answer is", + "sampling_methods": [ + "LOGPROBS" + ], + "specific": null, + "stop_sequences": [], + "task_name": "agieval:aqua-rat|0", + "unconditioned_query": null, + "use_logits": true + }, + "metric": { + "acc": 0 + }, + "model_response": { + "argmax_logits_eq_gold": [ + false, + false, + false, + false, + false + ], + "input": null, + "input_tokens": [ + 1, + 9690, + 198, + 2683, + 359, + 253, + 5356, + 5646, + 11173, + 3365, + 3511, + 308, + 34519, + 28, + 7018 + ], + "logits": null, + "logprobs": [ + -13.234375, + -14.203125, + -14.4296875, + -15.453125, + -11.671875 + ], + "output_tokens": [ + [ + 198, + 365, + 49, + 25, + 37 + ], + [ + 198, + 365, + 50, + 25, + 39 + ], + [ + 198, + 365, + 51, + 25, + 41 + ], + [ + 198, + 365, + 52, + 25, + 3482 + ], + [ + 198, + 365, + 53, + 25, + 40206 + ] + ], + "padded_tokens_count": 0, + "reasonings": [], + "text": [], + "text_post_processed": [], + "truncated_tokens_count": 0, + "unconditioned_logprobs": null + } + } +] \ No newline at end of file diff --git a/tests/fixtures/lighteval_results_aggregate.json b/tests/fixtures/lighteval_results_aggregate.json new file mode 100644 index 0000000..3442708 --- /dev/null +++ b/tests/fixtures/lighteval_results_aggregate.json @@ -0,0 +1,206 @@ +{ + "config_general": { + "lighteval_sha": "01bd59882e01ab82971e6ab07c7c39c69ab8664b", + "num_fewshot_seeds": 1, + "max_samples": 10, + "job_id": "0", + "start_time": 4878719.033134899, + "end_time": 4878749.286077319, + "total_evaluation_time_secondes": "30.252942419610918", + "model_config": { + "model_name": "HuggingFaceTB/SmolLM2-1.7B-Instruct", + "generation_parameters": { + "num_blocks": null, + "block_size": null, + "early_stopping": null, + "repetition_penalty": null, + "frequency_penalty": null, + "length_penalty": null, + "presence_penalty": null, + "max_new_tokens": null, + "min_new_tokens": null, + "seed": null, + "stop_tokens": null, + "temperature": 0.0, + "top_k": null, + "min_p": null, + "top_p": 0.9, + "truncate_prompt": null, + "cache_implementation": null, + "response_format": null + }, + "system_prompt": null, + "cache_dir": "~/.cache/huggingface/lighteval", + "tokenizer": null, + "subfolder": null, + "revision": "57aa3c6599c53705406c648e7acca7e11dc45ea3", + "batch_size": 1, + "max_length": null, + "model_loading_kwargs": { + "attn_implementation": "eager" + }, + "add_special_tokens": true, + "skip_special_tokens": true, + "model_parallel": false, + "dtype": "float16", + "device": "cuda", + "trust_remote_code": false, + "compile": false, + "multichoice_continuations_start_space": null, + "pairwise_tokenization": false, + "continuous_batching": false, + "override_chat_template": null + }, + "model_name": "HuggingFaceTB/SmolLM2-1.7B-Instruct" + }, + "results": { + "arc:challenge|25": { + "acc": 0.4, + "acc_stderr": 0.16329931618554522 + }, + "bigbench_hard:ruin_names|3": { + "acc": 0.1, + "acc_stderr": 0.09999999999999999 + }, + "all": { + "acc": 0.29545454545454547, + "acc_stderr": 0.11711038848327954, + "truthfulqa_mc1": 0.2, + "truthfulqa_mc1_stderr": 0.13333333333333333, + "truthfulqa_mc2": 0.48125721389542864, + "truthfulqa_mc2_stderr": 0.13930231370271956, + "extractive_match": 0.5, + "extractive_match_stderr": 0.16666666666666666, + "em": 0.5, + "em_stderr": 0.15739057099901865 + } + }, + "versions": {}, + "config_tasks": { + "arc:challenge|25": { + "name": "arc:challenge", + "prompt_function": "arc", + "hf_repo": "allenai/ai2_arc", + "hf_subset": "ARC-Challenge", + "metrics": [ + { + "metric_name": "acc", + "higher_is_better": true, + "category": "LOGPROBS", + "sample_level_fn": "LoglikelihoodAcc(logprob_normalization=None)", + "corpus_level_fn": "mean", + "batched_compute": false + } + ], + "solver": null, + "scorer": null, + "sample_fields": null, + "sample_to_fewshot": null, + "filter": null, + "hf_revision": null, + "hf_filter": null, + "hf_avail_splits": [ + "train", + "test" + ], + "evaluation_splits": [ + "test" + ], + "few_shots_split": null, + "few_shots_select": "random_sampling_from_train", + "generation_size": 1, + "generation_grammar": null, + "stop_sequence": [ + "\n" + ], + "num_samples": null, + "original_num_docs": -1, + "effective_num_docs": -1, + "must_remove_duplicate_docs": false, + "num_fewshots": 25, + "version": 0 + }, + "bigbench_hard:ruin_names|3": { + "name": "bigbench_hard:ruin_names", + "prompt_function": "bbh_lighteval", + "hf_repo": "lighteval/bbh", + "hf_subset": "ruin_names", + "metrics": [ + { + "metric_name": "acc", + "higher_is_better": true, + "category": "LOGPROBS", + "sample_level_fn": "LoglikelihoodAcc(logprob_normalization=None)", + "corpus_level_fn": "mean", + "batched_compute": false + } + ], + "solver": null, + "scorer": null, + "sample_fields": null, + "sample_to_fewshot": null, + "filter": null, + "hf_revision": null, + "hf_filter": null, + "hf_avail_splits": [ + "train" + ], + "evaluation_splits": [ + "train" + ], + "few_shots_split": null, + "few_shots_select": null, + "generation_size": -1, + "generation_grammar": null, + "stop_sequence": [ + "", + "Q=", + "\n\n" + ], + "num_samples": null, + "original_num_docs": -1, + "effective_num_docs": -1, + "must_remove_duplicate_docs": false, + "num_fewshots": 3, + "version": 0 + } + }, + "summary_tasks": { + "arc:challenge|25": { + "hashes": { + "hash_examples": "0f147b3f7931a7ed", + "hash_full_prompts": "ef46db3751d8e999", + "hash_input_tokens": "3c2c9fdc04d335b2", + "hash_cont_tokens": "db8f2aba7bbd27e3" + }, + "truncated": 0, + "non_truncated": 0, + "padded": 0, + "non_padded": 0 + }, + "bigbench_hard:ruin_names|3": { + "hashes": { + "hash_examples": "a17e9634a21f6d7a", + "hash_full_prompts": "ef46db3751d8e999", + "hash_input_tokens": "1c924f607a3f005a", + "hash_cont_tokens": "5ae0849cc03dab66" + }, + "truncated": 0, + "non_truncated": 0, + "padded": 0, + "non_padded": 0 + } + }, + "summary_general": { + "hashes": { + "hash_examples": "68b0b3cbd628cac8", + "hash_full_prompts": "6c276b4f520c3deb", + "hash_input_tokens": "7b2896e8f6925563", + "hash_cont_tokens": "896954fbadfda3b1" + }, + "truncated": 0, + "non_truncated": 0, + "padded": 0, + "non_padded": 0 + } +} \ No newline at end of file diff --git a/tests/test_lighteval_adapter.py b/tests/test_lighteval_adapter.py new file mode 100644 index 0000000..42919b7 --- /dev/null +++ b/tests/test_lighteval_adapter.py @@ -0,0 +1,511 @@ +"""Tests for the Hugging Face Lighteval details adapter. + +Lighteval writes per-sample scores to details Parquet files. Recent official +reference artifacts use columns doc / metric / model_response; the current +public documentation describes __doc__ / __metric__ / __model_response__. +Both exact aliases are accepted. The aggregate results.json holds task +summaries only. Detection is structural; filenames are never consulted. +""" + +import copy +import json +from pathlib import Path + +import pytest + +from evaltrust.adapters.deepeval import DeepEvalAdapter +from evaltrust.adapters.generic import GenericRecordsAdapter, NativeNestedAdapter +from evaltrust.adapters.helm import HelmAdapter +from evaltrust.adapters.inspect_ai import InspectAdapter +from evaltrust.adapters.lighteval import LightevalAdapter +from evaltrust.adapters.promptfoo import PromptfooAdapter +from evaltrust.adapters.registry import detect_adapter + +_TESTS_DIR = Path(__file__).parent +_REPO_ROOT = _TESTS_DIR.parent + + +def _load(path): + return json.loads(Path(path).read_text()) + + +DETAILS = _load(_TESTS_DIR / "fixtures" / "lighteval_details_agieval_aqua_rat.json") +AGGREGATE = _load(_TESTS_DIR / "fixtures" / "lighteval_results_aggregate.json") + +# Documented underscore-prefixed shape (public HF docs); not the authentic +# recent Parquet fixture, which uses unprefixed column names. +DOCUMENTED = [ + { + "__doc__": { + "query": "What is 2+2?", + "choices": ["3", "4"], + "gold_index": 1, + "id": "d1", + "task_name": "gsm8k|0", + }, + "__metric__": {"em": 1.0, "maj@8": 0.0}, + "__model_response__": {"text": ["4"]}, + }, + { + "__doc__": { + "query": "What is 3+3?", + "choices": ["5", "6"], + "gold_index": 1, + "id": "d2", + "task_name": "gsm8k|0", + }, + "__metric__": {"em": 0.0, "maj@8": 0.0}, + "__model_response__": {"text": ["5"]}, + }, +] + + +# --------------------------------------------------------------------------- +# Detection — authentic fixture +# --------------------------------------------------------------------------- + + +def test_lighteval_detects_the_real_details_fixture(): + assert LightevalAdapter().detect(DETAILS) + + +def test_lighteval_detects_aggregate_results_structurally(): + assert LightevalAdapter().detect(AGGREGATE) + + +def test_lighteval_detection_is_independent_of_filename(): + # Same payload loaded from differently named paths must detect identically. + raw = copy.deepcopy(DETAILS) + assert LightevalAdapter().detect(raw) + + +def test_lighteval_does_not_detect_generic_similar_json(): + generic = {"results": {"task|0": {"em": 0.5, "em_stderr": 0.1}}} + assert not LightevalAdapter().detect(generic) + + +def test_lighteval_does_not_detect_native_nested(): + native = {"models": ["A"], "examples": [{"id": "q1", "scores": {"A": 1}}]} + assert not LightevalAdapter().detect(native) + + +def test_lighteval_does_not_detect_promptfoo(): + promptfoo = { + "results": {"results": [{"provider": "gpt", "testIdx": 0, "score": 1}], + "table": {"head": {"prompts": []}}}, + "version": 3, + } + assert not LightevalAdapter().detect(promptfoo) + + +def test_lighteval_does_not_detect_helm_per_instance_stats(): + helm = _load(_TESTS_DIR / "fixtures" / "helm_per_instance_stats.json") + assert not LightevalAdapter().detect(helm) + + +def test_lighteval_does_not_detect_inspect_log(): + inspect = _load(_TESTS_DIR / "fixtures" / "inspect_log.json") + assert not LightevalAdapter().detect(inspect) + + +def test_lighteval_does_not_false_positive_on_other_fixtures(): + adapter = LightevalAdapter() + files = list((_TESTS_DIR / "fixtures").glob("*.json")) + \ + list((_REPO_ROOT / "examples").glob("*.json")) + for f in files: + raw = _load(f) + detected = adapter.detect(raw) + if f.name.startswith("lighteval_"): + assert detected, f.name + else: + assert not detected, f.name + + +# --------------------------------------------------------------------------- +# Conversion — authentic fixture +# --------------------------------------------------------------------------- + + +def test_lighteval_parses_the_real_details_fixture(): + data = LightevalAdapter().parse(DETAILS) + assert data.source_format == "lighteval" + # Details rows alone have no model field; label defaults like HELM. + assert data.models == ["model"] + assert data.n_examples == 3 + assert data.examples[0].id == "agieval:aqua-rat|0:44" + assert data.examples[0].scores["model"] == 0.0 + + +def test_lighteval_suite_from_real_fixture(): + suite = LightevalAdapter().parse_suite(DETAILS) + assert list(suite) == ["acc"] + assert suite["acc"].n_examples == 3 + + +def test_lighteval_preserves_example_ids_deterministically(): + data = LightevalAdapter().parse(DETAILS) + assert [ex.id for ex in data.examples] == [ + "agieval:aqua-rat|0:44", + "agieval:aqua-rat|0:9", + "agieval:aqua-rat|0:73", + ] + + +# --------------------------------------------------------------------------- +# Multiple metrics +# --------------------------------------------------------------------------- + + +def test_lighteval_preserves_multiple_metric_names(): + raw = [ + { + "doc": { + "query": "Q?", + "choices": ["A", "B"], + "gold_index": 0, + "id": "ex1", + "task_name": "gsm8k|0", + }, + "metric": {"em": 1.0, "maj@8": 0.0}, + "model_response": {"text": ["answer"]}, + }, + ] + suite = LightevalAdapter().parse_suite(raw) + assert set(suite.keys()) == {"em", "maj@8"} + assert suite["em"].examples[0].scores["model"] == 1.0 + assert suite["maj@8"].examples[0].scores["model"] == 0.0 + + +def test_lighteval_documented_shape_preserves_multiple_metrics(): + suite = LightevalAdapter().parse_suite(DOCUMENTED) + assert set(suite.keys()) == {"em", "maj@8"} + assert [ex.id for ex in suite["em"].examples] == ["gsm8k|0:d1", "gsm8k|0:d2"] + assert [ex.scores["model"] for ex in suite["em"].examples] == [1.0, 0.0] + assert [ex.scores["model"] for ex in suite["maj@8"].examples] == [0.0, 0.0] + + +# --------------------------------------------------------------------------- +# Documented underscore-prefixed aliases +# --------------------------------------------------------------------------- + + +def test_lighteval_detects_and_parses_documented_underscore_shape(): + a = LightevalAdapter() + assert a.detect(DOCUMENTED) + data = a.parse(DOCUMENTED) + assert data.source_format == "lighteval" + assert data.n_examples == 2 + assert data.examples[0].id == "gsm8k|0:d1" + assert data.examples[0].scores["model"] == 1.0 + + +def test_lighteval_documented_shape_without_model_response(): + raw = copy.deepcopy(DOCUMENTED[0]) + del raw["__model_response__"] + data = LightevalAdapter().parse([raw]) + assert data.n_examples == 1 + assert data.examples[0].id == "gsm8k|0:d1" + + +def test_lighteval_equal_aliases_are_accepted(): + doc = { + "query": "Q?", + "choices": ["A"], + "gold_index": 0, + "id": "same", + "task_name": "t|0", + } + raw = [{ + "doc": doc, + "__doc__": copy.deepcopy(doc), + "metric": {"acc": 1.0}, + "__metric__": {"acc": 1.0}, + }] + data = LightevalAdapter().parse(raw) + assert data.n_examples == 1 + assert data.examples[0].id == "t|0:same" + + +def test_lighteval_conflicting_doc_aliases_are_not_silently_accepted(): + raw = [ + { + "doc": { + "query": "Q?", + "choices": ["A"], + "gold_index": 0, + "id": "from-doc", + "task_name": "t|0", + }, + "__doc__": { + "query": "Q?", + "choices": ["A"], + "gold_index": 0, + "id": "from-underscore", + "task_name": "t|0", + }, + "metric": {"acc": 1.0}, + }, + { + "doc": { + "query": "Q2?", + "choices": ["B"], + "gold_index": 0, + "id": "ok", + "task_name": "t|0", + }, + "metric": {"acc": 0.0}, + }, + ] + assert LightevalAdapter().detect(raw) + data = LightevalAdapter().parse(raw) + assert [ex.id for ex in data.examples] == ["t|0:ok"] + assert data.metadata["skipped_rows"] == 1 + + +def test_lighteval_does_not_detect_generic_json_with_one_similar_key(): + # A lone similarly named key without the detail fingerprint is not enough. + assert not LightevalAdapter().detect([{"__doc__": {"text": "not a Doc"}}]) + assert not LightevalAdapter().detect([{"doc": {"query": "only query"}}]) + assert not LightevalAdapter().detect([{"__metric__": {"acc": 1.0}}]) + assert not LightevalAdapter().detect({"__results__": {"task|0": {"em": 1.0}}}) + + +def test_detect_routes_documented_shape_before_generic(): + assert detect_adapter(DOCUMENTED).source_format == "lighteval" + assert GenericRecordsAdapter().detect(DOCUMENTED) + + +# --------------------------------------------------------------------------- +# Optional fields and supported variants +# --------------------------------------------------------------------------- + + +def test_lighteval_accepts_details_without_model_response(): + raw = copy.deepcopy(DETAILS[0]) + del raw["model_response"] + data = LightevalAdapter().parse([raw]) + assert data.n_examples == 1 + + +def test_lighteval_accepts_task_grouped_dict_export(): + grouped = {"agieval:aqua-rat|0": DETAILS} + data = LightevalAdapter().parse(grouped) + assert data.n_examples == 3 + + +def test_lighteval_accepts_config_general_wrapped_details_list(): + wrapped = { + "config_general": {"model_name": "my-model", "lighteval_sha": "abc"}, + "details": DETAILS, + } + data = LightevalAdapter().parse(wrapped) + assert data.models == ["my-model"] + assert data.n_examples == 3 + + +def test_lighteval_optional_doc_fields_absent_still_parse(): + raw = { + "doc": { + "query": "Q?", + "choices": ["A"], + "gold_index": 0, + "id": "only-required", + }, + "metric": {"acc": 1.0}, + } + data = LightevalAdapter().parse([raw]) + assert data.examples[0].id == "only-required" + assert data.examples[0].scores["model"] == 1.0 + + +# --------------------------------------------------------------------------- +# Aggregate-only and malformed input +# --------------------------------------------------------------------------- + + +def test_lighteval_aggregate_results_raise_without_per_example_rows(): + with pytest.raises(ValueError, match="aggregate"): + LightevalAdapter().parse(AGGREGATE) + + +def test_lighteval_malformed_detail_missing_id_is_counted(): + raw = copy.deepcopy(DETAILS) + del raw[1]["doc"]["id"] + data = LightevalAdapter().parse(raw) + assert data.n_examples == 2 + assert data.metadata["skipped_rows"] == 1 + + +def test_lighteval_malformed_metric_structure_skipped(): + raw = [ + { + "doc": {"query": "Q", "choices": ["A"], "gold_index": 0, "id": "1"}, + "metric": "not-a-dict", + }, + { + "doc": {"query": "Q2", "choices": ["B"], "gold_index": 0, "id": "2"}, + "metric": {"acc": 1.0}, + }, + ] + data = LightevalAdapter().parse(raw) + assert data.n_examples == 1 + assert data.metadata["skipped_rows"] == 1 + + +def test_lighteval_null_and_non_numeric_metrics_not_treated_as_scores(): + raw = [ + { + "doc": {"query": "Q", "choices": ["A"], "gold_index": 0, "id": "1"}, + "metric": {"acc": None, "notes": "text", "acc_stderr": 0.1}, + }, + { + "doc": {"query": "Q2", "choices": ["B"], "gold_index": 0, "id": "2"}, + "metric": {"acc": 0.5}, + }, + ] + data = LightevalAdapter().parse(raw) + assert data.n_examples == 1 + assert data.metadata["skipped_rows"] == 1 + + +def test_lighteval_valid_metric_plus_stderr_does_not_skip_row(): + raw = [ + { + "doc": {"query": "Q", "choices": ["A"], "gold_index": 0, "id": "1"}, + "metric": {"acc": 1.0, "acc_stderr": 0.1}, + }, + ] + data = LightevalAdapter().parse(raw) + assert data.n_examples == 1 + assert data.examples[0].scores["model"] == 1.0 + assert data.metadata.get("skipped_rows", 0) == 0 + + +def test_lighteval_valid_metric_plus_invalid_field_does_not_skip_row(): + raw = [ + { + "doc": {"query": "Q", "choices": ["A"], "gold_index": 0, "id": "1"}, + "metric": {"acc": 1.0, "metadata": "x"}, + }, + ] + data = LightevalAdapter().parse(raw) + assert data.n_examples == 1 + assert data.examples[0].scores["model"] == 1.0 + assert data.metadata.get("skipped_rows", 0) == 0 + + +def test_lighteval_only_invalid_null_or_stderr_metrics_skip_row_once(): + raw = [ + { + "doc": {"query": "Q", "choices": ["A"], "gold_index": 0, "id": "1"}, + "metric": {"acc": None, "notes": "text", "acc_stderr": 0.1}, + }, + { + "doc": {"query": "Q2", "choices": ["B"], "gold_index": 0, "id": "2"}, + "metric": {"acc": 0.5}, + }, + ] + data = LightevalAdapter().parse(raw) + assert data.n_examples == 1 + assert data.metadata["skipped_rows"] == 1 + + +def test_lighteval_unsupported_shape_not_detected(): + assert not LightevalAdapter().detect({"doc": {"query": "x"}, "metric": {}}) + + +# --------------------------------------------------------------------------- +# Detail-list detection beyond the first rows +# --------------------------------------------------------------------------- + + +def _valid_detail(ex_id: str, score: float = 1.0) -> dict: + return { + "doc": { + "query": f"Q{ex_id}?", + "choices": ["A", "B"], + "gold_index": 0, + "id": ex_id, + "task_name": "gsm8k|0", + }, + "metric": {"acc": score}, + } + + +def test_lighteval_detects_valid_row_after_ten_malformed(): + # Rows 1–10 unusable; row 11 establishes the Lighteval shape. + raw = [{"not": "detail"} for _ in range(10)] + [_valid_detail("late")] + assert LightevalAdapter().detect(raw) + data = LightevalAdapter().parse(raw) + assert [ex.id for ex in data.examples] == ["gsm8k|0:late"] + # Ten non-detail mappings are counted as skipped input rows. + assert data.metadata["skipped_rows"] == 10 + + +def test_lighteval_task_grouped_detects_despite_malformed_first_item(): + grouped = { + "gsm8k|0": [ + "not-a-mapping", + {"doc": {"id": "bare"}, "metric": {"acc": 1.0}}, + _valid_detail("ok", 0.0), + ] + } + assert LightevalAdapter().detect(grouped) + data = LightevalAdapter().parse(grouped) + assert [ex.id for ex in data.examples] == ["gsm8k|0:ok"] + assert data.metadata["skipped_rows"] == 1 + + +def test_detect_routes_late_valid_row_and_task_grouped_to_lighteval(): + late = [{"x": i} for i in range(10)] + [_valid_detail("late")] + grouped = { + "gsm8k|0": [ + {"junk": True}, + _valid_detail("ok"), + ] + } + assert detect_adapter(late).source_format == "lighteval" + assert detect_adapter(grouped).source_format == "lighteval" + + +def test_lighteval_revalidates_fingerprint_on_every_row(): + # First row establishes detection; a later id+metric-only mapping must not + # become a canonical example. + raw = [ + _valid_detail("good"), + { + "doc": {"id": "incomplete", "task_name": "gsm8k|0"}, + "metric": {"acc": 1.0}, + }, + ] + assert LightevalAdapter().detect(raw) + data = LightevalAdapter().parse(raw) + assert [ex.id for ex in data.examples] == ["gsm8k|0:good"] + assert data.metadata["skipped_rows"] == 1 + + +# --------------------------------------------------------------------------- +# Registry integration +# --------------------------------------------------------------------------- + + +def test_detect_routes_lighteval_details_before_generic(): + assert detect_adapter(DETAILS).source_format == "lighteval" + + +def test_detect_aggregate_lighteval_raises_specific_error_not_unknown_format(): + adapter = detect_adapter(AGGREGATE) + assert adapter.source_format == "lighteval" + with pytest.raises(ValueError, match="aggregate"): + adapter.parse(AGGREGATE) + + +def test_no_earlier_adapter_claims_lighteval_details(): + assert not PromptfooAdapter().detect(DETAILS) + assert not DeepEvalAdapter().detect(DETAILS) + assert not InspectAdapter().detect(DETAILS) + assert not HelmAdapter().detect(DETAILS) + assert not NativeNestedAdapter().detect(DETAILS) + # Generic would claim any list of dicts; Lighteval must win in the registry. + assert GenericRecordsAdapter().detect(DETAILS) + assert detect_adapter(DETAILS).source_format == "lighteval"