


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


A      = logging.getLogger(__name__)


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


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




@dataclass
class     lowercase__  :
  A__=  field(
      default=_lowerCAmelCase					,							metadata={'help': 'The input training data file (a text file).'}		)
  A__=  field(
      default=_lowerCAmelCase					,							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'
          )
      }					,							)
  A__=  field(
      default=_lowerCAmelCase					,							metadata={'help': 'An optional input evaluation data file to evaluate the perplexity on (a text file).'}					,							)
  A__=  field(
      default=_lowerCAmelCase					,							metadata={'help': 'An optional input train ref data file for whole word mask in Chinese.'}					,							)
  A__=  field(
      default=_lowerCAmelCase					,							metadata={'help': 'An optional input eval ref data file for whole word mask in Chinese.'}					,							)
  A__=  field(
      default=_lowerCAmelCase					,							metadata={'help': 'Whether distinct lines of text in the dataset are to be handled as distinct sequences.'}					,							)

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

  A__=  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).'
          )
      }					,							)
  A__=  field(
      default=_lowerCAmelCase					,							metadata={'help': 'Overwrite the cached training and evaluation sets'}		)





def __UpperCAmelCase       (		__A ,						__A ,						__A = False ,						__A = None ,						)						->					List[str]:



       '''simple docstring'''





       def _dataset(__A ,						__A=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 __UpperCAmelCase       (		)						->					Optional[Any]:



       '''simple docstring'''





       UpperCAmelCase__										=     HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)			)
       UpperCAmelCase__						,			UpperCAmelCase__						,			UpperCAmelCase__										=     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:
              UpperCAmelCase__										=     AutoConfig.from_pretrained(model_args.config_name ,						cache_dir=model_args.cache_dir			)
       elif model_args.model_name_or_path:
              UpperCAmelCase__										=     AutoConfig.from_pretrained(model_args.model_name_or_path ,						cache_dir=model_args.cache_dir			)
       else:
              UpperCAmelCase__										=     CONFIG_MAPPING[model_args.model_type]()
              logger.warning("You are instantiating a new config instance from scratch."			)

       if model_args.tokenizer_name:
              UpperCAmelCase__										=     AutoTokenizer.from_pretrained(model_args.tokenizer_name ,						cache_dir=model_args.cache_dir			)
       elif model_args.model_name_or_path:
              UpperCAmelCase__										=     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:
              UpperCAmelCase__										=     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"			)
              UpperCAmelCase__										=     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:
              UpperCAmelCase__										=     tokenizer.max_len
              # Our input block size will be the max possible for the model
       else:
              UpperCAmelCase__										=     min(data_args.block_size ,						tokenizer.max_len			)

       # Get datasets

       UpperCAmelCase__										=     (
           get_dataset(__A ,						tokenizer=__A ,						cache_dir=model_args.cache_dir			) if training_args.do_train else None
       )
       UpperCAmelCase__										=     (
           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":
              UpperCAmelCase__										=     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:
                     UpperCAmelCase__										=     DataCollatorForWholeWordMask(
                         tokenizer=__A ,						mlm_probability=data_args.mlm_probability			)
              else:
                     UpperCAmelCase__										=     DataCollatorForLanguageModeling(
                         tokenizer=__A ,						mlm=data_args.mlm ,						mlm_probability=data_args.mlm_probability			)

    # Initialize our Trainer
       UpperCAmelCase__										=     Trainer(
           model=__A ,						args=__A ,						data_collator=__A ,						train_dataset=__A ,						eval_dataset=__A ,						prediction_loss_only=__A ,						)

       # Training
       if training_args.do_train:
              UpperCAmelCase__										=     (
                  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
       UpperCAmelCase__										=     {}
       if training_args.do_eval:
              logger.info("*** Evaluate ***"			)

              UpperCAmelCase__										=     trainer.evaluate()

              UpperCAmelCase__										=     math.exp(eval_output["eval_loss"]			)
              UpperCAmelCase__										=     {"perplexity": perplexity}

              UpperCAmelCase__										=     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 __UpperCAmelCase       (		__A			)						->					Optional[int]:



       '''simple docstring'''





       main()


if __name__ == "__main__":
   main()









from copy import deepcopy
from typing import Optional, Union

import numpy as np

from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding
from ...utils import TensorType, is_tf_available, is_torch_available


if is_torch_available():
    import torch

if is_tf_available():
    import tensorflow as tf


class     lowercase__  (					__SCREAMING_SNAKE_CASE		):
  A__=  ['image_processor']
  A__=  'SamImageProcessor'






  def __init__(					self      :					int		,						_lowercase      :					List[Any] ):




         """simple docstring"""







         super().__init__(_lowercase )
         UpperCAmelCase__										=     self.image_processor
         UpperCAmelCase__										=     -10
         UpperCAmelCase__										=     self.image_processor.size["longest_edge"]






  def __call__(					self      :					Union[str, Any]		,						_lowercase      :					str=None		,						_lowercase      :					Union[str, Any]=None		,						_lowercase      :					List[Any]=None		,						_lowercase      :					Dict=None		,						_lowercase      :					Optional[Union[str, TensorType]] = None		,						**_lowercase      :					Union[str, Any]		,						):




         """simple docstring"""







         UpperCAmelCase__										=     self.image_processor(
             _lowercase		,						return_tensors=_lowercase		,						**_lowercase		,						)

         # pop arguments that are not used in the foward but used nevertheless
         UpperCAmelCase__										=     encoding_image_processor["original_sizes"]

         if hasattr(_lowercase		,						"numpy" ):  # Checks if Torch or TF tensor
                UpperCAmelCase__										=     original_sizes.numpy()

         UpperCAmelCase__						,			UpperCAmelCase__						,			UpperCAmelCase__										=     self._check_and_preprocess_points(
             input_points=_lowercase		,						input_labels=_lowercase		,						input_boxes=_lowercase		,						)

         UpperCAmelCase__										=     self._normalize_and_convert(
             _lowercase		,						_lowercase		,						input_points=_lowercase		,						input_labels=_lowercase		,						input_boxes=_lowercase		,						return_tensors=_lowercase		,						)

         return encoding_image_processor






  def 			_UpperCAmelCase  (					self      :					Dict		,						_lowercase      :					int		,						_lowercase      :					Dict		,						_lowercase      :					Optional[Any]=None		,						_lowercase      :					Any=None		,						_lowercase      :					Union[str, Any]=None		,						_lowercase      :					List[Any]="pt"		,						):




         """simple docstring"""







         if input_points is not None:
                if len(_lowercase ) != len(_lowercase ):
                       UpperCAmelCase__										=     [
                           self._normalize_coordinates(self.target_size		,						_lowercase		,						original_sizes[0] ) for point in input_points
                       ]
                else:
                       UpperCAmelCase__										=     [
                           self._normalize_coordinates(self.target_size		,						_lowercase		,						_lowercase )
                           for point, original_size in zip(_lowercase		,						_lowercase )
                       ]
                # check that all arrays have the same shape
                if not all(point.shape == input_points[0].shape for point in input_points ):
                       if input_labels is not None:
                              UpperCAmelCase__						,			UpperCAmelCase__										=     self._pad_points_and_labels(_lowercase		,						_lowercase )

                UpperCAmelCase__										=     np.array(_lowercase )

         if input_labels is not None:
                UpperCAmelCase__										=     np.array(_lowercase )

         if input_boxes is not None:
                if len(_lowercase ) != len(_lowercase ):
                       UpperCAmelCase__										=     [
                           self._normalize_coordinates(self.target_size		,						_lowercase		,						original_sizes[0]		,						is_bounding_box=_lowercase )
                           for box in input_boxes
                       ]
                else:
                       UpperCAmelCase__										=     [
                           self._normalize_coordinates(self.target_size		,						_lowercase		,						_lowercase		,						is_bounding_box=_lowercase )
                           for box, original_size in zip(_lowercase		,						_lowercase )
                       ]
                UpperCAmelCase__										=     np.array(_lowercase )

         if input_boxes is not None:
                if return_tensors == "pt":
                       UpperCAmelCase__										=     torch.from_numpy(_lowercase )
                       # boxes batch size of 1 by default
                       UpperCAmelCase__										=     input_boxes.unsqueeze(1 ) if len(input_boxes.shape ) != 3 else input_boxes
                elif return_tensors == "tf":
                       UpperCAmelCase__										=     tf.convert_to_tensor(_lowercase )
                       # boxes batch size of 1 by default
                       UpperCAmelCase__										=     tf.expand_dims(_lowercase		,						1 ) if len(input_boxes.shape ) != 3 else input_boxes
                encoding_image_processor.update({"input_boxes": input_boxes} )
         if input_points is not None:
                if return_tensors == "pt":
                       UpperCAmelCase__										=     torch.from_numpy(_lowercase )
                       # point batch size of 1 by default
                       UpperCAmelCase__										=     input_points.unsqueeze(1 ) if len(input_points.shape ) != 4 else input_points
                elif return_tensors == "tf":
                       UpperCAmelCase__										=     tf.convert_to_tensor(_lowercase )
                       # point batch size of 1 by default
                       UpperCAmelCase__										=     tf.expand_dims(_lowercase		,						1 ) if len(input_points.shape ) != 4 else input_points
                encoding_image_processor.update({"input_points": input_points} )
         if input_labels is not None:
                if return_tensors == "pt":
                       UpperCAmelCase__										=     torch.from_numpy(_lowercase )
                       # point batch size of 1 by default
                       UpperCAmelCase__										=     input_labels.unsqueeze(1 ) if len(input_labels.shape ) != 3 else input_labels
                elif return_tensors == "tf":
                       UpperCAmelCase__										=     tf.convert_to_tensor(_lowercase )
                       # point batch size of 1 by default
                       UpperCAmelCase__										=     tf.expand_dims(_lowercase		,						1 ) if len(input_labels.shape ) != 3 else input_labels
                encoding_image_processor.update({"input_labels": input_labels} )

         return encoding_image_processor






  def 			_UpperCAmelCase  (					self      :					Union[str, Any]		,						_lowercase      :					Any		,						_lowercase      :					Optional[Any] ):




         """simple docstring"""







         UpperCAmelCase__										=     max([point.shape[0] for point in input_points] )
         UpperCAmelCase__										=     []
         for i, point in enumerate(_lowercase ):
                if point.shape[0] != expected_nb_points:
                       UpperCAmelCase__										=     np.concatenate(
                           [point, np.zeros((expected_nb_points - point.shape[0], 2) ) + self.point_pad_value]		,						axis=0 )
                       UpperCAmelCase__										=     np.append(input_labels[i]		,						[self.point_pad_value] )
                processed_input_points.append(_lowercase )
         UpperCAmelCase__										=     processed_input_points
         return input_points, input_labels






  def 			_UpperCAmelCase  (					self      :					Any		,						_lowercase      :					int		,						_lowercase      :					np.ndarray		,						_lowercase      :					Optional[Any]		,						_lowercase      :					Any=False ):




         """simple docstring"""







         UpperCAmelCase__						,			UpperCAmelCase__										=     original_size
         UpperCAmelCase__						,			UpperCAmelCase__										=     self.image_processor._get_preprocess_shape(_lowercase		,						longest_edge=_lowercase )
         UpperCAmelCase__										=     deepcopy(_lowercase ).astype(_lowercase )

         if is_bounding_box:
                UpperCAmelCase__										=     coords.reshape(-1		,						2		,						2 )

         UpperCAmelCase__										=     coords[..., 0] * (new_w / old_w)
         UpperCAmelCase__										=     coords[..., 1] * (new_h / old_h)

         if is_bounding_box:
                UpperCAmelCase__										=     coords.reshape(-1		,						4 )

         return coords






  def 			_UpperCAmelCase  (					self      :					int		,						_lowercase      :					Tuple=None		,						_lowercase      :					Optional[Any]=None		,						_lowercase      :					List[Any]=None		,						):




         """simple docstring"""







         if input_points is not None:
                if hasattr(_lowercase		,						"numpy" ):  # Checks for TF or Torch tensor
                       UpperCAmelCase__										=     input_points.numpy().tolist()

                if not isinstance(_lowercase		,						_lowercase ) or not isinstance(input_points[0]		,						_lowercase ):
                       raise ValueError("Input points must be a list of list of floating points." )
                UpperCAmelCase__										=     [np.array(_lowercase ) for input_point in input_points]
         else:
                UpperCAmelCase__										=     None

         if input_labels is not None:
                if hasattr(_lowercase		,						"numpy" ):
                       UpperCAmelCase__										=     input_labels.numpy().tolist()

                if not isinstance(_lowercase		,						_lowercase ) or not isinstance(input_labels[0]		,						_lowercase ):
                       raise ValueError("Input labels must be a list of list integers." )
                UpperCAmelCase__										=     [np.array(_lowercase ) for label in input_labels]
         else:
                UpperCAmelCase__										=     None

         if input_boxes is not None:
                if hasattr(_lowercase		,						"numpy" ):
                       UpperCAmelCase__										=     input_boxes.numpy().tolist()

                if (
                    not isinstance(_lowercase		,						_lowercase )
                    or not isinstance(input_boxes[0]		,						_lowercase )
                    or not isinstance(input_boxes[0][0]		,						_lowercase )
                ):
                       raise ValueError("Input boxes must be a list of list of list of floating points." )
                UpperCAmelCase__										=     [np.array(_lowercase ).astype(np.floataa ) for box in input_boxes]
         else:
                UpperCAmelCase__										=     None

         return input_points, input_labels, input_boxes






  @property
  def 			_UpperCAmelCase  (					self      :					Optional[Any] ):




         """simple docstring"""







         UpperCAmelCase__										=     self.image_processor.model_input_names
         return list(dict.fromkeys(_lowercase ) )






  def 			_UpperCAmelCase  (					self      :					int		,						*_lowercase      :					List[str]		,						**_lowercase      :					Any ):




         """simple docstring"""







         return self.image_processor.post_process_masks(*_lowercase		,						**_lowercase )





