mirror of
https://github.com/open-mmlab/mmclassification.git
synced 2025-06-03 21:53:55 +08:00
* [Feat] Migrate blip caption to mmpretrain. (#50) * Migrate blip caption to mmpretrain * minor fix * support train * [Feature] Support OFA caption task. (#51) * [Feature] Support OFA caption task. * Remove duplicated files. * [Feature] Support OFA vqa task. (#58) * [Feature] Support OFA vqa task. * Fix lint. * [Feat] Add BLIP retrieval to mmpretrain. (#55) * init * minor fix for train * fix according to comments * refactor * Update Blip retrieval. (#62) * [Feature] Support OFA visual grounding task. (#59) * [Feature] Support OFA visual grounding task. * minor add TODO --------- Co-authored-by: yingfhu <yingfhu@gmail.com> * [Feat] Add flamingos coco caption and vqa. (#60) * first init * init flamingo coco * add vqa * minor fix * remove unnecessary modules * Update config * Use `ApplyToList`. --------- Co-authored-by: mzr1996 <mzr1996@163.com> * [Feature]: BLIP2 coco retrieval (#53) * [Feature]: Add blip2 retriever * [Feature]: Add blip2 all modules * [Feature]: Refine model * [Feature]: x1 * [Feature]: Runnable coco ret * [Feature]: Runnable version * [Feature]: Fix lint * [Fix]: Fix lint * [Feature]: Use 364 img size * [Feature]: Refactor blip2 * [Fix]: Fix lint * refactor files * minor fix * minor fix --------- Co-authored-by: yingfhu <yingfhu@gmail.com> * Remove * fix blip caption inputs (#68) * [Feat] Add BLIP NLVR support. (#67) * first init * init flamingo coco * add vqa * add nlvr * refactor nlvr * minor fix * minor fix * Update dataset --------- Co-authored-by: mzr1996 <mzr1996@163.com> * [Feature]: BLIP2 Caption (#70) * [Feature]: Add language model * [Feature]: blip2 caption forward * [Feature]: Reproduce the results * [Feature]: Refactor caption * refine config --------- Co-authored-by: yingfhu <yingfhu@gmail.com> * [Feat] Migrate BLIP VQA to mmpretrain (#69) * reformat * change * change * change * change * change * change * change * change * change * change * change * change * change * change * change * change * change * change * change * refactor code --------- Co-authored-by: yingfhu <yingfhu@gmail.com> * Update RefCOCO dataset * [Fix] fix lint * [Feature] Implement inference APIs for multi-modal tasks. (#65) * [Feature] Implement inference APIs for multi-modal tasks. * [Project] Add gradio demo. * [Improve] Update requirements * Update flamingo * Update blip * Add NLVR inferencer * Update flamingo * Update hugging face model register * Update ofa vqa * Update BLIP-vqa (#71) * Update blip-vqa docstring (#72) * Refine flamingo docstring (#73) * [Feature]: BLIP2 VQA (#61) * [Feature]: VQA forward * [Feature]: Reproduce accuracy * [Fix]: Fix lint * [Fix]: Add blank line * minor fix --------- Co-authored-by: yingfhu <yingfhu@gmail.com> * [Feature]: BLIP2 docstring (#74) * [Feature]: Add caption docstring * [Feature]: Add docstring to blip2 vqa * [Feature]: Add docstring to retrieval * Update BLIP-2 metafile and README (#75) * [Feature]: Add readme and docstring * Update blip2 results --------- Co-authored-by: mzr1996 <mzr1996@163.com> * [Feature] BLIP Visual Grounding on MMPretrain Branch (#66) * blip grounding merge with mmpretrain * remove commit * blip grounding test and inference api * refcoco dataset * refcoco dataset refine config * rebasing * gitignore * rebasing * minor edit * minor edit * Update blip-vqa docstring (#72) * rebasing * Revert "minor edit" This reverts commit 639cec757c215e654625ed0979319e60f0be9044. * blip grounding final * precommit * refine config * refine config * Update blip visual grounding --------- Co-authored-by: Yiqin Wang 王逸钦 <wyq1217@outlook.com> Co-authored-by: mzr1996 <mzr1996@163.com> * Update visual grounding metric * Update OFA docstring, README and metafiles. (#76) * [Docs] Update installation docs and gradio demo docs. (#77) * Update OFA name * Update Visual Grounding Visualizer * Integrate accelerate support * Fix imports. * Fix timm backbone * Update imports * Update README * Update circle ci * Update flamingo config * Add gradio demo README * [Feature]: Add scienceqa (#1571) * [Feature]: Add scienceqa * [Feature]: Change param name * Update docs * Update video --------- Co-authored-by: Hubert <42952108+yingfhu@users.noreply.github.com> Co-authored-by: yingfhu <yingfhu@gmail.com> Co-authored-by: Yuan Liu <30762564+YuanLiuuuuuu@users.noreply.github.com> Co-authored-by: Yiqin Wang 王逸钦 <wyq1217@outlook.com> Co-authored-by: Rongjie Li <limo97@163.com>
137 lines
4.4 KiB
Python
137 lines
4.4 KiB
Python
# Copyright (c) OpenMMLab. All rights reserved.
|
|
import json
|
|
import os
|
|
import tempfile
|
|
from typing import List, Optional
|
|
|
|
from mmengine.evaluator import BaseMetric
|
|
from mmengine.utils import track_iter_progress
|
|
|
|
from mmpretrain.registry import METRICS
|
|
from mmpretrain.utils import require
|
|
|
|
try:
|
|
from pycocoevalcap.eval import COCOEvalCap
|
|
from pycocotools.coco import COCO
|
|
except ImportError:
|
|
COCOEvalCap = None
|
|
COCO = None
|
|
|
|
|
|
@METRICS.register_module()
|
|
class COCOCaption(BaseMetric):
|
|
"""Coco Caption evaluation wrapper.
|
|
|
|
Save the generated captions and transform into coco format.
|
|
Calling COCO API for caption metrics.
|
|
|
|
Args:
|
|
ann_file (str): the path for the COCO format caption ground truth
|
|
json file, load for evaluations.
|
|
collect_device (str): Device name used for collecting results from
|
|
different ranks during distributed training. Must be 'cpu' or
|
|
'gpu'. Defaults to 'cpu'.
|
|
prefix (str, optional): The prefix that will be added in the metric
|
|
names to disambiguate homonymous metrics of different evaluators.
|
|
If prefix is not provided in the argument, self.default_prefix
|
|
will be used instead. Should be modified according to the
|
|
`retrieval_type` for unambiguous results. Defaults to TR.
|
|
"""
|
|
|
|
@require('pycocoevalcap')
|
|
def __init__(self,
|
|
ann_file: str,
|
|
collect_device: str = 'cpu',
|
|
prefix: Optional[str] = None):
|
|
super().__init__(collect_device=collect_device, prefix=prefix)
|
|
self.ann_file = ann_file
|
|
|
|
def process(self, data_batch, data_samples):
|
|
"""Process one batch of data samples.
|
|
|
|
The processed results should be stored in ``self.results``, which will
|
|
be used to computed the metrics when all batches have been processed.
|
|
|
|
Args:
|
|
data_batch: A batch of data from the dataloader.
|
|
data_samples (Sequence[dict]): A batch of outputs from the model.
|
|
"""
|
|
|
|
for data_sample in data_samples:
|
|
result = dict()
|
|
|
|
result['caption'] = data_sample.get('pred_caption')
|
|
result['image_id'] = int(data_sample.get('image_id'))
|
|
|
|
# Save the result to `self.results`.
|
|
self.results.append(result)
|
|
|
|
def compute_metrics(self, results: List):
|
|
"""Compute the metrics from processed results.
|
|
|
|
Args:
|
|
results (dict): The processed results of each batch.
|
|
|
|
Returns:
|
|
Dict: The computed metrics. The keys are the names of the metrics,
|
|
and the values are corresponding results.
|
|
"""
|
|
# NOTICE: don't access `self.results` from the method.
|
|
|
|
with tempfile.TemporaryDirectory() as temp_dir:
|
|
|
|
eval_result_file = save_result(
|
|
result=results,
|
|
result_dir=temp_dir,
|
|
filename='m4-caption_pred',
|
|
remove_duplicate='image_id',
|
|
)
|
|
|
|
coco_val = coco_caption_eval(eval_result_file, self.ann_file)
|
|
|
|
return coco_val
|
|
|
|
|
|
def save_result(result, result_dir, filename, remove_duplicate=''):
|
|
"""Saving predictions as json file for evaluation."""
|
|
|
|
# combine results from all processes
|
|
result_new = []
|
|
|
|
if remove_duplicate:
|
|
result_new = []
|
|
id_list = []
|
|
for res in track_iter_progress(result):
|
|
if res[remove_duplicate] not in id_list:
|
|
id_list.append(res[remove_duplicate])
|
|
result_new.append(res)
|
|
result = result_new
|
|
|
|
final_result_file_url = os.path.join(result_dir, '%s.json' % filename)
|
|
print(f'result file saved to {final_result_file_url}')
|
|
json.dump(result, open(final_result_file_url, 'w'))
|
|
|
|
return final_result_file_url
|
|
|
|
|
|
def coco_caption_eval(results_file, ann_file):
|
|
"""Evaluation between gt json and prediction json files."""
|
|
# create coco object and coco_result object
|
|
coco = COCO(ann_file)
|
|
coco_result = coco.loadRes(results_file)
|
|
|
|
# create coco_eval object by taking coco and coco_result
|
|
coco_eval = COCOEvalCap(coco, coco_result)
|
|
|
|
# make sure the image ids are the same
|
|
coco_eval.params['image_id'] = coco_result.getImgIds()
|
|
|
|
# This will take some times at the first run
|
|
coco_eval.evaluate()
|
|
|
|
# print output evaluation scores
|
|
for metric, score in coco_eval.eval.items():
|
|
print(f'{metric}: {score:.3f}')
|
|
|
|
return coco_eval.eval
|