



"""simple docstring"""







from __future__ import annotations

import inspect
import unittest
from typing import List, Tuple

from transformers import RegNetConfig
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 TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFRegNetForImageClassification, TFRegNetModel


if is_vision_available():
							from PIL import Image

							from transformers import AutoImageProcessor






class      UpperCAmelCase__		:



		def __init__( self  :    List[Any]      ,							snake_case  :    Optional[int]      ,							snake_case  :    List[Any]=3      ,							snake_case  :    Union[str, Any]=32      ,							snake_case  :    List[Any]=3      ,							snake_case  :    Optional[int]=10      ,							snake_case  :    Optional[Any]=[10, 20, 30, 40]      ,							snake_case  :    Tuple=[1, 1, 2, 1]      ,							snake_case  :    Optional[Any]=True      ,							snake_case  :    Dict=True      ,							snake_case  :    List[str]="relu"      ,							snake_case  :    Tuple=3      ,							snake_case  :    Union[str, Any]=None      ,							)			->						str:






									'''simple docstring'''

									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(__lowerCamelCase				)



		def 					A_		( self  :    Dict				)			->						List[Any]:






									'''simple docstring'''

									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 					A_		( self  :    List[str]				)			->						int:






									'''simple docstring'''

									return RegNetConfig(
									    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      ,							)



		def 					A_		( self  :    Union[str, Any]      ,							snake_case  :    Dict      ,							snake_case  :    List[str]      ,							snake_case  :    Union[str, Any]				)			->						Tuple:






									'''simple docstring'''

									A         =					TFRegNetModel(config=__lowerCamelCase				)
									A         =					model(__lowerCamelCase      ,							training=__lowerCamelCase				)
									# 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 					A_		( self  :    Optional[Any]      ,							snake_case  :    Optional[Any]      ,							snake_case  :    Any      ,							snake_case  :    Tuple				)			->						List[str]:






									'''simple docstring'''

									A         =					self.num_labels
									A         =					TFRegNetForImageClassification(__lowerCamelCase				)
									A         =					model(__lowerCamelCase      ,							labels=__lowerCamelCase      ,							training=__lowerCamelCase				)
									self.parent.assertEqual(result.logits.shape      ,							(self.batch_size, self.num_labels)				)



		def 					A_		( self  :    str				)			->						Dict:






									'''simple docstring'''

									A         =					self.prepare_config_and_inputs()
									A         =					config_and_inputs
									A         =					{"pixel_values": pixel_values}
									return config, inputs_dict






