

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






class 			lowerCamelCase_    (  lowercase		):
							__lowercase				:	str        =				"train"
							__lowercase				:	List[str]        =				"dev"






class 			lowerCamelCase_    (  lowercase		):
							__lowercase				:	str        =				42
							__lowercase				:	str        =				42
							__lowercase				:	Optional[int]        =				42
							__lowercase				:	Any        =				42


							def __init__( self      ,				lowerCamelCase_      ,				lowerCamelCase_      ,				lowerCamelCase_ = None      ,				lowerCamelCase_ = Split.train      ,				lowerCamelCase_ = False      ,				lowerCamelCase_ = None      ,				lowerCamelCase_ = "pt"      ,				)							->   Dict:



								"""simple docstring"""

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

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

										_UpperCamelCase			=   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_      ,				)

										_UpperCamelCase			=   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						)							->   str:



								"""simple docstring"""

								return len(self.features						)







							def __getitem__( self      ,				lowerCamelCase_						)							->   int:



								"""simple docstring"""

								_UpperCamelCase			=   self.features[i]

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

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

								return inputs








import random
import unittest

import numpy as np
import torch

from diffusers import (
    DPMSolverMultistepScheduler,
    EulerAncestralDiscreteScheduler,
    EulerDiscreteScheduler,
    LMSDiscreteScheduler,
    OnnxStableDiffusionUpscalePipeline,
    PNDMScheduler,
)
from diffusers.utils import floats_tensor
from diffusers.utils.testing_utils import (
    is_onnx_available,
    load_image,
    nightly,
    require_onnxruntime,
    require_torch_gpu,
)

from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin


if is_onnx_available():
 import onnxruntime as ort


