





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


lowercase__		:     Any			=							logging.getLogger(__name__)
class 							__lowerCAmelCase	(       __magic_name__					):






       """simple docstring"""
       _snake_case      :	List[str]									=       'sequence-classification'





       def __init__(				self  :						int			,					lowerCAmelCase__  :						Dict	)       ->	Union[str, Any]:

            '''simple docstring'''




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

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





       def snake_case__		(				self  :						int			,					**lowerCAmelCase__  :						int	)       ->	int:

            '''simple docstring'''




            return self.model(**lowerCAmelCase__	)





       def snake_case__		(				self  :						Dict			,					lowerCAmelCase__  :						Dict			,					lowerCAmelCase__  :						str	)       ->	Optional[int]:

            '''simple docstring'''




            _UpperCamelCase							       =			{'''input_ids''': batch[0], '''attention_mask''': batch[1], '''labels''': batch[3]}

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

            _UpperCamelCase							       =			self(**lowerCAmelCase__	)
            _UpperCamelCase							       =			outputs[0]

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





       def snake_case__		(				self  :						int	)       ->	Tuple:

            '''simple docstring'''




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

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





       def snake_case__		(				self  :						Optional[Any]			,					lowerCAmelCase__  :						str			,					lowerCAmelCase__  :						int			,					lowerCAmelCase__  :						bool = False	)       ->	DataLoader:

            '''simple docstring'''




            _UpperCamelCase							       =			'''dev''' if mode == '''test''' else mode

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

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





       def snake_case__		(				self  :						Optional[int]			,					lowerCAmelCase__  :						str			,					lowerCAmelCase__  :						List[Any]	)       ->	List[str]:

            '''simple docstring'''




            _UpperCamelCase							       =			{'''input_ids''': batch[0], '''attention_mask''': batch[1], '''labels''': batch[3]}

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

            _UpperCamelCase							       =			self(**lowerCAmelCase__	)
            _UpperCamelCase       ,							_UpperCamelCase							       =			outputs[:2]
            _UpperCamelCase							       =			logits.detach().cpu().numpy()
            _UpperCamelCase							       =			inputs['''labels'''].detach().cpu().numpy()

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





       def snake_case__		(				self  :						List[str]			,					lowerCAmelCase__  :						Any	)       ->	tuple:

            '''simple docstring'''




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

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

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

            _UpperCamelCase							       =			{**{'''val_loss''': val_loss_mean}, **compute_metrics(self.hparams.task			,					lowerCAmelCase__			,					lowerCAmelCase__	)}

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





       def snake_case__		(				self  :						Any			,					lowerCAmelCase__  :						list	)       ->	dict:

            '''simple docstring'''




            _UpperCamelCase       ,							_UpperCamelCase       ,							_UpperCamelCase							       =			self._eval_end(lowerCAmelCase__	)
            _UpperCamelCase							       =			ret['''log''']
            return {"val_loss": logs["val_loss"], "log": logs, "progress_bar": logs}





       def snake_case__		(				self  :						Optional[Any]			,					lowerCAmelCase__  :						int	)       ->	dict:

            '''simple docstring'''




            _UpperCamelCase       ,							_UpperCamelCase       ,							_UpperCamelCase							       =			self._eval_end(lowerCAmelCase__	)
            _UpperCamelCase							       =			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 snake_case__		(				lowerCAmelCase__  :						Union[str, Any]			,					lowerCAmelCase__  :						Optional[int]	)       ->	str:

            '''simple docstring'''




            BaseTransformer.add_model_specific_args(lowerCAmelCase__			,					lowerCAmelCase__	)
            parser.add_argument(
                '''--max_seq_length'''			,					default=128			,					type=lowerCAmelCase__			,					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=lowerCAmelCase__			,					required=lowerCAmelCase__			,					help='''The GLUE task to run'''			,					)
            parser.add_argument(
                '''--gpus'''			,					default=0			,					type=lowerCAmelCase__			,					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__							(							)						->						Optional[Any]:





     """simple docstring"""

     _UpperCamelCase							       =			argparse.ArgumentParser()
     add_generic_args(lowercase,   os.getcwd() )
     _UpperCamelCase							       =			GLUETransformer.add_model_specific_args(lowercase,   os.getcwd() )
     _UpperCamelCase							       =			parser.parse_args()

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

     _UpperCamelCase							       =			GLUETransformer(lowercase )
     _UpperCamelCase							       =			generic_train(lowercase,   lowercase )

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


if __name__ == "__main__":
   main()










'''simple docstring'''

import itertools
import json
import linecache
import os
import pickle
import re
import socket
import string
from collections import Counter
from logging import getLogger
from pathlib import Path
from typing import Callable, Dict, Iterable, List

import git
import torch
from torch.utils.data import Dataset

from transformers import BartTokenizer, RagTokenizer, TaTokenizer







def    a__							(							lowercase   :	Tuple,   lowercase   :	List[str],   lowercase   :	Optional[int],   lowercase   :	List[str],   lowercase   :	List[str]=True,   lowercase   :	str="pt" )						->						Union[str, Any]:





     """simple docstring"""

     _UpperCamelCase							       =			{'''add_prefix_space''': True} if isinstance(lowercase,   lowercase ) and not line.startswith(''' ''' ) else {}
     _UpperCamelCase							       =			padding_side
     return tokenizer(
         [line],   max_length=lowercase,   padding='''max_length''' if pad_to_max_length else None,   truncation=lowercase,   return_tensors=lowercase,   add_special_tokens=lowercase,   **lowercase,   )







def    a__							(							lowercase   :	str,   lowercase   :	int,   lowercase   :	Tuple=None,   )						->						Union[str, Any]:





     """simple docstring"""

     _UpperCamelCase							       =			input_ids.ne(lowercase ).any(dim=0 )
     if attention_mask is None:
          return input_ids[:, keep_column_mask]
     else:
          return (input_ids[:, keep_column_mask], attention_mask[:, keep_column_mask])
class 							__lowerCAmelCase	(       __magic_name__					):






       """simple docstring"""





       def __init__(				self  :						Optional[int]			,					lowerCAmelCase__  :						int			,					lowerCAmelCase__  :						int			,					lowerCAmelCase__  :						str			,					lowerCAmelCase__  :						Tuple			,					lowerCAmelCase__  :						str="train"			,					lowerCAmelCase__  :						List[str]=None			,					lowerCAmelCase__  :						Dict=None			,					lowerCAmelCase__  :						Optional[Any]=None			,					lowerCAmelCase__  :						Dict=""			,					)       ->	Any:

            '''simple docstring'''




            super().__init__()
            _UpperCamelCase							       =			Path(lowerCAmelCase__	).joinpath(type_path + '''.source'''	)
            _UpperCamelCase							       =			Path(lowerCAmelCase__	).joinpath(type_path + '''.target'''	)
            _UpperCamelCase							       =			self.get_char_lens(self.src_file	)
            _UpperCamelCase							       =			max_source_length
            _UpperCamelCase							       =			max_target_length
            assert min(self.src_lens	) > 0, f"""found empty line in {self.src_file}"""
            _UpperCamelCase							       =			tokenizer
            _UpperCamelCase							       =			prefix
            if n_obs is not None:
                 _UpperCamelCase							       =			self.src_lens[:n_obs]
            _UpperCamelCase							       =			src_lang
            _UpperCamelCase							       =			tgt_lang





       def __len__(				self  :						Optional[Any]	)       ->	List[Any]:

            '''simple docstring'''




            return len(self.src_lens	)





       def __getitem__(				self  :						Optional[Any]			,					lowerCAmelCase__  :						Any	)       ->	Dict[str, torch.Tensor]:

            '''simple docstring'''




            _UpperCamelCase							       =			index + 1  # linecache starts at 1
            _UpperCamelCase							       =			self.prefix + linecache.getline(str(self.src_file	)			,					lowerCAmelCase__	).rstrip('''\n'''	)
            _UpperCamelCase							       =			linecache.getline(str(self.tgt_file	)			,					lowerCAmelCase__	).rstrip('''\n'''	)
            assert source_line, f"""empty source line for index {index}"""
            assert tgt_line, f"""empty tgt line for index {index}"""

            # Need to add eos token manually for T5
            if isinstance(self.tokenizer			,					lowerCAmelCase__	):
                 source_line += self.tokenizer.eos_token
                 tgt_line += self.tokenizer.eos_token

            # Pad source and target to the right
            _UpperCamelCase							       =			(
                self.tokenizer.question_encoder if isinstance(self.tokenizer			,					lowerCAmelCase__	) else self.tokenizer
            )
            _UpperCamelCase							       =			self.tokenizer.generator if isinstance(self.tokenizer			,					lowerCAmelCase__	) else self.tokenizer

            _UpperCamelCase							       =			encode_line(lowerCAmelCase__			,					lowerCAmelCase__			,					self.max_source_length			,					'''right'''	)
            _UpperCamelCase							       =			encode_line(lowerCAmelCase__			,					lowerCAmelCase__			,					self.max_target_length			,					'''right'''	)

            _UpperCamelCase							       =			source_inputs['''input_ids'''].squeeze()
            _UpperCamelCase							       =			target_inputs['''input_ids'''].squeeze()
            _UpperCamelCase							       =			source_inputs['''attention_mask'''].squeeze()
            return {
                "input_ids": source_ids,
                "attention_mask": src_mask,
                "decoder_input_ids": target_ids,
            }





       @staticmethod
       def snake_case__		(				lowerCAmelCase__  :						List[Any]	)       ->	Optional[int]:

            '''simple docstring'''




            return [len(lowerCAmelCase__	) for x in Path(lowerCAmelCase__	).open().readlines()]







       def snake_case__		(				self  :						Dict			,					lowerCAmelCase__  :						List[str]	)       ->	Dict[str, torch.Tensor]:

            '''simple docstring'''




            _UpperCamelCase							       =			torch.stack([x['''input_ids'''] for x in batch]	)
            _UpperCamelCase							       =			torch.stack([x['''attention_mask'''] for x in batch]	)
            _UpperCamelCase							       =			torch.stack([x['''decoder_input_ids'''] for x in batch]	)
            _UpperCamelCase							       =			(
                self.tokenizer.generator.pad_token_id
                if isinstance(self.tokenizer			,					lowerCAmelCase__	)
                else self.tokenizer.pad_token_id
            )
            _UpperCamelCase							       =			(
                self.tokenizer.question_encoder.pad_token_id
                if isinstance(self.tokenizer			,					lowerCAmelCase__	)
                else self.tokenizer.pad_token_id
            )
            _UpperCamelCase							       =			trim_batch(lowerCAmelCase__			,					lowerCAmelCase__	)
            _UpperCamelCase       ,							_UpperCamelCase							       =			trim_batch(lowerCAmelCase__			,					lowerCAmelCase__			,					attention_mask=lowerCAmelCase__	)
            _UpperCamelCase							       =			{
                '''input_ids''': source_ids,
                '''attention_mask''': source_mask,
                '''decoder_input_ids''': y,
            }
            return batch

lowercase__		:     Union[str, Any]			=							getLogger(__name__)







def    a__							(							lowercase   :	List[List] )						->						Optional[int]:





     """simple docstring"""

     return list(itertools.chain.from_iterable(lowercase ) )







def    a__							(							lowercase   :	str )						->						None:





     """simple docstring"""

     _UpperCamelCase							       =			get_git_info()
     save_json(lowercase,   os.path.join(lowercase,   '''git_log.json''' ) )







def    a__							(							lowercase   :	Optional[int],   lowercase   :	List[str],   lowercase   :	str=4,   **lowercase   :	Optional[Any] )						->						Any:





     """simple docstring"""

     with open(lowercase,   '''w''' ) as f:
          json.dump(lowercase,   lowercase,   indent=lowercase,   **lowercase )







def    a__							(							lowercase   :	Union[str, Any] )						->						Optional[int]:





     """simple docstring"""

     with open(lowercase ) as f:
          return json.load(lowercase )







def    a__							(							)						->						List[Any]:





     """simple docstring"""

     _UpperCamelCase							       =			git.Repo(search_parent_directories=lowercase )
     _UpperCamelCase							       =			{
         '''repo_id''': str(lowercase ),
         '''repo_sha''': str(repo.head.object.hexsha ),
         '''repo_branch''': str(repo.active_branch ),
         '''hostname''': str(socket.gethostname() ),
     }
     return repo_infos







def    a__							(							lowercase   :	Callable,   lowercase   :	Iterable )						->						List:





     """simple docstring"""

     return list(map(lowercase,   lowercase ) )







def    a__							(							lowercase   :	List[Any],   lowercase   :	Dict )						->						Optional[int]:





     """simple docstring"""

     with open(lowercase,   '''wb''' ) as f:
          return pickle.dump(lowercase,   lowercase )







def    a__							(							lowercase   :	Tuple )						->						Tuple:





     """simple docstring"""

     def remove_articles(lowercase   :	Tuple ):
          return re.sub(r'''\b(a|an|the)\b''',   ''' ''',   lowercase )

     def white_space_fix(lowercase   :	Tuple ):
          return " ".join(text.split() )

     def remove_punc(lowercase   :	Optional[int] ):
          _UpperCamelCase							       =			set(string.punctuation )
          return "".join(ch for ch in text if ch not in exclude )

     def lower(lowercase   :	Tuple ):
          return text.lower()

     return white_space_fix(remove_articles(remove_punc(lower(lowercase ) ) ) )







def    a__							(							lowercase   :	Tuple,   lowercase   :	Union[str, Any] )						->						Dict:





     """simple docstring"""

     _UpperCamelCase							       =			normalize_answer(lowercase ).split()
     _UpperCamelCase							       =			normalize_answer(lowercase ).split()
     _UpperCamelCase							       =			Counter(lowercase ) & Counter(lowercase )
     _UpperCamelCase							       =			sum(common.values() )
     if num_same == 0:
          return 0
     _UpperCamelCase							       =			1.0 * num_same / len(lowercase )
     _UpperCamelCase							       =			1.0 * num_same / len(lowercase )
     _UpperCamelCase							       =			(2 * precision * recall) / (precision + recall)
     return fa







def    a__							(							lowercase   :	Tuple,   lowercase   :	Any )						->						List[str]:





     """simple docstring"""

     return normalize_answer(lowercase ) == normalize_answer(lowercase )







def    a__							(							lowercase   :	List[str],   lowercase   :	List[str] )						->						Dict:





     """simple docstring"""

     assert len(lowercase ) == len(lowercase )
     _UpperCamelCase							       =			0
     for hypo, pred in zip(lowercase,   lowercase ):
          em += exact_match_score(lowercase,   lowercase )
     if len(lowercase ) > 0:
          em /= len(lowercase )
     return {"em": em}







def    a__							(							lowercase   :	Tuple )						->						Union[str, Any]:





     """simple docstring"""

     return model_prefix.startswith('''rag''' )







def    a__							(							lowercase   :	int,   lowercase   :	List[Any],   lowercase   :	List[Any] )						->						Optional[int]:





     """simple docstring"""

     _UpperCamelCase							       =			{p: p for p in extra_params}
     # T5 models don't have `dropout` param, they have `dropout_rate` instead
     _UpperCamelCase							       =			'''dropout_rate'''
     for p in extra_params:
          if getattr(lowercase,   lowercase,   lowercase ):
               if not hasattr(lowercase,   lowercase ) and not hasattr(lowercase,   equivalent_param[p] ):
                    logger.info('''config doesn\'t have a `{}` attribute'''.format(lowercase ) )
                    delattr(lowercase,   lowercase )
                    continue
               _UpperCamelCase							       =			p if hasattr(lowercase,   lowercase ) else equivalent_param[p]
               setattr(lowercase,   lowercase,   getattr(lowercase,   lowercase ) )
               delattr(lowercase,   lowercase )
     return hparams, config



