


'''simple docstring'''






from __future__ import annotations

import inspect
import unittest

import numpy as np

from transformers import ResNetConfig
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 TFResNetForImageClassification, TFResNetModel
 from transformers.models.resnet.modeling_tf_resnet import TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
 from PIL import Image

 from transformers import AutoImageProcessor




class 	a       :
 def __init__(	self ,			__magic_name__ ,			__magic_name__=3 ,			__magic_name__=32 ,			__magic_name__=3 ,			__magic_name__=10 ,			__magic_name__=[10, 20, 30, 40] ,			__magic_name__=[1, 1, 2, 1] ,			__magic_name__=True ,			__magic_name__=True ,			__magic_name__="relu" ,			__magic_name__=3 ,			__magic_name__=None ,			)   ->							Tuple:
      _a      =							parent
      _a      =							batch_size
      _a      =							image_size
      _a      =							num_channels
      _a      =							embeddings_size
      _a      =							hidden_sizes
      _a      =							depths
      _a      =							is_training
      _a      =							use_labels
      _a      =							hidden_act
      _a      =							num_labels
      _a      =							scope
      _a      =							len(__magic_name__  )
 def 							__UpperCAmelCase						(	self  )   ->							List[Any]:
      _a      =							floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]  )

      _a      =							None
      if self.use_labels:
           _a      =							ids_tensor([self.batch_size] ,			self.num_labels  )

      _a      =							self.get_config()

      return config, pixel_values, labels
 def 							__UpperCAmelCase						(	self  )   ->							str:
      return ResNetConfig(
          num_channels=self.num_channels ,			embeddings_size=self.embeddings_size ,			hidden_sizes=self.hidden_sizes ,			depths=self.depths ,			hidden_act=self.hidden_act ,			num_labels=self.num_labels ,			image_size=self.image_size ,			)
 def 							__UpperCAmelCase						(	self ,			__magic_name__ ,			__magic_name__ ,			__magic_name__  )   ->							int:
      _a      =							TFResNetModel(config=__magic_name__  )
      _a      =							model(__magic_name__  )
      # expected last hidden states: B, C, H // 32, W // 32
      self.parent.assertEqual(
          result.last_hidden_state.shape ,			(self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) ,			)
 def 							__UpperCAmelCase						(	self ,			__magic_name__ ,			__magic_name__ ,			__magic_name__  )   ->							Optional[Any]:
      _a      =							self.num_labels
      _a      =							TFResNetForImageClassification(__magic_name__  )
      _a      =							model(__magic_name__ ,			labels=__magic_name__  )
      self.parent.assertEqual(result.logits.shape ,			(self.batch_size, self.num_labels)  )




 def 							__UpperCAmelCase						(	self  )   ->							Union[str, Any]:
      _a      =							self.prepare_config_and_inputs()
      _a ,				_a ,				_a      =							config_and_inputs
      _a      =							{'pixel_values': pixel_values}
      return config, inputs_dict





