from __future__ import annotations

import unittest

from transformers import DistilBertConfig, is_tf_available
from transformers.testing_utils import require_tf, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
      import tensorflow as tf

      from transformers.models.distilbert.modeling_tf_distilbert import (
          TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
          TFDistilBertForMaskedLM,
          TFDistilBertForMultipleChoice,
          TFDistilBertForQuestionAnswering,
          TFDistilBertForSequenceClassification,
          TFDistilBertForTokenClassification,
          TFDistilBertModel,
      )






class 		_lowerCamelCase		:
    def __init__(	self			,			lowerCAmelCase			,			)							->       List[Any]:
     SCREAMING_SNAKE_CASE__: List[Any]=   parent
     SCREAMING_SNAKE_CASE__: List[Any]=   13
     SCREAMING_SNAKE_CASE__: Dict=   7
     SCREAMING_SNAKE_CASE__: int=   True
     SCREAMING_SNAKE_CASE__: Dict=   True
     SCREAMING_SNAKE_CASE__: Optional[Any]=   False
     SCREAMING_SNAKE_CASE__: Union[str, Any]=   True
     SCREAMING_SNAKE_CASE__: str=   99
     SCREAMING_SNAKE_CASE__: List[str]=   32
     SCREAMING_SNAKE_CASE__: Union[str, Any]=   2
     SCREAMING_SNAKE_CASE__: List[str]=   4
     SCREAMING_SNAKE_CASE__: Union[str, Any]=   37
     SCREAMING_SNAKE_CASE__: int=   """gelu"""
     SCREAMING_SNAKE_CASE__: Dict=   0.1
     SCREAMING_SNAKE_CASE__: int=   0.1
     SCREAMING_SNAKE_CASE__: Dict=   512
     SCREAMING_SNAKE_CASE__: Any=   16
     SCREAMING_SNAKE_CASE__: List[str]=   2
     SCREAMING_SNAKE_CASE__: Tuple=   0.02
     SCREAMING_SNAKE_CASE__: Tuple=   3
     SCREAMING_SNAKE_CASE__: List[Any]=   4
     SCREAMING_SNAKE_CASE__: List[str]=   None
    def     UpperCamelCase_					(	self )							->       Union[str, Any]:
     SCREAMING_SNAKE_CASE__: int=   ids_tensor([self.batch_size, self.seq_length]			,			self.vocab_size )

     SCREAMING_SNAKE_CASE__: List[str]=   None
     if self.use_input_mask:
      SCREAMING_SNAKE_CASE__: List[str]=   random_attention_mask([self.batch_size, self.seq_length] )

     SCREAMING_SNAKE_CASE__: Dict=   None
     SCREAMING_SNAKE_CASE__: Optional[Any]=   None
     SCREAMING_SNAKE_CASE__: Any=   None
     if self.use_labels:
      SCREAMING_SNAKE_CASE__: List[str]=   ids_tensor([self.batch_size]			,			self.type_sequence_label_size )
      SCREAMING_SNAKE_CASE__: Optional[int]=   ids_tensor([self.batch_size, self.seq_length]			,			self.num_labels )
      SCREAMING_SNAKE_CASE__: List[str]=   ids_tensor([self.batch_size]			,			self.num_choices )

     SCREAMING_SNAKE_CASE__: Dict=   DistilBertConfig(
         vocab_size=self.vocab_size			,			dim=self.hidden_size			,			n_layers=self.num_hidden_layers			,			n_heads=self.num_attention_heads			,			hidden_dim=self.intermediate_size			,			hidden_act=self.hidden_act			,			dropout=self.hidden_dropout_prob			,			attention_dropout=self.attention_probs_dropout_prob			,			max_position_embeddings=self.max_position_embeddings			,			initializer_range=self.initializer_range			,			)

     return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels
    def     UpperCamelCase_					(	self			,			lowerCAmelCase			,			lowerCAmelCase			,			lowerCAmelCase			,			lowerCAmelCase			,			lowerCAmelCase			,			lowerCAmelCase )							->       int:
     SCREAMING_SNAKE_CASE__: Tuple=   TFDistilBertModel(config=__a )
     SCREAMING_SNAKE_CASE__: Tuple=   {"""input_ids""": input_ids, """attention_mask""": input_mask}

     SCREAMING_SNAKE_CASE__: Optional[int]=   model(__a )

     SCREAMING_SNAKE_CASE__: int=   [input_ids, input_mask]

     SCREAMING_SNAKE_CASE__: int=   model(__a )

     self.parent.assertEqual(result.last_hidden_state.shape			,			(self.batch_size, self.seq_length, self.hidden_size) )
    def     UpperCamelCase_					(	self			,			lowerCAmelCase			,			lowerCAmelCase			,			lowerCAmelCase			,			lowerCAmelCase			,			lowerCAmelCase			,			lowerCAmelCase )							->       Optional[int]:
     SCREAMING_SNAKE_CASE__: Dict=   TFDistilBertForMaskedLM(config=__a )
     SCREAMING_SNAKE_CASE__: Union[str, Any]=   {"""input_ids""": input_ids, """attention_mask""": input_mask}
     SCREAMING_SNAKE_CASE__: Union[str, Any]=   model(__a )
     self.parent.assertEqual(result.logits.shape			,			(self.batch_size, self.seq_length, self.vocab_size) )
    def     UpperCamelCase_					(	self			,			lowerCAmelCase			,			lowerCAmelCase			,			lowerCAmelCase			,			lowerCAmelCase			,			lowerCAmelCase			,			lowerCAmelCase )							->       str:
     SCREAMING_SNAKE_CASE__: List[str]=   TFDistilBertForQuestionAnswering(config=__a )
     SCREAMING_SNAKE_CASE__: List[str]=   {
         """input_ids""": input_ids,
         """attention_mask""": input_mask,
     }
     SCREAMING_SNAKE_CASE__: List[Any]=   model(__a )
     self.parent.assertEqual(result.start_logits.shape			,			(self.batch_size, self.seq_length) )
     self.parent.assertEqual(result.end_logits.shape			,			(self.batch_size, self.seq_length) )
    def     UpperCamelCase_					(	self			,			lowerCAmelCase			,			lowerCAmelCase			,			lowerCAmelCase			,			lowerCAmelCase			,			lowerCAmelCase			,			lowerCAmelCase )							->       Union[str, Any]:
     SCREAMING_SNAKE_CASE__: Optional[int]=   self.num_labels
     SCREAMING_SNAKE_CASE__: Dict=   TFDistilBertForSequenceClassification(__a )
     SCREAMING_SNAKE_CASE__: Tuple=   {"""input_ids""": input_ids, """attention_mask""": input_mask}
     SCREAMING_SNAKE_CASE__: int=   model(__a )
     self.parent.assertEqual(result.logits.shape			,			(self.batch_size, self.num_labels) )
    def     UpperCamelCase_					(	self			,			lowerCAmelCase			,			lowerCAmelCase			,			lowerCAmelCase			,			lowerCAmelCase			,			lowerCAmelCase			,			lowerCAmelCase )							->       Any:
     SCREAMING_SNAKE_CASE__: int=   self.num_choices
     SCREAMING_SNAKE_CASE__: int=   TFDistilBertForMultipleChoice(__a )
     SCREAMING_SNAKE_CASE__: str=   tf.tile(tf.expand_dims(__a			,			1 )			,			(1, self.num_choices, 1) )
     SCREAMING_SNAKE_CASE__: int=   tf.tile(tf.expand_dims(__a			,			1 )			,			(1, self.num_choices, 1) )
     SCREAMING_SNAKE_CASE__: Union[str, Any]=   {
         """input_ids""": multiple_choice_inputs_ids,
         """attention_mask""": multiple_choice_input_mask,
     }
     SCREAMING_SNAKE_CASE__: Dict=   model(__a )
     self.parent.assertEqual(result.logits.shape			,			(self.batch_size, self.num_choices) )
    def     UpperCamelCase_					(	self			,			lowerCAmelCase			,			lowerCAmelCase			,			lowerCAmelCase			,			lowerCAmelCase			,			lowerCAmelCase			,			lowerCAmelCase )							->       str:
     SCREAMING_SNAKE_CASE__: Dict=   self.num_labels
     SCREAMING_SNAKE_CASE__: Optional[int]=   TFDistilBertForTokenClassification(__a )
     SCREAMING_SNAKE_CASE__: List[Any]=   {"""input_ids""": input_ids, """attention_mask""": input_mask}
     SCREAMING_SNAKE_CASE__: str=   model(__a )
     self.parent.assertEqual(result.logits.shape			,			(self.batch_size, self.seq_length, self.num_labels) )



    def     UpperCamelCase_					(	self )							->       Optional[Any]:
     SCREAMING_SNAKE_CASE__: str=   self.prepare_config_and_inputs()
     (SCREAMING_SNAKE_CASE__): Dict=   config_and_inputs
     SCREAMING_SNAKE_CASE__: Optional[int]=   {"""input_ids""": input_ids, """attention_mask""": input_mask}
     return config, inputs_dict






