





import argparse
import collections
import os
import re

from transformers.utils import direct_transformers_import


# All paths are set with the intent you should run this script from the root of the repo with the command
# python utils/check_table.py
snake_case_				=			'src/transformers'
snake_case_				=			'docs/source/en'
snake_case_				=			'.'






def lowerCamelCase__    (							snake_case_	:  List[str]       ,      snake_case_	:  List[str]       ,      snake_case_	:  Dict       )      ->				int:
   with open(snake_case_       ,      '''r'''       ,      encoding='''utf-8'''       ,      newline='''\n'''       ) as f:
      __snake_case							       =   f.readlines()
   # Find the start prompt.
   __snake_case							       =   0
   while not lines[start_index].startswith(snake_case_       ):
      start_index += 1
   start_index += 1

   __snake_case							       =   start_index
   while not lines[end_index].startswith(snake_case_       ):
      end_index += 1
   end_index -= 1

   while len(lines[start_index]       ) <= 1:
      start_index += 1
   while len(lines[end_index]       ) <= 1:
      end_index -= 1
   end_index += 1
   return "".join(lines[start_index:end_index]       ), start_index, end_index, lines


# Add here suffixes that are used to identify models, separated by |
snake_case_				=			'Model|Encoder|Decoder|ForConditionalGeneration'
# Regexes that match TF/Flax/PT model names.
snake_case_				=			re.compile(R'TF(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)')
snake_case_				=			re.compile(R'Flax(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)')
# Will match any TF or Flax model too so need to be in an else branch afterthe two previous regexes.
snake_case_				=			re.compile(R'(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)')


# This is to make sure the transformers module imported is the one in the repo.
snake_case_				=			direct_transformers_import(TRANSFORMERS_PATH)






def lowerCamelCase__    (							snake_case_	:  List[Any]       )      ->				Union[str, Any]:
   __snake_case							       =   re.finditer('''.+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)'''       ,      snake_case_       )
   return [m.group(0       ) for m in matches]






def lowerCamelCase__    (							snake_case_	:  Union[str, Any]       ,      snake_case_	:  Tuple       )      ->				Optional[Any]:
   __snake_case							       =   2 if text == '''✅''' or text == '''❌''' else len(snake_case_       )
   __snake_case							       =   (width - text_length) // 2
   __snake_case							       =   width - text_length - left_indent
   return " " * left_indent + text + " " * right_indent






def lowerCamelCase__    (							)      ->				List[str]:
   __snake_case							       =   transformers_module.models.auto.configuration_auto.CONFIG_MAPPING_NAMES
   __snake_case							       =   {
       name: config_maping_names[code]
       for code, name in transformers_module.MODEL_NAMES_MAPPING.items()
       if code in config_maping_names
   }
   __snake_case							       =   {name: config.replace('''Config'''       ,      ''''''       ) for name, config in model_name_to_config.items()}

   # Dictionaries flagging if each model prefix has a slow/fast tokenizer, backend in PT/TF/Flax.
   __snake_case							       =   collections.defaultdict(snake_case_       )
   __snake_case							       =   collections.defaultdict(snake_case_       )
   __snake_case							       =   collections.defaultdict(snake_case_       )
   __snake_case							       =   collections.defaultdict(snake_case_       )
   __snake_case							       =   collections.defaultdict(snake_case_       )

   # Let's lookup through all transformers object (once).
   for attr_name in dir(snake_case_       ):
      __snake_case							       =   None
      if attr_name.endswith('''Tokenizer'''       ):
         __snake_case							       =   slow_tokenizers
         __snake_case							       =   attr_name[:-9]
      elif attr_name.endswith('''TokenizerFast'''       ):
         __snake_case							       =   fast_tokenizers
         __snake_case							       =   attr_name[:-13]
      elif _re_tf_models.match(snake_case_       ) is not None:
         __snake_case							       =   tf_models
         __snake_case							       =   _re_tf_models.match(snake_case_       ).groups()[0]
      elif _re_flax_models.match(snake_case_       ) is not None:
         __snake_case							       =   flax_models
         __snake_case							       =   _re_flax_models.match(snake_case_       ).groups()[0]
      elif _re_pt_models.match(snake_case_       ) is not None:
         __snake_case							       =   pt_models
         __snake_case							       =   _re_pt_models.match(snake_case_       ).groups()[0]

      if lookup_dict is not None:
         while len(snake_case_       ) > 0:
            if attr_name in model_name_to_prefix.values():
               __snake_case							       =   True
               break
            # Try again after removing the last word in the name
            __snake_case							       =   ''''''.join(camel_case_split(snake_case_       )[:-1]       )

    # Let's build that table!
   __snake_case							       =   list(model_name_to_config.keys()       )
   model_names.sort(key=str.lower       )
   __snake_case							       =   ['''Model''', '''Tokenizer slow''', '''Tokenizer fast''', '''PyTorch support''', '''TensorFlow support''', '''Flax Support''']
   # We'll need widths to properly display everything in the center (+2 is to leave one extra space on each side).
   __snake_case							       =   [len(snake_case_       ) + 2 for c in columns]
   __snake_case							       =   max([len(snake_case_       ) for name in model_names]       ) + 2

   # Build the table per se
   __snake_case							       =   '''|''' + '''|'''.join([_center_text(snake_case_       ,      snake_case_       ) for c, w in zip(snake_case_       ,      snake_case_       )]       ) + '''|\n'''
   # Use ":-----:" format to center-aligned table cell texts
   table += "|" + "|".join([''':''' + '''-''' * (w - 2) + ''':''' for w in widths]       ) + "|\n"

   __snake_case							       =   {True: '''✅''', False: '''❌'''}
   for name in model_names:
      __snake_case							       =   model_name_to_prefix[name]
      __snake_case							       =   [
          name,
          check[slow_tokenizers[prefix]],
          check[fast_tokenizers[prefix]],
          check[pt_models[prefix]],
          check[tf_models[prefix]],
          check[flax_models[prefix]],
      ]
      table += "|" + "|".join([_center_text(snake_case_       ,      snake_case_       ) for l, w in zip(snake_case_       ,      snake_case_       )]       ) + "|\n"
   return table






