

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 	A_		(	SCREAMING_SNAKE_CASE      ,							unittest.TestCase    ):
							# TODO: is there an appropriate internal test set?
							_UpperCAmelCase   :  Optional[Any]										=				'''ssube/stable-diffusion-x4-upscaler-onnx'''
							def    lowerCAmelCase					(		self		:      Optional[int]       ,SCREAMING_SNAKE_CASE__		:      str=0):
								__lowerCamelCase    :    int 	=			floats_tensor((1, 3, 1_2_8, 1_2_8)       ,rng=random.Random(SCREAMING_SNAKE_CASE__))
								__lowerCamelCase    :    Any 	=			torch.manual_seed(SCREAMING_SNAKE_CASE__)
								__lowerCamelCase    :    List[str] 	=			{
								    '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    lowerCAmelCase					(		self		:      int):
								__lowerCamelCase    :    int 	=			OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint       ,provider='CPUExecutionProvider')
								pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__)

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

								# started as 128, should now be 512
								assert image.shape == (1, 5_1_2, 5_1_2, 3)
								__lowerCamelCase    :    List[str] 	=			np.array(
								    [0.6974782, 0.68902093, 0.70135885, 0.7583618, 0.7804545, 0.7854912, 0.78667426, 0.78743863, 0.78070223])
								assert np.abs(image_slice - expected_slice).max() < 1E-1
							def    lowerCAmelCase					(		self		:      str):
								__lowerCamelCase    :    List[str] 	=			OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint       ,provider='CPUExecutionProvider')
								__lowerCamelCase    :    List[Any] 	=			PNDMScheduler.from_config(pipe.scheduler.config       ,skip_prk_steps=SCREAMING_SNAKE_CASE__)
								pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__)

								__lowerCamelCase    :    Optional[int] 	=			self.get_dummy_inputs()
								__lowerCamelCase    :    List[Any] 	=			pipe(**SCREAMING_SNAKE_CASE__).images
								__lowerCamelCase    :    Dict 	=			image[0, -3:, -3:, -1]

								assert image.shape == (1, 5_1_2, 5_1_2, 3)
								__lowerCamelCase    :    str 	=			np.array(
								    [0.6898892, 0.59240556, 0.52499527, 0.58866215, 0.52258235, 0.52572715, 0.62414473, 0.6174387, 0.6214964])
								assert np.abs(image_slice.flatten() - expected_slice).max() < 1E-1
							def    lowerCAmelCase					(		self		:      Union[str, Any]):
								__lowerCamelCase    :    Any 	=			OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint       ,provider='CPUExecutionProvider')
								__lowerCamelCase    :    int 	=			DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)
								pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__)

								__lowerCamelCase    :    Dict 	=			self.get_dummy_inputs()
								__lowerCamelCase    :    Union[str, Any] 	=			pipe(**SCREAMING_SNAKE_CASE__).images
								__lowerCamelCase    :    Any 	=			image[0, -3:, -3:, -1]

								assert image.shape == (1, 5_1_2, 5_1_2, 3)
								__lowerCamelCase    :    Optional[int] 	=			np.array(
								    [0.7659278, 0.76437664, 0.75579107, 0.7691116, 0.77666986, 0.7727672, 0.7758664, 0.7812226, 0.76942515])

								assert np.abs(image_slice.flatten() - expected_slice).max() < 1E-1
							def    lowerCAmelCase					(		self		:      Dict):
								__lowerCamelCase    :    Optional[Any] 	=			OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint       ,provider='CPUExecutionProvider')
								__lowerCamelCase    :    int 	=			EulerDiscreteScheduler.from_config(pipe.scheduler.config)
								pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__)

								__lowerCamelCase    :    Dict 	=			self.get_dummy_inputs()
								__lowerCamelCase    :    int 	=			pipe(**SCREAMING_SNAKE_CASE__).images
								__lowerCamelCase    :    Any 	=			image[0, -3:, -3:, -1]

								assert image.shape == (1, 5_1_2, 5_1_2, 3)
								__lowerCamelCase    :    Union[str, Any] 	=			np.array(
								    [0.6974782, 0.68902093, 0.70135885, 0.7583618, 0.7804545, 0.7854912, 0.78667426, 0.78743863, 0.78070223])
								assert np.abs(image_slice.flatten() - expected_slice).max() < 1E-1


							def    lowerCAmelCase					(		self		:      Optional[Any]):
								__lowerCamelCase    :    List[str] 	=			OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint       ,provider='CPUExecutionProvider')
								__lowerCamelCase    :    Dict 	=			EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config)
								pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__)

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

								assert image.shape == (1, 5_1_2, 5_1_2, 3)
								__lowerCamelCase    :    Dict 	=			np.array(
								    [0.77424496, 0.773601, 0.7645288, 0.7769598, 0.7772739, 0.7738688, 0.78187233, 0.77879584, 0.767043])

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






