



"""simple docstring"""






import copy
import inspect
import unittest

from transformers import AutoBackbone
from transformers.configuration_utils import PretrainedConfig
from transformers.testing_utils import require_timm, require_torch, torch_device
from transformers.utils.import_utils import is_torch_available

from ...test_backbone_common import BackboneTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor


if is_torch_available():
		import torch

		from transformers import TimmBackbone, TimmBackboneConfig

from ...test_pipeline_mixin import PipelineTesterMixin

class        __SCREAMING_SNAKE_CASE	:


					'''simple docstring'''





					def __init__(       self							:  Optional[int],  lowerCamelCase							:  str,  lowerCamelCase							:  List[str]=None,  lowerCamelCase							:  Dict=None,  lowerCamelCase							:  Tuple=None,  lowerCamelCase							:  List[Any]="resnet50",  lowerCamelCase							:  Any=3,  lowerCamelCase							:  Any=32,  lowerCamelCase							:  str=3,  lowerCamelCase							:  List[str]=True,  lowerCamelCase							:  Dict=True,  )->					List[str]:
								lowerCamelCase__		:		int			=parent
								lowerCamelCase__		:		Optional[int]			=out_indices if out_indices is not None else [4]
								lowerCamelCase__		:		List[Any]			=stage_names
								lowerCamelCase__		:		Dict			=out_features
								lowerCamelCase__		:		Optional[Any]			=backbone
								lowerCamelCase__		:		int			=batch_size
								lowerCamelCase__		:		Union[str, Any]			=image_size
								lowerCamelCase__		:		Any			=num_channels
								lowerCamelCase__		:		int			=use_pretrained_backbone
								lowerCamelCase__		:		Any			=is_training



					def 		snake_case       (       self							:  Optional[Any]     )->					Tuple:
								lowerCamelCase__		:		List[Any]			=floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]     )
								lowerCamelCase__		:		Optional[int]			=self.get_config()

								return config, pixel_values



					def 		snake_case       (       self							:  List[str]     )->					Any:
								return TimmBackboneConfig(
								    image_size=self.image_size,  num_channels=self.num_channels,  out_features=self.out_features,  out_indices=self.out_indices,  stage_names=self.stage_names,  use_pretrained_backbone=self.use_pretrained_backbone,  backbone=self.backbone,  )



					def 		snake_case       (       self							:  Dict,  lowerCamelCase							:  Optional[Any],  lowerCamelCase							:  Optional[Any]     )->					Union[str, Any]:
								lowerCamelCase__		:		Union[str, Any]			=TimmBackbone(config=lowerCamelCase     )
								model.to(lowerCamelCase     )
								model.eval()
								with torch.no_grad():
											lowerCamelCase__		:		Union[str, Any]			=model(lowerCamelCase     )
								self.parent.assertEqual(
								    result.feature_map[-1].shape,  (self.batch_size, model.channels[-1], 14, 14),  )




					def 		snake_case       (       self							:  List[Any]     )->					Tuple:
								lowerCamelCase__		:		str			=self.prepare_config_and_inputs()
								lowerCamelCase__	,   lowerCamelCase__		:		Optional[int]			=config_and_inputs
								lowerCamelCase__		:		str			={'''pixel_values''': pixel_values}
								return config, inputs_dict





