

import os
import time
import warnings
from dataclasses import dataclass, field
from enum import Enum
from typing import List, Optional, Union

import torch
from filelock import FileLock
from torch.utils.data import Dataset

from ...tokenization_utils_base import PreTrainedTokenizerBase
from ...utils import logging
from ..processors.glue import glue_convert_examples_to_features, glue_output_modes, glue_processors
from ..processors.utils import InputFeatures


_UpperCAmelCase	:     List[Any]		       = logging.get_logger(__name__)







@dataclass
class 				lowercase       :
				__SCREAMING_SNAKE_CASE      :				str     =    field(metadata={'''help''': '''The name of the task to train on: ''' + ''', '''.join(glue_processors.keys()    )}    )
				__SCREAMING_SNAKE_CASE      :				str     =    field(
				    metadata={'''help''': '''The input data dir. Should contain the .tsv files (or other data files) for the task.'''}    )
				__SCREAMING_SNAKE_CASE      :				int     =    field(
				    default=128			,						metadata={
				        '''help''': (
				            '''The maximum total input sequence length after tokenization. Sequences longer '''
				            '''than this will be truncated, sequences shorter will be padded.'''
				        )
				    }			,						)
				__SCREAMING_SNAKE_CASE      :				bool     =    field(
				    default=lowercase_			,						metadata={'''help''': '''Overwrite the cached training and evaluation sets'''}    )




				def 					a							(      self ):
											snake_case_           =					self.task_name.lower()







class 				lowercase       ( lowercase_    ):
				__SCREAMING_SNAKE_CASE      :				List[str]     =    '''train'''
				__SCREAMING_SNAKE_CASE      :				str     =    '''dev'''
				__SCREAMING_SNAKE_CASE      :				Optional[int]     =    '''test'''







class 				lowercase       ( lowercase_    ):
				__SCREAMING_SNAKE_CASE      :				GlueDataTrainingArguments
				__SCREAMING_SNAKE_CASE      :				str
				__SCREAMING_SNAKE_CASE      :				List[InputFeatures]




				def __init__(      self   ,     snake_case   ,     snake_case   ,     snake_case = None   ,     snake_case = Split.train   ,     snake_case = None   ,     ):
											warnings.warn(
											    'This dataset will be removed from the library soon, preprocessing should be handled with the 🤗 Datasets '
											    'library. You can have a look at this example script for pointers: '
											    'https://github.com/huggingface/transformers/blob/main/examples/pytorch/text-classification/run_glue.py'   ,     snake_case   ,     )
											snake_case_           =					args
											snake_case_           =					glue_processors[args.task_name]()
											snake_case_           =					glue_output_modes[args.task_name]
											if isinstance(snake_case   ,     snake_case ):
																		try:
																									snake_case_           =					Split[mode]
																		except KeyError:
																									raise KeyError('mode is not a valid split name' )
        # Load data features from cache or dataset file
											snake_case_           =					os.path.join(
											    cache_dir if cache_dir is not None else args.data_dir   ,     F'''cached_{mode.value}_{tokenizer.__class__.__name__}_{args.max_seq_length}_{args.task_name}'''   ,     )
											snake_case_           =					self.processor.get_labels()
											if args.task_name in ["mnli", "mnli-mm"] and tokenizer.__class__.__name__ in (
											    "RobertaTokenizer",
											    "RobertaTokenizerFast",
											    "XLMRobertaTokenizer",
											    "BartTokenizer",
											    "BartTokenizerFast",
											):
																		# HACK(label indices are swapped in RoBERTa pretrained model)
																		snake_case_       ,					snake_case_           =					label_list[2], label_list[1]
											snake_case_           =					label_list

											# Make sure only the first process in distributed training processes the dataset,
											# and the others will use the cache.
											snake_case_           =					cached_features_file + '.lock'
											with FileLock(snake_case ):
																		if os.path.exists(snake_case ) and not args.overwrite_cache:
																									snake_case_           =					time.time()
																									snake_case_           =					torch.load(snake_case )
																									logger.info(
																									    F'''Loading features from cached file {cached_features_file} [took %.3f s]'''   ,     time.time() - start )
																		else:
																									logger.info(F'''Creating features from dataset file at {args.data_dir}''' )

																									if mode == Split.dev:
																																snake_case_           =					self.processor.get_dev_examples(args.data_dir )
																									elif mode == Split.test:
																																snake_case_           =					self.processor.get_test_examples(args.data_dir )
																									else:
																																snake_case_           =					self.processor.get_train_examples(args.data_dir )
																									if limit_length is not None:
																																snake_case_           =					examples[:limit_length]
																									snake_case_           =					glue_convert_examples_to_features(
																									    snake_case   ,     snake_case   ,     max_length=args.max_seq_length   ,     label_list=snake_case   ,     output_mode=self.output_mode   ,     )
																									snake_case_           =					time.time()
																									torch.save(self.features   ,     snake_case )
																									# ^ This seems to take a lot of time so I want to investigate why and how we can improve.
																									logger.info(
																									    F'''Saving features into cached file {cached_features_file} [took {time.time() - start:.3f} s]''' )




				def __len__(      self ):
											return len(self.features )




				def __getitem__(      self   ,     snake_case ):
											return self.features[i]




				def 					a							(      self ):
											return self.label_list







