




UpperCamelCase__         =      """0.18.2"""

from .configuration_utils import ConfigMixin
from .utils import (
    OptionalDependencyNotAvailable,
    is_flax_available,
    is_inflect_available,
    is_invisible_watermark_available,
    is_k_diffusion_available,
    is_k_diffusion_version,
    is_librosa_available,
    is_note_seq_available,
    is_onnx_available,
    is_scipy_available,
    is_torch_available,
    is_torchsde_available,
    is_transformers_available,
    is_transformers_version,
    is_unidecode_available,
    logging,
)


try:
					if not is_onnx_available():
										raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
					from .utils.dummy_onnx_objects import *  # noqa F403
else:
					from .pipelines import OnnxRuntimeModel

try:
					if not is_torch_available():
										raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
					from .utils.dummy_pt_objects import *  # noqa F403
else:
					from .models import (
					    AutoencoderKL,
					    ControlNetModel,
					    ModelMixin,
					    PriorTransformer,
					    TaFilmDecoder,
					    TransformeraDModel,
					    UNetaDModel,
					    UNetaDConditionModel,
					    UNetaDModel,
					    UNetaDConditionModel,
					    VQModel,
					)
					from .optimization import (
					    get_constant_schedule,
					    get_constant_schedule_with_warmup,
					    get_cosine_schedule_with_warmup,
					    get_cosine_with_hard_restarts_schedule_with_warmup,
					    get_linear_schedule_with_warmup,
					    get_polynomial_decay_schedule_with_warmup,
					    get_scheduler,
					)
					from .pipelines import (
					    AudioPipelineOutput,
					    ConsistencyModelPipeline,
					    DanceDiffusionPipeline,
					    DDIMPipeline,
					    DDPMPipeline,
					    DiffusionPipeline,
					    DiTPipeline,
					    ImagePipelineOutput,
					    KarrasVePipeline,
					    LDMPipeline,
					    LDMSuperResolutionPipeline,
					    PNDMPipeline,
					    RePaintPipeline,
					    ScoreSdeVePipeline,
					)
					from .schedulers import (
					    CMStochasticIterativeScheduler,
					    DDIMInverseScheduler,
					    DDIMParallelScheduler,
					    DDIMScheduler,
					    DDPMParallelScheduler,
					    DDPMScheduler,
					    DEISMultistepScheduler,
					    DPMSolverMultistepInverseScheduler,
					    DPMSolverMultistepScheduler,
					    DPMSolverSinglestepScheduler,
					    EulerAncestralDiscreteScheduler,
					    EulerDiscreteScheduler,
					    HeunDiscreteScheduler,
					    IPNDMScheduler,
					    KarrasVeScheduler,
					    KDPMaAncestralDiscreteScheduler,
					    KDPMaDiscreteScheduler,
					    PNDMScheduler,
					    RePaintScheduler,
					    SchedulerMixin,
					    ScoreSdeVeScheduler,
					    UnCLIPScheduler,
					    UniPCMultistepScheduler,
					    VQDiffusionScheduler,
					)
					from .training_utils import EMAModel

try:
					if not (is_torch_available() and is_scipy_available()):
										raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
					from .utils.dummy_torch_and_scipy_objects import *  # noqa F403
else:
					from .schedulers import LMSDiscreteScheduler

try:
					if not (is_torch_available() and is_torchsde_available()):
										raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
					from .utils.dummy_torch_and_torchsde_objects import *  # noqa F403
else:
					from .schedulers import DPMSolverSDEScheduler

try:
					if not (is_torch_available() and is_transformers_available()):
										raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
					from .utils.dummy_torch_and_transformers_objects import *  # noqa F403
