





import unittest

import numpy as np

from transformers import RobertaPreLayerNormConfig, is_flax_available
from transformers.testing_utils import require_flax, slow

from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask


if is_flax_available():
    import jax.numpy as jnp

    from transformers.models.roberta_prelayernorm.modeling_flax_roberta_prelayernorm import (
        FlaxRobertaPreLayerNormForCausalLM,
        FlaxRobertaPreLayerNormForMaskedLM,
        FlaxRobertaPreLayerNormForMultipleChoice,
        FlaxRobertaPreLayerNormForQuestionAnswering,
        FlaxRobertaPreLayerNormForSequenceClassification,
        FlaxRobertaPreLayerNormForTokenClassification,
        FlaxRobertaPreLayerNormModel,
    )

class 		SCREAMING_SNAKE_CASE__				(       unittest.TestCase  ):


      def __init__(self       :      List[Any]				,			a__       :      Optional[int]				,			a__       :      Optional[int]=13				,			a__       :      List[Any]=7				,			a__       :      Dict=True				,			a__       :      Optional[Any]=True				,			a__       :      List[Any]=True				,			a__       :      Optional[Any]=True				,			a__       :      Optional[int]=99				,			a__       :      Optional[Any]=32				,			a__       :      List[str]=5				,			a__       :      Any=4				,			a__       :      str=37				,			a__       :      Optional[int]="gelu"				,			a__       :      Optional[Any]=0.1				,			a__       :      Dict=0.1				,			a__       :      Any=512				,			a__       :      Union[str, Any]=16				,			a__       :      Any=2				,			a__       :      Optional[int]=0.0_2				,			a__       :      Optional[int]=4				,			):





         """simple docstring"""



         __snake_case							       =   parent
         __snake_case							       =   batch_size
         __snake_case							       =   seq_length
         __snake_case							       =   is_training
         __snake_case							       =   use_attention_mask
         __snake_case							       =   use_token_type_ids
         __snake_case							       =   use_labels
         __snake_case							       =   vocab_size
         __snake_case							       =   hidden_size
         __snake_case							       =   num_hidden_layers
         __snake_case							       =   num_attention_heads
         __snake_case							       =   intermediate_size
         __snake_case							       =   hidden_act
         __snake_case							       =   hidden_dropout_prob
         __snake_case							       =   attention_probs_dropout_prob
         __snake_case							       =   max_position_embeddings
         __snake_case							       =   type_vocab_size
         __snake_case							       =   type_sequence_label_size
         __snake_case							       =   initializer_range
         __snake_case							       =   num_choices


      def    a (self       :      Union[str, Any]      ):





         """simple docstring"""



         __snake_case							       =   ids_tensor([self.batch_size, self.seq_length]				,			self.vocab_size      )

         __snake_case							       =   None
         if self.use_attention_mask:
            __snake_case							       =   random_attention_mask([self.batch_size, self.seq_length]      )

         __snake_case							       =   None
         if self.use_token_type_ids:
            __snake_case							       =   ids_tensor([self.batch_size, self.seq_length]				,			self.type_vocab_size      )

         __snake_case							       =   RobertaPreLayerNormConfig(
             vocab_size=self.vocab_size				,			hidden_size=self.hidden_size				,			num_hidden_layers=self.num_hidden_layers				,			num_attention_heads=self.num_attention_heads				,			intermediate_size=self.intermediate_size				,			hidden_act=self.hidden_act				,			hidden_dropout_prob=self.hidden_dropout_prob				,			attention_probs_dropout_prob=self.attention_probs_dropout_prob				,			max_position_embeddings=self.max_position_embeddings				,			type_vocab_size=self.type_vocab_size				,			is_decoder=a__				,			initializer_range=self.initializer_range				,			)

         return config, input_ids, token_type_ids, attention_mask


      def    a (self       :      List[Any]      ):





         """simple docstring"""



         __snake_case							       =   self.prepare_config_and_inputs()
         __snake_case       ,	__snake_case       ,	__snake_case       ,	__snake_case							       =   config_and_inputs
         __snake_case							       =   {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': attention_mask}
         return config, inputs_dict


      def    a (self       :      Dict      ):





         """simple docstring"""



         __snake_case							       =   self.prepare_config_and_inputs()
         __snake_case       ,	__snake_case       ,	__snake_case       ,	__snake_case							       =   config_and_inputs

         __snake_case							       =   True
         __snake_case							       =   floats_tensor([self.batch_size, self.seq_length, self.hidden_size]      )
         __snake_case							       =   ids_tensor([self.batch_size, self.seq_length]				,			vocab_size=2      )

         return (
             config,
             input_ids,
             token_type_ids,
             encoder_hidden_states,
             encoder_attention_mask,
         )






@require_flax
# Copied from tests.models.roberta.test_modelling_flax_roberta.FlaxRobertaPreLayerNormModelTest with ROBERTA->ROBERTA_PRELAYERNORM,Roberta->RobertaPreLayerNorm,roberta-base->andreasmadsen/efficient_mlm_m0.40
class 		SCREAMING_SNAKE_CASE__				(       _UpperCAmelCase						,      unittest.TestCase  ):
      A_						:				Any							=    True

      A_						:				Optional[Any]							=    (
          (
              FlaxRobertaPreLayerNormModel,
              FlaxRobertaPreLayerNormForCausalLM,
              FlaxRobertaPreLayerNormForMaskedLM,
              FlaxRobertaPreLayerNormForSequenceClassification,
              FlaxRobertaPreLayerNormForTokenClassification,
              FlaxRobertaPreLayerNormForMultipleChoice,
              FlaxRobertaPreLayerNormForQuestionAnswering,
          )
          if is_flax_available()
          else ()
      )


      def    a (self       :      Dict      ):





         """simple docstring"""



         __snake_case							       =   FlaxRobertaPreLayerNormModelTester(self      )


      @slow
      def    a (self       :      List[Any]      ):





         """simple docstring"""



         for model_class_name in self.all_model_classes:
            __snake_case							       =   model_class_name.from_pretrained('''andreasmadsen/efficient_mlm_m0.40'''				,			from_pt=a__      )
            __snake_case							       =   model(np.ones((1, 1)      )      )
            self.assertIsNotNone(a__      )






@require_flax
class 		SCREAMING_SNAKE_CASE__				(       unittest.TestCase  ):


      @slow
      def    a (self       :      str      ):





         """simple docstring"""



         __snake_case							       =   FlaxRobertaPreLayerNormForMaskedLM.from_pretrained('''andreasmadsen/efficient_mlm_m0.40'''				,			from_pt=a__      )

         __snake_case							       =   np.array([[0, 3_1414, 232, 328, 740, 1140, 1_2695, 69, 4_6078, 1588, 2]]				,			dtype=jnp.intaa      )
         __snake_case							       =   model(a__      )[0]
         __snake_case							       =   [1, 11, 5_0265]
         self.assertEqual(list(output.shape      )				,			a__      )
         # compare the actual values for a slice.
         __snake_case							       =   np.array(
             [[[4_0.4_8_8_0, 1_8.0_1_9_9, -5.2_3_6_7], [-1.8_8_7_7, -4.0_8_8_5, 1_0.7_0_8_5], [-2.2_6_1_3, -5.6_1_1_0, 7.2_6_6_5]]]				,			dtype=np.floataa      )
         self.assertTrue(np.allclose(output[:, :3, :3]				,			a__				,			atol=1E-4      )      )


      @slow
      def    a (self       :      Any      ):





         """simple docstring"""



         __snake_case							       =   FlaxRobertaPreLayerNormModel.from_pretrained('''andreasmadsen/efficient_mlm_m0.40'''				,			from_pt=a__      )

         __snake_case							       =   np.array([[0, 3_1414, 232, 328, 740, 1140, 1_2695, 69, 4_6078, 1588, 2]]				,			dtype=jnp.intaa      )
         __snake_case							       =   model(a__      )[0]
         # compare the actual values for a slice.
         __snake_case							       =   np.array(
             [[[0.0_2_0_8, -0.0_3_5_6, 0.0_2_3_7], [-0.1_5_6_9, -0.0_4_1_1, -0.2_6_2_6], [0.1_8_7_9, 0.0_1_2_5, -0.0_0_8_9]]]				,			dtype=np.floataa      )
         self.assertTrue(np.allclose(output[:, :3, :3]				,			a__				,			atol=1E-4      )      )








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,
)