import copy
import os
from typing import Union

from ...configuration_utils import PretrainedConfig
from ...models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES
from ...utils import logging
from ..auto import CONFIG_MAPPING


_UpperCAmelCase	:     Dict		       = logging.get_logger(__name__)

_UpperCAmelCase	:     Dict		       = {
    """salesforce/blip2-opt-2.7b""": """https://huggingface.co/salesforce/blip2-opt-2.7b/resolve/main/config.json""",
}







class 				lowercase       ( lowercase_    ):
				__SCREAMING_SNAKE_CASE      :				Optional[int]     =    '''blip_2_vision_model'''




				def __init__(      self   ,     snake_case=1408   ,     snake_case=6144   ,     snake_case=39   ,     snake_case=16   ,     snake_case=224   ,     snake_case=14   ,     snake_case="gelu"   ,     snake_case=0.0_00_01   ,     snake_case=0.0   ,     snake_case=1e-1_0   ,     snake_case=True   ,     **snake_case   ,     ):
											super().__init__(**snake_case )

											snake_case_           =					hidden_size
											snake_case_           =					intermediate_size
											snake_case_           =					num_hidden_layers
											snake_case_           =					num_attention_heads
											snake_case_           =					patch_size
											snake_case_           =					image_size
											snake_case_           =					initializer_range
											snake_case_           =					attention_dropout
											snake_case_           =					layer_norm_eps
											snake_case_           =					hidden_act
											snake_case_           =					qkv_bias




				@classmethod
				def 					a							(      cls   ,     snake_case   ,     **snake_case ):
											cls._set_token_in_kwargs(snake_case )

											snake_case_       ,					snake_case_           =					cls.get_config_dict(snake_case   ,     **snake_case )

											# get the vision config dict if we are loading from Blip2Config
											if config_dict.get('model_type' ) == "blip-2":
																		snake_case_           =					config_dict['vision_config']

											if "model_type" in config_dict and hasattr(cls   ,     'model_type' ) and config_dict["model_type"] != cls.model_type:
																		logger.warning(
																		    F'''You are using a model of type {config_dict["model_type"]} to instantiate a model of type '''
																		    F'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' )

											return cls.from_dict(snake_case   ,     **snake_case )