@require_tf
class 		_lowerCamelCase		( a__     ,  a__     ,  unittest.TestCase     ):
    __a						=   (
        (
            TFDistilBertModel,
            TFDistilBertForMaskedLM,
            TFDistilBertForQuestionAnswering,
            TFDistilBertForSequenceClassification,
            TFDistilBertForTokenClassification,
            TFDistilBertForMultipleChoice,
        )
        if is_tf_available()
        else None
    )
    __a						=   (
        {
            "feature-extraction": TFDistilBertModel,
            "fill-mask": TFDistilBertForMaskedLM,
            "question-answering": TFDistilBertForQuestionAnswering,
            "text-classification": TFDistilBertForSequenceClassification,
            "token-classification": TFDistilBertForTokenClassification,
            "zero-shot": TFDistilBertForSequenceClassification,
        }
        if is_tf_available()
        else {}
    )
    __a						=   False
    __a						=   False
    def     UpperCamelCase_					(	self )							->       List[str]:
     SCREAMING_SNAKE_CASE__: List[Any]=   TFDistilBertModelTester(self )
     SCREAMING_SNAKE_CASE__: Dict=   ConfigTester(self			,			config_class=__a			,			dim=37 )
    def     UpperCamelCase_					(	self )							->       Optional[Any]:
     self.config_tester.run_common_tests()
    def     UpperCamelCase_					(	self )							->       Optional[int]:
     SCREAMING_SNAKE_CASE__: int=   self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_distilbert_model(*__a )
    def     UpperCamelCase_					(	self )							->       Union[str, Any]:
     SCREAMING_SNAKE_CASE__: List[str]=   self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_distilbert_for_masked_lm(*__a )
    def     UpperCamelCase_					(	self )							->       List[str]:
     SCREAMING_SNAKE_CASE__: List[str]=   self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_distilbert_for_question_answering(*__a )
    def     UpperCamelCase_					(	self )							->       List[str]:
     SCREAMING_SNAKE_CASE__: List[str]=   self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_distilbert_for_sequence_classification(*__a )
    def     UpperCamelCase_					(	self )							->       List[str]:
     SCREAMING_SNAKE_CASE__: Optional[int]=   self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_distilbert_for_multiple_choice(*__a )
    def     UpperCamelCase_					(	self )							->       Tuple:
     SCREAMING_SNAKE_CASE__: Optional[int]=   self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_distilbert_for_token_classification(*__a )



    @slow
    def     UpperCamelCase_					(	self )							->       Optional[Any]:
     for model_name in list(TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1] ):
      SCREAMING_SNAKE_CASE__: Optional[Any]=   TFDistilBertModel.from_pretrained(__a )
      self.assertIsNotNone(__a )






