Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 28 additions & 4 deletions examples/image_understanding/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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

Expand Down
22 changes: 22 additions & 0 deletions examples/image_understanding/configs/eval_tasks.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
47 changes: 41 additions & 6 deletions examples/image_understanding/evaluation/evaluator.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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.

Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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(
Expand Down
134 changes: 131 additions & 3 deletions examples/image_understanding/evaluation/scorers.py
Original file line number Diff line number Diff line change
Expand Up @@ -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``,
Expand Down Expand Up @@ -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
Expand All @@ -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]:
Expand Down Expand Up @@ -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"<answer\b[^<>]*>|(?<![\w</])answer>|\\boxed\s*\{", re.IGNORECASE)
Expand Down Expand Up @@ -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),
Expand Down
Loading
Loading