class 		_SCREAMING_SNAKE_CASE     (						A							,	unittest.TestCase     ):
     # TODO: is there an appropriate internal test set?
     __SCREAMING_SNAKE_CASE     					=    '''ssube/stable-diffusion-x4-upscaler-onnx'''


     def        __snake_case(  self							,					A_=0    ):
       _UpperCAmelCase		:							List[Any]							=     floats_tensor((1, 3, 1_28, 1_28)							,					rng=random.Random(A_    )    )
       _UpperCAmelCase		:							Any							=     torch.manual_seed(A_    )
       _UpperCAmelCase		:							List[Any]							=     {
           """prompt""": """A painting of a squirrel eating a burger""",
           """image""": image,
           """generator""": generator,
           """num_inference_steps""": 3,
           """guidance_scale""": 7.5,
           """output_type""": """numpy""",
       }
       return inputs


     def        __snake_case(  self    ):
       _UpperCAmelCase		:							Optional[int]							=     OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint							,					provider="""CPUExecutionProvider"""    )
       pipe.set_progress_bar_config(disable=A_    )

       _UpperCAmelCase		:							Optional[Any]							=     self.get_dummy_inputs()
       _UpperCAmelCase		:							List[str]							=     pipe(**A_    ).images
       _UpperCAmelCase		:							Tuple							=     image[0, -3:, -3:, -1].flatten()

       # started as 128, should now be 512
       assert image.shape == (1, 5_12, 5_12, 3)
       _UpperCAmelCase		:							Any							=     np.array(
           [0.6_9_7_4_7_8_2, 0.6_8_9_0_2_0_9_3, 0.7_0_1_3_5_8_8_5, 0.7_5_8_3_6_1_8, 0.7_8_0_4_5_4_5, 0.7_8_5_4_9_1_2, 0.7_8_6_6_7_4_2_6, 0.7_8_7_4_3_8_6_3, 0.7_8_0_7_0_2_2_3]    )
       assert np.abs(image_slice - expected_slice    ).max() < 1e-1


     def        __snake_case(  self    ):
       _UpperCAmelCase		:							int							=     OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint							,					provider="""CPUExecutionProvider"""    )
       _UpperCAmelCase		:							Tuple							=     PNDMScheduler.from_config(pipe.scheduler.config							,					skip_prk_steps=A_    )
       pipe.set_progress_bar_config(disable=A_    )

       _UpperCAmelCase		:							Optional[Any]							=     self.get_dummy_inputs()
       _UpperCAmelCase		:							Optional[Any]							=     pipe(**A_    ).images
       _UpperCAmelCase		:							Dict							=     image[0, -3:, -3:, -1]

       assert image.shape == (1, 5_12, 5_12, 3)
       _UpperCAmelCase		:							Optional[Any]							=     np.array(
           [0.6_8_9_8_8_9_2, 0.5_9_2_4_0_5_5_6, 0.5_2_4_9_9_5_2_7, 0.5_8_8_6_6_2_1_5, 0.5_2_2_5_8_2_3_5, 0.5_2_5_7_2_7_1_5, 0.6_2_4_1_4_4_7_3, 0.6_1_7_4_3_8_7, 0.6_2_1_4_9_6_4]    )
       assert np.abs(image_slice.flatten() - expected_slice    ).max() < 1e-1


     def        __snake_case(  self    ):
       _UpperCAmelCase		:							List[str]							=     OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint							,					provider="""CPUExecutionProvider"""    )
       _UpperCAmelCase		:							Dict							=     DPMSolverMultistepScheduler.from_config(pipe.scheduler.config    )
       pipe.set_progress_bar_config(disable=A_    )

       _UpperCAmelCase		:							str							=     self.get_dummy_inputs()
       _UpperCAmelCase		:							List[Any]							=     pipe(**A_    ).images
       _UpperCAmelCase		:							Any							=     image[0, -3:, -3:, -1]

       assert image.shape == (1, 5_12, 5_12, 3)
       _UpperCAmelCase		:							Tuple							=     np.array(
           [0.7_6_5_9_2_7_8, 0.7_6_4_3_7_6_6_4, 0.7_5_5_7_9_1_0_7, 0.7_6_9_1_1_1_6, 0.7_7_6_6_6_9_8_6, 0.7_7_2_7_6_7_2, 0.7_7_5_8_6_6_4, 0.7_8_1_2_2_2_6, 0.7_6_9_4_2_5_1_5]    )

       assert np.abs(image_slice.flatten() - expected_slice    ).max() < 1e-1


     def        __snake_case(  self    ):
       _UpperCAmelCase		:							Tuple							=     OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint							,					provider="""CPUExecutionProvider"""    )
       _UpperCAmelCase		:							Dict							=     EulerDiscreteScheduler.from_config(pipe.scheduler.config    )
       pipe.set_progress_bar_config(disable=A_    )

       _UpperCAmelCase		:							Union[str, Any]							=     self.get_dummy_inputs()
       _UpperCAmelCase		:							Union[str, Any]							=     pipe(**A_    ).images
       _UpperCAmelCase		:							int							=     image[0, -3:, -3:, -1]

       assert image.shape == (1, 5_12, 5_12, 3)
       _UpperCAmelCase		:							List[Any]							=     np.array(
           [0.6_9_7_4_7_8_2, 0.6_8_9_0_2_0_9_3, 0.7_0_1_3_5_8_8_5, 0.7_5_8_3_6_1_8, 0.7_8_0_4_5_4_5, 0.7_8_5_4_9_1_2, 0.7_8_6_6_7_4_2_6, 0.7_8_7_4_3_8_6_3, 0.7_8_0_7_0_2_2_3]    )
       assert np.abs(image_slice.flatten() - expected_slice    ).max() < 1e-1




     def        __snake_case(  self    ):
       _UpperCAmelCase		:							List[str]							=     OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint							,					provider="""CPUExecutionProvider"""    )
       _UpperCAmelCase		:							List[Any]							=     EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config    )
       pipe.set_progress_bar_config(disable=A_    )

       _UpperCAmelCase		:							Union[str, Any]							=     self.get_dummy_inputs()
       _UpperCAmelCase		:							str							=     pipe(**A_    ).images
       _UpperCAmelCase		:							Optional[int]							=     image[0, -3:, -3:, -1]

       assert image.shape == (1, 5_12, 5_12, 3)
       _UpperCAmelCase		:							Tuple							=     np.array(
           [0.7_7_4_2_4_4_9_6, 0.7_7_3_6_0_1, 0.7_6_4_5_2_8_8, 0.7_7_6_9_5_9_8, 0.7_7_7_2_7_3_9, 0.7_7_3_8_6_8_8, 0.7_8_1_8_7_2_3_3, 0.7_7_8_7_9_5_8_4, 0.7_6_7_0_4_3]    )

       assert np.abs(image_slice.flatten() - expected_slice    ).max() < 1e-1