@require_tf
class 		_lowerCamelCase		( unittest.TestCase     ):
    @slow
    def     UpperCamelCase_					(	self )							->       str:
     SCREAMING_SNAKE_CASE__: Union[str, Any]=   TFDistilBertModel.from_pretrained('''distilbert-base-uncased''' )
     SCREAMING_SNAKE_CASE__: Any=   tf.constant([[0, 1, 2, 3, 4, 5]] )
     SCREAMING_SNAKE_CASE__: Optional[Any]=   model(__a )[0]

     SCREAMING_SNAKE_CASE__: Union[str, Any]=   [1, 6, 768]
     self.assertEqual(output.shape			,			__a )

     SCREAMING_SNAKE_CASE__: Any=   tf.constant(
         [
             [
                 [0.19261885, -0.13732955, 0.4119799],
                 [0.22150156, -0.07422661, 0.39037204],
                 [0.22756018, -0.0896414, 0.3701467],
             ]
         ] )
     tf.debugging.assert_near(output[:, :3, :3]			,			__a			,			atol=1e-4 )





import os
import time
import warnings
from dataclasses import dataclass, field
from enum import Enum
from typing import List, Optional, Union

import torch
from filelock import FileLock
from torch.utils.data import Dataset

from ...tokenization_utils_base import PreTrainedTokenizerBase
from ...utils import logging
from ..processors.glue import glue_convert_examples_to_features, glue_output_modes, glue_processors
from ..processors.utils import InputFeatures


snake_case__				:	str					       =					logging.get_logger(__name__)





