'''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


SCREAMING_SNAKE_CASE_:     Dict  =logging.get_logger(__name__)

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




@dataclass
class        __A      :
    a__       :						str          =  field(
        default=UpperCamelCase__		,	metadata={"""help""": """Model type selected in the list: """ + """, """.join(UpperCamelCase__	)}	)
    a__       :						str          =  field(
        default=UpperCamelCase__		,	metadata={"""help""": """The input data dir. Should contain the .json files for the SQuAD task."""}	)
    a__       :						int          =  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__       :						int          =  field(
        default=128		,	metadata={"""help""": """When splitting up a long document into chunks, how much stride to take between chunks."""}		,	)
    a__       :						int          =  field(
        default=64		,	metadata={
            """help""": (
                """The maximum number of tokens for the question. Questions longer than this will """
                """be truncated to this length."""
            )
        }		,	)
    a__       :						int          =  field(
        default=30		,	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."""
            )
        }		,	)
    a__       :						bool          =  field(
        default=UpperCamelCase__		,	metadata={"""help""": """Overwrite the cached training and evaluation sets"""}	)
    a__       :						bool          =  field(
        default=UpperCamelCase__		,	metadata={"""help""": """If true, the SQuAD examples contain some that do not have an answer."""}	)
    a__       :						float          =  field(
        default=0.0		,	metadata={"""help""": """If null_score - best_non_null is greater than the threshold predict null."""}	)
    a__       :						int          =  field(
        default=20		,	metadata={"""help""": """If null_score - best_non_null is greater than the threshold predict null."""}	)
    a__       :						int          =  field(
        default=0		,	metadata={
            """help""": (
                """language id of input for language-specific xlm models (see"""
                """ tokenization_xlm.PRETRAINED_INIT_CONFIGURATION)"""
            )
        }		,	)
    a__       :						int          =  field(default=1		,	metadata={"""help""": """multiple threads for converting example to features"""}	)




class        __A      ( UpperCamelCase__	):
    a__       :						str          =  """train"""
    a__       :						List[Any]          =  """dev"""




class        __A      ( UpperCamelCase__	):
    a__       :						SquadDataTrainingArguments
    a__       :						List[SquadFeatures]
    a__       :						Split
    a__       :						bool



    def __init__(self    :    Optional[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"   ,			):
         UpperCAmelCase_           =   args
         UpperCAmelCase_           =   is_language_sensitive
         UpperCAmelCase_           =   SquadVaProcessor() if args.version_2_with_negative else SquadVaProcessor()
         if isinstance(__a   ,			__a ):
              try:
                   UpperCAmelCase_           =   Split[mode]
              except KeyError:
                   raise KeyError("mode is not a valid split name" )
         UpperCAmelCase_           =   mode
         # Load data features from cache or dataset file
         UpperCAmelCase_           =   "v2" if args.version_2_with_negative else "v1"
         UpperCAmelCase_           =   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.
         UpperCAmelCase_           =   cached_features_file + ".lock"
         with FileLock(__a ):
              if os.path.exists(__a ) and not args.overwrite_cache:
                   UpperCAmelCase_           =   time.time()
                   UpperCAmelCase_           =   torch.load(__a )

                   # Legacy cache files have only features, while new cache files
                   # will have dataset and examples also.
                   UpperCAmelCase_           =   self.old_features["features"]
                   UpperCAmelCase_           =   self.old_features.get("dataset"   ,			__a )
                   UpperCAmelCase_           =   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:
                        UpperCAmelCase_           =   self.processor.get_dev_examples(args.data_dir )
                   else:
                        UpperCAmelCase_           =   self.processor.get_train_examples(args.data_dir )

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

                   UpperCAmelCase_           =   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    :    List[Any] ):
         return len(self.features )






    def __getitem__(self    :    Dict   ,			__a    :    Optional[int] ):
         # Convert to Tensors and build dataset
         UpperCAmelCase_           =   self.features[i]

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

         UpperCAmelCase_           =   {
             "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:
              UpperCAmelCase_           =   torch.tensor(feature.start_position   ,			dtype=torch.long )
              UpperCAmelCase_           =   torch.tensor(feature.end_position   ,			dtype=torch.long )
              inputs.update({"start_positions": start_positions, "end_positions": end_positions} )

         return inputs





'''simple docstring'''





import inspect
import unittest

import numpy as np

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

from ...test_configuration_common import ConfigTester
from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor


if is_flax_available():
    import jax

    from transformers.models.vit.modeling_flax_vit import FlaxViTForImageClassification, FlaxViTModel




class        __A      ( unittest.TestCase	):



    def __init__(self    :    str   ,			__a    :    Optional[Any]   ,			__a    :    Optional[Any]=13   ,			__a    :    int=30   ,			__a    :    Union[str, Any]=2   ,			__a    :    Dict=3   ,			__a    :    List[Any]=True   ,			__a    :    Optional[Any]=True   ,			__a    :    List[Any]=32   ,			__a    :    Any=5   ,			__a    :    str=4   ,			__a    :    Optional[int]=37   ,			__a    :    Optional[int]="gelu"   ,			__a    :    List[str]=0.1   ,			__a    :    Tuple=0.1   ,			__a    :    List[str]=10   ,			__a    :    Optional[int]=0.02   ,			):
         UpperCAmelCase_           =   parent
         UpperCAmelCase_           =   batch_size
         UpperCAmelCase_           =   image_size
         UpperCAmelCase_           =   patch_size
         UpperCAmelCase_           =   num_channels
         UpperCAmelCase_           =   is_training
         UpperCAmelCase_           =   use_labels
         UpperCAmelCase_           =   hidden_size
         UpperCAmelCase_           =   num_hidden_layers
         UpperCAmelCase_           =   num_attention_heads
         UpperCAmelCase_           =   intermediate_size
         UpperCAmelCase_           =   hidden_act
         UpperCAmelCase_           =   hidden_dropout_prob
         UpperCAmelCase_           =   attention_probs_dropout_prob
         UpperCAmelCase_           =   type_sequence_label_size
         UpperCAmelCase_           =   initializer_range

         # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
         UpperCAmelCase_           =   (image_size // patch_size) ** 2
         UpperCAmelCase_           =   num_patches + 1



    def 					_lowercase						(self    :    Any ):
         UpperCAmelCase_           =   floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )

         UpperCAmelCase_           =   ViTConfig(
             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   ,			)

         return config, pixel_values



    def 					_lowercase						(self    :    Dict   ,			__a    :    Any   ,			__a    :    List[Any] ):
         UpperCAmelCase_           =   FlaxViTModel(config=__a )
         UpperCAmelCase_           =   model(__a )
         # expected sequence length = num_patches + 1 (we add 1 for the [CLS] token)
         UpperCAmelCase_           =   (self.image_size, self.image_size)
         UpperCAmelCase_           =   (self.patch_size, self.patch_size)
         UpperCAmelCase_           =   (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
         self.parent.assertEqual(result.last_hidden_state.shape   ,			(self.batch_size, num_patches + 1, self.hidden_size) )



    def 					_lowercase						(self    :    Tuple   ,			__a    :    str   ,			__a    :    Any ):
         UpperCAmelCase_           =   self.type_sequence_label_size
         UpperCAmelCase_           =   FlaxViTForImageClassification(config=__a )
         UpperCAmelCase_           =   model(__a )
         self.parent.assertEqual(result.logits.shape   ,			(self.batch_size, self.type_sequence_label_size) )

         # test greyscale images
         UpperCAmelCase_           =   1
         UpperCAmelCase_           =   FlaxViTForImageClassification(__a )

         UpperCAmelCase_           =   floats_tensor([self.batch_size, 1, self.image_size, self.image_size] )
         UpperCAmelCase_           =   model(__a )






    def 					_lowercase						(self    :    Optional[Any] ):
         UpperCAmelCase_           =   self.prepare_config_and_inputs()
         (
             (
             UpperCAmelCase_
         )    , (
             UpperCAmelCase_
         )    , 
         )           =   config_and_inputs
         UpperCAmelCase_           =   {"pixel_values": pixel_values}
         return config, inputs_dict




@require_flax
class        __A      ( UpperCamelCase__		,	unittest.TestCase	):
    a__       :						Tuple          =  (FlaxViTModel, FlaxViTForImageClassification) if is_flax_available() else ()



    def 					_lowercase						(self    :    Any ):
         UpperCAmelCase_           =   FlaxViTModelTester(self )
         UpperCAmelCase_           =   ConfigTester(self   ,			config_class=__a   ,			has_text_modality=__a   ,			hidden_size=37 )



    def 					_lowercase						(self    :    Tuple ):
         self.config_tester.run_common_tests()



    def 					_lowercase						(self    :    str ):
         UpperCAmelCase_           =   self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*__a )



    def 					_lowercase						(self    :    str ):
         UpperCAmelCase_           =   self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_image_classification(*__a )



    def 					_lowercase						(self    :    Tuple ):
         UpperCAmelCase_    , UpperCAmelCase_           =   self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
              UpperCAmelCase_           =   model_class(__a )
              UpperCAmelCase_           =   inspect.signature(model.__call__ )
              # signature.parameters is an OrderedDict => so arg_names order is deterministic
              UpperCAmelCase_           =   [*signature.parameters.keys()]

              UpperCAmelCase_           =   ["pixel_values"]
              self.assertListEqual(arg_names[:1]   ,			__a )



    def 					_lowercase						(self    :    Optional[Any] ):
         UpperCAmelCase_    , UpperCAmelCase_           =   self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
              with self.subTest(model_class.__name__ ):
                   UpperCAmelCase_           =   self._prepare_for_class(__a   ,			__a )
                   UpperCAmelCase_           =   model_class(__a )

                   @jax.jit
                   def model_jitted(__a    :    Tuple   ,			**__a    :    List[Any] ):
                        return model(pixel_values=__a   ,			**__a )

                   with self.subTest("JIT Enabled" ):
                        UpperCAmelCase_           =   model_jitted(**__a ).to_tuple()

                   with self.subTest("JIT Disabled" ):
                        with jax.disable_jit():
                             UpperCAmelCase_           =   model_jitted(**__a ).to_tuple()

                   self.assertEqual(len(__a )   ,			len(__a ) )
                   for jitted_output, output in zip(__a   ,			__a ):
                        self.assertEqual(jitted_output.shape   ,			output.shape )






    @slow
    def 					_lowercase						(self    :    Tuple ):
         for model_class_name in self.all_model_classes:
              UpperCAmelCase_           =   model_class_name.from_pretrained("google/vit-base-patch16-224" )
              UpperCAmelCase_           =   model(np.ones((1, 3, 224, 224) ) )
              self.assertIsNotNone(__a )




