



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



class       _a  ( SCREAMING_SNAKE_CASE__):
			__magic_name__     					=     """train"""
			__magic_name__     					=     """dev"""



class       _a  ( SCREAMING_SNAKE_CASE__):
			__magic_name__     					=     42
			__magic_name__     					=     42
			__magic_name__     					=     42
			__magic_name__     					=     42



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

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

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

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



			def __getitem__(			self							:				Optional[int]   ,	_lowercase							:				Any		)							->					Dict[str, torch.Tensor]:
									# Convert to Tensors and build dataset
									snake_case   :			Optional[Any]						    = self.features[i]

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

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

									return inputs








"""simple docstring"""







from collections import OrderedDict
from typing import TYPE_CHECKING, Any, List, Mapping, Optional

from packaging import version


if TYPE_CHECKING:
			from ... import PreTrainedTokenizer, TensorType

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfigWithPast, PatchingSpec
from ...utils import is_torch_available, logging


A		=						logging.get_logger(__name__)

A		=						{
    'bigscience/bloom': 'https://huggingface.co/bigscience/bloom/resolve/main/config.json',
    'bigscience/bloom-560m': 'https://huggingface.co/bigscience/bloom-560m/blob/main/config.json',
    'bigscience/bloom-1b1': 'https://huggingface.co/bigscience/bloom-1b1/blob/main/config.json',
    'bigscience/bloom-1b7': 'https://huggingface.co/bigscience/bloom-1b7/blob/main/config.json',
    'bigscience/bloom-3b': 'https://huggingface.co/bigscience/bloom-3b/blob/main/config.json',
    'bigscience/bloom-7b1': 'https://huggingface.co/bigscience/bloom-7b1/blob/main/config.json',
}

class       _a  ( SCREAMING_SNAKE_CASE__):
			__magic_name__     					=     """bloom"""
			__magic_name__     					=     ["""past_key_values"""]
			__magic_name__     					=     {
			    """num_hidden_layers""": """n_layer""",
			    """num_attention_heads""": """n_head""",
			}



			def __init__(			self							:				Tuple   ,	_lowercase							:				List[Any]=250880   ,	_lowercase							:				int=64   ,	_lowercase							:				Optional[Any]=2   ,	_lowercase							:				Dict=8   ,	_lowercase							:				List[str]=1E-5   ,	_lowercase							:				List[Any]=0.02   ,	_lowercase							:				Optional[Any]=True   ,	_lowercase							:				Dict=1   ,	_lowercase							:				Union[str, Any]=2   ,	_lowercase							:				str=False   ,	_lowercase							:				List[Any]=0.0   ,	_lowercase							:				Tuple=0.0   ,	_lowercase							:				Dict=1   ,	_lowercase							:				int=False   ,	**_lowercase							:				int   ,	)							->					List[str]:
									snake_case   :			Any						    = vocab_size
									# Backward compatibility with n_embed kwarg
									snake_case   :			Any						    = kwargs.pop("n_embed"   ,	_lowercase		)
									snake_case   :			Tuple						    = hidden_size if n_embed is None else n_embed
									snake_case   :			Optional[Any]						    = n_layer
									snake_case   :			Optional[Any]						    = n_head
									snake_case   :			Union[str, Any]						    = layer_norm_epsilon
									snake_case   :			int						    = initializer_range
									snake_case   :			int						    = use_cache
									snake_case   :			int						    = pretraining_tp
									snake_case   :			Tuple						    = apply_residual_connection_post_layernorm
									snake_case   :			Union[str, Any]						    = hidden_dropout
									snake_case   :			Optional[Any]						    = attention_dropout

									snake_case   :			List[Any]						    = bos_token_id
									snake_case   :			Any						    = eos_token_id
									snake_case   :			Optional[Any]						    = slow_but_exact

									super().__init__(bos_token_id=_lowercase   ,	eos_token_id=_lowercase   ,	**_lowercase		)