@nightly
@require_onnxruntime
@require_torch_gpu
class 	A_		(	unittest.TestCase    ):
							@property
							def    lowerCAmelCase					(		self		:      Optional[int]):
								return (
								    "CUDAExecutionProvider",
								    {
								        "gpu_mem_limit": "15000000000",  # 15GB
								        "arena_extend_strategy": "kSameAsRequested",
								    },
								)
							@property
							def    lowerCAmelCase					(		self		:      List[Any]):
								__lowerCamelCase    :    int 	=			ort.SessionOptions()
								__lowerCamelCase    :    List[Any] 	=			False
								return options
							def    lowerCAmelCase					(		self		:      List[Any]):
								__lowerCamelCase    :    str 	=			load_image(
								    'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
								    '/img2img/sketch-mountains-input.jpg')
								__lowerCamelCase    :    Union[str, Any] 	=			init_image.resize((1_2_8, 1_2_8))
								# using the PNDM scheduler by default
								__lowerCamelCase    :    int 	=			OnnxStableDiffusionUpscalePipeline.from_pretrained(
								    'ssube/stable-diffusion-x4-upscaler-onnx'       ,provider=self.gpu_provider       ,sess_options=self.gpu_options       ,)
								pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__)

								__lowerCamelCase    :    Optional[int] 	=			'A fantasy landscape, trending on artstation'

								__lowerCamelCase    :    Optional[Any] 	=			torch.manual_seed(0)
								__lowerCamelCase    :    Union[str, Any] 	=			pipe(
								    prompt=SCREAMING_SNAKE_CASE__       ,image=SCREAMING_SNAKE_CASE__       ,guidance_scale=7.5       ,num_inference_steps=1_0       ,generator=SCREAMING_SNAKE_CASE__       ,output_type='np'       ,)
								__lowerCamelCase    :    Union[str, Any] 	=			output.images
								__lowerCamelCase    :    Optional[int] 	=			images[0, 2_5_5:2_5_8, 3_8_3:3_8_6, -1]

								assert images.shape == (1, 5_1_2, 5_1_2, 3)
								__lowerCamelCase    :    List[Any] 	=			np.array([0.4883, 0.4947, 0.4980, 0.4975, 0.4982, 0.4980, 0.5000, 0.5006, 0.4972])
								# TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues

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


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

								__lowerCamelCase    :    Optional[Any] 	=			'A fantasy landscape, trending on artstation'

								__lowerCamelCase    :    List[Any] 	=			torch.manual_seed(0)
								__lowerCamelCase    :    Dict 	=			pipe(
								    prompt=SCREAMING_SNAKE_CASE__       ,image=SCREAMING_SNAKE_CASE__       ,guidance_scale=7.5       ,num_inference_steps=2_0       ,generator=SCREAMING_SNAKE_CASE__       ,output_type='np'       ,)
								__lowerCamelCase    :    int 	=			output.images
								__lowerCamelCase    :    str 	=			images[0, 2_5_5:2_5_8, 3_8_3:3_8_6, -1]

								assert images.shape == (1, 5_1_2, 5_1_2, 3)
								__lowerCamelCase    :    List[Any] 	=			np.array(
								    [0.50173753, 0.50223356, 0.502039, 0.50233036, 0.5023725, 0.5022601, 0.5018758, 0.50234085, 0.50241566])
								# TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues

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







import math
import os
from copy import deepcopy

import datasets
import evaluate
import torch
import transformers
from datasets import load_dataset
from torch.utils.data import DataLoader
from transformers import AutoModelForSequenceClassification, AutoTokenizer

from accelerate import Accelerator
from accelerate.test_utils import RegressionDataset, RegressionModel
from accelerate.utils import is_tpu_available, set_seed


a		="""true"""






def        SCREAMING_SNAKE_CASE__	(  lowerCamelCase__     ,			lowerCamelCase__=8_2     ,			lowerCamelCase__=1_6      )  ->					List[Any]:
	set_seed(4_2      )
	__lowerCamelCase    :    Tuple 	=			RegressionModel()
	__lowerCamelCase    :    str 	=			deepcopy(lowerCamelCase__      )
	__lowerCamelCase    :    Optional[int] 	=			RegressionDataset(length=lowerCamelCase__      )
	__lowerCamelCase    :    Union[str, Any] 	=			DataLoader(lowerCamelCase__     ,			batch_size=lowerCamelCase__      )
	model.to(accelerator.device      )
	__lowerCamelCase	,			__lowerCamelCase    :    Tuple 	=			accelerator.prepare(lowerCamelCase__     ,			lowerCamelCase__      )
	return model, ddp_model, dataloader






