

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


lowerCAmelCase__										= logging.get_logger(__name__)

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



@dataclass
class 					lowercase						:
							_lowerCamelCase		:      str=   field(
							    default=a_,					metadata={"help": "Model type selected in the list: " + ", ".join(a_ )} )
							_lowerCamelCase		:      str=   field(
							    default=a_,					metadata={"help": "The input data dir. Should contain the .json files for the SQuAD task."} )
							_lowerCamelCase		:      int=   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		:      int=   field(
							    default=128,					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=a_,					metadata={"help": "Overwrite the cached training and evaluation sets"} )
							_lowerCamelCase		:      bool=   field(
							    default=a_,					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 					lowercase						(  a_ ):
							_lowerCamelCase		:      str=   "train"
							_lowerCamelCase		:      Optional[Any]=   "dev"



class 					lowercase						(  a_ ):
							_lowerCamelCase		:      SquadDataTrainingArguments
							_lowerCamelCase		:      List[SquadFeatures]
							_lowerCamelCase		:      Split
							_lowerCamelCase		:      bool


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

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

										UpperCAmelCase_		:      Any       	=					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    ,			)

										UpperCAmelCase_		:      Optional[int]       	=					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)							->				str:
								return len(self.features)





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

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

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

								return inputs









'''simple docstring'''


from dataclasses import dataclass
from typing import Optional, Tuple, Union

import torch
import torch.nn as nn

from ..configuration_utils import ConfigMixin, register_to_config
from ..utils import BaseOutput
from .embeddings import GaussianFourierProjection, TimestepEmbedding, Timesteps
from .modeling_utils import ModelMixin
from .unet_ad_blocks import get_down_block, get_mid_block, get_out_block, get_up_block



@dataclass
class 					lowercase						(  a_ ):
							_lowerCamelCase		:      torch.FloatTensor