@require_tf
class      UpperCAmelCase__		(      _A   ,_A   ,unittest.TestCase     ):
		lowerCAmelCase_       :	int 							=     (TFRegNetModel, TFRegNetForImageClassification) if is_tf_available() else ()
		lowerCAmelCase_       :	Optional[int] 							=     (
		    {"""feature-extraction""": TFRegNetModel, """image-classification""": TFRegNetForImageClassification}
		    if is_tf_available()
		    else {}
		)

		lowerCAmelCase_       :	Dict 							=     False
		lowerCAmelCase_       :	Dict 							=     False
		lowerCAmelCase_       :	Optional[int] 							=     False
		lowerCAmelCase_       :	Optional[int] 							=     False
		lowerCAmelCase_       :	Optional[Any] 							=     False



		def 					A_		( self  :    str				)			->						List[str]:






									'''simple docstring'''

									A         =					TFRegNetModelTester(self				)
									A         =					ConfigTester(self      ,							config_class=__lowerCamelCase      ,							has_text_modality=__lowerCamelCase				)



		def 					A_		( self  :    Optional[Any]				)			->						Tuple:






									'''simple docstring'''

									return



		@unittest.skip(reason='RegNet does not use inputs_embeds'				)
		def 					A_		( self  :    Optional[int]				)			->						Optional[Any]:






									'''simple docstring'''

									pass



		@unittest.skipIf(
		    not is_tf_available() or len(tf.config.list_physical_devices('GPU'				)				) == 0      ,							reason='TF does not support backprop for grouped convolutions on CPU.'      ,							)
		@slow
		def 					A_		( self  :    str				)			->						Any:






									'''simple docstring'''

									super().test_keras_fit()



		@unittest.skip(reason='RegNet does not support input and output embeddings'				)
		def 					A_		( self  :    Union[str, Any]				)			->						Union[str, Any]:






									'''simple docstring'''

									pass



		def 					A_		( self  :    Union[str, Any]				)			->						Tuple:






									'''simple docstring'''

									A         =					self.model_tester.prepare_config_and_inputs_for_common()

									for model_class in self.all_model_classes:
																A         =					model_class(__lowerCamelCase				)
																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]      ,							__lowerCamelCase				)



		def 					A_		( self  :    Tuple				)			->						Tuple:






									'''simple docstring'''

									A         =					self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_model(*__lowerCamelCase				)



		def 					A_		( self  :    str				)			->						List[str]:






									'''simple docstring'''

									def check_hidden_states_output(snake_case  :    Union[str, Any]      ,							snake_case  :    Optional[Any]      ,							snake_case  :    str				):
																A         =					model_class(__lowerCamelCase				)
																A         =					model(**self._prepare_for_class(__lowerCamelCase      ,							__lowerCamelCase				)      ,							training=__lowerCamelCase				)

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

																A         =					self.model_tester.num_stages
																self.assertEqual(len(__lowerCamelCase				)      ,							expected_num_stages + 1				)

																# RegNet'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 // 2, self.model_tester.image_size // 2]      ,							)

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

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

																							check_hidden_states_output(__lowerCamelCase      ,							__lowerCamelCase      ,							__lowerCamelCase				)



		def 					A_		( self  :    Any				)			->						Dict:






									'''simple docstring'''

									A         =					self.model_tester.prepare_config_and_inputs_for_common()

									def check_equivalence(snake_case  :    int      ,							snake_case  :    List[str]      ,							snake_case  :    Dict      ,							snake_case  :    Optional[Any]={}				):
																A         =					model(__lowerCamelCase      ,							return_dict=__lowerCamelCase      ,							**__lowerCamelCase				)
																A         =					model(__lowerCamelCase      ,							return_dict=__lowerCamelCase      ,							**__lowerCamelCase				).to_tuple()

																def recursive_check(snake_case  :    List[str]      ,							snake_case  :    Any				):
																							if isinstance(__lowerCamelCase      ,							(List, Tuple)				):
																														for tuple_iterable_value, dict_iterable_value in zip(__lowerCamelCase      ,							__lowerCamelCase				):
																																					recursive_check(__lowerCamelCase      ,							__lowerCamelCase				)
																							elif tuple_object is None:
																														return
																							else:
																														self.assertTrue(
																														    all(tf.equal(__lowerCamelCase      ,							__lowerCamelCase				)				)      ,							msg=(
																														        'Tuple and dict output are not equal. Difference:'
																														        f""" {tf.math.reduce_max(tf.abs(tuple_object - dict_object				)				)}"""
																														    )      ,							)

																							recursive_check(__lowerCamelCase      ,							__lowerCamelCase				)

									for model_class in self.all_model_classes:
																A         =					model_class(__lowerCamelCase				)

																A         =					self._prepare_for_class(__lowerCamelCase      ,							__lowerCamelCase				)
																A         =					self._prepare_for_class(__lowerCamelCase      ,							__lowerCamelCase				)
																check_equivalence(__lowerCamelCase      ,							__lowerCamelCase      ,							__lowerCamelCase				)

																A         =					self._prepare_for_class(__lowerCamelCase      ,							__lowerCamelCase      ,							return_labels=__lowerCamelCase				)
																A         =					self._prepare_for_class(__lowerCamelCase      ,							__lowerCamelCase      ,							return_labels=__lowerCamelCase				)
																check_equivalence(__lowerCamelCase      ,							__lowerCamelCase      ,							__lowerCamelCase				)

																A         =					self._prepare_for_class(__lowerCamelCase      ,							__lowerCamelCase				)
																A         =					self._prepare_for_class(__lowerCamelCase      ,							__lowerCamelCase				)
																check_equivalence(__lowerCamelCase      ,							__lowerCamelCase      ,							__lowerCamelCase      ,							{'output_hidden_states': True}				)

																A         =					self._prepare_for_class(__lowerCamelCase      ,							__lowerCamelCase      ,							return_labels=__lowerCamelCase				)
																A         =					self._prepare_for_class(__lowerCamelCase      ,							__lowerCamelCase      ,							return_labels=__lowerCamelCase				)
																check_equivalence(__lowerCamelCase      ,							__lowerCamelCase      ,							__lowerCamelCase      ,							{'output_hidden_states': True}				)



		def 					A_		( self  :    Union[str, Any]				)			->						Optional[Any]:






									'''simple docstring'''

									A         =					self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_image_classification(*__lowerCamelCase				)



		@slow
		def 					A_		( self  :    Any				)			->						Union[str, Any]:






									'''simple docstring'''

									for model_name in TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																A         =					TFRegNetModel.from_pretrained(__lowerCamelCase				)
																self.assertIsNotNone(__lowerCamelCase				)