def        SCREAMING_SNAKE_CASE__	(  lowerCamelCase__     ,			lowerCamelCase__=False      )  ->					List[Any]:
	__lowerCamelCase    :    Tuple 	=			AutoTokenizer.from_pretrained('hf-internal-testing/mrpc-bert-base-cased'      )
	__lowerCamelCase    :    Any 	=			load_dataset('glue'     ,			'mrpc'     ,			split='validation'      )

	def tokenize_function(lowerCamelCase__      ):
		__lowerCamelCase    :    Union[str, Any] 	=			tokenizer(examples['sentence1']     ,			examples['sentence2']     ,			truncation=lowerCamelCase__     ,			max_length=lowerCamelCase__      )
		return outputs

	with accelerator.main_process_first():
		__lowerCamelCase    :    Union[str, Any] 	=			dataset.map(
		    lowerCamelCase__     ,			batched=lowerCamelCase__     ,			remove_columns=['idx', 'sentence1', 'sentence2']     ,			)

	__lowerCamelCase    :    Tuple 	=			tokenized_datasets.rename_column('label'     ,			'labels'      )

	def collate_fn(lowerCamelCase__      ):
		if use_longest:
			return tokenizer.pad(lowerCamelCase__     ,			padding='longest'     ,			return_tensors='pt'      )
		return tokenizer.pad(lowerCamelCase__     ,			padding='max_length'     ,			max_length=1_2_8     ,			return_tensors='pt'      )

	return DataLoader(lowerCamelCase__     ,			shuffle=lowerCamelCase__     ,			collate_fn=lowerCamelCase__     ,			batch_size=1_6      )






def        SCREAMING_SNAKE_CASE__	(  lowerCamelCase__     ,			lowerCamelCase__      )  ->					Optional[int]:
	__lowerCamelCase    :    Optional[int] 	=			Accelerator(dispatch_batches=lowerCamelCase__     ,			split_batches=lowerCamelCase__      )
	__lowerCamelCase    :    Union[str, Any] 	=			get_dataloader(lowerCamelCase__     ,			not dispatch_batches      )
	__lowerCamelCase    :    Union[str, Any] 	=			AutoModelForSequenceClassification.from_pretrained(
	    'hf-internal-testing/mrpc-bert-base-cased'     ,			return_dict=lowerCamelCase__      )
	__lowerCamelCase	,			__lowerCamelCase    :    Tuple 	=			accelerator.prepare(lowerCamelCase__     ,			lowerCamelCase__      )
	return {"ddp": [ddp_model, ddp_dataloader, "cuda:0"], "no": [model, dataloader, accelerator.device]}, accelerator






def        SCREAMING_SNAKE_CASE__	(  lowerCamelCase__     ,			lowerCamelCase__     ,			lowerCamelCase__      )  ->					List[Any]:
	__lowerCamelCase    :    str 	=			[]
	for batch in dataloader:
		__lowerCamelCase	,			__lowerCamelCase    :    Union[str, Any] 	=			batch.values()
		with torch.no_grad():
			__lowerCamelCase    :    Tuple 	=			model(lowerCamelCase__      )
			__lowerCamelCase	,			__lowerCamelCase    :    Optional[Any] 	=			accelerator.gather_for_metrics((logit, target)      )
			logits_and_targets.append((logit, target)      )
	__lowerCamelCase	,			__lowerCamelCase    :    Dict 	=			[], []
	for logit, targ in logits_and_targets:
		logits.append(lowerCamelCase__      )
		targs.append(lowerCamelCase__      )
	__lowerCamelCase	,			__lowerCamelCase    :    Union[str, Any] 	=			torch.cat(lowerCamelCase__      ), torch.cat(lowerCamelCase__      )
	return logits, targs






def        SCREAMING_SNAKE_CASE__	(  lowerCamelCase__     ,			lowerCamelCase__=8_2     ,			lowerCamelCase__=False     ,			lowerCamelCase__=False     ,			lowerCamelCase__=1_6      )  ->					Dict:
	__lowerCamelCase	,			__lowerCamelCase	,			__lowerCamelCase    :    Optional[Any] 	=			get_basic_setup(lowerCamelCase__     ,			lowerCamelCase__     ,			lowerCamelCase__      )
	__lowerCamelCase	,			__lowerCamelCase    :    Dict 	=			generate_predictions(lowerCamelCase__     ,			lowerCamelCase__     ,			lowerCamelCase__      )
	assert (
	    len(lowerCamelCase__      ) == num_samples
	), F"Unexpected number of inputs:\n    Expected: {num_samples}\n    Actual: {len(lowerCamelCase__      )}"






