"""simple docstring"""



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

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

from ...models.auto.modeling_auto import MODEL_FOR_QUESTION_ANSWERING_MAPPING
from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging
from ..processors.squad import SquadFeatures, SquadVaProcessor, SquadVaProcessor, squad_convert_examples_to_features


__lowercase		:		int								=				logging.get_logger(__name__)

__lowercase		:		Optional[int]								=				list(MODEL_FOR_QUESTION_ANSWERING_MAPPING.keys())
__lowercase		:		Dict								=				tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)



@dataclass
class   _A						:




    """simple docstring"""




    UpperCamelCase_						:       str      					=       field(
        default=_UpperCAmelCase				,			metadata={'''help''': '''Model type selected in the list: ''' + ''', '''.join(_UpperCAmelCase       )}       )
    UpperCamelCase_						:       str      					=       field(
        default=_UpperCAmelCase				,			metadata={'''help''': '''The input data dir. Should contain the .json files for the SQuAD task.'''}       )
    UpperCamelCase_						:       int      					=       field(
        default=1_2_8				,			metadata={
            '''help''': (
                '''The maximum total input sequence length after tokenization. Sequences longer '''
                '''than this will be truncated, sequences shorter will be padded.'''
            )
        }				,			)
    UpperCamelCase_						:       int      					=       field(
        default=1_2_8				,			metadata={'''help''': '''When splitting up a long document into chunks, how much stride to take between chunks.'''}				,			)
    UpperCamelCase_						:       int      					=       field(
        default=6_4				,			metadata={
            '''help''': (
                '''The maximum number of tokens for the question. Questions longer than this will '''
                '''be truncated to this length.'''
            )
        }				,			)
    UpperCamelCase_						:       int      					=       field(
        default=3_0				,			metadata={
            '''help''': (
                '''The maximum length of an answer that can be generated. This is needed because the start '''
                '''and end predictions are not conditioned on one another.'''
            )
        }				,			)
    UpperCamelCase_						:       bool      					=       field(
        default=_UpperCAmelCase				,			metadata={'''help''': '''Overwrite the cached training and evaluation sets'''}       )
    UpperCamelCase_						:       bool      					=       field(
        default=_UpperCAmelCase				,			metadata={'''help''': '''If true, the SQuAD examples contain some that do not have an answer.'''}       )
    UpperCamelCase_						:       float      					=       field(
        default=0.0				,			metadata={'''help''': '''If null_score - best_non_null is greater than the threshold predict null.'''}       )
    UpperCamelCase_						:       int      					=       field(
        default=2_0				,			metadata={'''help''': '''If null_score - best_non_null is greater than the threshold predict null.'''}       )
    UpperCamelCase_						:       int      					=       field(
        default=0				,			metadata={
            '''help''': (
                '''language id of input for language-specific xlm models (see'''
                ''' tokenization_xlm.PRETRAINED_INIT_CONFIGURATION)'''
            )
        }				,			)
    UpperCamelCase_						:       int      					=       field(default=1				,			metadata={'''help''': '''multiple threads for converting example to features'''}       )






class   _A						(    _UpperCAmelCase       ):




    """simple docstring"""




    UpperCamelCase_						:       List[str]      					=       'train'
    UpperCamelCase_						:       Any      					=       'dev'