else:
					from .pipelines import (
					    AltDiffusionImgaImgPipeline,
					    AltDiffusionPipeline,
					    AudioLDMPipeline,
					    CycleDiffusionPipeline,
					    IFImgaImgPipeline,
					    IFImgaImgSuperResolutionPipeline,
					    IFInpaintingPipeline,
					    IFInpaintingSuperResolutionPipeline,
					    IFPipeline,
					    IFSuperResolutionPipeline,
					    ImageTextPipelineOutput,
					    KandinskyImgaImgPipeline,
					    KandinskyInpaintPipeline,
					    KandinskyPipeline,
					    KandinskyPriorPipeline,
					    KandinskyVaaControlnetImgaImgPipeline,
					    KandinskyVaaControlnetPipeline,
					    KandinskyVaaImgaImgPipeline,
					    KandinskyVaaInpaintPipeline,
					    KandinskyVaaPipeline,
					    KandinskyVaaPriorEmbaEmbPipeline,
					    KandinskyVaaPriorPipeline,
					    LDMTextToImagePipeline,
					    PaintByExamplePipeline,
					    SemanticStableDiffusionPipeline,
					    ShapEImgaImgPipeline,
					    ShapEPipeline,
					    StableDiffusionAttendAndExcitePipeline,
					    StableDiffusionControlNetImgaImgPipeline,
					    StableDiffusionControlNetInpaintPipeline,
					    StableDiffusionControlNetPipeline,
					    StableDiffusionDepthaImgPipeline,
					    StableDiffusionDiffEditPipeline,
					    StableDiffusionImageVariationPipeline,
					    StableDiffusionImgaImgPipeline,
					    StableDiffusionInpaintPipeline,
					    StableDiffusionInpaintPipelineLegacy,
					    StableDiffusionInstructPixaPixPipeline,
					    StableDiffusionLatentUpscalePipeline,
					    StableDiffusionLDMaDPipeline,
					    StableDiffusionModelEditingPipeline,
					    StableDiffusionPanoramaPipeline,
					    StableDiffusionParadigmsPipeline,
					    StableDiffusionPipeline,
					    StableDiffusionPipelineSafe,
					    StableDiffusionPixaPixZeroPipeline,
					    StableDiffusionSAGPipeline,
					    StableDiffusionUpscalePipeline,
					    StableUnCLIPImgaImgPipeline,
					    StableUnCLIPPipeline,
					    TextToVideoSDPipeline,
					    TextToVideoZeroPipeline,
					    UnCLIPImageVariationPipeline,
					    UnCLIPPipeline,
					    UniDiffuserModel,
					    UniDiffuserPipeline,
					    UniDiffuserTextDecoder,
					    VersatileDiffusionDualGuidedPipeline,
					    VersatileDiffusionImageVariationPipeline,
					    VersatileDiffusionPipeline,
					    VersatileDiffusionTextToImagePipeline,
					    VideoToVideoSDPipeline,
					    VQDiffusionPipeline,
					)

try:
					if not (is_torch_available() and is_transformers_available() and is_invisible_watermark_available()):
										raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
					from .utils.dummy_torch_and_transformers_and_invisible_watermark_objects import *  # noqa F403
else:
					from .pipelines import StableDiffusionXLImgaImgPipeline, StableDiffusionXLPipeline

try:
					if not (is_torch_available() and is_transformers_available() and is_k_diffusion_available()):
										raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
					from .utils.dummy_torch_and_transformers_and_k_diffusion_objects import *  # noqa F403
else:
					from .pipelines import StableDiffusionKDiffusionPipeline

try:
					if not (is_torch_available() and is_transformers_available() and is_onnx_available()):
										raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
					from .utils.dummy_torch_and_transformers_and_onnx_objects import *  # noqa F403
else:
					from .pipelines import (
					    OnnxStableDiffusionImgaImgPipeline,
					    OnnxStableDiffusionInpaintPipeline,
					    OnnxStableDiffusionInpaintPipelineLegacy,
					    OnnxStableDiffusionPipeline,
					    OnnxStableDiffusionUpscalePipeline,
					    StableDiffusionOnnxPipeline,
					)

try:
					if not (is_torch_available() and is_librosa_available()):
										raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
					from .utils.dummy_torch_and_librosa_objects import *  # noqa F403
else:
					from .pipelines import AudioDiffusionPipeline, Mel

try:
					if not (is_transformers_available() and is_torch_available() and is_note_seq_available()):
										raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
					from .utils.dummy_transformers_and_torch_and_note_seq_objects import *  # noqa F403
else:
					from .pipelines import SpectrogramDiffusionPipeline

try:
					if not is_flax_available():
										raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
					from .utils.dummy_flax_objects import *  # noqa F403
else:
					from .models.controlnet_flax import FlaxControlNetModel
					from .models.modeling_flax_utils import FlaxModelMixin
					from .models.unet_ad_condition_flax import FlaxUNetaDConditionModel
					from .models.vae_flax import FlaxAutoencoderKL
					from .pipelines import FlaxDiffusionPipeline
					from .schedulers import (
					    FlaxDDIMScheduler,
					    FlaxDDPMScheduler,
					    FlaxDPMSolverMultistepScheduler,
					    FlaxKarrasVeScheduler,
					    FlaxLMSDiscreteScheduler,
					    FlaxPNDMScheduler,
					    FlaxSchedulerMixin,
					    FlaxScoreSdeVeScheduler,
					)


try:
					if not (is_flax_available() and is_transformers_available()):
										raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
					from .utils.dummy_flax_and_transformers_objects import *  # noqa F403
