



"""simple docstring"""
import argparse
import glob
import logging
import os
from argparse import Namespace
from importlib import import_module

import numpy as np
import torch
from lightning_base import BaseTransformer, add_generic_args, generic_train
from seqeval.metrics import accuracy_score, fa_score, precision_score, recall_score
from torch.nn import CrossEntropyLoss
from torch.utils.data import DataLoader, TensorDataset
from utils_ner import TokenClassificationTask


__a      =				logging.getLogger(__name__)
class 				lowerCamelCase  (			_lowerCAmelCase				):






					'''simple docstring'''





					_A		:			Union[str, Any]						=     """token-classification"""






					def __init__(       self:							Any						,     snake_case:							Tuple						)   ->	List[Any]:
											if type(snake_case						) == dict:
																	snake_case_ :Optional[int]						=			Namespace(**snake_case						)
											snake_case_ :Optional[int]						=			import_module("""tasks"""						)
											try:
																	snake_case_ :Any						=			getattr(snake_case						,     hparams.task_type						)
																	snake_case_ :TokenClassificationTask						=			token_classification_task_clazz()
											except AttributeError:
																	raise ValueError(
																	    f"""Task {hparams.task_type} needs to be defined as a TokenClassificationTask subclass in {module}. """
																	    f"""Available tasks classes are: {TokenClassificationTask.__subclasses__()}"""						)
											snake_case_ :Any						=			self.token_classification_task.get_labels(hparams.labels						)
											snake_case_ :str						=			CrossEntropyLoss().ignore_index
											super().__init__(snake_case						,     len(self.labels						)						,     self.mode						)






					def    lowerCAmelCase_				(       self:							Dict						,     **snake_case:							List[Any]						)   ->	Any:
											return self.model(**snake_case						)






					def    lowerCAmelCase_				(       self:							str						,     snake_case:							Tuple						,     snake_case:							List[Any]						)   ->	Optional[int]:
											snake_case_ :List[str]						=			{"""input_ids""": batch[0], """attention_mask""": batch[1], """labels""": batch[3]}
											if self.config.model_type != "distilbert":
																	snake_case_ :List[str]						=			(
																	    batch[2] if self.config.model_type in ["""bert""", """xlnet"""] else None
																	)  # XLM and RoBERTa don"t use token_type_ids

											snake_case_ :Optional[Any]						=			self(**snake_case						)
											snake_case_ :List[str]						=			outputs[0]
											# tensorboard_logs = {"loss": loss, "rate": self.lr_scheduler.get_last_lr()[-1]}
											return {"loss": loss}






					def    lowerCAmelCase_				(       self:							int						)   ->	Dict:
											snake_case_ :List[Any]						=			self.hparams
											for mode in ["train", "dev", "test"]:
																	snake_case_ :Optional[int]						=			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						)
																							snake_case_ :Optional[int]						=			torch.load(snake_case						)
																	else:
																							logger.info("""Creating features from dataset file at %s"""						,     args.data_dir						)
																							snake_case_ :Optional[int]						=			self.token_classification_task.read_examples_from_file(args.data_dir						,     snake_case						)
																							snake_case_ :Any						=			self.token_classification_task.convert_examples_to_features(
																							    snake_case						,     self.labels						,     args.max_seq_length						,     self.tokenizer						,     cls_token_at_end=bool(self.config.model_type in ["""xlnet"""]						)						,     cls_token=self.tokenizer.cls_token						,     cls_token_segment_id=2 if self.config.model_type in ["""xlnet"""] else 0						,     sep_token=self.tokenizer.sep_token						,     sep_token_extra=snake_case						,     pad_on_left=bool(self.config.model_type in ["""xlnet"""]						)						,     pad_token=self.tokenizer.pad_token_id						,     pad_token_segment_id=self.tokenizer.pad_token_type_id						,     pad_token_label_id=self.pad_token_label_id						,     )
																							logger.info("""Saving features into cached file %s"""						,     snake_case						)
																							torch.save(snake_case						,     snake_case						)






					def    lowerCAmelCase_				(       self:							Optional[int]						,     snake_case:							int						,     snake_case:							int						,     snake_case:							bool = False						)   ->	DataLoader:
											snake_case_ :int						=			self._feature_file(snake_case						)
											logger.info("""Loading features from cached file %s"""						,     snake_case						)
											snake_case_ :str						=			torch.load(snake_case						)
											snake_case_ :Dict						=			torch.tensor([f.input_ids for f in features]						,     dtype=torch.long						)
											snake_case_ :str						=			torch.tensor([f.attention_mask for f in features]						,     dtype=torch.long						)
											if features[0].token_type_ids is not None:
																	snake_case_ :List[Any]						=			torch.tensor([f.token_type_ids for f in features]						,     dtype=torch.long						)
											else:
																	snake_case_ :List[str]						=			torch.tensor([0 for f in features]						,     dtype=torch.long						)
																	# HACK(we will not use this anymore soon)
											snake_case_ :Any						=			torch.tensor([f.label_ids for f in features]						,     dtype=torch.long						)
											return DataLoader(
											    TensorDataset(snake_case						,     snake_case						,     snake_case						,     snake_case						)						,     batch_size=snake_case						)






					def    lowerCAmelCase_				(       self:							List[str]						,     snake_case:							Dict						,     snake_case:							Union[str, Any]						)   ->	List[str]:
											"""Compute validation""" ""
											snake_case_ :List[str]						=			{"""input_ids""": batch[0], """attention_mask""": batch[1], """labels""": batch[3]}
											if self.config.model_type != "distilbert":
																	snake_case_ :Dict						=			(
																	    batch[2] if self.config.model_type in ["""bert""", """xlnet"""] else None
																	)  # XLM and RoBERTa don"t use token_type_ids
											snake_case_ :Dict						=			self(**snake_case						)
											snake_case_,       snake_case_ :Dict						=			outputs[:2]
											snake_case_ :Union[str, Any]						=			logits.detach().cpu().numpy()
											snake_case_ :List[Any]						=			inputs["""labels"""].detach().cpu().numpy()
											return {"val_loss": tmp_eval_loss.detach().cpu(), "pred": preds, "target": out_label_ids}






					def    lowerCAmelCase_				(       self:							List[Any]						,     snake_case:							int						)   ->	Tuple:
											snake_case_ :Union[str, Any]						=			torch.stack([x["""val_loss"""] for x in outputs]						).mean()
											snake_case_ :Tuple						=			np.concatenate([x["""pred"""] for x in outputs]						,     axis=0						)
											snake_case_ :Tuple						=			np.argmax(snake_case						,     axis=2						)
											snake_case_ :List[str]						=			np.concatenate([x["""target"""] for x in outputs]						,     axis=0						)

											snake_case_ :Optional[Any]						=			dict(enumerate(self.labels						)						)
											snake_case_ :Dict						=			[[] for _ in range(out_label_ids.shape[0]						)]
											snake_case_ :Dict						=			[[] for _ in range(out_label_ids.shape[0]						)]

											for i in range(out_label_ids.shape[0]						):
																	for j in range(out_label_ids.shape[1]						):
																							if out_label_ids[i, j] != self.pad_token_label_id:
																													out_label_list[i].append(label_map[out_label_ids[i][j]]						)
																													preds_list[i].append(label_map[preds[i][j]]						)

											snake_case_ :str						=			{
											    """val_loss""": val_loss_mean,
											    """accuracy_score""": accuracy_score(snake_case						,     snake_case						),
											    """precision""": precision_score(snake_case						,     snake_case						),
											    """recall""": recall_score(snake_case						,     snake_case						),
											    """f1""": fa_score(snake_case						,     snake_case						),
											}

											snake_case_ :List[Any]						=			dict(results.items()						)
											snake_case_ :Union[str, Any]						=			results
											return ret, preds_list, out_label_list






					def    lowerCAmelCase_				(       self:							Optional[Any]						,     snake_case:							Dict						)   ->	Optional[Any]:
											# when stable
											snake_case_,       snake_case_,       snake_case_ :Tuple						=			self._eval_end(snake_case						)
											snake_case_ :str						=			ret["""log"""]
											return {"val_loss": logs["val_loss"], "log": logs, "progress_bar": logs}






					def    lowerCAmelCase_				(       self:							Tuple						,     snake_case:							Optional[int]						)   ->	Any:
											# updating to test_epoch_end instead of deprecated test_end
											snake_case_,       snake_case_,       snake_case_ :Any						=			self._eval_end(snake_case						)

											# Converting to the dict required by pl
											# https://github.com/PyTorchLightning/pytorch-lightning/blob/master/\
											# pytorch_lightning/trainer/logging.py#L139
											snake_case_ :Optional[int]						=			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    lowerCAmelCase_				(       snake_case:							Any						,     snake_case:							int						)   ->	Dict:
											# Add NER specific options
											BaseTransformer.add_model_specific_args(snake_case						,     snake_case						)
											parser.add_argument(
											    """--task_type"""						,     default="""NER"""						,     type=snake_case						,     help="""Task type to fine tune in training (e.g. NER, POS, etc)"""						)
											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(
											    """--labels"""						,     default=""""""						,     type=snake_case						,     help="""Path to a file containing all labels. If not specified, CoNLL-2003 labels are used."""						,     )
											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


