'''simple docstring'''






import logging
import os
from dataclasses import dataclass
from typing import List, Optional, Union

import tqdm
from filelock import FileLock

from transformers import (
    BartTokenizer,
    BartTokenizerFast,
    DataProcessor,
    PreTrainedTokenizer,
    RobertaTokenizer,
    RobertaTokenizerFast,
    XLMRobertaTokenizer,
    is_tf_available,
    is_torch_available,
)


__a										=					logging.getLogger(__name__)





@dataclass(frozen=UpperCamelCase__   )
class     A__							:





   """simple docstring"""





   UpperCamelCase_       :						str
   UpperCamelCase_       :						str
   UpperCamelCase_       :						Optional[str]    				=     None
   UpperCamelCase_       :						Optional[str]    				=     None
   UpperCamelCase_       :						Optional[str]    				=     None





@dataclass(frozen=UpperCamelCase__   )
class     A__							:





   """simple docstring"""





   UpperCamelCase_       :						List[int]
   UpperCamelCase_       :						Optional[List[int]]    				=     None
   UpperCamelCase_       :						Optional[List[int]]    				=     None
   UpperCamelCase_       :						Optional[Union[int, float]]    				=     None
   UpperCamelCase_       :						Optional[int]    				=     None


if is_torch_available():
     import torch
     from torch.utils.data import Dataset





     class     A__							(       UpperCamelCase__   ):





        """simple docstring"""





        UpperCamelCase_       :						List[InputFeatures]




        def __init__( self     :		Any						,     lowerCAmelCase__     :		str						,     lowerCAmelCase__     :		PreTrainedTokenizer						,     lowerCAmelCase__     :		str						,     lowerCAmelCase__     :		Optional[int] = None						,     lowerCAmelCase__     :		Dict=False						,     lowerCAmelCase__     :		bool = False						,     )       ->    Tuple:







           """simple docstring"""




           _UpperCAmelCase							:	Optional[Any]							=   hans_processors[task]()

           _UpperCAmelCase							:	Any							=   os.path.join(
               __a						,     "cached_{}_{}_{}_{}".format(
                   "dev" if evaluate else "train"						,     tokenizer.__class__.__name__						,     str(__a			)						,     __a						,     )						,     )
           _UpperCAmelCase							:	Any							=   processor.get_labels()
           if tokenizer.__class__ in (
               RobertaTokenizer,
               RobertaTokenizerFast,
               XLMRobertaTokenizer,
               BartTokenizer,
               BartTokenizerFast,
           ):
              # HACK(label indices are swapped in RoBERTa pretrained model)
              _UpperCAmelCase							,       _UpperCAmelCase							:	List[Any]							=   label_list[2], label_list[1]
           _UpperCAmelCase							:	Dict							=   label_list

           # Make sure only the first process in distributed training processes the dataset,
           # and the others will use the cache.
           _UpperCAmelCase							:	str							=   cached_features_file + ".lock"
           with FileLock(__a			):
              if os.path.exists(__a			) and not overwrite_cache:
                 logger.info(F"""Loading features from cached file {cached_features_file}"""			)
                 _UpperCAmelCase							:	Optional[int]							=   torch.load(__a			)
              else:
                 logger.info(F"""Creating features from dataset file at {data_dir}"""			)

                 _UpperCAmelCase							:	Dict							=   (
                     processor.get_dev_examples(__a			) if evaluate else processor.get_train_examples(__a			)
                 )

                 logger.info("Training examples: %s"						,     len(__a			)			)
                 _UpperCAmelCase							:	List[str]							=   hans_convert_examples_to_features(__a						,     __a						,     __a						,     __a			)
                 logger.info("Saving features into cached file %s"						,     __a			)
                 torch.save(self.features						,     __a			)




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







           """simple docstring"""




           return len(self.features			)




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







           """simple docstring"""




           return self.features[i]




        def 			_lowerCAmelCase		( self     :		Union[str, Any]			)       ->    Optional[Any]:







           """simple docstring"""




           return self.label_list