def lowerCamelCase__    (							snake_case_	:  List[str]=False       )      ->				Optional[int]:
   __snake_case       ,	__snake_case       ,	__snake_case       ,	__snake_case							       =   _find_text_in_file(
       filename=os.path.join(snake_case_       ,      '''index.md'''       )       ,      start_prompt='''<!--This table is updated automatically from the auto modules'''       ,      end_prompt='''<!-- End table-->'''       ,      )
   __snake_case							       =   get_model_table_from_auto_modules()

   if current_table != new_table:
      if overwrite:
         with open(os.path.join(snake_case_       ,      '''index.md'''       )       ,      '''w'''       ,      encoding='''utf-8'''       ,      newline='''\n'''       ) as f:
            f.writelines(lines[:start_index] + [new_table] + lines[end_index:]       )
      else:
         raise ValueError(
             '''The model table in the `index.md` has not been updated. Run `make fix-copies` to fix this.'''       )


if __name__ == "__main__":
    snake_case_				=			argparse.ArgumentParser()
    parser.add_argument('--fix_and_overwrite', action='store_true', help='Whether to fix inconsistencies.')
    snake_case_				=			parser.parse_args()

    check_model_table(args.fix_and_overwrite)







import argparse
import glob
import logging
import os
import time
from argparse import Namespace

import numpy as np
import torch
from lightning_base import BaseTransformer, add_generic_args, generic_train
from torch.utils.data import DataLoader, TensorDataset

from transformers import glue_compute_metrics as compute_metrics
from transformers import glue_convert_examples_to_features as convert_examples_to_features
from transformers import glue_output_modes, glue_tasks_num_labels
from transformers import glue_processors as processors


SCREAMING_SNAKE_CASE__       :      Dict  =   logging.getLogger(__name__)




