




"""simple docstring"""



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    =	logging.getLogger(__name__)




class      UpperCAmelCase_  (						A_							):
    lowercase__						 =				'''sequence-classification'''




    def __init__(   self						:	str     ,			snake_case_						:	Any				)				->							Tuple:




     '''simple docstring'''

     if type(snake_case_				) == dict:
      A__	=    Namespace(**snake_case_				)
     A__	=    glue_output_modes[hparams.task]
     A__	=    glue_tasks_num_labels[hparams.task]

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




    def 							__magic_name__							(   self						:	List[str]     ,			**snake_case_						:	List[Any]				)				->							Any:




     '''simple docstring'''

     return self.model(**snake_case_				)




    def 							__magic_name__							(   self						:	List[str]     ,			snake_case_						:	Optional[int]     ,			snake_case_						:	Optional[Any]				)				->							Optional[int]:




     '''simple docstring'''

     A__	=    {"input_ids": batch[0], "attention_mask": batch[1], "labels": batch[3]}

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

     A__	=    self(**snake_case_				)
     A__	=    outputs[0]

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




    def 							__magic_name__							(   self						:	Any				)				->							Dict:




     '''simple docstring'''

     A__	=    self.hparams
     A__	=    processors[args.task]()
     A__	=    processor.get_labels()

     for mode in ["train", "dev"]:
      A__	=    self._feature_file(snake_case_				)
      if os.path.exists(snake_case_				) and not args.overwrite_cache:
       logger.info("Loading features from cached file %s"     ,			snake_case_				)
      else:
       logger.info("Creating features from dataset file at %s"     ,			args.data_dir				)
       A__	=    (
           processor.get_dev_examples(args.data_dir				)
           if mode == "dev"
           else processor.get_train_examples(args.data_dir				)
       )
       A__	=    convert_examples_to_features(
           snake_case_     ,			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"     ,			snake_case_				)
       torch.save(snake_case_     ,			snake_case_				)




    def 							__magic_name__							(   self						:	Dict     ,			snake_case_						:	str     ,			snake_case_						:	int     ,			snake_case_						:	bool = False				)				->							DataLoader:




     '''simple docstring'''

     A__	=    "dev" if mode == "test" else mode

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

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




    def 							__magic_name__							(   self						:	int     ,			snake_case_						:	int     ,			snake_case_						:	int				)				->							Optional[int]:




     '''simple docstring'''

     A__	=    {"input_ids": batch[0], "attention_mask": batch[1], "labels": batch[3]}

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

     A__	=    self(**snake_case_				)
     A__,				A__	=    outputs[:2]
     A__	=    logits.detach().cpu().numpy()
     A__	=    inputs["labels"].detach().cpu().numpy()

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




    def 							__magic_name__							(   self						:	Union[str, Any]     ,			snake_case_						:	List[Any]				)				->							tuple:




     '''simple docstring'''

     A__	=    torch.stack([x["val_loss"] for x in outputs]				).mean().detach().cpu().item()
     A__	=    np.concatenate([x["pred"] for x in outputs]     ,			axis=0				)

     if self.hparams.glue_output_mode == "classification":
      A__	=    np.argmax(snake_case_     ,			axis=1				)
     elif self.hparams.glue_output_mode == "regression":
      A__	=    np.squeeze(snake_case_				)

     A__	=    np.concatenate([x["target"] for x in outputs]     ,			axis=0				)
     A__	=    [[] for _ in range(out_label_ids.shape[0]				)]
     A__	=    [[] for _ in range(out_label_ids.shape[0]				)]

     A__	=    {**{"val_loss": val_loss_mean}, **compute_metrics(self.hparams.task     ,			snake_case_     ,			snake_case_				)}

     A__	=    dict(results.items()				)
     A__	=    results
     return ret, preds_list, out_label_list




    def 							__magic_name__							(   self						:	Dict     ,			snake_case_						:	list				)				->							dict:




     '''simple docstring'''

     A__,				A__,				A__	=    self._eval_end(snake_case_				)
     A__	=    ret["log"]
     return {"val_loss": logs["val_loss"], "log": logs, "progress_bar": logs}




    def 							__magic_name__							(   self						:	str     ,			snake_case_						:	str				)				->							dict:




     '''simple docstring'''

     A__,				A__,				A__	=    self._eval_end(snake_case_				)
     A__	=    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 							__magic_name__							(   snake_case_						:	Union[str, Any]     ,			snake_case_						:	Dict				)				->							Optional[Any]:




     '''simple docstring'''

     BaseTransformer.add_model_specific_args(snake_case_     ,			snake_case_				)
     parser.add_argument(
         "--max_seq_length"     ,			default=128     ,			type=snake_case_     ,			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=snake_case_     ,			required=snake_case_     ,			help="The GLUE task to run"     ,			)
     parser.add_argument(
         "--gpus"     ,			default=0     ,			type=snake_case_     ,			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   _SCREAMING_SNAKE_CASE       (							)						->		Optional[Any]:
 A__	=    argparse.ArgumentParser()
 add_generic_args(lowercase_      ,			os.getcwd()						)
 A__	=    GLUETransformer.add_model_specific_args(lowercase_      ,			os.getcwd()						)
 A__	=    parser.parse_args()

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

 A__	=    GLUETransformer(lowercase_						)
 A__	=    generic_train(lowercase_      ,			lowercase_						)

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


if __name__ == "__main__":
      main()











"""simple docstring"""



SCREAMING_SNAKE_CASE    =	[
    999,
    800,
    799,
    600,
    599,
    500,
    400,
    399,
    377,
    355,
    333,
    311,
    288,
    266,
    244,
    222,
    200,
    199,
    177,
    155,
    133,
    111,
    88,
    66,
    44,
    22,
    0,
]

SCREAMING_SNAKE_CASE    =	[
    999,
    976,
    952,
    928,
    905,
    882,
    858,
    857,
    810,
    762,
    715,
    714,
    572,
    429,
    428,
    286,
    285,
    238,
    190,
    143,
    142,
    118,
    95,
    71,
    47,
    24,
    0,
]

SCREAMING_SNAKE_CASE    =	[
    999,
    988,
    977,
    966,
    955,
    944,
    933,
    922,
    911,
    900,
    899,
    879,
    859,
    840,
    820,
    800,
    799,
    766,
    733,
    700,
    699,
    650,
    600,
    599,
    500,
    499,
    400,
    399,
    350,
    300,
    299,
    266,
    233,
    200,
    199,
    179,
    159,
    140,
    120,
    100,
    99,
    88,
    77,
    66,
    55,
    44,
    33,
    22,
    11,
    0,
]

SCREAMING_SNAKE_CASE    =	[
    999,
    995,
    992,
    989,
    985,
    981,
    978,
    975,
    971,
    967,
    964,
    961,
    957,
    956,
    951,
    947,
    942,
    937,
    933,
    928,
    923,
    919,
    914,
    913,
    908,
    903,
    897,
    892,
    887,
    881,
    876,
    871,
    870,
    864,
    858,
    852,
    846,
    840,
    834,
    828,
    827,
    820,
    813,
    806,
    799,
    792,
    785,
    784,
    777,
    770,
    763,
    756,
    749,
    742,
    741,
    733,
    724,
    716,
    707,
    699,
    698,
    688,
    677,
    666,
    656,
    655,
    645,
    634,
    623,
    613,
    612,
    598,
    584,
    570,
    569,
    555,
    541,
    527,
    526,
    505,
    484,
    483,
    462,
    440,
    439,
    396,
    395,
    352,
    351,
    308,
    307,
    264,
    263,
    220,
    219,
    176,
    132,
    88,
    44,
    0,
]

SCREAMING_SNAKE_CASE    =	[
    999,
    997,
    995,
    992,
    990,
    988,
    986,
    984,
    981,
    979,
    977,
    975,
    972,
    970,
    968,
    966,
    964,
    961,
    959,
    957,
    956,
    954,
    951,
    949,
    946,
    944,
    941,
    939,
    936,
    934,
    931,
    929,
    926,
    924,
    921,
    919,
    916,
    914,
    913,
    910,
    907,
    905,
    902,
    899,
    896,
    893,
    891,
    888,
    885,
    882,
    879,
    877,
    874,
    871,
    870,
    867,
    864,
    861,
    858,
    855,
    852,
    849,
    846,
    843,
    840,
    837,
    834,
    831,
    828,
    827,
    824,
    821,
    817,
    814,
    811,
    808,
    804,
    801,
    798,
    795,
    791,
    788,
    785,
    784,
    780,
    777,
    774,
    770,
    766,
    763,
    760,
    756,
    752,
    749,
    746,
    742,
    741,
    737,
    733,
    730,
    726,
    722,
    718,
    714,
    710,
    707,
    703,
    699,
    698,
    694,
    690,
    685,
    681,
    677,
    673,
    669,
    664,
    660,
    656,
    655,
    650,
    646,
    641,
    636,
    632,
    627,
    622,
    618,
    613,
    612,
    607,
    602,
    596,
    591,
    586,
    580,
    575,
    570,
    569,
    563,
    557,
    551,
    545,
    539,
    533,
    527,
    526,
    519,
    512,
    505,
    498,
    491,
    484,
    483,
    474,
    466,
    457,
    449,
    440,
    439,
    428,
    418,
    407,
    396,
    395,
    381,
    366,
    352,
    351,
    330,
    308,
    307,
    286,
    264,
    263,
    242,
    220,
    219,
    176,
    175,
    132,
    131,
    88,
    44,
    0,
]

SCREAMING_SNAKE_CASE    =	[
    999,
    991,
    982,
    974,
    966,
    958,
    950,
    941,
    933,
    925,
    916,
    908,
    900,
    899,
    874,
    850,
    825,
    800,
    799,
    700,
    600,
    500,
    400,
    300,
    200,
    100,
    0,
]

SCREAMING_SNAKE_CASE    =	[
    999,
    992,
    985,
    978,
    971,
    964,
    957,
    949,
    942,
    935,
    928,
    921,
    914,
    907,
    900,
    899,
    879,
    859,
    840,
    820,
    800,
    799,
    766,
    733,
    700,
    699,
    650,
    600,
    599,
    500,
    499,
    400,
    399,
    300,
    299,
    200,
    199,
    100,
    99,
    0,
]

SCREAMING_SNAKE_CASE    =	[
    999,
    996,
    992,
    989,
    985,
    982,
    979,
    975,
    972,
    968,
    965,
    961,
    958,
    955,
    951,
    948,
    944,
    941,
    938,
    934,
    931,
    927,
    924,
    920,
    917,
    914,
    910,
    907,
    903,
    900,
    899,
    891,
    884,
    876,
    869,
    861,
    853,
    846,
    838,
    830,
    823,
    815,
    808,
    800,
    799,
    788,
    777,
    766,
    755,
    744,
    733,
    722,
    711,
    700,
    699,
    688,
    677,
    666,
    655,
    644,
    633,
    622,
    611,
    600,
    599,
    585,
    571,
    557,
    542,
    528,
    514,
    500,
    499,
    485,
    471,
    457,
    442,
    428,
    414,
    400,
    399,
    379,
    359,
    340,
    320,
    300,
    299,
    279,
    259,
    240,
    220,
    200,
    199,
    166,
    133,
    100,
    99,
    66,
    33,
    0,
]





