




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()












import os
import unicodedata
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple

import sentencepiece as spm

from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...utils import SPIECE_UNDERLINE, logging


SCREAMING_SNAKE_CASE__       :      Optional[Any]  =   logging.get_logger(__name__)

SCREAMING_SNAKE_CASE__       :      Tuple  =   {'vocab_file': 'spiece.model'}

SCREAMING_SNAKE_CASE__       :      int  =   {
    'vocab_file': {
        'xlnet-base-cased': 'https://huggingface.co/xlnet-base-cased/resolve/main/spiece.model',
        'xlnet-large-cased': 'https://huggingface.co/xlnet-large-cased/resolve/main/spiece.model',
    }
}

SCREAMING_SNAKE_CASE__       :      str  =   {
    'xlnet-base-cased': None,
    'xlnet-large-cased': None,
}

# Segments (not really needed)
SCREAMING_SNAKE_CASE__       :      Dict  =   0
SCREAMING_SNAKE_CASE__       :      Tuple  =   1
SCREAMING_SNAKE_CASE__       :      Optional[int]  =   2
SCREAMING_SNAKE_CASE__       :      List[str]  =   3
SCREAMING_SNAKE_CASE__       :      Optional[int]  =   4




class 		UpperCamelCase__	(lowerCAmelCase__     ):

    '''simple docstring'''



    lowerCamelCase_      :	Dict	     =      VOCAB_FILES_NAMES
    lowerCamelCase_      :	Optional[Any]	     =      PRETRAINED_VOCAB_FILES_MAP
    lowerCamelCase_      :	Optional[int]	     =      PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
    lowerCamelCase_      :	List[str]	     =      """left"""







    def __init__(    self     ,  UpperCamelCase__     ,  UpperCamelCase__=False     ,  UpperCamelCase__=True     ,  UpperCamelCase__=False     ,  UpperCamelCase__="<s>"     ,  UpperCamelCase__="</s>"     ,  UpperCamelCase__="<unk>"     ,  UpperCamelCase__="<sep>"     ,  UpperCamelCase__="<pad>"     ,  UpperCamelCase__="<cls>"     ,  UpperCamelCase__="<mask>"     ,  UpperCamelCase__=["<eop>", "<eod>"]     ,  UpperCamelCase__ = None     ,  **UpperCamelCase__     ,  )     ->      None:
           # Mask token behave like a normal word, i.e. include the space before it
           lowerCamelCase   :      str			 =					AddedToken(UpperCamelCase__     ,  lstrip=UpperCamelCase__     ,  rstrip=UpperCamelCase__     ) if isinstance(UpperCamelCase__     ,  UpperCamelCase__     ) else mask_token

           lowerCamelCase   :      Dict			 =					{} if sp_model_kwargs is None else sp_model_kwargs

           super().__init__(
               do_lower_case=UpperCamelCase__     ,  remove_space=UpperCamelCase__     ,  keep_accents=UpperCamelCase__     ,  bos_token=UpperCamelCase__     ,  eos_token=UpperCamelCase__     ,  unk_token=UpperCamelCase__     ,  sep_token=UpperCamelCase__     ,  pad_token=UpperCamelCase__     ,  cls_token=UpperCamelCase__     ,  mask_token=UpperCamelCase__     ,  additional_special_tokens=UpperCamelCase__     ,  sp_model_kwargs=self.sp_model_kwargs     ,  **UpperCamelCase__     ,  )

           lowerCamelCase   :      Any			 =					3

           lowerCamelCase   :      Optional[Any]			 =					do_lower_case
           lowerCamelCase   :      List[Any]			 =					remove_space
           lowerCamelCase   :      str			 =					keep_accents
           lowerCamelCase   :      List[Any]			 =					vocab_file

           lowerCamelCase   :      int			 =					spm.SentencePieceProcessor(**self.sp_model_kwargs     )
           self.sp_model.Load(UpperCamelCase__     )







    @property
    def     _lowercase     (    self     )     ->      Optional[Any]:
           return len(self.sp_model     )







    def     _lowercase     (    self     )     ->      Optional[int]:
           lowerCamelCase   :      int			 =					{self.convert_ids_to_tokens(UpperCamelCase__     ): i for i in range(self.vocab_size     )}
           vocab.update(self.added_tokens_encoder     )
           return vocab







    def __getstate__(    self     )     ->      Optional[Any]:
           lowerCamelCase   :      Optional[int]			 =					self.__dict__.copy()
           lowerCamelCase   :      Union[str, Any]			 =					None
           return state







    def __setstate__(    self     ,  UpperCamelCase__     )     ->      int:
           lowerCamelCase   :      int			 =					d

           # for backward compatibility
           if not hasattr(self     ,  "sp_model_kwargs"     ):
                  lowerCamelCase   :      Any			 =					{}

           lowerCamelCase   :      Optional[int]			 =					spm.SentencePieceProcessor(**self.sp_model_kwargs     )
           self.sp_model.Load(self.vocab_file     )







    def     _lowercase     (    self     ,  UpperCamelCase__     )     ->      Any:
           if self.remove_space:
                  lowerCamelCase   :      Dict			 =					" ".join(inputs.strip().split()     )
           else:
                  lowerCamelCase   :      Union[str, Any]			 =					inputs
           lowerCamelCase   :      Optional[Any]			 =					outputs.replace("``"     ,  "\""     ).replace("''"     ,  "\""     )

           if not self.keep_accents:
                  lowerCamelCase   :      Optional[int]			 =					unicodedata.normalize("NFKD"     ,  UpperCamelCase__     )
                  lowerCamelCase   :      List[Any]			 =					"".join([c for c in outputs if not unicodedata.combining(UpperCamelCase__     )]     )
           if self.do_lower_case:
                  lowerCamelCase   :      List[str]			 =					outputs.lower()

           return outputs







    def     _lowercase     (    self     ,  UpperCamelCase__     )     ->      List[str]:
           lowerCamelCase   :      Optional[Any]			 =					self.preprocess_text(UpperCamelCase__     )
           lowerCamelCase   :      Dict			 =					self.sp_model.encode(UpperCamelCase__     ,  out_type=UpperCamelCase__     )
           lowerCamelCase   :      Dict			 =					[]
           for piece in pieces:
                  if len(UpperCamelCase__     ) > 1 and piece[-1] == str(","     ) and piece[-2].isdigit():
                         lowerCamelCase   :      List[Any]			 =					self.sp_model.EncodeAsPieces(piece[:-1].replace(UpperCamelCase__     ,  ""     )     )
                         if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE:
                                if len(cur_pieces[0]     ) == 1:
                                       lowerCamelCase   :      Union[str, Any]			 =					cur_pieces[1:]
                                else:
                                       lowerCamelCase   :      Optional[int]			 =					cur_pieces[0][1:]
                         cur_pieces.append(piece[-1]     )
                         new_pieces.extend(UpperCamelCase__     )
                  else:
                         new_pieces.append(UpperCamelCase__     )

           return new_pieces







    def     _lowercase     (    self     ,  UpperCamelCase__     )     ->      int:
           return self.sp_model.PieceToId(UpperCamelCase__     )







    def     _lowercase     (    self     ,  UpperCamelCase__     )     ->      Tuple:
           return self.sp_model.IdToPiece(UpperCamelCase__     )







    def     _lowercase     (    self     ,  UpperCamelCase__     )     ->      List[str]:
           lowerCamelCase   :      Union[str, Any]			 =					"".join(UpperCamelCase__     ).replace(UpperCamelCase__     ,  " "     ).strip()
           return out_string







    def     _lowercase     (    self     ,  UpperCamelCase__     ,  UpperCamelCase__ = False     ,  UpperCamelCase__ = None     ,  UpperCamelCase__ = True     ,  **UpperCamelCase__     ,  )     ->      str:
           lowerCamelCase   :      Optional[int]			 =					kwargs.pop("use_source_tokenizer"     ,  UpperCamelCase__     )

           lowerCamelCase   :      Optional[int]			 =					self.convert_ids_to_tokens(UpperCamelCase__     ,  skip_special_tokens=UpperCamelCase__     )

           # To avoid mixing byte-level and unicode for byte-level BPT
           # we need to build string separately for added tokens and byte-level tokens
           # cf. https://github.com/huggingface/transformers/issues/1133
           lowerCamelCase   :      Any			 =					[]
           lowerCamelCase   :      Any			 =					[]
           for token in filtered_tokens:
                  if skip_special_tokens and token in self.all_special_ids:
                         continue
                  if token in self.added_tokens_encoder:
                         if current_sub_text:
                                sub_texts.append(self.convert_tokens_to_string(UpperCamelCase__     )     )
                                lowerCamelCase   :      int			 =					[]
                         sub_texts.append(UpperCamelCase__     )
                  else:
                         current_sub_text.append(UpperCamelCase__     )
           if current_sub_text:
                  sub_texts.append(self.convert_tokens_to_string(UpperCamelCase__     )     )

           # Mimic the behavior of the Rust tokenizer:
           # By default, there are no spaces between special tokens
           lowerCamelCase   :      Union[str, Any]			 =					"".join(UpperCamelCase__     )

           lowerCamelCase   :      Tuple			 =					(
               clean_up_tokenization_spaces
               if clean_up_tokenization_spaces is not None
               else self.clean_up_tokenization_spaces
           )
           if clean_up_tokenization_spaces:
                  lowerCamelCase   :      int			 =					self.clean_up_tokenization(UpperCamelCase__     )
                  return clean_text
           else:
                  return text







    def     _lowercase     (    self     ,  UpperCamelCase__     ,  UpperCamelCase__ = None     )     ->      List[int]:
           lowerCamelCase   :      str			 =					[self.sep_token_id]
           lowerCamelCase   :      Optional[int]			 =					[self.cls_token_id]
           if token_ids_a is None:
                  return token_ids_a + sep + cls
           return token_ids_a + sep + token_ids_a + sep + cls







    def     _lowercase     (    self     ,  UpperCamelCase__     ,  UpperCamelCase__ = None     ,  UpperCamelCase__ = False     )     ->      List[int]:

           if already_has_special_tokens:
                  return super().get_special_tokens_mask(
                      token_ids_a=UpperCamelCase__     ,  token_ids_a=UpperCamelCase__     ,  already_has_special_tokens=UpperCamelCase__     )

           if token_ids_a is not None:
                  return ([0] * len(UpperCamelCase__     )) + [1] + ([0] * len(UpperCamelCase__     )) + [1, 1]
           return ([0] * len(UpperCamelCase__     )) + [1, 1]







    def     _lowercase     (    self     ,  UpperCamelCase__     ,  UpperCamelCase__ = None     )     ->      List[int]:
           lowerCamelCase   :      Any			 =					[self.sep_token_id]
           lowerCamelCase   :      List[str]			 =					[2]

           if token_ids_a is None:
                  return len(token_ids_a + sep     ) * [0] + cls_segment_id
           return len(token_ids_a + sep     ) * [0] + len(token_ids_a + sep     ) * [1] + cls_segment_id







    def     _lowercase     (    self     ,  UpperCamelCase__     ,  UpperCamelCase__ = None     )     ->      Tuple[str]:
           if not os.path.isdir(UpperCamelCase__     ):
                  logger.error(F'''Vocabulary path ({save_directory}) should be a directory'''     )
                  return
           lowerCamelCase   :      Union[str, Any]			 =					os.path.join(
               UpperCamelCase__     ,  (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]     )

           if os.path.abspath(self.vocab_file     ) != os.path.abspath(UpperCamelCase__     ) and os.path.isfile(self.vocab_file     ):
                  copyfile(self.vocab_file     ,  UpperCamelCase__     )
           elif not os.path.isfile(self.vocab_file     ):
                  with open(UpperCamelCase__     ,  "wb"     ) as fi:
                         lowerCamelCase   :      str			 =					self.sp_model.serialized_model_proto()
                         fi.write(UpperCamelCase__     )

           return (out_vocab_file,)