def   lowerCAmelCase__			(     ) ->							Union[str, Any]:
							A         =					Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'			)
							return image






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



		@cached_property
		def 					A_		( self  :    Any				)			->						Optional[Any]:






									'''simple docstring'''

									return (
									    AutoImageProcessor.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]				)
									    if is_vision_available()
									    else None
									)



		@slow
		def 					A_		( self  :    Dict				)			->						Optional[Any]:






									'''simple docstring'''

									A         =					TFRegNetForImageClassification.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]				)

									A         =					self.default_image_processor
									A         =					prepare_img()
									A         =					image_processor(images=__lowerCamelCase      ,							return_tensors='tf'				)

									# forward pass
									A         =					model(**__lowerCamelCase      ,							training=__lowerCamelCase				)

									# verify the logits
									A         =					tf.TensorShape((1, 1_000)				)
									self.assertEqual(outputs.logits.shape      ,							__lowerCamelCase				)

									A         =					tf.constant([-0.4180, -1.5051, -3.4836]				)

									tf.debugging.assert_near(outputs.logits[0, :3]      ,							__lowerCamelCase      ,							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    =			logging.get_logger(__name__)

A    =			list(MODEL_FOR_QUESTION_ANSWERING_MAPPING.keys())
A    =			tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)






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






class      UpperCAmelCase__		(      UpperCamelCase     ):
		lowerCAmelCase_       :	str 							=     """train"""
		lowerCAmelCase_       :	Union[str, Any] 							=     """dev"""






class      UpperCAmelCase__		(      UpperCamelCase     ):
		lowerCAmelCase_       :	SquadDataTrainingArguments
		lowerCAmelCase_       :	List[SquadFeatures]
		lowerCAmelCase_       :	Split
		lowerCAmelCase_       :	bool



		def __init__( self  :    List[Any]      ,							snake_case  :    SquadDataTrainingArguments      ,							snake_case  :    PreTrainedTokenizer      ,							snake_case  :    Optional[int] = None      ,							snake_case  :    Union[str, Split] = Split.train      ,							snake_case  :    Optional[bool] = False      ,							snake_case  :    Optional[str] = None      ,							snake_case  :    Optional[str] = "pt"      ,							)			->						Optional[Any]:






									'''simple docstring'''

									A         =					args
									A         =					is_language_sensitive
									A         =					SquadVaProcessor() if args.version_2_with_negative else SquadVaProcessor()
									if isinstance(snake_case      ,							snake_case				):
																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(snake_case				):
																if os.path.exists(snake_case				) and not args.overwrite_cache:
																							A         =					time.time()
																							A         =					torch.load(snake_case				)

																							# 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'      ,							snake_case				)
																							A         =					self.old_features.get('examples'      ,							snake_case				)
																							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=snake_case      ,							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=snake_case      ,							)

																							A         =					time.time()
																							torch.save(
																							    {'features': self.features, 'dataset': self.dataset, 'examples': self.examples}      ,							snake_case      ,							)
																							# ^ 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				)			->						Dict:






									'''simple docstring'''

									return len(self.features				)



		def __getitem__( self  :    Union[str, Any]      ,							snake_case  :    List[str]				)			->						Dict[str, torch.Tensor]:






									'''simple docstring'''

									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