class 		UpperCamelCase__	(lowerCAmelCase__     ):

    '''simple docstring'''



    lowerCamelCase_      :	Optional[int]	     =      """sequence-classification"""







    def __init__(    self     ,  UpperCamelCase__     )     ->      List[Any]:
           if type(UpperCamelCase__     ) == dict:
                  lowerCamelCase   :      int			 =					Namespace(**UpperCamelCase__     )
           lowerCamelCase   :      str			 =					glue_output_modes[hparams.task]
           lowerCamelCase   :      int			 =					glue_tasks_num_labels[hparams.task]

           super().__init__(UpperCamelCase__     ,  UpperCamelCase__     ,  self.mode     )







    def     _lowercase     (    self     ,  **UpperCamelCase__     )     ->      Tuple:
           return self.model(**UpperCamelCase__     )







    def     _lowercase     (    self     ,  UpperCamelCase__     ,  UpperCamelCase__     )     ->      Tuple:
           lowerCamelCase   :      Union[str, Any]			 =					{"input_ids": batch[0], "attention_mask": batch[1], "labels": batch[3]}

           if self.config.model_type not in ["distilbert", "bart"]:
                  lowerCamelCase   :      List[str]			 =					batch[2] if self.config.model_type in ["bert", "xlnet", "albert"] else None

           lowerCamelCase   :      Optional[int]			 =					self(**UpperCamelCase__     )
           lowerCamelCase   :      Union[str, Any]			 =					outputs[0]

           lowerCamelCase   :      str			 =					self.trainer.lr_schedulers[0]["scheduler"]
           lowerCamelCase   :      Optional[int]			 =					{"loss": loss, "rate": lr_scheduler.get_last_lr()[-1]}
           return {"loss": loss, "log": tensorboard_logs}







    def     _lowercase     (    self     )     ->      str:
           lowerCamelCase   :      Any			 =					self.hparams
           lowerCamelCase   :      Union[str, Any]			 =					processors[args.task]()
           lowerCamelCase   :      Optional[int]			 =					processor.get_labels()

           for mode in ["train", "dev"]:
                  lowerCamelCase   :      Optional[Any]			 =					self._feature_file(UpperCamelCase__     )
                  if os.path.exists(UpperCamelCase__     ) and not args.overwrite_cache:
                         logger.info("Loading features from cached file %s"     ,  UpperCamelCase__     )
                  else:
                         logger.info("Creating features from dataset file at %s"     ,  args.data_dir     )
                         lowerCamelCase   :      List[str]			 =					(
                             processor.get_dev_examples(args.data_dir     )
                             if mode == "dev"
                             else processor.get_train_examples(args.data_dir     )
                         )
                         lowerCamelCase   :      Dict			 =					convert_examples_to_features(
                             UpperCamelCase__     ,  self.tokenizer     ,  max_length=args.max_seq_length     ,  label_list=self.labels     ,  output_mode=args.glue_output_mode     ,  )
                         logger.info("Saving features into cached file %s"     ,  UpperCamelCase__     )
                         torch.save(UpperCamelCase__     ,  UpperCamelCase__     )







    def     _lowercase     (    self     ,  UpperCamelCase__     ,  UpperCamelCase__     ,  UpperCamelCase__ = False     )     ->      DataLoader:
           lowerCamelCase   :      str			 =					"dev" if mode == "test" else mode

           lowerCamelCase   :      int			 =					self._feature_file(UpperCamelCase__     )
           logger.info("Loading features from cached file %s"     ,  UpperCamelCase__     )
           lowerCamelCase   :      str			 =					torch.load(UpperCamelCase__     )
           lowerCamelCase   :      List[str]			 =					torch.tensor([f.input_ids for f in features]     ,  dtype=torch.long     )
           lowerCamelCase   :      str			 =					torch.tensor([f.attention_mask for f in features]     ,  dtype=torch.long     )
           lowerCamelCase   :      List[str]			 =					torch.tensor([f.token_type_ids for f in features]     ,  dtype=torch.long     )
           if self.hparams.glue_output_mode == "classification":
                  lowerCamelCase   :      Any			 =					torch.tensor([f.label for f in features]     ,  dtype=torch.long     )
           elif self.hparams.glue_output_mode == "regression":
                  lowerCamelCase   :      Union[str, Any]			 =					torch.tensor([f.label for f in features]     ,  dtype=torch.float     )

           return DataLoader(
               TensorDataset(UpperCamelCase__     ,  UpperCamelCase__     ,  UpperCamelCase__     ,  UpperCamelCase__     )     ,  batch_size=UpperCamelCase__     ,  shuffle=UpperCamelCase__     ,  )







    def     _lowercase     (    self     ,  UpperCamelCase__     ,  UpperCamelCase__     )     ->      List[Any]:
           lowerCamelCase   :      Dict			 =					{"input_ids": batch[0], "attention_mask": batch[1], "labels": batch[3]}

           if self.config.model_type not in ["distilbert", "bart"]:
                  lowerCamelCase   :      Tuple			 =					batch[2] if self.config.model_type in ["bert", "xlnet", "albert"] else None

           lowerCamelCase   :      Dict			 =					self(**UpperCamelCase__     )
           lowerCamelCase ,      lowerCamelCase   :      Any			 =					outputs[:2]
           lowerCamelCase   :      Union[str, Any]			 =					logits.detach().cpu().numpy()
           lowerCamelCase   :      Optional[Any]			 =					inputs["labels"].detach().cpu().numpy()

           return {"val_loss": tmp_eval_loss.detach().cpu(), "pred": preds, "target": out_label_ids}







    def     _lowercase     (    self     ,  UpperCamelCase__     )     ->      tuple:
           lowerCamelCase   :      Union[str, Any]			 =					torch.stack([x["val_loss"] for x in outputs]     ).mean().detach().cpu().item()
           lowerCamelCase   :      Optional[int]			 =					np.concatenate([x["pred"] for x in outputs]     ,  axis=0     )

           if self.hparams.glue_output_mode == "classification":
                  lowerCamelCase   :      Union[str, Any]			 =					np.argmax(UpperCamelCase__     ,  axis=1     )
           elif self.hparams.glue_output_mode == "regression":
                  lowerCamelCase   :      str			 =					np.squeeze(UpperCamelCase__     )

           lowerCamelCase   :      List[Any]			 =					np.concatenate([x["target"] for x in outputs]     ,  axis=0     )
           lowerCamelCase   :      List[str]			 =					[[] for _ in range(out_label_ids.shape[0]     )]
           lowerCamelCase   :      Optional[int]			 =					[[] for _ in range(out_label_ids.shape[0]     )]

           lowerCamelCase   :      Dict			 =					{**{"val_loss": val_loss_mean}, **compute_metrics(self.hparams.task     ,  UpperCamelCase__     ,  UpperCamelCase__     )}

           lowerCamelCase   :      List[str]			 =					dict(results.items()     )
           lowerCamelCase   :      Optional[int]			 =					results
           return ret, preds_list, out_label_list







    def     _lowercase     (    self     ,  UpperCamelCase__     )     ->      dict:
           lowerCamelCase ,      lowerCamelCase ,      lowerCamelCase   :      Union[str, Any]			 =					self._eval_end(UpperCamelCase__     )
           lowerCamelCase   :      str			 =					ret["log"]
           return {"val_loss": logs["val_loss"], "log": logs, "progress_bar": logs}







    def     _lowercase     (    self     ,  UpperCamelCase__     )     ->      dict:
           lowerCamelCase ,      lowerCamelCase ,      lowerCamelCase   :      str			 =					self._eval_end(UpperCamelCase__     )
           lowerCamelCase   :      str			 =					ret["log"]
           # `val_loss` is the key returned by `self._eval_end()` but actually refers to `test_loss`
           return {"avg_test_loss": logs["val_loss"], "log": logs, "progress_bar": logs}







    @staticmethod
    def     _lowercase     (    UpperCamelCase__     ,  UpperCamelCase__     )     ->      int:
           BaseTransformer.add_model_specific_args(UpperCamelCase__     ,  UpperCamelCase__     )
           parser.add_argument(
               "--max_seq_length"     ,  default=128     ,  type=UpperCamelCase__     ,  help=(
                   "The maximum total input sequence length after tokenization. Sequences longer "
                   "than this will be truncated, sequences shorter will be padded."
               )     ,  )

           parser.add_argument(
               "--task"     ,  default=""     ,  type=UpperCamelCase__     ,  required=UpperCamelCase__     ,  help="The GLUE task to run"     ,  )
           parser.add_argument(
               "--gpus"     ,  default=0     ,  type=UpperCamelCase__     ,  help="The number of GPUs allocated for this, it is by default 0 meaning none"     ,  )

           parser.add_argument(
               "--overwrite_cache"     ,  action="store_true"     ,  help="Overwrite the cached training and evaluation sets"     )

           return parser