if __name__ == "__main__":
						__a      =				argparse.ArgumentParser()
						add_generic_args(parser, os.getcwd())
						__a      =				NERTransformer.add_model_specific_args(parser, os.getcwd())
						__a      =				parser.parse_args()
						__a      =				NERTransformer(args)
						__a      =				generic_train(model, args)

						if args.do_predict:
												# See https://github.com/huggingface/transformers/issues/3159
												# pl use this default format to create a checkpoint:
												# https://github.com/PyTorchLightning/pytorch-lightning/blob/master\
												# /pytorch_lightning/callbacks/model_checkpoint.py#L322
												__a      =				sorted(glob.glob(os.path.join(args.output_dir, "checkpoint-epoch=*.ckpt"), recursive=True))
												__a      =				model.load_from_checkpoint(checkpoints[-1])
												trainer.test(model)








from ...configuration_utils import PretrainedConfig
from ...utils import logging


UpperCAmelCase__				   =		logging.get_logger(__name__)

UpperCAmelCase__				   =		{}






class 		lowercase_					(	lowercase   ):






      '''simple docstring'''




      __snake_case       =  '''llama'''
      __snake_case       =  ['''past_key_values''']







      def __init__(      self      :						Optional[Any] ,					__UpperCAmelCase      :						Union[str, Any]=32_000 ,					__UpperCAmelCase      :						str=4_096 ,					__UpperCAmelCase      :						int=11_008 ,					__UpperCAmelCase      :						Tuple=32 ,					__UpperCAmelCase      :						Optional[int]=32 ,					__UpperCAmelCase      :						List[str]=None ,					__UpperCAmelCase      :						Union[str, Any]="silu" ,					__UpperCAmelCase      :						Tuple=2_048 ,					__UpperCAmelCase      :						Optional[Any]=0.02 ,					__UpperCAmelCase      :						Any=1e-6 ,					__UpperCAmelCase      :						Union[str, Any]=True ,					__UpperCAmelCase      :						Optional[int]=0 ,					__UpperCAmelCase      :						Optional[int]=1 ,					__UpperCAmelCase      :						Optional[int]=2 ,					__UpperCAmelCase      :						Tuple=1 ,					__UpperCAmelCase      :						List[str]=False ,					__UpperCAmelCase      :						Tuple=None ,					**__UpperCAmelCase      :						Tuple ,					)    ->str:




       """simple docstring"""


       a		  =      vocab_size
       a		  =      max_position_embeddings
       a		  =      hidden_size
       a		  =      intermediate_size
       a		  =      num_hidden_layers
       a		  =      num_attention_heads

       # for backward compatibility
       if num_key_value_heads is None:
        a		  =      num_attention_heads

       a		  =      num_key_value_heads
       a		  =      hidden_act
       a		  =      initializer_range
       a		  =      rms_norm_eps
       a		  =      pretraining_tp
       a		  =      use_cache
       a		  =      rope_scaling
       self._rope_scaling_validation()

       super().__init__(
           pad_token_id=__UpperCAmelCase ,					bos_token_id=__UpperCAmelCase ,					eos_token_id=__UpperCAmelCase ,					tie_word_embeddings=__UpperCAmelCase ,					**__UpperCAmelCase ,					)







      def       __lowerCAmelCase					(      self      :						Tuple  )    ->Tuple:




       """simple docstring"""


       if self.rope_scaling is None:
        return

       if not isinstance(self.rope_scaling ,					__UpperCAmelCase  ) or len(self.rope_scaling  ) != 2:
        raise ValueError(
            '''`rope_scaling` must be a dictionary with with two fields, `name` and `factor`, '''
            F"""got {self.rope_scaling}"""  )
       a		  =      self.rope_scaling.get('''type''' ,					__UpperCAmelCase  )
       a		  =      self.rope_scaling.get('''factor''' ,					__UpperCAmelCase  )
       if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
        raise ValueError(
            F"""`rope_scaling`'s name field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"""  )
       if rope_scaling_factor is None or not isinstance(__UpperCAmelCase ,					__UpperCAmelCase  ) or rope_scaling_factor <= 1.0:
        raise ValueError(F"""`rope_scaling`'s factor field must be an float > 1, got {rope_scaling_factor}"""  )


