# pyre-strict import copy import json import os import random from dataclasses import dataclass from typing import Dict, List, Sequence import numpy as np import tokenizers import torch import transformers from longvu import conversation as conversation_lib from longvu.constants import ( DEFAULT_IM_END_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IMAGE_TOKEN, IGNORE_INDEX, IMAGE_TOKEN_INDEX, ) # pyre-fixme[21]: Could not find module `decord`. from decord import cpu, VideoReader # @manual=fbsource//third-party/pypi/decord:decord from packaging import version from PIL import Image from torch import distributed as dist from torch.distributed.fsdp import ( FullStateDictConfig, FullyShardedDataParallel as FSDP, StateDictType, ) from torch.utils.data import Dataset # pyre-fixme IS_TOKENIZER_GREATER_THAN_0_14 = version.parse(tokenizers.__version__) >= version.parse( "0.14" ) from transformers import StoppingCriteria from longvu.mm_utils import KeywordsStoppingCriteria # pyre-fixme[3]: Return type must be annotated. # pyre-fixme[2]: Parameter must be annotated. def maybe_zero_3(param, ignore_status: bool = False, name=None): # NO deepspeed # from deepspeed import zero # from deepspeed.runtime.zero.partition_parameters import ZeroParamStatus # if hasattr(param, "ds_id"): # if param.ds_status == ZeroParamStatus.NOT_AVAILABLE: # if not ignore_status: # print(name, 'no ignore status') # with zero.GatheredParameters([param]): # param = param.data.detach().cpu().clone() # else: # param = param.detach().cpu().clone() return param.detach().cpu().clone() # pyre-fixme[3]: Return type must be annotated. # pyre-fixme[2]: Parameter must be annotated. def get_mm_adapter_state_maybe_zero_3(named_params, keys_to_match): to_return = { k: t for k, t in named_params if any(key_match in k for key_match in keys_to_match) } to_return = { k: maybe_zero_3(v, ignore_status=True, name=k).cpu() for k, v in to_return.items() } return to_return # pyre-fixme[3]: Return type must be annotated. # pyre-fixme[2]: Parameter must be annotated. def find_all_linear_names(model): cls = torch.nn.Linear lora_module_names = set() multimodal_keywords = ["mm_projector", "vision_tower", "vision_resampler"] for name, module in model.named_modules(): if any(mm_keyword in name for mm_keyword in multimodal_keywords): continue if isinstance(module, cls): names = name.split(".") lora_module_names.add(names[0] if len(names) == 1 else names[-1]) if "lm_head" in lora_module_names: # needed for 16-bit lora_module_names.remove("lm_head") return list(lora_module_names) def safe_save_model_for_hf_trainer( trainer: transformers.Trainer, output_dir: str ) -> None: """Collects the state dict and dump to disk.""" global_rank = dist.get_rank() save_policy = FullStateDictConfig(offload_to_cpu=True, rank0_only=True) # pyre-fixme[16]: `Trainer` has no attribute `args`. if len(trainer.args.fsdp) == 0: # pyre-fixme[16]: `Trainer` has no attribute `model`. cpu_state_dict = trainer.model.state_dict() else: with FSDP.state_dict_type( trainer.model, StateDictType.FULL_STATE_DICT, save_policy ): cpu_state_dict = trainer.model.state_dict() for key in cpu_state_dict.keys(): cpu_state_dict[key] = cpu_state_dict[key].to(torch.bfloat16) if global_rank == 0: trainer.model.config.save_pretrained(output_dir) current_folder = output_dir.split("/")[-1] parent_folder = os.path.dirname(output_dir) save_path = os.path.join(output_dir, "pytorch_model.bin") if getattr(trainer.args, "tune_mm_mlp_adapter", False) and not getattr( trainer.args, "tune_text_decoder", False ): # Only save Adapter keys_to_match = ["mm_projector"] if getattr(trainer.args, "use_im_start_end", False): keys_to_match.extend(["embed_tokens", "embed_in"]) freeze_layer_remove = [] for key in cpu_state_dict.keys(): remove = True for key_match in keys_to_match: if key_match in key: remove = False break if remove: freeze_layer_remove.append(key) for key in freeze_layer_remove: del cpu_state_dict[key] if current_folder.startswith("checkpoint-"): mm_projector_folder = os.path.join(parent_folder, "mm_projector") os.makedirs(mm_projector_folder, exist_ok=True) save_path = os.path.join(mm_projector_folder, f"{current_folder}.bin") else: save_path = os.path.join(output_dir, f"mm_projector.bin") torch.save(cpu_state_dict, save_path) def smart_tokenizer_and_embedding_resize( # pyre-fixme[24]: Generic type `dict` expects 2 type parameters, use # `typing.Dict[, ]` to avoid runtime subscripting errors. special_tokens_dict: Dict, tokenizer: transformers.PreTrainedTokenizer, model: transformers.PreTrainedModel, ) -> None: """Resize tokenizer and embedding. Note: This is the unoptimized version that may make your embedding size not be divisible by 64. """ num_new_tokens = tokenizer.add_special_tokens(special_tokens_dict) # pyre-fixme[16]: `PreTrainedModel` has no attribute `resize_token_embeddings`. model.resize_token_embeddings(len(tokenizer)) if num_new_tokens > 0: # pyre-fixme[16]: `PreTrainedModel` has no attribute `get_input_embeddings`. input_embeddings = model.get_input_embeddings().weight.data # pyre-fixme[16]: `PreTrainedModel` has no attribute `get_output_embeddings`. output_embeddings = model.get_output_embeddings().weight.data input_embeddings_avg = input_embeddings[:-num_new_tokens].mean( dim=0, keepdim=True ) output_embeddings_avg = output_embeddings[:-num_new_tokens].mean( dim=0, keepdim=True ) input_embeddings[-num_new_tokens:] = input_embeddings_avg output_embeddings[-num_new_tokens:] = output_embeddings_avg def _tokenize_fn( strings: Sequence[str], tokenizer: transformers.PreTrainedTokenizer, # pyre-fixme[24]: Generic type `dict` expects 2 type parameters, use # `typing.Dict[, ]` to avoid runtime subscripting errors. ) -> Dict: """Tokenize a list of strings.""" tokenized_list = [ tokenizer( text, return_tensors="pt", padding="longest", max_length=tokenizer.model_max_length, truncation=True, ) for text in strings ] input_ids = labels = [tokenized.input_ids[0] for tokenized in tokenized_list] input_ids_lens = labels_lens = [ tokenized.input_ids.ne(tokenizer.pad_token_id).sum().item() for tokenized in tokenized_list ] return dict( input_ids=input_ids, labels=labels, input_ids_lens=input_ids_lens, labels_lens=labels_lens, ) # pyre-fixme[2]: Parameter must be annotated. def _mask_targets(target, tokenized_lens, speakers) -> None: # cur_idx = 0 cur_idx = tokenized_lens[0] tokenized_lens = tokenized_lens[1:] target[:cur_idx] = IGNORE_INDEX for tokenized_len, speaker in zip(tokenized_lens, speakers): if speaker == "human": target[cur_idx + 2 : cur_idx + tokenized_len] = IGNORE_INDEX cur_idx += tokenized_len # pyre-fixme[3]: Return type must be annotated. # pyre-fixme[2]: Parameter must be annotated. def _add_speaker_and_signal(header, source, get_conversation: bool = True): """Add speaker and start/end signal on each round.""" BEGIN_SIGNAL = "### " END_SIGNAL = "\n" conversation = header for sentence in source: from_str = sentence["from"] if from_str.lower() == "human": from_str = conversation_lib.default_conversation.roles[0] elif from_str.lower() == "gpt": from_str = conversation_lib.default_conversation.roles[1] else: from_str = "unknown" sentence["value"] = ( BEGIN_SIGNAL + from_str + ": " + sentence["value"] + END_SIGNAL ) if get_conversation: conversation += sentence["value"] conversation += BEGIN_SIGNAL return conversation # pyre-fixme[3]: Return type must be annotated. # pyre-fixme[2]: Parameter must be annotated. def expand2square(pil_img, background_color): width, height = pil_img.size if width == height: return pil_img elif width > height: result = Image.new(pil_img.mode, (width, width), background_color) result.paste(pil_img, (0, (width - height) // 2)) return result else: result = Image.new(pil_img.mode, (height, height), background_color) result.paste(pil_img, ((height - width) // 2, 0)) return result # pyre-fixme[3]: Return type must be annotated. # pyre-fixme[2]: Parameter must be annotated. def process_images(images, image_processor, model_cfg): if isinstance(image_processor, list): processor_aux_list = image_processor new_images_aux_list = [] for image in images: if isinstance(image, np.ndarray): image = Image.fromarray(image) image_aux_list = [] for processor_aux in processor_aux_list: image_aux = image if hasattr(processor_aux, "image_mean"): try: target_resolution = processor_aux.crop_size["height"] except: target_resolution = processor_aux.size["height"] image_aux = expand2square( image_aux, tuple(int(x * 255) for x in processor_aux.image_mean) ).resize((target_resolution, target_resolution)) image_aux = processor_aux.preprocess(image_aux, return_tensors="pt")[ "pixel_values" ][0] image_aux_list.append(image_aux) new_images_aux_list.append(image_aux_list) new_images_aux_list = [ list(batch_image_aux) for batch_image_aux in zip(*new_images_aux_list) ] new_images_aux_list = [ torch.stack(image_aux).half().cuda() for image_aux in new_images_aux_list ] return new_images_aux_list else: image_aspect_ratio = getattr(model_cfg, "image_aspect_ratio", None) new_images = [] if image_aspect_ratio == "pad": for image in images: image = expand2square( image, tuple(int(x * 255) for x in image_processor.image_mean) ) image = image_processor.preprocess(image, return_tensors="pt")[ "pixel_values" ][0] new_images.append(image) else: return image_processor(images, return_tensors="pt")["pixel_values"] if all(x.shape == new_images[0].shape for x in new_images): new_images = torch.stack(new_images, dim=0) return new_images # pyre-fixme[2]: Parameter must be annotated. # pyre-fixme[24]: Generic type `dict` expects 2 type parameters, use # `typing.Dict[, ]` to avoid runtime subscripting errors. def preprocess_multimodal(sources: Sequence[str], data_args) -> Dict: is_multimodal = data_args.is_multimodal if not is_multimodal: # pyre-fixme[7]: Expected `Dict[typing.Any, typing.Any]` but got # `Sequence[str]`. return sources for source in sources: for sentence in source: if ( # pyre-fixme[6]: For 1st argument expected `Union[slice, SupportsIndex]` # but got `str`. DEFAULT_IMAGE_TOKEN in sentence["value"] # pyre-fixme[6]: For 1st argument expected `Union[slice, SupportsIndex]` # but got `str`. or "