else:
					from .pipelines import (
					    FlaxStableDiffusionControlNetPipeline,
					    FlaxStableDiffusionImgaImgPipeline,
					    FlaxStableDiffusionInpaintPipeline,
					    FlaxStableDiffusionPipeline,
					)

try:
					if not (is_note_seq_available()):
										raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
					from .utils.dummy_note_seq_objects import *  # noqa F403
else:
					from .pipelines import MidiProcessor










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


UpperCamelCase__         =      logging.get_logger(__name__)

UpperCamelCase__         =      list(MODEL_FOR_QUESTION_ANSWERING_MAPPING.keys())
UpperCamelCase__         =      tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)
@dataclass
class       a__   :
						_a							:   str =   field(
						    default=snake_case__			,    metadata={"""help""": """Model type selected in the list: """ + """, """.join(snake_case__				)}				)
						_a							:   str =   field(
						    default=snake_case__			,    metadata={"""help""": """The input data dir. Should contain the .json files for the SQuAD task."""}				)
						_a							:   int =   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							:   int =   field(
						    default=1_2_8			,    metadata={"""help""": """When splitting up a long document into chunks, how much stride to take between chunks."""}			,    )
						_a							:   int =   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							:   int =   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							:   bool =   field(
						    default=snake_case__			,    metadata={"""help""": """Overwrite the cached training and evaluation sets"""}				)
						_a							:   bool =   field(
						    default=snake_case__			,    metadata={"""help""": """If true, the SQuAD examples contain some that do not have an answer."""}				)
						_a							:   float =   field(
						    default=0.0			,    metadata={"""help""": """If null_score - best_non_null is greater than the threshold predict null."""}				)
						_a							:   int =   field(
						    default=2_0			,    metadata={"""help""": """If null_score - best_non_null is greater than the threshold predict null."""}				)
						_a							:   int =   field(
						    default=0			,    metadata={
						        """help""": (
						            """language id of input for language-specific xlm models (see"""
						            """ tokenization_xlm.PRETRAINED_INIT_CONFIGURATION)"""
						        )
						    }			,    )
						_a							:   int =   field(default=1			,    metadata={"""help""": """multiple threads for converting example to features"""}				)






class       a__   ( snake_case__				):
						_a							:   Any =   """train"""
						_a							:   Union[str, Any] =   """dev"""






class       a__   ( snake_case__				):
						_a							:   SquadDataTrainingArguments
						_a							:   List[SquadFeatures]
						_a							:   Split
						_a							:   bool






						def __init__(       self		,      _A		,      _A		,      _A = None		,      _A = Split.train		,      _A = False		,      _A = None		,      _A = "pt"		,      ):




											"""simple docstring"""



											__lowerCAmelCase           =	args
											__lowerCAmelCase           =	is_language_sensitive
											__lowerCAmelCase           =	SquadVaProcessor() if args.version_2_with_negative else SquadVaProcessor()
											if isinstance(_A		,      _A      ):
																try:
																					__lowerCAmelCase           =	Split[mode]
																except KeyError:
																					raise KeyError("mode is not a valid split name"      )
											__lowerCAmelCase           =	mode
											# Load data features from cache or dataset file
											__lowerCAmelCase           =	"v2" if args.version_2_with_negative else "v1"
											__lowerCAmelCase           =	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           =	cached_features_file + ".lock"
											with FileLock(_A      ):
																if os.path.exists(_A      ) and not args.overwrite_cache:
																					__lowerCAmelCase           =	time.time()
																					__lowerCAmelCase           =	torch.load(_A      )

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

																					__lowerCAmelCase       ,							__lowerCAmelCase           =	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           =	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           =	self.features[i]

											__lowerCAmelCase           =	torch.tensor(feature.input_ids		,      dtype=torch.long      )
											__lowerCAmelCase           =	torch.tensor(feature.attention_mask		,      dtype=torch.long      )
											__lowerCAmelCase           =	torch.tensor(feature.token_type_ids		,      dtype=torch.long      )
											__lowerCAmelCase           =	torch.tensor(feature.cls_index		,      dtype=torch.long      )
											__lowerCAmelCase           =	torch.tensor(feature.p_mask		,      dtype=torch.float      )
											__lowerCAmelCase           =	torch.tensor(feature.is_impossible		,      dtype=torch.float      )

											__lowerCAmelCase           =	{
											    "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           =	torch.tensor(feature.start_position		,      dtype=torch.long      )
																__lowerCAmelCase           =	torch.tensor(feature.end_position		,      dtype=torch.long      )
																inputs.update({"start_positions": start_positions, "end_positions": end_positions}      )

											return inputs