if is_tf_available():
     import tensorflow as tf





     class     A__							:





        """simple docstring"""





        UpperCamelCase_       :						List[InputFeatures]




        def __init__( self     :		Union[str, Any]						,     lowerCAmelCase__     :		str						,     lowerCAmelCase__     :		PreTrainedTokenizer						,     lowerCAmelCase__     :		str						,     lowerCAmelCase__     :		Optional[int] = 1_2_8						,     lowerCAmelCase__     :		Any=False						,     lowerCAmelCase__     :		bool = False						,     )       ->    Dict:







           """simple docstring"""




           _UpperCAmelCase							:	Optional[int]							=   hans_processors[task]()
           _UpperCAmelCase							:	Optional[Any]							=   processor.get_labels()
           if tokenizer.__class__ in (
               RobertaTokenizer,
               RobertaTokenizerFast,
               XLMRobertaTokenizer,
               BartTokenizer,
               BartTokenizerFast,
           ):
              # HACK(label indices are swapped in RoBERTa pretrained model)
              _UpperCAmelCase							,       _UpperCAmelCase							:	List[str]							=   label_list[2], label_list[1]
           _UpperCAmelCase							:	List[str]							=   label_list

           _UpperCAmelCase							:	Tuple							=   processor.get_dev_examples(__a			) if evaluate else processor.get_train_examples(__a			)
           _UpperCAmelCase							:	Any							=   hans_convert_examples_to_features(__a						,     __a						,     __a						,     __a			)

           def gen():
              for ex_index, ex in tqdm.tqdm(enumerate(self.features			)						,     desc="convert examples to features"			):
                 if ex_index % 1_0_0_0_0 == 0:
                    logger.info("Writing example %d of %d" % (ex_index, len(__a			))			)

                 yield (
                     {
                         "example_id": 0,
                         "input_ids": ex.input_ids,
                         "attention_mask": ex.attention_mask,
                         "token_type_ids": ex.token_type_ids,
                     },
                     ex.label,
                 )

           _UpperCAmelCase							:	Tuple							=   tf.data.Dataset.from_generator(
               __a						,     (
                   {
                       "example_id": tf.intaa,
                       "input_ids": tf.intaa,
                       "attention_mask": tf.intaa,
                       "token_type_ids": tf.intaa,
                   },
                   tf.intaa,
               )						,     (
                   {
                       "example_id": tf.TensorShape([]			),
                       "input_ids": tf.TensorShape([None, None]			),
                       "attention_mask": tf.TensorShape([None, None]			),
                       "token_type_ids": tf.TensorShape([None, None]			),
                   },
                   tf.TensorShape([]			),
               )						,     )




        def 			_lowerCAmelCase		( self     :		int			)       ->    Optional[int]:







           """simple docstring"""




           return self.dataset




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







           """simple docstring"""




           return len(self.features			)




        def __getitem__( self     :		int						,     lowerCAmelCase__     :		Union[str, Any]			)       ->    Optional[Any]:







           """simple docstring"""




           return self.features[i]




        def 			_lowerCAmelCase		( self     :		int			)       ->    Union[str, Any]:







           """simple docstring"""




           return self.label_list





class     A__							(       UpperCamelCase__   ):





   """simple docstring"""





   def 			_lowerCAmelCase		( self     :		List[Any]						,     lowerCAmelCase__     :		Dict			)       ->    List[str]:







      """simple docstring"""




      return self._create_examples(self._read_tsv(os.path.join(__a						,     "heuristics_train_set.txt"			)			)						,     "train"			)




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







      """simple docstring"""




      return self._create_examples(self._read_tsv(os.path.join(__a						,     "heuristics_evaluation_set.txt"			)			)						,     "dev"			)




   def 			_lowerCAmelCase		( self     :		Any			)       ->    Optional[int]:







      """simple docstring"""




      return ["contradiction", "entailment", "neutral"]




   def 			_lowerCAmelCase		( self     :		Union[str, Any]						,     lowerCAmelCase__     :		Optional[int]						,     lowerCAmelCase__     :		Union[str, Any]			)       ->    str:







      """simple docstring"""




      _UpperCAmelCase							:	List[str]							=   []
      for i, line in enumerate(__a			):
         if i == 0:
            continue
         _UpperCAmelCase							:	Optional[int]							=   "%s-%s" % (set_type, line[0])
         _UpperCAmelCase							:	Tuple							=   line[5]
         _UpperCAmelCase							:	int							=   line[6]
         _UpperCAmelCase							:	Any							=   line[7][2:] if line[7].startswith("ex"			) else line[7]
         _UpperCAmelCase							:	Optional[Any]							=   line[0]
         examples.append(InputExample(guid=__a						,     text_a=__a						,     text_b=__a						,     label=__a						,     pairID=__a			)			)
      return examples