@require_torch
@require_timm
class        __SCREAMING_SNAKE_CASE	(      lowerCAmelCase_		,   lowerCAmelCase_		,   lowerCAmelCase_		,   unittest.TestCase   ):


					'''simple docstring'''





					_a   			=							(TimmBackbone,) if is_torch_available() else ()
					_a   			=							{'feature-extraction': TimmBackbone} if is_torch_available() else {}
					_a   			=							False
					_a   			=							False
					_a   			=							False
					_a   			=							False



					def 		snake_case       (       self							:  Optional[Any]     )->					List[Any]:
								lowerCamelCase__		:		Union[str, Any]			=TimmBackboneModelTester(self     )
								lowerCamelCase__		:		List[str]			=ConfigTester(self,  config_class=lowerCamelCase,  has_text_modality=lowerCamelCase     )



					def 		snake_case       (       self							:  Optional[int]     )->					str:
								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 		snake_case       (       self							:  int     )->					int:
								lowerCamelCase__		:		List[str]			='''resnet18'''
								lowerCamelCase__		:		List[str]			='''microsoft/resnet-18'''

								lowerCamelCase__		:		List[str]			=AutoBackbone.from_pretrained(lowerCamelCase,  use_timm_backbone=lowerCamelCase     )
								lowerCamelCase__		:		Optional[int]			=AutoBackbone.from_pretrained(lowerCamelCase     )

								self.assertEqual(len(timm_model.out_features     ),  len(transformers_model.out_features     )     )
								self.assertEqual(len(timm_model.stage_names     ),  len(transformers_model.stage_names     )     )
								self.assertEqual(timm_model.channels,  transformers_model.channels     )
								# Out indices are set to the last layer by default. For timm models, we don't know
								# the number of layers in advance, so we set it to (-1,), whereas for transformers
								# models, we set it to [len(stage_names) - 1] (kept for backward compatibility).
								self.assertEqual(timm_model.out_indices,  (-1,)     )
								self.assertEqual(transformers_model.out_indices,  [len(timm_model.stage_names     ) - 1]     )

								lowerCamelCase__		:		Union[str, Any]			=AutoBackbone.from_pretrained(lowerCamelCase,  use_timm_backbone=lowerCamelCase,  out_indices=[1, 2, 3]     )
								lowerCamelCase__		:		int			=AutoBackbone.from_pretrained(lowerCamelCase,  out_indices=[1, 2, 3]     )

								self.assertEqual(timm_model.out_indices,  transformers_model.out_indices     )
								self.assertEqual(len(timm_model.out_features     ),  len(transformers_model.out_features     )     )
								self.assertEqual(timm_model.channels,  transformers_model.channels     )



					@unittest.skip('''TimmBackbone doesn\'t support feed forward chunking'''     )
					def 		snake_case       (       self							:  List[str]     )->					Optional[Any]:
								pass



					@unittest.skip('''TimmBackbone doesn\'t have num_hidden_layers attribute'''     )
					def 		snake_case       (       self							:  Optional[int]     )->					Tuple:
								pass



					@unittest.skip('''TimmBackbone initialization is managed on the timm side'''     )
					def 		snake_case       (       self							:  str     )->					Dict:
								pass



					@unittest.skip('''TimmBackbone models doesn\'t have inputs_embeds'''     )
					def 		snake_case       (       self							:  List[str]     )->					str:
								pass



					@unittest.skip('''TimmBackbone models doesn\'t have inputs_embeds'''     )
					def 		snake_case       (       self							:  Union[str, Any]     )->					List[str]:
								pass



					@unittest.skip('''TimmBackbone model cannot be created without specifying a backbone checkpoint'''     )
					def 		snake_case       (       self							:  int     )->					Optional[int]:
								pass



					@unittest.skip('''Only checkpoints on timm can be loaded into TimmBackbone'''     )
					def 		snake_case       (       self							:  str     )->					List[Any]:
								pass



					@unittest.skip('''model weights aren\'t tied in TimmBackbone.'''     )
					def 		snake_case       (       self							:  List[str]     )->					Optional[Any]:
								pass



					@unittest.skip('''model weights aren\'t tied in TimmBackbone.'''     )
					def 		snake_case       (       self							:  List[Any]     )->					List[Any]:
								pass



					@unittest.skip('''Only checkpoints on timm can be loaded into TimmBackbone'''     )
					def 		snake_case       (       self							:  int     )->					Optional[int]:
								pass



					@unittest.skip('''Only checkpoints on timm can be loaded into TimmBackbone'''     )
					def 		snake_case       (       self							:  Any     )->					Optional[int]:
								pass



					@unittest.skip('''TimmBackbone doesn\'t have hidden size info in its configuration.'''     )
					def 		snake_case       (       self							:  Dict     )->					Union[str, Any]:
								pass



					@unittest.skip('''TimmBackbone doesn\'t support output_attentions.'''     )
					def 		snake_case       (       self							:  str     )->					Optional[Any]:
								pass



					@unittest.skip('''Safetensors is not supported by timm.'''     )
					def 		snake_case       (       self							:  Dict     )->					List[Any]:
								pass



					@unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.'''     )
					def 		snake_case       (       self							:  List[str]     )->					Any:
								pass



					def 		snake_case       (       self							:  Optional[int]     )->					List[Any]:
								lowerCamelCase__	,   lowerCamelCase__		:		str			=self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
											lowerCamelCase__		:		Union[str, Any]			=model_class(lowerCamelCase     )
											lowerCamelCase__		:		Optional[int]			=inspect.signature(model.forward     )
											# signature.parameters is an OrderedDict => so arg_names order is deterministic
											lowerCamelCase__		:		Optional[Any]			=[*signature.parameters.keys()]

											lowerCamelCase__		:		List[str]			=['''pixel_values''']
											self.assertListEqual(arg_names[:1],  lowerCamelCase     )



					def 		snake_case       (       self							:  Optional[int]     )->					Optional[int]:
								lowerCamelCase__	,   lowerCamelCase__		:		Union[str, Any]			=self.model_tester.prepare_config_and_inputs_for_common()
								lowerCamelCase__		:		List[str]			=True
								lowerCamelCase__		:		List[str]			=self.has_attentions

								# no need to test all models as different heads yield the same functionality
								lowerCamelCase__		:		List[Any]			=self.all_model_classes[0]
								lowerCamelCase__		:		Optional[Any]			=model_class(lowerCamelCase     )
								model.to(lowerCamelCase     )

								lowerCamelCase__		:		Tuple			=self._prepare_for_class(lowerCamelCase,  lowerCamelCase     )
								lowerCamelCase__		:		Optional[Any]			=model(**lowerCamelCase     )
								lowerCamelCase__		:		Optional[Any]			=outputs[0][-1]

								# Encoder-/Decoder-only models
								lowerCamelCase__		:		Tuple			=outputs.hidden_states[0]
								hidden_states.retain_grad()

								if self.has_attentions:
											lowerCamelCase__		:		int			=outputs.attentions[0]
											attentions.retain_grad()

								output.flatten()[0].backward(retain_graph=lowerCamelCase     )

								self.assertIsNotNone(hidden_states.grad     )

								if self.has_attentions:
											self.assertIsNotNone(attentions.grad     )




					def 		snake_case       (       self							:  Optional[Any]     )->					str:
								lowerCamelCase__	,   lowerCamelCase__		:		int			=self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
											lowerCamelCase__		:		str			=model_class(lowerCamelCase     )
											model.to(lowerCamelCase     )
											model.eval()
											lowerCamelCase__		:		Optional[Any]			=model(**lowerCamelCase     )

											self.assertEqual(len(result.feature_maps     ),  len(config.out_indices     )     )
											self.assertEqual(len(model.channels     ),  len(config.out_indices     )     )

											# Check output of last stage is taken if out_features=None, out_indices=None
											lowerCamelCase__		:		int			=copy.deepcopy(lowerCamelCase     )
											lowerCamelCase__		:		str			=None
											lowerCamelCase__		:		Any			=model_class(lowerCamelCase     )
											model.to(lowerCamelCase     )
											model.eval()
											lowerCamelCase__		:		Any			=model(**lowerCamelCase     )

											self.assertEqual(len(result.feature_maps     ),  1     )
											self.assertEqual(len(model.channels     ),  1     )

											# Check backbone can be initialized with fresh weights
											lowerCamelCase__		:		Tuple			=copy.deepcopy(lowerCamelCase     )
											lowerCamelCase__		:		int			=False
											lowerCamelCase__		:		Optional[Any]			=model_class(lowerCamelCase     )
											model.to(lowerCamelCase     )
											model.eval()
											lowerCamelCase__		:		Optional[Any]			=model(**lowerCamelCase     )









"""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 : Optional[int]      						=						logging.get_logger(__name__)

_lowercase : Tuple      						=						list(MODEL_FOR_QUESTION_ANSWERING_MAPPING.keys())
_lowercase : Tuple      						=						tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)

@dataclass
class        __SCREAMING_SNAKE_CASE	:


					'''simple docstring'''





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





class        __SCREAMING_SNAKE_CASE	(      lowerCAmelCase_   ):


					'''simple docstring'''





					_a   			=							'train'
					_a   			=							'dev'





class        __SCREAMING_SNAKE_CASE	(      lowerCAmelCase_   ):


					'''simple docstring'''





					_a   			=							42
					_a   			=							42
					_a   			=							42
					_a   			=							42



					def __init__(       self							:  Dict,  lowerCamelCase							:  SquadDataTrainingArguments,  lowerCamelCase							:  PreTrainedTokenizer,  lowerCamelCase							:  Optional[int] = None,  lowerCamelCase							:  Union[str, Split] = Split.train,  lowerCamelCase							:  Optional[bool] = False,  lowerCamelCase							:  Optional[str] = None,  lowerCamelCase							:  Optional[str] = "pt",  )->					List[str]:
								lowerCamelCase__		:		List[str]			=args
								lowerCamelCase__		:		Optional[Any]			=is_language_sensitive
								lowerCamelCase__		:		Any			=SquadVaProcessor() if args.version_2_with_negative else SquadVaProcessor()
								if isinstance(lowerCamelCase,  lowerCamelCase     ):
											try:
														lowerCamelCase__		:		int			=Split[mode]
											except KeyError:
														raise KeyError('''mode is not a valid split name'''     )
								lowerCamelCase__		:		Optional[Any]			=mode
								# Load data features from cache or dataset file
								lowerCamelCase__		:		Any			='''v2''' if args.version_2_with_negative else '''v1'''
								lowerCamelCase__		:		Optional[int]			=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.
								lowerCamelCase__		:		Optional[Any]			=cached_features_file + '''.lock'''
								with FileLock(lowerCamelCase     ):
											if os.path.exists(lowerCamelCase     ) and not args.overwrite_cache:
														lowerCamelCase__		:		Tuple			=time.time()
														lowerCamelCase__		:		str			=torch.load(lowerCamelCase     )

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

														lowerCamelCase__	,   lowerCamelCase__		:		List[str]			=squad_convert_examples_to_features(
														    examples=self.examples,  tokenizer=lowerCamelCase,  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=lowerCamelCase,  )

														lowerCamelCase__		:		List[str]			=time.time()
														torch.save(
														    {'''features''': self.features, '''dataset''': self.dataset, '''examples''': self.examples},  lowerCamelCase,  )
														# ^ 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							:  Optional[int]     )->					Dict:
								return len(self.features     )




					def __getitem__(       self							:  List[str],  lowerCamelCase							:  List[Any]     )->					Dict[str, torch.Tensor]:
								# Convert to Tensors and build dataset
								lowerCamelCase__		:		List[Any]			=self.features[i]

								lowerCamelCase__		:		List[Any]			=torch.tensor(feature.input_ids,  dtype=torch.long     )
								lowerCamelCase__		:		List[str]			=torch.tensor(feature.attention_mask,  dtype=torch.long     )
								lowerCamelCase__		:		List[Any]			=torch.tensor(feature.token_type_ids,  dtype=torch.long     )
								lowerCamelCase__		:		Optional[int]			=torch.tensor(feature.cls_index,  dtype=torch.long     )
								lowerCamelCase__		:		Optional[int]			=torch.tensor(feature.p_mask,  dtype=torch.float     )
								lowerCamelCase__		:		List[Any]			=torch.tensor(feature.is_impossible,  dtype=torch.float     )

								lowerCamelCase__		:		Optional[Any]			={
								    '''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:
											lowerCamelCase__		:		str			=torch.tensor(feature.start_position,  dtype=torch.long     )
											lowerCamelCase__		:		int			=torch.tensor(feature.end_position,  dtype=torch.long     )
											inputs.update({'''start_positions''': start_positions, '''end_positions''': end_positions}     )

								return inputs