@require_tf
class 	a       (       _SCREAMING_SNAKE_CASE					,			_SCREAMING_SNAKE_CASE					,			unittest.TestCase    ):
 _lowerCAmelCase	   =		(TFResNetModel, TFResNetForImageClassification) if is_tf_available() else ()
 _lowerCAmelCase	   =		(
     {"""feature-extraction""": TFResNetModel, """image-classification""": TFResNetForImageClassification}
     if is_tf_available()
     else {}
 )

 _lowerCAmelCase	   =		False
 _lowerCAmelCase	   =		False
 _lowerCAmelCase	   =		False
 _lowerCAmelCase	   =		False
 _lowerCAmelCase	   =		False
 def 							__UpperCAmelCase						(	self  )   ->							str:
      _a      =							TFResNetModelTester(self  )
      _a      =							ConfigTester(self ,			config_class=__magic_name__ ,			has_text_modality=__magic_name__  )
 def 							__UpperCAmelCase						(	self  )   ->							int:
      self.create_and_test_config_common_properties()
      self.config_tester.create_and_test_config_to_json_string()
      self.config_tester.create_and_test_config_to_json_file()
      self.config_tester.create_and_test_config_from_and_save_pretrained()
      self.config_tester.create_and_test_config_with_num_labels()
      self.config_tester.check_config_can_be_init_without_params()
      self.config_tester.check_config_arguments_init()
 def 							__UpperCAmelCase						(	self  )   ->							Optional[int]:
      return
 @unittest.skip(reason='ResNet does not use inputs_embeds'  )
 def 							__UpperCAmelCase						(	self  )   ->							Any:
      pass
 @unittest.skip(reason='ResNet does not support input and output embeddings'  )
 def 							__UpperCAmelCase						(	self  )   ->							Optional[int]:
      pass
 def 							__UpperCAmelCase						(	self  )   ->							Union[str, Any]:
      _a ,				_a      =							self.model_tester.prepare_config_and_inputs_for_common()

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

           _a      =							['pixel_values']
           self.assertListEqual(arg_names[:1] ,			__magic_name__  )
 def 							__UpperCAmelCase						(	self  )   ->							Dict:
      _a      =							self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*__magic_name__  )
 def 							__UpperCAmelCase						(	self  )   ->							List[Any]:
      def check_hidden_states_output(__magic_name__ ,			__magic_name__ ,			__magic_name__  ):
           _a      =							model_class(__magic_name__  )
           _a      =							model(**self._prepare_for_class(__magic_name__ ,			__magic_name__  )  )

           _a      =							outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

           _a      =							self.model_tester.num_stages
           self.assertEqual(len(__magic_name__  ) ,			expected_num_stages + 1  )

           # ResNet's feature maps are of shape (batch_size, num_channels, height, width)
           self.assertListEqual(
               list(hidden_states[0].shape[-2:]  ) ,			[self.model_tester.image_size // 4, self.model_tester.image_size // 4] ,			)

      _a ,				_a      =							self.model_tester.prepare_config_and_inputs_for_common()
      _a      =							['basic', 'bottleneck']
      for model_class in self.all_model_classes:
           for layer_type in layers_type:
                _a      =							layer_type
                _a      =							True
                check_hidden_states_output(__magic_name__ ,			__magic_name__ ,			__magic_name__  )

                # check that output_hidden_states also work using config
                del inputs_dict["output_hidden_states"]
                _a      =							True

                check_hidden_states_output(__magic_name__ ,			__magic_name__ ,			__magic_name__  )
 def 							__UpperCAmelCase						(	self  )   ->							Union[str, Any]:
      _a      =							self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_image_classification(*__magic_name__  )




 @slow
 def 							__UpperCAmelCase						(	self  )   ->							Tuple:
      for model_name in TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
           _a      =							TFResNetModel.from_pretrained(__magic_name__  )
           self.assertIsNotNone(__magic_name__  )






def 		_A			()				->					Dict:




     '''simple docstring'''



     _a      =							Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'						)
     return image






@require_tf
@require_vision
class 	a       (       unittest.TestCase    ):
 @cached_property
 def 							__UpperCAmelCase						(	self  )   ->							Union[str, Any]:
      return (
          AutoImageProcessor.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]  )
          if is_vision_available()
          else None
      )




 @slow
 def 							__UpperCAmelCase						(	self  )   ->							Optional[Any]:
      _a      =							TFResNetForImageClassification.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]  )

      _a      =							self.default_image_processor
      _a      =							prepare_img()
      _a      =							image_processor(images=__magic_name__ ,			return_tensors='tf'  )

      # forward pass
      _a      =							model(**__magic_name__  )

      # verify the logits
      _a      =							tf.TensorShape((1, 10_00)  )
      self.assertEqual(outputs.logits.shape ,			__magic_name__  )

      _a      =							tf.constant([-1_1.1_0_6_9, -9.7_8_7_7, -8.3_7_7_7]  )

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





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


a_   :      Optional[int]				    =      logging.get_logger(__name__)

a_   :      List[Any]				    =      list(MODEL_FOR_QUESTION_ANSWERING_MAPPING.keys())
a_   :      List[str]				    =      tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)




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





class 	a       (       _SCREAMING_SNAKE_CASE    ):
 _lowerCAmelCase	   =		"""train"""
 _lowerCAmelCase	   =		"""dev"""





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

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

                _a ,				_a      =							squad_convert_examples_to_features(
                    examples=self.examples ,			tokenizer=__magic_name__ ,			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=__magic_name__ ,			)

                _a      =							time.time()
                torch.save(
                    {'features': self.features, 'dataset': self.dataset, 'examples': self.examples} ,			__magic_name__ ,			)
                # ^ 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 ,			__magic_name__  )   ->							Dict[str, torch.Tensor]:
      # Convert to Tensors and build dataset
      _a      =							self.features[i]

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

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

      return inputs

