From 40f787ce934645e431e6f12e84a15c70cac37c6c Mon Sep 17 00:00:00 2001 From: amazloumi Date: Sun, 6 Dec 2026 02:14:59 -0500 Subject: [PATCH 1/2] Add a CIDEr-D scorer and the COCO Captions and Flickr30k caption tasks CIDEr-D weighs n-grams by document frequency over the whole split, so a scorer may now rate a split's rows together (Scorer.corpus), which the evaluator does on rank 0 once the ranks' records are merged. Each caption row records its own CIDEr-D under the split's weights, and the task's metric is their mean. Texts are split on whitespace as written. --- examples/image_understanding/README.md | 32 ++- .../configs/eval_tasks.toml | 22 ++ .../evaluation/evaluator.py | 47 +++- .../image_understanding/evaluation/scorers.py | 134 ++++++++++- .../cider_pycocoevalcap_scores.json | 131 +++++++++++ .../evaluation/test_evaluate_checkpoint.py | 2 + .../tests/evaluation/test_evaluator.py | 217 +++++++++++++++++- .../tests/evaluation/test_scorers.py | 90 ++++++++ .../tests/evaluation/test_tasks.py | 21 +- 9 files changed, 678 insertions(+), 18 deletions(-) create mode 100644 examples/image_understanding/tests/evaluation/cider_pycocoevalcap_scores.json diff --git a/examples/image_understanding/README.md b/examples/image_understanding/README.md index 84a6adcb4..8fb553387 100644 --- a/examples/image_understanding/README.md +++ b/examples/image_understanding/README.md @@ -508,8 +508,10 @@ skipped and nothing else cleaned up; the scorers normalize their own input. The predictions file keeps the raw `generation` beside it. A task's metrics are over its scored rows, with the counts beside them. A -missing image file, a task whose cap leaves no room for any prompt, or a task -with no scored row fails the run. +scorer that rates a split's rows together, as `cider` does, rates them on +rank 0 once they are merged, and each row's record then holds the score it got +among them. A missing image file, a task whose cap leaves no room for any +prompt, or a task with no scored row fails the run. ``` /your/results/dir/ @@ -695,6 +697,23 @@ scorer. a non-empty sequence of `str`; anything else raises before any scoring, naming the argument. `get_scorer` returns one by name; its `score` rates a sample and its `aggregate` turns a task's sample scores into the task's metrics. + - `cider` (COCO Captions, Flickr30k): CIDEr-D (Vedantam, Zitnick and Parikh, + CVPR 2015) with n-grams of one to four words and sigma 6: n-gram counts + weighted by inverse document frequency over the references of the split's + scored rows, compared for each n as a cosine with the prediction's counts + clipped to the reference's, a Gaussian penalty on the difference in length, + averaged over the references and the four n, times 10. The weights need + every row, so the rows are scored together on rank 0 once they are merged + (the scorer's `corpus`): each row's record holds its own CIDEr-D under the + split's weights, and the task's score, the mean of the rows', is the + split's CIDEr-D. It can exceed 1, and a split of one row scores 0. As in + the recipe, the prediction and the references are split on whitespace as + written, so case and punctuation count (`yak.` is not `yak`); the standard + COCO caption evaluation first lowercases them and drops punctuation with + its PTB tokenizer, so these numbers differ from its. On the same raw + strings they match pycocoevalcap's `Cider`. The `coco_captions` reader asks + each image the task's `prompt` and keeps all of its captions as the + references. - `vqa_accuracy` (VQAv2, TextVQA): each annotator is left out in turn, the prediction scores `min(1, m / 3)` against the `m` remaining annotators who gave the same answer, and the score is the mean over those rounds, after the @@ -750,7 +769,10 @@ scorer. - `choice_letter` (MMLU): 1 when the first standalone capital `A` to `D` is the reference letter. -`configs/eval_tasks.toml` is a sample with VQAv2 (10), the nine tasks of the +`configs/eval_tasks.toml` is a sample with COCO Captions (Karpathy val, 5,000 +images) and Flickr30k (val, 1,014 images), each capped at the recipe's 100 and +asked "Provide a short caption for the image.", as the training mixtures ask +for a caption, VQAv2 (10), the nine tasks of the board, with its caps: A-OKVQA 10, DocVQA 50, TextVQA 75, ChartQA human and machine 50, PixMo pointing 75 and counting 20, GSM8K 256 and MMLU 10, and RealWorldQA (16). The @@ -796,7 +818,9 @@ the pinned revision. A reader is an entry of `READERS` and a scorer an entry of `SCORERS`, so a new one is added there. A scorer may report several named components per sample and -aggregate them its own way; the default is the mean of each component. +aggregate them its own way; the default is the mean of each component. A scorer +whose sample scores depend on the whole split, as CIDEr-D's do, sets `corpus`, +which rates the split's scored rows together on rank 0. ## Roadmap diff --git a/examples/image_understanding/configs/eval_tasks.toml b/examples/image_understanding/configs/eval_tasks.toml index 0994e7185..34546eb9c 100644 --- a/examples/image_understanding/configs/eval_tasks.toml +++ b/examples/image_understanding/configs/eval_tasks.toml @@ -4,6 +4,28 @@ # layout its reader takes. The tasks after VQAv2 are the board's, with its # answer caps. +[[tasks]] +name = "coco-captions" +reader = "coco_captions" +scorer = "cider" +max_new_tokens = 100 + +[tasks.reader_args] +annotation_file = "path-to-coco-karpathy-val-annotations" +image_root = "path-to-coco-images" +prompt = "Provide a short caption for the image." + +[[tasks]] +name = "flickr30k" +reader = "coco_captions" +scorer = "cider" +max_new_tokens = 100 + +[tasks.reader_args] +annotation_file = "path-to-flickr30k-val-annotations" +image_root = "path-to-flickr30k-images" +prompt = "Provide a short caption for the image." + [[tasks]] name = "vqav2" reader = "vqav2" diff --git a/examples/image_understanding/evaluation/evaluator.py b/examples/image_understanding/evaluation/evaluator.py index 349b8513b..adde8ea8a 100644 --- a/examples/image_understanding/evaluation/evaluator.py +++ b/examples/image_understanding/evaluation/evaluator.py @@ -4,7 +4,8 @@ with the checkpoint's model, scores it with the task's scorer and writes the task metrics and the per-row predictions. Under several processes each rank decodes its own batches of a split and rank 0 merges them, so the results are -those of one process. +those of one process. A scorer that rates a split's rows together +(``Scorer.corpus``) rates them on rank 0 once they are merged. A row is scored as it is or counted under a reason, never changed to fit: @@ -209,7 +210,8 @@ def evaluate_batch( ``question``, reference ``answers``, the decoded ``generation``, the ``prediction`` that was scored (the generation with special tokens skipped), whether the decode ``stopped`` on a stop - token, and its ``score``. A skipped row records the reason under ``skipped``. + token, and its ``score``, which ``score_corpus`` replaces for a scorer that + rates the split's rows together. A skipped row records the reason under ``skipped``. The rows are read and rendered by ``pool``, or by the calling thread without one. A reader with a ``reference`` method gives each row's reference to score @@ -268,6 +270,35 @@ def merge_records(per_rank: Sequence[Sequence[Record]], rows: int) -> list[Recor return merged +def score_corpus(task: EvalTask, reader: DocumentSource, records: Sequence[Record]) -> list[Record]: + """``records`` with the scores of a scorer that rates the split's rows together. + + A scorer with a ``corpus`` (``cider``) rates the scored rows of ``records`` + together, in row order, from each row's ``prediction`` and its reference as + ``evaluate_batch`` scores it: ``reader.reference(row)`` for a reader with a + ``reference`` method, else the row's ``answers``. Each scored row then + holds the score ``corpus`` gave it; the input records are not changed. The + records of any other scorer are returned as they are. + """ + corpus = get_scorer(task.scorer).corpus + if corpus is None: + return list(records) + reference = getattr(reader, "reference", None) + scored = [record for record in records if "skipped" not in record] + scores = corpus( + [record["prediction"] for record in scored], + [record["answers"] if reference is None else reference(_row(record)) for record in scored], + ) + by_row = { + _row(record): dict(score) if isinstance(score, Mapping) else score + for record, score in zip(scored, scores, strict=True) + } + return [ + {**record, "score": by_row[_row(record)]} if _row(record) in by_row else record + for record in records + ] + + def summarize(task: EvalTask, records: Sequence[Record]) -> Record: """The report of ``task`` from its rows' records: counts, skips by reason and metrics. @@ -384,7 +415,7 @@ def evaluate_checkpoint( ) summary = _on_rank_zero( rank, - partial(_finish_task, task, _gather(records), len(reader), output), + partial(_finish_task, task, reader, _gather(records), output), f"Writing the results of task {task.name!r}", ) if summary is not None: @@ -593,10 +624,14 @@ def _start(output: Path, checkpoint: str | Path) -> str: def _finish_task( - task: EvalTask, per_rank: Sequence[Sequence[Record]], rows: int, output: Path + task: EvalTask, reader: DocumentSource, per_rank: Sequence[Sequence[Record]], output: Path ) -> Record: - """Merge the ranks' records of ``task``, write its predictions and return its report.""" - records = merge_records(per_rank, rows) + """Merge the ranks' records of ``task``, write its predictions and return its report. + + The merged records are scored together first when the task's scorer rates + the split's rows together (``score_corpus``). + """ + records = score_corpus(task, reader, merge_records(per_rank, len(reader))) summary = summarize(task, records) predictions = Path(PREDICTIONS_DIR) / f"{task.name}.jsonl" _write_whole( diff --git a/examples/image_understanding/evaluation/scorers.py b/examples/image_understanding/evaluation/scorers.py index 30ae9dd2c..9333feaf0 100644 --- a/examples/image_understanding/evaluation/scorers.py +++ b/examples/image_understanding/evaluation/scorers.py @@ -7,8 +7,11 @@ ``str``; anything else raises before any scoring (``TypeError``, or ``ValueError`` for no reference). A sample's score is one value in [0, 1], or a mapping of named components for a scorer that -reports several (an error component may exceed 1). A task's metrics are the -scorer's aggregate of its samples' scores, by default the mean of each component. +reports several (an error component may exceed 1), but for ``cider``: CIDEr-D +weighs n-grams over the whole split, so a split's samples are scored together +(``Scorer.corpus``), and a sample's CIDEr-D may exceed 1. A task's metrics are +the scorer's aggregate of its samples' scores, by default the mean of each +component. ``extract_mcq_answer`` and the code it calls (``_Choice``, ``_word_character``, ``_starts_with_alternative``, ``_read_choice``, ``_has_alternative``, @@ -43,9 +46,11 @@ from __future__ import annotations +import math import re import statistics import unicodedata +from collections import Counter from collections.abc import Callable, Iterable, Mapping, Sequence from dataclasses import dataclass, field from typing import Any, NamedTuple @@ -61,6 +66,9 @@ RELAXED_TOLERANCE = 0.05 ZERO_TARGET_GUARD = 1e-10 REALWORLDQA_CHOICES: tuple[str, ...] = ("A", "B", "C", "D") +CIDER_MAX_N = 4 +CIDER_SIGMA = 6.0 +CIDER_SCALE = 10.0 def _references(prediction: str, answers: Sequence[str]) -> Sequence[str]: @@ -336,6 +344,120 @@ def choice_letter(prediction: str, answers: Sequence[str]) -> float: return float(letter is not None and letter.group(1) == reference) +_NGram = tuple[str, ...] + + +class _Caption(NamedTuple): + """A text as CIDEr-D compares it: weighted n-gram counts, their norm for each n, length.""" + + vector: dict[_NGram, float] + norms: tuple[float, ...] + length: int + + +def _ngram_counts(text: str) -> Counter[_NGram]: + """How often each run of 1 to ``CIDER_MAX_N`` whitespace-separated words of ``text`` occurs.""" + words = text.split() + return Counter( + tuple(words[start : start + n]) + for n in range(1, CIDER_MAX_N + 1) + for start in range(len(words) - n + 1) + ) + + +def _caption(counts: Counter[_NGram], weights: Mapping[_NGram, float], rarest: float) -> _Caption: + """``counts`` times the weight of each n-gram, ``rarest`` for one ``weights`` does not hold.""" + vector = {ngram: count * weights.get(ngram, rarest) for ngram, count in counts.items()} + squares = [0.0] * CIDER_MAX_N + for ngram, value in vector.items(): + squares[len(ngram) - 1] += value * value + length = sum(count for ngram, count in counts.items() if len(ngram) == 1) + return _Caption(vector, tuple(math.sqrt(square) for square in squares), length) + + +def _cider_similarity(candidate: _Caption, reference: _Caption) -> float: + """The mean over n of the clipped similarity to ``reference``, times the length penalty.""" + shared = [0.0] * CIDER_MAX_N + for ngram, value in candidate.vector.items(): + in_reference = reference.vector.get(ngram, 0.0) + shared[len(ngram) - 1] += min(value, in_reference) * in_reference + per_n = [ + overlap / (norm * other) if norm and other else 0.0 + for overlap, norm, other in zip(shared, candidate.norms, reference.norms, strict=True) + ] + penalty = math.exp(-((candidate.length - reference.length) ** 2) / (2 * CIDER_SIGMA**2)) + return penalty * statistics.fmean(per_n) + + +def cider_d(predictions: Sequence[str], references: Sequence[Sequence[str]]) -> list[float]: + """CIDEr-D of each prediction against its references, with the n-gram weights of the split. + + Prediction ``i`` is scored against ``references[i]``. The samples are a + split's, and the weights come from all of them, so a sample's score + depends on the others but not on their order. This is the CIDEr-D of + Vedantam, Zitnick and Parikh ("CIDEr: Consensus-based Image Description + Evaluation", CVPR 2015, equations 4 and 5) as pycocoevalcap's ``Cider`` + computes it from the raw strings: a text is split on whitespace as written, + as the recipe scores captions, so case and punctuation count (``yak.`` is + not ``yak``). The standard COCO caption evaluation first lowercases the + texts and drops their punctuation with the PTB tokenizer, so these numbers + differ from its. + + For n from 1 to 4, a text's vector holds the count of each of its n-grams + (the paper's equation 1 divides it by the text's count of all n-grams) + times the n-gram's weight ``log(N / df)``, where ``N`` is the number of + samples and ``df`` the number whose references hold the n-gram, or 1 for + an n-gram in no reference. Against one reference, the similarity for n is + the sum over the prediction's n-grams of the smaller of the two weighted + counts times the reference's, so a repeated n-gram counts at most as often + as the reference holds it, over the product of the two vectors' norms, or + 0 when either is 0; it is scaled by ``exp(-d**2 / (2 * 6**2))``, where + ``d`` is the difference of the two lengths in words. A sample's CIDEr-D is + 10 times the mean of these over n and over its references, and a split's + is the mean of its samples'. In a split of one sample every weight is + ``log 1``, so it scores 0, as does an empty prediction in any split. An + empty split has no scores. + + Raises: + TypeError: a prediction is not a ``str``, or its references are not a + sequence of ``str``. + ValueError: a prediction has no reference, or ``predictions`` and + ``references`` differ in length. + """ + samples = [] + for prediction, answers in zip(predictions, references, strict=True): + texts = _references(prediction, answers) + samples.append((_ngram_counts(prediction), [_ngram_counts(text) for text in texts])) + if not samples: + return [] + frequency: Counter[_NGram] = Counter() + for _, reference_counts in samples: + frequency.update({ngram for counts in reference_counts for ngram in counts}) + rarest = math.log(len(samples)) + weights = {ngram: rarest - math.log(df) for ngram, df in frequency.items()} + scores = [] + for prediction_counts, reference_counts in samples: + candidate = _caption(prediction_counts, weights, rarest) + similarities = [ + _cider_similarity(candidate, _caption(counts, weights, rarest)) + for counts in reference_counts + ] + scores.append(CIDER_SCALE * statistics.fmean(similarities)) + return scores + + +def cider(prediction: str, answers: Sequence[str]) -> float: + """CIDEr-D of one sample scored alone, as a split of its own: always 0. + + Every weight of a split of one sample is ``log 1`` (see ``cider_d``). The + rows of a ``cider`` task are scored together once they are all decoded, by + ``cider_d`` as the scorer's ``corpus``; this checks a row's inputs as it is + decoded, as the other text scorers do, raising ``TypeError`` or + ``ValueError``. + """ + return cider_d([prediction], [answers])[0] + + _DEFAULT_CHOICES = list("ABCDEFGH") _CONTAINER_START = re.compile(r"]*>|(?|\\boxed\s*\{", re.IGNORECASE) @@ -737,16 +859,22 @@ class Scorer: ``score(prediction, reference)`` rates one sample from its decoded text and its reference, and returns one value or a mapping of named components. ``aggregate`` reduces the sequence of a task's sample scores to its metrics by - name, by default the mean of each component. + name, by default the mean of each component. ``corpus``, when set, rates a + split's samples together, for a metric whose sample scores depend on the + whole split: ``corpus(predictions, references)`` takes the split's scored + samples in row order and returns their scores, in that order, which the + evaluator puts in place of those ``score`` gave before it aggregates them. """ score: Callable[[str, Any], SampleScore] aggregate: Callable[[Sequence[Any]], dict[str, float]] = field(default=mean_scores) + corpus: Callable[[Sequence[str], Sequence[Any]], Sequence[SampleScore]] | None = None SCORERS: dict[str, Scorer] = { "anls": Scorer(anls), "choice_letter": Scorer(choice_letter), + "cider": Scorer(cider, corpus=cider_d), "count_accuracy": Scorer(count_accuracy), "exact_vqa_accuracy": Scorer(exact_vqa_accuracy), "final_number": Scorer(final_number), diff --git a/examples/image_understanding/tests/evaluation/cider_pycocoevalcap_scores.json b/examples/image_understanding/tests/evaluation/cider_pycocoevalcap_scores.json new file mode 100644 index 000000000..bd6b8b4f1 --- /dev/null +++ b/examples/image_understanding/tests/evaluation/cider_pycocoevalcap_scores.json @@ -0,0 +1,131 @@ +{ + "source": "pycocoevalcap 1.2 from PyPI: pycocoevalcap.cider.cider.Cider() at its defaults (n=4, sigma=6.0), compute_score given each split's raw strings, no tokenizer; numpy 2.5.5, Python 3.12.11", + "splits": [ + { + "name": "captions", + "score": 1.7992932825682304, + "rows": [ + { + "case": "case and punctuation count", + "prediction": "A child pets a yak.", + "references": [ + "a child pets a yak", + "A boy with an umbrella touches a yak.", + "a child petting a yak in a field" + ], + "score": 1.8455347787832244 + }, + { + "case": "a repeated n-gram is clipped", + "prediction": "a cat a cat a cat a cat", + "references": [ + "a cat sits on a mat", + "a small cat on a mat", + "the cat is sitting on a red mat" + ], + "score": 0.41195350370521605 + }, + { + "case": "n-grams in no reference", + "prediction": "a horse grazing beside a purple tower", + "references": [ + "a horse grazing in a green field", + "a brown horse eats grass in a field", + "horses grazing near a fence" + ], + "score": 1.1303179213722439 + }, + { + "case": "a one-word prediction", + "prediction": "horses", + "references": [ + "two horses standing in a field next to a wooden fence", + "horses grazing on the grass of a large field", + "a pair of horses in a pasture" + ], + "score": 0.41276672590442703 + }, + { + "case": "a long prediction", + "prediction": "a man in a red shirt rides a bicycle down a long road past a row of trees while cars drive by on the other side", + "references": [ + "a man rides a bicycle down the road", + "a cyclist in a red shirt on a road", + "a man riding a bike" + ], + "score": 0.019487915786761068 + }, + { + "case": "one reference", + "prediction": "two birds sit on a wire", + "references": [ + "two birds sitting on a power line" + ], + "score": 1.612412004979675 + }, + { + "case": "five references", + "prediction": "a plate of food with rice and vegetables", + "references": [ + "a plate of rice and vegetables", + "a white plate holding rice, broccoli and carrots", + "food on a plate with a fork", + "a meal of rice and steamed vegetables", + "a dinner plate with rice and some vegetables on it" + ], + "score": 2.3179590228407227 + }, + { + "case": "an empty prediction", + "prediction": "", + "references": [ + "a red bus parked on a city street", + "a double decker bus by the road" + ], + "score": 0.0 + }, + { + "case": "runs of whitespace separate words", + "prediction": " a red bus\tparked on\na city street ", + "references": [ + "a red bus parked on a city street", + "a bus at the curb of a busy street" + ], + "score": 5.340816464410532 + }, + { + "case": "a one-word reference", + "prediction": "a dog catches a frisbee", + "references": [ + "frisbee", + "a dog jumps to catch a frisbee in the park" + ], + "score": 1.3115832868945807 + }, + { + "case": "the prediction is a reference", + "prediction": "a man holding an umbrella in the rain", + "references": [ + "a man holding an umbrella in the rain", + "a person with an umbrella walks down a wet street" + ], + "score": 5.389394483573153 + } + ] + }, + { + "name": "one row", + "score": 0.0, + "rows": [ + { + "case": "one reference", + "prediction": "two birds sit on a wire", + "references": [ + "two birds sitting on a power line" + ], + "score": 0.0 + } + ] + } + ] +} diff --git a/examples/image_understanding/tests/evaluation/test_evaluate_checkpoint.py b/examples/image_understanding/tests/evaluation/test_evaluate_checkpoint.py index 55f941aac..980f9fa80 100644 --- a/examples/image_understanding/tests/evaluation/test_evaluate_checkpoint.py +++ b/examples/image_understanding/tests/evaluation/test_evaluate_checkpoint.py @@ -65,6 +65,8 @@ def test_the_loaded_config_and_tasks_are_handed_off( ) assert seen["config"].train.max_steps == 1 assert [task.name for task in seen["tasks"]] == [ + "coco-captions", + "flickr30k", "vqav2", "textvqa", "docvqa", diff --git a/examples/image_understanding/tests/evaluation/test_evaluator.py b/examples/image_understanding/tests/evaluation/test_evaluator.py index 62f6dffce..cb48ee344 100644 --- a/examples/image_understanding/tests/evaluation/test_evaluator.py +++ b/examples/image_understanding/tests/evaluation/test_evaluator.py @@ -8,13 +8,13 @@ import statistics import threading import time -from collections.abc import Callable +from collections.abc import Callable, Sequence from concurrent.futures import ThreadPoolExecutor from contextlib import ExitStack from dataclasses import dataclass from functools import partial from pathlib import Path -from types import SimpleNamespace +from types import MappingProxyType, SimpleNamespace from typing import Any import pytest @@ -35,6 +35,7 @@ evaluate_checkpoint, merge_records, read_row, + score_corpus, shard_batches, summarize, token_budgets, @@ -46,7 +47,7 @@ build_renderer, document_inputs, ) -from evaluation.scorers import SCORERS, Scorer, anls +from evaluation.scorers import SCORERS, Scorer, anls, cider_d from evaluation.tasks import READERS, EvalTask, build_reader, load_tasks from image_text.document import Document, Turn from image_text.render import ChatRenderer, UnrenderableDocumentError @@ -569,6 +570,163 @@ def test_a_task_with_no_scored_row_is_refused(self) -> None: summarize(self.TASK, records) +CAPTION_PROMPT = "what is shown in the image ?" +OTHER_CAPTIONS = ( + "a red square", + "a blue circle left of a green square", + "two big dogs and one small cat", + "it is a bird", + "a small blue square", +) + + +def _caption_task( + tmp_path: Path, captions: Sequence[Sequence[str]], name: str = "captions" +) -> Path: + """Writes a split in the Karpathy val layout, image ``i`` with ``captions[i]``, and its task.""" + root = tmp_path / name + root.mkdir() + rows = [] + for row, texts in enumerate(captions): + Image.new("RGB", (8, 6), (40 * row % 256, 90, 25 * row % 256)).save(root / f"{row}.png") + rows.append({"image": f"{row}.png", "caption": list(texts)}) + (root / "annotations.json").write_text(json.dumps(rows)) + path = tmp_path / f"{name}.toml" + path.write_text( + f'[[tasks]]\nname = "{name}"\nreader = "coco_captions"\nscorer = "cider"\n' + f"max_new_tokens = 6\n\n[tasks.reader_args]\n" + f'annotation_file = "{root / "annotations.json"}"\nimage_root = "{root}"\n' + f'prompt = "{CAPTION_PROMPT}"\n' + ) + return path + + +def _captions_with_the_runs_own(run: Run, tmp_path: Path, rows: int) -> list[list[str]]: + """Five captions for each of ``rows`` images, one of them the run's own for every second image. + + The run's caption of an image is what it decodes for it, so those rows share + n-grams with their references and score above 0. + """ + first = _caption_task(tmp_path, [OTHER_CAPTIONS] * rows, name="first") + _evaluate(run, first, tmp_path / "first-results") + records = _predictions(tmp_path / "first-results", "first") + decoded = [record["prediction"].strip() for record in records] + own = [row for row in range(0, rows, 2) if decoded[row]] + assert own + return [ + [decoded[row], *OTHER_CAPTIONS[1:]] if row in own else list(OTHER_CAPTIONS) + for row in range(rows) + ] + + +class TestScoreCorpus: + CAPTIONS = EvalTask( + "captions", + "coco_captions", + "cider", + 6, + {"annotation_file": "a", "image_root": "b", "prompt": CAPTION_PROMPT}, + ) + RECORDS = ( + { + "row": 0, + "prediction": "a red square", + "answers": ["a red square", "a square"], + "score": 0.0, + "stopped": True, + }, + {"row": 1, "skipped": UNREADABLE_ROW}, + { + "row": 2, + "prediction": "a blue circle", + "answers": ["a blue circle"], + "score": 0.0, + "stopped": False, + }, + { + "row": 3, + "prediction": "two dogs", + "answers": ["one cat", "two dogs"], + "score": 0.0, + "stopped": True, + }, + ) + + def _with(self, monkeypatch: pytest.MonkeyPatch, scorer: Scorer) -> EvalTask: + monkeypatch.setitem(SCORERS, "together", scorer) + return dataclasses.replace(self.CAPTIONS, scorer="together") + + def test_the_scored_rows_are_scored_together_and_the_skipped_ones_kept(self) -> None: + records = [dict(record) for record in self.RECORDS] + rescored = score_corpus(self.CAPTIONS, [], records) + scored = [records[0], records[2], records[3]] + expected = cider_d([r["prediction"] for r in scored], [r["answers"] for r in scored]) + assert min(expected) > 0.0 + assert [record.get("score") for record in rescored] == [ + expected[0], + None, + expected[1], + expected[2], + ] + assert [{**r, "score": 0.0} if "score" in r else r for r in rescored] == records + assert records == list(self.RECORDS) + + def test_a_scorer_without_a_corpus_leaves_the_records_as_they_are(self) -> None: + assert score_corpus(TestSummarize.TASK, [], self.RECORDS) == list(self.RECORDS) + + def test_a_reader_with_references_is_scored_against_them( + self, monkeypatch: pytest.MonkeyPatch + ) -> None: + class Referenced(list): + def reference(self, row: int) -> list[str]: + return [f"reference {row}"] + + seen: list[Any] = [] + + def corpus(predictions: Sequence[str], references: Sequence[Any]) -> list[float]: + seen.append((list(predictions), list(references))) + return [1.0] * len(predictions) + + task = self._with(monkeypatch, Scorer(lambda prediction, reference: 0.0, corpus=corpus)) + rescored = score_corpus(task, Referenced(), self.RECORDS) + assert seen == [ + ( + ["a red square", "a blue circle", "two dogs"], + [["reference 0"], ["reference 2"], ["reference 3"]], + ) + ] + assert [record.get("score") for record in rescored] == [1.0, None, 1.0, 1.0] + + def test_a_corpus_may_score_named_components(self, monkeypatch: pytest.MonkeyPatch) -> None: + def corpus(predictions: Sequence[str], references: Sequence[Any]) -> list[Any]: + return [MappingProxyType({"exact": 1.0, "close": 0.5})] * len(predictions) + + task = self._with(monkeypatch, Scorer(lambda prediction, reference: {}, corpus=corpus)) + rescored = score_corpus(task, [], self.RECORDS) + assert [record.get("score") for record in rescored] == [ + {"exact": 1.0, "close": 0.5}, + None, + {"exact": 1.0, "close": 0.5}, + {"exact": 1.0, "close": 0.5}, + ] + assert json.loads(json.dumps(rescored)) == rescored + assert summarize(task, rescored)["metrics"] == {"exact": 1.0, "close": 0.5} + + def test_a_corpus_must_score_every_scored_row(self, monkeypatch: pytest.MonkeyPatch) -> None: + task = self._with( + monkeypatch, + Scorer(lambda prediction, reference: 0.0, corpus=lambda predictions, references: [1.0]), + ) + with pytest.raises(ValueError): + score_corpus(task, [], self.RECORDS) + + def test_a_split_with_no_scored_row_is_left_for_summarize_to_refuse(self) -> None: + records = [{"row": 0, "skipped": UNREADABLE_ROW}] + assert score_corpus(self.CAPTIONS, [], records) == records + with pytest.raises(ValueError, match="task 'captions': none of its 1 rows was scored"): + summarize(self.CAPTIONS, records) + + class TestClearResults: def test_rank_zero_removes_the_marker_and_other_ranks_leave_it( self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch @@ -873,6 +1031,46 @@ def test_the_shards_of_any_number_of_ranks_merge_into_one_ranks_records( summary = {**summarize(task, merged), "predictions": "predictions/docvqa.jsonl"} assert summary == reference["tasks"]["docvqa"] + def test_a_caption_task_scores_its_rows_with_the_weights_of_the_whole_split( + self, run: Run, tmp_path: Path + ) -> None: + captions = _captions_with_the_runs_own(run, tmp_path, rows=6) + output = tmp_path / "results" + results = _evaluate(run, _caption_task(tmp_path, captions), output, batch_size=4) + rows = _predictions(output, "captions") + scores = cider_d([row["prediction"] for row in rows], [row["answers"] for row in rows]) + assert [(row["question"], row["answers"]) for row in rows] == [ + (CAPTION_PROMPT, texts) for texts in captions + ] + assert [row["score"] for row in rows] == scores + assert max(scores) > 0.0 + assert results["tasks"]["captions"]["metrics"] == {"score": statistics.fmean(scores)} + assert json.loads((output / "metrics.json").read_text()) == { + "captions/score": statistics.fmean(scores) + } + + @pytest.mark.parametrize(("world_size", "batch_size"), [(2, 1), (3, 2)]) + def test_the_shards_of_any_number_of_ranks_score_a_caption_task_as_one_rank( + self, run: Run, tmp_path: Path, world_size: int, batch_size: int + ) -> None: + tasks = _caption_task(tmp_path, _captions_with_the_runs_own(run, tmp_path, rows=7)) + reference = _evaluate(run, tasks, tmp_path / "reference", batch_size=4) + (task,) = load_tasks(tasks) + per_rank = [ + [ + record + for batch in shard_batches(7, batch_size, rank, world_size) + for record in _batch_records(run, tasks, batch) + ] + for rank in range(world_size) + ] + merged = merge_records(per_rank, 7) + assert {record["score"] for record in merged} == {0.0} + rescored = score_corpus(task, build_reader(task), merged) + assert rescored == _predictions(tmp_path / "reference", "captions") + summary = {**summarize(task, rescored), "predictions": "predictions/captions.jsonl"} + assert summary == reference["tasks"]["captions"] + def test_an_unsupported_config_is_refused_before_anything_is_read( self, write_config: Callable[..., Path], write_task: Callable[..., Path], tmp_path: Path ) -> None: @@ -1307,6 +1505,19 @@ def test_several_ranks_write_what_one_process_writes( json.loads((output / "metrics.json").read_text()), ] + def test_two_ranks_score_a_caption_task_as_one_process(self, run: Run, tmp_path: Path) -> None: + """Rank 0 scores the merged rows together, so the split's weights are one process's.""" + tasks = _caption_task(tmp_path, _captions_with_the_runs_own(run, tmp_path, rows=7)) + _evaluate(run, tasks, tmp_path / "one" / "results", batch_size=2) + output = tmp_path / "ranks" / "results" + output.parent.mkdir() + assert _spawn_ranks(2, run, tasks, output) == ["finished"] * 2 + for name in ("results.json", "metrics.json", "predictions/captions.jsonl"): + assert (output / name).read_bytes() == ( + tmp_path / "one" / "results" / name + ).read_bytes() + assert max(row["score"] for row in _predictions(output, "captions")) > 0.0 + def test_a_finished_rank_skips_the_interpreter_shutdown( self, run: Run, write_task: Callable[..., Path], tmp_path: Path ) -> None: diff --git a/examples/image_understanding/tests/evaluation/test_scorers.py b/examples/image_understanding/tests/evaluation/test_scorers.py index b0306f610..c5dfa6c9a 100644 --- a/examples/image_understanding/tests/evaluation/test_scorers.py +++ b/examples/image_understanding/tests/evaluation/test_scorers.py @@ -15,6 +15,8 @@ Scorer, anls, choice_letter, + cider, + cider_d, count_accuracy, exact_vqa_accuracy, final_number, @@ -40,6 +42,10 @@ LMMS_EVAL_SCORES = json.loads( Path(__file__).with_name("realworldqa_lmms_eval_scores.json").read_text(encoding="utf-8") ) +PYCOCOEVALCAP_CIDER = json.loads( + Path(__file__).with_name("cider_pycocoevalcap_scores.json").read_text(encoding="utf-8") +) +ROUNDING = {"rel": 1e-12, "abs": 1e-15} def _votes(matching: int, total: int) -> list[str]: @@ -566,3 +572,87 @@ def test_any_matching_reference_counts(self) -> None: assert realworldqa_accuracy("B", ["A", "B"]) == 1.0 assert realworldqa_accuracy("Downhill.", ("A", "Downhill")) == 1.0 assert realworldqa_accuracy("C", ("A", "B")) == 0.0 + + +class TestCIDEr: + """``cider_d`` against the CIDEr-D pycocoevalcap gives, and ``cider``'s checks. + + ``cider_pycocoevalcap_scores.json`` holds two splits of fixed captions with + the score pycocoevalcap's ``Cider`` gives each row and each split from the + raw strings, with no tokenizer; its ``source`` names the versions. The rows + are cases: case and punctuation, a repeated n-gram, n-grams in no + reference, a one-word and a long prediction, one, two, three and five + references, an empty prediction, runs of whitespace, a one-word reference + and a prediction equal to a reference. The second split is one of those + rows alone. The scores match to within rounding, a relative difference of + at most 1e-12 (``ROUNDING``). + """ + + SPLITS = PYCOCOEVALCAP_CIDER["splits"] + + def test_the_table_holds_every_case(self) -> None: + captions, alone = self.SPLITS + cases = [row["case"] for row in captions["rows"]] + assert len(cases) == len(set(cases)) == 11 + assert sorted({len(row["references"]) for row in captions["rows"]}) == [1, 2, 3, 5] + assert [row["prediction"] for row in captions["rows"] if not row["prediction"]] == [""] + (row,) = alone["rows"] + (same,) = [other for other in captions["rows"] if other["case"] == row["case"]] + assert (row["prediction"], row["references"]) == (same["prediction"], same["references"]) + assert row["score"] == alone["score"] == 0.0 < same["score"] + + @pytest.mark.parametrize("split", SPLITS, ids=lambda split: split["name"]) + def test_every_row_and_split_scores_as_in_pycocoevalcap(self, split: dict[str, Any]) -> None: + rows = split["rows"] + scores = cider_d([row["prediction"] for row in rows], [row["references"] for row in rows]) + assert scores == pytest.approx([row["score"] for row in rows], **ROUNDING) + assert get_scorer("cider").aggregate(scores) == { + "score": pytest.approx(split["score"], **ROUNDING) + } + + def test_case_and_punctuation_count(self) -> None: + scores = cider_d(["a yak", "a yak.", "two dogs"], [["a yak"], ["a yak"], ["two dogs"]]) + assert scores[0] == pytest.approx(5.0) == scores[2] + assert 0.0 < scores[1] < scores[0] + + def test_the_order_of_the_rows_does_not_matter(self) -> None: + rows = self.SPLITS[0]["rows"] + predictions = [row["prediction"] for row in rows] + references = [row["references"] for row in rows] + backwards = cider_d(predictions[::-1], references[::-1]) + assert backwards == cider_d(predictions, references)[::-1] + + def test_a_sample_alone_scores_zero(self) -> None: + assert cider("a red bus", ["a red bus"]) == 0.0 + assert cider_d(["a red bus"], [["a red bus", "a bus"]]) == [0.0] + + def test_an_empty_split_has_no_scores(self) -> None: + assert cider_d([], []) == [] + + @pytest.mark.parametrize( + ("prediction", "answers", "error", "message"), + [ + (None, ["a dog"], TypeError, "prediction must be a str"), + (b"a dog", ["a dog"], TypeError, "prediction must be a str"), + ("a dog", "a dog", TypeError, "not one string"), + ("a dog", {"a dog"}, TypeError, "answers must be a sequence of str"), + ("a dog", ["a dog", 3], TypeError, r"answers\[1\] must be a str"), + ("a dog", [], ValueError, "at least one reference answer"), + ], + ) + def test_inputs_are_checked_as_by_the_other_text_scorers( + self, prediction: Any, answers: Any, error: type[Exception], message: str + ) -> None: + with pytest.raises(error, match=message): + cider(prediction, answers) + with pytest.raises(error, match=message): + cider_d(["a cat", prediction], [["a cat"], answers]) + + def test_each_prediction_needs_its_references(self) -> None: + with pytest.raises(ValueError): + cider_d(["a dog", "a cat"], [["a dog"]]) + + def test_the_scorer_rates_a_split_together_and_averages_the_rows(self) -> None: + scorer = get_scorer("cider") + assert (scorer.score, scorer.corpus, scorer.aggregate) == (cider, cider_d, mean_scores) + assert [name for name, other in SCORERS.items() if other.corpus is not None] == ["cider"] diff --git a/examples/image_understanding/tests/evaluation/test_tasks.py b/examples/image_understanding/tests/evaluation/test_tasks.py index b1e98c424..8b7ee7da8 100644 --- a/examples/image_understanding/tests/evaluation/test_tasks.py +++ b/examples/image_understanding/tests/evaluation/test_tasks.py @@ -5,6 +5,7 @@ import functools import json import re +import tomllib from dataclasses import FrozenInstanceError from pathlib import Path from typing import Any, Optional @@ -16,6 +17,9 @@ from PIL import Image SAMPLE = Path(__file__).resolve().parents[2] / "configs" / "eval_tasks.toml" +TRAINING_MIXTURE = ( + Path(__file__).resolve().parents[2] / "mixtures" / "stage2_testbed_finevision_pixmo_text.toml" +) TASK = """\ [[tasks]] @@ -150,6 +154,8 @@ def test_it_holds_vqav2_and_the_boards_tasks_with_their_caps(self) -> None: (task.name, task.reader, task.scorer, task.max_new_tokens) for task in load_tasks(SAMPLE) ] == [ + ("coco-captions", "coco_captions", "cider", 100), + ("flickr30k", "coco_captions", "cider", 100), ("vqav2", "vqav2", "vqa_accuracy", 10), ("textvqa", "textvqa", "vqa_accuracy", 75), ("docvqa", "docvqa", "anls", 50), @@ -168,11 +174,22 @@ def test_its_paths_are_placeholders(self) -> None: for task in load_tasks(SAMPLE): text_only = task.reader in ("gsm8k", "mmlu") default = {"annotation_file"} if text_only else {"annotation_file", "image_root"} - assert set(task.reader_args) == own.get(task.reader, default) - for value in task.reader_args.values(): + paths = {key: value for key, value in task.reader_args.items() if key != "prompt"} + assert set(paths) == own.get(task.reader, default) + for value in paths.values(): assert Path(value).parent == SAMPLE.parent assert Path(value).name.startswith("path-to-") + def test_the_caption_tasks_ask_for_a_caption_as_training_does(self) -> None: + sources = tomllib.loads(TRAINING_MIXTURE.read_text())["source"] + (trained,) = [source["prompt"] for source in sources if source["reader"] == "coco_captions"] + asked = { + task.name: task.reader_args.get("prompt") + for task in load_tasks(SAMPLE) + if task.reader == "coco_captions" or "prompt" in task.reader_args + } + assert asked == {"coco-captions": trained, "flickr30k": trained} + def _relative_task(annotation_file: str, image_root: str) -> str: return TASK.replace('"ann.json"', f'"{annotation_file}"').replace('"images"', f'"{image_root}"') From 2bf0d2c88b7a7924766494f8b72f769598e68ea3 Mon Sep 17 00:00:00 2001 From: amazloumi Date: Sun, 6 Dec 2026 04:15:30 -0500 Subject: [PATCH 2/2] Test that case counts in CIDEr-D with a capitalized prediction The case and punctuation test had no capital letter, so lowercasing the texts before the whitespace split left it green, and only the fixture row caught that. A prediction "A yak" against the reference "a yak" now has to score above 0 and below the exact match. --- .../image_understanding/tests/evaluation/test_scorers.py | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/examples/image_understanding/tests/evaluation/test_scorers.py b/examples/image_understanding/tests/evaluation/test_scorers.py index c5dfa6c9a..460417faa 100644 --- a/examples/image_understanding/tests/evaluation/test_scorers.py +++ b/examples/image_understanding/tests/evaluation/test_scorers.py @@ -611,9 +611,13 @@ def test_every_row_and_split_scores_as_in_pycocoevalcap(self, split: dict[str, A } def test_case_and_punctuation_count(self) -> None: - scores = cider_d(["a yak", "a yak.", "two dogs"], [["a yak"], ["a yak"], ["two dogs"]]) - assert scores[0] == pytest.approx(5.0) == scores[2] + scores = cider_d( + ["a yak", "A yak", "a yak.", "two dogs"], + [["a yak"], ["a yak"], ["a yak"], ["two dogs"]], + ) + assert scores[0] == pytest.approx(5.0) == scores[3] assert 0.0 < scores[1] < scores[0] + assert 0.0 < scores[2] < scores[0] def test_the_order_of_the_rows_does_not_matter(self) -> None: rows = self.SPLITS[0]["rows"]