{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "## Evaluation on TVBench\n", "This notebook evaluates VideoChat2 on the TVBench dataset. To run this code, first install VideoChat2 [dependencies](https://github.com/OpenGVLab/Ask-Anything/blob/main/video_chat2/requirements.txt). TVBench follows the same structure as MVBench, so any codebase with support for MVBench can be directly adapted to TVBench by simple updating the dataset path.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import json\n", "import torch\n", "\n", "from tqdm import tqdm\n", "\n", "from vqa_dataset import VQADataset, check_ans\n", "from vqa_model import build_videoChat2_infer, get_sinusoid_encoding_table, ask, answer\n", "from utils.easydict import EasyDict\n", "from utils.config import Config" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## TVBench dataset paths\n", "Download the TVBench dataset from [here](https://huggingface.co/datasets/FunAILab/TVBench).\n", "\n", "Replace `/datasets/TVBench/` with the path to the TVBench folder on your system." ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "data_dir = \"/datasets/TVBench/json\"\n", "data_list = {\n", " \"Action Count\": (\"action_count.json\", \"/datasets/TVBench/video/action_count\", \"video\", False),\n", " \"Object Count\": (\"object_count.json\", \"/datasets/TVBench/video/object_count\", \"video\", False),\n", " \"Action Sequence\": (\"action_sequence.json\", \"/datasets/TVBench/video/action_sequence\", \"video\", True), # has start & end\n", " \"Object Shuffle\": (\"object_shuffle.json\", \"/datasets/TVBench/video/object_shuffle\", \"video\", False),\n", " \"Scene Transition\": (\"scene_transition.json\", \"/datasets/TVBench/video/scene_transition\", \"video\", False),\n", " \"Action Localization\": (\"action_localization.json\", \"/datasets/TVBench/video/action_localization\", \"video\", True), # has start & end\n", " \"Action Antonym\": (\"action_antonym.json\", \"/datasets/TVBench/video/action_antonym\", \"video\", False),\n", " \"Unexpected Action\": (\"unexpected_action.json\", \"/datasets/TVBench/video/unexpected_action\", \"video\", False),\n", " \"Egocentric Sequence\": (\"egocentric_sequence.json\", \"/datasets/TVBench/video/egocentric_sequence\", \"video\", False),\n", " \"Moving Direction\": (\"moving_direction.json\", \"/datasets/TVBench/video/moving_direction\", \"video\", False),\n", "}" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Create a VQA dataset\n", "\n", "Create a VQADataset that will load the TVBench dataset defined above." ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [], "source": [ "# position embedding\n", "num_frame = 16\n", "resolution = 224\n", "\n", "dataset = VQADataset(data_dir, data_list, num_segments=num_frame, resolution=resolution)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Init VideoChat2\n", "Download [VideoChat Stage 3](https://github.com/OpenGVLab/Ask-Anything/blob/main/video_chat2/scripts/videochat_vicuna/config_7b_stage3.py) and update `model_path`. Also update model paths on `configs/config.yaml` to the following files:\n", "\n", "- `\"videochat2_model_path\"`: [VideoChat2](https://huggingface.co/OpenGVLab/videochat/resolve/main/videochat2_7b_stage2.pth)\n", "- `\"vit_blip_model_path\"`: [VideoBLIP](https://huggingface.co/OpenGVLab/videochat/resolve/main/umt_l16_qformer.pth)\n", "- `\"llama_model_path\"`: [LLM](https://github.com/OpenGVLab/Ask-Anything/tree/main/video_chat#running-usage)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "config_file = \"configs/config.json\"\n", "cfg = Config.from_file(config_file)\n", "\n", "num_frame = 16\n", "resolution = 224\n", "model = build_videoChat2_infer(\"/models/video_chat2/videochat2_7b_stage3.pth\", cfg)\n", "new_pos_emb = get_sinusoid_encoding_table(n_position=(resolution//16)**2*num_frame, cur_frame=num_frame)\n", "model.vision_encoder.encoder.pos_embed = new_pos_emb" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## VideoChat2 inference function\n", "We keep the same inference function as in the original implementation, as methods evaluated on MVBench can be directly evaluated on TVBench following the same strategy." ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [], "source": [ "def infer(\n", " data_sample, system=\"\", \n", " question_prompt='', # add in the end of question\n", " answer_prompt=None, # add in the begining of answer\n", " return_prompt='', # add in the begining of return message\n", " system_q=False, # whether add question in the system prompt for QFormer\n", " print_res=True,\n", " system_llm=False\n", " ):\n", " video = data_sample[\"video\"]\n", " TC, H, W = video.shape\n", " video = video.reshape(1, TC//3, 3, H, W).to(\"cuda:0\")\n", " \n", " video_list = []\n", " with torch.no_grad():\n", " if system_q:\n", " video_emb, _ = model.encode_img(video, system + data_sample['question'])\n", " else:\n", " video_emb, _ = model.encode_img(video, system)\n", " video_list.append(video_emb)\n", "# video_list.append(torch.zeros_like(video_emb))\n", "\n", " chat = EasyDict({\n", " \"system\": system,\n", " \"roles\": (\"Human\", \"Assistant\"),\n", " \"messages\": [],\n", " \"sep\": \"###\"\n", " })\n", "\n", " chat.messages.append([chat.roles[0], f\"\\n\"])\n", " \n", " if system_llm:\n", " prompt = system + data_sample['question'] + question_prompt\n", " else:\n", " prompt = data_sample['question'] + question_prompt\n", " \n", " ask(prompt, chat)\n", "\n", " llm_message = answer(\n", " conv=chat, model=model, do_sample=False, \n", " img_list=video_list, max_new_tokens=100, \n", " answer_prompt=answer_prompt, print_res=print_res\n", " )[0]\n", " # remove potential explanation\n", " llm_message = return_prompt + llm_message.strip().split('\\n')[0]\n", " print(llm_message)\n", " print(f\"GT: {data_sample['answer']}\")\n", " return llm_message" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Inference loop\n", "We also keep the same implementation of the inference loop." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "save_path = \"./test\"\n", "\n", "correct = 0\n", "total = 0\n", "res_list = []\n", "acc_dict = {}\n", "\n", "for example in tqdm(dataset):\n", " task_type = example['task_type']\n", " if task_type not in acc_dict:\n", " acc_dict[task_type] = [0, 0] # correct, total\n", " acc_dict[task_type][1] += 1\n", " total += 1\n", " pred = infer(\n", " example, \n", " system=\"Carefully watch the video and pay attention to the cause and sequence of events, the detail and movement of objects, and the action and pose of persons. Based on your observations, select the best option that accurately addresses the question.\\n\",\n", " question_prompt=\"\\nOnly give the best option.\",\n", " answer_prompt=\"Best option:(\",\n", " return_prompt='(',\n", " system_q=False,\n", " print_res=True,\n", " system_llm=True\n", " )\n", " gt = example['answer']\n", " res_list.append({\n", " 'pred': pred,\n", " 'gt': gt\n", " })\n", " if check_ans(pred=pred, gt=gt):\n", " acc_dict[task_type][0] += 1\n", " correct += 1\n", " print(f\"Part Acc: {acc_dict[task_type][0] / acc_dict[task_type][1] * 100 :.2f}%\")\n", " print(f\"Total Acc: {correct / total * 100 :.2f}%\")\n", " print('-' * 30, task_type, '-' * 30)\n", "\n", "with open(f\"{save_path}.json\", \"w\") as f:\n", " json.dump({\n", " \"acc_dict\": acc_dict,\n", " \"res_list\": res_list\n", " }, f)" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.10.12" } }, "nbformat": 4, "nbformat_minor": 2 }