class   _A						(    _UpperCAmelCase       ):




    """simple docstring"""




    UpperCamelCase_						:       SquadDataTrainingArguments
    UpperCamelCase_						:       List[SquadFeatures]
    UpperCamelCase_						:       Split
    UpperCamelCase_						:       bool
    def __init__(		self				:  int						,   A_				:  SquadDataTrainingArguments						,   A_				:  PreTrainedTokenizer						,   A_				:  Optional[int] = None						,   A_				:  Union[str, Split] = Split.train						,   A_				:  Optional[bool] = False						,   A_				:  Optional[str] = None						,   A_				:  Optional[str] = "pt"						,   )     ->							List[Any]:
         __snake_case				=				args
         __snake_case				=				is_language_sensitive
         __snake_case				=				SquadVaProcessor() if args.version_2_with_negative else SquadVaProcessor()
         if isinstance(A_						,   A_     ):
              try:
                   __snake_case				=				Split[mode]
              except KeyError:
                   raise KeyError('''mode is not a valid split name'''     )
         __snake_case				=				mode
         # Load data features from cache or dataset file
         __snake_case				=				"v2" if args.version_2_with_negative else "v1"
         __snake_case				=				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}_{version_tag}"						,   )

         # 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 args.overwrite_cache:
                   __snake_case				=				time.time()
                   __snake_case				=				torch.load(A_     )

                   # Legacy cache files have only features, while new cache files
                   # will have dataset and examples also.
                   __snake_case				=				self.old_features["features"]
                   __snake_case				=				self.old_features.get('''dataset'''						,   A_     )
                   __snake_case				=				self.old_features.get('''examples'''						,   A_     )
                   logger.info(
                       f"Loading features from cached file {cached_features_file} [took %.3f s]"						,   time.time() - start     )

                   if self.dataset is None or self.examples is None:
                        logger.warning(
                            f"Deleting cached file {cached_features_file} will allow dataset and examples to be cached in"
                            ''' future run'''     )
              else:
                   if mode == Split.dev:
                        __snake_case				=				self.processor.get_dev_examples(args.data_dir     )
                   else:
                        __snake_case				=				self.processor.get_train_examples(args.data_dir     )

                   __snake_case				=				squad_convert_examples_to_features(
                       examples=self.examples						,   tokenizer=A_						,   max_seq_length=args.max_seq_length						,   doc_stride=args.doc_stride						,   max_query_length=args.max_query_length						,   is_training=mode == Split.train						,   threads=args.threads						,   return_dataset=A_						,   )

                   __snake_case				=				time.time()
                   torch.save(
                       {'''features''': self.features, '''dataset''': self.dataset, '''examples''': self.examples}						,   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				:  Dict     )     ->							Optional[Any]:
         return len(self.features     )







    def __getitem__(		self				:  List[Any]						,   A_				:  str     )     ->							Tuple:
         __snake_case				=				self.features[i]

         __snake_case				=				torch.tensor(feature.input_ids						,   dtype=torch.long     )
         __snake_case				=				torch.tensor(feature.attention_mask						,   dtype=torch.long     )
         __snake_case				=				torch.tensor(feature.token_type_ids						,   dtype=torch.long     )
         __snake_case				=				torch.tensor(feature.cls_index						,   dtype=torch.long     )
         __snake_case				=				torch.tensor(feature.p_mask						,   dtype=torch.float     )
         __snake_case				=				torch.tensor(feature.is_impossible						,   dtype=torch.float     )

         __snake_case				=				{
             "input_ids": input_ids,
             "attention_mask": attention_mask,
             "token_type_ids": token_type_ids,
         }

         if self.args.model_type in ["xlm", "roberta", "distilbert", "camembert"]:
              del inputs["token_type_ids"]

         if self.args.model_type in ["xlnet", "xlm"]:
              inputs.update({'''cls_index''': cls_index, '''p_mask''': p_mask}     )
              if self.args.version_2_with_negative:
                   inputs.update({'''is_impossible''': is_impossible}     )
              if self.is_language_sensitive:
                   inputs.update({'''langs''': (torch.ones(input_ids.shape						,   dtype=torch.intaa     ) * self.args.lang_id)}     )

         if self.mode == Split.train:
              __snake_case				=				torch.tensor(feature.start_position						,   dtype=torch.long     )
              __snake_case				=				torch.tensor(feature.end_position						,   dtype=torch.long     )
              inputs.update({'''start_positions''': start_positions, '''end_positions''': end_positions}     )

         return inputs







'''simple docstring'''
from __future__ import annotations

import inspect
import unittest

import numpy as np

from transformers import DeiTConfig
from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import cached_property, is_tf_available, is_vision_available

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


if is_tf_available():
 import tensorflow as tf

 from transformers import (
     TFDeiTForImageClassification,
     TFDeiTForImageClassificationWithTeacher,
     TFDeiTForMaskedImageModeling,
     TFDeiTModel,
 )
 from transformers.models.deit.modeling_tf_deit import TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
 from PIL import Image

 from transformers import DeiTImageProcessor