def      A      (      )	-> int:
       lowerCamelCase   :      int			 =					argparse.ArgumentParser()
       add_generic_args(_SCREAMING_SNAKE_CASE ,os.getcwd()    )
       lowerCamelCase   :      str			 =					GLUETransformer.add_model_specific_args(_SCREAMING_SNAKE_CASE ,os.getcwd()    )
       lowerCamelCase   :      str			 =					parser.parse_args()

       # If output_dir not provided, a folder will be generated in pwd
       if args.output_dir is None:
              lowerCamelCase   :      int			 =					os.path.join(
                  "./results" ,f'''{args.task}_{time.strftime("%Y%m%d_%H%M%S"    )}''' ,)
              os.makedirs(args.output_dir    )

       lowerCamelCase   :      int			 =					GLUETransformer(_SCREAMING_SNAKE_CASE    )
       lowerCamelCase   :      Dict			 =					generic_train(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE    )

       # Optionally, predict on dev set and write to output_dir
       if args.do_predict:
              lowerCamelCase   :      Optional[int]			 =					sorted(glob.glob(os.path.join(args.output_dir ,"checkpoint-epoch=*.ckpt"    ) ,recursive=_SCREAMING_SNAKE_CASE    )    )
              lowerCamelCase   :      Tuple			 =					model.load_from_checkpoint(checkpoints[-1]    )
              return trainer.test(_SCREAMING_SNAKE_CASE    )


if __name__ == "__main__":
       main()