class 					lowercase						(  a_,					a_ ):


							@register_to_config
							def __init__(			self    ,			_snake_case = 6_5536    ,			_snake_case = None    ,			_snake_case = 2    ,			_snake_case = 2    ,			_snake_case = 0    ,			_snake_case = "fourier"    ,			_snake_case = True    ,			_snake_case = False    ,			_snake_case = 0.0    ,			_snake_case = ("DownBlock1DNoSkip", "DownBlock1D", "AttnDownBlock1D")    ,			_snake_case = ("AttnUpBlock1D", "UpBlock1D", "UpBlock1DNoSkip")    ,			_snake_case = "UNetMidBlock1D"    ,			_snake_case = None    ,			_snake_case = (32, 32, 64)    ,			_snake_case = None    ,			_snake_case = 8    ,			_snake_case = 1    ,			_snake_case = False    ,			)							->				List[str]:
								super().__init__()
								UpperCAmelCase_		:      Optional[Any]       	=					sample_size

								# time
								if time_embedding_type == "fourier":
									UpperCAmelCase_		:      Tuple       	=					GaussianFourierProjection(
									    embedding_size=8    ,			set_W_to_weight=_snake_case    ,			log=_snake_case    ,			flip_sin_to_cos=_snake_case)
									UpperCAmelCase_		:      int       	=					2 * block_out_channels[0]
								elif time_embedding_type == "positional":
									UpperCAmelCase_		:      Optional[Any]       	=					Timesteps(
									    block_out_channels[0]    ,			flip_sin_to_cos=_snake_case    ,			downscale_freq_shift=_snake_case)
									UpperCAmelCase_		:      List[Any]       	=					block_out_channels[0]

								if use_timestep_embedding:
									UpperCAmelCase_		:      Dict       	=					block_out_channels[0] * 4
									UpperCAmelCase_		:      List[Any]       	=					TimestepEmbedding(
									    in_channels=_snake_case    ,			time_embed_dim=_snake_case    ,			act_fn=_snake_case    ,			out_dim=block_out_channels[0]    ,			)

								UpperCAmelCase_		:      int       	=					nn.ModuleList([])
								UpperCAmelCase_		:      Optional[int]       	=					None
								UpperCAmelCase_		:      Optional[int]       	=					nn.ModuleList([])
								UpperCAmelCase_		:      Any       	=					None

								# down
								UpperCAmelCase_		:      Dict       	=					in_channels
								for i, down_block_type in enumerate(_snake_case):
									UpperCAmelCase_		:      int       	=					output_channel
									UpperCAmelCase_		:      Optional[int]       	=					block_out_channels[i]

									if i == 0:
										input_channel += extra_in_channels

									UpperCAmelCase_		:      int       	=					i == len(_snake_case) - 1

									UpperCAmelCase_		:      Any       	=					get_down_block(
									    _snake_case    ,			num_layers=_snake_case    ,			in_channels=_snake_case    ,			out_channels=_snake_case    ,			temb_channels=block_out_channels[0]    ,			add_downsample=not is_final_block or downsample_each_block    ,			)
									self.down_blocks.append(_snake_case)

								# mid
								UpperCAmelCase_		:      Optional[int]       	=					get_mid_block(
								    _snake_case    ,			in_channels=block_out_channels[-1]    ,			mid_channels=block_out_channels[-1]    ,			out_channels=block_out_channels[-1]    ,			embed_dim=block_out_channels[0]    ,			num_layers=_snake_case    ,			add_downsample=_snake_case    ,			)

								# up
								UpperCAmelCase_		:      Union[str, Any]       	=					list(reversed(_snake_case))
								UpperCAmelCase_		:      Optional[int]       	=					reversed_block_out_channels[0]
								if out_block_type is None:
									UpperCAmelCase_		:      Tuple       	=					out_channels
								else:
									UpperCAmelCase_		:      int       	=					block_out_channels[0]

								for i, up_block_type in enumerate(_snake_case):
									UpperCAmelCase_		:      Dict       	=					output_channel
									UpperCAmelCase_		:      Optional[Any]       	=					(
									    reversed_block_out_channels[i + 1] if i < len(_snake_case) - 1 else final_upsample_channels
									)

									UpperCAmelCase_		:      str       	=					i == len(_snake_case) - 1

									UpperCAmelCase_		:      Union[str, Any]       	=					get_up_block(
									    _snake_case    ,			num_layers=_snake_case    ,			in_channels=_snake_case    ,			out_channels=_snake_case    ,			temb_channels=block_out_channels[0]    ,			add_upsample=not is_final_block    ,			)
									self.up_blocks.append(_snake_case)
									UpperCAmelCase_		:      Dict       	=					output_channel

								# out
								UpperCAmelCase_		:      Union[str, Any]       	=					norm_num_groups if norm_num_groups is not None else min(block_out_channels[0] // 4    ,			32)
								UpperCAmelCase_		:      Any       	=					get_out_block(
								    out_block_type=_snake_case    ,			num_groups_out=_snake_case    ,			embed_dim=block_out_channels[0]    ,			out_channels=_snake_case    ,			act_fn=_snake_case    ,			fc_dim=block_out_channels[-1] // 4    ,			)





							def 						_snake_case							(			self    ,			_snake_case    ,			_snake_case    ,			_snake_case = True    ,			)							->				Union[UNetaDOutput, Tuple]:
								UpperCAmelCase_		:      Union[str, Any]       	=					timestep
								if not torch.is_tensor(_snake_case):
									UpperCAmelCase_		:      Union[str, Any]       	=					torch.tensor([timesteps]    ,			dtype=torch.long    ,			device=sample.device)
								elif torch.is_tensor(_snake_case) and len(timesteps.shape) == 0:
									UpperCAmelCase_		:      Tuple       	=					timesteps[None].to(sample.device)

								UpperCAmelCase_		:      Any       	=					self.time_proj(_snake_case)
								if self.config.use_timestep_embedding:
									UpperCAmelCase_		:      int       	=					self.time_mlp(_snake_case)
								else:
									UpperCAmelCase_		:      int       	=					timestep_embed[..., None]
									UpperCAmelCase_		:      List[Any]       	=					timestep_embed.repeat([1, 1, sample.shape[2]]).to(sample.dtype)
									UpperCAmelCase_		:      int       	=					timestep_embed.broadcast_to((sample.shape[:1] + timestep_embed.shape[1:]))

								# 2. down
								UpperCAmelCase_		:      Optional[Any]       	=					()
								for downsample_block in self.down_blocks:
									UpperCAmelCase_	,    UpperCAmelCase_		:      Optional[int]       	=					downsample_block(hidden_states=_snake_case    ,			temb=_snake_case)
									down_block_res_samples += res_samples

								# 3. mid
								if self.mid_block:
									UpperCAmelCase_		:      List[Any]       	=					self.mid_block(_snake_case    ,			_snake_case)

								# 4. up
								for i, upsample_block in enumerate(self.up_blocks):
									UpperCAmelCase_		:      int       	=					down_block_res_samples[-1:]
									UpperCAmelCase_		:      Tuple       	=					down_block_res_samples[:-1]
									UpperCAmelCase_		:      List[Any]       	=					upsample_block(_snake_case    ,			res_hidden_states_tuple=_snake_case    ,			temb=_snake_case)

								# 5. post-process
								if self.out_block:
									UpperCAmelCase_		:      Optional[Any]       	=					self.out_block(_snake_case    ,			_snake_case)

								if not return_dict:
									return (sample,)

								return UNetaDOutput(sample=_snake_case)