def    __UpperCAmelCase			(  a_:       List[InputExample],					a_:       List[str],					a_:       int,					a_:       PreTrainedTokenizer,					):
   _UpperCAmelCase							:	List[Any]							=   {label: i for i, label in enumerate(snake_case_							)}

   _UpperCAmelCase							:	List[Any]							=   []
   for ex_index, example in tqdm.tqdm(enumerate(snake_case_							),					desc="convert examples to features"							):
      if ex_index % 10_000 == 0:
         logger.info("Writing example %d" % (ex_index)							)

      _UpperCAmelCase							:	Dict							=   tokenizer(
          example.text_a,					example.text_b,					add_special_tokens=snake_case_,					max_length=snake_case_,					padding="max_length",					truncation=snake_case_,					return_overflowing_tokens=snake_case_,					)

      _UpperCAmelCase							:	Tuple							=   label_map[example.label] if example.label in label_map else 0

      _UpperCAmelCase							:	int							=   int(example.pairID							)

      features.append(InputFeatures(**snake_case_,					label=snake_case_,					pairID=snake_case_							)							)

   for i, example in enumerate(examples[:5]							):
      logger.info("*** Example ***"							)
      logger.info(f"""guid: {example}"""							)
      logger.info(f"""features: {features[i]}"""							)

   return features


__a										=					{
    'hans': 3,
}






__a										=					{
    'hans': HansProcessor,
}
'''simple docstring'''





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


SCREAMING_SNAKE_CASE_:     Dict  =logging.get_logger(__name__)

SCREAMING_SNAKE_CASE_:     Tuple  ={}




class        __A      ( UpperCamelCase__	):
    a__       :						int          =  """llama"""
    a__       :						Any          =  ["""past_key_values"""]



    def __init__(self    :    List[str]   ,			__a    :    List[str]=32000   ,			__a    :    Tuple=4096   ,			__a    :    List[Any]=11008   ,			__a    :    Dict=32   ,			__a    :    Tuple=32   ,			__a    :    Any=None   ,			__a    :    Any="silu"   ,			__a    :    List[Any]=2048   ,			__a    :    List[Any]=0.02   ,			__a    :    str=1E-6   ,			__a    :    Optional[Any]=True   ,			__a    :    Union[str, Any]=0   ,			__a    :    Any=1   ,			__a    :    Dict=2   ,			__a    :    Dict=1   ,			__a    :    str=False   ,			__a    :    str=None   ,			**__a    :    Optional[Any]   ,			):
         UpperCAmelCase_           =   vocab_size
         UpperCAmelCase_           =   max_position_embeddings
         UpperCAmelCase_           =   hidden_size
         UpperCAmelCase_           =   intermediate_size
         UpperCAmelCase_           =   num_hidden_layers
         UpperCAmelCase_           =   num_attention_heads

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

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

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






    def 					_lowercase						(self    :    List[str] ):
         if self.rope_scaling is None:
              return

         if not isinstance(self.rope_scaling   ,			__a ) 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}""" )
         UpperCAmelCase_           =   self.rope_scaling.get("type"   ,			__a )
         UpperCAmelCase_           =   self.rope_scaling.get("factor"   ,			__a )
         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(__a   ,			__a ) or rope_scaling_factor <= 1.0:
              raise ValueError(f"""`rope_scaling`'s factor field must be an float > 1, got {rope_scaling_factor}""" )




