Add files using upload-large-folder tool
Browse files- spatial-model/GeoThinker/src/lmms_eval/caching/__init__.py +0 -0
- spatial-model/GeoThinker/src/lmms_eval/caching/cache.py +68 -0
- spatial-model/GeoThinker/src/lmms_eval/loggers/__init__.py +2 -0
- spatial-model/GeoThinker/src/lmms_eval/loggers/evaluation_tracker.py +452 -0
- spatial-model/GeoThinker/src/lmms_eval/models/claude.py +264 -0
- spatial-model/GeoThinker/src/lmms_eval/models/from_log.py +116 -0
- spatial-model/GeoThinker/src/lmms_eval/models/llava_hf.py +342 -0
- spatial-model/GeoThinker/src/lmms_eval/models/minicpm_v.py +221 -0
- spatial-model/GeoThinker/src/lmms_eval/models/model_utils/__init__.py +0 -0
- spatial-model/GeoThinker/src/lmms_eval/models/model_utils/load_video.py +151 -0
- spatial-model/GeoThinker/src/lmms_eval/models/model_utils/qwen/qwen_generate_utils.py +369 -0
- spatial-model/GeoThinker/src/lmms_eval/models/video_chatgpt/constants.py +11 -0
- spatial-model/GeoThinker/src/lmms_eval/models/video_chatgpt/eval/__init__.py +0 -0
- spatial-model/GeoThinker/src/lmms_eval/models/video_chatgpt/eval/model_utils.py +149 -0
- spatial-model/GeoThinker/src/lmms_eval/models/video_chatgpt/inference.py +189 -0
- spatial-model/GeoThinker/src/lmms_eval/models/video_chatgpt/model/__init__.py +4 -0
- spatial-model/GeoThinker/src/lmms_eval/models/video_chatgpt/model/consolidate.py +29 -0
- spatial-model/GeoThinker/src/lmms_eval/models/video_chatgpt/single_video_inference.py +173 -0
- spatial-model/GeoThinker/src/lmms_eval/models/video_chatgpt/utils.py +8 -0
- spatial-model/GeoThinker/src/lmms_eval/models/video_chatgpt/video_conversation.py +157 -0
spatial-model/GeoThinker/src/lmms_eval/caching/__init__.py
ADDED
|
File without changes
|
spatial-model/GeoThinker/src/lmms_eval/caching/cache.py
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import hashlib
|
| 2 |
+
import os
|
| 3 |
+
import pickle
|
| 4 |
+
|
| 5 |
+
import dill
|
| 6 |
+
|
| 7 |
+
from lmms_eval.loggers.utils import _handle_non_serializable, is_serializable
|
| 8 |
+
from lmms_eval.utils import eval_logger
|
| 9 |
+
|
| 10 |
+
MODULE_DIR = os.path.dirname(os.path.realpath(__file__))
|
| 11 |
+
|
| 12 |
+
OVERRIDE_PATH = os.getenv("LM_HARNESS_CACHE_PATH")
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
PATH = OVERRIDE_PATH if OVERRIDE_PATH else f"{MODULE_DIR}/.cache"
|
| 16 |
+
|
| 17 |
+
# This should be sufficient for uniqueness
|
| 18 |
+
HASH_INPUT = "EleutherAI-lm-evaluation-harness"
|
| 19 |
+
|
| 20 |
+
HASH_PREFIX = hashlib.sha256(HASH_INPUT.encode("utf-8")).hexdigest()
|
| 21 |
+
|
| 22 |
+
FILE_SUFFIX = f".{HASH_PREFIX}.pickle"
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def load_from_cache(file_name):
|
| 26 |
+
try:
|
| 27 |
+
path = f"{PATH}/{file_name}{FILE_SUFFIX}"
|
| 28 |
+
|
| 29 |
+
with open(path, "rb") as file:
|
| 30 |
+
cached_task_dict = dill.loads(file.read())
|
| 31 |
+
return cached_task_dict
|
| 32 |
+
|
| 33 |
+
except Exception:
|
| 34 |
+
eval_logger.debug(f"{file_name} is not cached, generating...")
|
| 35 |
+
pass
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def save_to_cache(file_name, obj):
|
| 39 |
+
if not os.path.exists(PATH):
|
| 40 |
+
os.mkdir(PATH)
|
| 41 |
+
|
| 42 |
+
file_path = f"{PATH}/{file_name}{FILE_SUFFIX}"
|
| 43 |
+
|
| 44 |
+
serializable_obj = []
|
| 45 |
+
|
| 46 |
+
for item in obj:
|
| 47 |
+
for subitem in item:
|
| 48 |
+
if hasattr(subitem, "arguments"): # we need to handle the arguments specially since doc_to_visual is callable method and not serializable
|
| 49 |
+
serializable_arguments = tuple(arg if not callable(arg) else None for arg in subitem.arguments)
|
| 50 |
+
subitem.arguments = serializable_arguments
|
| 51 |
+
|
| 52 |
+
eval_logger.debug(f"Saving {file_path} to cache...")
|
| 53 |
+
try:
|
| 54 |
+
with open(file_path, "wb") as file:
|
| 55 |
+
file.write(dill.dumps(serializable_obj))
|
| 56 |
+
except (pickle.PickleError, dill.PicklingError, TypeError, AttributeError):
|
| 57 |
+
with open(file_path, "wb") as file:
|
| 58 |
+
file.write(dill.dumps([[subitem if is_serializable(subitem) else _handle_non_serializable(subitem) for subitem in item] for item in obj]))
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
# NOTE the "key" param is to allow for flexibility
|
| 62 |
+
def delete_cache(key: str = ""):
|
| 63 |
+
files = os.listdir(PATH)
|
| 64 |
+
|
| 65 |
+
for file in files:
|
| 66 |
+
if file.startswith(key) and file.endswith(FILE_SUFFIX):
|
| 67 |
+
file_path = f"{PATH}/{file}"
|
| 68 |
+
os.unlink(file_path)
|
spatial-model/GeoThinker/src/lmms_eval/loggers/__init__.py
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .evaluation_tracker import EvaluationTracker
|
| 2 |
+
from .wandb_logger import WandbLogger
|
spatial-model/GeoThinker/src/lmms_eval/loggers/evaluation_tracker.py
ADDED
|
@@ -0,0 +1,452 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# code is adapted from https://github.com/EleutherAI/lm-evaluation-harness/blob/main/lm_eval/loggers/evaluation_tracker.py
|
| 2 |
+
import json
|
| 3 |
+
import os
|
| 4 |
+
import re
|
| 5 |
+
import time
|
| 6 |
+
from collections import defaultdict
|
| 7 |
+
from dataclasses import asdict, dataclass
|
| 8 |
+
from datetime import datetime
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
|
| 11 |
+
from datasets import load_dataset
|
| 12 |
+
from datasets.utils.metadata import MetadataConfigs
|
| 13 |
+
from huggingface_hub import DatasetCard, DatasetCardData, HfApi, hf_hub_url
|
| 14 |
+
from huggingface_hub.utils import build_hf_headers, get_session, hf_raise_for_status
|
| 15 |
+
|
| 16 |
+
from lmms_eval.utils import (
|
| 17 |
+
eval_logger,
|
| 18 |
+
get_datetime_str,
|
| 19 |
+
get_file_datetime,
|
| 20 |
+
get_file_task_name,
|
| 21 |
+
get_results_filenames,
|
| 22 |
+
get_sample_results_filenames,
|
| 23 |
+
handle_non_serializable,
|
| 24 |
+
hash_string,
|
| 25 |
+
sanitize_list,
|
| 26 |
+
sanitize_model_name,
|
| 27 |
+
sanitize_task_name,
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
@dataclass(init=False)
|
| 32 |
+
class GeneralConfigTracker:
|
| 33 |
+
"""
|
| 34 |
+
Tracker for the evaluation parameters.
|
| 35 |
+
|
| 36 |
+
Attributes:
|
| 37 |
+
model_source (str): Source of the model (e.g. Hugging Face, GGUF, etc.)
|
| 38 |
+
model_name (str): Name of the model.
|
| 39 |
+
model_name_sanitized (str): Sanitized model name for directory creation.
|
| 40 |
+
start_time (float): Start time of the experiment. Logged at class init.
|
| 41 |
+
end_time (float): Start time of the experiment. Logged when calling [`GeneralConfigTracker.log_end_time`]
|
| 42 |
+
total_evaluation_time_seconds (str): Inferred total evaluation time in seconds (from the start and end times).
|
| 43 |
+
"""
|
| 44 |
+
|
| 45 |
+
model_source: str = None
|
| 46 |
+
model_name: str = None
|
| 47 |
+
model_name_sanitized: str = None
|
| 48 |
+
system_instruction: str = None
|
| 49 |
+
system_instruction_sha: str = None
|
| 50 |
+
fewshot_as_multiturn: bool = None
|
| 51 |
+
chat_template: str = None
|
| 52 |
+
chat_template_sha: str = None
|
| 53 |
+
start_time: float = None
|
| 54 |
+
end_time: float = None
|
| 55 |
+
total_evaluation_time_seconds: str = None
|
| 56 |
+
|
| 57 |
+
def __init__(self) -> None:
|
| 58 |
+
"""Starts the evaluation timer."""
|
| 59 |
+
self.start_time = time.perf_counter()
|
| 60 |
+
|
| 61 |
+
@staticmethod
|
| 62 |
+
def _get_model_name(model_args: str) -> str:
|
| 63 |
+
"""Extracts the model name from the model arguments."""
|
| 64 |
+
|
| 65 |
+
def extract_model_name(model_args: str, key: str) -> str:
|
| 66 |
+
"""Extracts the model name from the model arguments using a key."""
|
| 67 |
+
args_after_key = model_args.split(key)[1]
|
| 68 |
+
return args_after_key.split(",")[0]
|
| 69 |
+
|
| 70 |
+
# order does matter, e.g. peft and delta are provided together with pretrained
|
| 71 |
+
prefixes = ["peft=", "delta=", "pretrained=", "model=", "path=", "engine="]
|
| 72 |
+
for prefix in prefixes:
|
| 73 |
+
if prefix in model_args:
|
| 74 |
+
return extract_model_name(model_args, prefix)
|
| 75 |
+
return ""
|
| 76 |
+
|
| 77 |
+
def log_experiment_args(
|
| 78 |
+
self,
|
| 79 |
+
model_source: str,
|
| 80 |
+
model_args: str,
|
| 81 |
+
system_instruction: str,
|
| 82 |
+
chat_template: str,
|
| 83 |
+
fewshot_as_multiturn: bool,
|
| 84 |
+
) -> None:
|
| 85 |
+
"""Logs model parameters and job ID."""
|
| 86 |
+
self.model_source = model_source
|
| 87 |
+
self.model_name = GeneralConfigTracker._get_model_name(model_args)
|
| 88 |
+
self.model_name_sanitized = sanitize_model_name(self.model_name)
|
| 89 |
+
self.system_instruction = system_instruction
|
| 90 |
+
self.system_instruction_sha = hash_string(system_instruction) if system_instruction else None
|
| 91 |
+
self.chat_template = chat_template
|
| 92 |
+
self.chat_template_sha = hash_string(chat_template) if chat_template else None
|
| 93 |
+
self.fewshot_as_multiturn = fewshot_as_multiturn
|
| 94 |
+
|
| 95 |
+
def log_end_time(self) -> None:
|
| 96 |
+
"""Logs the end time of the evaluation and calculates the total evaluation time."""
|
| 97 |
+
self.end_time = time.perf_counter()
|
| 98 |
+
self.total_evaluation_time_seconds = str(self.end_time - self.start_time)
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
class EvaluationTracker:
|
| 102 |
+
"""
|
| 103 |
+
Keeps track and saves relevant information of the evaluation process.
|
| 104 |
+
Compiles the data from trackers and writes it to files, which can be published to the Hugging Face hub if requested.
|
| 105 |
+
"""
|
| 106 |
+
|
| 107 |
+
def __init__(
|
| 108 |
+
self,
|
| 109 |
+
output_path: str = None,
|
| 110 |
+
hub_results_org: str = "",
|
| 111 |
+
hub_repo_name: str = "",
|
| 112 |
+
details_repo_name: str = "",
|
| 113 |
+
results_repo_name: str = "",
|
| 114 |
+
push_results_to_hub: bool = False,
|
| 115 |
+
push_samples_to_hub: bool = False,
|
| 116 |
+
public_repo: bool = False,
|
| 117 |
+
token: str = "",
|
| 118 |
+
leaderboard_url: str = "",
|
| 119 |
+
point_of_contact: str = "",
|
| 120 |
+
gated: bool = False,
|
| 121 |
+
) -> None:
|
| 122 |
+
"""
|
| 123 |
+
Creates all the necessary loggers for evaluation tracking.
|
| 124 |
+
|
| 125 |
+
Args:
|
| 126 |
+
output_path (str): Path to save the results. If not provided, the results won't be saved.
|
| 127 |
+
hub_results_org (str): The Hugging Face organization to push the results to. If not provided, the results will be pushed to the owner of the Hugging Face token.
|
| 128 |
+
hub_repo_name (str): The name of the Hugging Face repository to push the results to. If not provided, the results will be pushed to `lm-eval-results`.
|
| 129 |
+
details_repo_name (str): The name of the Hugging Face repository to push the details to. If not provided, the results will be pushed to `lm-eval-results`.
|
| 130 |
+
result_repo_name (str): The name of the Hugging Face repository to push the results to. If not provided, the results will not be pushed and will be found in the details_hub_repo.
|
| 131 |
+
push_results_to_hub (bool): Whether to push the results to the Hugging Face hub.
|
| 132 |
+
push_samples_to_hub (bool): Whether to push the samples to the Hugging Face hub.
|
| 133 |
+
public_repo (bool): Whether to push the results to a public or private repository.
|
| 134 |
+
token (str): Token to use when pushing to the Hugging Face hub. This token should have write access to `hub_results_org`.
|
| 135 |
+
leaderboard_url (str): URL to the leaderboard on the Hugging Face hub on the dataset card.
|
| 136 |
+
point_of_contact (str): Contact information on the Hugging Face hub dataset card.
|
| 137 |
+
gated (bool): Whether to gate the repository.
|
| 138 |
+
"""
|
| 139 |
+
self.general_config_tracker = GeneralConfigTracker()
|
| 140 |
+
|
| 141 |
+
self.output_path = output_path
|
| 142 |
+
self.push_results_to_hub = push_results_to_hub
|
| 143 |
+
self.push_samples_to_hub = push_samples_to_hub
|
| 144 |
+
self.public_repo = public_repo
|
| 145 |
+
self.leaderboard_url = leaderboard_url
|
| 146 |
+
self.point_of_contact = point_of_contact
|
| 147 |
+
self.api = HfApi(token=token) if token else None
|
| 148 |
+
self.gated_repo = gated
|
| 149 |
+
|
| 150 |
+
if not self.api and (push_results_to_hub or push_samples_to_hub):
|
| 151 |
+
raise ValueError("Hugging Face token is not defined, but 'push_results_to_hub' or 'push_samples_to_hub' is set to True. " "Please provide a valid Hugging Face token by setting the HF_TOKEN environment variable.")
|
| 152 |
+
|
| 153 |
+
if self.api and hub_results_org == "" and (push_results_to_hub or push_samples_to_hub):
|
| 154 |
+
hub_results_org = self.api.whoami()["name"]
|
| 155 |
+
eval_logger.warning(f"hub_results_org was not specified. Results will be pushed to '{hub_results_org}'.")
|
| 156 |
+
|
| 157 |
+
if hub_repo_name == "":
|
| 158 |
+
details_repo_name = details_repo_name if details_repo_name != "" else "lmms-eval-results"
|
| 159 |
+
results_repo_name = results_repo_name if results_repo_name != "" else details_repo_name
|
| 160 |
+
else:
|
| 161 |
+
details_repo_name = hub_repo_name
|
| 162 |
+
results_repo_name = hub_repo_name
|
| 163 |
+
eval_logger.warning("hub_repo_name was specified. Both details and results will be pushed to the same repository. Using hub_repo_name is no longer recommended, details_repo_name and results_repo_name should be used instead.")
|
| 164 |
+
|
| 165 |
+
self.details_repo = f"{hub_results_org}/{details_repo_name}"
|
| 166 |
+
self.details_repo_private = f"{hub_results_org}/{details_repo_name}-private"
|
| 167 |
+
self.results_repo = f"{hub_results_org}/{results_repo_name}"
|
| 168 |
+
self.results_repo_private = f"{hub_results_org}/{results_repo_name}-private"
|
| 169 |
+
|
| 170 |
+
def save_results_aggregated(
|
| 171 |
+
self,
|
| 172 |
+
results: dict,
|
| 173 |
+
samples: dict,
|
| 174 |
+
datetime_str: str,
|
| 175 |
+
) -> None:
|
| 176 |
+
"""
|
| 177 |
+
Saves the aggregated results and samples to the output path and pushes them to the Hugging Face hub if requested.
|
| 178 |
+
|
| 179 |
+
Args:
|
| 180 |
+
results (dict): The aggregated results to save.
|
| 181 |
+
samples (dict): The samples results to save.
|
| 182 |
+
datetime_str (str): The datetime string to use for the results file.
|
| 183 |
+
"""
|
| 184 |
+
self.general_config_tracker.log_end_time()
|
| 185 |
+
|
| 186 |
+
if self.output_path:
|
| 187 |
+
try:
|
| 188 |
+
eval_logger.info("Saving results aggregated")
|
| 189 |
+
|
| 190 |
+
# calculate cumulative hash for each task - only if samples are provided
|
| 191 |
+
task_hashes = {}
|
| 192 |
+
if samples:
|
| 193 |
+
for task_name, task_samples in samples.items():
|
| 194 |
+
sample_hashes = [s["doc_hash"] + s["prompt_hash"] + s["target_hash"] for s in task_samples]
|
| 195 |
+
task_hashes[task_name] = hash_string("".join(sample_hashes))
|
| 196 |
+
|
| 197 |
+
# update initial results dict
|
| 198 |
+
results.update({"task_hashes": task_hashes})
|
| 199 |
+
results.update(asdict(self.general_config_tracker))
|
| 200 |
+
dumped = json.dumps(
|
| 201 |
+
results,
|
| 202 |
+
indent=2,
|
| 203 |
+
default=handle_non_serializable,
|
| 204 |
+
ensure_ascii=False,
|
| 205 |
+
)
|
| 206 |
+
|
| 207 |
+
path = Path(self.output_path if self.output_path else Path.cwd())
|
| 208 |
+
path = path.joinpath(self.general_config_tracker.model_name_sanitized)
|
| 209 |
+
path.mkdir(parents=True, exist_ok=True)
|
| 210 |
+
|
| 211 |
+
self.date_id = datetime_str.replace(":", "-")
|
| 212 |
+
file_results_aggregated = path.joinpath(f"{self.date_id}_results.json")
|
| 213 |
+
file_results_aggregated.open("w", encoding="utf-8").write(dumped)
|
| 214 |
+
|
| 215 |
+
if self.api and self.push_results_to_hub:
|
| 216 |
+
repo_id = self.results_repo if self.public_repo else self.results_repo_private
|
| 217 |
+
self.api.create_repo(
|
| 218 |
+
repo_id=repo_id,
|
| 219 |
+
repo_type="dataset",
|
| 220 |
+
private=not self.public_repo,
|
| 221 |
+
exist_ok=True,
|
| 222 |
+
)
|
| 223 |
+
self.api.upload_file(
|
| 224 |
+
repo_id=repo_id,
|
| 225 |
+
path_or_fileobj=str(path.joinpath(f"{self.date_id}_results.json")),
|
| 226 |
+
path_in_repo=os.path.join(
|
| 227 |
+
self.general_config_tracker.model_name,
|
| 228 |
+
f"{self.date_id}_results.json",
|
| 229 |
+
),
|
| 230 |
+
repo_type="dataset",
|
| 231 |
+
commit_message=f"Adding aggregated results for {self.general_config_tracker.model_name}",
|
| 232 |
+
)
|
| 233 |
+
eval_logger.info("Successfully pushed aggregated results to the Hugging Face Hub. " f"You can find them at: {repo_id}")
|
| 234 |
+
|
| 235 |
+
except Exception as e:
|
| 236 |
+
eval_logger.warning("Could not save results aggregated")
|
| 237 |
+
eval_logger.info(repr(e))
|
| 238 |
+
else:
|
| 239 |
+
eval_logger.info("Output path not provided, skipping saving results aggregated")
|
| 240 |
+
|
| 241 |
+
def save_results_samples(
|
| 242 |
+
self,
|
| 243 |
+
task_name: str,
|
| 244 |
+
samples: dict,
|
| 245 |
+
) -> None:
|
| 246 |
+
"""
|
| 247 |
+
Saves the samples results to the output path and pushes them to the Hugging Face hub if requested.
|
| 248 |
+
|
| 249 |
+
Args:
|
| 250 |
+
task_name (str): The task name to save the samples for.
|
| 251 |
+
samples (dict): The samples results to save.
|
| 252 |
+
"""
|
| 253 |
+
if self.output_path:
|
| 254 |
+
try:
|
| 255 |
+
eval_logger.info(f"Saving per-sample results for: {task_name}")
|
| 256 |
+
|
| 257 |
+
path = Path(self.output_path if self.output_path else Path.cwd())
|
| 258 |
+
path = path.joinpath(self.general_config_tracker.model_name_sanitized)
|
| 259 |
+
path.mkdir(parents=True, exist_ok=True)
|
| 260 |
+
|
| 261 |
+
file_results_samples = path.joinpath(f"{self.date_id}_samples_{task_name}.jsonl")
|
| 262 |
+
|
| 263 |
+
for sample in samples:
|
| 264 |
+
# we first need to sanitize arguments and resps
|
| 265 |
+
# otherwise we won't be able to load the dataset
|
| 266 |
+
# using the datasets library
|
| 267 |
+
arguments = {}
|
| 268 |
+
for key, value in enumerate(sample["arguments"][1]): # update metadata into args
|
| 269 |
+
arguments[key] = value
|
| 270 |
+
|
| 271 |
+
sample["input"] = sample["arguments"][0]
|
| 272 |
+
sample["resps"] = sanitize_list(sample["resps"])
|
| 273 |
+
sample["filtered_resps"] = sanitize_list(sample["filtered_resps"])
|
| 274 |
+
sample["arguments"] = arguments
|
| 275 |
+
sample["target"] = str(sample["target"])
|
| 276 |
+
|
| 277 |
+
sample_dump = (
|
| 278 |
+
json.dumps(
|
| 279 |
+
sample,
|
| 280 |
+
default=handle_non_serializable,
|
| 281 |
+
ensure_ascii=False,
|
| 282 |
+
)
|
| 283 |
+
+ "\n"
|
| 284 |
+
)
|
| 285 |
+
|
| 286 |
+
with open(file_results_samples, "a", encoding="utf-8") as f:
|
| 287 |
+
f.write(sample_dump)
|
| 288 |
+
|
| 289 |
+
if self.api and self.push_samples_to_hub:
|
| 290 |
+
repo_id = self.details_repo if self.public_repo else self.details_repo_private
|
| 291 |
+
self.api.create_repo(
|
| 292 |
+
repo_id=repo_id,
|
| 293 |
+
repo_type="dataset",
|
| 294 |
+
private=not self.public_repo,
|
| 295 |
+
exist_ok=True,
|
| 296 |
+
)
|
| 297 |
+
try:
|
| 298 |
+
if self.gated_repo:
|
| 299 |
+
headers = build_hf_headers()
|
| 300 |
+
r = get_session().put(
|
| 301 |
+
url=f"https://huggingface.co/api/datasets/{repo_id}/settings",
|
| 302 |
+
headers=headers,
|
| 303 |
+
json={"gated": "auto"},
|
| 304 |
+
)
|
| 305 |
+
hf_raise_for_status(r)
|
| 306 |
+
except Exception as e:
|
| 307 |
+
eval_logger.warning("Could not gate the repository")
|
| 308 |
+
eval_logger.info(repr(e))
|
| 309 |
+
self.api.upload_folder(
|
| 310 |
+
repo_id=repo_id,
|
| 311 |
+
folder_path=str(path),
|
| 312 |
+
path_in_repo=self.general_config_tracker.model_name_sanitized,
|
| 313 |
+
repo_type="dataset",
|
| 314 |
+
commit_message=f"Adding samples results for {task_name} to {self.general_config_tracker.model_name}",
|
| 315 |
+
)
|
| 316 |
+
eval_logger.info(f"Successfully pushed sample results for task: {task_name} to the Hugging Face Hub. " f"You can find them at: {repo_id}")
|
| 317 |
+
|
| 318 |
+
except Exception as e:
|
| 319 |
+
eval_logger.warning("Could not save sample results")
|
| 320 |
+
eval_logger.info(repr(e))
|
| 321 |
+
else:
|
| 322 |
+
eval_logger.info("Output path not provided, skipping saving sample results")
|
| 323 |
+
|
| 324 |
+
def recreate_metadata_card(self) -> None:
|
| 325 |
+
"""
|
| 326 |
+
Creates a metadata card for the evaluation results dataset and pushes it to the Hugging Face hub.
|
| 327 |
+
"""
|
| 328 |
+
|
| 329 |
+
eval_logger.info("Recreating metadata card")
|
| 330 |
+
repo_id = self.details_repo if self.public_repo else self.details_repo_private
|
| 331 |
+
|
| 332 |
+
files_in_repo = self.api.list_repo_files(repo_id=repo_id, repo_type="dataset")
|
| 333 |
+
results_files = get_results_filenames(files_in_repo)
|
| 334 |
+
sample_files = get_sample_results_filenames(files_in_repo)
|
| 335 |
+
|
| 336 |
+
# Build a dictionary to store the latest evaluation datetime for:
|
| 337 |
+
# - Each tested model and its aggregated results
|
| 338 |
+
# - Each task and sample results, if existing
|
| 339 |
+
# i.e. {
|
| 340 |
+
# "org__model_name__gsm8k": "2021-09-01T12:00:00",
|
| 341 |
+
# "org__model_name__ifeval": "2021-09-01T12:00:00",
|
| 342 |
+
# "org__model_name__results": "2021-09-01T12:00:00"
|
| 343 |
+
# }
|
| 344 |
+
latest_task_results_datetime = defaultdict(lambda: datetime.min.isoformat())
|
| 345 |
+
|
| 346 |
+
for file_path in sample_files:
|
| 347 |
+
file_path = Path(file_path)
|
| 348 |
+
filename = file_path.name
|
| 349 |
+
model_name = file_path.parent
|
| 350 |
+
task_name = get_file_task_name(filename)
|
| 351 |
+
results_datetime = get_file_datetime(filename)
|
| 352 |
+
task_name_sanitized = sanitize_task_name(task_name)
|
| 353 |
+
# Results and sample results for the same model and task will have the same datetime
|
| 354 |
+
samples_key = f"{model_name}__{task_name_sanitized}"
|
| 355 |
+
results_key = f"{model_name}__results"
|
| 356 |
+
latest_datetime = max(
|
| 357 |
+
latest_task_results_datetime[samples_key],
|
| 358 |
+
results_datetime,
|
| 359 |
+
)
|
| 360 |
+
latest_task_results_datetime[samples_key] = latest_datetime
|
| 361 |
+
latest_task_results_datetime[results_key] = max(
|
| 362 |
+
latest_task_results_datetime[results_key],
|
| 363 |
+
latest_datetime,
|
| 364 |
+
)
|
| 365 |
+
|
| 366 |
+
# Create metadata card
|
| 367 |
+
card_metadata = MetadataConfigs()
|
| 368 |
+
|
| 369 |
+
# Add the latest aggregated results to the metadata card for easy access
|
| 370 |
+
for file_path in results_files:
|
| 371 |
+
file_path = Path(file_path)
|
| 372 |
+
results_filename = file_path.name
|
| 373 |
+
model_name = file_path.parent
|
| 374 |
+
eval_date = get_file_datetime(results_filename)
|
| 375 |
+
eval_date_sanitized = re.sub(r"[^\w\.]", "_", eval_date)
|
| 376 |
+
results_filename = Path("**") / Path(results_filename).name
|
| 377 |
+
config_name = f"{model_name}__results"
|
| 378 |
+
sanitized_last_eval_date_results = re.sub(r"[^\w\.]", "_", latest_task_results_datetime[config_name])
|
| 379 |
+
|
| 380 |
+
if eval_date_sanitized == sanitized_last_eval_date_results:
|
| 381 |
+
# Ensure that all results files are listed in the metadata card
|
| 382 |
+
current_results = card_metadata.get(config_name, {"data_files": []})
|
| 383 |
+
current_results["data_files"].append({"split": eval_date_sanitized, "path": [str(results_filename)]})
|
| 384 |
+
card_metadata[config_name] = current_results
|
| 385 |
+
# If the results file is the newest, update the "latest" field in the metadata card
|
| 386 |
+
card_metadata[config_name]["data_files"].append({"split": "latest", "path": [str(results_filename)]})
|
| 387 |
+
|
| 388 |
+
# Add the tasks details configs
|
| 389 |
+
for file_path in sample_files:
|
| 390 |
+
file_path = Path(file_path)
|
| 391 |
+
filename = file_path.name
|
| 392 |
+
model_name = file_path.parent
|
| 393 |
+
task_name = get_file_task_name(filename)
|
| 394 |
+
eval_date = get_file_datetime(filename)
|
| 395 |
+
task_name_sanitized = sanitize_task_name(task_name)
|
| 396 |
+
eval_date_sanitized = re.sub(r"[^\w\.]", "_", eval_date)
|
| 397 |
+
results_filename = Path("**") / Path(filename).name
|
| 398 |
+
config_name = f"{model_name}__{task_name_sanitized}"
|
| 399 |
+
sanitized_last_eval_date_results = re.sub(r"[^\w\.]", "_", latest_task_results_datetime[config_name])
|
| 400 |
+
if eval_date_sanitized == sanitized_last_eval_date_results:
|
| 401 |
+
# Ensure that all sample results files are listed in the metadata card
|
| 402 |
+
current_details_for_task = card_metadata.get(config_name, {"data_files": []})
|
| 403 |
+
current_details_for_task["data_files"].append({"split": eval_date_sanitized, "path": [str(results_filename)]})
|
| 404 |
+
card_metadata[config_name] = current_details_for_task
|
| 405 |
+
# If the samples results file is the newest, update the "latest" field in the metadata card
|
| 406 |
+
card_metadata[config_name]["data_files"].append({"split": "latest", "path": [str(results_filename)]})
|
| 407 |
+
|
| 408 |
+
# Get latest results and extract info to update metadata card examples
|
| 409 |
+
latest_datetime = max(latest_task_results_datetime.values())
|
| 410 |
+
latest_model_name = max(latest_task_results_datetime, key=lambda k: latest_task_results_datetime[k])
|
| 411 |
+
last_results_file = [f for f in results_files if latest_datetime.replace(":", "-") in f][0]
|
| 412 |
+
last_results_file_path = hf_hub_url(repo_id=repo_id, filename=last_results_file, repo_type="dataset")
|
| 413 |
+
latest_results_file = load_dataset("json", data_files=last_results_file_path, split="train")
|
| 414 |
+
results_dict = latest_results_file["results"][0]
|
| 415 |
+
new_dictionary = {"all": results_dict}
|
| 416 |
+
new_dictionary.update(results_dict)
|
| 417 |
+
results_string = json.dumps(new_dictionary, indent=4)
|
| 418 |
+
|
| 419 |
+
dataset_summary = "Dataset automatically created during the evaluation run of model "
|
| 420 |
+
if self.general_config_tracker.model_source == "hf":
|
| 421 |
+
dataset_summary += f"[{self.general_config_tracker.model_name}](https://huggingface.co/{self.general_config_tracker.model_name})\n"
|
| 422 |
+
else:
|
| 423 |
+
dataset_summary += f"{self.general_config_tracker.model_name}\n"
|
| 424 |
+
dataset_summary += (
|
| 425 |
+
f"The dataset is composed of {len(card_metadata)-1} configuration(s), each one corresponding to one of the evaluated task.\n\n"
|
| 426 |
+
f"The dataset has been created from {len(results_files)} run(s). Each run can be found as a specific split in each "
|
| 427 |
+
'configuration, the split being named using the timestamp of the run.The "train" split is always pointing to the latest results.\n\n'
|
| 428 |
+
'An additional configuration "results" store all the aggregated results of the run.\n\n'
|
| 429 |
+
"To load the details from a run, you can for instance do the following:\n"
|
| 430 |
+
)
|
| 431 |
+
if self.general_config_tracker.model_source == "hf":
|
| 432 |
+
dataset_summary += "```python\nfrom datasets import load_dataset\n" f'data = load_dataset(\n\t"{repo_id}",\n\tname="{latest_model_name}",\n\tsplit="latest"\n)\n```\n\n'
|
| 433 |
+
dataset_summary += (
|
| 434 |
+
"## Latest results\n\n"
|
| 435 |
+
f'These are the [latest results from run {latest_datetime}]({last_results_file_path.replace("/resolve/", "/blob/")}) '
|
| 436 |
+
"(note that there might be results for other tasks in the repos if successive evals didn't cover the same tasks. "
|
| 437 |
+
'You find each in the results and the "latest" split for each eval):\n\n'
|
| 438 |
+
f"```python\n{results_string}\n```"
|
| 439 |
+
)
|
| 440 |
+
card_data = DatasetCardData(
|
| 441 |
+
dataset_summary=dataset_summary,
|
| 442 |
+
repo_url=f"https://huggingface.co/{self.general_config_tracker.model_name}",
|
| 443 |
+
pretty_name=f"Evaluation run of {self.general_config_tracker.model_name}",
|
| 444 |
+
leaderboard_url=self.leaderboard_url,
|
| 445 |
+
point_of_contact=self.point_of_contact,
|
| 446 |
+
)
|
| 447 |
+
card_metadata.to_dataset_card_data(card_data)
|
| 448 |
+
card = DatasetCard.from_template(
|
| 449 |
+
card_data,
|
| 450 |
+
pretty_name=card_data.pretty_name,
|
| 451 |
+
)
|
| 452 |
+
card.push_to_hub(repo_id, repo_type="dataset")
|
spatial-model/GeoThinker/src/lmms_eval/models/claude.py
ADDED
|
@@ -0,0 +1,264 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import base64
|
| 2 |
+
import json
|
| 3 |
+
import os
|
| 4 |
+
import time
|
| 5 |
+
from copy import deepcopy
|
| 6 |
+
from io import BytesIO
|
| 7 |
+
from typing import List, Tuple, Union
|
| 8 |
+
|
| 9 |
+
from accelerate import Accelerator, DistributedType
|
| 10 |
+
from PIL import Image
|
| 11 |
+
from tqdm import tqdm
|
| 12 |
+
|
| 13 |
+
from lmms_eval.api.instance import Instance
|
| 14 |
+
from lmms_eval.api.model import lmms
|
| 15 |
+
from lmms_eval.api.registry import register_model
|
| 16 |
+
|
| 17 |
+
NUM_SECONDS_TO_SLEEP = 5
|
| 18 |
+
|
| 19 |
+
from loguru import logger
|
| 20 |
+
|
| 21 |
+
eval_logger = logger
|
| 22 |
+
|
| 23 |
+
try:
|
| 24 |
+
import anthropic
|
| 25 |
+
import numpy as np
|
| 26 |
+
from decord import VideoReader, cpu
|
| 27 |
+
except Exception as e:
|
| 28 |
+
eval_logger.warning(f"Error importing claude: {e}")
|
| 29 |
+
|
| 30 |
+
API_URL = os.getenv("ANTHROPIC_API_URL", "https://api.anthropic.com/v1/complete")
|
| 31 |
+
API_KEY = os.getenv("ANTHROPIC_API_KEY", "YOUR_API_KEY")
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
@register_model("claude")
|
| 35 |
+
class Claude(lmms):
|
| 36 |
+
def __init__(
|
| 37 |
+
self,
|
| 38 |
+
model_version: str = "claude-3-opus-20240229",
|
| 39 |
+
image_token: str = "<image>", # Use to separate interleaved image and text
|
| 40 |
+
system_prompt: str = "", # Whether you want some special system prompt here
|
| 41 |
+
modality: str = "image",
|
| 42 |
+
max_frames_num: int = 10,
|
| 43 |
+
continual_mode: bool = False,
|
| 44 |
+
response_persistent_folder: str = None,
|
| 45 |
+
**kwargs,
|
| 46 |
+
) -> None:
|
| 47 |
+
super().__init__()
|
| 48 |
+
self.model_version = model_version
|
| 49 |
+
self.image_token = image_token
|
| 50 |
+
self.system_prompt = system_prompt
|
| 51 |
+
self.modality = modality
|
| 52 |
+
self.max_frames_num = max_frames_num
|
| 53 |
+
|
| 54 |
+
self.continual_mode = continual_mode
|
| 55 |
+
if self.continual_mode:
|
| 56 |
+
if response_persistent_folder is None:
|
| 57 |
+
raise ValueError("Continual mode requires a persistent path for the response. Please provide a valid path.")
|
| 58 |
+
|
| 59 |
+
os.makedirs(response_persistent_folder, exist_ok=True)
|
| 60 |
+
self.response_persistent_folder = response_persistent_folder
|
| 61 |
+
self.response_persistent_file = os.path.join(self.response_persistent_folder, f"{self.model_version}_response.json")
|
| 62 |
+
|
| 63 |
+
if os.path.exists(self.response_persistent_file):
|
| 64 |
+
with open(self.response_persistent_file, "r") as f:
|
| 65 |
+
self.response_cache = json.load(f)
|
| 66 |
+
self.cache_mode = "resume"
|
| 67 |
+
else:
|
| 68 |
+
self.response_cache = {}
|
| 69 |
+
self.cache_mode = "start"
|
| 70 |
+
|
| 71 |
+
accelerator = Accelerator()
|
| 72 |
+
if accelerator.num_processes > 1:
|
| 73 |
+
assert accelerator.distributed_type in [DistributedType.FSDP, DistributedType.MULTI_GPU, DistributedType.DEEPSPEED], "Unsupported distributed type provided. Only DDP and FSDP are supported."
|
| 74 |
+
self.accelerator = accelerator
|
| 75 |
+
if self.accelerator.is_local_main_process:
|
| 76 |
+
eval_logger.info(f"Using {accelerator.num_processes} devices with data parallelism")
|
| 77 |
+
self._rank = self.accelerator.local_process_index
|
| 78 |
+
self._world_size = self.accelerator.num_processes
|
| 79 |
+
else:
|
| 80 |
+
self.accelerator = accelerator
|
| 81 |
+
self._rank = self.accelerator.local_process_index
|
| 82 |
+
self._world_size = self.accelerator.num_processes
|
| 83 |
+
|
| 84 |
+
self.device = self.accelerator.device
|
| 85 |
+
|
| 86 |
+
def encode_image(self, image):
|
| 87 |
+
output_buffer = BytesIO()
|
| 88 |
+
image.save(output_buffer, format="JPEG")
|
| 89 |
+
byte_data = output_buffer.getvalue()
|
| 90 |
+
base64_str = base64.b64encode(byte_data).decode("utf-8")
|
| 91 |
+
return base64_str
|
| 92 |
+
|
| 93 |
+
def flatten(self, input):
|
| 94 |
+
new_list = []
|
| 95 |
+
for i in input:
|
| 96 |
+
for j in i:
|
| 97 |
+
new_list.append(j)
|
| 98 |
+
return new_list
|
| 99 |
+
|
| 100 |
+
def get_image_size(self, image):
|
| 101 |
+
# Create a BytesIO object to store the image bytes
|
| 102 |
+
img_byte_array = BytesIO()
|
| 103 |
+
|
| 104 |
+
# Save the image to the BytesIO object
|
| 105 |
+
image.save(img_byte_array, format="PNG")
|
| 106 |
+
|
| 107 |
+
# Get the size of the BytesIO object
|
| 108 |
+
img_size = img_byte_array.tell()
|
| 109 |
+
|
| 110 |
+
return img_size
|
| 111 |
+
|
| 112 |
+
# The max file size is 5MB for claude
|
| 113 |
+
def shrink_image_to_file_size(self, img: Image, max_file_size=4838990) -> Image:
|
| 114 |
+
# Get the current size of the image
|
| 115 |
+
original_size = self.get_image_size(img)
|
| 116 |
+
|
| 117 |
+
# If the image size is already smaller than the desired size, return
|
| 118 |
+
if original_size <= max_file_size:
|
| 119 |
+
return img
|
| 120 |
+
|
| 121 |
+
# Calculate the ratio to shrink the image
|
| 122 |
+
# Somehow I found out sqrt ratio is not enough to shrink the image
|
| 123 |
+
# below threshold, so I guess we do more
|
| 124 |
+
shrink_ratio = min(0.9, max_file_size / original_size)
|
| 125 |
+
|
| 126 |
+
# Resize the image with the calculated ratio
|
| 127 |
+
new_width = int(img.width * shrink_ratio)
|
| 128 |
+
new_height = int(img.height * shrink_ratio)
|
| 129 |
+
img = img.resize((new_width, new_height), Image.LANCZOS)
|
| 130 |
+
|
| 131 |
+
return self.shrink_image_to_file_size(img, max_file_size)
|
| 132 |
+
|
| 133 |
+
def encode_video(self, video_path):
|
| 134 |
+
vr = VideoReader(video_path, ctx=cpu(0))
|
| 135 |
+
total_frame_num = len(vr)
|
| 136 |
+
uniform_sampled_frames = np.linspace(0, total_frame_num - 1, self.max_frames_num, dtype=int)
|
| 137 |
+
frame_idx = uniform_sampled_frames.tolist()
|
| 138 |
+
frames = vr.get_batch(frame_idx).asnumpy()
|
| 139 |
+
|
| 140 |
+
base64_frames = []
|
| 141 |
+
for frame in frames:
|
| 142 |
+
img = Image.fromarray(frame)
|
| 143 |
+
output_buffer = BytesIO()
|
| 144 |
+
img.save(output_buffer, format="JPEG")
|
| 145 |
+
byte_data = output_buffer.getvalue()
|
| 146 |
+
base64_str = base64.b64encode(byte_data).decode("utf-8")
|
| 147 |
+
base64_frames.append(f"{base64_str}")
|
| 148 |
+
|
| 149 |
+
return base64_frames
|
| 150 |
+
|
| 151 |
+
def generate_until(self, requests) -> List[str]:
|
| 152 |
+
client = anthropic.Anthropic()
|
| 153 |
+
|
| 154 |
+
res = []
|
| 155 |
+
pbar = tqdm(total=len(requests), disable=(self.rank != 0), desc="Model Responding")
|
| 156 |
+
|
| 157 |
+
empty_image_block = {
|
| 158 |
+
"type": "image",
|
| 159 |
+
"source": {
|
| 160 |
+
"type": "base64",
|
| 161 |
+
"media_type": "image/jpeg",
|
| 162 |
+
},
|
| 163 |
+
}
|
| 164 |
+
empty_text_block = {"type": "text"}
|
| 165 |
+
empty_messages = [
|
| 166 |
+
{
|
| 167 |
+
"role": "user",
|
| 168 |
+
"content": [],
|
| 169 |
+
}
|
| 170 |
+
]
|
| 171 |
+
|
| 172 |
+
for contexts, gen_kwargs, doc_to_visual, doc_id, task, split in [reg.args for reg in requests]:
|
| 173 |
+
###################### CONTINUAL MODE ######################
|
| 174 |
+
if self.continual_mode is True and self.cache_mode == "resume":
|
| 175 |
+
doc_uuid = f"{task}___{split}___{doc_id}"
|
| 176 |
+
if doc_uuid in self.response_cache:
|
| 177 |
+
response_text = self.response_cache[doc_uuid]
|
| 178 |
+
if response_text:
|
| 179 |
+
res.append(response_text)
|
| 180 |
+
pbar.update(1)
|
| 181 |
+
continue
|
| 182 |
+
|
| 183 |
+
visuals = [doc_to_visual(self.task_dict[task][split][doc_id])]
|
| 184 |
+
visuals = self.flatten(visuals)
|
| 185 |
+
imgs = []
|
| 186 |
+
for visual in visuals:
|
| 187 |
+
if isinstance(visual, str) and os.path.exists(visual): # Assuming visual is a path to a video
|
| 188 |
+
visual = self.encode_video(visual)
|
| 189 |
+
for img in visual:
|
| 190 |
+
imgs.append(img)
|
| 191 |
+
else:
|
| 192 |
+
visual = self.shrink_image_to_file_size(visual)
|
| 193 |
+
img = self.encode_image(visual)
|
| 194 |
+
imgs.append(img)
|
| 195 |
+
|
| 196 |
+
messages = deepcopy(empty_messages)
|
| 197 |
+
|
| 198 |
+
if self.image_token not in contexts:
|
| 199 |
+
for img in imgs:
|
| 200 |
+
image_block = deepcopy(empty_image_block)
|
| 201 |
+
image_block["source"]["data"] = img
|
| 202 |
+
messages[0]["content"].append(image_block)
|
| 203 |
+
text_block = deepcopy(empty_text_block)
|
| 204 |
+
text_block["text"] = contexts
|
| 205 |
+
messages[0]["content"].append(text_block)
|
| 206 |
+
else:
|
| 207 |
+
contexts = contexts.split(self.image_token)
|
| 208 |
+
for idx, img in enumerate(imgs):
|
| 209 |
+
text_block = deepcopy(empty_text_block)
|
| 210 |
+
image_block = deepcopy(empty_image_block)
|
| 211 |
+
text_block["text"] = contexts
|
| 212 |
+
messages[0]["content"].append(text_block)
|
| 213 |
+
image_block["source"]["data"] = img
|
| 214 |
+
messages[0]["content"].append(image_block)
|
| 215 |
+
|
| 216 |
+
# If n image tokens are in the contexts
|
| 217 |
+
# contexts will be splitted into n+1 chunks
|
| 218 |
+
# Manually add it into the messages
|
| 219 |
+
text_block = deepcopy(empty_text_block)
|
| 220 |
+
text_block["text"] = contexts
|
| 221 |
+
messages["content"].append(text_block)
|
| 222 |
+
|
| 223 |
+
if "max_new_tokens" not in gen_kwargs:
|
| 224 |
+
gen_kwargs["max_new_tokens"] = 1024
|
| 225 |
+
if gen_kwargs["max_new_tokens"] > 4096:
|
| 226 |
+
gen_kwargs["max_new_tokens"] = 4096
|
| 227 |
+
if "temperature" not in gen_kwargs:
|
| 228 |
+
gen_kwargs["temperature"] = 0
|
| 229 |
+
if "top_p" not in gen_kwargs or gen_kwargs["top_p"] is None:
|
| 230 |
+
gen_kwargs["top_p"] = 1
|
| 231 |
+
if "num_beams" not in gen_kwargs:
|
| 232 |
+
gen_kwargs["num_beams"] = 1
|
| 233 |
+
|
| 234 |
+
for attempt in range(5):
|
| 235 |
+
try:
|
| 236 |
+
message = client.messages.create(model=self.model_version, max_tokens=gen_kwargs["max_new_tokens"], system=self.system_prompt, temperature=gen_kwargs["temperature"], top_p=gen_kwargs["top_p"], messages=messages)
|
| 237 |
+
except Exception as e:
|
| 238 |
+
eval_logger.info(f"Attempt {attempt + 1} failed with error: {str(e)}")
|
| 239 |
+
if attempt < 5 - 1: # If we have retries left, sleep and then continue to next attempt
|
| 240 |
+
time.sleep(NUM_SECONDS_TO_SLEEP)
|
| 241 |
+
else: # If this was the last attempt, log and return empty
|
| 242 |
+
eval_logger.error(f"All 5 attempts failed. Last error message: {str(e)}")
|
| 243 |
+
res.append("")
|
| 244 |
+
pbar.update(1)
|
| 245 |
+
continue
|
| 246 |
+
|
| 247 |
+
response_text = message.content[0].text
|
| 248 |
+
res.append(message.content[0].text)
|
| 249 |
+
pbar.update(1)
|
| 250 |
+
|
| 251 |
+
###################### CONTINUAL MODE ######################
|
| 252 |
+
if self.continual_mode is True: # Cache the response
|
| 253 |
+
response_text = message.content[0].text
|
| 254 |
+
doc_uuid = f"{task}___{split}___{doc_id}"
|
| 255 |
+
self.response_cache[doc_uuid] = response_text
|
| 256 |
+
with open(self.response_persistent_file, "w") as f:
|
| 257 |
+
json.dump(self.response_cache, f)
|
| 258 |
+
|
| 259 |
+
pbar.close()
|
| 260 |
+
|
| 261 |
+
return res
|
| 262 |
+
|
| 263 |
+
def loglikelihood(self, requests: List[Instance]) -> List[Tuple[float, bool]]:
|
| 264 |
+
assert False, "Not supported for claude"
|
spatial-model/GeoThinker/src/lmms_eval/models/from_log.py
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import os
|
| 3 |
+
import re
|
| 4 |
+
from datetime import datetime
|
| 5 |
+
from typing import List, Tuple
|
| 6 |
+
|
| 7 |
+
from accelerate import Accelerator, DistributedType
|
| 8 |
+
from loguru import logger as eval_logger
|
| 9 |
+
from tqdm import tqdm
|
| 10 |
+
|
| 11 |
+
from lmms_eval.api.instance import Instance
|
| 12 |
+
from lmms_eval.api.model import lmms
|
| 13 |
+
from lmms_eval.api.registry import register_model
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
@register_model("from_log")
|
| 17 |
+
class FromLog(lmms):
|
| 18 |
+
def __init__(
|
| 19 |
+
self,
|
| 20 |
+
logs: str = "logs",
|
| 21 |
+
model_name: str = None,
|
| 22 |
+
model_args: str = None,
|
| 23 |
+
have_limits: bool = False,
|
| 24 |
+
**kwargs,
|
| 25 |
+
) -> None:
|
| 26 |
+
super().__init__()
|
| 27 |
+
|
| 28 |
+
self.logs = {}
|
| 29 |
+
|
| 30 |
+
log_folders = logs.split(",")
|
| 31 |
+
|
| 32 |
+
def matched_model(_model_args):
|
| 33 |
+
if model_name and model_name != _model_args["model"]:
|
| 34 |
+
return False
|
| 35 |
+
|
| 36 |
+
if model_args:
|
| 37 |
+
_model_args_list = model_args.split(",")
|
| 38 |
+
|
| 39 |
+
for _model_arg in _model_args_list:
|
| 40 |
+
if _model_arg not in _model_args["model_args"]:
|
| 41 |
+
return False
|
| 42 |
+
|
| 43 |
+
if not have_limits and _model_args["limit"] is not None:
|
| 44 |
+
return False
|
| 45 |
+
|
| 46 |
+
return True
|
| 47 |
+
|
| 48 |
+
for log_folder in log_folders:
|
| 49 |
+
for root, dirs, files in os.walk(log_folder):
|
| 50 |
+
for file in files:
|
| 51 |
+
if file.endswith(".json"):
|
| 52 |
+
try:
|
| 53 |
+
log_file = os.path.join(root, file)
|
| 54 |
+
|
| 55 |
+
with open(log_file, "r") as f:
|
| 56 |
+
log_data = json.load(f)
|
| 57 |
+
|
| 58 |
+
# check if model is matched
|
| 59 |
+
_model_args = log_data["args"]
|
| 60 |
+
if not matched_model(_model_args):
|
| 61 |
+
raise Exception("Model not matched")
|
| 62 |
+
|
| 63 |
+
# load logs
|
| 64 |
+
logs = {}
|
| 65 |
+
for data in log_data["logs"]:
|
| 66 |
+
id = data["doc_id"]
|
| 67 |
+
response = data["resps"][0]
|
| 68 |
+
logs[id] = response
|
| 69 |
+
|
| 70 |
+
task = log_data["model_configs"]["task"]
|
| 71 |
+
|
| 72 |
+
pattern = re.compile(r"\d{4}_\d{4}")
|
| 73 |
+
|
| 74 |
+
if "time" in log_data:
|
| 75 |
+
log_time = log_data["time"]
|
| 76 |
+
elif pattern.search(os.path.abspath(log_file)):
|
| 77 |
+
log_time = pattern.findall(os.path.abspath(log_file))[-1]
|
| 78 |
+
else:
|
| 79 |
+
log_time = "unknown"
|
| 80 |
+
|
| 81 |
+
if task not in self.logs or (self.logs[task]["time"] == "unknown" or datetime.strptime(log_time, "%m%d_%H%M") > datetime.strptime(self.logs[task]["time"], "%m%d_%H%M")):
|
| 82 |
+
self.logs[task] = {"time": log_time, "logs": logs}
|
| 83 |
+
|
| 84 |
+
except Exception as e:
|
| 85 |
+
pass
|
| 86 |
+
|
| 87 |
+
accelerator = Accelerator()
|
| 88 |
+
if accelerator.num_processes > 1:
|
| 89 |
+
assert accelerator.distributed_type in [DistributedType.FSDP, DistributedType.MULTI_GPU, DistributedType.DEEPSPEED], "Unsupported distributed type provided. Only DDP and FSDP are supported."
|
| 90 |
+
self.accelerator = accelerator
|
| 91 |
+
if self.accelerator.is_local_main_process:
|
| 92 |
+
eval_logger.info(f"Using {accelerator.num_processes} devices with data parallelism")
|
| 93 |
+
self._rank = self.accelerator.local_process_index
|
| 94 |
+
self._world_size = self.accelerator.num_processes
|
| 95 |
+
else:
|
| 96 |
+
self.accelerator = accelerator
|
| 97 |
+
self._rank = self.accelerator.local_process_index
|
| 98 |
+
self._world_size = self.accelerator.num_processes
|
| 99 |
+
|
| 100 |
+
self.device = self.accelerator.device
|
| 101 |
+
|
| 102 |
+
def generate_until(self, requests) -> List[str]:
|
| 103 |
+
res = []
|
| 104 |
+
pbar = tqdm(total=len(requests), disable=(self.rank != 0), desc="Model Responding")
|
| 105 |
+
|
| 106 |
+
for contexts, gen_kwargs, doc_to_visual, doc_id, task, split in [reg.args for reg in requests]:
|
| 107 |
+
response = self.logs[task]["logs"][doc_id]
|
| 108 |
+
res.append(response[0])
|
| 109 |
+
pbar.update(1)
|
| 110 |
+
|
| 111 |
+
pbar.close()
|
| 112 |
+
return res
|
| 113 |
+
|
| 114 |
+
def loglikelihood(self, requests: List[Instance]) -> List[Tuple[float, bool]]:
|
| 115 |
+
# TODO
|
| 116 |
+
assert False, "not support"
|
spatial-model/GeoThinker/src/lmms_eval/models/llava_hf.py
ADDED
|
@@ -0,0 +1,342 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import warnings
|
| 2 |
+
from typing import List, Optional, Tuple, Union
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
from accelerate import Accelerator, DistributedType
|
| 6 |
+
from accelerate.state import AcceleratorState
|
| 7 |
+
from tqdm import tqdm
|
| 8 |
+
from transformers import (
|
| 9 |
+
AutoProcessor,
|
| 10 |
+
LlavaForConditionalGeneration,
|
| 11 |
+
LlavaNextForConditionalGeneration,
|
| 12 |
+
)
|
| 13 |
+
|
| 14 |
+
from lmms_eval import utils
|
| 15 |
+
from lmms_eval.api.instance import Instance
|
| 16 |
+
from lmms_eval.api.model import lmms
|
| 17 |
+
from lmms_eval.api.registry import register_model
|
| 18 |
+
|
| 19 |
+
warnings.filterwarnings("ignore")
|
| 20 |
+
|
| 21 |
+
from loguru import logger as eval_logger
|
| 22 |
+
|
| 23 |
+
DEFAULT_IMAGE_TOKEN = "<image>"
|
| 24 |
+
|
| 25 |
+
# Default chat for llava-hf/llava-1.5 models: https://huggingface.co/collections/llava-hf/llava-15-65f762d5b6941db5c2ba07e0
|
| 26 |
+
VICUNA_CHAT_TEMPLATE = "{% for message in messages %}{% if loop.index0 == 0 %}A chat between a curious user and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the user's questions. USER: {{ message['content'] }} {% elif message['role'] == 'user' %}USER: {{ message['content'] }} {% else %} ASSISTANT: {{ message['content'] }}{{ eos_token }}{% endif %}{% endfor %}{% if add_generation_prompt %}{{ 'ASSISTANT:' }}{% endif %}"
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
@register_model("llava_hf")
|
| 30 |
+
class LlavaHf(lmms):
|
| 31 |
+
"""
|
| 32 |
+
Llava Model for Hugging Face Transformers: https://huggingface.co/docs/transformers/v4.39.3/en/model_doc/llava
|
| 33 |
+
|
| 34 |
+
Adapted from the InstructBLIP model in lmms_eval/models/instructblip.py
|
| 35 |
+
|
| 36 |
+
Example usage:
|
| 37 |
+
|
| 38 |
+
accelerate launch --num_processes=8 --main_process_port 12345 -m lmms_eval \
|
| 39 |
+
--model llava_hf \
|
| 40 |
+
--model_args pretrained=llava-hf/llava-1.5-7b-hf \
|
| 41 |
+
--tasks seedbench \
|
| 42 |
+
--batch_size 1 \
|
| 43 |
+
--output_path ./logs/ \
|
| 44 |
+
--log_samples
|
| 45 |
+
"""
|
| 46 |
+
|
| 47 |
+
def __init__(
|
| 48 |
+
self,
|
| 49 |
+
pretrained: str = "llava-hf/llava-1.5-7b-hf",
|
| 50 |
+
revision: str = "main",
|
| 51 |
+
device: str = "cuda",
|
| 52 |
+
dtype: Optional[Union[str, torch.dtype]] = "auto",
|
| 53 |
+
batch_size: int = 1,
|
| 54 |
+
trust_remote_code: Optional[bool] = False,
|
| 55 |
+
attn_implementation: Optional[str] = None,
|
| 56 |
+
device_map: str = "",
|
| 57 |
+
chat_template: Optional[str] = None,
|
| 58 |
+
use_cache: bool = True,
|
| 59 |
+
specified_eot_token_id: Optional[int] = None,
|
| 60 |
+
**kwargs,
|
| 61 |
+
) -> None:
|
| 62 |
+
super().__init__()
|
| 63 |
+
# Do not use kwargs for now
|
| 64 |
+
assert kwargs == {}, f"Unexpected kwargs: {kwargs}"
|
| 65 |
+
|
| 66 |
+
accelerator = Accelerator()
|
| 67 |
+
if accelerator.num_processes > 1 and device_map == "":
|
| 68 |
+
self._device = torch.device(f"cuda:{accelerator.local_process_index}")
|
| 69 |
+
self.device_map = f"cuda:{accelerator.local_process_index}"
|
| 70 |
+
else:
|
| 71 |
+
self._device = torch.device(device)
|
| 72 |
+
self.device_map = device_map
|
| 73 |
+
if isinstance(dtype, str) and dtype != "auto":
|
| 74 |
+
dtype = getattr(torch, dtype)
|
| 75 |
+
|
| 76 |
+
if "1.5" in pretrained:
|
| 77 |
+
self._model = LlavaForConditionalGeneration.from_pretrained(pretrained, revision=revision, torch_dtype=dtype, device_map=self.device_map, trust_remote_code=trust_remote_code, attn_implementation=attn_implementation)
|
| 78 |
+
elif "1.6" in pretrained:
|
| 79 |
+
self._model = LlavaNextForConditionalGeneration.from_pretrained(pretrained, revision=revision, torch_dtype=dtype, device_map=self.device_map, trust_remote_code=trust_remote_code, attn_implementation=attn_implementation)
|
| 80 |
+
else:
|
| 81 |
+
eval_logger.info("Not sure whether you use 1.5 or 1.6. Use 1.5 by default. This might cause bugs if you are actually using 1.6")
|
| 82 |
+
self._model = LlavaForConditionalGeneration.from_pretrained(pretrained, revision=revision, torch_dtype=dtype, device_map=self.device_map, trust_remote_code=trust_remote_code, attn_implementation=attn_implementation)
|
| 83 |
+
|
| 84 |
+
self.pretrained = pretrained
|
| 85 |
+
self._image_processor = AutoProcessor.from_pretrained(pretrained, revision=revision, trust_remote_code=trust_remote_code)
|
| 86 |
+
# Pad from left for batched generation: https://huggingface.co/docs/transformers/v4.39.3/en/model_doc/llava#usage-tips
|
| 87 |
+
self._image_processor.tokenizer.padding_side = "left"
|
| 88 |
+
self._tokenizer = self._image_processor.tokenizer
|
| 89 |
+
self._config = self._model.config
|
| 90 |
+
self.batch_size_per_gpu = int(batch_size)
|
| 91 |
+
self.chat_template = chat_template
|
| 92 |
+
self.use_cache = use_cache
|
| 93 |
+
self.specified_eot_token_id = specified_eot_token_id
|
| 94 |
+
if accelerator.num_processes > 1 and device_map == "":
|
| 95 |
+
assert accelerator.distributed_type in [DistributedType.FSDP, DistributedType.MULTI_GPU, DistributedType.DEEPSPEED], "Unsupported distributed type provided. Only DDP and FSDP are supported."
|
| 96 |
+
# If you want to use DistributedType.DEEPSPEED, you have to run accelerate config before using the model
|
| 97 |
+
# Also, you have to select zero stage 0 (equivalent to DDP) in order to make the prepare model works
|
| 98 |
+
# I tried to set different parameters in the kwargs to let default zero 2 stage works, but it didn't work.
|
| 99 |
+
if accelerator.distributed_type == DistributedType.DEEPSPEED:
|
| 100 |
+
kwargs = {
|
| 101 |
+
"train_micro_batch_size_per_gpu": self.batch_size_per_gpu,
|
| 102 |
+
"train_batch_size": self.batch_size_per_gpu * accelerator.num_processes,
|
| 103 |
+
}
|
| 104 |
+
AcceleratorState().deepspeed_plugin.deepspeed_config_process(must_match=True, **kwargs)
|
| 105 |
+
eval_logger.info("Detected that you are using DistributedType.DEEPSPEED. Make sure you run `accelerate config` and set zero stage to 0")
|
| 106 |
+
if accelerator.distributed_type == DistributedType.FSDP or accelerator.distributed_type == DistributedType.DEEPSPEED:
|
| 107 |
+
self._model = accelerator.prepare(self.model)
|
| 108 |
+
else:
|
| 109 |
+
self._model = accelerator.prepare_model(self.model, evaluation_mode=True)
|
| 110 |
+
self.accelerator = accelerator
|
| 111 |
+
if self.accelerator.is_local_main_process:
|
| 112 |
+
eval_logger.info(f"Using {accelerator.num_processes} devices with data parallelism")
|
| 113 |
+
self._rank = self.accelerator.local_process_index
|
| 114 |
+
self._world_size = self.accelerator.num_processes
|
| 115 |
+
elif accelerator.num_processes == 1 and device_map == "auto":
|
| 116 |
+
eval_logger.info(f"Using {accelerator.num_processes} devices with pipeline parallelism")
|
| 117 |
+
self._rank = 0
|
| 118 |
+
self._word_size = 1
|
| 119 |
+
else:
|
| 120 |
+
eval_logger.info(f"Using single device: {self._device}")
|
| 121 |
+
self.model.to(self._device)
|
| 122 |
+
self._rank = 0
|
| 123 |
+
self._word_size = 1
|
| 124 |
+
self.accelerator = accelerator
|
| 125 |
+
|
| 126 |
+
@property
|
| 127 |
+
def config(self):
|
| 128 |
+
# return the associated transformers.AutoConfig for the given pretrained model.
|
| 129 |
+
return self._config
|
| 130 |
+
|
| 131 |
+
@property
|
| 132 |
+
def tokenizer(self):
|
| 133 |
+
return self._tokenizer
|
| 134 |
+
|
| 135 |
+
@property
|
| 136 |
+
def model(self):
|
| 137 |
+
# returns the model, unwrapping it if using Accelerate
|
| 138 |
+
if hasattr(self, "accelerator"):
|
| 139 |
+
return self.accelerator.unwrap_model(self._model)
|
| 140 |
+
else:
|
| 141 |
+
return self._model
|
| 142 |
+
|
| 143 |
+
@property
|
| 144 |
+
def eot_token_id(self):
|
| 145 |
+
# we use EOT because end of *text* is more accurate for what we're doing than end of *sentence*
|
| 146 |
+
return self.tokenizer.eos_token_id
|
| 147 |
+
|
| 148 |
+
@property
|
| 149 |
+
def max_length(self):
|
| 150 |
+
return self._max_length
|
| 151 |
+
|
| 152 |
+
@property
|
| 153 |
+
def batch_size(self):
|
| 154 |
+
return self.batch_size_per_gpu
|
| 155 |
+
|
| 156 |
+
@property
|
| 157 |
+
def device(self):
|
| 158 |
+
return self._device
|
| 159 |
+
|
| 160 |
+
@property
|
| 161 |
+
def rank(self):
|
| 162 |
+
return self._rank
|
| 163 |
+
|
| 164 |
+
@property
|
| 165 |
+
def world_size(self):
|
| 166 |
+
return self._world_size
|
| 167 |
+
|
| 168 |
+
def tok_encode(self, string: str, left_truncate_len=None, add_special_tokens=None) -> List[int]:
|
| 169 |
+
""" """
|
| 170 |
+
add_special_tokens = False if add_special_tokens is None else add_special_tokens
|
| 171 |
+
encoding = self.tokenizer.encode(string, add_special_tokens=add_special_tokens)
|
| 172 |
+
# left-truncate the encoded context to be at most `left_truncate_len` tokens long
|
| 173 |
+
if left_truncate_len:
|
| 174 |
+
encoding = encoding[-left_truncate_len:]
|
| 175 |
+
return encoding
|
| 176 |
+
|
| 177 |
+
def tok_decode(self, tokens):
|
| 178 |
+
return self.tokenizer.decode(tokens)
|
| 179 |
+
|
| 180 |
+
def loglikelihood(self, requests: List[Instance]) -> List[Tuple[float, bool]]:
|
| 181 |
+
res = []
|
| 182 |
+
pbar = tqdm(total=len(requests), disable=(self.rank != 0), desc="Model Responding")
|
| 183 |
+
|
| 184 |
+
for context, doc_to_target, doc_to_visual, doc_id, task, split in [reg.args for reg in requests]:
|
| 185 |
+
# encode, pad, and truncate contexts for this batch
|
| 186 |
+
if type(doc_to_target) == str:
|
| 187 |
+
continuation = doc_to_target
|
| 188 |
+
else:
|
| 189 |
+
continuation = doc_to_target(self.task_dict[task][split][doc_id])
|
| 190 |
+
visuals = [doc_to_visual(self.task_dict[task][split][doc_id])]
|
| 191 |
+
visuals = self.flatten(visuals)
|
| 192 |
+
|
| 193 |
+
image_tokens = [DEFAULT_IMAGE_TOKEN] * len(visuals)
|
| 194 |
+
image_tokens = " ".join(image_tokens)
|
| 195 |
+
context = f"{image_tokens}\n{context}"
|
| 196 |
+
# Apply chat template
|
| 197 |
+
messages = [{"role": "user", "content": context}, {"role": "assistant", "content": continuation}]
|
| 198 |
+
if self.chat_template is not None:
|
| 199 |
+
self.tokenizer.chat_template = self.chat_template
|
| 200 |
+
prompt = self.tokenizer.apply_chat_template(messages[:-1], tokenize=False, add_generation_prompt=True)
|
| 201 |
+
prompt_and_continuation = self.tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=False)
|
| 202 |
+
elif self.tokenizer.chat_template is not None:
|
| 203 |
+
prompt = self.tokenizer.apply_chat_template(messages[:-1], tokenize=False, add_generation_prompt=True)
|
| 204 |
+
prompt_and_continuation = self.tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=False)
|
| 205 |
+
else:
|
| 206 |
+
self.tokenizer.chat_template = VICUNA_CHAT_TEMPLATE
|
| 207 |
+
prompt = self.tokenizer.apply_chat_template(messages[:-1], tokenize=False, add_generation_prompt=True)
|
| 208 |
+
prompt_and_continuation = self.tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=False)
|
| 209 |
+
|
| 210 |
+
formatted_contexts = [prompt]
|
| 211 |
+
formatted_continuation = [prompt_and_continuation]
|
| 212 |
+
model_inputs = self._image_processor(text=formatted_continuation, images=visuals).to(self._device, self.model.dtype)
|
| 213 |
+
labels = model_inputs["input_ids"].clone()
|
| 214 |
+
contxt_id = self._image_processor(text=formatted_contexts, return_tensors="pt")["input_ids"]
|
| 215 |
+
labels[: len(contxt_id)] = -100
|
| 216 |
+
|
| 217 |
+
if self.accelerator.is_main_process and doc_id % 100 == 0:
|
| 218 |
+
eval_logger.debug(f"Prompt for doc ID {doc_id}:\n\n{formatted_contexts[0]}\n")
|
| 219 |
+
eval_logger.debug(f"Prompt and continuation for doc ID {doc_id}:\n\n{formatted_continuation[0]}\n")
|
| 220 |
+
|
| 221 |
+
with torch.inference_mode():
|
| 222 |
+
outputs = self.model(**model_inputs, labels=labels)
|
| 223 |
+
loss = outputs["loss"]
|
| 224 |
+
logits = outputs["logits"]
|
| 225 |
+
greedy_tokens = logits.argmax(dim=-1)
|
| 226 |
+
cont_toks = model_inputs["input_ids"][:, contxt_id.shape[1] :] # [1, seq]
|
| 227 |
+
greedy_tokens = greedy_tokens[:, contxt_id.shape[1] : model_inputs["input_ids"].shape[1]] # [1, seq]
|
| 228 |
+
max_equal = (greedy_tokens == cont_toks).all()
|
| 229 |
+
res.append((float(loss.item()), bool(max_equal)))
|
| 230 |
+
pbar.update(1)
|
| 231 |
+
|
| 232 |
+
pbar.close()
|
| 233 |
+
return res
|
| 234 |
+
|
| 235 |
+
def flatten(self, input):
|
| 236 |
+
new_list = []
|
| 237 |
+
for i in input:
|
| 238 |
+
for j in i:
|
| 239 |
+
new_list.append(j)
|
| 240 |
+
return new_list
|
| 241 |
+
|
| 242 |
+
def generate_until(self, requests: List[Instance]) -> List[str]:
|
| 243 |
+
res = []
|
| 244 |
+
|
| 245 |
+
def _collate(x):
|
| 246 |
+
# the negative sign on len(toks) sorts descending - this has a few advantages:
|
| 247 |
+
# - time estimates will always be over not underestimates, which is more useful for planning
|
| 248 |
+
# - to know the size of a batch when going through the list, you know the first one is always the batch
|
| 249 |
+
# padded context length. this is useful to simplify the batching logic and more importantly to make
|
| 250 |
+
# automatic adaptive batches much much easier to implement
|
| 251 |
+
# - any OOMs will happen right away rather than near the end
|
| 252 |
+
toks = self.tok_encode(x[0])
|
| 253 |
+
return -len(toks), x[0]
|
| 254 |
+
|
| 255 |
+
# we group requests by their generation_kwargs,
|
| 256 |
+
# so that we don't try to execute e.g. greedy sampling and temp=0.8 sampling
|
| 257 |
+
# in the same batch.
|
| 258 |
+
re_ords = utils.Collator([reg.args for reg in requests], _collate, grouping=True)
|
| 259 |
+
chunks = re_ords.get_batched(n=self.batch_size, batch_fn=None)
|
| 260 |
+
num_iters = len(requests) // self.batch_size if len(requests) % self.batch_size == 0 else len(requests) // self.batch_size + 1
|
| 261 |
+
pbar = tqdm(total=num_iters, disable=(self.rank != 0), desc="Model Responding")
|
| 262 |
+
for chunk in chunks:
|
| 263 |
+
contexts, all_gen_kwargs, doc_to_visual, doc_id, task, split = zip(*chunk)
|
| 264 |
+
task = task[0]
|
| 265 |
+
split = split[0]
|
| 266 |
+
visuals = [doc_to_visual[0](self.task_dict[task][split][ids]) for ids in doc_id]
|
| 267 |
+
visuals = self.flatten(visuals)
|
| 268 |
+
# we assume all gen kwargs in the batch are the same
|
| 269 |
+
# this is safe to assume because the `grouper` object ensures it.
|
| 270 |
+
gen_kwargs = all_gen_kwargs[0]
|
| 271 |
+
|
| 272 |
+
# Set default values for until and max_new_tokens
|
| 273 |
+
until = [self.tok_decode(self.eot_token_id)]
|
| 274 |
+
|
| 275 |
+
# Update values from gen_kwargs if present
|
| 276 |
+
if "until" in gen_kwargs:
|
| 277 |
+
until = gen_kwargs.pop("until")
|
| 278 |
+
if isinstance(until, str):
|
| 279 |
+
until = [until]
|
| 280 |
+
elif not isinstance(until, list):
|
| 281 |
+
raise ValueError(f"Expected `gen_kwargs['until']` to be of type Union[str,list] but got {type(until)}")
|
| 282 |
+
assert self.batch_size_per_gpu == 1, "Do not support batch_size_per_gpu > 1 for now"
|
| 283 |
+
context = contexts[0]
|
| 284 |
+
|
| 285 |
+
# Some benchmarks like MME do not contain image tokens, so we prepend them to the prompt.
|
| 286 |
+
if DEFAULT_IMAGE_TOKEN not in context:
|
| 287 |
+
image_tokens = [DEFAULT_IMAGE_TOKEN] * len(visuals)
|
| 288 |
+
image_tokens = " ".join(image_tokens)
|
| 289 |
+
context = f"{image_tokens}\n{context}"
|
| 290 |
+
# Apply chat template
|
| 291 |
+
messages = [{"role": "user", "content": context}]
|
| 292 |
+
if self.chat_template is not None:
|
| 293 |
+
self.tokenizer.chat_template = self.chat_template
|
| 294 |
+
text = self.tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
| 295 |
+
elif self.tokenizer.chat_template is not None:
|
| 296 |
+
text = self.tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
| 297 |
+
else:
|
| 298 |
+
self.tokenizer.chat_template = VICUNA_CHAT_TEMPLATE
|
| 299 |
+
text = self.tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
| 300 |
+
|
| 301 |
+
if self.accelerator.is_main_process and doc_id[0] % 100 == 0:
|
| 302 |
+
eval_logger.debug(f"Prompt for doc ID {doc_id[0]}:\n\n{text}\n")
|
| 303 |
+
|
| 304 |
+
inputs = self._image_processor(images=visuals, text=text, return_tensors="pt").to(self._device, self.model.dtype)
|
| 305 |
+
|
| 306 |
+
gen_kwargs["image_sizes"] = [visuals[idx].size for idx in range(len(visuals))]
|
| 307 |
+
if "max_new_tokens" not in gen_kwargs:
|
| 308 |
+
gen_kwargs["max_new_tokens"] = 1024
|
| 309 |
+
if "temperature" not in gen_kwargs:
|
| 310 |
+
gen_kwargs["temperature"] = 0
|
| 311 |
+
if "top_p" not in gen_kwargs:
|
| 312 |
+
gen_kwargs["top_p"] = None
|
| 313 |
+
if "num_beams" not in gen_kwargs:
|
| 314 |
+
gen_kwargs["num_beams"] = 1
|
| 315 |
+
try:
|
| 316 |
+
cont = self.model.generate(
|
| 317 |
+
**inputs,
|
| 318 |
+
do_sample=True if gen_kwargs["temperature"] > 0 else False,
|
| 319 |
+
temperature=gen_kwargs["temperature"],
|
| 320 |
+
top_p=gen_kwargs["top_p"],
|
| 321 |
+
num_beams=gen_kwargs["num_beams"],
|
| 322 |
+
max_new_tokens=gen_kwargs["max_new_tokens"],
|
| 323 |
+
use_cache=self.use_cache,
|
| 324 |
+
pad_token_id=self.tokenizer.eos_token_id,
|
| 325 |
+
eos_token_id=self.specified_eot_token_id,
|
| 326 |
+
)
|
| 327 |
+
cont = cont[:, inputs["input_ids"].shape[-1] :]
|
| 328 |
+
except Exception as e:
|
| 329 |
+
eval_logger.error(f"Error {e} in generating")
|
| 330 |
+
cont = ""
|
| 331 |
+
text_outputs = self.tokenizer.batch_decode(cont, skip_special_tokens=True)[0]
|
| 332 |
+
if self.accelerator.is_main_process and doc_id[0] % 100 == 0:
|
| 333 |
+
eval_logger.debug(f"Generated text for doc ID {doc_id[0]}:\n\n{text_outputs}\n")
|
| 334 |
+
|
| 335 |
+
res.append(text_outputs)
|
| 336 |
+
self.cache_hook.add_partial("generate_until", (context, gen_kwargs), text_outputs)
|
| 337 |
+
pbar.update(1)
|
| 338 |
+
# reorder this group of results back to original unsorted form
|
| 339 |
+
res = re_ords.get_original(res)
|
| 340 |
+
|
| 341 |
+
pbar.close()
|
| 342 |
+
return res
|
spatial-model/GeoThinker/src/lmms_eval/models/minicpm_v.py
ADDED
|
@@ -0,0 +1,221 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import warnings
|
| 2 |
+
from typing import List, Optional, Tuple, Union
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
from accelerate import Accelerator, DistributedType
|
| 6 |
+
from accelerate.state import AcceleratorState
|
| 7 |
+
from tqdm import tqdm
|
| 8 |
+
from transformers import AutoModel, AutoTokenizer
|
| 9 |
+
|
| 10 |
+
from lmms_eval import utils
|
| 11 |
+
from lmms_eval.api.instance import Instance
|
| 12 |
+
from lmms_eval.api.model import lmms
|
| 13 |
+
from lmms_eval.api.registry import register_model
|
| 14 |
+
|
| 15 |
+
warnings.filterwarnings("ignore")
|
| 16 |
+
|
| 17 |
+
from loguru import logger as eval_logger
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
@register_model("minicpm_v")
|
| 21 |
+
class MiniCPM_V(lmms):
|
| 22 |
+
"""
|
| 23 |
+
MiniCPM_V Model
|
| 24 |
+
"""
|
| 25 |
+
|
| 26 |
+
def __init__(
|
| 27 |
+
self,
|
| 28 |
+
pretrained: str = "openbmb/MiniCPM-V",
|
| 29 |
+
device: Optional[str] = "cuda",
|
| 30 |
+
dtype: Optional[Union[str, torch.dtype]] = torch.bfloat16,
|
| 31 |
+
batch_size: Optional[Union[int, str]] = 1,
|
| 32 |
+
trust_remote_code: Optional[bool] = True,
|
| 33 |
+
**kwargs,
|
| 34 |
+
) -> None:
|
| 35 |
+
super().__init__()
|
| 36 |
+
# Do not use kwargs for now
|
| 37 |
+
assert kwargs == {}, f"Unexpected kwargs: {kwargs}"
|
| 38 |
+
|
| 39 |
+
accelerator = Accelerator()
|
| 40 |
+
if accelerator.num_processes > 1:
|
| 41 |
+
self._device = torch.device(f"cuda:{accelerator.local_process_index}")
|
| 42 |
+
else:
|
| 43 |
+
self._device = device
|
| 44 |
+
self._model = AutoModel.from_pretrained(pretrained, trust_remote_code=trust_remote_code, torch_dtype=dtype, device_map=self._device).to(dtype)
|
| 45 |
+
self._tokenizer = AutoTokenizer.from_pretrained(pretrained, trust_remote_code=trust_remote_code)
|
| 46 |
+
self._config = self._model.config
|
| 47 |
+
self.model.eval()
|
| 48 |
+
self.model.tie_weights()
|
| 49 |
+
self.batch_size_per_gpu = int(batch_size)
|
| 50 |
+
if accelerator.num_processes > 1:
|
| 51 |
+
assert accelerator.distributed_type in [DistributedType.FSDP, DistributedType.MULTI_GPU, DistributedType.DEEPSPEED], "Unsupported distributed type provided. Only DDP and FSDP are supported."
|
| 52 |
+
# If you want to use DistributedType.DEEPSPEED, you have to run accelerate config before using the model
|
| 53 |
+
# Also, you have to select zero stage 0 (equivalent to DDP) in order to make the prepare model works
|
| 54 |
+
# I tried to set different parameters in the kwargs to let default zero 2 stage works, but it didn't work.
|
| 55 |
+
if accelerator.distributed_type == DistributedType.DEEPSPEED:
|
| 56 |
+
kwargs = {
|
| 57 |
+
"train_micro_batch_size_per_gpu": self.batch_size_per_gpu,
|
| 58 |
+
"train_batch_size": self.batch_size_per_gpu * accelerator.num_processes,
|
| 59 |
+
}
|
| 60 |
+
AcceleratorState().deepspeed_plugin.deepspeed_config_process(must_match=True, **kwargs)
|
| 61 |
+
eval_logger.info("Detected that you are using DistributedType.DEEPSPEED. Make sure you run `accelerate config` and set zero stage to 0")
|
| 62 |
+
if accelerator.distributed_type == DistributedType.FSDP or accelerator.distributed_type == DistributedType.DEEPSPEED:
|
| 63 |
+
self._model = accelerator.prepare(self.model)
|
| 64 |
+
else:
|
| 65 |
+
self._model = accelerator.prepare_model(self.model, evaluation_mode=True)
|
| 66 |
+
self.accelerator = accelerator
|
| 67 |
+
if self.accelerator.is_local_main_process:
|
| 68 |
+
eval_logger.info(f"Using {accelerator.num_processes} devices with data parallelism")
|
| 69 |
+
self._rank = self.accelerator.local_process_index
|
| 70 |
+
self._world_size = self.accelerator.num_processes
|
| 71 |
+
else:
|
| 72 |
+
self.model.to(self._device)
|
| 73 |
+
self._rank = 0
|
| 74 |
+
self._word_size = 1
|
| 75 |
+
|
| 76 |
+
@property
|
| 77 |
+
def config(self):
|
| 78 |
+
# return the associated transformers.AutoConfig for the given pretrained model.
|
| 79 |
+
return self._config
|
| 80 |
+
|
| 81 |
+
@property
|
| 82 |
+
def tokenizer(self):
|
| 83 |
+
return self._tokenizer
|
| 84 |
+
|
| 85 |
+
@property
|
| 86 |
+
def model(self):
|
| 87 |
+
# returns the model, unwrapping it if using Accelerate
|
| 88 |
+
if hasattr(self, "accelerator"):
|
| 89 |
+
return self.accelerator.unwrap_model(self._model)
|
| 90 |
+
else:
|
| 91 |
+
return self._model
|
| 92 |
+
|
| 93 |
+
@property
|
| 94 |
+
def eot_token_id(self):
|
| 95 |
+
# we use EOT because end of *text* is more accurate for what we're doing than end of *sentence*
|
| 96 |
+
return self.tokenizer.eos_token_id
|
| 97 |
+
|
| 98 |
+
@property
|
| 99 |
+
def max_length(self):
|
| 100 |
+
return self._max_length
|
| 101 |
+
|
| 102 |
+
@property
|
| 103 |
+
def batch_size(self):
|
| 104 |
+
return self.batch_size_per_gpu
|
| 105 |
+
|
| 106 |
+
@property
|
| 107 |
+
def device(self):
|
| 108 |
+
return self._device
|
| 109 |
+
|
| 110 |
+
@property
|
| 111 |
+
def rank(self):
|
| 112 |
+
return self._rank
|
| 113 |
+
|
| 114 |
+
@property
|
| 115 |
+
def world_size(self):
|
| 116 |
+
return self._world_size
|
| 117 |
+
|
| 118 |
+
def tok_encode(self, string: str, left_truncate_len=None, add_special_tokens=None) -> List[int]:
|
| 119 |
+
""" """
|
| 120 |
+
add_special_tokens = False if add_special_tokens is None else add_special_tokens
|
| 121 |
+
encoding = self.tokenizer.encode(string, add_special_tokens=add_special_tokens)
|
| 122 |
+
# left-truncate the encoded context to be at most `left_truncate_len` tokens long
|
| 123 |
+
if left_truncate_len:
|
| 124 |
+
encoding = encoding[-left_truncate_len:]
|
| 125 |
+
return encoding
|
| 126 |
+
|
| 127 |
+
def tok_decode(self, tokens):
|
| 128 |
+
return self.tokenizer.decode(tokens)
|
| 129 |
+
|
| 130 |
+
def loglikelihood(self, requests: List[Instance]) -> List[Tuple[float, bool]]:
|
| 131 |
+
# TODO
|
| 132 |
+
assert False, "We have not implemented this function for MiniCPM_V yet"
|
| 133 |
+
|
| 134 |
+
def flatten(self, input):
|
| 135 |
+
new_list = []
|
| 136 |
+
for i in input:
|
| 137 |
+
for j in i:
|
| 138 |
+
new_list.append(j)
|
| 139 |
+
return new_list
|
| 140 |
+
|
| 141 |
+
def generate_until(self, requests: List[Instance]) -> List[str]:
|
| 142 |
+
res = []
|
| 143 |
+
|
| 144 |
+
def _collate(x):
|
| 145 |
+
# the negative sign on len(toks) sorts descending - this has a few advantages:
|
| 146 |
+
# - time estimates will always be over not underestimates, which is more useful for planning
|
| 147 |
+
# - to know the size of a batch when going through the list, you know the first one is always the batch
|
| 148 |
+
# padded context length. this is useful to simplify the batching logic and more importantly to make
|
| 149 |
+
# automatic adaptive batches much much easier to implement
|
| 150 |
+
# - any OOMs will happen right away rather than near the end
|
| 151 |
+
toks = self.tok_encode(x[0])
|
| 152 |
+
return -len(toks), x[0]
|
| 153 |
+
|
| 154 |
+
# we group requests by their generation_kwargs,
|
| 155 |
+
# so that we don't try to execute e.g. greedy sampling and temp=0.8 sampling
|
| 156 |
+
# in the same batch.
|
| 157 |
+
re_ords = utils.Collator([reg.args for reg in requests], _collate, grouping=True)
|
| 158 |
+
chunks = re_ords.get_batched(n=self.batch_size, batch_fn=None)
|
| 159 |
+
num_iters = len(requests) // self.batch_size if len(requests) % self.batch_size == 0 else len(requests) // self.batch_size + 1
|
| 160 |
+
pbar = tqdm(total=num_iters, disable=(self.rank != 0), desc="Model Responding")
|
| 161 |
+
for chunk in chunks:
|
| 162 |
+
contexts, all_gen_kwargs, doc_to_visual, doc_id, task, split = zip(*chunk)
|
| 163 |
+
task = task[0]
|
| 164 |
+
split = split[0]
|
| 165 |
+
visuals = [doc_to_visual[0](self.task_dict[task][split][ids]) for ids in doc_id]
|
| 166 |
+
visuals = self.flatten(visuals)
|
| 167 |
+
# we assume all gen kwargs in the batch are the same
|
| 168 |
+
# this is safe to assume because the `grouper` object ensures it.
|
| 169 |
+
gen_kwargs = all_gen_kwargs[0]
|
| 170 |
+
|
| 171 |
+
# Set default values for until and max_new_tokens
|
| 172 |
+
until = [self.tok_decode(self.eot_token_id)]
|
| 173 |
+
|
| 174 |
+
# Update values from gen_kwargs if present
|
| 175 |
+
if "until" in gen_kwargs:
|
| 176 |
+
until = gen_kwargs.pop("until")
|
| 177 |
+
if isinstance(until, str):
|
| 178 |
+
until = [until]
|
| 179 |
+
elif not isinstance(until, list):
|
| 180 |
+
raise ValueError(f"Expected `gen_kwargs['until']` to be of type Union[str,list] but got {type(until)}")
|
| 181 |
+
assert self.batch_size_per_gpu == 1, "Do not support batch_size_per_gpu > 1 for now"
|
| 182 |
+
assert len(visuals) == 1, "MiniCPM_V interface does not support bn_image > 1 for now"
|
| 183 |
+
context = contexts[0]
|
| 184 |
+
if "<image>" in context:
|
| 185 |
+
# minicpm does not expect the <image> tag
|
| 186 |
+
context = context.replace("<image>", "")
|
| 187 |
+
msgs = [{"role": "user", "content": context}]
|
| 188 |
+
|
| 189 |
+
gen_kwargs["image_sizes"] = [visuals[idx].size for idx in range(len(visuals))]
|
| 190 |
+
if "max_new_tokens" not in gen_kwargs:
|
| 191 |
+
gen_kwargs["max_new_tokens"] = 1024
|
| 192 |
+
if "temperature" not in gen_kwargs:
|
| 193 |
+
gen_kwargs["temperature"] = 0
|
| 194 |
+
if "top_p" not in gen_kwargs:
|
| 195 |
+
gen_kwargs["top_p"] = None
|
| 196 |
+
if "num_beams" not in gen_kwargs:
|
| 197 |
+
gen_kwargs["num_beams"] = 1
|
| 198 |
+
try:
|
| 199 |
+
# ominicpm does not give much information on how they do eval so I just use the chat format.
|
| 200 |
+
response, context, _ = self.model.chat(
|
| 201 |
+
image=visuals[0],
|
| 202 |
+
msgs=msgs,
|
| 203 |
+
context=None,
|
| 204 |
+
tokenizer=self.tokenizer,
|
| 205 |
+
sampling=True if gen_kwargs["temperature"] > 0 else False,
|
| 206 |
+
temperature=gen_kwargs["temperature"],
|
| 207 |
+
top_p=gen_kwargs["top_p"],
|
| 208 |
+
num_beams=gen_kwargs["num_beams"],
|
| 209 |
+
max_new_tokens=gen_kwargs["max_new_tokens"],
|
| 210 |
+
)
|
| 211 |
+
except Exception as e:
|
| 212 |
+
eval_logger.error(f"Error {e} in generating")
|
| 213 |
+
cont = ""
|
| 214 |
+
res.append(response)
|
| 215 |
+
self.cache_hook.add_partial("generate_until", (context, gen_kwargs), response)
|
| 216 |
+
pbar.update(1)
|
| 217 |
+
# reorder this group of results back to original unsorted form
|
| 218 |
+
res = re_ords.get_original(res)
|
| 219 |
+
|
| 220 |
+
pbar.close()
|
| 221 |
+
return res
|
spatial-model/GeoThinker/src/lmms_eval/models/model_utils/__init__.py
ADDED
|
File without changes
|
spatial-model/GeoThinker/src/lmms_eval/models/model_utils/load_video.py
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import base64
|
| 2 |
+
from io import BytesIO
|
| 3 |
+
from random import sample
|
| 4 |
+
from typing import Optional, Tuple, Union
|
| 5 |
+
|
| 6 |
+
import av
|
| 7 |
+
import numpy as np
|
| 8 |
+
from av.codec.context import CodecContext
|
| 9 |
+
from decord import VideoReader, cpu
|
| 10 |
+
from PIL import Image
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def load_video_decord(video_path, max_frames_num):
|
| 14 |
+
if type(video_path) == str:
|
| 15 |
+
vr = VideoReader(video_path, ctx=cpu(0))
|
| 16 |
+
else:
|
| 17 |
+
vr = VideoReader(video_path[0], ctx=cpu(0))
|
| 18 |
+
total_frame_num = len(vr)
|
| 19 |
+
uniform_sampled_frames = np.linspace(0, total_frame_num - 1, max_frames_num, dtype=int)
|
| 20 |
+
frame_idx = uniform_sampled_frames.tolist()
|
| 21 |
+
spare_frames = vr.get_batch(frame_idx).asnumpy()
|
| 22 |
+
return spare_frames # (frames, height, width, channels)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
# This one is faster
|
| 26 |
+
def record_video_length_stream(container, indices):
|
| 27 |
+
frames = []
|
| 28 |
+
start_index = indices[0]
|
| 29 |
+
end_index = indices[-1]
|
| 30 |
+
for i, frame in enumerate(container.decode(video=0)):
|
| 31 |
+
if i > end_index:
|
| 32 |
+
break
|
| 33 |
+
if i >= start_index and i in indices:
|
| 34 |
+
frames.append(frame)
|
| 35 |
+
return frames
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
# This one works for all types of video
|
| 39 |
+
def record_video_length_packet(container):
|
| 40 |
+
frames = []
|
| 41 |
+
# https://github.com/PyAV-Org/PyAV/issues/1269
|
| 42 |
+
# https://www.cnblogs.com/beyond-tester/p/17641872.html
|
| 43 |
+
# context = CodecContext.create("libvpx-vp9", "r")
|
| 44 |
+
for packet in container.demux(video=0):
|
| 45 |
+
for frame in packet.decode():
|
| 46 |
+
frames.append(frame)
|
| 47 |
+
return frames
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def load_video_stream(container, num_frm: int = 8, fps: float = None, force_include_last_frame=False):
|
| 51 |
+
# container = av.open(video_path)
|
| 52 |
+
total_frames = container.streams.video[0].frames
|
| 53 |
+
frame_rate = container.streams.video[0].average_rate
|
| 54 |
+
if fps is not None:
|
| 55 |
+
video_length = total_frames / frame_rate
|
| 56 |
+
num_frm = min(num_frm, int(video_length * fps))
|
| 57 |
+
sampled_frm = min(total_frames, num_frm)
|
| 58 |
+
indices = np.linspace(0, total_frames - 1, sampled_frm, dtype=int)
|
| 59 |
+
if force_include_last_frame:
|
| 60 |
+
last_frame = total_frames - 1
|
| 61 |
+
if last_frame not in indices:
|
| 62 |
+
indices = np.linspace(0, total_frames - 2, sampled_frm - 1, dtype=int)
|
| 63 |
+
indices = np.append(indices, last_frame)
|
| 64 |
+
|
| 65 |
+
return record_video_length_stream(container, indices)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def load_video_packet(container, num_frm: int = 8, fps: float = None):
|
| 69 |
+
frames = record_video_length_packet(container)
|
| 70 |
+
total_frames = len(frames)
|
| 71 |
+
frame_rate = container.streams.video[0].average_rate
|
| 72 |
+
if fps is not None:
|
| 73 |
+
video_length = total_frames / frame_rate
|
| 74 |
+
num_frm = min(num_frm, int(video_length * fps))
|
| 75 |
+
sampled_frm = min(total_frames, num_frm)
|
| 76 |
+
indices = np.linspace(0, total_frames - 1, sampled_frm, dtype=int)
|
| 77 |
+
|
| 78 |
+
# Append the last frame index if not already included
|
| 79 |
+
if total_frames - 1 not in indices:
|
| 80 |
+
indices = np.append(indices, total_frames - 1)
|
| 81 |
+
|
| 82 |
+
return [frames[i] for i in indices]
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def read_video_pyav(video_path: str, *, num_frm: int = 8, fps: float = None, format="rgb24", force_include_last_frame=False) -> np.ndarray:
|
| 86 |
+
"""
|
| 87 |
+
Read video using the PyAV library.
|
| 88 |
+
|
| 89 |
+
Args:
|
| 90 |
+
video_path (str): The path to the video file.
|
| 91 |
+
num_frm (int, optional): The maximum number of frames to extract. Defaults to 8.
|
| 92 |
+
fps (float, optional): The frames per second for extraction. If `None`, the maximum number of frames will be extracted. Defaults to None.
|
| 93 |
+
format (str, optional): The format of the extracted frames. Defaults to "rgb24".
|
| 94 |
+
|
| 95 |
+
Returns:
|
| 96 |
+
np.ndarray: A numpy array containing the extracted frames in RGB format.
|
| 97 |
+
"""
|
| 98 |
+
|
| 99 |
+
container = av.open(video_path)
|
| 100 |
+
|
| 101 |
+
if "webm" not in video_path and "mkv" not in video_path:
|
| 102 |
+
# For mp4, we try loading with stream first
|
| 103 |
+
try:
|
| 104 |
+
frames = load_video_stream(container, num_frm, fps, force_include_last_frame=force_include_last_frame)
|
| 105 |
+
except:
|
| 106 |
+
frames = record_video_length_packet(container)
|
| 107 |
+
else:
|
| 108 |
+
frames = record_video_length_packet(container)
|
| 109 |
+
|
| 110 |
+
return np.stack([x.to_ndarray(format=format) for x in frames])
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def read_video_pyav_pil(video_path: str, *, num_frm: int = 8, fps: float = None, format="rgb24", max_image_size: Optional[Union[Tuple[int, int], int]] = None, resize_strategy: str = "resize", force_include_last_frame=False):
|
| 114 |
+
frames = read_video_pyav(video_path, num_frm=num_frm, fps=fps, format=format, force_include_last_frame=force_include_last_frame)
|
| 115 |
+
pil_frames = []
|
| 116 |
+
for frame in frames:
|
| 117 |
+
img = Image.fromarray(frame)
|
| 118 |
+
if max_image_size:
|
| 119 |
+
if resize_strategy == "resize":
|
| 120 |
+
if isinstance(max_image_size, int):
|
| 121 |
+
max_image_size = (max_image_size, max_image_size)
|
| 122 |
+
img = img.resize(max_image_size)
|
| 123 |
+
elif resize_strategy == "thumbnail":
|
| 124 |
+
img.thumbnail(max_image_size)
|
| 125 |
+
else:
|
| 126 |
+
raise ValueError(f"Unknown resize strategy: {resize_strategy}")
|
| 127 |
+
pil_frames.append(img)
|
| 128 |
+
return pil_frames
|
| 129 |
+
# return [Image.fromarray(frame) for frame in frames]
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def read_video_pyav_base64(video_path: str, *, num_frm: int = 8, fps: Optional[float] = None, format="rgb24", img_format="PNG", max_image_size: Optional[Union[Tuple[int, int], int]] = None, resize_strategy: str = "resize"):
|
| 133 |
+
frames = read_video_pyav(video_path, num_frm=num_frm, fps=fps, format=format)
|
| 134 |
+
base64_frames = []
|
| 135 |
+
for frame in frames:
|
| 136 |
+
img = Image.fromarray(frame)
|
| 137 |
+
if max_image_size:
|
| 138 |
+
if resize_strategy == "resize":
|
| 139 |
+
if isinstance(max_image_size, int):
|
| 140 |
+
max_image_size = (max_image_size, max_image_size)
|
| 141 |
+
img = img.resize(max_image_size)
|
| 142 |
+
elif resize_strategy == "thumbnail":
|
| 143 |
+
img.thumbnail(max_image_size)
|
| 144 |
+
else:
|
| 145 |
+
raise ValueError(f"Unknown resize strategy: {resize_strategy}")
|
| 146 |
+
output_buffer = BytesIO()
|
| 147 |
+
img.save(output_buffer, format=img_format)
|
| 148 |
+
byte_data = output_buffer.getvalue()
|
| 149 |
+
base64_str = base64.b64encode(byte_data).decode("utf-8")
|
| 150 |
+
base64_frames.append(base64_str)
|
| 151 |
+
return base64_frames
|
spatial-model/GeoThinker/src/lmms_eval/models/model_utils/qwen/qwen_generate_utils.py
ADDED
|
@@ -0,0 +1,369 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Alibaba Cloud.
|
| 2 |
+
#
|
| 3 |
+
# This source code is licensed under the license found in the
|
| 4 |
+
# LICENSE file in the root directory of this source tree.
|
| 5 |
+
|
| 6 |
+
"""Generation support."""
|
| 7 |
+
import warnings
|
| 8 |
+
|
| 9 |
+
warnings.simplefilter("ignore", category=DeprecationWarning)
|
| 10 |
+
warnings.filterwarnings("ignore")
|
| 11 |
+
|
| 12 |
+
from typing import Iterable, List, Tuple, Union
|
| 13 |
+
|
| 14 |
+
import numpy as np
|
| 15 |
+
import torch
|
| 16 |
+
import torch.nn.functional as F
|
| 17 |
+
from loguru import logger
|
| 18 |
+
from transformers import PreTrainedTokenizer
|
| 19 |
+
from transformers.generation import LogitsProcessor
|
| 20 |
+
|
| 21 |
+
# Types.
|
| 22 |
+
HistoryType = List[Tuple[str, str]]
|
| 23 |
+
TokensType = List[int]
|
| 24 |
+
BatchTokensType = List[List[int]]
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def pad_batch(batch: BatchTokensType, pad_id: int, seq_length: int) -> BatchTokensType:
|
| 28 |
+
for tokens in batch:
|
| 29 |
+
context_length = len(tokens)
|
| 30 |
+
if context_length < seq_length:
|
| 31 |
+
tokens.extend([pad_id] * (seq_length - context_length))
|
| 32 |
+
return batch
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def get_ltor_masks_and_position_ids(
|
| 36 |
+
data,
|
| 37 |
+
eod_token,
|
| 38 |
+
reset_position_ids,
|
| 39 |
+
reset_attention_mask,
|
| 40 |
+
eod_mask_loss,
|
| 41 |
+
):
|
| 42 |
+
"""Build masks and position id for left to right model."""
|
| 43 |
+
|
| 44 |
+
# Extract batch size and sequence length.
|
| 45 |
+
micro_batch_size, seq_length = data.size()
|
| 46 |
+
|
| 47 |
+
# Attention mask (lower triangular).
|
| 48 |
+
if reset_attention_mask:
|
| 49 |
+
att_mask_batch = micro_batch_size
|
| 50 |
+
else:
|
| 51 |
+
att_mask_batch = 1
|
| 52 |
+
attention_mask = torch.tril(torch.ones((att_mask_batch, seq_length, seq_length), device=data.device)).view(att_mask_batch, 1, seq_length, seq_length)
|
| 53 |
+
|
| 54 |
+
# Loss mask.
|
| 55 |
+
loss_mask = torch.ones(data.size(), dtype=torch.float, device=data.device)
|
| 56 |
+
if eod_mask_loss:
|
| 57 |
+
loss_mask[data == eod_token] = 0.0
|
| 58 |
+
|
| 59 |
+
# Position ids.
|
| 60 |
+
position_ids = torch.arange(seq_length, dtype=torch.long, device=data.device)
|
| 61 |
+
position_ids = position_ids.unsqueeze(0).expand_as(data)
|
| 62 |
+
# We need to clone as the ids will be modifed based on batch index.
|
| 63 |
+
if reset_position_ids:
|
| 64 |
+
position_ids = position_ids.clone()
|
| 65 |
+
|
| 66 |
+
if reset_position_ids or reset_attention_mask:
|
| 67 |
+
# Loop through the batches:
|
| 68 |
+
for b in range(micro_batch_size):
|
| 69 |
+
# Find indecies where EOD token is.
|
| 70 |
+
eod_index = position_ids[b, data[b] == eod_token]
|
| 71 |
+
# Detach indecies from positions if going to modify positions.
|
| 72 |
+
if reset_position_ids:
|
| 73 |
+
eod_index = eod_index.clone()
|
| 74 |
+
|
| 75 |
+
# Loop through EOD indecies:
|
| 76 |
+
prev_index = 0
|
| 77 |
+
for j in range(eod_index.size()[0]):
|
| 78 |
+
i = eod_index[j]
|
| 79 |
+
# Mask attention loss.
|
| 80 |
+
if reset_attention_mask:
|
| 81 |
+
attention_mask[b, 0, (i + 1) :, : (i + 1)] = 0
|
| 82 |
+
# Reset positions.
|
| 83 |
+
if reset_position_ids:
|
| 84 |
+
position_ids[b, (i + 1) :] -= i + 1 - prev_index
|
| 85 |
+
prev_index = i + 1
|
| 86 |
+
|
| 87 |
+
# Convert attention mask to binary:
|
| 88 |
+
attention_mask = attention_mask < 0.5
|
| 89 |
+
|
| 90 |
+
return attention_mask, loss_mask, position_ids
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def get_batch(context_tokens: torch.LongTensor, eod_id: int):
|
| 94 |
+
"""Generate batch from context tokens."""
|
| 95 |
+
# Move to GPU.
|
| 96 |
+
tokens = context_tokens.contiguous().to(context_tokens.device)
|
| 97 |
+
# Get the attention mask and postition ids.
|
| 98 |
+
attention_mask, _, position_ids = get_ltor_masks_and_position_ids(
|
| 99 |
+
tokens,
|
| 100 |
+
eod_id,
|
| 101 |
+
reset_position_ids=False,
|
| 102 |
+
reset_attention_mask=False,
|
| 103 |
+
eod_mask_loss=False,
|
| 104 |
+
)
|
| 105 |
+
return tokens, attention_mask, position_ids
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def get_stop_words_ids(chat_format, tokenizer):
|
| 109 |
+
if chat_format == "raw":
|
| 110 |
+
stop_words_ids = [tokenizer.encode("Human:"), [tokenizer.eod_id]]
|
| 111 |
+
elif chat_format == "chatml":
|
| 112 |
+
stop_words_ids = [[tokenizer.im_end_id], [tokenizer.im_start_id]]
|
| 113 |
+
else:
|
| 114 |
+
raise NotImplementedError(f"Unknown chat format {chat_format!r}")
|
| 115 |
+
return stop_words_ids
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def make_context(
|
| 119 |
+
tokenizer: PreTrainedTokenizer,
|
| 120 |
+
query: str,
|
| 121 |
+
history: List[Tuple[str, str]] = None,
|
| 122 |
+
system: str = "",
|
| 123 |
+
max_window_size: int = 6144,
|
| 124 |
+
chat_format: str = "chatml",
|
| 125 |
+
):
|
| 126 |
+
if history is None:
|
| 127 |
+
history = []
|
| 128 |
+
|
| 129 |
+
if chat_format == "chatml":
|
| 130 |
+
im_start, im_end = "<|im_start|>", "<|im_end|>"
|
| 131 |
+
im_start_tokens = [tokenizer.im_start_id]
|
| 132 |
+
im_end_tokens = [tokenizer.im_end_id]
|
| 133 |
+
nl_tokens = tokenizer.encode("\n")
|
| 134 |
+
|
| 135 |
+
def _tokenize_str(role, content):
|
| 136 |
+
return f"{role}\n{content}", tokenizer.encode(role, allowed_special=set(tokenizer.IMAGE_ST)) + nl_tokens + tokenizer.encode(content, allowed_special=set(tokenizer.IMAGE_ST))
|
| 137 |
+
|
| 138 |
+
system_text, system_tokens_part = _tokenize_str("system", system)
|
| 139 |
+
system_tokens = im_start_tokens + system_tokens_part + im_end_tokens
|
| 140 |
+
|
| 141 |
+
raw_text = ""
|
| 142 |
+
context_tokens = []
|
| 143 |
+
|
| 144 |
+
for turn_query, turn_response in reversed(history):
|
| 145 |
+
query_text, query_tokens_part = _tokenize_str("user", turn_query)
|
| 146 |
+
query_tokens = im_start_tokens + query_tokens_part + im_end_tokens
|
| 147 |
+
if turn_response is not None:
|
| 148 |
+
response_text, response_tokens_part = _tokenize_str("assistant", turn_response)
|
| 149 |
+
response_tokens = im_start_tokens + response_tokens_part + im_end_tokens
|
| 150 |
+
|
| 151 |
+
next_context_tokens = nl_tokens + query_tokens + nl_tokens + response_tokens
|
| 152 |
+
prev_chat = f"\n{im_start}{query_text}{im_end}\n{im_start}{response_text}{im_end}"
|
| 153 |
+
else:
|
| 154 |
+
next_context_tokens = nl_tokens + query_tokens + nl_tokens
|
| 155 |
+
prev_chat = f"\n{im_start}{query_text}{im_end}\n"
|
| 156 |
+
|
| 157 |
+
current_context_size = len(system_tokens) + len(next_context_tokens) + len(context_tokens)
|
| 158 |
+
if current_context_size < max_window_size:
|
| 159 |
+
context_tokens = next_context_tokens + context_tokens
|
| 160 |
+
raw_text = prev_chat + raw_text
|
| 161 |
+
else:
|
| 162 |
+
break
|
| 163 |
+
|
| 164 |
+
context_tokens = system_tokens + context_tokens
|
| 165 |
+
raw_text = f"{im_start}{system_text}{im_end}" + raw_text
|
| 166 |
+
context_tokens += nl_tokens + im_start_tokens + _tokenize_str("user", query)[1] + im_end_tokens + nl_tokens + im_start_tokens + tokenizer.encode("assistant") + nl_tokens
|
| 167 |
+
raw_text += f"\n{im_start}user\n{query}{im_end}\n{im_start}assistant\n"
|
| 168 |
+
|
| 169 |
+
elif chat_format == "raw":
|
| 170 |
+
raw_text = query
|
| 171 |
+
context_tokens = tokenizer.encode(raw_text)
|
| 172 |
+
else:
|
| 173 |
+
raise NotImplementedError(f"Unknown chat format {chat_format!r}")
|
| 174 |
+
|
| 175 |
+
return raw_text, context_tokens
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
def _decode_default(
|
| 179 |
+
tokens: List[int],
|
| 180 |
+
*,
|
| 181 |
+
stop_words: List[str],
|
| 182 |
+
eod_words: List[str],
|
| 183 |
+
tokenizer: PreTrainedTokenizer,
|
| 184 |
+
raw_text_len: int,
|
| 185 |
+
verbose: bool = False,
|
| 186 |
+
return_end_reason: bool = False,
|
| 187 |
+
errors: str = "replace",
|
| 188 |
+
):
|
| 189 |
+
trim_decode_tokens = tokenizer.decode(tokens, errors=errors)[raw_text_len:]
|
| 190 |
+
if verbose:
|
| 191 |
+
print("\nRaw Generate: ", trim_decode_tokens)
|
| 192 |
+
|
| 193 |
+
end_reason = f"Gen length {len(tokens)}"
|
| 194 |
+
for stop_word in stop_words:
|
| 195 |
+
trim_decode_tokens = trim_decode_tokens.replace(stop_word, "").strip()
|
| 196 |
+
for eod_word in eod_words:
|
| 197 |
+
if eod_word in trim_decode_tokens:
|
| 198 |
+
end_reason = f"Gen {eod_word!r}"
|
| 199 |
+
trim_decode_tokens = trim_decode_tokens.split(eod_word)[0]
|
| 200 |
+
trim_decode_tokens = trim_decode_tokens.strip()
|
| 201 |
+
if verbose:
|
| 202 |
+
print("\nEnd Reason:", end_reason)
|
| 203 |
+
print("\nGenerate: ", trim_decode_tokens)
|
| 204 |
+
|
| 205 |
+
if return_end_reason:
|
| 206 |
+
return trim_decode_tokens, end_reason
|
| 207 |
+
else:
|
| 208 |
+
return trim_decode_tokens
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def _decode_chatml(
|
| 212 |
+
tokens: List[int], *, stop_words: List[str], eod_token_ids: List[int], tokenizer: PreTrainedTokenizer, raw_text_len: int, context_length: int, verbose: bool = False, return_end_reason: bool = False, errors: str = "replace"
|
| 213 |
+
):
|
| 214 |
+
end_reason = f"Gen length {len(tokens)}"
|
| 215 |
+
eod_token_idx = context_length
|
| 216 |
+
for eod_token_idx in range(context_length, len(tokens)):
|
| 217 |
+
if tokens[eod_token_idx] in eod_token_ids:
|
| 218 |
+
end_reason = f"Gen {tokenizer.decode([tokens[eod_token_idx]])!r}"
|
| 219 |
+
break
|
| 220 |
+
|
| 221 |
+
trim_decode_tokens = tokenizer.decode(tokens[:eod_token_idx], errors=errors)[raw_text_len:]
|
| 222 |
+
if verbose:
|
| 223 |
+
print("\nRaw Generate w/o EOD:", tokenizer.decode(tokens, errors=errors)[raw_text_len:])
|
| 224 |
+
print("\nRaw Generate:", trim_decode_tokens)
|
| 225 |
+
print("\nEnd Reason:", end_reason)
|
| 226 |
+
for stop_word in stop_words:
|
| 227 |
+
trim_decode_tokens = trim_decode_tokens.replace(stop_word, "").strip()
|
| 228 |
+
trim_decode_tokens = trim_decode_tokens.strip()
|
| 229 |
+
if verbose:
|
| 230 |
+
print("\nGenerate:", trim_decode_tokens)
|
| 231 |
+
|
| 232 |
+
if return_end_reason:
|
| 233 |
+
return trim_decode_tokens, end_reason
|
| 234 |
+
else:
|
| 235 |
+
return trim_decode_tokens
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
def decode_tokens(
|
| 239 |
+
tokens: Union[torch.LongTensor, TokensType],
|
| 240 |
+
tokenizer: PreTrainedTokenizer,
|
| 241 |
+
raw_text_len: int,
|
| 242 |
+
context_length: int,
|
| 243 |
+
chat_format: str,
|
| 244 |
+
verbose: bool = False,
|
| 245 |
+
return_end_reason: bool = False,
|
| 246 |
+
errors: str = "replace",
|
| 247 |
+
) -> str:
|
| 248 |
+
if torch.is_tensor(tokens):
|
| 249 |
+
tokens = tokens.cpu().numpy().tolist()
|
| 250 |
+
|
| 251 |
+
if chat_format == "chatml":
|
| 252 |
+
return _decode_chatml(
|
| 253 |
+
tokens,
|
| 254 |
+
stop_words=[],
|
| 255 |
+
eod_token_ids=[tokenizer.im_start_id, tokenizer.im_end_id],
|
| 256 |
+
tokenizer=tokenizer,
|
| 257 |
+
raw_text_len=raw_text_len,
|
| 258 |
+
context_length=context_length,
|
| 259 |
+
verbose=verbose,
|
| 260 |
+
return_end_reason=return_end_reason,
|
| 261 |
+
errors=errors,
|
| 262 |
+
)
|
| 263 |
+
elif chat_format == "raw":
|
| 264 |
+
return _decode_default(
|
| 265 |
+
tokens,
|
| 266 |
+
stop_words=["<|endoftext|>"],
|
| 267 |
+
eod_words=["<|endoftext|>"],
|
| 268 |
+
tokenizer=tokenizer,
|
| 269 |
+
raw_text_len=raw_text_len,
|
| 270 |
+
verbose=verbose,
|
| 271 |
+
return_end_reason=return_end_reason,
|
| 272 |
+
errors=errors,
|
| 273 |
+
)
|
| 274 |
+
else:
|
| 275 |
+
raise NotImplementedError(f"Unknown chat format {chat_format!r}")
|
| 276 |
+
|
| 277 |
+
|
| 278 |
+
class StopWordsLogitsProcessor(LogitsProcessor):
|
| 279 |
+
"""
|
| 280 |
+
:class:`transformers.LogitsProcessor` that enforces that when specified sequences appear, stop geration.
|
| 281 |
+
Args:
|
| 282 |
+
stop_words_ids (:obj:`List[List[int]]`):
|
| 283 |
+
List of list of token ids of stop ids. In order to get the tokens of the words
|
| 284 |
+
that should not appear in the generated text, use :obj:`tokenizer(bad_word,
|
| 285 |
+
add_prefix_space=True).input_ids`.
|
| 286 |
+
eos_token_id (:obj:`int`):
|
| 287 |
+
The id of the `end-of-sequence` token.
|
| 288 |
+
"""
|
| 289 |
+
|
| 290 |
+
def __init__(self, stop_words_ids: Iterable[Iterable[int]], eos_token_id: int):
|
| 291 |
+
if not isinstance(stop_words_ids, List) or len(stop_words_ids) == 0:
|
| 292 |
+
raise ValueError(f"`stop_words_ids` has to be a non-emtpy list, but is {stop_words_ids}.")
|
| 293 |
+
if any(not isinstance(bad_word_ids, list) for bad_word_ids in stop_words_ids):
|
| 294 |
+
raise ValueError(f"`stop_words_ids` has to be a list of lists, but is {stop_words_ids}.")
|
| 295 |
+
if any(any((not isinstance(token_id, (int, np.integer)) or token_id < 0) for token_id in stop_word_ids) for stop_word_ids in stop_words_ids):
|
| 296 |
+
raise ValueError(f"Each list in `stop_words_ids` has to be a list of positive integers, but is {stop_words_ids}.")
|
| 297 |
+
|
| 298 |
+
self.stop_words_ids = list(filter(lambda bad_token_seq: bad_token_seq != [eos_token_id], stop_words_ids))
|
| 299 |
+
self.eos_token_id = eos_token_id
|
| 300 |
+
for stop_token_seq in self.stop_words_ids:
|
| 301 |
+
assert len(stop_token_seq) > 0, "Stop words token sequences {} cannot have an empty list".format(stop_words_ids)
|
| 302 |
+
|
| 303 |
+
def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
|
| 304 |
+
stopped_samples = self._calc_stopped_samples(input_ids)
|
| 305 |
+
for i, should_stop in enumerate(stopped_samples):
|
| 306 |
+
if should_stop:
|
| 307 |
+
scores[i, self.eos_token_id] = float(2**15)
|
| 308 |
+
return scores
|
| 309 |
+
|
| 310 |
+
def _tokens_match(self, prev_tokens: torch.LongTensor, tokens: List[int]) -> bool:
|
| 311 |
+
if len(tokens) == 0:
|
| 312 |
+
# if bad word tokens is just one token always ban it
|
| 313 |
+
return True
|
| 314 |
+
elif len(tokens) > len(prev_tokens):
|
| 315 |
+
# if bad word tokens are longer then prev input_ids they can't be equal
|
| 316 |
+
return False
|
| 317 |
+
elif prev_tokens[-len(tokens) :].tolist() == tokens:
|
| 318 |
+
# if tokens match
|
| 319 |
+
return True
|
| 320 |
+
else:
|
| 321 |
+
return False
|
| 322 |
+
|
| 323 |
+
def _calc_stopped_samples(self, prev_input_ids: Iterable[int]) -> Iterable[int]:
|
| 324 |
+
stopped_samples = []
|
| 325 |
+
for prev_input_ids_slice in prev_input_ids:
|
| 326 |
+
match = False
|
| 327 |
+
for stop_token_seq in self.stop_words_ids:
|
| 328 |
+
if self._tokens_match(prev_input_ids_slice, stop_token_seq):
|
| 329 |
+
# if tokens do not match continue
|
| 330 |
+
match = True
|
| 331 |
+
break
|
| 332 |
+
stopped_samples.append(match)
|
| 333 |
+
|
| 334 |
+
return stopped_samples
|
| 335 |
+
|
| 336 |
+
|
| 337 |
+
def top_k_logits(logits, top_k=0, top_p=0.0, filter_value=-float("Inf")):
|
| 338 |
+
"""This function has been mostly taken from huggingface conversational
|
| 339 |
+
ai code at
|
| 340 |
+
https://medium.com/huggingface/how-to-build-a-state-of-the-art-
|
| 341 |
+
conversational-ai-with-transfer-learning-2d818ac26313"""
|
| 342 |
+
|
| 343 |
+
if top_k > 0:
|
| 344 |
+
# Remove all tokens with a probability less than the
|
| 345 |
+
# last token of the top-k
|
| 346 |
+
indices_to_remove = logits < torch.topk(logits, top_k)[0][..., -1, None]
|
| 347 |
+
logits[indices_to_remove] = filter_value
|
| 348 |
+
|
| 349 |
+
if top_p > 0.0:
|
| 350 |
+
# Cconvert to 1D
|
| 351 |
+
sorted_logits, sorted_indices = torch.sort(logits, descending=True, dim=-1)
|
| 352 |
+
cumulative_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1)
|
| 353 |
+
|
| 354 |
+
# Remove tokens with cumulative probability above the threshold
|
| 355 |
+
sorted_indices_to_remove = cumulative_probs > top_p
|
| 356 |
+
# Shift the indices to the right to keep also the first token
|
| 357 |
+
# above the threshold
|
| 358 |
+
sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone()
|
| 359 |
+
sorted_indices_to_remove[..., 0] = 0
|
| 360 |
+
for i in range(sorted_indices.size(0)):
|
| 361 |
+
indices_to_remove = sorted_indices[i][sorted_indices_to_remove[i]]
|
| 362 |
+
logits[i][indices_to_remove] = filter_value
|
| 363 |
+
|
| 364 |
+
return logits
|
| 365 |
+
|
| 366 |
+
|
| 367 |
+
def switch(val1, val2, boolean):
|
| 368 |
+
boolean = boolean.type_as(val1)
|
| 369 |
+
return (1 - boolean) * val1 + boolean * val2
|
spatial-model/GeoThinker/src/lmms_eval/models/video_chatgpt/constants.py
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
CONTROLLER_HEART_BEAT_EXPIRATION = 30
|
| 2 |
+
WORKER_HEART_BEAT_INTERVAL = 15
|
| 3 |
+
|
| 4 |
+
LOGDIR = "."
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
# Defining model
|
| 8 |
+
DEFAULT_VIDEO_TOKEN = "<video>"
|
| 9 |
+
DEFAULT_VIDEO_PATCH_TOKEN = "<vid_patch>"
|
| 10 |
+
DEFAULT_VID_START_TOKEN = "<vid_start>"
|
| 11 |
+
DEFAULT_VID_END_TOKEN = "<vid_end>"
|
spatial-model/GeoThinker/src/lmms_eval/models/video_chatgpt/eval/__init__.py
ADDED
|
File without changes
|
spatial-model/GeoThinker/src/lmms_eval/models/video_chatgpt/eval/model_utils.py
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
import torch
|
| 5 |
+
from decord import VideoReader, cpu
|
| 6 |
+
from PIL import Image
|
| 7 |
+
from transformers import AutoTokenizer, CLIPImageProcessor, CLIPVisionModel
|
| 8 |
+
|
| 9 |
+
from lmms_eval.models.video_chatgpt.constants import *
|
| 10 |
+
from lmms_eval.models.video_chatgpt.model import VideoChatGPTLlamaForCausalLM
|
| 11 |
+
from lmms_eval.models.video_chatgpt.utils import disable_torch_init
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def load_video(vis_path, n_clips=1, num_frm=100):
|
| 15 |
+
"""
|
| 16 |
+
Load video frames from a video file.
|
| 17 |
+
|
| 18 |
+
Parameters:
|
| 19 |
+
vis_path (str): Path to the video file.
|
| 20 |
+
n_clips (int): Number of clips to extract from the video. Defaults to 1.
|
| 21 |
+
num_frm (int): Number of frames to extract from each clip. Defaults to 100.
|
| 22 |
+
|
| 23 |
+
Returns:
|
| 24 |
+
list: List of PIL.Image.Image objects representing video frames.
|
| 25 |
+
"""
|
| 26 |
+
|
| 27 |
+
# Load video with VideoReader
|
| 28 |
+
vr = VideoReader(vis_path, ctx=cpu(0))
|
| 29 |
+
total_frame_num = len(vr)
|
| 30 |
+
|
| 31 |
+
# Currently, this function supports only 1 clip
|
| 32 |
+
assert n_clips == 1
|
| 33 |
+
|
| 34 |
+
# Calculate total number of frames to extract
|
| 35 |
+
total_num_frm = min(total_frame_num, num_frm)
|
| 36 |
+
# Get indices of frames to extract
|
| 37 |
+
frame_idx = get_seq_frames(total_frame_num, total_num_frm)
|
| 38 |
+
# Extract frames as numpy array
|
| 39 |
+
img_array = vr.get_batch(frame_idx).asnumpy()
|
| 40 |
+
# Set target image height and width
|
| 41 |
+
target_h, target_w = 224, 224
|
| 42 |
+
# If image shape is not as target, resize it
|
| 43 |
+
if img_array.shape[-3] != target_h or img_array.shape[-2] != target_w:
|
| 44 |
+
img_array = torch.from_numpy(img_array).permute(0, 3, 1, 2).float()
|
| 45 |
+
img_array = torch.nn.functional.interpolate(img_array, size=(target_h, target_w))
|
| 46 |
+
img_array = img_array.permute(0, 2, 3, 1).to(torch.uint8).numpy()
|
| 47 |
+
|
| 48 |
+
# Reshape array to match number of clips and frames
|
| 49 |
+
img_array = img_array.reshape((n_clips, total_num_frm, img_array.shape[-3], img_array.shape[-2], img_array.shape[-1]))
|
| 50 |
+
# Convert numpy arrays to PIL Image objects
|
| 51 |
+
clip_imgs = [Image.fromarray(img_array[0, j]) for j in range(total_num_frm)]
|
| 52 |
+
|
| 53 |
+
return clip_imgs
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def get_seq_frames(total_num_frames, desired_num_frames):
|
| 57 |
+
"""
|
| 58 |
+
Calculate the indices of frames to extract from a video.
|
| 59 |
+
|
| 60 |
+
Parameters:
|
| 61 |
+
total_num_frames (int): Total number of frames in the video.
|
| 62 |
+
desired_num_frames (int): Desired number of frames to extract.
|
| 63 |
+
|
| 64 |
+
Returns:
|
| 65 |
+
list: List of indices of frames to extract.
|
| 66 |
+
"""
|
| 67 |
+
|
| 68 |
+
# Calculate the size of each segment from which a frame will be extracted
|
| 69 |
+
seg_size = float(total_num_frames - 1) / desired_num_frames
|
| 70 |
+
|
| 71 |
+
seq = []
|
| 72 |
+
for i in range(desired_num_frames):
|
| 73 |
+
# Calculate the start and end indices of each segment
|
| 74 |
+
start = int(np.round(seg_size * i))
|
| 75 |
+
end = int(np.round(seg_size * (i + 1)))
|
| 76 |
+
|
| 77 |
+
# Append the middle index of the segment to the list
|
| 78 |
+
seq.append((start + end) // 2)
|
| 79 |
+
|
| 80 |
+
return seq
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def initialize_model(model_name, projection_path=None, device="cuda"):
|
| 84 |
+
"""
|
| 85 |
+
Initializes the model with given parameters.
|
| 86 |
+
|
| 87 |
+
Parameters:
|
| 88 |
+
model_name (str): Name of the model to initialize.
|
| 89 |
+
projection_path (str, optional): Path to the projection weights. Defaults to None.
|
| 90 |
+
|
| 91 |
+
Returns:
|
| 92 |
+
tuple: Model, vision tower, tokenizer, image processor, vision config, and video token length.
|
| 93 |
+
"""
|
| 94 |
+
|
| 95 |
+
# Disable initial torch operations
|
| 96 |
+
disable_torch_init()
|
| 97 |
+
|
| 98 |
+
# Convert model name to user path
|
| 99 |
+
model_name = os.path.expanduser(model_name)
|
| 100 |
+
|
| 101 |
+
# Load tokenizer
|
| 102 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
| 103 |
+
|
| 104 |
+
# Load model
|
| 105 |
+
model = VideoChatGPTLlamaForCausalLM.from_pretrained(model_name, low_cpu_mem_usage=True, torch_dtype=torch.float16, use_cache=True)
|
| 106 |
+
|
| 107 |
+
# Load image processor
|
| 108 |
+
image_processor = CLIPImageProcessor.from_pretrained(model.config.mm_vision_tower, torch_dtype=torch.float16)
|
| 109 |
+
|
| 110 |
+
# Set to use start and end tokens for video
|
| 111 |
+
mm_use_vid_start_end = True
|
| 112 |
+
|
| 113 |
+
# Add tokens to tokenizer
|
| 114 |
+
tokenizer.add_tokens([DEFAULT_VIDEO_PATCH_TOKEN], special_tokens=True)
|
| 115 |
+
if mm_use_vid_start_end:
|
| 116 |
+
tokenizer.add_tokens([DEFAULT_VID_START_TOKEN, DEFAULT_VID_END_TOKEN], special_tokens=True)
|
| 117 |
+
|
| 118 |
+
# Resize token embeddings of the model
|
| 119 |
+
model.resize_token_embeddings(len(tokenizer))
|
| 120 |
+
|
| 121 |
+
# Load the weights from projection_path after resizing the token_embeddings
|
| 122 |
+
if projection_path:
|
| 123 |
+
print(f"Loading weights from {projection_path}")
|
| 124 |
+
status = model.load_state_dict(torch.load(projection_path, map_location="cpu"), strict=False)
|
| 125 |
+
if status.unexpected_keys:
|
| 126 |
+
print(f"Unexpected Keys: {status.unexpected_keys}.\nThe Video-ChatGPT weights are not loaded correctly.")
|
| 127 |
+
print(f"Weights loaded from {projection_path}")
|
| 128 |
+
|
| 129 |
+
# Set model to evaluation mode and move to GPU
|
| 130 |
+
model = model.eval()
|
| 131 |
+
model = model.to(device)
|
| 132 |
+
|
| 133 |
+
vision_tower_name = "openai/clip-vit-large-patch14"
|
| 134 |
+
|
| 135 |
+
# Load vision tower and move to GPU
|
| 136 |
+
vision_tower = CLIPVisionModel.from_pretrained(vision_tower_name, torch_dtype=torch.float16, low_cpu_mem_usage=True).to(device)
|
| 137 |
+
vision_tower = vision_tower.eval()
|
| 138 |
+
|
| 139 |
+
# Configure vision model
|
| 140 |
+
vision_config = model.get_model().vision_config
|
| 141 |
+
vision_config.vid_patch_token = tokenizer.convert_tokens_to_ids([DEFAULT_VIDEO_PATCH_TOKEN])[0]
|
| 142 |
+
vision_config.use_vid_start_end = mm_use_vid_start_end
|
| 143 |
+
if mm_use_vid_start_end:
|
| 144 |
+
vision_config.vid_start_token, vision_config.vid_end_token = tokenizer.convert_tokens_to_ids([DEFAULT_VID_START_TOKEN, DEFAULT_VID_END_TOKEN])
|
| 145 |
+
|
| 146 |
+
# Set video token length
|
| 147 |
+
video_token_len = 356
|
| 148 |
+
|
| 149 |
+
return model, vision_tower, tokenizer, image_processor, video_token_len
|
spatial-model/GeoThinker/src/lmms_eval/models/video_chatgpt/inference.py
ADDED
|
@@ -0,0 +1,189 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
|
| 3 |
+
from lmms_eval.models.video_chatgpt.model.utils import KeywordsStoppingCriteria
|
| 4 |
+
from lmms_eval.models.video_chatgpt.video_conversation import (
|
| 5 |
+
SeparatorStyle,
|
| 6 |
+
conv_templates,
|
| 7 |
+
)
|
| 8 |
+
|
| 9 |
+
# Define constants
|
| 10 |
+
DEFAULT_VIDEO_TOKEN = "<video>"
|
| 11 |
+
DEFAULT_VIDEO_PATCH_TOKEN = "<vid_patch>"
|
| 12 |
+
DEFAULT_VID_START_TOKEN = "<vid_start>"
|
| 13 |
+
DEFAULT_VID_END_TOKEN = "<vid_end>"
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def get_spatio_temporal_features_torch(features):
|
| 17 |
+
"""
|
| 18 |
+
Computes spatio-temporal features from given features.
|
| 19 |
+
|
| 20 |
+
Parameters:
|
| 21 |
+
features (torch.Tensor): Input features to process.
|
| 22 |
+
|
| 23 |
+
Returns:
|
| 24 |
+
torch.Tensor: Spatio-temporal features.
|
| 25 |
+
"""
|
| 26 |
+
|
| 27 |
+
# Extract the dimensions of the features
|
| 28 |
+
t, s, c = features.shape
|
| 29 |
+
|
| 30 |
+
# Compute temporal tokens as the mean along the time axis
|
| 31 |
+
temporal_tokens = torch.mean(features, dim=1)
|
| 32 |
+
|
| 33 |
+
# Padding size calculation
|
| 34 |
+
padding_size = 100 - t
|
| 35 |
+
|
| 36 |
+
# Pad temporal tokens if necessary
|
| 37 |
+
if padding_size > 0:
|
| 38 |
+
padding = torch.zeros(padding_size, c, device=features.device)
|
| 39 |
+
temporal_tokens = torch.cat((temporal_tokens, padding), dim=0)
|
| 40 |
+
|
| 41 |
+
# Compute spatial tokens as the mean along the spatial axis
|
| 42 |
+
spatial_tokens = torch.mean(features, dim=0)
|
| 43 |
+
|
| 44 |
+
# Concatenate temporal and spatial tokens and cast to half precision
|
| 45 |
+
concat_tokens = torch.cat([temporal_tokens, spatial_tokens], dim=0).half()
|
| 46 |
+
|
| 47 |
+
return concat_tokens
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def video_chatgpt_infer(video_frames, question, conv_mode, model, vision_tower, tokenizer, image_processor, video_token_len):
|
| 51 |
+
"""
|
| 52 |
+
Run inference using the Video-ChatGPT model.
|
| 53 |
+
|
| 54 |
+
Parameters:
|
| 55 |
+
sample : Initial sample
|
| 56 |
+
video_frames (torch.Tensor): Video frames to process.
|
| 57 |
+
question (str): The question string.
|
| 58 |
+
conv_mode: Conversation mode.
|
| 59 |
+
model: The pretrained Video-ChatGPT model.
|
| 60 |
+
vision_tower: Vision model to extract video features.
|
| 61 |
+
tokenizer: Tokenizer for the model.
|
| 62 |
+
image_processor: Image processor to preprocess video frames.
|
| 63 |
+
video_token_len (int): The length of video tokens.
|
| 64 |
+
|
| 65 |
+
Returns:
|
| 66 |
+
dict: Dictionary containing the model's output.
|
| 67 |
+
"""
|
| 68 |
+
|
| 69 |
+
# Prepare question string for the model
|
| 70 |
+
if model.get_model().vision_config.use_vid_start_end:
|
| 71 |
+
qs = question + "\n" + DEFAULT_VID_START_TOKEN + DEFAULT_VIDEO_PATCH_TOKEN * video_token_len + DEFAULT_VID_END_TOKEN
|
| 72 |
+
else:
|
| 73 |
+
qs = question + "\n" + DEFAULT_VIDEO_PATCH_TOKEN * video_token_len
|
| 74 |
+
|
| 75 |
+
# Prepare conversation prompt
|
| 76 |
+
conv = conv_templates[conv_mode].copy()
|
| 77 |
+
conv.append_message(conv.roles[0], qs)
|
| 78 |
+
conv.append_message(conv.roles[1], None)
|
| 79 |
+
prompt = conv.get_prompt()
|
| 80 |
+
|
| 81 |
+
# Tokenize the prompt
|
| 82 |
+
inputs = tokenizer([prompt])
|
| 83 |
+
|
| 84 |
+
# Preprocess video frames and get image tensor
|
| 85 |
+
image_tensor = image_processor.preprocess(video_frames, return_tensors="pt")["pixel_values"]
|
| 86 |
+
|
| 87 |
+
# Move image tensor to GPU and reduce precision to half
|
| 88 |
+
image_tensor = image_tensor.half().cuda()
|
| 89 |
+
|
| 90 |
+
# Generate video spatio-temporal features
|
| 91 |
+
with torch.no_grad():
|
| 92 |
+
image_forward_outs = vision_tower(image_tensor, output_hidden_states=True)
|
| 93 |
+
frame_features = image_forward_outs.hidden_states[-2][:, 1:] # Use second to last layer as in LLaVA
|
| 94 |
+
video_spatio_temporal_features = get_spatio_temporal_features_torch(frame_features)
|
| 95 |
+
|
| 96 |
+
# Move inputs to GPU
|
| 97 |
+
input_ids = torch.as_tensor(inputs.input_ids).cuda()
|
| 98 |
+
|
| 99 |
+
# Define stopping criteria for generation
|
| 100 |
+
stop_str = conv.sep if conv.sep_style != SeparatorStyle.TWO else conv.sep2
|
| 101 |
+
stopping_criteria = KeywordsStoppingCriteria([stop_str], tokenizer, input_ids)
|
| 102 |
+
|
| 103 |
+
# Run model inference
|
| 104 |
+
with torch.inference_mode():
|
| 105 |
+
output_ids = model.generate(input_ids, video_spatio_temporal_features=video_spatio_temporal_features.unsqueeze(0), do_sample=True, temperature=0.2, max_new_tokens=1024, stopping_criteria=[stopping_criteria])
|
| 106 |
+
|
| 107 |
+
# Check if output is the same as input
|
| 108 |
+
n_diff_input_output = (input_ids != output_ids[:, : input_ids.shape[1]]).sum().item()
|
| 109 |
+
if n_diff_input_output > 0:
|
| 110 |
+
print(f"[Warning] {n_diff_input_output} output_ids are not the same as the input_ids")
|
| 111 |
+
|
| 112 |
+
# Decode output tokens
|
| 113 |
+
outputs = tokenizer.batch_decode(output_ids[:, input_ids.shape[1] :], skip_special_tokens=True)[0]
|
| 114 |
+
|
| 115 |
+
# Clean output string
|
| 116 |
+
outputs = outputs.strip().rstrip(stop_str).strip()
|
| 117 |
+
|
| 118 |
+
return outputs
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def video_chatgpt_infer_ppl(question, continuation, conv_mode, model, vision_tower, tokenizer, image_processor, video_token_len, video_spatio_temporal_features):
|
| 122 |
+
"""
|
| 123 |
+
Run inference using the Video-ChatGPT model.
|
| 124 |
+
|
| 125 |
+
Parameters:
|
| 126 |
+
sample : Initial sample
|
| 127 |
+
video_frames (torch.Tensor): Video frames to process.
|
| 128 |
+
question (str): The question string.
|
| 129 |
+
conv_mode: Conversation mode.
|
| 130 |
+
model: The pretrained Video-ChatGPT model.
|
| 131 |
+
vision_tower: Vision model to extract video features.
|
| 132 |
+
tokenizer: Tokenizer for the model.
|
| 133 |
+
image_processor: Image processor to preprocess video frames.
|
| 134 |
+
video_token_len (int): The length of video tokens.
|
| 135 |
+
|
| 136 |
+
Returns:
|
| 137 |
+
dict: Dictionary containing the model's output.
|
| 138 |
+
"""
|
| 139 |
+
|
| 140 |
+
# Prepare question string for the model
|
| 141 |
+
if model.get_model().vision_config.use_vid_start_end:
|
| 142 |
+
qs = question + "\n" + DEFAULT_VID_START_TOKEN + DEFAULT_VIDEO_PATCH_TOKEN * video_token_len + DEFAULT_VID_END_TOKEN
|
| 143 |
+
else:
|
| 144 |
+
qs = question + "\n" + DEFAULT_VIDEO_PATCH_TOKEN * video_token_len
|
| 145 |
+
|
| 146 |
+
# Prepare context prompt
|
| 147 |
+
conv = conv_templates[conv_mode].copy()
|
| 148 |
+
conv.append_message(conv.roles[0], qs)
|
| 149 |
+
conv.append_message(conv.roles[1], None)
|
| 150 |
+
prompt = conv.get_prompt()
|
| 151 |
+
|
| 152 |
+
# Tokenize the prompt
|
| 153 |
+
context_ids = torch.as_tensor(tokenizer([prompt]).input_ids)
|
| 154 |
+
|
| 155 |
+
# Prepare context + continuation prompt
|
| 156 |
+
conv = conv_templates[conv_mode].copy()
|
| 157 |
+
conv.append_message(conv.roles[0], qs)
|
| 158 |
+
conv.append_message(conv.roles[1], continuation)
|
| 159 |
+
prompt = conv.get_prompt()
|
| 160 |
+
inputs = tokenizer([prompt])
|
| 161 |
+
|
| 162 |
+
"""# Preprocess video frames and get image tensor
|
| 163 |
+
image_tensor = image_processor.preprocess(video_frames, return_tensors='pt')['pixel_values']
|
| 164 |
+
|
| 165 |
+
# Move image tensor to GPU and reduce precision to half
|
| 166 |
+
# image_tensor = image_tensor.half().cuda()
|
| 167 |
+
|
| 168 |
+
# Generate video spatio-temporal features
|
| 169 |
+
with torch.no_grad():
|
| 170 |
+
image_forward_outs = vision_tower(image_tensor, output_hidden_states=True)
|
| 171 |
+
frame_features = image_forward_outs.hidden_states[-2][:, 1:] # Use second to last layer as in LLaVA
|
| 172 |
+
video_spatio_temporal_features = get_spatio_temporal_features_torch(frame_features).cuda()
|
| 173 |
+
|
| 174 |
+
del image_tensor
|
| 175 |
+
torch.cuda.empty_cache()"""
|
| 176 |
+
# Move inputs to GPU
|
| 177 |
+
input_ids = torch.as_tensor(inputs.input_ids).cuda()
|
| 178 |
+
attention_mask = torch.as_tensor(inputs.attention_mask).cuda()
|
| 179 |
+
labels = torch.as_tensor(inputs["input_ids"]).clone().cuda()
|
| 180 |
+
labels[0, : len(context_ids)] = -100
|
| 181 |
+
|
| 182 |
+
# Define stopping criteria for generation
|
| 183 |
+
stop_str = conv.sep if conv.sep_style != SeparatorStyle.TWO else conv.sep2
|
| 184 |
+
stopping_criteria = KeywordsStoppingCriteria([stop_str], tokenizer, input_ids)
|
| 185 |
+
|
| 186 |
+
with torch.inference_mode():
|
| 187 |
+
output = model(input_ids, video_spatio_temporal_features=video_spatio_temporal_features.unsqueeze(0), attention_mask=attention_mask, labels=labels)
|
| 188 |
+
|
| 189 |
+
return output, input_ids, context_ids
|
spatial-model/GeoThinker/src/lmms_eval/models/video_chatgpt/model/__init__.py
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from lmms_eval.models.video_chatgpt.model.video_chatgpt import (
|
| 2 |
+
VideoChatGPTConfig,
|
| 3 |
+
VideoChatGPTLlamaForCausalLM,
|
| 4 |
+
)
|
spatial-model/GeoThinker/src/lmms_eval/models/video_chatgpt/model/consolidate.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Usage:
|
| 3 |
+
python3 -m llava.model.consolidate --src ~/model_weights/llava-7b --dst ~/model_weights/llava-7b_consolidate
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import argparse
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 10 |
+
|
| 11 |
+
from lmms_eval.models.video_chatgpt.model import *
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def consolidate_ckpt(src_path, dst_path):
|
| 15 |
+
print("Loading model")
|
| 16 |
+
src_model = AutoModelForCausalLM.from_pretrained(src_path, torch_dtype=torch.float16, low_cpu_mem_usage=True)
|
| 17 |
+
src_tokenizer = AutoTokenizer.from_pretrained(src_path)
|
| 18 |
+
src_model.save_pretrained(dst_path)
|
| 19 |
+
src_tokenizer.save_pretrained(dst_path)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
if __name__ == "__main__":
|
| 23 |
+
parser = argparse.ArgumentParser()
|
| 24 |
+
parser.add_argument("--src", type=str, required=True)
|
| 25 |
+
parser.add_argument("--dst", type=str, required=True)
|
| 26 |
+
|
| 27 |
+
args = parser.parse_args()
|
| 28 |
+
|
| 29 |
+
consolidate_ckpt(args.src, args.dst)
|
spatial-model/GeoThinker/src/lmms_eval/models/video_chatgpt/single_video_inference.py
ADDED
|
@@ -0,0 +1,173 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
How to run this file:
|
| 3 |
+
|
| 4 |
+
cd VideoChatGPT
|
| 5 |
+
python -m video_chatgpt.single_video_inference \
|
| 6 |
+
--model-name <path of llava weights, for eg "LLaVA-7B-Lightening-v1-1"> \
|
| 7 |
+
--projection_path <path of projection for eg "video-chatgpt-weights/video_chatgpt-7B.bin"> \
|
| 8 |
+
--video_path <video_path>
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
import argparse
|
| 12 |
+
import os
|
| 13 |
+
|
| 14 |
+
import numpy as np
|
| 15 |
+
import torch
|
| 16 |
+
from decord import VideoReader, cpu
|
| 17 |
+
|
| 18 |
+
# add new packages as below
|
| 19 |
+
from PIL import Image
|
| 20 |
+
|
| 21 |
+
from lmms_eval.models.video_chatgpt.eval.model_utils import initialize_model, load_video
|
| 22 |
+
from lmms_eval.models.video_chatgpt.model.utils import KeywordsStoppingCriteria
|
| 23 |
+
from lmms_eval.models.video_chatgpt.video_conversation import (
|
| 24 |
+
SeparatorStyle,
|
| 25 |
+
conv_templates,
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
# Define constants
|
| 29 |
+
DEFAULT_VIDEO_TOKEN = "<video>"
|
| 30 |
+
DEFAULT_VIDEO_PATCH_TOKEN = "<vid_patch>"
|
| 31 |
+
DEFAULT_VID_START_TOKEN = "<vid_start>"
|
| 32 |
+
DEFAULT_VID_END_TOKEN = "<vid_end>"
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def get_spatio_temporal_features_torch(features):
|
| 36 |
+
"""
|
| 37 |
+
Computes spatio-temporal features from given features.
|
| 38 |
+
|
| 39 |
+
Parameters:
|
| 40 |
+
features (torch.Tensor): Input features to process.
|
| 41 |
+
|
| 42 |
+
Returns:
|
| 43 |
+
torch.Tensor: Spatio-temporal features.
|
| 44 |
+
"""
|
| 45 |
+
|
| 46 |
+
# Extract the dimensions of the features
|
| 47 |
+
t, s, c = features.shape
|
| 48 |
+
|
| 49 |
+
# Compute temporal tokens as the mean along the time axis
|
| 50 |
+
temporal_tokens = torch.mean(features, dim=1)
|
| 51 |
+
|
| 52 |
+
# Padding size calculation
|
| 53 |
+
padding_size = 100 - t
|
| 54 |
+
|
| 55 |
+
# Pad temporal tokens if necessary
|
| 56 |
+
if padding_size > 0:
|
| 57 |
+
padding = torch.zeros(padding_size, c, device=features.device)
|
| 58 |
+
temporal_tokens = torch.cat((temporal_tokens, padding), dim=0)
|
| 59 |
+
|
| 60 |
+
# Compute spatial tokens as the mean along the spatial axis
|
| 61 |
+
spatial_tokens = torch.mean(features, dim=0)
|
| 62 |
+
|
| 63 |
+
# Concatenate temporal and spatial tokens and cast to half precision
|
| 64 |
+
concat_tokens = torch.cat([temporal_tokens, spatial_tokens], dim=0).half()
|
| 65 |
+
|
| 66 |
+
return concat_tokens
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def video_chatgpt_infer(video_frames, question, conv_mode, model, vision_tower, tokenizer, image_processor, video_token_len):
|
| 70 |
+
"""
|
| 71 |
+
Run inference using the Video-ChatGPT model.
|
| 72 |
+
|
| 73 |
+
Parameters:
|
| 74 |
+
sample : Initial sample
|
| 75 |
+
video_frames (torch.Tensor): Video frames to process.
|
| 76 |
+
question (str): The question string.
|
| 77 |
+
conv_mode: Conversation mode.
|
| 78 |
+
model: The pretrained Video-ChatGPT model.
|
| 79 |
+
vision_tower: Vision model to extract video features.
|
| 80 |
+
tokenizer: Tokenizer for the model.
|
| 81 |
+
image_processor: Image processor to preprocess video frames.
|
| 82 |
+
video_token_len (int): The length of video tokens.
|
| 83 |
+
|
| 84 |
+
Returns:
|
| 85 |
+
dict: Dictionary containing the model's output.
|
| 86 |
+
"""
|
| 87 |
+
|
| 88 |
+
# Prepare question string for the model
|
| 89 |
+
if model.get_model().vision_config.use_vid_start_end:
|
| 90 |
+
qs = question + "\n" + DEFAULT_VID_START_TOKEN + DEFAULT_VIDEO_PATCH_TOKEN * video_token_len + DEFAULT_VID_END_TOKEN
|
| 91 |
+
else:
|
| 92 |
+
qs = question + "\n" + DEFAULT_VIDEO_PATCH_TOKEN * video_token_len
|
| 93 |
+
|
| 94 |
+
# Prepare conversation prompt
|
| 95 |
+
conv = conv_templates[conv_mode].copy()
|
| 96 |
+
conv.append_message(conv.roles[0], qs)
|
| 97 |
+
conv.append_message(conv.roles[1], None)
|
| 98 |
+
prompt = conv.get_prompt()
|
| 99 |
+
|
| 100 |
+
# Tokenize the prompt
|
| 101 |
+
inputs = tokenizer([prompt])
|
| 102 |
+
|
| 103 |
+
# Preprocess video frames and get image tensor
|
| 104 |
+
image_tensor = image_processor.preprocess(video_frames, return_tensors="pt")["pixel_values"]
|
| 105 |
+
|
| 106 |
+
# Move image tensor to GPU and reduce precision to half
|
| 107 |
+
image_tensor = image_tensor.half().cuda()
|
| 108 |
+
|
| 109 |
+
# Generate video spatio-temporal features
|
| 110 |
+
with torch.no_grad():
|
| 111 |
+
image_forward_outs = vision_tower(image_tensor, output_hidden_states=True)
|
| 112 |
+
frame_features = image_forward_outs.hidden_states[-2][:, 1:] # Use second to last layer as in LLaVA
|
| 113 |
+
video_spatio_temporal_features = get_spatio_temporal_features_torch(frame_features)
|
| 114 |
+
|
| 115 |
+
# Move inputs to GPU
|
| 116 |
+
input_ids = torch.as_tensor(inputs.input_ids).cuda()
|
| 117 |
+
|
| 118 |
+
# Define stopping criteria for generation
|
| 119 |
+
stop_str = conv.sep if conv.sep_style != SeparatorStyle.TWO else conv.sep2
|
| 120 |
+
stopping_criteria = KeywordsStoppingCriteria([stop_str], tokenizer, input_ids)
|
| 121 |
+
|
| 122 |
+
# Run model inference
|
| 123 |
+
with torch.inference_mode():
|
| 124 |
+
output_ids = model.generate(input_ids, video_spatio_temporal_features=video_spatio_temporal_features.unsqueeze(0), do_sample=True, temperature=0.2, max_new_tokens=1024, stopping_criteria=[stopping_criteria])
|
| 125 |
+
|
| 126 |
+
# Check if output is the same as input
|
| 127 |
+
n_diff_input_output = (input_ids != output_ids[:, : input_ids.shape[1]]).sum().item()
|
| 128 |
+
if n_diff_input_output > 0:
|
| 129 |
+
print(f"[Warning] {n_diff_input_output} output_ids are not the same as the input_ids")
|
| 130 |
+
|
| 131 |
+
# Decode output tokens
|
| 132 |
+
outputs = tokenizer.batch_decode(output_ids[:, input_ids.shape[1] :], skip_special_tokens=True)[0]
|
| 133 |
+
|
| 134 |
+
# Clean output string
|
| 135 |
+
outputs = outputs.strip().rstrip(stop_str).strip()
|
| 136 |
+
|
| 137 |
+
return outputs
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def parse_args():
|
| 141 |
+
parser = argparse.ArgumentParser(description="Demo")
|
| 142 |
+
|
| 143 |
+
parser.add_argument("--model-name", type=str, required=True)
|
| 144 |
+
parser.add_argument("--vision_tower_name", type=str, default="openai/clip-vit-large-patch14")
|
| 145 |
+
parser.add_argument("--projection_path", type=str, required=False, default="")
|
| 146 |
+
parser.add_argument("--video_path", type=str, required=True, default="")
|
| 147 |
+
parser.add_argument("--conv_mode", type=str, required=False, default="video-chatgpt_v1")
|
| 148 |
+
|
| 149 |
+
args = parser.parse_args()
|
| 150 |
+
|
| 151 |
+
return args
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
if __name__ == "__main__":
|
| 155 |
+
args = parse_args()
|
| 156 |
+
|
| 157 |
+
model, vision_tower, tokenizer, image_processor, video_token_len = initialize_model(args.model_name, args.projection_path)
|
| 158 |
+
|
| 159 |
+
video_path = args.video_path
|
| 160 |
+
|
| 161 |
+
if os.path.exists(video_path):
|
| 162 |
+
video_frames = load_video(video_path)
|
| 163 |
+
|
| 164 |
+
question = input("Enter a question to check from the video:")
|
| 165 |
+
conv_mode = args.conv_mode
|
| 166 |
+
|
| 167 |
+
try:
|
| 168 |
+
# Run inference on the video and add the output to the list
|
| 169 |
+
output = video_chatgpt_infer(video_frames, question, conv_mode, model, vision_tower, tokenizer, image_processor, video_token_len)
|
| 170 |
+
print("\n\n", output)
|
| 171 |
+
|
| 172 |
+
except Exception as e:
|
| 173 |
+
print(f"Error processing video file '{video_path}': {e}")
|
spatial-model/GeoThinker/src/lmms_eval/models/video_chatgpt/utils.py
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
def disable_torch_init():
|
| 2 |
+
"""
|
| 3 |
+
Disable the redundant torch default initialization to accelerate model creation.
|
| 4 |
+
"""
|
| 5 |
+
import torch
|
| 6 |
+
|
| 7 |
+
setattr(torch.nn.Linear, "reset_parameters", lambda self: None)
|
| 8 |
+
setattr(torch.nn.LayerNorm, "reset_parameters", lambda self: None)
|
spatial-model/GeoThinker/src/lmms_eval/models/video_chatgpt/video_conversation.py
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import dataclasses
|
| 2 |
+
from enum import Enum, auto
|
| 3 |
+
from typing import List
|
| 4 |
+
|
| 5 |
+
from lmms_eval.models.video_chatgpt.eval.model_utils import load_video
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class SeparatorStyle(Enum):
|
| 9 |
+
"""Different separator style."""
|
| 10 |
+
|
| 11 |
+
SINGLE = auto()
|
| 12 |
+
TWO = auto()
|
| 13 |
+
MPT = auto()
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
@dataclasses.dataclass
|
| 17 |
+
class Conversation:
|
| 18 |
+
"""A class that keeps all conversation history."""
|
| 19 |
+
|
| 20 |
+
system: str
|
| 21 |
+
roles: List[str]
|
| 22 |
+
messages: List[List[str]]
|
| 23 |
+
offset: int
|
| 24 |
+
sep_style: SeparatorStyle = SeparatorStyle.SINGLE
|
| 25 |
+
sep: str = "###"
|
| 26 |
+
sep2: str = None
|
| 27 |
+
version: str = "Unknown"
|
| 28 |
+
|
| 29 |
+
skip_next: bool = False
|
| 30 |
+
|
| 31 |
+
def get_prompt(self):
|
| 32 |
+
if self.sep_style == SeparatorStyle.SINGLE:
|
| 33 |
+
ret = self.system + self.sep
|
| 34 |
+
for role, message in self.messages:
|
| 35 |
+
if message:
|
| 36 |
+
if type(message) is tuple:
|
| 37 |
+
message, _ = message
|
| 38 |
+
ret += role + ": " + message + self.sep
|
| 39 |
+
else:
|
| 40 |
+
ret += role + ":"
|
| 41 |
+
return ret
|
| 42 |
+
elif self.sep_style == SeparatorStyle.TWO:
|
| 43 |
+
seps = [self.sep, self.sep2]
|
| 44 |
+
ret = self.system + seps[0]
|
| 45 |
+
for i, (role, message) in enumerate(self.messages):
|
| 46 |
+
if message:
|
| 47 |
+
if type(message) is tuple:
|
| 48 |
+
message, _ = message
|
| 49 |
+
ret += role + ": " + message + seps[i % 2]
|
| 50 |
+
else:
|
| 51 |
+
ret += role + ":"
|
| 52 |
+
return ret
|
| 53 |
+
if self.sep_style == SeparatorStyle.MPT:
|
| 54 |
+
ret = self.system + self.sep
|
| 55 |
+
for role, message in self.messages:
|
| 56 |
+
if message:
|
| 57 |
+
if type(message) is tuple:
|
| 58 |
+
message, _ = message
|
| 59 |
+
ret += role + message + self.sep
|
| 60 |
+
else:
|
| 61 |
+
ret += role
|
| 62 |
+
return ret
|
| 63 |
+
else:
|
| 64 |
+
raise ValueError(f"Invalid style: {self.sep_style}")
|
| 65 |
+
|
| 66 |
+
def append_message(self, role, message):
|
| 67 |
+
self.messages.append([role, message])
|
| 68 |
+
|
| 69 |
+
def get_video_frames(self, n_clips=1, num_frm=100):
|
| 70 |
+
video_frames = []
|
| 71 |
+
for i, (role, msg) in enumerate(self.messages[self.offset :]):
|
| 72 |
+
if i % 2 == 0:
|
| 73 |
+
if type(msg) is tuple:
|
| 74 |
+
msg, video_path = msg
|
| 75 |
+
|
| 76 |
+
clip_imgs = load_video(video_path, n_clips, num_frm)
|
| 77 |
+
|
| 78 |
+
for image in clip_imgs:
|
| 79 |
+
video_frames.append(image)
|
| 80 |
+
return video_frames
|
| 81 |
+
|
| 82 |
+
def to_gradio_chatbot(self):
|
| 83 |
+
ret = []
|
| 84 |
+
for i, (role, msg) in enumerate(self.messages[self.offset :]):
|
| 85 |
+
if i % 2 == 0:
|
| 86 |
+
if type(msg) is tuple:
|
| 87 |
+
msg, image = msg
|
| 88 |
+
ret.append([msg, None])
|
| 89 |
+
else:
|
| 90 |
+
ret[-1][-1] = msg
|
| 91 |
+
# Hack to make the demo work
|
| 92 |
+
try:
|
| 93 |
+
if "<video>" in ret[0][0]:
|
| 94 |
+
ret[0][0] = ret[0][0].replace("<video>", "")
|
| 95 |
+
except Exception as e:
|
| 96 |
+
pass
|
| 97 |
+
|
| 98 |
+
return ret
|
| 99 |
+
|
| 100 |
+
def copy(self):
|
| 101 |
+
return Conversation(system=self.system, roles=self.roles, messages=[[x, y] for x, y in self.messages], offset=self.offset, sep_style=self.sep_style, sep=self.sep, sep2=self.sep2)
|
| 102 |
+
|
| 103 |
+
def dict(self):
|
| 104 |
+
return {
|
| 105 |
+
"system": self.system,
|
| 106 |
+
"roles": self.roles,
|
| 107 |
+
"messages": self.messages,
|
| 108 |
+
"offset": self.offset,
|
| 109 |
+
"sep": self.sep,
|
| 110 |
+
"sep2": self.sep2,
|
| 111 |
+
}
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
conv_v1_2 = Conversation(
|
| 115 |
+
system="A chat between a curious human and an artificial intelligence assistant. " "The assistant gives helpful, detailed, and polite answers to the human's questions.",
|
| 116 |
+
roles=("Human", "Assistant"),
|
| 117 |
+
messages=(("Human", "What are the key differences between renewable and non-renewable energy sources?"), ("Assistant", "Renewable energy sources are those that can be replenished naturally.\n")),
|
| 118 |
+
offset=2,
|
| 119 |
+
sep_style=SeparatorStyle.SINGLE,
|
| 120 |
+
sep="###",
|
| 121 |
+
)
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
conv_vicuna_v1_1 = Conversation(
|
| 125 |
+
system="A chat between a curious user and an artificial intelligence assistant. " "The assistant gives helpful, detailed, and polite answers to the user's questions.",
|
| 126 |
+
roles=("USER", "ASSISTANT"),
|
| 127 |
+
version="v1",
|
| 128 |
+
messages=(),
|
| 129 |
+
offset=0,
|
| 130 |
+
sep_style=SeparatorStyle.TWO,
|
| 131 |
+
sep=" ",
|
| 132 |
+
sep2="</s>",
|
| 133 |
+
)
|
| 134 |
+
|
| 135 |
+
conv_video_chatgpt_v1 = Conversation(
|
| 136 |
+
system="You are Video-ChatGPT, a large vision-language assistant. "
|
| 137 |
+
"You are able to understand the video content that the user provides, and assist the user with a variety of tasks using natural language."
|
| 138 |
+
"Follow the instructions carefully and explain your answers in detail based on the provided video.",
|
| 139 |
+
# system="",
|
| 140 |
+
roles=("USER", "ASSISTANT"),
|
| 141 |
+
version="v1",
|
| 142 |
+
messages=(),
|
| 143 |
+
offset=0,
|
| 144 |
+
sep_style=SeparatorStyle.TWO,
|
| 145 |
+
sep=" ",
|
| 146 |
+
sep2="</s>",
|
| 147 |
+
)
|
| 148 |
+
|
| 149 |
+
default_conversation = conv_v1_2
|
| 150 |
+
conv_templates = {
|
| 151 |
+
"default": conv_v1_2,
|
| 152 |
+
"video-chatgpt_v1": conv_video_chatgpt_v1,
|
| 153 |
+
"vicuna_v1_1": conv_vicuna_v1_1,
|
| 154 |
+
}
|
| 155 |
+
|
| 156 |
+
if __name__ == "__main__":
|
| 157 |
+
print(default_conversation.get_prompt())
|