class       _a  ( SCREAMING_SNAKE_CASE__):
			__magic_name__     					=     version.parse("""1.12""")



			def __init__(			self							:				int   ,	_lowercase							:				PretrainedConfig   ,	_lowercase							:				str = "default"   ,	_lowercase							:				List[PatchingSpec] = None   ,	_lowercase							:				bool = False   ,	)							->					Dict:
									super().__init__(_lowercase   ,	task=_lowercase   ,	patching_specs=_lowercase   ,	use_past=_lowercase		)
									if not getattr(self._config   ,	"pad_token_id"   ,	_lowercase		):
															# TODO: how to do that better?
															snake_case   :			int						    = 0



			@property
			def 				__lowercase					(			self							:				str		)							->					Mapping[str, Mapping[int, str]]:
									snake_case   :			int						    = OrderedDict({"input_ids": {0: "batch", 1: "sequence"}}		)
									if self.use_past:
															# BLOOM stores values on dynamic axis 2. For more details see: https://github.com/huggingface/transformers/pull/18344
															self.fill_with_past_key_values_(_lowercase   ,	direction="inputs"   ,	inverted_values_shape=_lowercase		)
															snake_case   :			Optional[int]						    = {0: "batch", 1: "past_sequence + sequence"}
									else:
															snake_case   :			Dict						    = {0: "batch", 1: "sequence"}

									return common_inputs



			@property
			def 				__lowercase					(			self							:				int		)							->					int:
									return self._config.n_layer



			@property
			def 				__lowercase					(			self							:				Dict		)							->					int:
									return self._config.n_head



			@property
			def 				__lowercase					(			self							:				Union[str, Any]		)							->					float:
									return 1E-3



			def 				__lowercase					(			self							:				List[str]   ,	_lowercase							:				"PreTrainedTokenizer"   ,	_lowercase							:				int = -1   ,	_lowercase							:				int = -1   ,	_lowercase							:				bool = False   ,	_lowercase							:				Optional["TensorType"] = None   ,	)							->					Mapping[str, Any]:
									snake_case   :			int						    = super(_lowercase   ,	self		).generate_dummy_inputs(
									    _lowercase   ,	batch_size=_lowercase   ,	seq_length=_lowercase   ,	is_pair=_lowercase   ,	framework=_lowercase		)

									# We need to order the input in the way they appears in the forward()
									snake_case   :			Any						    = OrderedDict({"input_ids": common_inputs["input_ids"]}		)

									# Need to add the past_keys
									if self.use_past:
															if not is_torch_available():
																					raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed."		)
															else:
																					import torch

																					snake_case    ,			snake_case   :			List[str]						    = common_inputs["input_ids"].shape
																					# Not using the same length for past_key_values
																					snake_case   :			Optional[Any]						    = seqlen + 2
																					snake_case   :			Optional[int]						    = self._config.hidden_size // self.num_attention_heads
																					snake_case   :			List[str]						    = (
																					    batch * self.num_attention_heads,
																					    head_dim,
																					    past_key_values_length,
																					)
																					snake_case   :			Any						    = (
																					    batch * self.num_attention_heads,
																					    past_key_values_length,
																					    head_dim,
																					)
																					snake_case   :			Dict						    = [
																					    (torch.zeros(_lowercase		), torch.zeros(_lowercase		)) for _ in range(self.num_layers		)
																					]

									snake_case   :			Tuple						    = common_inputs["attention_mask"]
									if self.use_past:
															snake_case   :			Any						    = ordered_inputs["attention_mask"].dtype
															snake_case   :			List[str]						    = torch.cat(
															    [ordered_inputs["attention_mask"], torch.ones(_lowercase   ,	_lowercase   ,	dtype=_lowercase		)]   ,	dim=1		)

									return ordered_inputs



			@property
			def 				__lowercase					(			self							:				str		)							->					int:
									return 13