class 							_UpperCAmelCase    :




    def __init__(      self	:							int	,  a	:							Dict	,  a	:							Optional[Any]=1_3	,  a	:							str=3_0	,  a	:							Dict=2	,  a	:							List[Any]=3	,  a	:							Optional[int]=True	,  a	:							Tuple=True	,  a	:							List[Any]=3_2	,  a	:							int=2	,  a	:							List[str]=4	,  a	:							Dict=3_7	,  a	:							Optional[Any]="gelu"	,  a	:							List[str]=0.1	,  a	:							Dict=0.1	,  a	:							List[Any]=1_0	,  a	:							Union[str, Any]=0.02	,  a	:							Union[str, Any]=3	,  a	:							int=None	,  a	:							Any=2	,  ):






       '''simple docstring'''






       lowercase_						:     Any							     =  parent
       lowercase_						:     Union[str, Any]							     =  batch_size
       lowercase_						:     Any							     =  image_size
       lowercase_						:     str							     =  patch_size
       lowercase_						:     int							     =  num_channels
       lowercase_						:     str							     =  is_training
       lowercase_						:     str							     =  use_labels
       lowercase_						:     List[Any]							     =  hidden_size
       lowercase_						:     List[str]							     =  num_hidden_layers
       lowercase_						:     Dict							     =  num_attention_heads
       lowercase_						:     Optional[int]							     =  intermediate_size
       lowercase_						:     str							     =  hidden_act
       lowercase_						:     Union[str, Any]							     =  hidden_dropout_prob
       lowercase_						:     List[str]							     =  attention_probs_dropout_prob
       lowercase_						:     List[str]							     =  type_sequence_label_size
       lowercase_						:     List[Any]							     =  initializer_range
       lowercase_						:     str							     =  scope
       lowercase_						:     Tuple							     =  encoder_stride

       # in DeiT, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distilation tokens)
       lowercase_						:     Any							     =  (image_size // patch_size) ** 2
       lowercase_						:     str							     =  num_patches + 2




    def 					lowerCAmelCase__					(      self	:							Dict      ):






       '''simple docstring'''






       lowercase_						:     Any							     =  floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]      )

       lowercase_						:     List[Any]							     =  None
       if self.use_labels:
          lowercase_						:     int							     =  ids_tensor([self.batch_size]	,  self.type_sequence_label_size      )

       lowercase_						:     Optional[Any]							     =  self.get_config()

       return config, pixel_values, labels




    def 					lowerCAmelCase__					(      self	:							Dict      ):






       '''simple docstring'''






       return DeiTConfig(
           image_size=self.image_size	,  patch_size=self.patch_size	,  num_channels=self.num_channels	,  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	,  is_decoder=a	,  initializer_range=self.initializer_range	,  encoder_stride=self.encoder_stride	,  )




    def 					lowerCAmelCase__					(      self	:							Any	,  a	:							List[str]	,  a	:							str	,  a	:							Tuple      ):






       '''simple docstring'''






       lowercase_						:     List[str]							     =  TFDeiTModel(config=a      )
       lowercase_						:     int							     =  model(a      )
       self.parent.assertEqual(result.last_hidden_state.shape	,  (self.batch_size, self.seq_length, self.hidden_size)      )




    def 					lowerCAmelCase__					(      self	:							Dict	,  a	:							Optional[int]	,  a	:							List[Any]	,  a	:							Union[str, Any]      ):






       '''simple docstring'''






       lowercase_						:     List[str]							     =  TFDeiTForMaskedImageModeling(config=a      )
       lowercase_						:     Union[str, Any]							     =  model(a      )
       self.parent.assertEqual(
           result.reconstruction.shape	,  (self.batch_size, self.num_channels, self.image_size, self.image_size)      )

       # test greyscale images
       lowercase_						:     Dict							     =  1
       lowercase_						:     Tuple							     =  TFDeiTForMaskedImageModeling(a      )

       lowercase_						:     Tuple							     =  floats_tensor([self.batch_size, 1, self.image_size, self.image_size]      )
       lowercase_						:     Dict							     =  model(a      )
       self.parent.assertEqual(result.reconstruction.shape	,  (self.batch_size, 1, self.image_size, self.image_size)      )




    def 					lowerCAmelCase__					(      self	:							int	,  a	:							List[str]	,  a	:							List[str]	,  a	:							Optional[int]      ):






       '''simple docstring'''






       lowercase_						:     str							     =  self.type_sequence_label_size
       lowercase_						:     Union[str, Any]							     =  TFDeiTForImageClassification(a      )
       lowercase_						:     int							     =  model(a	,  labels=a      )
       self.parent.assertEqual(result.logits.shape	,  (self.batch_size, self.type_sequence_label_size)      )

       # test greyscale images
       lowercase_						:     Dict							     =  1
       lowercase_						:     str							     =  TFDeiTForImageClassification(a      )

       lowercase_						:     Tuple							     =  floats_tensor([self.batch_size, 1, self.image_size, self.image_size]      )
       lowercase_						:     Any							     =  model(a	,  labels=a      )
       self.parent.assertEqual(result.logits.shape	,  (self.batch_size, self.type_sequence_label_size)      )





    def 					lowerCAmelCase__					(      self	:							Tuple      ):






       '''simple docstring'''






       lowercase_						:     Dict							     =  self.prepare_config_and_inputs()
       lowercase_     ,		lowercase_     ,		lowercase_						:     Optional[int]							     =  config_and_inputs
       lowercase_						:     Optional[Any]							     =  {"pixel_values": pixel_values}
       return config, inputs_dict


