

"""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


__UpperCAmelCase			=					logging.getLogger(__name__)







class   __lowercase      (     __lowerCamelCase       ):
  snake_case_												=							"""sequence-classification"""

  def __init__(	self		:      str       ,A		:      int     ):






   '''simple docstring'''
   if type(A     ) == dict:
    UpperCAmelCase__       :	Tuple        =       Namespace(**A     )
   UpperCAmelCase__       :	List[str]        =       glue_output_modes[hparams.task]
   UpperCAmelCase__       :	Optional[int]        =       glue_tasks_num_labels[hparams.task]

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

  def  __lowercase							(	self		:      int       ,**A		:      Dict     ):






   '''simple docstring'''
   return self.model(**A     )

  def  __lowercase							(	self		:      Dict       ,A		:      Any       ,A		:      Optional[int]     ):






   '''simple docstring'''
   UpperCAmelCase__       :	Any        =       {"""input_ids""": batch[0], """attention_mask""": batch[1], """labels""": batch[3]}

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

   UpperCAmelCase__       :	Union[str, Any]        =       self(**A     )
   UpperCAmelCase__       :	Dict        =       outputs[0]

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

  def  __lowercase							(	self		:      str     ):






   '''simple docstring'''
   UpperCAmelCase__       :	Dict        =       self.hparams
   UpperCAmelCase__       :	str        =       processors[args.task]()
   UpperCAmelCase__       :	List[Any]        =       processor.get_labels()

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

  def  __lowercase							(	self		:      List[Any]       ,A		:      str       ,A		:      int       ,A		:      bool = False     ):






   '''simple docstring'''
   UpperCAmelCase__       :	str        =       """dev""" if mode == """test""" else mode

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

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

  def  __lowercase							(	self		:      List[str]       ,A		:      Union[str, Any]       ,A		:      str     ):






   '''simple docstring'''
   UpperCAmelCase__       :	Dict        =       {"""input_ids""": batch[0], """attention_mask""": batch[1], """labels""": batch[3]}

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

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

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

  def  __lowercase							(	self		:      Dict       ,A		:      Any     ):






   '''simple docstring'''
   UpperCAmelCase__       :	str        =       torch.stack([x["""val_loss"""] for x in outputs]     ).mean().detach().cpu().item()
   UpperCAmelCase__       :	Optional[int]        =       np.concatenate([x["""pred"""] for x in outputs]       ,axis=0     )

   if self.hparams.glue_output_mode == "classification":
    UpperCAmelCase__       :	str        =       np.argmax(A       ,axis=1     )
   elif self.hparams.glue_output_mode == "regression":
    UpperCAmelCase__       :	Dict        =       np.squeeze(A     )

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

   UpperCAmelCase__       :	List[Any]        =       {**{"""val_loss""": val_loss_mean}, **compute_metrics(self.hparams.task       ,A       ,A     )}

   UpperCAmelCase__       :	Any        =       dict(results.items()     )
   UpperCAmelCase__       :	Optional[int]        =       results
   return ret, preds_list, out_label_list

  def  __lowercase							(	self		:      int       ,A		:      list     ):






   '''simple docstring'''
   UpperCAmelCase__ ,   UpperCAmelCase__ ,   UpperCAmelCase__       :	str        =       self._eval_end(A     )
   UpperCAmelCase__       :	str        =       ret["""log"""]
   return {"val_loss": logs["val_loss"], "log": logs, "progress_bar": logs}

  def  __lowercase							(	self		:      Any       ,A		:      int     ):






   '''simple docstring'''
   UpperCAmelCase__ ,   UpperCAmelCase__ ,   UpperCAmelCase__       :	Tuple        =       self._eval_end(A     )
   UpperCAmelCase__       :	Union[str, Any]        =       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							(	A		:      List[str]       ,A		:      Union[str, Any]     ):






   '''simple docstring'''
   BaseTransformer.add_model_specific_args(A       ,A     )
   parser.add_argument(
       """--max_seq_length"""       ,default=128       ,type=A       ,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=A       ,required=A       ,help="""The GLUE task to run"""       ,)
   parser.add_argument(
       """--gpus"""       ,default=0       ,type=A       ,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 	lowerCAmelCase    (       ):
 '''simple docstring'''





 UpperCAmelCase__       :	List[str]        =       argparse.ArgumentParser()
 add_generic_args(__UpperCamelCase				,     os.getcwd()   )
 UpperCAmelCase__       :	Tuple        =       GLUETransformer.add_model_specific_args(__UpperCamelCase				,     os.getcwd()   )
 UpperCAmelCase__       :	Optional[int]        =       parser.parse_args()

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

 UpperCAmelCase__       :	str        =       GLUETransformer(__UpperCamelCase   )
 UpperCAmelCase__       :	Tuple        =       generic_train(__UpperCamelCase				,     __UpperCamelCase   )

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


if __name__ == "__main__":
      main()







from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available


lowercase    :   Tuple						=			{
    'configuration_luke': ['LUKE_PRETRAINED_CONFIG_ARCHIVE_MAP', 'LukeConfig'],
    'tokenization_luke': ['LukeTokenizer'],
}

try:
		if not is_torch_available():
				raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
		pass
else:
		lowercase    :   int						=			[
		    'LUKE_PRETRAINED_MODEL_ARCHIVE_LIST',
		    'LukeForEntityClassification',
		    'LukeForEntityPairClassification',
		    'LukeForEntitySpanClassification',
		    'LukeForMultipleChoice',
		    'LukeForQuestionAnswering',
		    'LukeForSequenceClassification',
		    'LukeForTokenClassification',
		    'LukeForMaskedLM',
		    'LukeModel',
		    'LukePreTrainedModel',
		]


if TYPE_CHECKING:
		from .configuration_luke import LUKE_PRETRAINED_CONFIG_ARCHIVE_MAP, LukeConfig
		from .tokenization_luke import LukeTokenizer

		try:
				if not is_torch_available():
						raise OptionalDependencyNotAvailable()
		except OptionalDependencyNotAvailable:
				pass
		else:
				from .modeling_luke import (
				    LUKE_PRETRAINED_MODEL_ARCHIVE_LIST,
				    LukeForEntityClassification,
				    LukeForEntityPairClassification,
				    LukeForEntitySpanClassification,
				    LukeForMaskedLM,
				    LukeForMultipleChoice,
				    LukeForQuestionAnswering,
				    LukeForSequenceClassification,
				    LukeForTokenClassification,
				    LukeModel,
				    LukePreTrainedModel,
				)

else:
		import sys

		lowercase    :   Any						=			_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)