def        SCREAMING_SNAKE_CASE__	(  lowerCamelCase__ = False     ,			lowerCamelCase__ = False      )  ->					Dict:
	__lowerCamelCase    :    Dict 	=			evaluate.load('glue'     ,			'mrpc'      )
	__lowerCamelCase	,			__lowerCamelCase    :    Optional[int] 	=			get_mrpc_setup(lowerCamelCase__     ,			lowerCamelCase__      )
	# First do baseline
	__lowerCamelCase	,			__lowerCamelCase	,			__lowerCamelCase    :    int 	=			setup['no']
	model.to(lowerCamelCase__      )
	model.eval()
	for batch in dataloader:
		batch.to(lowerCamelCase__      )
		with torch.inference_mode():
			__lowerCamelCase    :    Dict 	=			model(**lowerCamelCase__      )
		__lowerCamelCase    :    Any 	=			outputs.logits.argmax(dim=-1      )
		metric.add_batch(predictions=lowerCamelCase__     ,			references=batch['labels']      )
	__lowerCamelCase    :    str 	=			metric.compute()

	# Then do distributed
	__lowerCamelCase	,			__lowerCamelCase	,			__lowerCamelCase    :    Union[str, Any] 	=			setup['ddp']
	model.eval()
	for batch in dataloader:
		with torch.inference_mode():
			__lowerCamelCase    :    List[str] 	=			model(**lowerCamelCase__      )
		__lowerCamelCase    :    List[Any] 	=			outputs.logits.argmax(dim=-1      )
		__lowerCamelCase    :    List[str] 	=			batch['labels']
		__lowerCamelCase	,			__lowerCamelCase    :    Union[str, Any] 	=			accelerator.gather_for_metrics((preds, references)      )
		metric.add_batch(predictions=lowerCamelCase__     ,			references=lowerCamelCase__      )
	__lowerCamelCase    :    Dict 	=			metric.compute()

	for key in "accuracy f1".split():
		assert math.isclose(
		    baseline[key]     ,			distributed[key]      ), F"Baseline and Distributed are not the same for key {key}:\n\tBaseline: {baseline[key]}\n\tDistributed: {distributed[key]}\n"






def        SCREAMING_SNAKE_CASE__	(  )  ->					List[str]:
	__lowerCamelCase    :    int 	=			Accelerator(split_batches=lowerCamelCase__     ,			dispatch_batches=lowerCamelCase__      )
	if accelerator.is_local_main_process:
		datasets.utils.logging.set_verbosity_warning()
		transformers.utils.logging.set_verbosity_warning()
	else:
		datasets.utils.logging.set_verbosity_error()
		transformers.utils.logging.set_verbosity_error()
	# These are a bit slower so they should only be ran on the GPU or TPU
	if torch.cuda.is_available() or is_tpu_available():
		if accelerator.is_local_main_process:
			print('**Testing gather_for_metrics**'      )
		for split_batches in [True, False]:
			for dispatch_batches in [True, False]:
				if accelerator.is_local_main_process:
					print(F"With: `split_batches={split_batches}`, `dispatch_batches={dispatch_batches}`"      )
				test_mrpc(lowerCamelCase__     ,			lowerCamelCase__      )
				accelerator.state._reset_state()
	if accelerator.is_local_main_process:
		print('**Test torch metrics**'      )
	for split_batches in [True, False]:
		for dispatch_batches in [True, False]:
			__lowerCamelCase    :    Optional[Any] 	=			Accelerator(split_batches=lowerCamelCase__     ,			dispatch_batches=lowerCamelCase__      )
			if accelerator.is_local_main_process:
				print(F"With: `split_batches={split_batches}`, `dispatch_batches={dispatch_batches}`, length=99"      )
			test_torch_metrics(lowerCamelCase__     ,			9_9      )
			accelerator.state._reset_state()
	if accelerator.is_local_main_process:
		print('**Test last batch is not dropped when perfectly divisible**'      )
	__lowerCamelCase    :    Dict 	=			Accelerator()
	test_torch_metrics(lowerCamelCase__     ,			5_1_2      )
	accelerator.state._reset_state()






def        SCREAMING_SNAKE_CASE__	(  lowerCamelCase__      )  ->					Optional[Any]:
	# For xla_spawn (TPUs)
	main()


if __name__ == "__main__":
					main()