@require_tf
class 							_UpperCAmelCase    (		snake_case					,       snake_case					,       unittest.TestCase      ):
    __lowerCamelCase: Tuple									=     (
        (
            TFDeiTModel,
            TFDeiTForImageClassification,
            TFDeiTForImageClassificationWithTeacher,
            TFDeiTForMaskedImageModeling,
        )
        if is_tf_available()
        else ()
    )
    __lowerCamelCase: Tuple									=     (
        {
            'feature-extraction': TFDeiTModel,
            'image-classification': (TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher),
        }
        if is_tf_available()
        else {}
    )

    __lowerCamelCase: Union[str, Any]									=     False
    __lowerCamelCase: Any									=     False
    __lowerCamelCase: List[str]									=     False
    __lowerCamelCase: Optional[Any]									=     False




    def 					lowerCAmelCase__					(      self	:							int      ):






       '''simple docstring'''






       lowercase_						:     int							     =  TFDeiTModelTester(self      )
       lowercase_						:     Any							     =  ConfigTester(self	,  config_class=a	,  has_text_modality=a	,  hidden_size=3_7      )




    def 					lowerCAmelCase__					(      self	:							int      ):






       '''simple docstring'''






       self.config_tester.run_common_tests()




    @unittest.skip(reason="DeiT does not use inputs_embeds"      )
    def 					lowerCAmelCase__					(      self	:							Optional[int]      ):






       '''simple docstring'''






       pass




    def 					lowerCAmelCase__					(      self	:							int      ):






       '''simple docstring'''






       lowercase_     ,		lowercase_						:     Tuple							     =  self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
          lowercase_						:     Dict							     =  model_class(a      )
          self.assertIsInstance(model.get_input_embeddings()	,  (tf.keras.layers.Layer)      )
          lowercase_						:     Optional[int]							     =  model.get_output_embeddings()
          self.assertTrue(x is None or isinstance(a	,  tf.keras.layers.Dense      )      )




    def 					lowerCAmelCase__					(      self	:							str      ):






       '''simple docstring'''






       lowercase_     ,		lowercase_						:     Union[str, Any]							     =  self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
          lowercase_						:     Any							     =  model_class(a      )
          lowercase_						:     str							     =  inspect.signature(model.call      )
          # signature.parameters is an OrderedDict => so arg_names order is deterministic
          lowercase_						:     int							     =  [*signature.parameters.keys()]

          lowercase_						:     Dict							     =  ["pixel_values"]
          self.assertListEqual(arg_names[:1]	,  a      )




    def 					lowerCAmelCase__					(      self	:							Optional[Any]      ):






       '''simple docstring'''






       lowercase_						:     int							     =  self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*a      )




    def 					lowerCAmelCase__					(      self	:							str      ):






       '''simple docstring'''






       lowercase_						:     int							     =  self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_masked_image_modeling(*a      )




    def 					lowerCAmelCase__					(      self	:							List[Any]      ):






       '''simple docstring'''






       lowercase_						:     int							     =  self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_image_classification(*a      )




    def 					lowerCAmelCase__					(      self	:							Any	,  a	:							int	,  a	:							Union[str, Any]	,  a	:							Any=False      ):






       '''simple docstring'''






       lowercase_						:     Union[str, Any]							     =  super()._prepare_for_class(a	,  a	,  return_labels=a      )

       if return_labels:
          if "labels" in inputs_dict and "labels" not in inspect.signature(model_class.call      ).parameters:
             del inputs_dict["labels"]

       return inputs_dict





    @slow
    def 					lowerCAmelCase__					(      self	:							Optional[Any]      ):






       '''simple docstring'''






       for model_name in TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
          lowercase_						:     List[Any]							     =  TFDeiTModel.from_pretrained(a      )
          self.assertIsNotNone(a      )




def 		__SCREAMING_SNAKE_CASE       (	):


   """simple docstring"""




   lowercase_						:     str							     =  Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"				)
   return image





@require_tf
@require_vision
class 							_UpperCAmelCase    (		unittest.TestCase      ):




    @cached_property
    def 					lowerCAmelCase__					(      self	:							List[Any]      ):






       '''simple docstring'''






       return (
           DeiTImageProcessor.from_pretrained("facebook/deit-base-distilled-patch16-224"      )
           if is_vision_available()
           else None
       )





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






       '''simple docstring'''






       lowercase_						:     Optional[Any]							     =  TFDeiTForImageClassificationWithTeacher.from_pretrained("facebook/deit-base-distilled-patch16-224"      )

       lowercase_						:     Union[str, Any]							     =  self.default_image_processor
       lowercase_						:     Tuple							     =  prepare_img()
       lowercase_						:     Optional[Any]							     =  image_processor(images=a	,  return_tensors="tf"      )

       # forward pass
       lowercase_						:     int							     =  model(**a      )

       # verify the logits
       lowercase_						:     Union[str, Any]							     =  tf.TensorShape((1, 1_0_0_0)      )
       self.assertEqual(outputs.logits.shape	,  a      )

       lowercase_						:     Optional[Any]							     =  tf.constant([-1.0266, 0.1912, -1.2861]      )

       self.assertTrue(np.allclose(outputs.logits[0, :3]	,  a	,  atol=1e-4      )      )