@dataclass
class   SCREAMING_SNAKE_CASE_			:




       '''simple docstring'''



       _a   							=							field(metadata={"help": "The name of the task to train on: " + ", ".join(glue_processors.keys()						)}						)
       _a   							=							field(
           metadata={"help": "The input data dir. Should contain the .tsv files (or other data files) for the task."}						)
       _a   							=							field(
           default=128						,       metadata={
               "help": (
                   "The maximum total input sequence length after tokenization. Sequences longer "
                   "than this will be truncated, sequences shorter will be padded."
               )
           }						,       )
       _a   							=							field(
           default=a__						,       metadata={"help": "Overwrite the cached training and evaluation sets"}						)



       def 				_lowerCAmelCase							(						self				:				Union[str, Any]							)					->Union[str, Any]:
          lowerCamelCase_						:   Optional[Any]		= self.task_name.lower()







class   SCREAMING_SNAKE_CASE_			(a__						):




       '''simple docstring'''



       _a   							=							"train"
       _a   							=							"dev"
       _a   							=							"test"







class   SCREAMING_SNAKE_CASE_			(a__						):




       '''simple docstring'''



       _a   							=							42
       _a   							=							42
       _a   							=							42



       def __init__(						self				:				Any		,				__a				:				GlueDataTrainingArguments		,				__a				:				PreTrainedTokenizerBase		,				__a				:				Optional[int] = None		,				__a				:				Union[str, Split] = Split.train		,				__a				:				Optional[str] = None		,				)					->Optional[int]:
          warnings.warn(
              """This dataset will be removed from the library soon, preprocessing should be handled with the 🤗 Datasets """
              """library. You can have a look at this example script for pointers: """
              """https://github.com/huggingface/transformers/blob/main/examples/pytorch/text-classification/run_glue.py"""		,				__a		,				)
          lowerCamelCase_						:   Optional[int]		= args
          lowerCamelCase_						:   Tuple		= glue_processors[args.task_name]()
          lowerCamelCase_						:   Optional[Any]		= glue_output_modes[args.task_name]
          if isinstance(__a		,				__a							):
             try:
                lowerCamelCase_						:   List[Any]		= Split[mode]
             except KeyError:
                raise KeyError("""mode is not a valid split name"""							)
        # Load data features from cache or dataset file
          lowerCamelCase_						:   List[Any]		= os.path.join(
              cache_dir if cache_dir is not None else args.data_dir		,				F'''cached_{mode.value}_{tokenizer.__class__.__name__}_{args.max_seq_length}_{args.task_name}'''		,				)
          lowerCamelCase_						:   Any		= self.processor.get_labels()
          if args.task_name in ["mnli", "mnli-mm"] and tokenizer.__class__.__name__ in (
              "RobertaTokenizer",
              "RobertaTokenizerFast",
              "XLMRobertaTokenizer",
              "BartTokenizer",
              "BartTokenizerFast",
          ):
             # HACK(label indices are swapped in RoBERTa pretrained model)
             lowerCamelCase_,	lowerCamelCase_						:   int		= label_list[2], label_list[1]
          lowerCamelCase_						:   Any		= label_list

          # Make sure only the first process in distributed training processes the dataset,
          # and the others will use the cache.
          lowerCamelCase_						:   List[Any]		= cached_features_file + """.lock"""
          with FileLock(__a							):
             if os.path.exists(__a							) and not args.overwrite_cache:
                lowerCamelCase_						:   str		= time.time()
                lowerCamelCase_						:   int		= torch.load(__a							)
                logger.info(
                    F'''Loading features from cached file {cached_features_file} [took %.3f s]'''		,				time.time() - start							)
             else:
                logger.info(F'''Creating features from dataset file at {args.data_dir}'''							)

                if mode == Split.dev:
                   lowerCamelCase_						:   List[Any]		= self.processor.get_dev_examples(args.data_dir							)
                elif mode == Split.test:
                   lowerCamelCase_						:   Tuple		= self.processor.get_test_examples(args.data_dir							)
                else:
                   lowerCamelCase_						:   List[Any]		= self.processor.get_train_examples(args.data_dir							)
                if limit_length is not None:
                   lowerCamelCase_						:   Dict		= examples[:limit_length]
                lowerCamelCase_						:   Union[str, Any]		= glue_convert_examples_to_features(
                    __a		,				__a		,				max_length=args.max_seq_length		,				label_list=__a		,				output_mode=self.output_mode		,				)
                lowerCamelCase_						:   Optional[Any]		= time.time()
                torch.save(self.features		,				__a							)
                # ^ This seems to take a lot of time so I want to investigate why and how we can improve.
                logger.info(
                    F'''Saving features into cached file {cached_features_file} [took {time.time() - start:.3f} s]'''							)



       def __len__(						self				:				Any							)					->Any:
          return len(self.features							)



       def __getitem__(						self				:				List[Any]		,				__a				:				Optional[int]							)					->InputFeatures:
          return self.features[i]




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





