|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
"""Evaluator for simple VQA variants (OCR-VQA, OKVQA, A-OKVQA). |
|
|
|
According to the (A-)OKVAQ papers, the eval for these datasets should follow |
|
VQAv2. But here we don't track different answer-types, and don't do any |
|
leave-one-out averaging, as this isn't done in the official implementation at |
|
https://github.com/allenai/aokvqa/blob/main/evaluation/eval_predictions.py |
|
either. |
|
|
|
Please read the description of how evaluators work at (internal link). |
|
This evaluator follows the pattern of also parallelizing the CPU computations |
|
(ie postprocessing, score computation) across hosts for more scalability. |
|
|
|
For now, simple decoding is implemented as part of the evaluator. We'll soon |
|
unify and move to a library of decoding functions, including fancier and more |
|
efficient ones. |
|
""" |
|
import functools |
|
|
|
import big_vision.evaluators.common as c |
|
import big_vision.pp.tokenizer |
|
import big_vision.utils as u |
|
import editdistance |
|
|
|
|
|
|
|
|
|
API = "jit" |
|
|
|
|
|
class Evaluator: |
|
"""Evaluator for simple VQA tasks. |
|
|
|
This evaluator expects the batch to contain a field `question_id` and a field |
|
`answer` for single ground truth or `answers` for multiple ground truths. |
|
|
|
The field names used when writting the json result can be controlled with |
|
`out_question_key` and `out_answer_key`. |
|
""" |
|
|
|
def __init__( |
|
self, predict_fn, tokenizer, to_lower=False, |
|
outfile="{workdir}/{split}.json", |
|
out_question_key="question_id", out_answer_key="answer", |
|
*, data, devices, **kw): |
|
self.get_data_iter, self.steps = c.eval_input_pipeline( |
|
keep_on_cpu={"answers", "answer", "question_id"}, |
|
data=data, devices=devices, **kw) |
|
|
|
self.outfile = c.resolve_outfile(outfile, split=data.get("split")) |
|
self.out_question_key = out_question_key |
|
self.out_answer_key = out_answer_key |
|
|
|
|
|
self.tok = big_vision.pp.tokenizer.get_tokenizer(tokenizer) |
|
self.postproc = (lambda s: s.lower()) if to_lower else lambda s: s |
|
self.decode = functools.partial( |
|
predict_fn, devices=devices, eos_token=self.tok.eos_token) |
|
|
|
def run(self, train_state): |
|
"""Does one evaluation run, yields metrics.""" |
|
|
|
accuracies = [] |
|
accuracies_any = [] |
|
anls_values = [] |
|
json_out = [] |
|
for _, batch in zip(range(self.steps), self.get_data_iter()): |
|
|
|
tokens = self.decode(train_state, batch) |
|
|
|
|
|
tokens = u.get_local_slice_from_fsarray(tokens) |
|
ex_masks = u.get_local_slice_from_fsarray(batch["_mask"]) |
|
|
|
|
|
for i in range(len(tokens)): |
|
if ex_masks[i] == 0: |
|
continue |
|
|
|
answer = self.postproc(self.tok.to_str(tokens[i], stop_at_eos=True)) |
|
|
|
|
|
if "answer" in batch: |
|
|
|
gt = self.postproc(batch["answer"][i]) |
|
gts = [gt] |
|
accuracies.append(float(answer == gt)) |
|
accuracies_any.append(float(answer == gt)) |
|
anls_values.append(anls_metric(gt, answer)) |
|
elif "answers" in batch and (gt_answers := batch["answers"][i]).size: |
|
|
|
|
|
gts = [self.postproc(a) for a in gt_answers] |
|
num_match = sum([answer == gt for gt in gts]) |
|
accuracies.append(min(1.0, num_match / 3.0)) |
|
accuracies_any.append(min(1.0, float(num_match))) |
|
anls_values.append(max(anls_metric(gt, answer) for gt in gts)) |
|
else: |
|
gts = [] |
|
|
|
json_out.append({ |
|
self.out_question_key: batch["question_id"][i].item(), |
|
self.out_answer_key: answer} | ({"gts": gts} if gts else {})) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
sum_accs, sum_accs_any, sum_anls, num_accs, num = c.process_sum( |
|
[sum(accuracies), sum(accuracies_any), sum(anls_values), |
|
len(accuracies), len(json_out)]) |
|
|
|
|
|
if num_accs: |
|
yield "acc", sum_accs / num_accs |
|
yield "acc_any", sum_accs_any / num_accs |
|
yield "anls", sum_anls / num_accs |
|
|
|
yield "num", num |
|
c.multiprocess_write_json(self.outfile, json_out) |
|
|
|
|
|
def anls_metric(target: str, prediction: str, theta: float = 0.5): |
|
"""Calculates ANLS for DocVQA. |
|
|
|
There does not seem to be an official evaluation script. |
|
Public implementation on which this implementation is based: |
|
https://github.com/herobd/layoutlmv2/blob/main/eval_docvqa.py#L92 |
|
|
|
Original paper (see Eq 1): https://arxiv.org/pdf/1907.00490.pdf |
|
|
|
Args: |
|
target: Target string. |
|
prediction: Predicted string. |
|
theta: Filter threshold set to 0.5 for DocVQA. |
|
|
|
Returns: |
|
ANLS score. |
|
""" |
|
if target: |
|
edit_distance = editdistance.eval(target, prediction) |
|
normalized_ld = edit_distance / max(len(target), len(prediction)) |
|
return 1 - normalized_ld if normalized_ld < theta else 0 |
|
else: |
|
return float(prediction == "") |
|
|