snake_case_				=			logging.getLogger(__name__)

@dataclass(frozen=_UpperCAmelCase  )
class 		SCREAMING_SNAKE_CASE__				:
      A_						:				str
      A_						:				str
      A_						:				Optional[str]							=    None
      A_						:				Optional[str]							=    None
      A_						:				Optional[str]							=    None






@dataclass(frozen=_UpperCAmelCase  )
class 		SCREAMING_SNAKE_CASE__				:
      A_						:				List[int]
      A_						:				Optional[List[int]]							=    None
      A_						:				Optional[List[int]]							=    None
      A_						:				Optional[Union[int, float]]							=    None
      A_						:				Optional[int]							=    None


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

    class 		SCREAMING_SNAKE_CASE__				(       _UpperCAmelCase  ):
          A_						:				List[InputFeatures]


          def __init__(self       :      int				,			a__       :      str				,			a__       :      PreTrainedTokenizer				,			a__       :      str				,			a__       :      Optional[int] = None				,			a__       :      List[Any]=False				,			a__       :      bool = False				,			):





             """simple docstring"""



             __snake_case							       =   hans_processors[task]()

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

             # Make sure only the first process in distributed training processes the dataset,
             # and the others will use the cache.
             __snake_case							       =   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}"""      )
                   __snake_case							       =   torch.load(a__      )
                else:
                   logger.info(f"""Creating features from dataset file at {data_dir}"""      )

                   __snake_case							       =   (
                       processor.get_dev_examples(a__      ) if evaluate else processor.get_train_examples(a__      )
                   )

                   logger.info('''Training examples: %s'''				,			len(a__      )      )
                   __snake_case							       =   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       :      int      ):





             """simple docstring"""



             return len(self.features      )


          def __getitem__(self       :      Dict				,			a__       :      List[Any]      ):





             """simple docstring"""



             return self.features[i]


          def    a (self       :      List[Any]      ):





             """simple docstring"""



             return self.label_list


if is_tf_available():
    import tensorflow as tf

    class 		SCREAMING_SNAKE_CASE__				:
          A_						:				List[InputFeatures]


          def __init__(self       :      Tuple				,			a__       :      str				,			a__       :      PreTrainedTokenizer				,			a__       :      str				,			a__       :      Optional[int] = 128				,			a__       :      Any=False				,			a__       :      bool = False				,			):





             """simple docstring"""



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

             __snake_case							       =   processor.get_dev_examples(a__      ) if evaluate else processor.get_train_examples(a__      )
             __snake_case							       =   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_0000 == 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,
                   )

             __snake_case							       =   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    a (self       :      Union[str, Any]      ):





             """simple docstring"""



             return self.dataset


          def __len__(self       :      Dict      ):





             """simple docstring"""



             return len(self.features      )


          def __getitem__(self       :      Any				,			a__       :      Dict      ):





             """simple docstring"""



             return self.features[i]


          def    a (self       :      str      ):





             """simple docstring"""



             return self.label_list

class 		SCREAMING_SNAKE_CASE__				(       _UpperCAmelCase  ):


      def    a (self       :      Dict				,			a__       :      Dict      ):





         """simple docstring"""



         return self._create_examples(self._read_tsv(os.path.join(a__				,			'''heuristics_train_set.txt'''      )      )				,			'''train'''      )


      def    a (self       :      Optional[int]				,			a__       :      Tuple      ):





         """simple docstring"""



         return self._create_examples(self._read_tsv(os.path.join(a__				,			'''heuristics_evaluation_set.txt'''      )      )				,			'''dev'''      )


      def    a (self       :      int      ):





         """simple docstring"""



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


      def    a (self       :      Any				,			a__       :      Optional[int]				,			a__       :      List[Any]      ):





         """simple docstring"""



         __snake_case							       =   []
         for i, line in enumerate(a__      ):
            if i == 0:
               continue
            __snake_case							       =   '''%s-%s''' % (set_type, line[0])
            __snake_case							       =   line[5]
            __snake_case							       =   line[6]
            __snake_case							       =   line[7][2:] if line[7].startswith('''ex'''      ) else line[7]
            __snake_case							       =   line[0]
            examples.append(InputExample(guid=a__				,			text_a=a__				,			text_b=a__				,			label=a__				,			pairID=a__      )      )
         return examples






def lowerCamelCase__    (							snake_case_	:  List[InputExample]       ,      snake_case_	:  List[str]       ,      snake_case_	:  int       ,      snake_case_	:  PreTrainedTokenizer       ,      )      ->				List[str]:
   __snake_case							       =   {label: i for i, label in enumerate(snake_case_       )}

   __snake_case							       =   []
   for ex_index, example in tqdm.tqdm(enumerate(snake_case_       )       ,      desc='''convert examples to features'''       ):
      if ex_index % 1_0000 == 0:
         logger.info('''Writing example %d''' % (ex_index)       )

      __snake_case							       =   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_       ,      )

      __snake_case							       =   label_map[example.label] if example.label in label_map else 0

      __snake_case							       =   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


snake_case_				=			{
    'hans': 3,
}







snake_case_				=			{
    'hans': HansProcessor,
}