@nightly
@require_onnxruntime
@require_torch_gpu
class 		_SCREAMING_SNAKE_CASE     (						unittest.TestCase     ):


     @property
     def        __snake_case(  self    ):
       return (
           "CUDAExecutionProvider",
           {
               "gpu_mem_limit": "15000000000",  # 15GB
               "arena_extend_strategy": "kSameAsRequested",
           },
       )


     @property
     def        __snake_case(  self    ):
       _UpperCAmelCase		:							List[str]							=     ort.SessionOptions()
       _UpperCAmelCase		:							Union[str, Any]							=     False
       return options


     def        __snake_case(  self    ):
       _UpperCAmelCase		:							List[Any]							=     load_image(
           """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
           """/img2img/sketch-mountains-input.jpg"""    )
       _UpperCAmelCase		:							Any							=     init_image.resize((1_28, 1_28)    )
       # using the PNDM scheduler by default
       _UpperCAmelCase		:							Union[str, Any]							=     OnnxStableDiffusionUpscalePipeline.from_pretrained(
           """ssube/stable-diffusion-x4-upscaler-onnx"""							,					provider=self.gpu_provider							,					sess_options=self.gpu_options							,					)
       pipe.set_progress_bar_config(disable=A_    )

       _UpperCAmelCase		:							Union[str, Any]							=     """A fantasy landscape, trending on artstation"""

       _UpperCAmelCase		:							Tuple							=     torch.manual_seed(0    )
       _UpperCAmelCase		:							Tuple							=     pipe(
           prompt=A_							,					image=A_							,					guidance_scale=7.5							,					num_inference_steps=10							,					generator=A_							,					output_type="""np"""							,					)
       _UpperCAmelCase		:							Dict							=     output.images
       _UpperCAmelCase		:							List[Any]							=     images[0, 2_55:2_58, 3_83:3_86, -1]

       assert images.shape == (1, 5_12, 5_12, 3)
       _UpperCAmelCase		:							List[str]							=     np.array([0.4_8_8_3, 0.4_9_4_7, 0.4_9_8_0, 0.4_9_7_5, 0.4_9_8_2, 0.4_9_8_0, 0.5_0_0_0, 0.5_0_0_6, 0.4_9_7_2]    )
       # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues

       assert np.abs(image_slice.flatten() - expected_slice    ).max() < 2e-2




     def        __snake_case(  self    ):
       _UpperCAmelCase		:							List[str]							=     load_image(
           """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
           """/img2img/sketch-mountains-input.jpg"""    )
       _UpperCAmelCase		:							Optional[int]							=     init_image.resize((1_28, 1_28)    )
       _UpperCAmelCase		:							Optional[int]							=     LMSDiscreteScheduler.from_pretrained(
           """ssube/stable-diffusion-x4-upscaler-onnx"""							,					subfolder="""scheduler"""    )
       _UpperCAmelCase		:							Union[str, Any]							=     OnnxStableDiffusionUpscalePipeline.from_pretrained(
           """ssube/stable-diffusion-x4-upscaler-onnx"""							,					scheduler=A_							,					provider=self.gpu_provider							,					sess_options=self.gpu_options							,					)
       pipe.set_progress_bar_config(disable=A_    )

       _UpperCAmelCase		:							Union[str, Any]							=     """A fantasy landscape, trending on artstation"""

       _UpperCAmelCase		:							str							=     torch.manual_seed(0    )
       _UpperCAmelCase		:							Optional[int]							=     pipe(
           prompt=A_							,					image=A_							,					guidance_scale=7.5							,					num_inference_steps=20							,					generator=A_							,					output_type="""np"""							,					)
       _UpperCAmelCase		:							Dict							=     output.images
       _UpperCAmelCase		:							Dict							=     images[0, 2_55:2_58, 3_83:3_86, -1]

       assert images.shape == (1, 5_12, 5_12, 3)
       _UpperCAmelCase		:							Optional[Any]							=     np.array(
           [0.5_0_1_7_3_7_5_3, 0.5_0_2_2_3_3_5_6, 0.5_0_2_0_3_9, 0.5_0_2_3_3_0_3_6, 0.5_0_2_3_7_2_5, 0.5_0_2_2_6_0_1, 0.5_0_1_8_7_5_8, 0.5_0_2_3_4_0_8_5, 0.5_0_2_4_1_5_6_6]    )
       # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues

       assert np.abs(image_slice.flatten() - expected_slice    ).max() < 2e-2





