
'''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     __snake_case		:
					_lowerCAmelCase			     =	field(
					    default=a__    ,   metadata={'''help''': '''Model type selected in the list: ''' + ''', '''.join(a__)})
					_lowerCAmelCase			     =	field(
					    default=a__    ,   metadata={'''help''': '''The input data dir. Should contain the .json files for the SQuAD task.'''})
					_lowerCAmelCase			     =	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.'''
					        )
					    }    ,   )
					_lowerCAmelCase			     =	field(
					    default=128    ,   metadata={'''help''': '''When splitting up a long document into chunks, how much stride to take between chunks.'''}    ,   )
					_lowerCAmelCase			     =	field(
					    default=64    ,   metadata={
					        '''help''': (
					            '''The maximum number of tokens for the question. Questions longer than this will '''
					            '''be truncated to this length.'''
					        )
					    }    ,   )
					_lowerCAmelCase			     =	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			     =	field(
					    default=a__    ,   metadata={'''help''': '''Overwrite the cached training and evaluation sets'''})
					_lowerCAmelCase			     =	field(
					    default=a__    ,   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=20    ,   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     __snake_case		(   a__):
					_lowerCAmelCase			     =	'''train'''
					_lowerCAmelCase			     =	'''dev'''





class     __snake_case		(   a__):
					_lowerCAmelCase			     =	42
					_lowerCAmelCase			     =	42
					_lowerCAmelCase			     =	42
					_lowerCAmelCase			     =	42
					def __init__(     self,    A,    A,    A = None,    A = Split.train,    A = False,    A = None,    A = "pt",    ):

									"""simple docstring"""


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

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

																	lowerCamelCase			, lowerCamelCase					:			Tuple									= 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,    )

																	lowerCamelCase					:			Optional[int]									= 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      ):

									"""simple docstring"""


									return len(self.features      )




					def __getitem__(     self,    A      ):

									"""simple docstring"""


									lowerCamelCase					:			Tuple									= self.features[i]

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

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

									return inputs


'''simple docstring'''






import warnings
from collections import OrderedDict
from typing import Mapping

from packaging import version

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


A			      =      logging.get_logger(__name__)

A			      =      {
    'nvidia/segformer-b0-finetuned-ade-512-512': (
        'https://huggingface.co/nvidia/segformer-b0-finetuned-ade-512-512/resolve/main/config.json'
    ),
    # See all SegFormer models at https://huggingface.co/models?filter=segformer
}




class     __snake_case		(   a__):
					_lowerCAmelCase			     =	'''segformer'''
					def __init__(     self,    A=3,    A=4,    A=[2, 2, 2, 2],    A=[8, 4, 2, 1],    A=[32, 64, 160, 256],    A=[7, 3, 3, 3],    A=[4, 2, 2, 2],    A=[1, 2, 5, 8],    A=[4, 4, 4, 4],    A="gelu",    A=0.0,    A=0.0,    A=0.1,    A=0.02,    A=0.1,    A=1e-6,    A=256,    A=255,    **A,    ):

									"""simple docstring"""


									super().__init__(**A      )

									if "reshape_last_stage" in kwargs and kwargs["reshape_last_stage"] is False:
													warnings.warn(
													    'Reshape_last_stage is set to False in this config. This argument is deprecated and will soon be'
													    ' removed, as the behaviour will default to that of reshape_last_stage = True.',    A,    )

									lowerCamelCase					:			Tuple									= num_channels
									lowerCamelCase					:			Dict									= num_encoder_blocks
									lowerCamelCase					:			Dict									= depths
									lowerCamelCase					:			Any									= sr_ratios
									lowerCamelCase					:			List[Any]									= hidden_sizes
									lowerCamelCase					:			List[Any]									= patch_sizes
									lowerCamelCase					:			Tuple									= strides
									lowerCamelCase					:			int									= mlp_ratios
									lowerCamelCase					:			Dict									= num_attention_heads
									lowerCamelCase					:			Union[str, Any]									= hidden_act
									lowerCamelCase					:			Tuple									= hidden_dropout_prob
									lowerCamelCase					:			Optional[int]									= attention_probs_dropout_prob
									lowerCamelCase					:			List[str]									= classifier_dropout_prob
									lowerCamelCase					:			Union[str, Any]									= initializer_range
									lowerCamelCase					:			Union[str, Any]									= drop_path_rate
									lowerCamelCase					:			int									= layer_norm_eps
									lowerCamelCase					:			Any									= decoder_hidden_size
									lowerCamelCase					:			Optional[int]									= kwargs.get('reshape_last_stage',    A      )
									lowerCamelCase					:			Any									= semantic_loss_ignore_index





class     __snake_case		(   a__):
					_lowerCAmelCase			     =	version.parse('''1.11''')
					@property
					def     UpperCAmelCase_							(     self      ):

									"""simple docstring"""


									return OrderedDict(
									    [
									        ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}),
									    ]      )
					@property
					def     UpperCAmelCase_							(     self      ):

									"""simple docstring"""


									return 1e-4




					@property
					def     UpperCAmelCase_							(     self      ):

									"""simple docstring"""


									return 12
