



import logging
import math
import os
from dataclasses import dataclass, field
from glob import glob
from typing import Optional

from torch.utils.data import ConcatDataset

import transformers
from transformers import (
    CONFIG_MAPPING,
    MODEL_WITH_LM_HEAD_MAPPING,
    AutoConfig,
    AutoModelWithLMHead,
    AutoTokenizer,
    DataCollatorForLanguageModeling,
    DataCollatorForPermutationLanguageModeling,
    DataCollatorForWholeWordMask,
    HfArgumentParser,
    LineByLineTextDataset,
    LineByLineWithRefDataset,
    PreTrainedTokenizer,
    TextDataset,
    Trainer,
    TrainingArguments,
    set_seed,
)
from transformers.trainer_utils import is_main_process


lowerCAmelCase__					  =  logging.getLogger(__name__)


lowerCAmelCase__					  =  list(MODEL_WITH_LM_HEAD_MAPPING.keys())
lowerCAmelCase__					  =  tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)

@dataclass
class 				snake_case__:

					"""simple docstring"""






					lowercase_								=		field(
					    default=_UpperCamelCase    ,      metadata={
					        """help""": (
					            """The model checkpoint for weights initialization. Leave None if you want to train a model from"""
					            """ scratch."""
					        )
					    }    ,      )
					lowercase_								=		field(
					    default=_UpperCamelCase    ,      metadata={"""help""": """If training from scratch, pass a model type from the list: """ + """, """.join(_UpperCamelCase      )}    ,      )
					lowercase_								=		field(
					    default=_UpperCamelCase    ,      metadata={"""help""": """Pretrained config name or path if not the same as model_name"""}      )
					lowercase_								=		field(
					    default=_UpperCamelCase    ,      metadata={"""help""": """Pretrained tokenizer name or path if not the same as model_name"""}      )
					lowercase_								=		field(
					    default=_UpperCamelCase    ,      metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co"""}    ,      )






@dataclass
class 				snake_case__:

					"""simple docstring"""






					lowercase_								=		field(
					    default=_UpperCamelCase    ,      metadata={"""help""": """The input training data file (a text file)."""}      )
					lowercase_								=		field(
					    default=_UpperCamelCase    ,      metadata={
					        """help""": (
					            """The input training data files (multiple files in glob format). """
					            """Very often splitting large files to smaller files can prevent tokenizer going out of memory"""
					        )
					    }    ,      )
					lowercase_								=		field(
					    default=_UpperCamelCase    ,      metadata={"""help""": """An optional input evaluation data file to evaluate the perplexity on (a text file)."""}    ,      )
					lowercase_								=		field(
					    default=_UpperCamelCase    ,      metadata={"""help""": """An optional input train ref data file for whole word mask in Chinese."""}    ,      )
					lowercase_								=		field(
					    default=_UpperCamelCase    ,      metadata={"""help""": """An optional input eval ref data file for whole word mask in Chinese."""}    ,      )
					lowercase_								=		field(
					    default=_UpperCamelCase    ,      metadata={"""help""": """Whether distinct lines of text in the dataset are to be handled as distinct sequences."""}    ,      )

					lowercase_								=		field(
					    default=_UpperCamelCase    ,      metadata={"""help""": """Train with masked-language modeling loss instead of language modeling."""}      )
					lowercase_								=		field(default=_UpperCamelCase    ,      metadata={"""help""": """Whether ot not to use whole word mask."""}      )
					lowercase_								=		field(
					    default=0.15    ,      metadata={"""help""": """Ratio of tokens to mask for masked language modeling loss"""}      )
					lowercase_								=		field(
					    default=1 / 6    ,      metadata={
					        """help""": (
					            """Ratio of length of a span of masked tokens to surrounding context length for permutation language"""
					            """ modeling."""
					        )
					    }    ,      )
					lowercase_								=		field(
					    default=5    ,      metadata={"""help""": """Maximum length of a span of masked tokens for permutation language modeling."""}      )

					lowercase_								=		field(
					    default=-1    ,      metadata={
					        """help""": (
					            """Optional input sequence length after tokenization."""
					            """The training dataset will be truncated in block of this size for training."""
					            """Default to the model max input length for single sentence inputs (take into account special tokens)."""
					        )
					    }    ,      )
					lowercase_								=		field(
					    default=_UpperCamelCase    ,      metadata={"""help""": """Overwrite the cached training and evaluation sets"""}      )






def  __lowerCamelCase (       lowerCamelCase__					,			lowerCamelCase__					,			lowerCamelCase__ = False					,			lowerCamelCase__ = None					,			):

				"""simple docstring"""


				def _dataset(lowerCamelCase__					,			lowerCamelCase__=None						):
								if args.line_by_line:
												if ref_path is not None:
																if not args.whole_word_mask or not args.mlm:
																				raise ValueError("You need to set world whole masking and mlm to True for Chinese Whole Word Mask"						)
																return LineByLineWithRefDataset(
																    tokenizer=_a					,			file_path=_a					,			block_size=args.block_size					,			ref_path=_a					,			)

												return LineByLineTextDataset(tokenizer=_a					,			file_path=_a					,			block_size=args.block_size						)
								else:
												return TextDataset(
												    tokenizer=_a					,			file_path=_a					,			block_size=args.block_size					,			overwrite_cache=args.overwrite_cache					,			cache_dir=_a					,			)

				if evaluate:
								return _dataset(args.eval_data_file					,			args.eval_ref_file						)
				elif args.train_data_files:
								return ConcatDataset([_dataset(_a						) for f in glob(args.train_data_files						)]						)
				else:
								return _dataset(args.train_data_file					,			args.train_ref_file						)


def  __lowerCamelCase (       ):

				"""simple docstring"""


				lowercase__					:   Optional[int]													=					HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)						)
				lowercase__							,							lowercase__							,							lowercase__					:   Union[str, Any]													=					parser.parse_args_into_dataclasses()

				if data_args.eval_data_file is None and training_args.do_eval:
								raise ValueError(
								    "Cannot do evaluation without an evaluation data file. Either supply a file to --eval_data_file "
								    "or remove the --do_eval argument."						)
				if (
				    os.path.exists(training_args.output_dir						)
				    and os.listdir(training_args.output_dir						)
				    and training_args.do_train
				    and not training_args.overwrite_output_dir
				):
								raise ValueError(
								    F"""Output directory ({training_args.output_dir}) already exists and is not empty. Use"""
								    " --overwrite_output_dir to overcome."						)

				# Setup logging
				logging.basicConfig(
				    format="%(asctime)s - %(levelname)s - %(name)s - %(message)s"					,			datefmt="%m/%d/%Y %H:%M:%S"					,			level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN					,			)
				logger.warning(
				    "Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s"					,			training_args.local_rank					,			training_args.device					,			training_args.n_gpu					,			bool(training_args.local_rank != -1						)					,			training_args.fpaa					,			)
				# Set the verbosity to info of the Transformers logger (on main process only):
				if is_main_process(training_args.local_rank						):
								transformers.utils.logging.set_verbosity_info()
								transformers.utils.logging.enable_default_handler()
								transformers.utils.logging.enable_explicit_format()
				logger.info("Training/evaluation parameters %s"					,			_a						)

				# Set seed
				set_seed(training_args.seed						)

				# Load pretrained model and tokenizer
				#
				# Distributed training:
				# The .from_pretrained methods guarantee that only one local process can concurrently
				# download model & vocab.

				if model_args.config_name:
								lowercase__					:   Optional[int]													=					AutoConfig.from_pretrained(model_args.config_name					,			cache_dir=model_args.cache_dir						)
				elif model_args.model_name_or_path:
								lowercase__					:   int													=					AutoConfig.from_pretrained(model_args.model_name_or_path					,			cache_dir=model_args.cache_dir						)
				else:
								lowercase__					:   int													=					CONFIG_MAPPING[model_args.model_type]()
								logger.warning("You are instantiating a new config instance from scratch."						)

				if model_args.tokenizer_name:
								lowercase__					:   List[str]													=					AutoTokenizer.from_pretrained(model_args.tokenizer_name					,			cache_dir=model_args.cache_dir						)
				elif model_args.model_name_or_path:
								lowercase__					:   int													=					AutoTokenizer.from_pretrained(model_args.model_name_or_path					,			cache_dir=model_args.cache_dir						)
				else:
								raise ValueError(
								    "You are instantiating a new tokenizer from scratch. This is not supported, but you can do it from another"
								    " script, save it,and load it from here, using --tokenizer_name"						)

				if model_args.model_name_or_path:
								lowercase__					:   Dict													=					AutoModelWithLMHead.from_pretrained(
								    model_args.model_name_or_path					,			from_tf=bool(".ckpt" in model_args.model_name_or_path						)					,			config=_a					,			cache_dir=model_args.cache_dir					,			)
				else:
								logger.info("Training new model from scratch"						)
								lowercase__					:   str													=					AutoModelWithLMHead.from_config(_a						)

				model.resize_token_embeddings(len(_a						)						)

				if config.model_type in ["bert", "roberta", "distilbert", "camembert"] and not data_args.mlm:
								raise ValueError(
								    "BERT and RoBERTa-like models do not have LM heads but masked LM heads. They must be run using the"
								    "--mlm flag (masked language modeling)."						)

				if data_args.block_size <= 0:
								lowercase__					:   Dict													=					tokenizer.max_len
								# Our input block size will be the max possible for the model
				else:
								lowercase__					:   Any													=					min(data_args.block_size					,			tokenizer.max_len						)

				# Get datasets

				lowercase__					:   str													=					(
				    get_dataset(_a					,			tokenizer=_a					,			cache_dir=model_args.cache_dir						) if training_args.do_train else None
				)
				lowercase__					:   Union[str, Any]													=					(
				    get_dataset(_a					,			tokenizer=_a					,			evaluate=_a					,			cache_dir=model_args.cache_dir						)
				    if training_args.do_eval
				    else None
				)
				if config.model_type == "xlnet":
								lowercase__					:   Any													=					DataCollatorForPermutationLanguageModeling(
								    tokenizer=_a					,			plm_probability=data_args.plm_probability					,			max_span_length=data_args.max_span_length					,			)
				else:
								if data_args.mlm and data_args.whole_word_mask:
												lowercase__					:   Optional[Any]													=					DataCollatorForWholeWordMask(
												    tokenizer=_a					,			mlm_probability=data_args.mlm_probability						)
								else:
												lowercase__					:   Optional[Any]													=					DataCollatorForLanguageModeling(
												    tokenizer=_a					,			mlm=data_args.mlm					,			mlm_probability=data_args.mlm_probability						)

    # Initialize our Trainer
				lowercase__					:   List[Any]													=					Trainer(
				    model=_a					,			args=_a					,			data_collator=_a					,			train_dataset=_a					,			eval_dataset=_a					,			prediction_loss_only=_a					,			)

				# Training
				if training_args.do_train:
								lowercase__					:   Optional[Any]													=					(
								    model_args.model_name_or_path
								    if model_args.model_name_or_path is not None and os.path.isdir(model_args.model_name_or_path						)
								    else None
								)
								trainer.train(model_path=_a						)
								trainer.save_model()
								# For convenience, we also re-save the tokenizer to the same directory,
								# so that you can share your model easily on huggingface.co/models =)
								if trainer.is_world_master():
												tokenizer.save_pretrained(training_args.output_dir						)

    # Evaluation
				lowercase__					:   Optional[Any]													=					{}
				if training_args.do_eval:
								logger.info("*** Evaluate ***"						)

								lowercase__					:   List[str]													=					trainer.evaluate()

								lowercase__					:   List[Any]													=					math.exp(eval_output["eval_loss"]						)
								lowercase__					:   str													=					{"perplexity": perplexity}

								lowercase__					:   str													=					os.path.join(training_args.output_dir					,			"eval_results_lm.txt"						)
								if trainer.is_world_master():
												with open(_a					,			"w"						) as writer:
																logger.info("***** Eval results *****"						)
																for key in sorted(result.keys()						):
																				logger.info("  %s = %s"					,			_a					,			str(result[key]						)						)
																				writer.write("%s = %s\n" % (key, str(result[key]						))						)

								results.update(_a						)

				return results


def  __lowerCamelCase (       lowerCamelCase__						):

				"""simple docstring"""


				main()


if __name__ == "__main__":
						main()









import copy
import os
from typing import Union

from ...configuration_utils import PretrainedConfig
from ...utils import logging


lowerCAmelCase__					  =  logging.get_logger(__name__)

lowerCAmelCase__					  =  {
    '''BridgeTower/bridgetower-base''': '''https://huggingface.co/BridgeTower/bridgetower-base/blob/main/config.json''',
    '''BridgeTower/bridgetower-base-itm-mlm''': (
        '''https://huggingface.co/BridgeTower/bridgetower-base-itm-mlm/blob/main/config.json'''
    ),
}

class 				snake_case__(_UpperCamelCase      ):

					"""simple docstring"""






					lowercase_								=		"""bridgetower_vision_model"""







					def __init__(							self :     str				,       SCREAMING_SNAKE_CASE :     Dict=768				,       SCREAMING_SNAKE_CASE :     Union[str, Any]=12				,       SCREAMING_SNAKE_CASE :     Dict=3				,       SCREAMING_SNAKE_CASE :     Dict=16				,       SCREAMING_SNAKE_CASE :     List[Any]=288				,       SCREAMING_SNAKE_CASE :     List[Any]=1				,       SCREAMING_SNAKE_CASE :     List[str]=1E-0_5				,       SCREAMING_SNAKE_CASE :     str=False				,       SCREAMING_SNAKE_CASE :     Any=True				,       SCREAMING_SNAKE_CASE :     Tuple=False				,       **SCREAMING_SNAKE_CASE :     List[str]				,       ):
									super().__init__(**SCREAMING_SNAKE_CASE					)
									lowercase__					:   Union[str, Any]													=					hidden_size
									lowercase__					:   str													=					num_hidden_layers
									lowercase__					:   str													=					num_channels
									lowercase__					:   Optional[int]													=					patch_size
									lowercase__					:   Dict													=					image_size
									lowercase__					:   List[Any]													=					initializer_factor
									lowercase__					:   int													=					layer_norm_eps
									lowercase__					:   List[str]													=					stop_gradient
									lowercase__					:   Optional[int]													=					share_layernorm
									lowercase__					:   Optional[int]													=					remove_last_layer







					@classmethod
					def 			snake_case					(							cls :     Tuple				,       SCREAMING_SNAKE_CASE :     Union[str, os.PathLike]				,       **SCREAMING_SNAKE_CASE :     str					):
									lowercase__							,							lowercase__					:   Optional[Any]													=					cls.get_config_dict(SCREAMING_SNAKE_CASE				,       **SCREAMING_SNAKE_CASE					)

									if config_dict.get("model_type"					) == "bridgetower":
													lowercase__					:   Optional[int]													=					config_dict["text_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(SCREAMING_SNAKE_CASE				,       **SCREAMING_SNAKE_CASE					)






class 				snake_case__(_UpperCamelCase      ):

					"""simple docstring"""






					lowercase_								=		"""bridgetower_text_model"""







					def __init__(							self :     Tuple				,       SCREAMING_SNAKE_CASE :     Union[str, Any]=50_265				,       SCREAMING_SNAKE_CASE :     Optional[int]=768				,       SCREAMING_SNAKE_CASE :     List[str]=12				,       SCREAMING_SNAKE_CASE :     Union[str, Any]=12				,       SCREAMING_SNAKE_CASE :     List[Any]=1				,       SCREAMING_SNAKE_CASE :     Any=3_072				,       SCREAMING_SNAKE_CASE :     Union[str, Any]="gelu"				,       SCREAMING_SNAKE_CASE :     Optional[int]=0.1				,       SCREAMING_SNAKE_CASE :     List[str]=0.1				,       SCREAMING_SNAKE_CASE :     Tuple=514				,       SCREAMING_SNAKE_CASE :     List[str]=1				,       SCREAMING_SNAKE_CASE :     Dict=1E-0_5				,       SCREAMING_SNAKE_CASE :     List[str]=1				,       SCREAMING_SNAKE_CASE :     str=0				,       SCREAMING_SNAKE_CASE :     List[Any]=2				,       SCREAMING_SNAKE_CASE :     Optional[Any]="absolute"				,       SCREAMING_SNAKE_CASE :     int=True				,       **SCREAMING_SNAKE_CASE :     int				,       ):
									super().__init__(**SCREAMING_SNAKE_CASE					)

									lowercase__					:   Any													=					vocab_size
									lowercase__					:   Optional[Any]													=					hidden_size
									lowercase__					:   Optional[int]													=					num_hidden_layers
									lowercase__					:   Optional[int]													=					num_attention_heads
									lowercase__					:   int													=					hidden_act
									lowercase__					:   Optional[Any]													=					initializer_factor
									lowercase__					:   Dict													=					intermediate_size
									lowercase__					:   Tuple													=					hidden_dropout_prob
									lowercase__					:   List[Any]													=					attention_probs_dropout_prob
									lowercase__					:   Optional[int]													=					max_position_embeddings
									lowercase__					:   str													=					type_vocab_size
									lowercase__					:   str													=					layer_norm_eps
									lowercase__					:   Dict													=					position_embedding_type
									lowercase__					:   Optional[Any]													=					use_cache
									lowercase__					:   List[str]													=					pad_token_id
									lowercase__					:   Optional[Any]													=					bos_token_id
									lowercase__					:   Optional[Any]													=					eos_token_id







					@classmethod
					def 			snake_case					(							cls :     Optional[int]				,       SCREAMING_SNAKE_CASE :     Union[str, os.PathLike]				,       **SCREAMING_SNAKE_CASE :     str					):
									lowercase__							,							lowercase__					:   Optional[Any]													=					cls.get_config_dict(SCREAMING_SNAKE_CASE				,       **SCREAMING_SNAKE_CASE					)

									if config_dict.get("model_type"					) == "bridgetower":
													lowercase__					:   List[Any]													=					config_dict["text_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(SCREAMING_SNAKE_CASE				,       **SCREAMING_SNAKE_CASE					)






class 				snake_case__(_UpperCamelCase      ):

					"""simple docstring"""






					lowercase_								=		"""bridgetower"""







					def __init__(							self :     Tuple				,       SCREAMING_SNAKE_CASE :     Optional[int]=True				,       SCREAMING_SNAKE_CASE :     Dict="gelu"				,       SCREAMING_SNAKE_CASE :     Any=768				,       SCREAMING_SNAKE_CASE :     Dict=1				,       SCREAMING_SNAKE_CASE :     Union[str, Any]=1E-0_5				,       SCREAMING_SNAKE_CASE :     Tuple=False				,       SCREAMING_SNAKE_CASE :     List[Any]="add"				,       SCREAMING_SNAKE_CASE :     Any=12				,       SCREAMING_SNAKE_CASE :     Any=6				,       SCREAMING_SNAKE_CASE :     Any=False				,       SCREAMING_SNAKE_CASE :     List[Any]=False				,       SCREAMING_SNAKE_CASE :     str=None				,       SCREAMING_SNAKE_CASE :     Dict=None				,       **SCREAMING_SNAKE_CASE :     List[Any]				,       ):
									# TODO: remove this once the Hub files are updated.
									lowercase__					:   int													=					kwargs.pop("text_config_dict"				,       SCREAMING_SNAKE_CASE					)
									lowercase__					:   int													=					kwargs.pop("vision_config_dict"				,       SCREAMING_SNAKE_CASE					)

									super().__init__(**SCREAMING_SNAKE_CASE					)
									lowercase__					:   Dict													=					share_cross_modal_transformer_layers
									lowercase__					:   int													=					hidden_act
									lowercase__					:   int													=					hidden_size
									lowercase__					:   Optional[int]													=					initializer_factor
									lowercase__					:   Optional[int]													=					layer_norm_eps
									lowercase__					:   str													=					share_link_tower_layers
									lowercase__					:   Optional[int]													=					link_tower_type
									lowercase__					:   List[Any]													=					num_attention_heads
									lowercase__					:   Dict													=					num_hidden_layers
									lowercase__					:   Dict													=					tie_word_embeddings
									lowercase__					:   Optional[Any]													=					init_layernorm_from_vision_encoder

									if text_config is None:
													lowercase__					:   Optional[Any]													=					{}
													logger.info("`text_config` is `None`. Initializing the `BridgeTowerTextConfig` with default values."					)

									if vision_config is None:
													lowercase__					:   List[Any]													=					{}
													logger.info("`vision_config` is `None`. Initializing the `BridgeTowerVisionConfig` with default values."					)

									lowercase__					:   Any													=					BridgeTowerTextConfig(**SCREAMING_SNAKE_CASE					)
									lowercase__					:   Dict													=					BridgeTowerVisionConfig(**SCREAMING_SNAKE_CASE					)







					@classmethod
					def 			snake_case					(							cls :     Optional[int]				,       SCREAMING_SNAKE_CASE :     BridgeTowerTextConfig				,       SCREAMING_SNAKE_CASE :     BridgeTowerVisionConfig				,       **SCREAMING_SNAKE_CASE :     List[str]					):
									return cls(text_config=text_config.to_dict()				,       vision_config=vision_config.to_dict()				,       **SCREAMING_SNAKE_CASE					)







					def 			snake_case					(							self :     Optional[int]					):
									lowercase__					:   List[str]													=					copy.deepcopy(self.__dict__					)
									lowercase__					:   Dict													=					self.text_config.to_dict()
									lowercase__					:   Tuple													=					self.vision_config.to_dict()
									lowercase__					:   Optional[Any]													=					self.__class__.model_type
									return output