class 				lowercase       ( lowercase_    ):
				__SCREAMING_SNAKE_CASE      :				Any     =    '''blip_2_qformer'''




				def __init__(      self   ,     snake_case=3_0522   ,     snake_case=768   ,     snake_case=12   ,     snake_case=12   ,     snake_case=3072   ,     snake_case="gelu"   ,     snake_case=0.1   ,     snake_case=0.1   ,     snake_case=512   ,     snake_case=0.02   ,     snake_case=1e-1_2   ,     snake_case=0   ,     snake_case="absolute"   ,     snake_case=2   ,     snake_case=1408   ,     **snake_case   ,     ):
											super().__init__(pad_token_id=snake_case   ,     **snake_case )

											snake_case_           =					vocab_size
											snake_case_           =					hidden_size
											snake_case_           =					num_hidden_layers
											snake_case_           =					num_attention_heads
											snake_case_           =					hidden_act
											snake_case_           =					intermediate_size
											snake_case_           =					hidden_dropout_prob
											snake_case_           =					attention_probs_dropout_prob
											snake_case_           =					max_position_embeddings
											snake_case_           =					initializer_range
											snake_case_           =					layer_norm_eps
											snake_case_           =					position_embedding_type
											snake_case_           =					cross_attention_frequency
											snake_case_           =					encoder_hidden_size




				@classmethod
				def 					a							(      cls   ,     snake_case   ,     **snake_case ):
											cls._set_token_in_kwargs(snake_case )

											snake_case_       ,					snake_case_           =					cls.get_config_dict(snake_case   ,     **snake_case )

											# get the qformer config dict if we are loading from Blip2Config
											if config_dict.get('model_type' ) == "blip-2":
																		snake_case_           =					config_dict['qformer_config']

											if "model_type" in config_dict and hasattr(cls   ,     'model_type' ) and config_dict["model_type"] != cls.model_type:
																		logger.warning(
																		    F'''You are using a model of type {config_dict["model_type"]} to instantiate a model of type '''
																		    F'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' )

											return cls.from_dict(snake_case   ,     **snake_case )







class 				lowercase       ( lowercase_    ):
				__SCREAMING_SNAKE_CASE      :				Optional[int]     =    '''blip-2'''
				__SCREAMING_SNAKE_CASE      :				Dict     =    True




				def __init__(      self   ,     snake_case=None   ,     snake_case=None   ,     snake_case=None   ,     snake_case=32   ,     **snake_case ):
											super().__init__(**snake_case )

											if vision_config is None:
																		snake_case_           =					{}
																		logger.info('vision_config is None. initializing the Blip2VisionConfig with default values.' )

											if qformer_config is None:
																		snake_case_           =					{}
																		logger.info('qformer_config is None. Initializing the Blip2QFormerConfig with default values.' )

											if text_config is None:
																		snake_case_           =					{}
																		logger.info('text_config is None. Initializing the text config with default values (`OPTConfig`).' )

											snake_case_           =					BlipaVisionConfig(**snake_case )
											snake_case_           =					BlipaQFormerConfig(**snake_case )
											snake_case_           =					text_config['model_type'] if 'model_type' in text_config else 'opt'
											snake_case_           =					CONFIG_MAPPING[text_model_type](**snake_case )

											snake_case_           =					self.text_config.tie_word_embeddings
											snake_case_           =					self.text_config.is_encoder_decoder

											snake_case_           =					num_query_tokens
											snake_case_           =					self.vision_config.hidden_size
											snake_case_           =					self.text_config.model_type in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES
											snake_case_           =					1.0
											snake_case_           =					0.02




				@classmethod
				def 					a							(      cls   ,     snake_case   ,     snake_case   ,     snake_case   ,     **snake_case   ,     ):
											return cls(
											    vision_config=vision_config.to_dict()   ,     qformer_config=qformer_config.to_dict()   ,     text_config=text_config.to_dict()   ,     **snake_case   ,     )




				def 					a							(      self ):
											snake_case_           =					copy.deepcopy(self.__dict__ )
											snake_case_           =					self.vision_config.to_dict()
											snake_case_           =					self.qformer_config.to_dict()
											snake_case_           =					self.text_config.to_dict()
											snake_case_           =					self.__class__.model_type
											return output




